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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
android/src/main/kotlin/com/onegini/mobile/sdk/flutter/useCases/RegistrationUseCase.kt | onewelcome | 418,922,893 | false | {"Kotlin": 252280, "Swift": 197938, "Dart": 158800, "Objective-C": 9672, "Java": 2851, "Ruby": 2849} | package com.onegini.mobile.sdk.flutter.useCases
import com.onegini.mobile.sdk.android.handlers.OneginiRegistrationHandler
import com.onegini.mobile.sdk.android.handlers.error.OneginiRegistrationError
import com.onegini.mobile.sdk.android.model.OneginiIdentityProvider
import com.onegini.mobile.sdk.android.model.entity.CustomInfo
import com.onegini.mobile.sdk.android.model.entity.UserProfile
import com.onegini.mobile.sdk.flutter.OneWelcomeWrapperErrors.NOT_FOUND_IDENTITY_PROVIDER
import com.onegini.mobile.sdk.flutter.OneginiSDK
import com.onegini.mobile.sdk.flutter.helpers.SdkError
import com.onegini.mobile.sdk.flutter.mapToOwCustomInfo
import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWRegistrationResponse
import com.onegini.mobile.sdk.flutter.pigeonPlugin.OWUserProfile
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class RegistrationUseCase @Inject constructor(private val oneginiSDK: OneginiSDK) {
operator fun invoke(identityProviderId: String?, scopes: List<String>?, callback: (Result<OWRegistrationResponse>) -> Unit) {
val identityProvider = oneginiSDK.oneginiClient.userClient.identityProviders.find { it.id == identityProviderId }
if (identityProviderId != null && identityProvider == null) {
callback(Result.failure(SdkError(NOT_FOUND_IDENTITY_PROVIDER).pigeonError()))
return
}
val registerScopes = scopes?.toTypedArray()
register(identityProvider, registerScopes, callback)
}
private fun register(
identityProvider: OneginiIdentityProvider?,
scopes: Array<String>?,
callback: (Result<OWRegistrationResponse>) -> Unit
) {
oneginiSDK.oneginiClient.userClient.registerUser(identityProvider, scopes, object : OneginiRegistrationHandler {
override fun onSuccess(userProfile: UserProfile, customInfo: CustomInfo?) {
val user = OWUserProfile(userProfile.profileId)
when (customInfo) {
null -> callback(Result.success(OWRegistrationResponse(user)))
else -> {
callback(Result.success(OWRegistrationResponse(user, customInfo.mapToOwCustomInfo())))
}
}
}
override fun onError(oneginiRegistrationError: OneginiRegistrationError) {
callback(
Result.failure(
SdkError(
code = oneginiRegistrationError.errorType,
message = oneginiRegistrationError.message
).pigeonError()
)
)
}
})
}
}
| 1 | Kotlin | 1 | 0 | 2a0b4be20fb01102761f321f1956161415c37fa0 | 2,464 | sdk-flutter | Apache License 2.0 |
core/local/src/test/java/com/ahmedvargos/local/mapper/AgentInfoToEntityMapperTest.kt | sarnav98 | 337,487,137 | true | {"Kotlin": 248520} | package com.ahmedvargos.local.mapper
import com.ahmedvargos.local.entities.AgentEntity
import com.ahmedvargos.local.utils.createTempAgent
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class AgentInfoToEntityMapperTest {
private lateinit var entityMapper: AgentInfoToEntityMapper
@Before
fun setup() {
entityMapper = AgentInfoToEntityMapper()
}
@Test
fun `Given AgentInfo, when map(), then return expected Entity`() {
// Arrange
val tempAgentInfo = createTempAgent()
val expectedEntity = tempAgentInfo.let { agent ->
AgentEntity(id = agent.uuid, isFav = agent.isFav, data = agent)
}
// Act
val result = entityMapper.map(tempAgentInfo)
// Assert
Assert.assertEquals(result, expectedEntity)
}
}
| 0 | null | 0 | 0 | e9695488c63b336b07dcb6d209f21326457c4ea3 | 833 | Valorant-Agents | Apache License 2.0 |
adaptive-core/src/commonMain/kotlin/hu/simplexion/adaptive/server/builtin/AdaptiveStore.kt | spxbhuhb | 788,711,010 | false | {"Kotlin": 1165965, "CSS": 23691, "Java": 20882, "HTML": 1381, "JavaScript": 980} | /*
* Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.adaptive.server.builtin
import hu.simplexion.adaptive.foundation.*
import hu.simplexion.adaptive.server.AdaptiveServerAdapter
import hu.simplexion.adaptive.server.AdaptiveServerFragment
@Adaptive
fun store(impl : () -> StoreImpl<*>) {
manualImplementation(impl)
}
class AdaptiveStore(
adapter: AdaptiveServerAdapter,
parent: AdaptiveFragment,
index: Int
) : AdaptiveServerFragment(adapter, parent, index) {
override fun mount() {
if (trace) trace("before-Mount")
impl?.mount()
if (trace) trace("after-Mount")
}
@OptIn(ExperimentalStdlibApi::class)
override fun unmount() {
if (trace) trace("before-Unmount")
impl?.let {
if (it is AutoCloseable) it.close()
}
impl = null
if (trace) trace("after-Unmount")
}
} | 12 | Kotlin | 0 | 0 | e3756d6a2faff396b43135312e8ad90b8c2fe8cb | 986 | adaptive | Apache License 2.0 |
publish-plugin/src/main/java/com/dorck/android/upload/config/Constants.kt | Moosphan | 524,811,058 | false | null | package com.dorck.android.upload.config
/**
* Consts used for repos.
* @author Dorck
* @since 2022/08/17
*/
object Constants {
const val REPOSITORY_USERNAME_KEY = "REPO_USER"
const val REPOSITORY_PASSWORD_KEY = "REPO_PASSWORD"
const val REPOSITORY_RELEASE_URL = "REPO_RELEASE_URL"
const val REPOSITORY_SNAPSHOT_URL = "REPO_SNAPSHOT_URL"
} | 0 | Kotlin | 0 | 7 | dbc7b0f857ed059548a6184dca7080e10bf3e9a5 | 360 | component-publisher | Apache License 2.0 |
app/src/main/java/com/peter/azure/data/entity/PrintGame.kt | peterdevacc | 649,972,321 | false | {"Kotlin": 302811} | /*
* Copyright (c) 2023 洪振健 All rights reserved.
*/
package com.peter.azure.data.entity
data class PrintGame(
val gameLevel: GameLevel,
val sudoku: List<List<Int>>
)
| 0 | Kotlin | 0 | 0 | eee1d8b81b2a5c1c67aad29bf6889211bb53e517 | 178 | Azure | Apache License 2.0 |
kirinmaru-android/src/main/java/stream/reconfig/kirinmaru/android/prefs/FirstLoadPref.kt | amirulzin | 121,656,356 | false | {"Gradle": 5, "Markdown": 2, "Java Properties": 1, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "EditorConfig": 1, "Proguard": 1, "JSON": 1, "Kotlin": 158, "XML": 54, "INI": 1, "Java": 6, "YAML": 1} | package stream.reconfig.kirinmaru.android.prefs
import android.content.SharedPreferences
import commons.android.core.prefs.primitive.BooleanPref
import javax.inject.Inject
/**
*
*/
class FirstLoadPref @Inject constructor(prefs: SharedPreferences) : BooleanPref("firstLoad", true, prefs) | 1 | null | 1 | 1 | 15c1eeafe8f467a55008b402e30d97e6966926f3 | 290 | Kirinmaru | Apache License 2.0 |
Wechat_chatroom_helper_android/app/src/main/kotlin/com/zdy/project/wechat_chatroom_helper/helper/ui/newConfig/viewmodel/WechatClassParserTask.kt | zhudongya123 | 96,015,224 | false | {"Text": 1, "Ignore List": 3, "Markdown": 2, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "INI": 1, "XML": 36, "Java": 11, "Proguard": 1, "Kotlin": 68} | package com.zdy.project.wechat_chatroom_helper.helper.ui.newConfig.viewmodel
import android.app.Application
import com.zdy.project.wechat_chatroom_helper.Constants
import com.zdy.project.wechat_chatroom_helper.R
import com.zdy.project.wechat_chatroom_helper.wechat.plugins.classparser.WXClassParser
import dalvik.system.DexClassLoader
import net.dongliu.apk.parser.ApkFile
import java.io.File
import java.lang.reflect.AnnotatedElement
import java.lang.reflect.Method
import java.util.Locale
import kotlin.random.Random
class WechatClassParserTask(private val application: Application) {
suspend fun parseClasses(messageCallback: suspend (ConfigMessage) -> Unit): Result<WechatClasses> {
messageCallback(ConfigMessage(Type.Normal, "开始"))
val srcPath = application.packageManager.getApplicationInfo(Constants.WECHAT_PACKAGE_NAME, 0).publicSourceDir
val optimizedDirectory = application.getDir("dex", 0).absolutePath
val wechatClasses = WechatClasses()
try {
val classes = mutableListOf<Class<*>>()
val apkFile = ApkFile(File(srcPath))
val dexClasses = apkFile.dexClasses
val classLoader = DexClassLoader(srcPath, optimizedDirectory, null, application.classLoader)
val message = String.format(
Locale.getDefault(),
application.getString(R.string.config_step3_text1),
srcPath, apkFile.apkMeta.versionName, apkFile.apkMeta.versionCode.toString()
)
messageCallback(ConfigMessage(Type.Normal, message))
val randomChangeClassesNumber = 1000
var currentCursor = 1
dexClasses
.map {
it.classType
.substring(1, it.classType.length - 1)
.replace("/", ".")
}.forEachIndexed { index, className ->
try {
val clazz = classLoader.loadClass(className)
classes.add(clazz)
} catch (e: Throwable) {
e.printStackTrace()
messageCallback(ConfigMessage(Type.Normal, "解析类时出现错误,类名$className"))
}
if (index == currentCursor) {
currentCursor += Random.nextInt(randomChangeClassesNumber)
val message = String.format(
Locale.getDefault(), application.getString(R.string.config_step3_text6), index + 1, classes.size
)
messageCallback(ConfigMessage(Type.Top, message))
}
}
wechatClasses.conversationWithCacheAdapter = parseAnnotatedElementToName(WXClassParser.Adapter.getConversationWithCacheAdapter(classes))
wechatClasses.conversationLongClickListener = parseAnnotatedElementToName(WXClassParser.Adapter.getConversationLongClickListener(classes))
wechatClasses.conversationClickListener = parseAnnotatedElementToName(WXClassParser.Adapter.getConversationClickListener(classes))
wechatClasses.conversationMenuItemSelectedListener = parseAnnotatedElementToName(WXClassParser.Adapter.getConversationMenuItemSelectedListener(classes))
wechatClasses.conversationStickyHeaderHandler = parseAnnotatedElementToName(WXClassParser.Adapter.getConversationStickyHeaderHandler(classes))
wechatClasses.conversationAvatar = parseAnnotatedElementToName(WXClassParser.Adapter.getConversationAvatar(classes))
// toMap(wechatClasses).forEach { entry ->
// val key = entry.key
// val value = entry.value.toString()
// messageCallback(ConfigMessage(Type.Normal, "配置-> $key, 位置-> $value"))
// }
messageCallback(ConfigMessage(Type.Normal, "成功"))
return Result.success(wechatClasses)
} catch (e: Throwable) {
messageCallback(ConfigMessage(Type.Normal, e.stackTrace.joinToString("\n") { it.toString() }))
e.printStackTrace()
return Result.failure(e)
}
}
@Throws(Exception::class)
private fun parseAnnotatedElementToName(element: AnnotatedElement?): String {
return if (element == null) throw ClassNotFoundException()
else {
when (element) {
is Method -> element.name
is Class<*> -> element.name
else -> ""
}
}
}
} | 11 | Kotlin | 21 | 86 | 641d8d004212196d443056a7b428ba03be60b4ec | 4,547 | WechatChatRoomHelper | Apache License 2.0 |
apps/etterlatte-vilkaarsvurdering-kafka/src/main/kotlin/no/nav/etterlatte/vilkaarsvurdering/TidshendelseRiver.kt | navikt | 417,041,535 | false | {"Kotlin": 5618023, "TypeScript": 1317735, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "Dockerfile": 745, "CSS": 598} | package no.nav.etterlatte.vilkaarsvurdering
import no.nav.etterlatte.libs.common.logging.getCorrelationId
import no.nav.etterlatte.libs.common.logging.withLogContext
import no.nav.etterlatte.rapidsandrivers.ALDERSOVERGANG_ID_KEY
import no.nav.etterlatte.rapidsandrivers.ALDERSOVERGANG_STEG_KEY
import no.nav.etterlatte.rapidsandrivers.ALDERSOVERGANG_TYPE_KEY
import no.nav.etterlatte.rapidsandrivers.DATO_KEY
import no.nav.etterlatte.rapidsandrivers.DRYRUN
import no.nav.etterlatte.rapidsandrivers.EventNames
import no.nav.etterlatte.rapidsandrivers.HENDELSE_DATA_KEY
import no.nav.etterlatte.rapidsandrivers.ListenerMedLogging
import no.nav.etterlatte.rapidsandrivers.SAK_ID_KEY
import no.nav.etterlatte.rapidsandrivers.sakId
import no.nav.etterlatte.vilkaarsvurdering.services.VilkaarsvurderingService
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.MessageContext
import no.nav.helse.rapids_rivers.RapidsConnection
import org.slf4j.LoggerFactory
class TidshendelseRiver(
rapidsConnection: RapidsConnection,
private val vilkaarsvurderingService: VilkaarsvurderingService,
) : ListenerMedLogging() {
private val logger = LoggerFactory.getLogger(this::class.java)
init {
initialiserRiver(rapidsConnection, EventNames.ALDERSOVERGANG) {
validate { it.requireValue(ALDERSOVERGANG_STEG_KEY, "VURDERT_LOEPENDE_YTELSE") }
validate { it.requireKey(ALDERSOVERGANG_TYPE_KEY) }
validate { it.requireKey(ALDERSOVERGANG_ID_KEY) }
validate { it.requireKey(SAK_ID_KEY) }
validate { it.requireKey(DATO_KEY) }
validate { it.requireKey(DRYRUN) }
validate { it.requireKey(HENDELSE_DATA_KEY) }
}
}
override fun haandterPakke(
packet: JsonMessage,
context: MessageContext,
) {
val type = packet[ALDERSOVERGANG_TYPE_KEY].asText()
val hendelseId = packet[ALDERSOVERGANG_ID_KEY].asText()
val dryrun = packet[DRYRUN].asBoolean()
val sakId = packet.sakId
withLogContext(
correlationId = getCorrelationId(),
mapOf(
"hendelseId" to hendelseId,
"sakId" to sakId.toString(),
"type" to type,
"dryRun" to dryrun.toString(),
),
) {
val hendelseData = packet[HENDELSE_DATA_KEY]
hendelseData["loependeYtelse_januar2024_behandlingId"]?.let {
val behandlingId = it.asText()
val result = vilkaarsvurderingService.harMigrertYrkesskadefordel(behandlingId)
logger.info("Løpende ytelse: sjekk av yrkesskadefordel før 2024-01-01: $result")
packet["yrkesskadefordel_pre_20240101"] = result
}
if (type in arrayOf("OMS_DOED_3AAR", "OMS_DOED_5AAR") && hendelseData["loependeYtelse"]?.asBoolean() == true) {
val loependeBehandlingId = hendelseData["loependeYtelse_behandlingId"].asText()
val result = vilkaarsvurderingService.harRettUtenTidsbegrensning(loependeBehandlingId)
logger.info("OMS: sjekk av rett uten tidsbegrensning: $result")
packet["oms_rett_uten_tidsbegrensning"] = result
}
packet[ALDERSOVERGANG_STEG_KEY] = "VURDERT_LOEPENDE_YTELSE_OG_VILKAAR"
context.publish(packet.toJson())
}
}
}
| 25 | Kotlin | 0 | 6 | e84b73f3decfa2cadfb02364fbd71ca96efbd948 | 3,409 | pensjon-etterlatte-saksbehandling | MIT License |
app/src/main/java/com/msg/gcms/data/remote/dto/auth/response/SignInResponse.kt | GSM-MSG | 465,292,111 | false | null | package com.msg.gcms.data.remote.dto.auth.response
data class SignInResponse(
val accessToken: String,
val refreshToken: String,
val accessExp: String,
val refreshExp: String
)
| 4 | Kotlin | 0 | 0 | 8239a015cc311b1631e0c6fc5047e231b5a7ec20 | 194 | GCMS-Android | MIT License |
ui/src/commonMain/kotlin/siarhei/luskanau/pixabayeye/ui/search/SearchVewModel.kt | siarhei-luskanau | 642,089,997 | false | null | package siarhei.luskanau.pixabayeye.ui.search
import app.cash.paging.Pager
import app.cash.paging.PagingConfig
import siarhei.luskanau.pixabayeye.network.HitModel
import siarhei.luskanau.pixabayeye.network.PixabayApiService
class SearchVewModel(
private val pixabayApiService: PixabayApiService,
) {
fun getPager(latestSearchTerm: String): Pager<Int, HitModel> {
val pagingConfig = PagingConfig(pageSize = 20, initialLoadSize = 20)
return Pager(pagingConfig) {
PixabayPagingSource(pixabayApiService, latestSearchTerm)
}
}
}
| 0 | Kotlin | 0 | 0 | b450363bfcbd4a8383d8931f48db9d005d07f794 | 574 | pixabayeye | MIT License |
src/main/kotlin/it/skrape/selects/html5/TextSemanticsElementPickers.kt | fejd | 214,291,752 | true | {"Kotlin": 138113, "HTML": 1597} | package it.skrape.selects.html5
import it.skrape.SkrapeItDslMarker
import it.skrape.core.Result
import it.skrape.selects.elements
import org.jsoup.select.Elements
/**
* Will pick all occurrences of <a> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.a(cssSelector: String ="", init: Elements.() -> Unit) = elements("a$cssSelector", init)
/**
* Will pick all occurrences of <abbr> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.abbr(cssSelector: String ="", init: Elements.() -> Unit) = elements("abbr$cssSelector", init)
/**
* Will pick all occurrences of <b> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.b(cssSelector: String ="", init: Elements.() -> Unit) = elements("b$cssSelector", init)
/**
* Will pick all occurrences of <bdi> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.bdi(cssSelector: String ="", init: Elements.() -> Unit) = elements("bdi$cssSelector", init)
/**
* Will pick all occurrences of <bdo> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.bdo(cssSelector: String ="", init: Elements.() -> Unit) = elements("bdo$cssSelector", init)
/**
* Will pick all occurrences of <br> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.br(cssSelector: String ="", init: Elements.() -> Unit) = elements("br$cssSelector", init)
/**
* Will pick all occurrences of <cite> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.cite(cssSelector: String ="", init: Elements.() -> Unit) = elements("cite$cssSelector", init)
/**
* Will pick all occurrences of <code> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.code(cssSelector: String ="", init: Elements.() -> Unit) = elements("code$cssSelector", init)
/**
* Will pick all occurrences of <data> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.data(cssSelector: String ="", init: Elements.() -> Unit) = elements("data$cssSelector", init)
/**
* Will pick all occurrences of <dfn> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.dfn(cssSelector: String ="", init: Elements.() -> Unit) = elements("dfn$cssSelector", init)
/**
* Will pick all occurrences of <em> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.em(cssSelector: String ="", init: Elements.() -> Unit) = elements("em$cssSelector", init)
/**
* Will pick all occurrences of <i> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.i(cssSelector: String ="", init: Elements.() -> Unit) = elements("i$cssSelector", init)
/**
* Will pick all occurrences of <kbd> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.kbd(cssSelector: String ="", init: Elements.() -> Unit) = elements("kbd$cssSelector", init)
/**
* Will pick all occurrences of <mark> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.mark(cssSelector: String ="", init: Elements.() -> Unit) = elements("mark$cssSelector", init)
/**
* Will pick all occurrences of <q> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.q(cssSelector: String ="", init: Elements.() -> Unit) = elements("q$cssSelector", init)
/**
* Will pick all occurrences of <rb> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.rb(cssSelector: String ="", init: Elements.() -> Unit) = elements("rb$cssSelector", init)
/**
* Will pick all occurrences of <rp> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.rp(cssSelector: String ="", init: Elements.() -> Unit) = elements("rp$cssSelector", init)
/**
* Will pick all occurrences of <rt> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.rt(cssSelector: String ="", init: Elements.() -> Unit) = elements("rt$cssSelector", init)
/**
* Will pick all occurrences of <rtc> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.rtc(cssSelector: String ="", init: Elements.() -> Unit) = elements("rtc$cssSelector", init)
/**
* Will pick all occurrences of <ruby> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.ruby(cssSelector: String ="", init: Elements.() -> Unit) = elements("ruby$cssSelector", init)
/**
* Will pick all occurrences of <s> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.s(cssSelector: String ="", init: Elements.() -> Unit) = elements("s$cssSelector", init)
/**
* Will pick all occurrences of <samp> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.samp(cssSelector: String ="", init: Elements.() -> Unit) = elements("samp$cssSelector", init)
/**
* Will pick all occurrences of <small> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.small(cssSelector: String ="", init: Elements.() -> Unit) = elements("small$cssSelector", init)
/**
* Will pick all occurrences of <span> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.span(cssSelector: String ="", init: Elements.() -> Unit) = elements("span$cssSelector", init)
/**
* Will pick all occurrences of <strong> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.strong(cssSelector: String ="", init: Elements.() -> Unit) = elements("strong$cssSelector", init)
/**
* Will pick all occurrences of <sub> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.sub(cssSelector: String ="", init: Elements.() -> Unit) = elements("sub$cssSelector", init)
/**
* Will pick all occurrences of <sup> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.sup(cssSelector: String ="", init: Elements.() -> Unit) = elements("sup$cssSelector", init)
/**
* Will pick all occurrences of <time> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.time(cssSelector: String ="", init: Elements.() -> Unit) = elements("time$cssSelector", init)
/**
* Will pick all occurrences of <tt> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.tt(cssSelector: String ="", init: Elements.() -> Unit) = elements("tt$cssSelector", init)
/**
* Will pick all occurrences of <u> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.u(cssSelector: String ="", init: Elements.() -> Unit) = elements("u$cssSelector", init)
/**
* Will pick all occurrences of <var> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.`var`(cssSelector: String ="", init: Elements.() -> Unit) = elements("var$cssSelector", init)
/**
* Will pick all occurrences of <wbr> elements from a Result.
* The selection can be specified/limited by an additional css-selector.
* @param cssSelector
* @return Elements
*/
@SkrapeItDslMarker
fun Result.wbr(cssSelector: String ="", init: Elements.() -> Unit) = elements("wbr$cssSelector", init)
| 0 | null | 0 | 0 | c921e5a79c77176ac2121a64f4891bb4e9bb53ea | 10,010 | skrape.it | MIT License |
app/src/main/java/com/master8/shana/domain/usecase/movies/AddGoodMovieUseCase.kt | master8 | 236,213,828 | false | null | package com.master8.shana.domain.usecase.movies
import com.master8.shana.domain.entity.ChangedMovie
import com.master8.shana.domain.entity.Movie
import com.master8.shana.domain.entity.WatchStatus
import com.master8.shana.domain.repository.MovieChangesRepository
import com.master8.shana.domain.repository.MoviesRepository
class AddGoodMovieUseCase(
private val moviesRepository: MoviesRepository,
private val movieChangesRepository: MovieChangesRepository,
private val prepareMovieToAddUseCase: PrepareMovieToAddUseCase
) {
suspend operator fun invoke(movie: Movie) {
val preparedMovie = prepareMovieToAddUseCase(movie, WatchStatus.WATCHED)
moviesRepository.addGoodMovie(preparedMovie)
movieChangesRepository.movieWasChanged(ChangedMovie(movie, preparedMovie))
}
} | 0 | Kotlin | 1 | 2 | c14364eb536c1c38ce7ff5f0c949878047df2e64 | 810 | shana-good-movies | MIT License |
plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/ExperimentalGradleToolingApi.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleTooling
@RequiresOptIn(level = RequiresOptIn.Level.WARNING, message = "This API might change in the future")
annotation class ExperimentalGradleToolingApi
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 356 | intellij-community | Apache License 2.0 |
idea/testData/codeInsight/moveUpDown/classBodyDeclarations/class/classAtFunction1.kt | JakeWharton | 99,388,807 | false | null | // MOVE: down
// class A
class A {
// class B
<caret>class B {
}
// fun foo
fun foo() {
}
} | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 117 | kotlin | Apache License 2.0 |
app/src/main/java/cn/yooking/genshin/view/HeaderManagerActivity.kt | yooking-git | 411,895,870 | false | {"Kotlin": 140299, "Java": 19530, "HTML": 670} | package cn.yooking.genshin.view
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.yooking.genshin.BaseActivity
import cn.yooking.genshin.R
import cn.yooking.genshin.utils.DateUtil
import cn.yooking.genshin.utils.FileUtil
import cn.yooking.genshin.utils.GlideUtil
import cn.yooking.genshin.utils.dialog.*
import cn.yooking.genshin.utils.sp.HeaderSpUtil
import cn.yooking.genshin.view.model.HeaderManagerModel
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.permissionx.guolindev.PermissionX
import com.yalantis.ucrop.UCrop
import java.io.File
import java.util.*
/**
* Created by yooking on 2022/4/25.
* Copyright (c) 2022 yooking. All rights reserved.
*/
class HeaderManagerActivity : BaseActivity() {
private lateinit var model:HeaderManagerModel
//数据缓存
private var headerName: String = ""
// private var checkType: Int = 0
private val adapter: BaseQuickAdapter<HeaderSpUtil.HeaderEntity, BaseViewHolder> =
object :
BaseQuickAdapter<HeaderSpUtil.HeaderEntity, BaseViewHolder>(R.layout.item_header_manager) {
override fun convert(holder: BaseViewHolder, item: HeaderSpUtil.HeaderEntity) {
// if (item.type == -1) {
// holder.setImageResource(R.id.iv_header_manager_item, R.mipmap.icon_header_add)
// holder.setText(R.id.tv_header_manager_item, "添加")
// return
// }
val view = holder.getView<ImageView>(R.id.iv_header_manager_item)
if(item.path.isNotEmpty()) {
view.setImageURI(Uri.parse(item.path))
}else{
// Log.i("HeaderManagerActivity",item.url)
GlideUtil.load(this@HeaderManagerActivity,view,item.url)
}
holder.setText(R.id.tv_header_manager_item, item.name)
}
}
override fun initLayoutId(): Int {
return R.layout.activity_header_manager
}
override fun initData() {
model = HeaderManagerModel(this)
}
override fun initView() {
val rvContent = holder.findView<RecyclerView>(R.id.rv_header_manager_content)
rvContent.layoutManager = GridLayoutManager(this, 3)
adapter.recyclerView = rvContent
rvContent.adapter = adapter
adapter.animationEnable = false
refresh()
}
override fun initListener() {
adapter.setOnItemClickListener { _, _, position ->
val item = adapter.getItem(position)
// if (item.type == -1) {//添加
// buildDialog("添加头像", type = -1)
// return@setOnItemClickListener
// }
buildDialog(name = item.name, nickname = item.nickname, type = item.type)
}
holder.setOnClickListener(R.id.tv_header_manager_update){
model.update{
runOnUiThread {
Toast.makeText(this, "数据加载完毕", Toast.LENGTH_SHORT).show()
refresh()
}
}
}
}
override fun initClient() {
}
private fun refresh() {
val headerData = HeaderSpUtil.instance.findAllHeader()
adapter.setNewInstance(headerData)
// adapter.addData(HeaderSpUtil.HeaderEntity("add", "", type = -1))
}
private fun buildDialog(
title: String = "修改头像",
name: String = "",
nickname: String = "",
type: Int = 0
) {
headerName = name
val view: View = LayoutInflater.from(this).inflate(R.layout.dialog_upload_header, null)
val etName = view.findViewById<EditText>(R.id.et_dialog_header_name)
val etNickname = view.findViewById<EditText>(R.id.et_dialog_header_nickname)
if (type == 0 || type == 1) {
etName.isEnabled = false
etName.setTextColor(resources.getColor(R.color.color_666, theme))
etName.setText(name)
etNickname.setText(nickname)
}
val rbRole = view.findViewById<RadioButton>(R.id.rb_dialog_header_role)
val rbArms = view.findViewById<RadioButton>(R.id.rb_dialog_header_arms)
if (type == 1) {
rbArms.isChecked = true
} else {
rbRole.isChecked = true
}
val dialog = createDialog(this, title, view)
.addListener(TAG_CENTER, "改图") { _, _ ->
PermissionX.init(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE)
.request { isAllGranted, _, _ ->
if (isAllGranted) {
val intent = Intent(Intent.ACTION_PICK, null)
intent.type = "image/*"
startActivityForResult(intent, 10010)
}
}
}
.addListener(TAG_LEFT, "取消")
.addListener(TAG_RIGHT, "改名") { _, _ ->
val headerNickname = etNickname.text.toString()
if (headerName.isEmpty()) {
Toast.makeText(this, "请输入角色名称", Toast.LENGTH_SHORT).show()
return@addListener
}
HeaderSpUtil.instance.changeHeaderNickname(headerName, headerNickname)
refresh()
}
// if (type != -1) {
// dialog.addListener(TAG_LEFT, "删除") { _, _ ->
// HeaderSpUtil.instance.removeHeader(name)
//
// refresh()
// }
// }
dialog.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 10010) {
if (data != null) {
val uri = data.data ?: return
val fileName = "header_img_${DateUtil.date2Str(Date(), "yyyyMMddHHmmss")}.jpg"
val file = File(FileUtil.getFileDirsPath(this) + fileName)
UCrop.of(uri, Uri.fromFile(file))
.withAspectRatio(1f, 1f)
.withMaxResultSize(512, 512)
.start(this)
}
return
}
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK && data != null) {
val uri = UCrop.getOutput(data)
HeaderSpUtil.instance.changeHeaderImg(
headerName,
uri?.path ?: ""
)
refresh()
}
}
} | 0 | Kotlin | 0 | 0 | 11a152f3687b72b0556e0e372eeb1fd4c8b230d2 | 6,926 | GenshinUtils | MIT License |
src/main/kotlin/it/frob/kaitaiplugin/KaitaiFileTypeDetector.kt | agatti | 519,946,890 | false | {"Kotlin": 23416, "HTML": 63} | /*
* Copyright (C) 2022 <NAME> - Frob.it
*
* SPDX-License-Identifier: Apache-2.0
*/
package it.frob.kaitaiplugin
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeRegistry.FileTypeDetector
import com.intellij.openapi.util.io.ByteSequence
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.yaml.YAMLFileType
class KaitaiFileTypeDetector : FileTypeDetector {
override fun detect(file: VirtualFile, firstBytes: ByteSequence, firstCharsIfText: CharSequence?): FileType? =
if (isKaitaiFile(file)) {
YAMLFileType.YML
} else {
null
}
}
| 0 | Kotlin | 1 | 1 | d86ffb35b3046cbfed2fa9aadebb89efce2ddddc | 645 | kaitai-intellij | Apache License 2.0 |
src/lang-xdm/main/uk/co/reecedunn/intellij/plugin/xdm/module/path/XdmModuleType.kt | rhdunn | 62,201,764 | false | {"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853} | /*
* Copyright (C) 2019-2021 <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 uk.co.reecedunn.intellij.plugin.xdm.module.path
enum class XdmModuleType(val extensions: Array<String>) {
DotNet(arrayOf()), // Saxon
DTD(arrayOf()), // EXPath Package
Java(arrayOf()), // BaseX, eXist-db, Saxon
NVDL(arrayOf()), // EXPath Package
RelaxNG(arrayOf()), // EXPath Package
RelaxNGCompact(arrayOf()), // EXPath Package
Resource(arrayOf()), // EXPath Package
Schematron(arrayOf()), // EXPath Package
XMLSchema(arrayOf(".xsd")), // Schema Aware Feature, EXPath Package
XPath(arrayOf()), // XSLT
XProc(arrayOf()), // EXPath Package
XQuery(arrayOf(".xq", ".xqm", ".xqy", ".xql", ".xqu", ".xquery")), // Module Feature, EXPath Package
XSLT(arrayOf()); // MarkLogic, EXPath Package
companion object {
val JAVA: Array<XdmModuleType> = arrayOf(Java)
val MODULE: Array<XdmModuleType> = arrayOf(XQuery, Java, DotNet)
val MODULE_OR_SCHEMA: Array<XdmModuleType> = arrayOf(XQuery, XMLSchema, Java, DotNet)
val NONE: Array<XdmModuleType> = arrayOf()
val XPATH_OR_XQUERY: Array<XdmModuleType> = arrayOf(XPath, XQuery)
val XQUERY: Array<XdmModuleType> = arrayOf(XQuery)
val RESOURCE: Array<XdmModuleType> = arrayOf(Resource)
val SCHEMA: Array<XdmModuleType> = arrayOf(XMLSchema)
val STYLESHEET: Array<XdmModuleType> = arrayOf(XSLT)
}
}
| 49 | Kotlin | 9 | 25 | d8d460d31334e8b2376a22f3832a20b2845bacab | 1,967 | xquery-intellij-plugin | Apache License 2.0 |
kotlin-script.kts | whalemare | 93,920,111 | false | null | #!/usr/bin/env kscript
//DEPS com.offbytwo.jenkins:jenkins-client:0.3.7
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
class App {
val jenkinsUrl = URL("http://localhost:8080/job/itemTest/build?token=<PASSWORD>")
fun main() {
jenkinsUrl.openConnection()
val response = (jenkinsUrl.openConnection() as HttpURLConnection).apply {
requestMethod = "GET"
addRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
)
}.inputStream
val scanner = Scanner(response)
println(scanner.useDelimiter("\\A").next())
}
}
App().main()
println("Script success-full") | 0 | Kotlin | 1 | 0 | a49bfa7d80246b0435bea13906fb0e1ef2521d0b | 737 | cell-adapter | Apache License 2.0 |
app/src/main/java/com/isaacsufyan/androidarchitecture/tdd/testapp/taskdetail/TaskDetailViewModel.kt | IsaacSufyan | 485,711,320 | false | null | package com.isaacsufyan.androidarchitecture.tdd.testapp.taskdetail
import android.app.Application
import androidx.annotation.StringRes
import androidx.lifecycle.*
import com.isaacsufyan.androidarchitecture.tdd.testapp.Event
import com.isaacsufyan.androidarchitecture.tdd.testapp.R
import com.isaacsufyan.androidarchitecture.tdd.testapp.data.Result
import com.isaacsufyan.androidarchitecture.tdd.testapp.data.Result.Success
import com.isaacsufyan.androidarchitecture.tdd.testapp.data.Task
import com.isaacsufyan.androidarchitecture.tdd.testapp.data.source.DefaultTasksRepository
import kotlinx.coroutines.launch
class TaskDetailViewModel(application: Application) : AndroidViewModel(application) {
private val tasksRepository = DefaultTasksRepository.getRepository(application)
private val _taskId = MutableLiveData<String>()
private val _task = _taskId.switchMap { taskId ->
tasksRepository.observeTask(taskId).map { computeResult(it) }
}
val task: LiveData<Task?> = _task
val isDataAvailable: LiveData<Boolean> = _task.map { it != null }
private val _dataLoading = MutableLiveData<Boolean>()
val dataLoading: LiveData<Boolean> = _dataLoading
private val _editTaskEvent = MutableLiveData<Event<Unit>>()
val editTaskEvent: LiveData<Event<Unit>> = _editTaskEvent
private val _deleteTaskEvent = MutableLiveData<Event<Unit>>()
val deleteTaskEvent: LiveData<Event<Unit>> = _deleteTaskEvent
private val _snackbarText = MutableLiveData<Event<Int>>()
val snackbarText: LiveData<Event<Int>> = _snackbarText
val completed: LiveData<Boolean> = _task.map { input: Task? ->
input?.isCompleted ?: false
}
fun deleteTask() = viewModelScope.launch {
_taskId.value?.let {
tasksRepository.deleteTask(it)
_deleteTaskEvent.value = Event(Unit)
}
}
fun editTask() {
_editTaskEvent.value = Event(Unit)
}
fun setCompleted(completed: Boolean) = viewModelScope.launch {
val task = _task.value ?: return@launch
if (completed) {
tasksRepository.completeTask(task)
showSnackbarMessage(R.string.task_marked_complete)
} else {
tasksRepository.activateTask(task)
showSnackbarMessage(R.string.task_marked_active)
}
}
fun start(taskId: String) {
if (_dataLoading.value == true || taskId == _taskId.value) {
return
}
_taskId.value = taskId
}
private fun computeResult(taskResult: Result<Task>): Task? {
return if (taskResult is Success) {
taskResult.data
} else {
showSnackbarMessage(R.string.loading_tasks_error)
null
}
}
fun refresh() {
_task.value?.let {
_dataLoading.value = true
viewModelScope.launch {
tasksRepository.refreshTask(it.id)
_dataLoading.value = false
}
}
}
private fun showSnackbarMessage(@StringRes message: Int) {
_snackbarText.value = Event(message)
}
}
| 0 | Kotlin | 0 | 3 | 75d9f9856885cf7e33c02a60f855b3e344d7a0c5 | 3,112 | TDD_TestApp | Apache License 2.0 |
src/main/kotlin/com/github/jntakpe/mockpi/MockpiApplication.kt | jntakpe | 85,351,357 | false | null | package com.github.jntakpe.mockpi
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class MockpiApplication
fun main(args: Array<String>) {
runApplication<MockpiApplication>(*args)
} | 0 | Kotlin | 0 | 14 | af3f028867f049d2d987b12895e4280c05388277 | 277 | mockpi | MIT License |
app/src/main/java/io/github/template/ui/modules/splash/SplashFragment.kt | Faierbel | 340,192,417 | false | {"Kotlin": 9878} | package io.github.template.ui.modules.splash
import dagger.hilt.android.AndroidEntryPoint
import io.github.template.R
import io.github.template.databinding.FragmentSplashBinding
import io.github.template.ui.base.BaseFragment
@AndroidEntryPoint
class SplashFragment : BaseFragment<FragmentSplashBinding>(R.layout.fragment_splash) {
} | 10 | Kotlin | 0 | 3 | dacb8a77b9145e3192f94c7517af0fdeb171d4c3 | 334 | android-template | MIT License |
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1020009.kt | pointillion | 428,683,199 | true | {"Kotlin": 538588, "HTML": 47353, "CSS": 17418, "JavaScript": 79} | package xyz.qwewqa.relive.simulator.core.presets.dress.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType
import xyz.qwewqa.relive.simulator.stage.character.Character
import xyz.qwewqa.relive.simulator.stage.character.DamageType
import xyz.qwewqa.relive.simulator.stage.character.Position
val dress1020009 = PartialDressBlueprint(
id = 1020009,
name = "オリオン",
baseRarity = 4,
character = Character.Hikari,
attribute = Attribute.Wind,
damageType = DamageType.Normal,
position = Position.Back,
positionValue = 34050,
stats = StatData(
hp = 1320,
actPower = 131,
normalDefense = 115,
specialDefense = 75,
agility = 187,
dexterity = 5,
critical = 50,
accuracy = 0,
evasion = 0,
),
growthStats = StatData(
hp = 40320,
actPower = 2500,
normalDefense = 1500,
specialDefense = 1050,
agility = 3060,
),
actParameters = mapOf(
ActType.Act1 to ActBlueprint(
name = "斬撃",
type = ActType.Act1,
apCost = 1,
icon = 1,
parameters = listOf(
ActParameters(
values = listOf(88, 92, 96, 101, 105),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
ActType.Act2 to ActBlueprint(
name = "キラめきの斬撃",
type = ActType.Act2,
apCost = 2,
icon = 89,
parameters = listOf(
ActParameters(
values = listOf(93, 98, 102, 107, 112),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(20, 20, 20, 20, 20),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
ActType.Act3 to ActBlueprint(
name = "キラめきの風",
type = ActType.Act3,
apCost = 3,
icon = 89,
parameters = listOf(
ActParameters(
values = listOf(15, 16, 17, 18, 20),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
ActType.ClimaxAct to ActBlueprint(
name = "星になる時",
type = ActType.ClimaxAct,
apCost = 2,
icon = 89,
parameters = listOf(
ActParameters(
values = listOf(15, 16, 17, 18, 20),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(20, 22, 24, 27, 30),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(10, 11, 12, 13, 15),
times = listOf(3, 3, 3, 3, 3),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
),
autoSkillRanks = listOf(1, 4, 9, null),
autoSkillPanels = listOf(0, 0, 5, 0),
rankPanels = listOf(
listOf(
StatBoost(StatBoostType.SpecialDefense, 1),
StatBoost(StatBoostType.ActPower, 1),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.NormalDefense, 1),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 1),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.Hp, 2),
),
listOf(
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 7),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 3),
StatBoost(StatBoostType.Act1Level, 0),
),
listOf(
StatBoost(StatBoostType.ActPower, 3),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.Hp, 3),
StatBoost(StatBoostType.ActPower, 3),
StatBoost(StatBoostType.SpecialDefense, 5),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.Hp, 4),
),
listOf(
StatBoost(StatBoostType.SpecialDefense, 3),
StatBoost(StatBoostType.NormalDefense, 7),
StatBoost(StatBoostType.Hp, 4),
StatBoost(StatBoostType.Agility, 8),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 4),
StatBoost(StatBoostType.NormalDefense, 3),
StatBoost(StatBoostType.Act1Level, 0),
),
listOf(
StatBoost(StatBoostType.ActPower, 4),
StatBoost(StatBoostType.Act1Level, 0),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.SpecialDefense, 8),
StatBoost(StatBoostType.ActPower, 5),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.NormalDefense, 4),
StatBoost(StatBoostType.Hp, 5),
),
listOf(
StatBoost(StatBoostType.SpecialDefense, 5),
StatBoost(StatBoostType.NormalDefense, 8),
StatBoost(StatBoostType.SpecialDefense, 5),
StatBoost(StatBoostType.Agility, 9),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 5),
StatBoost(StatBoostType.NormalDefense, 8),
StatBoost(StatBoostType.Hp, 5),
),
listOf(
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.Agility, 11),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.Act1Level, 0),
),
listOf(
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.NormalDefense, 6),
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.NormalDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.SpecialDefense, 6),
),
listOf(
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.NormalDefense, 6),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.NormalDefense, 6),
),
),
friendshipPanels = listOf(
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 1),
StatBoost(StatBoostType.Hp, 1),
StatBoost(StatBoostType.NormalDefense, 1),
StatBoost(StatBoostType.SpecialDefense, 1),
StatBoost(StatBoostType.Agility, 1),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 1),
StatBoost(StatBoostType.Hp, 1),
StatBoost(StatBoostType.NormalDefense, 1),
StatBoost(StatBoostType.SpecialDefense, 1),
StatBoost(StatBoostType.Agility, 1),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 1),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
),
remakeParameters = listOf(
StatData(
hp = 5400,
actPower = 540,
normalDefense = 240,
specialDefense = 90,
agility = 180,
),
StatData(
hp = 9000,
actPower = 900,
normalDefense = 400,
specialDefense = 150,
agility = 300,
),
StatData(
hp = 14400,
actPower = 1440,
normalDefense = 640,
specialDefense = 240,
agility = 480,
),
StatData(
hp = 18000,
actPower = 1800,
normalDefense = 800,
specialDefense = 300,
agility = 600,
),
),
)
| 0 | null | 0 | 0 | 53479fe3d1f4a067682509376afd87bdd205d19d | 10,758 | relive-simulator | MIT License |
app/src/main/java/dev/arkbuilders/arkdrop/presentation/feature/transferprogress/TransferProgressScreen.kt | ARK-Builders | 786,456,358 | false | {"Kotlin": 65774} | package dev.arkbuilders.arkdrop.presentation.feature.transferprogress
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.outlined.AddCircleOutline
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import dev.arkbuilders.arkdrop.presentation.feature.transferprogress.composables.FileItem
import dev.arkbuilders.arkdrop.presentation.feature.transferprogress.composables.FileTransferAlertDialog
import dev.arkbuilders.arkdrop.presentation.feature.transferprogress.composables.TransferParticipantHeader
import dev.arkbuilders.arkdrop.ui.theme.Background
import dev.arkbuilders.arkdrop.ui.theme.BlueDark600
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TransferProgressScreen(
modifier: Modifier = Modifier,
navController: NavController
) {
val openAlertDialog = remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.White
),
title = { Text("Transferring Files") },
navigationIcon = {
IconButton(
onClick = {
navController.navigateUp()
},
) {
Icon(
imageVector = Icons.Filled.Close,
contentDescription = null
)
}
})
}
) { padding ->
Column(
modifier = modifier
.background(Background)
.fillMaxSize()
.padding(padding),
horizontalAlignment = Alignment.CenterHorizontally
) {
TransferParticipantHeader()
LazyColumn(
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(listOf(1, 2, 3)) { item ->
Box(
modifier = modifier
.fillMaxWidth()
.border(
width = 0.5.dp, color = Color.LightGray,
shape = RoundedCornerShape(25)
)
.padding(16.dp)
) {
FileItem(modifier = modifier,
onCloseIconClick = {
openAlertDialog.value = true
}
)
}
}
}
OutlinedButton(
onClick = {
},
colors = ButtonDefaults.outlinedButtonColors(
contentColor = BlueDark600
),
border = BorderStroke(
width = 1.dp,
color = BlueDark600,
)) {
Icon(
imageVector = Icons.Outlined.AddCircleOutline,
contentDescription = null
)
Text("Send more")
}
if (openAlertDialog.value) {
FileTransferAlertDialog(
onDismissRequest = { openAlertDialog.value = false },
onConfirmation = { /*TODO*/ },
dialogTitle = "Cancel this file",
dialogText = "When you remove this file it cannot be undone.",
) {
FileItem(modifier = modifier)
}
} else {
}
}
}
}
@Preview
@Composable
fun PreviewTransferProgressScreen() {
TransferProgressScreen(navController = rememberNavController())
} | 1 | Kotlin | 0 | 0 | df09f7079dbb458c81dc89fb83d327de5ff1918d | 5,345 | ARK-Drop | MIT License |
src/test/integrasjonstester/kotlin/no/nav/familie/ba/sak/cucumber/mock/komponentMocks/MockTilpassKompetanserTilRegelverkService.kt | navikt | 224,639,942 | false | {"Kotlin": 6460160, "Gherkin": 961198, "PLpgSQL": 4478, "Shell": 3178, "Dockerfile": 522} | package no.nav.familie.ba.sak.cucumber.mock
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import no.nav.familie.ba.sak.kjerne.eøs.endringsabonnement.TilpassKompetanserTilRegelverkService
fun mockTilpassKompetanserTilRegelverkService(): TilpassKompetanserTilRegelverkService {
val tilpassKompetanserTilRegelverkService = mockk<TilpassKompetanserTilRegelverkService>()
every { tilpassKompetanserTilRegelverkService.tilpassKompetanserTilRegelverk(any()) } just runs
return tilpassKompetanserTilRegelverkService
}
| 10 | Kotlin | 1 | 9 | 308b51659908b302c8175719c6c6188b2b0c1bab | 565 | familie-ba-sak | MIT License |
jetpack-compose-pathways/BasicsCodelab/app/src/main/java/br/com/globalbyte/sample/and/basicscodelab/MainActivity.kt | fabio-blanco | 694,455,789 | false | {"Kotlin": 106045} | package br.com.globalbyte.sample.and.basicscodelab
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import br.com.globalbyte.sample.and.basicscodelab.ui.theme.BasicsCodelabTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BasicsCodelabTheme {
MyApp(modifier = Modifier.fillMaxSize())
}
}
}
}
@Composable
fun MyApp(modifier: Modifier = Modifier) {
var shouldShowOnboarding by rememberSaveable { mutableStateOf(true) }
Surface(modifier) {
if (shouldShowOnboarding) {
OnboardingScreen(onContinueClicked = { shouldShowOnboarding = false })
} else {
Greetings()
}
}
}
@Composable
fun OnboardingScreen(
onContinueClicked: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxSize()
.background(color = MaterialTheme.colorScheme.background),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Welcome to the Basics Codelab!", color = MaterialTheme.colorScheme.onSurface)
Button(
modifier = Modifier.padding(vertical = 24.dp),
onClick = onContinueClicked
) {
Text(text = "Continue")
}
}
}
@Composable
fun Greetings(
modifier: Modifier = Modifier,
names: List<String> = List(1000) { "$it" }
) {
LazyColumn(modifier = modifier.padding(vertical = 4.dp)) {
items(names) {name ->
Greeting(name)
}
}
}
@Preview(
showBackground = true,
widthDp = 320,
heightDp = 320
)
@Preview(
name = "NightMode",
showBackground = true,
widthDp = 320,
heightDp = 320,
uiMode = UI_MODE_NIGHT_YES
)
@Composable
fun OnboardingPreview() {
BasicsCodelabTheme {
OnboardingScreen(onContinueClicked = {})
}
}
/*@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
var expanded by remember { mutableStateOf(false) }
val extraPadding by animateDpAsState(
targetValue = if (expanded) 48.dp else 0.dp,
label = "animateExtraPadding",
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
Surface(
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
) {
Row(modifier = Modifier.padding(24.dp)) {
Column(
modifier = modifier
.weight(1f)
.padding(bottom = extraPadding.coerceAtLeast(0.dp))
) {
Text("Hello, ")
Text(
text = name,
style = MaterialTheme.typography.headlineMedium.copy(
fontWeight = FontWeight.ExtraBold
)
)
}
ElevatedButton(
onClick = { expanded = !expanded }
) {
Text(if (expanded) "Show less" else "Show more")
}
}
}
}*/
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primary
),
modifier = modifier.padding(vertical = 4.dp, horizontal = 8.dp)
) {
CardContent(name = name)
}
}
@Composable
private fun CardContent(name: String) {
var expanded by remember { mutableStateOf(false) }
Row(
modifier = Modifier
.padding(12.dp)
.animateContentSize(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
) {
Column(
modifier = Modifier
.weight(1f)
.padding(12.dp)
) {
Text("Hello, ")
Text(
text = name,
style = MaterialTheme.typography.headlineMedium.copy(
fontWeight = FontWeight.ExtraBold
)
)
if (expanded) {
Text(text = ("Compose ipsum color sit lazy, " +
"padding theme elit, sed do bouncy. ").repeat(4)
)
}
}
IconButton(onClick = { expanded = !expanded }) {
Icon(
imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
contentDescription = if (expanded) {
stringResource(id = R.string.show_less)
} else {
stringResource(id = R.string.show_more)
}
)
}
}
}
@Preview(showBackground = true, widthDp = 320)
@Preview(
name = "DarkMode",
showBackground = true,
widthDp = 320,
uiMode = UI_MODE_NIGHT_YES
)
@Composable
fun GreetingsPreview() {
BasicsCodelabTheme {
Greetings(Modifier.background(MaterialTheme.colorScheme.background))
}
}
@Preview
@Composable
fun MyAppPreview() {
BasicsCodelabTheme {
MyApp(modifier = Modifier.fillMaxSize())
}
}
| 0 | Kotlin | 0 | 0 | 58b845233d43d5a0839b6c49aacc79816628b7b9 | 7,212 | kotlin-android-samples | MIT License |
wear/src/main/java/com/wojdor/polygonwatchface/base/BaseConfigurationActivity.kt | wojciechkryg | 284,104,870 | false | {"Kotlin": 57847} | package com.wojdor.polygonwatchface.base
import android.app.Activity
import android.os.Bundle
import com.wojdor.polygonwatchface.configuration.ConfigurationItemsAdapter
import com.wojdor.polygonwatchface.databinding.ActivityConfigurationBaseBinding
abstract class BaseConfigurationActivity : Activity() {
private lateinit var binding: ActivityConfigurationBaseBinding
abstract val configurationRepository: BaseConfigurationRepository
abstract val items: List<BaseConfigurationItem>
lateinit var adapter: ConfigurationItemsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityConfigurationBaseBinding.inflate(layoutInflater)
setContentView(binding.root)
with(binding.baseConfigurationItems) {
isEdgeItemsCenteringEnabled = true
setHasFixedSize(true)
adapter = ConfigurationItemsAdapter().apply {
items = [email protected]
}.also {
[email protected] = it
}
requestFocus()
}
}
}
| 0 | Kotlin | 0 | 14 | e3a8af9bc6f80df1e6fcbf1f079f462a696878d3 | 1,149 | polygon-watch-face | Apache License 2.0 |
kodex-gradle-plugin-figma/src/main/kotlin/io/vitalir/kodex/data/figma/network/FigmaTypes.kt | vitalir2 | 519,806,381 | false | {"Kotlin": 22803} | package io.vitalir.kodex.data.figma.network
import kotlinx.serialization.Serializable
@Serializable
data class Paint(
val type: String,
val color: Color,
val opacity: Double,
)
@Serializable
data class Color(
val r: Double,
val g: Double,
val b: Double,
val a: Double,
)
| 0 | Kotlin | 0 | 0 | d1363f901de7e1dc1d2ae8d9b6a9859547f965ba | 302 | Kodex | Apache License 2.0 |
lib/template-kmp-library-core/src/commonTest/kotlin/CoreLibTest.kt | mpetuska | 354,298,645 | false | null | package dev.petuska.template.kmp.library.core
import dev.petuska.klip.api.assertKlip
import local.test.BlockingTest
import kotlin.test.Test
import kotlin.test.assertEquals
class CoreLibTest : BlockingTest {
@Test
fun test() = blockingTest {
val result = CoreLib().sampleApi()
println(result)
assertEquals(result, platform)
}
@Test
fun testSuspend() = blockingTest {
val result = CoreLib().sampleSuspendApi()
println(result)
assertEquals(result, platform)
}
@Test
fun testValue() = blockingTest {
val result = CoreLib().sampleValue
println(result)
result.assertKlip()
}
}
| 9 | Kotlin | 5 | 53 | 1f58e2bb28b4bdeda4cd8b38e2620e7bbd5f4f2b | 629 | template-kmp-library | Apache License 2.0 |
app/src/main/java/com/setianjay/githubuser/screens/fragment/FollowingFragment.kt | setianjay | 393,715,206 | false | null | package com.setianjay.githubuser.screens.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.setianjay.githubuser.databinding.FragmentFollowingBinding
import com.setianjay.githubuser.model.user.UsersModel
import com.setianjay.githubuser.network.resource.Resource
import com.setianjay.githubuser.screens.adapter.UserListAdapter
import com.setianjay.githubuser.utill.Constant
import com.setianjay.githubuser.utill.display
import com.setianjay.githubuser.viewmodel.GithubViewModel
class FollowingFragment private constructor() : Fragment() {
private var _binding: FragmentFollowingBinding? = null
private val binding get() = _binding
private lateinit var userAdapter: UserListAdapter
private var username: String? = null
private val viewModel by viewModels<GithubViewModel>({
requireActivity()
})
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentFollowingBinding.inflate(inflater, container, false)
return binding?.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initData()
setupObserver()
setupRecycleView()
}
override fun onStart() {
super.onStart()
showFollowing()
}
/* function to initialize data */
private fun initData(){
username = arguments?.getString(ARG_USERNAME)
}
/* function to set up any observer in view model */
private fun setupObserver(){
// observe for following of user and set with value based on condition
viewModel.network.getFollowing().observe(viewLifecycleOwner){
when(it.statusType){
Resource.StatusType.LOADING -> {
showLoading(true)
}
Resource.StatusType.SUCCESS -> {
showLoading(false)
it.data?.let { following -> userAdapter.setDataUser(following) }
}
Resource.StatusType.ERROR -> {
showLoading(false)
it.message?.let { message -> getError(message) }
}
}
}
}
/* function to set up recycle view */
private fun setupRecycleView(){
userAdapter = UserListAdapter(object: UserListAdapter.OnUserListAdapterListener{
override fun onClick(data: UsersModel) {
}
})
binding?.rvFollowing?.apply {
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL,false)
adapter = userAdapter
setHasFixedSize(true)
}
}
/* function to show following of user */
private fun showFollowing(){
username?.let { viewModel.network.userFollowing(it) }
}
/* function to show and not show progress bar for loading content */
private fun showLoading(show: Boolean){
binding?.pbLoading?.display(show)
}
/* function to show and not show button refresh */
private fun showBtnRefresh(show: Boolean){
binding?.btnRefresh?.display(show)
}
/* function to get error code */
private fun getError(errorCode: Int){
when(errorCode){
Constant.ERROR.ERR_USERS_NOT_FOUND -> {
binding?.tvNoFollowers?.visibility = View.VISIBLE
}
Constant.ERROR.ERR_API -> {
showBtnRefresh(true)
binding?.btnRefresh?.setOnClickListener {
showFollowing()
showBtnRefresh(false)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
companion object{
private const val ARG_USERNAME = "username"
/* function to initialize this class */
fun newInstance(username: String): Fragment{
val fragment = FollowingFragment()
val bundle = Bundle()
bundle.putString(ARG_USERNAME, username)
fragment.arguments = bundle
return fragment
}
}
} | 0 | Kotlin | 0 | 0 | 490919a7ee8555603f4c7e2446640cd491a8a6cc | 4,408 | GithubUser | MIT License |
app/src/main/java/com/karlgao/kotlintemplate/data/network/WebServiceManager.kt | gtk890811 | 101,605,710 | false | null | package com.karlgao.kotlintemplate.data.network
/**
* Created by dev on 12/9/17.
*/
class WebServiceManager {
} | 0 | Kotlin | 0 | 0 | 2e475ada30b198e68ea643379618aba4169eda59 | 114 | androidkot-fluffy-system | Apache License 2.0 |
presentation/src/main/java/com/dsm/dms/presentation/di/module/main/apply/ApplyStaticModule.kt | DSM-DMS | 203,186,000 | false | null | package com.dsm.dms.presentation.di.module.main.apply
import com.dsm.dms.presentation.di.scope.MainFragmentScope
import com.dsm.dms.presentation.viewmodel.main.apply.ApplyViewModelFactory
import dagger.Module
import dagger.Provides
@Module
class ApplyStaticModule {
@MainFragmentScope
@Provides
fun provideViewModelFactory(): ApplyViewModelFactory
= ApplyViewModelFactory()
} | 0 | Kotlin | 2 | 14 | ae7de227cee270d22a72a4f59090bff07c43f019 | 401 | DMS-Android-V4 | MIT License |
spring/break/src/test/kotlin/com/project/break/BreakApplicationTests.kt | lms2002 | 868,402,813 | false | {"Kotlin": 14640} | package com.project.`break`
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class BreakApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Kotlin | 0 | 0 | 29d78758454246b18ef6dbfcb53341e34c9d151d | 206 | break | Apache License 2.0 |
core/src/main/java/io/astronout/core/data/source/remote/model/GamesResponse.kt | ariastro | 716,076,256 | false | {"Kotlin": 121806} | package io.astronout.core.data.source.remote.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class GamesResponse(
@Json(name = "count")
val count: Int? = null,
@Json(name = "next")
val next: String? = null,
@Json(name = "previous")
val previous: Any? = null,
@Json(name = "results")
val results: List<GameItem>? = null
) | 0 | Kotlin | 0 | 4 | d102554842a942baa52129812df72dc7e1a7a1f8 | 419 | Geem-Compose | MIT License |
behavioral-observer/src/main/kotlin/com/ahasanidea/kotlin/observer/one/Subject.kt | ahasanhub | 156,586,794 | false | {"Kotlin": 4917, "Java": 792} | package com.ahasanidea.kotlin.observer.one
/**
* This is subject
*/
class Subject {
var observers= mutableListOf<Observer>()
var state=0
fun changeState(s:Int){
state=s
notifyAllObservers()
}
fun attach(observer: Observer){
observers.add(observer)
}
fun detach(observer: Observer){
observers.remove(observer)
}
fun notifyAllObservers(){
for (o in observers)
o.update(state)
}
}
| 0 | Kotlin | 0 | 0 | 28a02ab73abc9a7c26c0a7e240989c7d045ebb9e | 473 | kotlin-designpattern | Apache License 2.0 |
src/main/java/ru/itmo/kazakov/autoschedule/algorithm/operator/NextPopulationSelectionBatcher.kt | AdvancerMan | 636,416,766 | false | null | package ru.itmo.kazakov.autoschedule.algorithm.operator
import ru.itmo.kazakov.autoschedule.algorithm.individual.Individual
import ru.itmo.kazakov.autoschedule.algorithm.integration.JmetalIndividual
interface NextPopulationSelectionBatcher<I : Individual<I>> {
fun <J : JmetalIndividual<I>> selectPopulationBatches(
population: MutableList<J>,
offspringPopulation: MutableList<J>,
populationSize: Int,
): Sequence<PopulationBatch<I, J>>
}
| 0 | Kotlin | 0 | 0 | b27a04ba71342c42af17b02654169107afaf23ea | 474 | itmo-ct-thesis-2023 | MIT License |
app/src/main/java/com/shencoder/srs_rtc_android_client/ui/check_user/adapter/CheckUserAdapter.kt | shenbengit | 444,852,543 | false | {"Kotlin": 275977} | package com.shencoder.srs_rtc_android_client.ui.check_user.adapter
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.shencoder.srs_rtc_android_client.R
import com.shencoder.srs_rtc_android_client.constant.ChatMode
import com.shencoder.srs_rtc_android_client.constant.MMKVConstant
import com.shencoder.srs_rtc_android_client.databinding.ItemCheckUserBinding
import com.shencoder.srs_rtc_android_client.http.bean.UserInfoBean
import com.tencent.mmkv.MMKV
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
/**
*
* @author ShenBen
* @date 2022/1/19 17:23
* @email <EMAIL>
*/
class CheckUserAdapter :
BaseQuickAdapter<UserInfoBean, BaseDataBindingHolder<ItemCheckUserBinding>>(R.layout.item_check_user),KoinComponent {
private companion object {
private const val UPDATE_CHECKED = "UPDATE_CHECKED"
}
private val mmkv: MMKV by inject()
private var chatMode = ChatMode.PRIVATE_MODE
private var lastCheckedPosition = RecyclerView.NO_POSITION
fun setChatMode(chatMode: ChatMode) {
if (this.chatMode != ChatMode.GROUP_MODE) {
this.chatMode = chatMode
lastCheckedPosition = RecyclerView.NO_POSITION
if (data.isNotEmpty()) {
val localUserInfo =
mmkv.decodeParcelable(MMKVConstant.USER_INFO, UserInfoBean::class.java)
//先还原数据,当前用户不可点击
data.forEach {
if (it == localUserInfo) {
it.selectable = false
it.isSelected = true
} else {
it.isSelected = false
}
}
notifyDataSetChanged()
}
}
}
override fun onItemViewHolderCreated(
viewHolder: BaseDataBindingHolder<ItemCheckUserBinding>,
viewType: Int
) {
viewHolder.dataBinding?.run {
cbSelected.setOnCheckedChangeListener { _, isChecked ->
val position = viewHolder.bindingAdapterPosition - headerLayoutCount
val item = getItem(position)
if (item.selectable.not()) {
return@setOnCheckedChangeListener
}
item.isSelected = isChecked
when (chatMode) {
ChatMode.PRIVATE_MODE -> {
//私聊-单选
if (isChecked) {
//选中状态
if (lastCheckedPosition != RecyclerView.NO_POSITION) {
getItem(lastCheckedPosition).isSelected = false
notifyItemChanged(lastCheckedPosition, UPDATE_CHECKED)
}
lastCheckedPosition = position
}
}
ChatMode.GROUP_MODE -> {
//群聊-多选
}
}
}
}
}
override fun convert(
holder: BaseDataBindingHolder<ItemCheckUserBinding>,
item: UserInfoBean,
payloads: List<Any>
) {
val any = payloads[0]
if (any is String) {
if (any == UPDATE_CHECKED) {
val cbSelected: CheckBox = holder.getView(R.id.cbSelected)
cbSelected.isChecked = item.isSelected
}
}
}
override fun convert(holder: BaseDataBindingHolder<ItemCheckUserBinding>, item: UserInfoBean) {
val avatarDrawable = when ((holder.bindingAdapterPosition - headerLayoutCount) % 5) {
0 -> R.drawable.ic_avatar01
1 -> R.drawable.ic_avatar02
2 -> R.drawable.ic_avatar03
3 -> R.drawable.ic_avatar04
else -> R.drawable.ic_avatar05
}
holder.run {
this.dataBinding?.item = item
setImageResource(R.id.ivAvatar, avatarDrawable)
val cbSelected: CheckBox = getView(R.id.cbSelected)
cbSelected.isChecked = item.isSelected
cbSelected.isEnabled = item.selectable
}
}
}
| 0 | Kotlin | 9 | 41 | c14bb9df72e542d3f4f187b47bab15bf68bb2886 | 4,308 | SrsRtcAndroidClient | MIT License |
app/src/main/java/com/loften/kweather/gson/Weather.kt | myloften | 100,086,119 | false | null | package com.loften.kweather.gson
/**
* Created by lcw on 2017/9/25.
*/
data class Weather(
val aqi: Aqi,
val basic: Basic,
val daily_forecast: List<DailyForecast>,
val hourly_forecast: List<HourlyForecast>,
val now: Now,
val status: String, //ok
val suggestion: Suggestion
)
data class Aqi(
val city: City
)
data class City(
val aqi: String, //17
val co: String, //1
val no2: String, //13
val o3: String, //47
val pm10: String, //17
val pm25: String, //8
val qlty: String, //优
val so2: String //5
)
data class HourlyForecast(
val cond: Cond,
val date: String, //2017-09-25 19:00
val hum: String, //81
val pop: String, //0
val pres: String, //1012
val tmp: String, //29
val wind: Wind
)
data class Wind(
val deg: String, //258
val dir: String, //西南风
val sc: String, //微风
val spd: String //5
)
data class Cond(
val code: String, //103
val txt: String //晴间多云
)
data class Basic(
val city: String, //南投
val cnty: String, //中国
val id: String, //CN101340404
val lat: String, //23.91600037
val lon: String, //120.68499756
val update: Update
)
data class Update(
val loc: String, //2017-09-25 16:46
val utc: String //2017-09-25 08:46
)
data class Now(
val cond: Cond,
val fl: String, //39
val hum: String, //73
val pcpn: String, //0.00
val pres: String, //1012
val tmp: String, //32
val vis: String, //20
val wind: Wind
)
data class Suggestion(
val air: Air,
val comf: Comf,
val cw: Cw,
val drsg: Drsg,
val flu: Flu,
val sport: Sport,
val trav: Trav,
val uv: Uv
)
data class Sport(
val brf: String, //较不宜
val txt: String //阴天,且天气较热,请减少运动时间并降低运动强度。
)
data class Air(
val brf: String, //良
val txt: String //气象条件有利于空气污染物稀释、扩散和清除,可在室外正常活动。
)
data class Comf(
val brf: String, //较不舒适
val txt: String //白天天气多云,同时会感到有些热,不很舒适。
)
data class Uv(
val brf: String, //弱
val txt: String //紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。
)
data class Drsg(
val brf: String, //炎热
val txt: String //天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。
)
data class Flu(
val brf: String, //少发
val txt: String //各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。
)
data class Trav(
val brf: String, //适宜
val txt: String //天气较好,风稍大,稍热,总体来说还是好天气。适宜旅游,可不要错过机会呦!
)
data class Cw(
val brf: String, //较不宜
val txt: String //较不宜洗车,未来一天无雨,风力较大,如果执意擦洗汽车,要做好蒙上污垢的心理准备。
)
data class DailyForecast(
val astro: Astro,
val cond: Cond,
val date: String, //2017-09-25
val hum: String, //69
val pcpn: String, //3.8
val pop: String, //10
val pres: String, //1012
val tmp: Tmp,
val uv: String, //10
val vis: String, //15
val wind: Wind
)
data class Tmp(
val max: String, //33
val min: String //26
)
data class Astro(
val mr: String, //10:00
val ms: String, //21:24
val sr: String, //05:46
val ss: String //17:50
) | 1 | null | 1 | 1 | 3a6683162684752b873267ae99255556f4f07432 | 2,819 | KWeather | Apache License 2.0 |
android/feature/vote/src/main/java/dylan/kwon/votechain/feature/vote/screen/detail/composable/VoteDetailLoadedScreen.kt | dylan-kwon | 823,387,423 | false | {"Kotlin": 320698, "Solidity": 9240, "JavaScript": 8572} | @file:OptIn(ExperimentalLayoutApi::class, ExperimentalLayoutApi::class)
package dylan.kwon.votechain.feature.vote.screen.detail.composable
import android.text.Layout
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.HowToVote
import androidx.compose.material.icons.filled.People
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import com.patrykandpatrick.vico.compose.cartesian.CartesianChartHost
import com.patrykandpatrick.vico.compose.cartesian.axis.rememberBottomAxis
import com.patrykandpatrick.vico.compose.cartesian.axis.rememberStartAxis
import com.patrykandpatrick.vico.compose.cartesian.layer.rememberColumnCartesianLayer
import com.patrykandpatrick.vico.compose.cartesian.rememberCartesianChart
import com.patrykandpatrick.vico.compose.common.component.rememberLineComponent
import com.patrykandpatrick.vico.compose.common.of
import com.patrykandpatrick.vico.compose.common.shape.rounded
import com.patrykandpatrick.vico.core.cartesian.data.CartesianChartModelProducer
import com.patrykandpatrick.vico.core.cartesian.data.columnSeries
import com.patrykandpatrick.vico.core.cartesian.layer.ColumnCartesianLayer
import com.patrykandpatrick.vico.core.cartesian.marker.DefaultCartesianMarker
import com.patrykandpatrick.vico.core.common.Defaults
import com.patrykandpatrick.vico.core.common.Dimensions
import com.patrykandpatrick.vico.core.common.component.TextComponent
import com.patrykandpatrick.vico.core.common.shape.Shape
import dylan.kwon.votechain.core.ui.design_system.theme.VoteChainTheme
import dylan.kwon.votechain.core.ui.design_system.theme.composable.iconWithText.IconWithText
import dylan.kwon.votechain.core.ui.design_system.theme.composable.image.VoteChainImage
import dylan.kwon.votechain.feature.vote.R
import dylan.kwon.votechain.feature.vote.screen.detail.composable.preview.VoteDetailLoadedUiStatePreviewParameterProvider
import dylan.kwon.votechain.feature.vote.screen.detail.VoteDetailScreen
import dylan.kwon.votechain.feature.vote.screen.detail.VoteDetailUiState
import kotlinx.collections.immutable.ImmutableList
import dylan.kwon.votechain.feature.vote.screen.detail.VoteDetailUiState.Loaded.BallotItem as BallotItemUiState
import dylan.kwon.votechain.feature.vote.screen.detail.VoteDetailUiState.Loaded.Vote as VoteUiState
@Composable
fun VoteDetailScreen.Loaded(
modifier: Modifier = Modifier,
uiState: VoteDetailUiState.Loaded,
scrollState: ScrollState = rememberScrollState(),
onBallotItemCheckedChange: (BallotItemUiState) -> Unit,
onSubmitClick: () -> Unit,
onConsumedToastMessage: () -> Unit
) {
Box(modifier = modifier) {
Column(
modifier = Modifier.verticalScroll(scrollState),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Time Ago
TimeAgo(
modifier = Modifier.align(Alignment.End),
timeAgo = uiState.vote.createdAgo
)
// Image
val imageUrl = uiState.vote.imageUrl
if (imageUrl != null) {
VoteImage(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(2 / 1f),
imageUrl = imageUrl,
contentDescription = uiState.vote.title
)
}
// Status & Voter Count
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
// Status
VoteStatus(
status = uiState.vote.voteStatus
)
// Voter Count
VoterCount(
voterCount = uiState.vote.voterCount
)
}
// Content
Content(
text = uiState.vote.content
)
// Ballot Items
AnimatedVisibility(uiState.canVoting) {
BallotItems(
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp),
ballotItems = uiState.vote.ballotItems,
enabled = uiState.canVoting,
canMultipleChoice = uiState.canMultipleChoice,
onCheckedChange = onBallotItemCheckedChange
)
}
// Submit Button
AnimatedVisibility(
modifier = Modifier.align(Alignment.End),
visible = uiState.canVoting
) {
SubmitButton(
enabled = uiState.isSubmitButtonEnabled,
onClick = onSubmitClick
)
}
// Statistics
AnimatedVisibility(!uiState.canVoting) {
Statistics(
modifier = Modifier.fillMaxWidth(),
ballotItems = uiState.vote.ballotItems
)
}
}
// Progress Bar
AnimatedVisibility(
modifier = Modifier
.align(Alignment.Center)
.padding(top = 16.dp),
visible = uiState.isProgressShowing
) {
CircularProgressIndicator()
}
}
val context = LocalContext.current
val toastMessage = uiState.toastMessage
if (toastMessage != null) LaunchedEffect(Unit) {
Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show()
onConsumedToastMessage()
}
}
@Composable
private fun TimeAgo(
modifier: Modifier = Modifier,
timeAgo: String
) {
Text(
modifier = modifier,
text = timeAgo,
style = MaterialTheme.typography.labelMedium
)
}
@Composable
private fun VoteImage(
modifier: Modifier = Modifier,
imageUrl: String,
contentDescription: String
) {
VoteChainImage(
modifier = modifier.clip(RoundedCornerShape(4.dp)),
model = imageUrl,
contentScale = ContentScale.Crop,
contentDescription = contentDescription,
)
}
@Composable
private fun VoteStatus(
modifier: Modifier = Modifier,
status: VoteUiState.Status
) {
IconWithText(
modifier = modifier,
imageVector = status.toImageVector(),
contentDescription = stringResource(id = R.string.status),
text = status.toLabel(),
textColor = status.toTextColor(),
backgroundColor = status.toBackgroundColor()
)
}
@Composable
private fun VoteUiState.Status.toImageVector(): ImageVector {
return when (this) {
VoteUiState.Status.IN_PROGRESS -> Icons.Default.HowToVote
VoteUiState.Status.CLOSED -> Icons.Default.Close
}
}
@Composable
private fun VoteUiState.Status.toLabel(): String {
return when (this) {
VoteUiState.Status.IN_PROGRESS -> stringResource(id = R.string.inprogress)
VoteUiState.Status.CLOSED -> stringResource(id = R.string.closed)
}
}
@Composable
private fun VoteUiState.Status.toBackgroundColor(): Color {
return when (this) {
VoteUiState.Status.IN_PROGRESS -> MaterialTheme.colorScheme.primaryContainer
VoteUiState.Status.CLOSED -> MaterialTheme.colorScheme.errorContainer
}
}
@Composable
private fun VoteUiState.Status.toTextColor(): Color {
return when (this) {
VoteUiState.Status.IN_PROGRESS -> MaterialTheme.colorScheme.onPrimaryContainer
VoteUiState.Status.CLOSED -> MaterialTheme.colorScheme.onErrorContainer
}
}
@Composable
private fun VoterCount(
modifier: Modifier = Modifier,
voterCount: String
) {
IconWithText(
modifier = modifier,
imageVector = Icons.Default.People,
contentDescription = stringResource(id = R.string.voter_count),
text = voterCount,
textColor = MaterialTheme.colorScheme.onTertiaryContainer,
backgroundColor = MaterialTheme.colorScheme.tertiaryContainer
)
}
@Composable
private fun Content(
modifier: Modifier = Modifier,
text: String
) {
Text(
modifier = modifier,
text = text,
)
}
@Composable
private fun BallotItems(
modifier: Modifier = Modifier,
enabled: Boolean,
canMultipleChoice: Boolean,
ballotItems: ImmutableList<BallotItemUiState>,
onCheckedChange: (BallotItemUiState) -> Unit
) {
Column(
modifier = modifier,
) {
ballotItems.forEach { ballotItem ->
key(ballotItem.name) {
BallotItem(
modifier = Modifier.fillMaxWidth(),
text = ballotItem.name,
isChecked = ballotItem.isVoted,
enabled = enabled,
canMultipleChoice = canMultipleChoice,
onCheckedChange = {
onCheckedChange(ballotItem)
}
)
}
}
}
}
@Composable
private fun BallotItem(
modifier: Modifier = Modifier,
text: String,
isChecked: Boolean,
enabled: Boolean,
canMultipleChoice: Boolean,
onCheckedChange: () -> Unit
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
when (canMultipleChoice) {
true -> Checkbox(
enabled = enabled,
checked = isChecked,
onCheckedChange = {
onCheckedChange()
}
)
else -> RadioButton(
enabled = enabled,
selected = isChecked,
onClick = {
onCheckedChange()
}
)
}
Text(
modifier = Modifier.weight(1f),
text = text,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
@Composable
private fun SubmitButton(
modifier: Modifier = Modifier,
enabled: Boolean,
onClick: () -> Unit
) {
ElevatedButton(
modifier = modifier,
enabled = enabled,
onClick = onClick
) {
Text(text = stringResource(id = R.string.submit))
}
}
@Composable
private fun Statistics(
modifier: Modifier = Modifier,
ballotItems: ImmutableList<BallotItemUiState>,
) {
val modelProducer = remember {
CartesianChartModelProducer()
}
LaunchedEffect(ballotItems) {
modelProducer.runTransaction {
columnSeries {
series(
ballotItems.map {
it.votingCount
}
)
}
}
}
CartesianChartHost(
modifier = modifier,
chart = rememberCartesianChart(
rememberColumnCartesianLayer(
ColumnCartesianLayer.ColumnProvider.series(
rememberLineComponent(
color = MaterialTheme.colorScheme.inversePrimary,
thickness = Defaults.COLUMN_WIDTH.dp,
shape = Shape.rounded(topLeft = 4.dp, topRight = 4.dp)
),
),
),
startAxis = rememberStartAxis(
label = TextComponent(
margins = Dimensions.of(end = 8.dp)
),
tick = null,
valueFormatter = remember {
{ value, _, _ ->
val toInt = value.toInt()
if (value > toInt && value < toInt + 1) {
""
} else {
toInt.toString()
}
}
}
),
bottomAxis = rememberBottomAxis(
tick = null,
guideline = null,
valueFormatter = remember {
{ value, _, _ ->
ballotItems[value.toInt()].name
}
}
),
marker = DefaultCartesianMarker(
label = TextComponent(
textAlignment = Layout.Alignment.ALIGN_OPPOSITE
),
labelPosition = DefaultCartesianMarker.LabelPosition.AbovePoint
)
),
modelProducer = modelProducer
)
}
@Composable
@Preview(showBackground = true)
internal fun LoadedPreview(
@PreviewParameter(VoteDetailLoadedUiStatePreviewParameterProvider::class)
uiState: VoteDetailUiState.Loaded
) {
VoteChainTheme {
VoteDetailScreen.Loaded(
uiState = uiState,
onBallotItemCheckedChange = {},
onSubmitClick = {},
onConsumedToastMessage = {}
)
}
} | 0 | Kotlin | 0 | 2 | 69a7999d8c11fde1b95c079380e8deecbba65659 | 14,536 | vote-chain | Apache License 2.0 |
foundation/permissions/api/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/foundation/permissions/api/ui/PermissionsState.kt | savvasdalkitsis | 485,908,521 | false | {"Kotlin": 2402997, "Ruby": 1294, "PowerShell": 325, "Shell": 158} | package com.savvasdalkitsis.uhuruphotos.foundation.permissions.api.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.google.accompanist.permissions.MultiplePermissionsState
import com.google.accompanist.permissions.rememberMultiplePermissionsState
class PermissionsState(
internal val missingPermissions: List<String>?,
internal var showRationale: MutableState<Boolean>,
internal var showAccessRequest: MutableState<Boolean>,
) {
private var permissionState: MultiplePermissionsState? = null
@Composable
internal fun Compose() {
permissionState = missingPermissions?.let {
rememberMultiplePermissionsState(it)
}
}
fun askForPermissions() {
permissionState?.let {
if (it.shouldShowRationale) {
showRationale.value = true
} else if (!it.allPermissionsGranted) {
showAccessRequest.value = true
}
}
}
companion object {
@Composable
fun rememberPermissionsState(
missingPermissions: List<String>?,
): MutableState<PermissionsState> {
val state = remember(missingPermissions) {
mutableStateOf(
PermissionsState(
missingPermissions,
mutableStateOf(false),
mutableStateOf(false),
)
)
}
PermissionsCheck(state.value)
return state
}
}
} | 45 | Kotlin | 24 | 296 | 09ba2d9d05dc177fbea09da907d51610e8640805 | 1,665 | uhuruphotos-android | Apache License 2.0 |
app/src/com/kostasdrakonakis/flappybird/FlappyBird.kt | kostasdrakonakis | 197,761,384 | false | {"Kotlin": 8892} | /*
* Copyright 2018 Konstantinos Drakonakis.
*
* 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.kostasdrakonakis.flappybird
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Circle
import com.badlogic.gdx.math.Intersector
import com.badlogic.gdx.math.Rectangle
import java.util.*
class FlappyBird : ApplicationAdapter() {
private lateinit var batch: SpriteBatch
private lateinit var background: Texture
private lateinit var gameOver: Texture
private lateinit var birds: Array<Texture>
private lateinit var topTubeRectangles: Array<Rectangle?>
private lateinit var bottomTubeRectangles: Array<Rectangle?>
private lateinit var birdCircle: Circle
private lateinit var font: BitmapFont
private lateinit var topTube: Texture
private lateinit var bottomTube: Texture
private lateinit var random: Random
private lateinit var manager: AssetManager
private var flapState = 0
private var birdY: Float = 0f
private var velocity: Float = 0f
private var score: Int = 0
private var scoringTube: Int = 0
private var gameState: Int = 0
private val numberOfTubes: Int = 4
private var gdxHeight: Int = 0
private var gdxWidth: Int = 0
private var topTubeWidth: Int = 0
private var bottomTubeWidth: Int = 0
private var topTubeHeight: Int = 0
private var bottomTubeHeight: Int = 0
private val tubeX = FloatArray(numberOfTubes)
private val tubeOffset = FloatArray(numberOfTubes)
private var distanceBetweenTubes: Float = 0.toFloat()
private lateinit var music: Music
override fun create() {
batch = SpriteBatch()
manager = AssetManager()
manager.load("smolove.mp3", Music::class.java)
manager.finishLoading()
background = Texture("bg.png")
gameOver = Texture("gameover.png")
birdCircle = Circle()
font = BitmapFont()
font.color = Color.WHITE
font.data.setScale(10f)
birds = arrayOf(Texture("bird.png"), Texture("bird2.png"))
gdxHeight = Gdx.graphics.height
gdxWidth = Gdx.graphics.width
topTube = Texture("toptube.png")
bottomTube = Texture("bottomtube.png")
random = Random()
distanceBetweenTubes = gdxWidth * 3f / 4f
topTubeRectangles = arrayOfNulls(numberOfTubes)
bottomTubeRectangles = arrayOfNulls(numberOfTubes)
topTubeWidth = topTube.width
topTubeHeight = topTube.height
bottomTubeWidth = bottomTube.width
bottomTubeHeight = bottomTube.height
startGame()
}
override fun render() {
batch.begin()
batch.draw(background, 0f, 0f, gdxWidth.toFloat(), gdxHeight.toFloat())
music = manager.get("smolove.mp3", Music::class.java)
music.isLooping
music.play()
if (gameState == 1) {
if (tubeX[scoringTube] < gdxWidth / 2) {
score++
if (scoringTube < numberOfTubes - 1) {
scoringTube++
} else {
scoringTube = 0
}
}
if (Gdx.input.justTouched()) {
velocity = -30f
}
for (i in 0 until numberOfTubes) {
if (tubeX[i] < -topTubeWidth) {
tubeX[i] += numberOfTubes * distanceBetweenTubes
tubeOffset[i] = (random.nextFloat() - 0.5f) * (gdxHeight.toFloat() - GAP - 200f)
} else {
tubeX[i] = tubeX[i] - TUBE_VELOCITY
}
batch.draw(topTube, tubeX[i], gdxHeight / 2f + GAP / 2 + tubeOffset[i])
batch.draw(bottomTube,
tubeX[i],
gdxHeight / 2f - GAP / 2 - bottomTubeHeight.toFloat() + tubeOffset[i])
topTubeRectangles[i] = Rectangle(tubeX[i],
gdxHeight / 2f + GAP / 2 + tubeOffset[i],
topTubeWidth.toFloat(),
topTubeHeight.toFloat())
bottomTubeRectangles[i] = Rectangle(tubeX[i],
gdxHeight / 2f - GAP / 2 - bottomTubeHeight.toFloat() + tubeOffset[i],
bottomTubeWidth.toFloat(),
bottomTubeHeight.toFloat())
}
if (birdY > 0) {
velocity += GRAVITY
birdY -= velocity
} else {
gameState = 2
}
} else if (gameState == 0) {
if (Gdx.input.justTouched()) {
gameState = 1
}
} else if (gameState == 2) {
batch.draw(gameOver,
gdxWidth / 2f - gameOver.width / 2f,
gdxHeight / 2f - gameOver.height / 2f)
if (Gdx.input.justTouched()) {
gameState = 1
startGame()
score = 0
scoringTube = 0
velocity = 0f
}
}
flapState = if (flapState == 0) 1 else 0
batch.draw(birds[flapState], gdxWidth / 2f - birds[flapState].width / 2f, birdY)
font.draw(batch, score.toString(), 100f, 200f)
birdCircle.set(gdxWidth / 2f,
birdY + birds[flapState].height / 2f,
birds[flapState].width / 2f)
for (i in 0 until numberOfTubes) {
if (Intersector.overlaps(birdCircle, topTubeRectangles[i])
|| Intersector.overlaps(birdCircle, bottomTubeRectangles[i])) gameState = 2
}
batch.end()
}
private fun startGame() {
birdY = gdxHeight / 2f - birds[0].height / 2f
for (i in 0 until numberOfTubes) {
tubeOffset[i] = (random.nextFloat() - 0.5f) * (gdxHeight.toFloat() - GAP - 200f)
tubeX[i] = gdxWidth / 2f - topTubeWidth / 2f + gdxWidth.toFloat() + i * distanceBetweenTubes
topTubeRectangles[i] = Rectangle()
bottomTubeRectangles[i] = Rectangle()
}
}
companion object {
private const val GRAVITY = 2f
private const val TUBE_VELOCITY = 4f
private const val GAP = 800f
}
}
| 0 | Kotlin | 22 | 26 | ab83ceda4e61171fda03a5434e60119afec54252 | 7,005 | flappybird | Apache License 2.0 |
domain/src/main/java/br/com/gielamo/tmdb/domain/usecase/movie/RetrieveMovieDetailsUseCase.kt | egoliveira | 736,048,637 | false | {"Kotlin": 115109} | package br.com.gielamo.tmdb.domain.usecase.movie
import br.com.gielamo.tmdb.domain.repository.MovieRepository
import br.com.gielamo.tmdb.domain.usecase.UseCase
import br.com.gielamo.tmdb.domain.vo.Movie
import br.com.gielamo.tmdb.domain.vo.MovieDetails
import javax.inject.Inject
class RetrieveMovieDetailsUseCase @Inject constructor(
private val movieRepository: MovieRepository
) : UseCase<RetrieveMovieDetailsUseCase.Params, MovieDetails> {
override suspend fun execute(params: Params): MovieDetails {
return movieRepository.getMovieDetails(params.movie.id, params.language)
}
data class Params(val movie: Movie, val language: String? = null)
} | 0 | Kotlin | 0 | 0 | ae88e7b77d58696c3c0f948d01ccac37ae26495c | 674 | TMDB-Demo | Apache License 2.0 |
src/main/kotlin/de/akquinet/tim/proxy/availability/RegistrationServiceHealthApi.kt | tim-ref | 751,475,615 | false | {"Kotlin": 312946, "Perl": 30621, "Shell": 11056, "Dockerfile": 3792, "Python": 976} | /*
* Copyright © 2023 - 2024 akquinet GmbH (https://www.akquinet.de)
*
* 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 de.akquinet.tim.proxy.availability
import de.akquinet.tim.proxy.ProxyConfiguration
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import java.net.URL
class RegistrationServiceHealthApi(
private val httpClientEngine: HttpClientEngine,
private val rsConfig: ProxyConfiguration.RegistrationServiceConfiguration
) {
private val client = HttpClient(httpClientEngine) {}
suspend fun getReadinessState(): HttpResponse = client.get(
URL(rsConfig.baseUrl + ":" + rsConfig.healthPort + rsConfig.readinessEndpoint).toString()
)
}
| 0 | Kotlin | 0 | 1 | 70c6c72b6ce80b877628d7634754f30f00cf21b9 | 1,303 | messenger-proxy | Apache License 2.0 |
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/MaksdatoE2ETest.kt | navikt | 193,907,367 | false | null | package no.nav.helse.spleis.e2e
import no.nav.helse.hendelser.Periode
import no.nav.helse.hendelser.Sykmeldingsperiode
import no.nav.helse.hendelser.Søknad
import no.nav.helse.hendelser.til
import no.nav.helse.januar
import no.nav.helse.person.IdInnhenter
import no.nav.helse.person.TilstandType
import no.nav.helse.økonomi.Prosentdel.Companion.prosent
import org.junit.jupiter.api.Test
internal class MaksdatoE2ETest : AbstractEndToEndTest() {
@Test
fun `syk etter maksdato`() {
var forrigePeriode = 1.januar til 31.januar
nyttVedtak(forrigePeriode.start, forrigePeriode.endInclusive, 100.prosent)
// setter opp vedtaksperioder frem til 182 dager etter maksdato
repeat(17) { _ ->
forrigePeriode = nestePeriode(forrigePeriode)
forlengVedtak(forrigePeriode.start, forrigePeriode.endInclusive)
}
// oppretter forlengelse fom 182 dager etter maksdato: denne blir kastet til Infotrygd
forrigePeriode = nyPeriodeMedYtelser(forrigePeriode)
assertSisteTilstand(observatør.sisteVedtaksperiode(), TilstandType.TIL_INFOTRYGD) {
"Disse periodene skal kastes ut pr nå"
}
forrigePeriode = nyPeriode(forrigePeriode)
val siste = observatør.sisteVedtaksperiode()
val inntektsmeldingId = inntektsmeldinger.keys.also { check(it.size == 1) { "forventer bare én inntektsmelding" } }.first()
håndterInntektsmeldingReplay(inntektsmeldingId, siste.id(ORGNUMMER))
assertSisteTilstand(siste, TilstandType.AVVENTER_INNTEKTSMELDING_ELLER_HISTORIKK_FERDIG_GAP) {
"denne perioden skal under ingen omstendigheter utbetales fordi personen ikke har vært på arbeid etter maksdato"
}
}
@Test
fun `avviser perioder med sammenhengende sykdom etter 26 uker fra maksdato`() {
var forrigePeriode = 1.januar til 31.januar
nyttVedtak(forrigePeriode.start, forrigePeriode.endInclusive, 100.prosent)
// setter opp vedtaksperioder frem til 182 dager etter maksdato
repeat(17) { _ ->
forrigePeriode = nestePeriode(forrigePeriode)
forlengVedtak(forrigePeriode.start, forrigePeriode.endInclusive)
}
// oppretter forlengelse fom 182 dager etter maksdato
forrigePeriode = nyPeriodeMedYtelser(forrigePeriode)
val siste = observatør.sisteVedtaksperiode()
assertError("Bruker er fortsatt syk 26 uker etter maksdato", siste.filter())
assertSisteTilstand(siste, TilstandType.TIL_INFOTRYGD) {
"Disse periodene skal kastes ut pr nå"
}
}
private fun nyPeriode(forrigePeriode: Periode): Periode {
val nestePeriode = nestePeriode(forrigePeriode)
håndterSykmelding(Sykmeldingsperiode(nestePeriode.start, nestePeriode.endInclusive, 100.prosent))
val id: IdInnhenter = observatør.sisteVedtaksperiode()
håndterSøknadMedValidering(id, Søknad.Søknadsperiode.Sykdom(nestePeriode.start, nestePeriode.endInclusive, 100.prosent))
return nestePeriode
}
private fun nyPeriodeMedYtelser(forrigePeriode: Periode): Periode {
val nestePeriode = nyPeriode(forrigePeriode)
val id: IdInnhenter = observatør.sisteVedtaksperiode()
håndterYtelser(id)
return nestePeriode
}
private fun nestePeriode(forrigePeriode: Periode): Periode {
val nesteMåned = forrigePeriode.start.plusMonths(1)
return nesteMåned til nesteMåned.plusDays(nesteMåned.lengthOfMonth().toLong() - 1)
}
}
| 0 | Kotlin | 2 | 4 | a3ba622f138449986fc9fd44e467104a61b95577 | 3,528 | helse-spleis | MIT License |
plugins/grazie/src/main/kotlin/com/intellij/grazie/text/TextContentModificationTrackerProvider.kt | JetBrains | 2,489,216 | false | null | package com.intellij.grazie.text
import com.intellij.lang.LanguageExtension
import com.intellij.openapi.util.ModificationTracker
import com.intellij.psi.PsiElement
interface TextContentModificationTrackerProvider {
companion object {
@JvmField
val EP_NAME: LanguageExtension<TextContentModificationTrackerProvider> = LanguageExtension("com.intellij.grazie.textContentModificationTrackerProvider")
}
fun getModificationTracker(psiElement: PsiElement): ModificationTracker?
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 490 | intellij-community | Apache License 2.0 |
src/test/kotlin/testing/MinimalRequiredCodeTest.kt | JLLeitschuh | 127,962,882 | false | null | package testing
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
class MinimalRequiredCodeTest {
@Test
fun simpleExampleCase() {
val listOfElements = 0..100
assertAll(listOfElements.map { _ ->
{
// This line is really important even though it does nothing.
listOfElements
assertEquals("wonderful", "wonderful") {
// Its very important that this lambda not use any externally scoped variables
"Should have worked"
}
}
})
}
} | 0 | Kotlin | 0 | 0 | 4d592631e3cabeca57f3d0c3e1962a8757630804 | 667 | gradle-classloading-test-bug | MIT License |
app/src/main/java/com/misit/faceidchecklogptabp/Response/PresentasiPenggunaResponse.kt | borisreyson | 354,711,920 | false | null | package com.misit.faceidchecklogptabp.Response
import com.google.gson.annotations.SerializedName
data class PresentasiPenggunaResponse(
@field:SerializedName("persentasi")
val persentasi: Double? = null,
@field:SerializedName("jumlah_karyawan")
val jumlah_karyawan: Int? = null,
@field:SerializedName("jumlah_pengguna")
val jumlah_pengguna: Int? = null
) | 0 | Kotlin | 0 | 0 | 2a0b507559cfeddd3bff624f447ce088d334d85a | 364 | FaceIdChecklogPTABP | MIT License |
kool-editor/src/commonMain/kotlin/de/fabmax/kool/editor/ui/MaterialBrowser.kt | kool-engine | 81,503,047 | false | {"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597} | package de.fabmax.kool.editor.ui
import de.fabmax.kool.KoolSystem
import de.fabmax.kool.editor.actions.DeleteMaterialAction
import de.fabmax.kool.editor.api.EditorScene
import de.fabmax.kool.editor.components.MaterialComponent
import de.fabmax.kool.editor.util.ThumbnailRenderer
import de.fabmax.kool.editor.util.ThumbnailState
import de.fabmax.kool.editor.util.materialThumbnail
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.modules.ui2.PointerEvent
import de.fabmax.kool.modules.ui2.UiScope
import de.fabmax.kool.modules.ui2.isLeftClick
import de.fabmax.kool.modules.ui2.isRightClick
import de.fabmax.kool.scene.Lighting
import kotlin.math.roundToInt
class MaterialBrowser(ui: EditorUi) : BrowserPanel("Material Browser", Icons.medium.palette, ui) {
private val thumbnailRenderer = ThumbnailRenderer("material-thumbnails")
private val materialThumbnails = BrowserThumbnails<MaterialComponent>(thumbnailRenderer) { thumbnailRenderer.materialThumbnail(it) }
private var prevActiveScene: EditorScene? = null
init {
KoolSystem.requireContext().backgroundPasses += thumbnailRenderer
thumbnailRenderer.lighting = Lighting().apply {
singleDirectionalLight { setup(Vec3f(-1f, -1f, -1f)) }
}
ui.editor.projectModel.listenerComponents += MaterialComponent.ListenerComponent { component, _ ->
materialThumbnails.getThumbnail(component)?.state?.set(ThumbnailState.USABLE_OUTDATED)
}
}
context(UiScope)
override fun titleBar() {
super.titleBar()
thumbnailRenderer.updateTileSize(sizes.browserItemSize.px.roundToInt())
if (ui.editor.activeScene.use() != prevActiveScene) {
prevActiveScene = ui.editor.activeScene.value
materialThumbnails.loadedThumbnails.values.forEach { it.thumbnail?.state?.set(ThumbnailState.USABLE_OUTDATED) }
}
}
override fun UiScope.collectBrowserDirs(traversedPaths: MutableSet<String>) {
val materialDir = browserItems.getOrPut("/materials") {
BrowserDir(0, "Materials", "/materials")
} as BrowserDir
expandedDirTree += materialDir
traversedPaths += "/materials"
materialDir.children.clear()
editor.projectModel.materials.use()
.filter { it.gameEntity.isVisible }
.forEach { material ->
material.dataState.use()
val materialItem = browserItems.getOrPut("/materials/${material.name}") {
BrowserMaterialItem(1, material).apply {
composable = materialThumbnails.getThumbnailComposable(material)
}
}
materialDir.children += materialItem
traversedPaths += materialItem.path
}
}
override fun onItemClick(item: BrowserItem, ev: PointerEvent): SubMenuItem<BrowserItem>? {
val material = item as? BrowserMaterialItem
return when {
material != null && ev.isLeftClick -> {
ui.editor.selectionOverlay.setSelection(listOf(material.material.gameEntity))
null
}
material != null && ev.isRightClick -> {
SubMenuItem {
item("Delete material") {
OkCancelTextDialog("Delete Material", "Delete material \"${item.name}\"?") {
DeleteMaterialAction(item.material).apply()
}
}
}
}
else -> super.onItemClick(item, ev)
}
}
} | 11 | Kotlin | 20 | 303 | 8d05acd3e72ff2fc115d0939bf021a5f421469a5 | 3,603 | kool | Apache License 2.0 |
analysis/analysis-api/testData/references/isReferenceTo/topLevelFunctionCall.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} | // FILE: DeclSite.kt
fun calculateX() = 0
// FILE: UseSite.kt
fun test() {
<caret>calculateX()
} | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 103 | kotlin | Apache License 2.0 |
domain/src/main/kotlin/com/example/domain/submitProposal2/proposeTip/ProposeTip.kt | upelsin | 133,687,964 | false | null | package com.example.domain.submitProposal2.proposeTip
import com.example.domain.UiCommand
import com.example.domain.UiDataCommand
import com.example.domain.UiResult
import com.example.domain.UiState
import com.example.domain.framework.ExtraCommandsComponent
import com.example.domain.framework.Memoizable
import com.example.domain.models.ItemOpportunity
import com.example.domain.submitProposal2.fees.FeesCalculator
import com.example.domain.submitProposal2.proposeTip.ProposeTip.*
class ProposeTip : ExtraCommandsComponent<Command, Result, ViewState>() {
sealed class Command : UiCommand {
data class START(val itemOpportunity: ItemOpportunity) : Command(), UiDataCommand
object ForceRecalculateTotal : Command()
data class UpdateTip(val tip: Int) : Command()
}
sealed class Result : UiResult {
data class ItemGreetingLoaded(val message: String) : Result()
data class TipValid(val tip: Int) : Result()
object TipNotEntered : Result()
data class TipRangeExceeded(val tip: Int, val min: Int, val max: Int) : Result()
data class TotalCalculated(val total: Int) : Result()
object TotalCleared : Result()
data class FeeCalculatorLoaded(val feeCalculator: FeesCalculator) : Result(), Memoizable
}
data class ViewState(
val itemGreeting: String = "",
val tip: String = "",
val isTipRangeError: Boolean = false,
val minTip: Int = 0,
val maxTip: Int = 0,
val total: String = "",
val isTotalCalculationPending: Boolean = true
) : UiState
override val processor = ProposeTipProcessor()
override val reducer = ProposeTipReducer()
}
| 0 | Kotlin | 0 | 0 | 94462f1294059f8078c0f6e34caabc3c2eadd44d | 1,729 | true-clean-architecture | Apache License 2.0 |
shared/src/commonMain/kotlin/ui/utils/Styles.kt | alexmaryin | 419,989,861 | false | {"Kotlin": 169549} | package ui.utils
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
@Composable
fun LargeWithShadow(multi: Int = 1) = LocalTextStyle.current.copy(
fontSize = 20.sp,
fontWeight = FontWeight.Normal,
shadow = Shadow(color = Color.DarkGray, offset = Offset(2f * multi, 2f * multi), blurRadius = 2f * multi),
color = MaterialTheme.colors.onSurface
)
| 2 | Kotlin | 1 | 5 | 8a2fe1ee7b5d4b6dc4af0973a24c189b3fd4e8c2 | 662 | sims_checklist | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2020/Day04.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /*
* Copyright (c) 2021 by Charles Anderson
*/
package co.csadev.advent2020
class Day04(input: String) {
private val passports: List<String> = input.split("\n\n")
fun solvePart1(): Int =
passports
.count { passport -> expectedFields.all { passport.contains(it) } }
fun solvePart2(): Int =
passports
.count { passport -> fieldPatterns.all { it.containsMatchIn(passport) } }
companion object {
private val expectedFields = listOf("byr:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:", "pid:")
private val fieldPatterns = listOf(
"""\bbyr:(19[2-9][0-9]|200[0-2])\b""",
"""\biyr:(201[0-9]|2020)\b""",
"""\beyr:(202[0-9]|2030)\b""",
"""\bhgt:((1([5-8][0-9]|9[0-3])cm)|((59|6[0-9]|7[0-6])in))\b""",
"""\bhcl:#[0-9a-f]{6}\b""",
"""\becl:(amb|blu|brn|gry|grn|hzl|oth)\b""",
"""\bpid:[0-9]{9}\b"""
).map { it.toRegex() }
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 986 | advent-of-kotlin | Apache License 2.0 |
src/test/kotlin/com/myapp/controller/MicropostControllerTest.kt | springboot-angular2-tutorial | 46,042,914 | false | null | package com.myapp.controller
import com.myapp.service.MicropostService
import com.myapp.service.exception.NotAuthorizedException
import com.myapp.testing.TestMicropost
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.doThrow
import com.nhaarman.mockito_kotlin.verify
import org.hamcrest.CoreMatchers.`is`
import org.junit.Test
import org.mockito.Mockito.`when`
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@WebMvcTest(MicropostController::class)
class MicropostControllerTest : BaseControllerTest() {
@MockBean
lateinit private var micropostService: MicropostService
@Test
fun `create should create a post`() {
signIn()
`when`(micropostService.create("my content"))
.doReturn(TestMicropost.copy(_id = 1, content = "my content"))
val response = perform(post("/api/microposts")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString {
obj("content" to "my content")
})
)
verify(micropostService).create("my content")
with(response) {
andExpect(status().isOk)
andExpect(jsonPath("$.id", `is`(1)))
andExpect(jsonPath("$.content", `is`("my content")))
}
}
@Test
fun `create should not create a post when not signed in`() {
perform(post("/api/microposts")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonString {
obj("content" to "my content")
})
).apply {
andExpect(status().isUnauthorized)
}
}
@Test
fun `delete should delete a post`() {
signIn()
val response = perform(delete("/api/microposts/1"))
verify(micropostService).delete(1)
response.andExpect(status().isOk)
}
@Test
fun `delete should not delete a post when not signed in`() {
perform(delete("/api/microposts/1")).apply {
andExpect(status().isUnauthorized)
}
}
@Test
fun `delete should not delete a post which belongs to others`() {
signIn()
`when`(micropostService.delete(1)).doThrow(NotAuthorizedException(""))
perform(delete("/api/microposts/1")).apply {
andExpect(status().isForbidden)
}
}
} | 2 | Kotlin | 46 | 115 | c6daf1df3dcb06813bbeb9096e5a5672c58481a7 | 2,777 | boot-app | MIT License |
app/src/main/java/com/phil/airinkorea/viewmodel/AddLocationViewModel.kt | wonhaeseong | 574,473,916 | false | {"Kotlin": 198684} | package com.phil.airinkorea.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.phil.airinkorea.data.model.Location
import com.phil.airinkorea.data.repository.LocationRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
data class AddLocationUiState(
var searchResult: List<Location> = emptyList()
)
@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class AddLocationViewModel @Inject constructor(
private val locationRepository: LocationRepository
) : ViewModel() {
private val _searchText: MutableStateFlow<String> = MutableStateFlow("")
val addLocationUiState: StateFlow<AddLocationUiState> = _searchText.flatMapLatest { searchText ->
locationRepository.getSearchResult(searchText)
}.map { searchResult ->
AddLocationUiState(searchResult)
}.stateIn(
viewModelScope, started = SharingStarted.WhileSubscribed(5000),
initialValue = AddLocationUiState()
)
fun onSearchTextChange(text: String) {
_searchText.value = text
}
fun addUserLocation(location: Location) {
viewModelScope.launch(Dispatchers.IO) {
locationRepository.addUserLocation(location)
}
}
} | 2 | Kotlin | 0 | 1 | c6f204fffb3e9a35067bb8afdfacb63628a58453 | 1,438 | AirInKorea | Apache License 2.0 |
src/main/kotlin/no/nav/tilleggsstonader/sak/brev/GenererPdfRequest.kt | navikt | 685,490,225 | false | {"Kotlin": 1923144, "Gherkin": 41142, "HTML": 39787, "Shell": 924, "Dockerfile": 164} | package no.nav.tilleggsstonader.sak.brev
data class GenererPdfRequest(val html: String)
| 3 | Kotlin | 1 | 0 | 5ecc0dd26e0aa23330cc5053d0a37b899a4d87b3 | 89 | tilleggsstonader-sak | MIT License |
app/src/main/java/com/example/cz2006ver2/Account/ViewProfileActivity.kt | kombucha7 | 483,281,978 | false | null | package com.example.cz2006ver2.Account
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.cz2006ver2.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_login.back_button_word
import kotlinx.android.synthetic.main.activity_view_profile.*
/**
* This page allows users to check their profile details
*/
class ViewProfileActivity : AppCompatActivity() {
/**
* Default method used to go to view profile details
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_profile)
val elderUID = intent.getStringExtra("key").toString()
//set the user's name and email to show
val currentFirebaseUser =
FirebaseAuth.getInstance().currentUser
val userID = currentFirebaseUser!!.uid
val TAG = "myLogTag"
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("users").document(userID)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
user_name.text = document.get("name").toString()
user_email.text = document.get("email").toString()
Log.d(TAG, "Our data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
//back button to the landing page
back_button_word.setOnClickListener{
val intent = Intent(this, AccountMainActivity::class.java)
intent.putExtra("key", elderUID)
println("view profile pageID: " + elderUID)
startActivity(intent)
}
change_pw_btn.setOnClickListener{
val intent = Intent(this, ChangePasswordActivity::class.java)
intent.putExtra("key", elderUID)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | d7c8a87db3681a2cd7132968958479d3d56e6c1d | 2,273 | CZ2006 | Apache License 2.0 |
app/src/main/java/com/example/cz2006ver2/Account/ViewProfileActivity.kt | kombucha7 | 483,281,978 | false | null | package com.example.cz2006ver2.Account
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.cz2006ver2.R
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_login.back_button_word
import kotlinx.android.synthetic.main.activity_view_profile.*
/**
* This page allows users to check their profile details
*/
class ViewProfileActivity : AppCompatActivity() {
/**
* Default method used to go to view profile details
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_profile)
val elderUID = intent.getStringExtra("key").toString()
//set the user's name and email to show
val currentFirebaseUser =
FirebaseAuth.getInstance().currentUser
val userID = currentFirebaseUser!!.uid
val TAG = "myLogTag"
val db = FirebaseFirestore.getInstance()
val docRef = db.collection("users").document(userID)
docRef.get()
.addOnSuccessListener { document ->
if (document != null) {
user_name.text = document.get("name").toString()
user_email.text = document.get("email").toString()
Log.d(TAG, "Our data: ${document.data}")
} else {
Log.d(TAG, "No such document")
}
}
.addOnFailureListener { exception ->
Log.d(TAG, "get failed with ", exception)
}
//back button to the landing page
back_button_word.setOnClickListener{
val intent = Intent(this, AccountMainActivity::class.java)
intent.putExtra("key", elderUID)
println("view profile pageID: " + elderUID)
startActivity(intent)
}
change_pw_btn.setOnClickListener{
val intent = Intent(this, ChangePasswordActivity::class.java)
intent.putExtra("key", elderUID)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | d7c8a87db3681a2cd7132968958479d3d56e6c1d | 2,273 | CZ2006 | Apache License 2.0 |
app/src/main/java/com/items/bim/entity/McRecordEntity.kt | losebai | 800,799,665 | false | {"Kotlin": 607587, "Java": 11455} | package com.items.bim.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "mc_record")
data class McRecordEntity(
@PrimaryKey(autoGenerate=true)
var id: Long = 0,
var cardPoolType: String = "",
var resourceId: Int = 0,
var qualityLevel: Int = 0,
var resourceType: String = "",
var name: String = "",
var count: Int = 0,
var time: String = "",
) | 0 | Kotlin | 0 | 0 | 135149f704d5d3b93ed2baabf3d88fc5eaa33244 | 418 | B-Im | Apache License 2.0 |
app/src/main/java/io/zoemeow/dutschedule/util/AppUtils.kt | ZoeMeow1027 | 504,228,485 | false | {"Kotlin": 268719} | package io.zoemeow.dutschedule.util
import java.math.BigInteger
import java.security.MessageDigest
class AppUtils {
companion object {
// https://stackoverflow.com/a/64171625
fun getMD5(input: String): String {
val md = MessageDigest.getInstance("MD5")
return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
}
fun calcMD5CharValue(input: String): Int {
var result = 0
val byteArray = input.toByteArray()
byteArray.forEach {
result += (it * 5)
}
return result
}
}
} | 0 | Kotlin | 0 | 1 | 72a4e1a7d63b496fef3b0420af15133826d5865b | 646 | DutSchedule | MIT License |
krossbow-websocket-core/src/commonMain/kotlin/org/hildan/krossbow/websocket/reconnection/RetryDelayStrategy.kt | joffrey-bion | 190,066,229 | false | null | package org.hildan.krossbow.websocket.reconnection
import kotlin.math.pow
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
/**
* Defines the time to wait before each attempt in a retry mechanism.
*/
interface RetryDelayStrategy {
/**
* Calculates the time to wait before the given [attempt].
*
* The first attempt has number 0, the next one is 1, etc.
*/
fun computeDelay(attempt: Int): Duration
}
/**
* A [RetryDelayStrategy] where the delay is the same for all attempts.
*/
class FixedDelay(private val delay: Duration): RetryDelayStrategy {
override fun computeDelay(attempt: Int): Duration = delay
}
/**
* A [RetryDelayStrategy] where the delay is multiplied by a constant factor after each attempt.
*/
class ExponentialBackOff(
/**
* The time to wait before the first attempt.
*/
private val initialDelay: Duration = 1.seconds,
/**
* The multiplier to use to increase the delay for subsequent attempts.
*/
private val factor: Double = 2.0,
): RetryDelayStrategy {
override fun computeDelay(attempt: Int): Duration = initialDelay * factor.pow(attempt)
}
| 12 | Kotlin | 7 | 82 | e72a8d8254399e439c454b2d0a689011c297b22e | 1,168 | krossbow | MIT License |
app/src/main/java/fingerfire/com/overwatch/features/maps/ui/viewstate/MapsViewState.kt | marlonsantini | 595,391,286 | false | null | package fingerfire.com.overwatch.features.maps.ui.viewstate
import fingerfire.com.overwatch.features.maps.data.response.MapsDataResponse
data class MapsViewState(val sucess: List<MapsDataResponse>? = null, val failure: Boolean = false) | 0 | Kotlin | 0 | 2 | 34e7026565fd689cac549f493369fc9ff80c201e | 237 | OverGuide | Apache License 2.0 |
data/src/test/java/com/example/data/repository/RepositoryImpTest.kt | Ahabdelhak | 535,852,545 | false | {"Kotlin": 134308} | /*
* Copyright 2022 <NAME>. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.repository
import androidx.test.filters.SmallTest
import app.cash.turbine.test
import com.example.common.Resource
import com.example.data.util.TestDataGenerator
import com.example.domain.repository.Repository
import com.google.common.truth.Truth
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import kotlin.time.ExperimentalTime
@ExperimentalTime
@ExperimentalCoroutinesApi
@SmallTest
class RepositoryImpTest {
@MockK
private lateinit var remoteDataSource: RemoteDataSource
private lateinit var repository: Repository
@Before
fun setUp() {
MockKAnnotations.init(this, relaxUnitFun = true) // turn relaxUnitFun on for all mocks
// Create RepositoryImp before every test
repository = RepositoryImp(
remoteDataSource = remoteDataSource
)
}
@Test
fun test_getCoinList_success() = runBlockingTest {
val coinList = TestDataGenerator.generateCoinListResponse()
// Given
coEvery { remoteDataSource.getCoinList() } returns coinList
// When & Assertions
val flow = repository.getCoinList()
flow.test {
// Expect Resource.Success
val expected = expectItem()
val expectedData = (expected as Resource.Success).data
Truth.assertThat(expected).isInstanceOf(Resource.Success::class.java)
Truth.assertThat(coinList).isEqualTo(coinList)
expectComplete()
}
// Then
coVerify { remoteDataSource.getCoinList() }
}
@Test
fun test_getCoinList_fail() = runBlockingTest {
// Given
coEvery { remoteDataSource.getCoinList() } throws Exception("Error")
// When && Assertions
val flow = repository.getCoinList()
flow.test {
// Expect Resource.Success
val expected = expectItem()
val expectedData = (expected as Resource.Error).message
Truth.assertThat(expected).isInstanceOf(Resource.Error::class.java)
Truth.assertThat(expectedData).isEqualTo("Error")
expectComplete()
}
// Then
coVerify { remoteDataSource.getCoinList() }
}
@Test
fun test_getCoinDetails_success() = runBlockingTest {
val coinDetails = TestDataGenerator.generateCoinDetailsResponse()
// Given
coEvery { remoteDataSource.getCoinDetails("1") } returns coinDetails
// When & Assertions
val flow = repository.getCoinDetails("1")
flow.test {
// Expect Resource.Success
val expected = expectItem()
val expectedData = (expected as Resource.Success).data
Truth.assertThat(expected).isInstanceOf(Resource.Success::class.java)
Truth.assertThat(coinDetails.id).isEqualTo(coinDetails.id)
expectComplete()
}
// Then
coVerify { remoteDataSource.getCoinDetails("1") }
}
@Test
fun test_getCoinDetails_fail() = runBlockingTest {
// Given
coEvery { remoteDataSource.getCoinDetails("1") } throws Exception("Error")
// When && Assertions
val flow = repository.getCoinDetails("1")
flow.test {
// Expect Resource.Success
val expected = expectItem()
val expectedData = (expected as Resource.Error).message
Truth.assertThat(expected).isInstanceOf(Resource.Error::class.java)
Truth.assertThat(expectedData).isEqualTo("Error")
expectComplete()
}
// Then
coVerify { remoteDataSource.getCoinDetails("1") }
}
} | 0 | Kotlin | 1 | 4 | 46a82e6c0c86b700f996a912547bf4f1fae70d82 | 4,493 | InstaCrypto | Apache License 2.0 |
compiler/src/main/java/tech/watanave/fulla/compiler/Compiler.kt | watanavex | 409,528,531 | false | null | package tech.watanave.fulla.compiler
import com.google.auto.common.BasicAnnotationProcessor
import com.google.auto.service.AutoService
import com.google.common.collect.SetMultimap
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asTypeName
import tech.watanave.fulla.annotation.State
import javax.annotation.processing.Filer
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.Processor
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import kotlin.reflect.jvm.internal.impl.builtins.jvm.JavaToKotlinClassMap
import kotlin.reflect.jvm.internal.impl.name.FqName
@AutoService(Processor::class)
class FullaProcessor: BasicAnnotationProcessor() {
override fun initSteps(): MutableIterable<ProcessingStep> {
return mutableListOf(
FullaProcessorStep(processingEnv.filer, processingEnv)
)
}
}
class FullaProcessorStep(private val filer: Filer, private val processingEnvironment: ProcessingEnvironment) : BasicAnnotationProcessor.ProcessingStep {
override fun annotations(): MutableSet<out Class<out Annotation>> {
return mutableSetOf(State::class.java)
}
override fun process(elementsByAnnotation: SetMultimap<Class<out Annotation>, Element>?): MutableSet<Element> {
elementsByAnnotation ?: return mutableSetOf()
elementsByAnnotation[State::class.java].forEach(this::generateActionAndReducer)
return mutableSetOf()
}
private fun generateActionAndReducer(element: Element) {
val packageName = processingEnvironment.elementUtils.getPackageOf(element).qualifiedName.toString() +
"." + element.simpleName.toString().lowercase()
val actionClassName = "Action"
val actionClassBuilder = TypeSpec
.classBuilder(actionClassName)
.addModifiers(KModifier.SEALED)
val actionSubClasses = mutableListOf<TypeSpec>()
element.enclosedElements
.filter { it.kind == ElementKind.FIELD }
.forEach { field ->
val constructorSpec = FunSpec.constructorBuilder()
.addParameter("value", field.asType().asTypeName().javaToKotlinType())
.build()
TypeSpec
.classBuilder(field.simpleName.toString().toUpperCamel())
.superclass(ClassName(packageName, actionClassName))
.addModifiers(KModifier.DATA)
.primaryConstructor(constructorSpec)
.addProperty(
PropertySpec.builder("value", field.asType().asTypeName().javaToKotlinType())
.initializer("value")
.build()
)
.build()
.also {
actionClassBuilder.addType(it)
actionSubClasses.add(it)
}
}
FileSpec.builder(packageName, actionClassName)
.addType(actionClassBuilder.build())
.build()
.writeTo(filer)
////////////////////////////////////////////////////////////
val reducerFunSpec = FunSpec.builder("reducer")
//.receiver(viewModelElement.asType().asTypeName())
.addParameter("state", element.asType().asTypeName())
.addParameter("action", ClassName(packageName, actionClassName))
.returns(element.asType().asTypeName())
.addCode(
CodeBlock.of("""
return when (action) {
${actionSubClasses
.map { "is $actionClassName.${it.name} -> { state.copy(${it.name!!.toLowerCamel()} = action.value) }" }
.joinToString(separator = "\n ")}
}
""".trimIndent()))
.build()
val stateName = element.simpleName.toString()
FileSpec.builder(packageName, "${stateName}Reducer")
.addFunction(reducerFunSpec)
.build()
.writeTo(filer)
}
private fun String.toUpperCamel() : String {
val initial = this.first().uppercase()
return this.replaceFirst(initial, initial, true)
}
private fun String.toLowerCamel() : String {
val initial = this.first().lowercase()
return this.replaceFirst(initial, initial, true)
}
private fun TypeName.javaToKotlinType(): TypeName {
return if (this is ParameterizedTypeName) {
val converted = this.rawType.javaToKotlinType()
val typeArguments = this.typeArguments.map { it.javaToKotlinType() }
(converted as ClassName).parameterizedBy(*typeArguments.toTypedArray())
} else {
val className =
JavaToKotlinClassMap.INSTANCE.mapJavaToKotlin(FqName(toString()))
?.asSingleFqName()?.asString()
return if (className == null) {
this
} else {
ClassName.bestGuess(className)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 2011f162effbe8c31924704c82e6adb449939e80 | 5,505 | fulla-kotlin | Apache License 2.0 |
src/render/Mesh.kt | Capster | 707,893,823 | false | {"Kotlin": 178235, "HTML": 717} | package render
import engine.render.AttributeType
import engine.render.VertexArray
import engine.render.VertexAttribute
data class Mesh(
val positions: Array<Float>,
val normals: Array<Float>,
val uvs: Array<Float>,
val indices: Array<Short>,
val drawMode: DrawMode
) {
private val vertexArray = VertexArray(
listOf(
VertexAttribute(AttributeType.POSITION, positions),
VertexAttribute(AttributeType.NORMAL, normals),
VertexAttribute(AttributeType.UV, uvs)
),
indices,
drawMode
)
private val material = Material()
companion object {
fun fromGLTF() {}
}
fun render(dt: Double) {
material.bind()
vertexArray.render()
material.unbind()
}
} | 0 | Kotlin | 0 | 1 | bad9ee8f1d0a9cbc676fac6768784dbb147776a9 | 745 | kotlin-webgl | MIT License |
src/main/kotlin/xyz/capybara/clamav/commands/Shutdown.kt | stemount | 101,389,121 | true | {"Kotlin": 22887} | package xyz.capybara.clamav.commands
internal object Shutdown : Command<Unit>() {
override val commandString: String
get() = "SHUTDOWN"
override val format: Command.CommandFormat
get() = Command.CommandFormat.NULL_CHAR
override fun parseResponse(responseString: String): Unit = logger.info("Shutting down the ClamAV server")
}
| 0 | Kotlin | 0 | 0 | 873fc48fd76cc888359474be0b544281e027c867 | 358 | clamav-client | MIT License |
SpanishWords/app/src/main/java/com/am10/spanishwords/Category.kt | adventam10 | 360,829,695 | false | null | package com.am10.spanishwords
enum class Category constructor(val wordType: Int) {
NOUN(0),
ADJECTIVE(1),
VERB(2),
PREPOSITION(3),
ARTICLE(4),
PRONOUN(5),
NUMBER(6),
MONTHANDWEEK(7),
INTERROGATIVE(8),
ADVERB(9);
companion object {
fun fromWordType(wordType: Int): Category {
return values().firstOrNull { it.wordType == wordType } ?: NOUN
}
}
val nameId: Int
get() = when(this) {
NOUN -> R.string.category_noun
ADJECTIVE -> R.string.category_adjective
VERB -> R.string.category_verb
PREPOSITION -> R.string.category_preposition
ARTICLE -> R.string.category_article
PRONOUN -> R.string.category_pronoun
NUMBER -> R.string.category_number
MONTHANDWEEK -> R.string.category_month_and_week
INTERROGATIVE -> R.string.category_interrogative
ADVERB -> R.string.category_adverb
}
}
| 4 | Kotlin | 0 | 0 | f71fe79ceab459fb47838798d4bb72dff5d043ee | 993 | SpanishWords-android | MIT License |
Week2/src/model/caffe/Item.kt | mmoreno1992 | 268,140,332 | false | {"Text": 1, "Markdown": 1, "XML": 387, "Kotlin": 97, "Ignore List": 14, "Gradle": 15, "Java Properties": 14, "Shell": 5, "Batchfile": 5, "Proguard": 5, "JSON": 1, "INI": 4, "Java": 1} | package model.caffe
/**
* Class that serves as a line of a receipt
* @author Mario
*/
data class Item(val product: Product, var quantity: Int) {
override fun toString(): String {
return """
{
productId: ${product.id},
desc: ${product.name}
quantity: ${quantity}
normal price: ${product.price}
}
"""
}
} | 0 | Kotlin | 0 | 2 | afb5060e7b3cba5cc40e2a24b8497ef20a14d32e | 419 | RWBootcamp | MIT License |
app/src/main/kotlin/by/bulba/watch/elektronika/receiver/BatteryBroadcastReceiver.kt | IlyaPavlovskii | 574,673,596 | false | {"Kotlin": 88768, "Shell": 148} | package by.bulba.watch.elektronika.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.BatteryManager
import android.os.BatteryManager.BATTERY_STATUS_CHARGING
import android.os.BatteryManager.BATTERY_STATUS_UNKNOWN
import android.util.Log
import by.bulba.watch.elektronika.data.watchface.WatchFaceData
import by.bulba.watch.elektronika.repository.WatchFaceDataStateRepository
internal class BatteryBroadcastReceiver(
private val repository: WatchFaceDataStateRepository,
) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) ?: 0
val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, BATTERY_STATUS_UNKNOWN)
?: BATTERY_STATUS_UNKNOWN
repository.update { watchFaceData ->
val battery = watchFaceData.battery.copy(
level = WatchFaceData.Battery.Level(level.toUInt()),
state = when (status) {
BATTERY_STATUS_CHARGING -> WatchFaceData.Battery.State.CHARGING
else -> WatchFaceData.Battery.State.NOT_CHARGING
}
)
Log.d("Elektronika", "Battery: $battery")
watchFaceData.copy(battery = battery)
}
}
} | 10 | Kotlin | 0 | 6 | 0a5d61a538c18d3bb0444a40efaa0aae8216db5d | 1,367 | Elektronika | Apache License 2.0 |
src/main/kotlin/simulation/NodeDataCollector.kt | FAWC438 | 443,940,908 | false | {"Kotlin": 185867} | package simulation
import bgp.notifications.BGPNotifier
import bgp.notifications.ExportListener
import bgp.notifications.ExportNotification
import core.simulator.notifications.*
import io.NodeDataReporter
import java.io.File
import java.io.IOException
/**
*
* 节点数据收集器收集与拓扑中每个单独节点相关的数据。
*/
class NodeDataCollector(private val reporter: NodeDataReporter) :
DataCollector, StartListener, EndListener, ExportListener {
/**
* 创建一个将结果输出到指定输出文件的 Basic Reporter。
*/
constructor(outputFile: File) : this(NodeDataReporter(outputFile))
private val data = NodeDataSet()
/**
* 将收集器添加为收集器需要侦听以收集数据的通知的侦听器。
*/
override fun register() {
Notifier.addStartListener(this)
Notifier.addEndListener(this)
BGPNotifier.addExportListener(this)
}
/**
* 从所有通知器中删除收集器
*/
override fun unregister() {
Notifier.removeStartListener(this)
Notifier.removeEndListener(this)
BGPNotifier.removeExportListener(this)
}
/**
* 报告当前收集的数据。
*
* @throws IOException 如果发生 IO 错误
*/
@Throws(IOException::class)
override fun report() {
reporter.report(data)
}
/**
* 清除所有收集的数据。
*/
override fun clear() {
data.clear()
}
/**
* 调用以通知侦听器新的开始通知。
*/
override fun onStart(notification: StartNotification) {
// 确保所有节点都以终止时间为 0 开始。
// 这也确保所有节点都包含在终止时间映射中。
// 为什么需要这样做?
// 可能会出现某些节点从不导出路由的情况。如果是这种情况,那么这些节点将不会包含在终止时间映射中。
for (node in notification.topology.nodes)
data.terminationTimes[node.id] = 0
}
/**
* 调用以通知侦听器新的导出通知。
*/
override fun onExport(notification: ExportNotification) {
// 更新导出新路由的节点的终止时间
data.terminationTimes[notification.node.id] = notification.time
}
/**
* 调用以通知侦听器新的结束通知。
*/
override fun onEnd(notification: EndNotification) {
for (node in notification.topology.nodes)
data.selectedRoutes[node.id] = node.protocol.selectedRoute
}
} | 0 | Kotlin | 0 | 3 | 8a1f75ee37535ba87d98c3e0fe93d79e5fb83c38 | 2,050 | BGP-ASPA | MIT License |
core/session-front/impl/src/commonMain/kotlin/ru/kyamshanov/mission/session_front/impl/domain/usecase/IdentifyUserUseCase.kt | KYamshanov | 656,042,097 | false | {"Kotlin": 339079, "Batchfile": 2703, "HTML": 199, "Dockerfile": 195} | package ru.kyamshanov.mission.session_front.impl.domain.usecase
import ru.kyamshanov.mission.session_front.api.model.Token
internal interface IdentifyUserUseCase {
suspend fun identify(): Result<Token>
} | 7 | Kotlin | 0 | 1 | af1de2e2976c467c8ca3d614bb369ba933167995 | 210 | Mission-app | Apache License 2.0 |
src/main/java/com/dzen/campfire/api/requests/project/RProjectStatistic.kt | ZeonXX | 381,983,751 | false | {"Kotlin": 1087578} | package com.dzen.campfire.api.requests.project
import com.dzen.campfire.api.tools.client.Request
import com.sup.dev.java.libs.json.Json
open class RProjectStatistic : Request<RProjectStatistic.Response>() {
init {
cashAvailable = false
}
override fun jsonSub(inp: Boolean, json: Json) {
}
override fun instanceResponse(json: Json): Response {
return Response(json)
}
class Response : Request.Response {
var accounts:Array<Long> = emptyArray()
var posts:Array<Long> = emptyArray()
var comments:Array<Long> = emptyArray()
var messages:Array<Long> = emptyArray()
var enters:Array<Long> = emptyArray()
var rates:Array<Long> = emptyArray()
constructor(json: Json) {
json(false, json)
}
constructor(accounts:Array<Long>,
posts:Array<Long>,
comments:Array<Long>,
messages:Array<Long>,
enters:Array<Long>,
rates:Array<Long>
) {
this.accounts = accounts
this.posts = posts
this.comments = comments
this.messages = messages
this.enters = enters
this.rates = rates
}
override fun json(inp: Boolean, json: Json) {
this.accounts = json.m(inp, "accounts", accounts)
this.posts = json.m(inp, "posts", posts)
this.comments = json.m(inp, "comments", comments)
this.messages = json.m(inp, "messages", messages)
this.enters = json.m(inp, "enters", enters)
this.rates = json.m(inp, "rates", rates)
}
}
} | 0 | Kotlin | 2 | 5 | 6f3b371624fb66a065bcbaa6302830c574c55e9f | 1,706 | CampfireApi | Apache License 2.0 |
ontrack-extension-scm/src/main/java/net/nemerosa/ontrack/extension/scm/graphql/ShareSCMFileChangeFilterInput.kt | nemerosa | 19,351,480 | false | null | package net.nemerosa.ontrack.extension.scm.graphql
import net.nemerosa.ontrack.graphql.support.ListRef
import net.nemerosa.ontrack.model.annotations.APIDescription
@APIDescription("File change filter to share/edit in a project")
data class ShareSCMFileChangeFilterInput(
@APIDescription("ID of the project")
val projectId: Int,
@APIDescription("Name of the filter")
val name: String,
@APIDescription("List of patterns")
@ListRef
val patterns: List<String>,
)
| 57 | null | 27 | 97 | 7c71a3047401e088ba0c6d43aa3a96422024857f | 489 | ontrack | MIT License |
src/main/kotlin/com/carbontower/domain/entities/database/T_PLAYER_IN_TEAM.kt | KhomDrake | 179,989,126 | false | null | package com.carbontower.domain.entities.database
import org.jetbrains.exposed.sql.Table
object T_PLAYER_IN_TEAM : Table() {
val idPlayer_fk = integer("idPlayer_fk").primaryKey(0) references T_USER_ROLE.idUserRole
val idTeam_fk = integer("idTeam_fk").primaryKey(1) references T_TEAM.idTeam
init {
index(true,
idPlayer_fk,
idTeam_fk
)
}
} | 0 | Kotlin | 0 | 0 | bcb237c4d086702a5e018c0f49402c2d1706e939 | 394 | CarbonTower-Backend-Kotlin | MIT License |
src/jsMain/kotlin/core/ErrorUi.kt | theapache64 | 674,853,366 | false | {"Kotlin": 107952, "HTML": 4186} | package core
data class ErrorUi(
val title : String,
val stacktrace : String? = null
) | 2 | Kotlin | 0 | 42 | 29372e77c277bb0954a7040888d805e68fd3c9fb | 95 | diffetto | Apache License 2.0 |
graph/adapter-output-spring-data-neo4j-ogm/src/main/kotlin/eu/tib/orkg/prototype/statements/adapter/output/neo4j/spring/internal/Neo4jComparisonRepository.kt | TIBHannover | 197,416,205 | false | null | package eu.tib.orkg.prototype.statements.adapter.output.neo4j.spring.internal
import eu.tib.orkg.prototype.statements.domain.model.ResourceId
import java.util.Optional
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.neo4j.annotation.Query
import org.springframework.data.neo4j.repository.Neo4jRepository
private const val id = "${'$'}id"
/**
* Partial query that returns the node as well as its ID and relationships.
* Queries using this partial query must use `node` as the binding name.
*/
private const val RETURN_NODE =
"""RETURN node, [ [ (node)<-[r_r1:`RELATED`]-(r1:`Resource`) | [ r_r1, r1 ] ], [ (node)-[r_r1:`RELATED`]->(r1:`Resource`) | [ r_r1, r1 ] ] ], ID(node)"""
/**
* Partial query that returns the node count for use in count queries.
* Queries using this partial query must use `node` as the binding name.
*/
private const val RETURN_NODE_COUNT = """RETURN count(node)"""
/**
* Partial query that expands the node properties so that they can be used with pagination in custom queries.
* Queries using this partial query must use `node` as the binding name.
*/
private const val WITH_NODE_PROPERTIES =
"""WITH node, node.label AS label, node.resource_id AS id, node.created_at AS created_at"""
private const val MATCH_FEATURED_COMPARISON =
"""MATCH (node) WHERE EXISTS(node.featured) AND node.featured = true AND ANY(collectionFields IN ['Comparison'] WHERE collectionFields IN LABELS(node))"""
private const val MATCH_NONFEATURED_COMPARISON =
"""MATCH (node) WHERE (NOT EXISTS(node.featured) OR node.featured = false) AND ANY(collectionFields IN ['Comparison'] WHERE collectionFields IN LABELS(node))"""
private const val MATCH_UNLISTED_COMPARISON =
"""MATCH (node) WHERE EXISTS(node.unlisted) AND node.unlisted = true AND ANY(collectionFields IN ['Comparison'] WHERE collectionFields IN LABELS(node))"""
private const val MATCH_LISTED_COMPARISON =
"""MATCH (node) WHERE (NOT EXISTS(node.unlisted) OR node.unlisted = false) AND ANY(collectionFields IN ['Comparison'] WHERE collectionFields IN LABELS(node))"""
private const val MATCH_COMPARISON_BY_ID = """MATCH (node:`Resource`:`Comparison` {resource_id: $id})"""
interface Neo4jComparisonRepository :
Neo4jRepository<Neo4jResource, Long> {
@Query("""$MATCH_COMPARISON_BY_ID $WITH_NODE_PROPERTIES $RETURN_NODE""")
fun findComparisonByResourceId(id: ResourceId): Optional<Neo4jResource>
@Query(
value = """$MATCH_FEATURED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE""",
countQuery = """$MATCH_FEATURED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE_COUNT"""
)
fun findAllFeaturedComparisons(pageable: Pageable): Page<Neo4jResource>
@Query(
value = """$MATCH_NONFEATURED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE""",
countQuery = """$MATCH_NONFEATURED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE_COUNT"""
)
fun findAllNonFeaturedComparisons(pageable: Pageable): Page<Neo4jResource>
@Query(
value = """$MATCH_UNLISTED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE""",
countQuery = """$MATCH_UNLISTED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE_COUNT"""
)
fun findAllUnlistedComparisons(pageable: Pageable): Page<Neo4jResource>
@Query(
value = """$MATCH_LISTED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE""",
countQuery = """$MATCH_LISTED_COMPARISON $WITH_NODE_PROPERTIES $RETURN_NODE_COUNT"""
)
fun findAllListedComparisons(pageable: Pageable): Page<Neo4jResource>
}
| 0 | Kotlin | 1 | 4 | 84e17adb51e35e7123e1d853d49ae1d8ea95d400 | 3,593 | orkg-backend | MIT License |
montior-web/src/main/java/com/jay/montior/webapp/Tags.kt | jaycarey | 46,915,158 | false | null | package com.jay.montior.webapp
class Tags {
companion object {
private val NotThin = "[^iIl1\\.,']"
@JvmStatic fun ellipsis(text: String, max: Int): String {
if (textWidth(text) <= max) return text
var end = text.lastIndexOf(' ', max - 3)
if (end == -1) return text.substring(0, max - 3) + "..."
var newEnd = end
do {
end = newEnd
newEnd = text.indexOf(' ', end + 1)
if (newEnd == -1) newEnd = text.length
} while (textWidth(text.substring(0, newEnd) + "...") < max)
return text.substring(0, end) + "..."
}
private fun textWidth(str: String): Int {
return (str.length - str.replace(NotThin.toRegex(), "").length / 2).toInt()
}
}
} | 0 | Kotlin | 0 | 0 | 621228a8966361f483ab0500d75f83081f5673e1 | 826 | montior | Apache License 2.0 |
src/main/kotlin/in/rcard/assertj/arrowcore/errors/RaiseShouldSucceedButFailed.kt | rcardin | 602,952,402 | false | {"Kotlin": 70167} | package `in`.rcard.assertj.arrowcore.errors
import org.assertj.core.error.BasicErrorMessageFactory
private const val SHOULD_SUCCEED_BUT_FAILED_MESSAGE: String =
"%nExpecting the lambda to succeed but it failed with:%n <%s>"
/**
* Build error message when a lambda should succeed, but it fails with a logic error.
*
* @author Riccardo Cardin
* @since 1.0.0
*/
internal class RaiseShouldSucceedButFailed private constructor(
actualRaisedError: Any,
) : BasicErrorMessageFactory(SHOULD_SUCCEED_BUT_FAILED_MESSAGE, actualRaisedError) {
companion object {
internal fun shouldSucceedButFailed(actualRaisedError: Any): RaiseShouldSucceedButFailed =
RaiseShouldSucceedButFailed(actualRaisedError)
}
}
| 11 | Kotlin | 3 | 12 | 0c77d878a7532dfd0bf57a79630d767256083842 | 738 | assertj-arrow-core | Apache License 2.0 |
2743.Count Substrings Without Repeating Character.kt | sarvex | 842,260,390 | false | {"Kotlin": 1775678, "PowerShell": 418} | internal class Solution {
fun numberOfSpecialSubstrings(s: String): Int {
val n = s.length
var ans = 0
val cnt = IntArray(26)
var i = 0
var j = 0
while (i < n) {
val k: Int = s[i].code - 'a'.code
++cnt[k]
while (cnt[k] > 1) {
--cnt[s[j++].code - 'a'.code]
}
ans += i - j + 1
++i
}
return ans
}
}
| 0 | Kotlin | 0 | 0 | 71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48 | 376 | kotlin-leetcode | MIT License |
app/src/main/java/com/codewithmehdi/myofflinemap/MainActivity.kt | djnotes | 527,419,119 | false | {"Kotlin": 3523} | package com.codewithmehdi.myofflinemap
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.codewithmehdi.myofflinemap.databinding.ActivityMainBinding
import org.mapsforge.core.model.LatLong
import org.mapsforge.map.android.graphics.AndroidGraphicFactory
import org.mapsforge.map.android.util.AndroidUtil
import org.mapsforge.map.layer.renderer.TileRendererLayer
import org.mapsforge.map.reader.MapFile
import org.mapsforge.map.rendertheme.InternalRenderTheme
import java.io.FileInputStream
class MainActivity : AppCompatActivity() {
companion object{
val BERLIN = LatLong(52.5200, 13.4050)
val ALABAMA = LatLong(32.3182, 86.9023)
}
private lateinit var b: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidGraphicFactory.createInstance(application)
b = ActivityMainBinding.inflate(layoutInflater)
setContentView(b.root)
val contract = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
){result->
result?.data?.data?.let{uri->
openMap(uri)
}
}
b.openMap.setOnClickListener{
contract.launch(
Intent(
Intent.ACTION_OPEN_DOCUMENT
).apply{
type = "*/*"
addCategory(Intent.CATEGORY_OPENABLE)
}
)
}
}
fun openMap(uri: Uri){
b.map.mapScaleBar.isVisible = true
b.map.setBuiltInZoomControls(true)
val cache = AndroidUtil.createTileCache(
this,
"mycache",
b.map.model.displayModel.tileSize,
1f,
b.map.model.frameBufferModel.overdrawFactor
)
val stream = contentResolver.openInputStream(uri) as FileInputStream
val mapStore = MapFile(stream)
val renderLayer = TileRendererLayer(
cache,
mapStore,
b.map.model.mapViewPosition,
AndroidGraphicFactory.INSTANCE
)
renderLayer.setXmlRenderTheme(
InternalRenderTheme.DEFAULT
)
b.map.layerManager.layers.add(renderLayer)
b.map.setCenter(BERLIN)
b.map.setZoomLevel(10)
}
} | 0 | Kotlin | 3 | 2 | 98c199d87dcd96b1b139eb01aaadb0d15ead9046 | 2,482 | my-offline-map | Apache License 2.0 |
app/src/main/java/com/upsa/covidnews/model/WorldResponse.kt | NachoHAF | 384,684,672 | false | null | package com.upsa.covidnews.model
data class WorldResponse(
val cases : Int,
val deaths : Int,
val recovered : Int,
val active : Int,
val critical : Int
)
| 0 | Kotlin | 0 | 0 | c45f19e3f6cd99752dd465535d621b841928dff3 | 175 | CovidNews | Apache License 2.0 |
app/src/main/java/com/example/adoptpuppy/composables/Loader.kt | yrickwong | 352,576,787 | false | null | package com.example.adoptpuppy.composables
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieAnimationSpec
import com.example.adoptpuppy.R
@Composable
fun Loader(
modifier: Modifier = Modifier
) {
val animationSpec = remember { LottieAnimationSpec.RawRes(R.raw.loading) }
LottieAnimation(
animationSpec,
modifier = Modifier
.fillMaxSize()
.then(modifier)
)
} | 0 | Kotlin | 0 | 0 | d45e8b45537fe294468aa669483193346d0d165f | 711 | JetpackCompose-AdoptPuppy | MIT License |
cli/src/commonMain/me/strangepan/tasks/cli/feature/init/InitParser.kt | StrangePan | 231,948,379 | false | {"Kotlin": 385990, "Swift": 54126} | package me.strangepan.tasks.cli.feature.init
import me.strangepan.tasks.cli.parser.CommandParser
import omnia.cli.`in`.CommandLine
/** Command line argument parser for the Init command. */
class InitParser : CommandParser<InitArguments> {
override fun parse(commandLine: CommandLine): InitArguments {
return InitArguments()
}
} | 0 | Kotlin | 0 | 3 | 4c6989b4510853d4179210b93806372a460efb2a | 337 | tasks | The Unlicense |
data/src/main/java/appus/software/githubusers/data/executors/JobExecutor.kt | appus-studio | 180,989,176 | false | null | package appus.software.githubusers.data.executors
import appus.software.githubusers.domain.executor.ThreadExecutor
import io.reactivex.annotations.NonNull
import java.util.concurrent.*
class JobExecutor: ThreadExecutor {
private val threadPoolExecutor = ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS,
LinkedBlockingQueue<Any>() as BlockingQueue<Runnable>,
JobThreadFactory()
)
override fun execute(@NonNull runnable: Runnable) {
this.threadPoolExecutor.execute(runnable)
}
private class JobThreadFactory : ThreadFactory {
private var counter = 0
override fun newThread(@NonNull runnable: Runnable): Thread {
return Thread(runnable, "android_" + counter++)
}
}
}
| 0 | Kotlin | 0 | 1 | 72b630dbaffe7e2d6c08a81ac48d551f8578b627 | 759 | top-github-contributors-android | Apache License 2.0 |
src/main/java/Main.kt | Terenfear | 277,903,426 | false | null | import com.elbekD.bot.Bot
import com.elbekD.bot.http.await
import java.util.logging.Level
import java.util.logging.Logger
class Main {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val logger = Logger.getLogger("Main")
val bot = Bot.createPolling(args[0], args[1])
bot.onInlineQuery { inlineQuery ->
val text = inlineQuery.query
val results = DBWannabe.findByQuery(text).take(50)
try {
bot.answerInlineQuery(inlineQuery.id, results, cacheTime = 0).await()
} catch (e: Exception) {
logger.log(Level.SEVERE, "User input: $text", e)
}
}
bot.start()
}
}
} | 0 | Kotlin | 0 | 0 | 906ada39bc815b15cfe35d55e4dd67f10f2c8b46 | 782 | GachiSoundBot | The Unlicense |
app/src/main/java/de/maxisma/allaboutsamsung/youtube/YouTubeTrimTransformation.kt | amitkpandey | 132,310,335 | false | null | package de.maxisma.allaboutsamsung.youtube
import android.graphics.Bitmap
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest
import kotlin.math.roundToInt
/**
* The height of one black bar in the YouTube thumbnail
*/
private const val TRIM_MARGIN_PERCENT = 0.125
private const val ID = "YOUTUBE_TRIM_TRANSFORMATION"
/**
* YouTube returns thumbnails with black bars above and below the actual image.
* This [BitmapTransformation] removes them.
*/
class YouTubeTrimTransformation : BitmapTransformation() {
override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
val marginPx = (TRIM_MARGIN_PERCENT * toTransform.height).roundToInt()
return Bitmap.createBitmap(toTransform, 0, marginPx, toTransform.width, toTransform.height - 2 * marginPx)
}
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
messageDigest.update(ID.toByteArray())
}
} | 0 | Kotlin | 2 | 0 | c7f2680e3515439b605ead0ca764b6d5a81eaf11 | 1,061 | allaboutsamsung-android | MIT License |
sample/src/main/java/io/samagra/oce_sample/FormListAdapter.kt | jayesh212 | 668,156,153 | true | {"Java Properties": 6, "Gradle": 42, "Shell": 3, "Markdown": 24, "YAML": 3, "INI": 31, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 34, "Gradle Kotlin DSL": 1, "Kotlin": 607, "Text": 2, "XML": 545, "Java": 783, "JSON": 5, "HTML": 1, "JavaScript": 1, "Proguard": 5} | package io.samagra.oce_sample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import org.odk.collect.forms.Form
class FormListAdapter(private var forms: ArrayList<Form> = ArrayList()): RecyclerView.Adapter<FormListAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private lateinit var formId: TextView
private lateinit var displayName: TextView
fun bind(position: Int) {
formId = itemView.findViewById(R.id.form_id)
displayName = itemView.findViewById(R.id.form_display_name)
formId.text = forms[position].formId
displayName.text = forms[position].displayName
}
}
fun setData(forms: ArrayList<Form>) {
this.forms = forms
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return ViewHolder(layoutInflater.inflate(R.layout.form_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount(): Int {
return forms.size
}
} | 0 | Java | 0 | 1 | d707b7798b7e3420105a4d321cf331263d96344d | 1,358 | odk-collect-extension | Apache License 2.0 |
octicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/octicons/octicons/FiscalHost24.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.octicons.octicons
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 com.woowla.compose.icon.collections.octicons.Octicons
public val Octicons.FiscalHost24: ImageVector
get() {
if (_fiscalHost24 != null) {
return _fiscalHost24!!
}
_fiscalHost24 = Builder(name = "FiscalHost24", defaultWidth = 24.0.dp, defaultHeight =
24.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(2.0f, 3.75f)
curveTo(2.0f, 2.784f, 2.784f, 2.0f, 3.75f, 2.0f)
horizontalLineToRelative(16.5f)
curveToRelative(0.966f, 0.0f, 1.75f, 0.784f, 1.75f, 1.75f)
verticalLineToRelative(14.5f)
arcTo(1.75f, 1.75f, 0.0f, false, true, 20.25f, 20.0f)
lineTo(19.0f, 20.0f)
verticalLineToRelative(0.25f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
lineTo(17.0f, 20.0f)
lineTo(6.997f, 20.0f)
verticalLineToRelative(0.25f)
arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f)
lineTo(4.997f, 20.0f)
lineTo(3.75f, 20.0f)
arcTo(1.75f, 1.75f, 0.0f, false, true, 2.0f, 18.25f)
lineTo(2.0f, 3.75f)
close()
moveTo(3.75f, 3.5f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.25f, 0.25f)
verticalLineToRelative(14.5f)
curveToRelative(0.0f, 0.138f, 0.112f, 0.25f, 0.25f, 0.25f)
horizontalLineToRelative(16.5f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, 0.25f, -0.25f)
lineTo(20.5f, 3.75f)
arcToRelative(0.25f, 0.25f, 0.0f, false, false, -0.25f, -0.25f)
lineTo(3.75f, 3.5f)
close()
moveTo(14.318f, 12.0f)
arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, -2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.0f, 2.0f)
close()
moveTo(6.0f, 8.5f)
arcTo(0.75f, 0.75f, 0.0f, true, false, 6.0f, 10.0f)
horizontalLineToRelative(1.5f)
verticalLineToRelative(2.0f)
lineTo(6.0f, 12.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f)
horizontalLineToRelative(1.5f)
lineTo(7.5f, 15.0f)
arcTo(1.5f, 1.5f, 0.0f, false, false, 9.0f, 16.5f)
horizontalLineToRelative(8.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, false, 1.5f, -1.5f)
lineTo(18.5f, 7.0f)
arcTo(1.5f, 1.5f, 0.0f, false, false, 17.0f, 5.5f)
lineTo(9.0f, 5.5f)
arcTo(1.5f, 1.5f, 0.0f, false, false, 7.5f, 7.0f)
verticalLineToRelative(1.5f)
lineTo(6.0f, 8.5f)
close()
moveTo(9.0f, 10.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f)
lineTo(9.0f, 7.0f)
horizontalLineToRelative(8.0f)
verticalLineToRelative(8.0f)
lineTo(9.0f, 15.0f)
verticalLineToRelative(-1.5f)
arcTo(0.75f, 0.75f, 0.0f, false, false, 9.0f, 12.0f)
verticalLineToRelative(-2.0f)
close()
}
}
.build()
return _fiscalHost24!!
}
private var _fiscalHost24: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 4,270 | compose-icon-collections | MIT License |
core/src/main/java/com/ridhoafni/core/data/remote/response/ReviewResponse.kt | ridhoafnidev | 352,913,233 | false | null | package com.ridhoafni.core.data.remote.response
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import com.ridhoafni.core.data.local.entity.ReviewEntity
import kotlinx.parcelize.Parcelize
data class ReviewResponse (
@field:SerializedName("results")
var reviews: List<ReviewEntity>? = null
)
@Parcelize
data class DataReviews(
@field:SerializedName("id")
var id: String,
@field:SerializedName( "movie_id")
var movieId: Int,
@field:SerializedName("author")
val author: String,
@field:SerializedName("content")
val content: String,
@field:SerializedName("url")
val url: String
) : Parcelable | 0 | Kotlin | 0 | 1 | 1d22e7b85ce47a4bc034b8cf5e0760b18e44b4f9 | 675 | codeinmoviedb | Apache License 2.0 |
codebase/android/feature/home/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/home/home/viewmodel/HomeScreenUIStateDelegateImpl.kt | Abhimanyu14 | 429,663,688 | false | {"Kotlin": 1857337} | package com.makeappssimple.abhimanyu.financemanager.android.feature.home.home.viewmodel
import com.makeappssimple.abhimanyu.financemanager.android.core.common.datetime.DateTimeUtil
import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.toEpochMilli
import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.toZonedDateTime
import com.makeappssimple.abhimanyu.financemanager.android.core.navigation.Navigator
import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.listitem.transaction.TransactionListItemData
import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.overview_card.OverviewCardAction
import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.overview_card.OverviewCardViewModelData
import com.makeappssimple.abhimanyu.financemanager.android.core.ui.component.overview_card.OverviewTabOption
import com.makeappssimple.abhimanyu.financemanager.android.feature.home.home.bottomsheet.HomeScreenBottomSheetType
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import java.time.Instant
private object HomeScreenUIStateDelegateImplConstants {
const val DEFAULT_OVERVIEW_TAB_SELECTION = 1
}
internal class HomeScreenUIStateDelegateImpl(
private val dateTimeUtil: DateTimeUtil,
private val navigator: Navigator,
) : HomeScreenUIStateDelegate {
// region UI state
override val isLoading: MutableStateFlow<Boolean> = MutableStateFlow(
value = true,
)
override val isBalanceVisible: MutableStateFlow<Boolean> = MutableStateFlow(
value = false,
)
override val screenBottomSheetType: MutableStateFlow<HomeScreenBottomSheetType> =
MutableStateFlow(
value = HomeScreenBottomSheetType.None,
)
override val homeListItemViewData: MutableStateFlow<ImmutableList<TransactionListItemData>> =
MutableStateFlow(
value = persistentListOf(),
)
override val overviewTabSelectionIndex: MutableStateFlow<Int> = MutableStateFlow(
value = HomeScreenUIStateDelegateImplConstants.DEFAULT_OVERVIEW_TAB_SELECTION,
)
override val selectedTimestamp: MutableStateFlow<Long> = MutableStateFlow(
value = dateTimeUtil.getCurrentTimeMillis(),
)
override val overviewCardData: MutableStateFlow<OverviewCardViewModelData?> = MutableStateFlow(
value = null,
)
// endregion
// region loading
override fun startLoading() {
isLoading.update {
true
}
}
override fun completeLoading() {
isLoading.update {
false
}
}
override fun <T> withLoading(
block: () -> T,
): T {
startLoading()
val result = block()
completeLoading()
return result
}
override suspend fun <T> withLoadingSuspend(
block: suspend () -> T,
): T {
startLoading()
try {
return block()
} finally {
completeLoading()
}
}
// endregion
// region state events
override fun handleOverviewCardAction(
overviewCardAction: OverviewCardAction,
) {
val overviewTabOption = OverviewTabOption.entries[overviewTabSelectionIndex.value]
when (overviewCardAction) {
OverviewCardAction.NEXT -> {
when (overviewTabOption) {
OverviewTabOption.DAY -> {
selectedTimestamp.value = Instant.ofEpochMilli(selectedTimestamp.value)
.toZonedDateTime()
.plusDays(1)
.toEpochMilli()
}
OverviewTabOption.MONTH -> {
selectedTimestamp.value = Instant.ofEpochMilli(selectedTimestamp.value)
.toZonedDateTime()
.plusMonths(1)
.toEpochMilli()
}
OverviewTabOption.YEAR -> {
selectedTimestamp.value = Instant.ofEpochMilli(selectedTimestamp.value)
.toZonedDateTime()
.plusYears(1)
.toEpochMilli()
}
}
}
OverviewCardAction.PREV -> {
when (overviewTabOption) {
OverviewTabOption.DAY -> {
selectedTimestamp.value = Instant.ofEpochMilli(selectedTimestamp.value)
.toZonedDateTime()
.minusDays(1)
.toEpochMilli()
}
OverviewTabOption.MONTH -> {
selectedTimestamp.value = Instant.ofEpochMilli(selectedTimestamp.value)
.toZonedDateTime()
.minusMonths(1)
.toEpochMilli()
}
OverviewTabOption.YEAR -> {
selectedTimestamp.value = Instant.ofEpochMilli(selectedTimestamp.value)
.toZonedDateTime()
.minusYears(1)
.toEpochMilli()
}
}
}
}
}
override fun navigateToAccountsScreen() {
navigator.navigateToAccountsScreen()
}
override fun navigateToAddTransactionScreen() {
navigator.navigateToAddTransactionScreen()
}
override fun navigateToAnalysisScreen() {
navigator.navigateToAnalysisScreen()
}
override fun navigateToSettingsScreen() {
navigator.navigateToSettingsScreen()
}
override fun navigateToTransactionsScreen() {
navigator.navigateToTransactionsScreen()
}
override fun navigateToViewTransactionScreen(
transactionId: Int,
) {
navigator.navigateToViewTransactionScreen(
transactionId = transactionId,
)
}
override fun resetScreenBottomSheetType() {
setScreenBottomSheetType(
updatedHomeScreenBottomSheetType = HomeScreenBottomSheetType.None,
)
}
override fun setBalanceVisible(
updatedIsBalanceVisible: Boolean,
) {
isBalanceVisible.update {
updatedIsBalanceVisible
}
}
override fun setOverviewTabSelectionIndex(
updatedOverviewTabSelectionIndex: Int,
) {
overviewTabSelectionIndex.value = updatedOverviewTabSelectionIndex
}
override fun setScreenBottomSheetType(
updatedHomeScreenBottomSheetType: HomeScreenBottomSheetType,
) {
screenBottomSheetType.update {
updatedHomeScreenBottomSheetType
}
}
// endregion
}
| 12 | Kotlin | 0 | 3 | 96ea20306dc89bd18641b6cd4ca4e7e73e221705 | 6,981 | finance-manager | Apache License 2.0 |
samples/app/src/main/java/com/pingidentity/samples/app/centralize/Centralize.kt | ForgeRock | 830,216,912 | false | {"Kotlin": 452482} | /*
* Copyright (c) 2024. PingIdentity. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package com.pingidentity.samples.app.centralize
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.pingidentity.samples.app.json
import kotlinx.serialization.encodeToString
@Composable
fun Centralize(centralizeLoginViewModel: CentralizeLoginViewModel) {
val scroll = rememberScrollState(0)
LaunchedEffect(true) {
// Not relaunch when recomposition
centralizeLoginViewModel.login()
}
val state by centralizeLoginViewModel.state.collectAsState()
Column(
modifier =
Modifier
.fillMaxWidth(),
) {
Card(
elevation =
CardDefaults.cardElevation(
defaultElevation = 10.dp,
),
modifier =
Modifier
.weight(1f)
.fillMaxHeight()
.fillMaxWidth()
.padding(8.dp),
border = BorderStroke(2.dp, Color.Black),
shape = MaterialTheme.shapes.medium,
) {
Text(
modifier =
Modifier
.padding(4.dp)
.verticalScroll(scroll),
text =
state.token?.let {
json.encodeToString(it)
} ?: state.error?.toString() ?: "",
)
}
Row(
modifier =
Modifier
.padding(8.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.aligned(Alignment.End),
) {
Button(
modifier = Modifier.padding(4.dp),
onClick = { centralizeLoginViewModel.login() },
) {
Text(text = "AccessToken")
}
Button(
modifier = Modifier.padding(4.dp),
onClick = { centralizeLoginViewModel.reset() },
) {
Text(text = "Clear")
}
}
}
}
| 2 | Kotlin | 0 | 0 | cb75e4da916db337f5cf8f628a98f68dc9121063 | 3,102 | unified-sdk-android | MIT License |
app/src/main/java/github/sachin2dehury/owlmail/epoxy/controller/MailBoxController.kt | owlmail | 391,310,709 | false | null | package github.sachin2dehury.owlmail.epoxy.controller
import com.airbnb.epoxy.EpoxyModel
import github.sachin2dehury.owlmail.datamodel.Mail
import github.sachin2dehury.owlmail.epoxy.UiModel
import github.sachin2dehury.owlmail.epoxy.model.ItemMailModel
import kotlinx.coroutines.ObsoleteCoroutinesApi
@ObsoleteCoroutinesApi
class MailBoxController : BaseController<Mail>() {
override fun addItem(uiModel: UiModel.Item<Mail>): EpoxyModel<*> =
ItemMailModel(uiModel.value).id("mail_${uiModel.value.id}")
override fun addFooter(uiModel: UiModel.Footer): EpoxyModel<*> {
TODO("Not yet implemented")
}
} | 1 | Kotlin | 1 | 1 | 6b4415aafc8d7c3071b0d0e1f3a0cecbee867b12 | 629 | OwlMail-Legacy | Apache License 2.0 |
feature/dashboard/src/main/kotlin/com/naveenapps/expensemanager/feature/dashboard/CategoryAmountView.kt | nkuppan | 536,435,007 | false | null | package com.naveenapps.expensemanager.feature.dashboard
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.graphics.toColorInt
import com.naveenapps.expensemanager.core.designsystem.components.DashboardWidgetTitle
import com.naveenapps.expensemanager.core.designsystem.ui.components.PieChartUiData
import com.naveenapps.expensemanager.core.designsystem.ui.components.PieChartView
import com.naveenapps.expensemanager.core.designsystem.ui.theme.ExpenseManagerTheme
import com.naveenapps.expensemanager.core.model.CategoryTransactionState
import com.naveenapps.expensemanager.feature.category.transaction.CategoryTransactionSmallItem
import com.naveenapps.expensemanager.feature.category.transaction.getRandomCategoryTransactionData
@Composable
fun CategoryAmountView(
modifier: Modifier = Modifier,
categoryTransactionState: CategoryTransactionState,
) {
Column(modifier = modifier) {
DashboardWidgetTitle(
modifier = Modifier.fillMaxWidth(),
title = stringResource(id = R.string.categories),
)
Row(modifier = Modifier.padding(top = 16.dp)) {
PieChartView(
totalAmountText = categoryTransactionState.totalAmount.amountString ?: "",
chartData = categoryTransactionState.pieChartData.map {
PieChartUiData(
it.name,
it.value,
it.color.toColorInt(),
)
},
hideValues = true,
chartHeight = 300,
chartWidth = 300,
)
Column(
modifier = Modifier
.wrapContentHeight()
.padding(start = 16.dp)
.align(Alignment.CenterVertically),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
repeat(categoryTransactionState.categoryTransactions.size) {
if (it < 4) {
val item = categoryTransactionState.categoryTransactions[it]
CategoryTransactionSmallItem(
name = item.category.name,
icon = item.category.storedIcon.name,
iconBackgroundColor = item.category.storedIcon.backgroundColor,
amount = item.amount.amountString ?: "",
)
}
}
}
}
}
}
@com.naveenapps.expensemanager.core.designsystem.AppPreviewsLightAndDarkMode
@Composable
fun CategoryAmountViewPreview() {
ExpenseManagerTheme {
Surface {
CategoryAmountView(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
categoryTransactionState = getRandomCategoryTransactionData(),
)
}
}
}
| 4 | null | 15 | 94 | 5a5c790bea3f1ce4a720d7cffe6fe72a506507b7 | 3,454 | expensemanager | Apache License 2.0 |
app/src/main/java/com/items/bim/common/consts/AppAPI.kt | losebai | 800,799,665 | false | {"Kotlin": 618707, "Java": 7404} | package com.items.bim.common.consts
import android.os.Build.VERSION
import com.items.bim.BuildConfig
object AppAPI {
const val GET_USER: String = "/dispatch-app/appUser/"
const val GET_USER_BY_NUMBER: String = "/dispatch-app/appUser/gerUserByNumber"
const val POST_USER_SAVE: String = "/dispatch-app/appUser/save"
const val POST_USER_LIST: String = "/dispatch-app/appUser/list"
const val CONFIG_URI: String = "/dispatch-app/config/app-config-${BuildConfig.VERSION_NAME}.json"
object CommunityAPI{
const val GET_DYNAMIC: String = "/dispatch-app/appDynamic/"
const val GET_DYNAMIC_PAGE: String = "/dispatch-app/appDynamic/page"
const val GET_DYNAMIC_SAVE: String = "/dispatch-app/appDynamic/save"
}
object DictAPI{
const val GET_DICT_BY_KEYS: String = "/dispatch-app/dict/getDictByKeys"
}
object AppLotteryPoolAPI{
const val CURRENT_POOLS = "/dispatch-app/AppLotteryPool/currentPools"
const val RANDOM_AWARD = "/dispatch-app/AppLotteryAward/randomAppAward"
const val LOTTERY_AWARD_COUNT = "/dispatch-app/AppLotteryAward/lotteryAwayCount"
const val LOTTERY_AWARD_COUNT_PROD = "/dispatch-app/AppLotteryAward/lotteryAwayCountPro"
const val AWARD_ASYNC_RECORD = "/dispatch-app/AppLotteryAward/asyncMcRecord"
}
object RakingAPI{
const val GET_RAKING_LIST = "/dispatch-app/raking/rakingList"
const val GET_USER_GAME = "/dispatch-app/raking/userGame"
}
object FileAPI{
const val POST_FILE_UPLOAD = "/dispatch-app/file/uploadImage"
}
object AppGameRoleRaking{
const val GET_APP_GAME_ROLE = "/dispatch-app/appGameRoleRaking/appGameRole"
}
} | 0 | Kotlin | 0 | 0 | 7c6d2b8c4f872f7d1a6791abffecfd5b6a2db3c7 | 1,727 | B-Im | Apache License 2.0 |
app/src/main/java/ca/on/hojat/gamenews/core/data/api/igdb/common/di/ErrorMessageExtractorsModule.kt | hojat72elect | 574,228,468 | false | null | package ca.on.hojat.gamenews.core.data.api.igdb.common.di
import ca.on.hojat.gamenews.core.data.api.common.ErrorMessageExtractor
import ca.on.hojat.gamenews.core.data.api.igdb.common.di.qualifiers.ErrorMessageExtractorKey
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoSet
@Module
@InstallIn(SingletonComponent::class)
interface ErrorMessageExtractorsModule {
@Binds
@IntoSet
fun bindTwitchErrorMessageExtractorToSet(
@ErrorMessageExtractorKey(ErrorMessageExtractorKey.Type.TWITCH)
errorMessageExtractor: ErrorMessageExtractor
): ErrorMessageExtractor
@Binds
@IntoSet
fun bindIgdbErrorMessageExtractorToSet(
@ErrorMessageExtractorKey(ErrorMessageExtractorKey.Type.IGDB)
errorMessageExtractor: ErrorMessageExtractor
): ErrorMessageExtractor
}
| 0 | Kotlin | 2 | 4 | b1c07551e90790ee3d273bc4c0ad3a5f97f71202 | 914 | GameHub | MIT License |
src/main/kotlin/com/hnidesu/net/proxy/internal/TrustAllTrustManager.kt | HNIdesu | 781,853,819 | false | {"Kotlin": 16295} | package com.hnidesu.net.proxy.internal
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
internal object TrustAllTrustManager:X509TrustManager {
override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {}
override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
} | 0 | Kotlin | 0 | 0 | 327aa338b954640cd4edc8b67fa40a117178f239 | 446 | HttpProxyServer | MIT License |
cache/src/main/java/com/technicalassigments/movieapp/cache/database/MovieDatabase.kt | anang2602 | 380,973,246 | false | null | package com.technicalassigments.movieapp.cache.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.technicalassigments.movieapp.cache.dao.GenreDao
import com.technicalassigments.movieapp.cache.entity.GenreEntity
@Database(
entities = [
GenreEntity::class
],
exportSchema = false,
version = 1
)
abstract class MovieDatabase: RoomDatabase() {
abstract fun genreDao(): GenreDao
} | 0 | Kotlin | 0 | 0 | 2d746afeb8ca41c4ef78b78e0ba2e0af8c3c3163 | 440 | movie-app | Apache License 2.0 |
cache/src/main/java/com/technicalassigments/movieapp/cache/database/MovieDatabase.kt | anang2602 | 380,973,246 | false | null | package com.technicalassigments.movieapp.cache.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.technicalassigments.movieapp.cache.dao.GenreDao
import com.technicalassigments.movieapp.cache.entity.GenreEntity
@Database(
entities = [
GenreEntity::class
],
exportSchema = false,
version = 1
)
abstract class MovieDatabase: RoomDatabase() {
abstract fun genreDao(): GenreDao
} | 0 | Kotlin | 0 | 0 | 2d746afeb8ca41c4ef78b78e0ba2e0af8c3c3163 | 440 | movie-app | Apache License 2.0 |
features/home/detail/src/main/kotlin/team/applemango/runnerbe/feature/home/detail/DetailActivity.kt | ricky-buzzni | 485,390,072 | false | {"Kotlin": 615137} | /*
* RunnerBe © 2022 Team AppleMango. all rights reserved.
* RunnerBe license is under the MIT.
*
* [DetailActivity.kt] created by <NAME> on 22. 3. 22. 오후 10:19
*
* Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE.
*/
package team.applemango.runnerbe.feature.home.detail
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import dagger.hilt.android.AndroidEntryPoint
import org.orbitmvi.orbit.viewmodel.observe
import team.applemango.runnerbe.domain.runningitem.model.runningitem.information.RunningItemInformation
import team.applemango.runnerbe.feature.home.detail.component.BoardDetail
import team.applemango.runnerbe.feature.home.detail.component.BoardDetailDummy
import team.applemango.runnerbe.feature.home.detail.mvi.DetailLoadState
import team.applemango.runnerbe.shared.android.extension.basicExceptionHandler
import team.applemango.runnerbe.shared.android.extension.collectWithLifecycle
import team.applemango.runnerbe.shared.android.extension.finishWithAnimation
import team.applemango.runnerbe.shared.android.extension.setWindowInsetsUsage
import team.applemango.runnerbe.shared.android.extension.toast
import team.applemango.runnerbe.shared.compose.extension.LocalActivity
import team.applemango.runnerbe.shared.compose.optin.LocalActivityUsageApi
import team.applemango.runnerbe.shared.compose.theme.GradientAsset
import team.applemango.runnerbe.shared.domain.constant.Intent
import team.applemango.runnerbe.shared.domain.extension.defaultCatch
@AndroidEntryPoint
class DetailActivity : ComponentActivity() {
private val vm: DetailViewModel by viewModels()
@OptIn(LocalActivityUsageApi::class) // LocalActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val runningItemId = intent.getIntExtra(Intent.MainBoard.RunningItemId, -1)
if (runningItemId == -1) {
toast(getString(R.string.detail_toast_fail_load_item))
finishWithAnimation()
return
}
vm.loadItemDetail(postId = runningItemId)
vm.exceptionFlow
.defaultCatch(action = ::basicExceptionHandler)
.collectWithLifecycle(lifecycleOwner = this) { exception ->
basicExceptionHandler(exception)
}
actionBar?.hide()
setWindowInsetsUsage()
setContent {
CompositionLocalProvider(LocalActivity provides this) {
var runningItemInformationState by remember {
mutableStateOf<RunningItemInformation?>(null)
}
LaunchedEffect(Unit) {
vm.observe(
lifecycleOwner = this@DetailActivity,
state = { state ->
handleState(
state = state,
updateRunningItemInformation = { loadedRunningItemInformation ->
runningItemInformationState = loadedRunningItemInformation
}
)
}
)
}
Crossfade(
modifier = Modifier // Do NOT insert padding. (because inner full-width map)
.fillMaxSize()
.background(brush = GradientAsset.Background.Brush),
targetState = runningItemInformationState != null
) { isLoaded ->
when (isLoaded) {
true -> {
BoardDetail(
modifier = Modifier.fillMaxSize(),
runningItemInformation = runningItemInformationState!!
)
}
else -> {
BoardDetailDummy(
modifier = Modifier.fillMaxSize(),
placeholderEnabled = runningItemInformationState == null
)
}
}
}
}
}
}
private fun handleState(
state: DetailLoadState,
updateRunningItemInformation: (item: RunningItemInformation) -> Unit,
) {
if (state is DetailLoadState.Loaded) {
updateRunningItemInformation(state.item)
}
}
}
| 0 | null | 0 | 0 | f48fb298c07732a9c32afcff0bddb16f9fe2e37a | 5,027 | RunnerBe-Android | MIT License |
app/src/main/java/com/example/noteapp/activities/LoginActivity.kt | lng8212 | 469,985,933 | false | {"Kotlin": 15839} | package com.example.noteapp.activities
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.noteapp.NoteApplication
import com.example.noteapp.R
import com.example.noteapp.databinding.ActivityLoginBinding
import com.example.noteapp.di.AuthComponent
import com.example.noteapp.di.DaggerAppComponent
import com.example.noteapp.viewmodel.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
class LoginActivity : AppCompatActivity() {
// @Inject
// lateinit var loginViewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityLoginBinding =
DataBindingUtil.setContentView(this, R.layout.activity_login)
// val authComponent = (application as NoteApplication).component.getAuthComponentFactory().create()
// authComponent.inject(this)
binding.btnLogin.setOnClickListener {
startActivity(
Intent(this, MainActivity::class.java)
)
finish()
}
}
} | 0 | Kotlin | 0 | 0 | 444290f62fd01aa14989242b38ba860662bde015 | 1,193 | note_app_with_dragger | MIT License |
app/src/main/java/com/example/myprofile/model/ProfileDataService.kt | NirvanaDogra | 570,923,017 | false | null | package com.example.myprofile.model
import com.example.network.environment.GithubEnvironmentUrl.WHATS_NEW_POST_URL
import io.reactivex.Observable
import retrofit2.http.GET
interface ProfileDataService {
@GET(WHATS_NEW_POST_URL)
fun getWhatsNewPostData(): Observable<PostDataModel>
} | 0 | Kotlin | 0 | 1 | 1cfeed2d914202a86a914ff07f06f1ca4a070eee | 292 | MyProfile | Apache License 2.0 |
app/src/main/java/com/example/linkyishop/data/retrofit/response/ProductsResponse.kt | Linkyi-Shop | 804,915,743 | false | {"Kotlin": 183601} | package com.example.linkyishop.data.retrofit.response
import kotlinx.parcelize.Parcelize
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
@Parcelize
data class ProductsResponse(
@field:SerializedName("data")
val data: Data? = null,
@field:SerializedName("success")
val success: Boolean? = null,
@field:SerializedName("message")
val message: String? = null
) : Parcelable
@Parcelize
data class DataItem(
@field:SerializedName("thumbnail")
val thumbnail: String? = null,
@field:SerializedName("is_active")
val isActive: Boolean? = null,
@field:SerializedName("price")
val price: String? = null,
@field:SerializedName("id")
val id: String? = null,
@field:SerializedName("title")
val title: String? = null,
@field:SerializedName("category")
val category: String? = null
) : Parcelable
@Parcelize
data class Products(
@field:SerializedName("per_page")
val perPage: Int? = null,
@field:SerializedName("data")
val data: List<DataItem?>? = null,
@field:SerializedName("last_page")
val lastPage: Int? = null,
@field:SerializedName("next_page_url")
val nextPageUrl: String? = null,
@field:SerializedName("prev_page_url")
val prevPageUrl: String? = null,
@field:SerializedName("first_page_url")
val firstPageUrl: String? = null,
@field:SerializedName("path")
val path: Int? = null,
@field:SerializedName("total")
val total: Int? = null,
@field:SerializedName("last_page_url")
val lastPageUrl: String? = null,
@field:SerializedName("from")
val from: Int? = null,
@field:SerializedName("links")
val links: List<LinksItem?>? = null,
@field:SerializedName("to")
val to: Int? = null,
@field:SerializedName("current_page")
val currentPage: Int? = null
) : Parcelable
@Parcelize
data class Data(
@field:SerializedName("products")
val products: Products? = null
) : Parcelable
@Parcelize
data class LinksItem(
@field:SerializedName("link")
val link: String? = null,
@field:SerializedName("id")
val id: String? = null,
@field:SerializedName("type")
val type: String? = null
) : Parcelable
| 0 | Kotlin | 0 | 0 | 6be7acc69abde5f4b57aacc0c15f804fe5aff416 | 2,083 | linkyi-mobile | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.