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
app/src/main/java/com/faranjit/meditory/features/home/presentation/adapter/story/StoriesAdapter.kt
faranjit
399,519,852
false
null
package com.faranjit.meditory.features.home.presentation.adapter.story import android.view.LayoutInflater import android.view.ViewGroup import com.faranjit.meditory.base.BaseRecyclerAdapter import com.faranjit.meditory.databinding.ListItemStoryBinding import com.faranjit.meditory.features.home.presentation.model.StoryModel /** * Created by <NAME> on 25.08.2021. */ class StoriesAdapter( onItemClickListener: OnItemClickListener<StoryModel> ) : BaseRecyclerAdapter<StoryModel, StoriesViewHolder>(onItemClickListener) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = StoriesViewHolder( ListItemStoryBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) }
0
Kotlin
0
0
97c1b1f1388b51797fa98a0e24cbfa85dd6cab61
762
meditory
MIT License
app/src/main/java/com/faranjit/meditory/features/home/presentation/adapter/story/StoriesAdapter.kt
faranjit
399,519,852
false
null
package com.faranjit.meditory.features.home.presentation.adapter.story import android.view.LayoutInflater import android.view.ViewGroup import com.faranjit.meditory.base.BaseRecyclerAdapter import com.faranjit.meditory.databinding.ListItemStoryBinding import com.faranjit.meditory.features.home.presentation.model.StoryModel /** * Created by <NAME> on 25.08.2021. */ class StoriesAdapter( onItemClickListener: OnItemClickListener<StoryModel> ) : BaseRecyclerAdapter<StoryModel, StoriesViewHolder>(onItemClickListener) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = StoriesViewHolder( ListItemStoryBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) }
0
Kotlin
0
0
97c1b1f1388b51797fa98a0e24cbfa85dd6cab61
762
meditory
MIT License
composeApp/src/desktopMain/kotlin/me/gustavolopezxyz/desktop/screens/overviewScreen/ExpensesSummaryCard.kt
gusaln
736,062,721
false
null
/* * Copyright (c) 2023. Gustavo López. All rights reserved. */ package me.gustavolopezxyz.desktop.screens.overviewScreen import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowLeft import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import app.cash.sqldelight.coroutines.mapToList import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.map import me.gustavolopezxyz.common.data.MissingCategory import me.gustavolopezxyz.common.data.MoneyTransaction import me.gustavolopezxyz.common.data.Palette import me.gustavolopezxyz.common.data.toDto import me.gustavolopezxyz.common.db.CategoryRepository import me.gustavolopezxyz.common.db.TransactionRepository import me.gustavolopezxyz.common.ext.datetime.* import me.gustavolopezxyz.common.money.currencyOf import me.gustavolopezxyz.common.ui.theme.AppDimensions import me.gustavolopezxyz.desktop.ui.common.AppListTitle import me.gustavolopezxyz.desktop.ui.core.MoneyPartitionEntry import me.gustavolopezxyz.desktop.ui.core.MoneyPartitionSummary internal val expensesColors = listOfNotNull( Palette.Colors["red800"], Palette.Colors["red600"], Palette.Colors["red400"], Palette.Colors["red200"], Palette.Colors["orange800"], Palette.Colors["orange600"], Palette.Colors["orange400"], Palette.Colors["orange200"], Palette.Colors["yellow800"], Palette.Colors["yellow600"], Palette.Colors["yellow400"], Palette.Colors["yellow200"], ) @Composable fun ExpensesSummaryCard( categoryRepository: CategoryRepository, transactionRepository: TransactionRepository, modifier: Modifier = Modifier, actions: @Composable RowScope.() -> Unit ) { var month by remember { mutableStateOf(nowLocalDateTime().date) } val categories by categoryRepository.allAsFlow().mapToList(Dispatchers.IO).map { list -> list.map { it.toDto() }.associateBy { it.categoryId } }.collectAsState(emptyMap()) var expenses by remember { mutableStateOf(emptyList<MoneyTransaction>()) } LaunchedEffect(month) { transactionRepository.getInPeriodAsFlow(month.startOfMonth().atStartOfDay(), month.endOfMonth().atEndOfDay()) .mapToList(Dispatchers.IO) .map { list -> list.filter { it.total < 0 } }.collect { expenses = it } } MoneyPartitionSummary( currency = currencyOf("USD"), amounts = expenses.groupBy { categories.getOrDefault( it.categoryId, MissingCategory.toDto() ).fullname() }.entries.map { transaction -> MoneyPartitionEntry(transaction.key, transaction.value.sumOf { it.total }) }, descending = false, colorPalette = expensesColors, modifier = modifier ) { AppListTitle(verticalAlignment = Alignment.Top) { actions() Spacer(Modifier.weight(1f)) Row( horizontalArrangement = Arrangement.spacedBy(AppDimensions.Default.spacing.small), verticalAlignment = Alignment.CenterVertically ) { Text(month.month.toString()) IconButton(onClick = { month = month.prevMonth() }) { Icon(Icons.Default.KeyboardArrowLeft, "prev month") } IconButton(onClick = { month = month.nextMonth() }) { Icon(Icons.Default.KeyboardArrowRight, "next month") } } } } }
0
null
0
1
d1e56bb6dce4a0d9c430a8d4f6bcf67b1249ea52
3,990
wimm
MIT License
src/main/kotlin/br/com/project/tasskfkotlin/exceptions/ResourceNotFoundException.kt
anekaroline
667,157,162
false
null
package br.com.project.tasskfkotlin.exceptions import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ResponseStatus import java.lang.Exception @ResponseStatus(HttpStatus.NOT_FOUND) class ResourceNotFoundException(exception: String?): RuntimeException(exception)
0
Kotlin
0
0
be74b68f26e76ac28d1a1346cbdd8e66d8d77158
299
tasskf-kotlin
Apache License 2.0
bukkit/bukkit-core/src/main/kotlin/kingmc/platform/bukkit/impl/spigot/SpigotPlatform.kt
Kingsthere
599,960,106
false
null
package kingmc.platform.bukkit.impl.spigot import kingmc.platform.bukkit.impl.BukkitPlatform import kingmc.platform.driver.PlatformDriver import kingmc.util.Version /** * Spigot platform compatible */ @SpigotImplementation open class SpigotPlatform(minecraftVersion: Version, driver: PlatformDriver, identifiers: Array<String> = arrayOf()) : BukkitPlatform(minecraftVersion, driver, arrayOf("spigot") + identifiers) { override fun toString(): String { return "Bukkit(Spigot) $minecraftVersion" } }
0
Kotlin
0
0
deb953d7a31738f8f602fb89e592db299ee3010c
523
kingmc-platform
MIT License
app/src/main/java/com/setianjay/githubuser/utill/AppUtil.kt
setianjay
393,715,206
false
null
package com.setianjay.githubuser.utill import android.content.Context import android.widget.Toast object AppUtil { fun showToast(context: Context, message: String){ Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
490919a7ee8555603f4c7e2446640cd491a8a6cc
247
GithubUser
MIT License
src/jsMain/kotlin/magneton/Application.kt
DaanVandenBosch
180,017,293
false
null
package magneton import magneton.nodes.Component import magneton.observable.ReactionDisposer import magneton.routing.Router import magneton.routing.defaultRouter import org.w3c.dom.Node as DomNode actual class Application( actual val rootComponent: Component, router: Router, private val domNode: DomNode? ) { actual constructor(rootComponent: Component, router: Router) : this(rootComponent, router, null) actual val context = Context(router = router) actual val started get() = disposer != null actual var disposer: ReactionDisposer? = null actual fun start() { internalStart() } actual fun stop() { internalStop() } internal actual fun mount() { if (domNode != null) { context.styleSheetRegistry.appendToDom(domNode) domNode.appendChild(rootComponent.domNode!!) } } internal actual fun unmount() { if (domNode != null) { context.styleSheetRegistry.removeFromDom() domNode.removeChild(rootComponent.domNode!!) } } } /** * @param component must produce a DOM node */ fun renderToDom(domNode: DomNode, component: Component): Application { val app = Application(component, defaultRouter, domNode) app.start() return app }
0
Kotlin
0
16
ff2d0cfb12db2173bdffb6bec689ddfd092c191d
1,311
magneton
MIT License
common/src/main/java/com/ishow/common/widget/viewpager/looping/indicator/DefaultLoopingIndicator.kt
i-show
62,766,394
false
null
package dev.hitools.common.widget.viewpager.looping.indicator import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import dev.hitools.common.utils.UnitUtils import dev.hitools.common.widget.viewpager.looping.ILoopingIndicator /** * Created by yuhaiyang on 2018/9/13. * 默认的 */ class DefaultLoopingIndicator : ILoopingIndicator { private val mIndicatorPaint: Paint private val mIndicatorBorderPaint: Paint private val mIndicatorRadius: Int = UnitUtils.dip2px(3) private val mIndicatorItemWidth: Int private var mIndicatorWidth: Int = 0 private val mIndicatorHeight: Int private var mWidth: Int = 0 private var mHeight: Int = 0 init { mIndicatorItemWidth = 5 * mIndicatorRadius mIndicatorHeight = 6 * mIndicatorRadius mIndicatorPaint = Paint() mIndicatorPaint.isAntiAlias = true mIndicatorPaint.isDither = true mIndicatorPaint.color = Color.WHITE mIndicatorBorderPaint = Paint() mIndicatorBorderPaint.isAntiAlias = true mIndicatorBorderPaint.isDither = true mIndicatorBorderPaint.color = Color.GRAY mIndicatorBorderPaint.style = Paint.Style.STROKE } override fun onViewSizeChanged(w: Int, h: Int) { mWidth = w mHeight = h } override fun onDataSizeChanged(count: Int) { mIndicatorWidth = mIndicatorItemWidth * count } override fun onDraw(canvas: Canvas, scrollX: Int, count: Int, currentPosition: Int, positionOffset: Float) { val nextPosition = if (currentPosition == count - 1) 0 else currentPosition + 1 val startX = mWidth / 2 - mIndicatorWidth / 2 + scrollX val y = mHeight - mIndicatorHeight val currentIndicatorRadius = (mIndicatorRadius + mIndicatorRadius.toFloat() * (1 - positionOffset) * 0.38f).toInt() val nextIndicatorRadius = (mIndicatorRadius + mIndicatorRadius.toFloat() * positionOffset * 0.38f).toInt() for (i in 0 until count) { val x = startX + i * mIndicatorItemWidth + (mIndicatorItemWidth - mIndicatorRadius) / 2 when (i) { currentPosition -> { canvas.drawCircle(x.toFloat(), y.toFloat(), currentIndicatorRadius.toFloat(), mIndicatorPaint) canvas.drawCircle(x.toFloat(), y.toFloat(), currentIndicatorRadius.toFloat(), mIndicatorBorderPaint) } nextPosition -> { canvas.drawCircle(x.toFloat(), y.toFloat(), nextIndicatorRadius.toFloat(), mIndicatorPaint) canvas.drawCircle(x.toFloat(), y.toFloat(), nextIndicatorRadius.toFloat(), mIndicatorBorderPaint) } else -> { canvas.drawCircle(x.toFloat(), y.toFloat(), mIndicatorRadius.toFloat(), mIndicatorPaint) canvas.drawCircle(x.toFloat(), y.toFloat(), mIndicatorRadius.toFloat(), mIndicatorBorderPaint) } } } } }
1
null
1
1
0b823a69256345078a0c110798c8e9ac4ae2b565
3,011
android-Common
Apache License 2.0
src/test/kotlin/no/nav/k9brukerdialogapi/wiremock/SøkerResponseTransformer.kt
navikt
460,765,798
false
{"Kotlin": 835877, "Dockerfile": 103}
package no.nav.k9brukerdialogapi.wiremock import com.github.tomakehurst.wiremock.extension.ResponseTransformerV2 import com.github.tomakehurst.wiremock.http.Response import com.github.tomakehurst.wiremock.stubbing.ServeEvent import no.nav.k9brukerdialogapi.TestUtils class SokerResponseTransformer : ResponseTransformerV2 { override fun getName(): String { return "k9-oppslag-soker" } override fun transform(response: Response, event: ServeEvent): Response { return Response.Builder.like(response) .body( getResponse( ident = TestUtils.getIdentFromIdToken(event.request) ) ) .build() } override fun applyGlobally(): Boolean { return false } } private fun getResponse(ident: String): String { when(ident) { "25037139184" -> { return """ { "aktør_id": "23456", "fornavn": "ARNE", "mellomnavn": "BJARNE", "etternavn": "CARLSEN", "fødselsdato": "1990-01-02" } """.trimIndent() } "290990123456" -> { return """ { "etternavn": "MORSEN", "fornavn": "MOR", "mellomnavn": "HEISANN", "aktør_id": "12345", "fødselsdato": "1997-05-25" } """.trimIndent() } "12125012345" -> { return """ { "etternavn": "MORSEN", "fornavn": "MOR", "mellomnavn": "HEISANN", "aktør_id": "12345", "fødselsdato": "2050-12-12" } """.trimIndent() } "02119970078" -> { return """ { "etternavn": "MORSEN", "fornavn": "MOR", "mellomnavn": "HEISANN", "aktør_id": "12345", "fødselsdato": "1999-11-02" } """.trimIndent() } else -> { return """ {} """.trimIndent() } } }
0
Kotlin
0
0
d7c6b3126bf1cc4cd7fd7d5f429eb4634140b49f
2,130
k9-brukerdialog-api
MIT License
src/main/kotlin/io/reactiverse/kotlin/pgclient/pubsub/PgSubscriber.kt
mp911de
173,499,536
true
{"Java": 759864, "Kotlin": 35910, "PLpgSQL": 16765, "Shell": 829, "Dockerfile": 814}
package io.reactiverse.kotlin.pgclient.pubsub import io.reactiverse.pgclient.pubsub.PgSubscriber import io.vertx.kotlin.coroutines.awaitResult /** * Connect the subscriber to Postgres. * * @param handler the handler notified of the connection success or failure * @returna reference to this, so the API can be used fluently * * <p/> * NOTE: This function has been automatically generated from the [io.reactiverse.pgclient.pubsub.PgSubscriber original] using Vert.x codegen. */ suspend fun PgSubscriber.connectAwait() : Unit { return awaitResult{ this.connect({ ar -> it.handle(ar.mapEmpty()) })} }
0
Java
0
0
f04bdb41c0ed535c20a098e2759b02de68c4085b
614
reactive-pg-client
Apache License 2.0
android/sdk/src/main/java/clover/studio/sdk/call/RoomMessageHandler.kt
cloverstudio
381,606,636
false
null
package clover.studio.sdk.call import androidx.annotation.WorkerThread import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import org.mediasoup.droid.Consumer import org.mediasoup.droid.Logger import org.protoojs.droid.Message import java.util.concurrent.ConcurrentHashMap internal open class RoomMessageHandler( // Stored Room States. val mStore: RoomStore ) { // mediasoup Consumers. val mConsumers: MutableMap<String, ConsumerHolder> internal class ConsumerHolder(val peerId: String, val mConsumer: Consumer) @WorkerThread @Throws(JSONException::class) fun handleNotification(notification: Message.Notification) { val data: JSONObject = notification.data when (notification.method) { "producerScore" -> { // {"producerId":"<PASSWORD>","score":[{"score":10,"ssrc":196184265}]} val producerId: String = data.getString("producerId") val score: JSONArray = data.getJSONArray("score") mStore.setProducerScore(producerId, score) } "newPeer" -> { val id: String = data.getString("id") val displayName: String = data.optString("displayName") mStore.addPeer(id, data) mStore.addNotify("$displayName has joined the room") } "peerClosed" -> { val peerId: String = data.getString("peerId") mStore.removePeer(peerId) } "peerDisplayNameChanged" -> { val peerId: String = data.getString("peerId") val displayName: String = data.optString("displayName") val oldDisplayName: String = data.optString("oldDisplayName") mStore.setPeerDisplayName(peerId, displayName) mStore.addNotify("$oldDisplayName is now $displayName") } "consumerClosed" -> { val consumerId: String = data.getString("consumerId") mConsumers.remove(consumerId)?.let { it.mConsumer.close() mConsumers.remove(consumerId) mStore.removeConsumer(it.peerId, it.mConsumer.id) } } "consumerPaused" -> { val consumerId: String = data.getString("consumerId") mConsumers[consumerId]?.let { mStore.setConsumerPaused(it.mConsumer.id, "remote") } } "consumerResumed" -> { val consumerId: String = data.getString("consumerId") mConsumers[consumerId]?.let { mStore.setConsumerResumed(it.mConsumer.id, "remote") } } "consumerLayersChanged" -> { val consumerId: String = data.getString("consumerId") val spatialLayer: Int = data.optInt("spatialLayer") val temporalLayer: Int = data.optInt("temporalLayer") mConsumers[consumerId]?.let { mStore.setConsumerCurrentLayers(consumerId, spatialLayer, temporalLayer) } } "consumerScore" -> { val consumerId: String = data.getString("consumerId") val score: JSONArray? = data.optJSONArray("score") mConsumers[consumerId]?.let { mStore.setConsumerScore(consumerId, score) } } "dataConsumerClosed" -> { } "activeSpeaker" -> { val peerId: String = data.getString("peerId") mStore.setRoomActiveSpeaker(peerId) } else -> { Logger.e(TAG, "unknown protoo notification.method " + notification.method) } } } companion object { const val TAG = "RoomClient" } init { mConsumers = ConcurrentHashMap() } }
0
Kotlin
0
2
3f7e7f4c88b0f95d914645ba235993c46560664b
4,000
SpikaBroadcast_old
MIT License
app/src/main/java/chat/rocket/android/app/RocketChatApplication.kt
gkganesh126
124,833,630
true
{"Kotlin": 386715, "Shell": 2737, "Java": 538}
package chat.rocket.android.app import android.app.Activity import android.app.Application import android.app.Service import chat.rocket.android.BuildConfig import chat.rocket.android.dagger.DaggerAppComponent import chat.rocket.android.helper.CrashlyticsTree import chat.rocket.android.server.domain.GetCurrentServerInteractor import chat.rocket.android.server.domain.MultiServerTokenRepository import chat.rocket.android.server.domain.SettingsRepository import chat.rocket.android.widget.emoji.EmojiRepository import chat.rocket.common.model.Token import chat.rocket.core.TokenRepository import com.crashlytics.android.Crashlytics import com.crashlytics.android.core.CrashlyticsCore import com.facebook.drawee.backends.pipeline.DraweeConfig import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.core.ImagePipelineConfig import com.jakewharton.threetenabp.AndroidThreeTen import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import dagger.android.HasServiceInjector import io.fabric.sdk.android.Fabric import timber.log.Timber import javax.inject.Inject class RocketChatApplication : Application(), HasActivityInjector, HasServiceInjector { @Inject lateinit var activityDispatchingAndroidInjector: DispatchingAndroidInjector<Activity> @Inject lateinit var serviceDispatchingAndroidInjector: DispatchingAndroidInjector<Service> @Inject lateinit var imagePipelineConfig: ImagePipelineConfig @Inject lateinit var draweeConfig: DraweeConfig // TODO - remove this from here when we have a proper service handling the connection. @Inject lateinit var getCurrentServerInteractor: GetCurrentServerInteractor @Inject lateinit var multiServerRepository: MultiServerTokenRepository @Inject lateinit var settingsRepository: SettingsRepository @Inject lateinit var tokenRepository: TokenRepository override fun onCreate() { super.onCreate() DaggerAppComponent.builder().application(this).build().inject(this) // TODO - remove this when we have a proper service handling connection... initCurrentServer() AndroidThreeTen.init(this) EmojiRepository.load(this) setupCrashlytics() setupFresco() setupTimber() } // TODO - remove this when we have a proper service handling connection... private fun initCurrentServer() { val currentServer = getCurrentServerInteractor.get() val serverToken = currentServer?.let { multiServerRepository.get(currentServer) } val settings = currentServer?.let { settingsRepository.get(currentServer) } if (currentServer != null && serverToken != null && settings != null) { tokenRepository.save(Token(serverToken.userId, serverToken.authToken)) } } private fun setupCrashlytics() { val core = CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build() Fabric.with(this, Crashlytics.Builder().core(core).build()) } private fun setupFresco() { Fresco.initialize(this, imagePipelineConfig, draweeConfig) } private fun setupTimber() { if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } else { Timber.plant(CrashlyticsTree()) } } override fun activityInjector(): AndroidInjector<Activity> { return activityDispatchingAndroidInjector } override fun serviceInjector(): AndroidInjector<Service> { return serviceDispatchingAndroidInjector } }
0
Kotlin
0
1
c1871a62843714c8fadffb3f97e8fa358b3c1efb
3,623
Rocket.Chat.Android
MIT License
fore-kt/fore-kt-network/src/main/java/co/early/fore/kt/net/apollo3/CallWrapperApollo3.kt
erdo
92,027,307
false
null
package co.early.fore.kt.net.apollo3 import co.early.fore.core.WorkMode import co.early.fore.kt.core.Either import co.early.fore.kt.core.coroutine.asyncMain import co.early.fore.kt.core.coroutine.awaitIO import co.early.fore.kt.core.delegate.Fore import co.early.fore.kt.core.logging.Logger import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.api.ExecutionContext import com.apollographql.apollo3.api.Operation import kotlinx.coroutines.Deferred @ExperimentalStdlibApi interface Apollo3Caller<F> { suspend fun <S : Operation.Data> processCallAwait( call: suspend () -> ApolloResponse<S> ): Either<F, CallProcessorApollo3.SuccessResult<S, F>> suspend fun <S : Operation.Data> processCallAsync( call: suspend () -> ApolloResponse<S> ): Deferred<Either<F, CallProcessorApollo3.SuccessResult<S, F>>> } /** * @property errorHandler Error handler for the service (interpreting HTTP codes, GraphQL errors * etc). This error handler is often the same across a range of services required by the app. * However, sometimes the APIs all have different error behaviours (say when the service APIs have * been developed at different times, or by different teams or different third parties). In this * case it might be easier to use a separate CallProcessorApollo3 instance (and ErrorHandler) for * each micro service. * @property logger (optional: ForeDelegateHolder will choose a sensible default) * @property workMode (optional: ForeDelegateHolder will choose a sensible default) * @property allowPartialSuccesses (defaults to true) The GraphQL spec allows for success responses * with qualified errors, like this: https://spec.graphql.org/draft/#example-90475 if true, you will * receive these responses as successes, together with the list of partial errors that were attached * in the response. If allowPartialSuccesses=false, these types of responses will be delivered as * errors and the successful parts of the response will be dropped. * * @param F The class type passed back in the event of a failure, Globally applicable * failure message class, like an enum for example */ @ExperimentalStdlibApi class CallProcessorApollo3<F>( private val errorHandler: ErrorHandler<F>, private val logger: Logger? = null, private val workMode: WorkMode? = null, private val allowPartialSuccesses: Boolean = true ) : Apollo3Caller<F> { data class SuccessResult<S, F>( val data: S, val partialErrors: List<F> = listOf(), val extensions: Map<String, Any?> = hashMapOf(), val executionContext: ExecutionContext = ExecutionContext.Empty ) /** * @param call functional type that returns the result of an ApolloRequest * @param S Success class you expect to be returned from the call (or Unit for an empty response) * * @return Either<F, SuccessResult<S>> */ override suspend fun <S : Operation.Data> processCallAwait(call: suspend () -> ApolloResponse<S>): Either<F, SuccessResult<S, F>> { return processCallAsync(call).await() } /** * @param call functional type that returns the result of an ApolloRequest * @param S Success class you expect to be returned from the call (or Unit for an empty response) * * @return Deferred<Either<F, SuccessResult<S>>> */ override suspend fun <S : Operation.Data> processCallAsync(call: suspend () -> ApolloResponse<S>): Deferred<Either<F, SuccessResult<S, F>>> { return asyncMain(Fore.getWorkMode(workMode)) { try { val result: ApolloResponse<S> = awaitIO(Fore.getWorkMode(workMode)) { Fore.getLogger(logger).d("about to make call from io dispatcher, thread:" + Thread.currentThread()) call() } processSuccessResponse(result) } catch (t: Throwable) { processFailResponse(t, null) } } } private fun <S : Operation.Data> processSuccessResponse( response: ApolloResponse<S> ): Either<F, SuccessResult<S,F>> { val data: S? = response.data return if (data != null) { if (!response.hasErrors() || allowPartialSuccesses) { Either.right( SuccessResult( data, errorHandler.handlePartialErrors(response.errors), response.extensions, response.executionContext ) ) } else { processFailResponse(null, response) } } else { processFailResponse(null, response) } } private fun <S> processFailResponse( t: Throwable?, errorResponse: ApolloResponse<*>? ): Either<F, SuccessResult<S,F>> { if (t != null) { Fore.getLogger(logger).e("processFailResponse() t:" + Thread.currentThread(), t) } if (errorResponse != null) { Fore.getLogger(logger).e("processFailResponse() errorResponse:$errorResponse t:" + Thread.currentThread()) } return Either.left(errorHandler.handleError(t, errorResponse)) } }
3
null
4
46
1af5bd3ad9b2395a636fac12c40016fd2c815d0c
5,260
android-fore
Apache License 2.0
whynotimagecarousel/src/main/java/org/life4what/image4carousel/model/CarouselType.kt
life4what
583,161,309
false
{"Kotlin": 59692}
package org.life4what.image4carousel.model enum class CarouselType(val value: Int) { BLOCK(0), SHOWCASE(1) }
0
Kotlin
0
0
c62fd8601821a8e396df0a97bf10126cc16fecb0
118
image4Carousel
Apache License 2.0
modules/wasm-binary/src/commonMain/kotlin/verifier/TableSectionVerifier.kt
wasmium
761,480,110
false
{"Kotlin": 661510, "JavaScript": 203}
package org.wasmium.wasm.binary.verifier import org.wasmium.wasm.binary.ParserException import org.wasmium.wasm.binary.WasmBinary import org.wasmium.wasm.binary.tree.TableType import org.wasmium.wasm.binary.visitor.TableSectionVisitor public class TableSectionVerifier(private val delegate: TableSectionVisitor? = null, private val context: VerifierContext) : TableSectionVisitor { private var done: Boolean = false private var numberOfTables: UInt = 0u public override fun visitTable(tableType: TableType) { checkEnd() if (tableType.limits.initial > WasmBinary.MAX_TABLE_PAGES) { throw ParserException("Invalid initial memory pages") } if (tableType.limits.maximum != null) { if (tableType.limits.maximum > WasmBinary.MAX_TABLE_PAGES) { throw ParserException("Invalid table max page") } } numberOfTables++ delegate?.visitTable(tableType) } override fun visitEnd() { checkEnd() if (this.numberOfTables > WasmBinary.MAX_TABLES) { throw VerifierException("Number of tables $numberOfTables exceed the maximum of ${WasmBinary.MAX_TABLES}"); } context.numberOfTables = numberOfTables done = true delegate?.visitEnd() } private fun checkEnd() { if (done) { throw VerifierException("Cannot call a visit method after visitEnd has been called") } } }
0
Kotlin
0
3
dc846f459f0bda1527cad253614df24bbdea012f
1,482
wasmium-wasm-binary
Apache License 2.0
text_world/src/main/kotlin/cubes/shaders/Starfield1Shader.kt
sentinelweb
228,927,082
false
null
package cubes.shaders import cubes.CubesProcessingView.Companion.BASE_RESOURCES import processing.core.PApplet class Starfield1Shader constructor( p: PApplet ) : ShaderWrapper( p, "$BASE_RESOURCES/cubes/st_starfield_1.glsl" )
14
Kotlin
0
0
623fd9f4d860b61dfc5b5dfbc5a8f536d978d9f6
239
processink
Apache License 2.0
app/src/main/java/com/coffee/shop/domain/models/DomainCoffeeCategory.kt
fahadnasrullah109
797,161,686
false
{"Kotlin": 248481}
package com.coffee.shop.domain.models import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class DomainCoffeeCategory( val category: String, val items: List<DomainCoffee> ) : Parcelable
0
Kotlin
0
0
28ed5f7f101c36a19c89c29628a530945cc1d432
222
CoffeeShop
Apache License 2.0
android/src/main/java/com/splashscreen/SplashScreen.kt
huynq1175
851,282,431
false
{"Kotlin": 6257, "Ruby": 3312, "Objective-C++": 3258, "Objective-C": 2591, "JavaScript": 1613, "TypeScript": 1474, "C": 103, "Swift": 64}
package com.splashscreen import android.app.Activity import android.app.Dialog import android.os.Build import android.view.WindowManager import java.lang.ref.WeakReference object SplashScreen { private var mSplashDialog: Dialog? = null private var mActivity: WeakReference<Activity>? = null fun show(activity: Activity?, themeResId: Int, fullScreen: Boolean) { if (activity == null) return mActivity = WeakReference(activity) activity.runOnUiThread { if (!activity.isFinishing) { mSplashDialog = Dialog(activity, themeResId).apply { setContentView(R.layout.splash_screen) setCancelable(false) if (fullScreen) { setActivityAndroidP(this) } if (!isShowing) { show() } } } } } fun show(activity: Activity, fullScreen: Boolean) { val resourceId = if (fullScreen) R.style.SplashScreen_Fullscreen else R.style.SplashScreen_SplashTheme show(activity, resourceId, fullScreen) } fun show(activity: Activity) { show(activity, false) } fun hide(activity: Activity?) { var activity = activity if (activity == null) { activity = mActivity?.get() } if (activity == null) return activity.runOnUiThread { mSplashDialog?.takeIf { it.isShowing }?.let { if (!activity.isFinishing && !(activity.isDestroyed)) { it.dismiss() } mSplashDialog = null } } } private fun setActivityAndroidP(dialog: Dialog) { if (Build.VERSION.SDK_INT >= 28) { dialog.window?.apply { addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) attributes = attributes.apply { layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } } } } }
0
Kotlin
0
0
ca25364c0df30b8d6d9fd5ad71a52b5dab1928cf
1,842
react-native-splash-screen
MIT License
androidApp/src/main/java/com/muneeb_dev/medicinetime_cmp/android/BaseApplication.kt
muneeb36
737,341,589
false
{"Kotlin": 96355, "Ruby": 1878, "Swift": 897}
package com.muneeb_dev.medicinetime_cmp.android import android.app.Application import com.muneeb_dev.medicinetime_cmp.di.initKoin import org.koin.android.ext.koin.androidContext class BaseApplication(): Application() { override fun onCreate() { super.onCreate() initKoin{ androidContext(this@BaseApplication) } } }
0
Kotlin
1
10
548a6fba6d6cfdc3b67ef80362dc46a817a33d36
361
Medicine-Time-CMP
MIT License
common/src/commonMain/kotlin/com/niji/claudio/common/tool/VoicePlayerService.kt
GuillaumeMuret
718,024,230
false
{"Kotlin": 265351, "Shell": 4408, "Swift": 571, "HTML": 357, "CSS": 108}
package com.niji.claudio.common.tool expect object VoicePlayerService { fun play(byteArray: ByteArray) }
0
Kotlin
0
0
85f940518daed3df33e724b44a89533355e96ea3
109
claudio-app
Apache License 2.0
app/src/main/java/com/yenaly/han1meviewer/ui/fragment/home/WatchHistoryFragment.kt
YenalyLiew
524,046,895
false
null
package com.yenaly.han1meviewer.ui.fragment.home import android.os.Bundle import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import com.yenaly.han1meviewer.R import com.yenaly.han1meviewer.databinding.FragmentListOnlyBinding import com.yenaly.han1meviewer.ui.activity.MainActivity import com.yenaly.han1meviewer.ui.adapter.WatchHistoryRvAdapter import com.yenaly.han1meviewer.ui.viewmodel.MainViewModel import com.yenaly.yenaly_libs.base.YenalyFragment import com.yenaly.yenaly_libs.utils.showSnackBar import com.yenaly.yenaly_libs.utils.unsafeLazy import kotlinx.coroutines.launch /** * @project Han1meViewer * @author <NAME> * @time 2022/07/01 001 21:23 */ class WatchHistoryFragment : YenalyFragment<FragmentListOnlyBinding, MainViewModel>() { private val historyAdapter by unsafeLazy { WatchHistoryRvAdapter() } override fun initData(savedInstanceState: Bundle?) { (activity as? MainActivity)?.setToolbarSubtitle(getString(R.string.watch_history)) addMenu(R.menu.menu_watch_history_toolbar, viewLifecycleOwner) { item -> when (item.itemId) { R.id.tb_delete -> { // todo: strings.xml MaterialAlertDialogBuilder(requireContext()) .setTitle("看這裏!") .setMessage("是否將影片觀看歷史記錄全部刪除🤔") .setPositiveButton("是的!") { _, _ -> viewModel.deleteAllWatchHistories() } .setNegativeButton("算了!", null) .show() return@addMenu true } R.id.tb_help -> { MaterialAlertDialogBuilder(requireContext()) .setTitle("使用注意!") .setMessage("左劃可以刪除歷史記錄哦,右上角的刪除按鈕是負責刪除全部歷史記錄的!") .setPositiveButton("OK", null) .show() return@addMenu true } } return@addMenu false } binding.rvList.apply { layoutManager = LinearLayoutManager(context) adapter = historyAdapter } historyAdapter.setDiffCallback(WatchHistoryRvAdapter.COMPARATOR) historyAdapter.setEmptyView(R.layout.layout_empty_view) ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.START) { // 上下滑動 override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ) = false // 左右滑動 override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.bindingAdapterPosition val data = historyAdapter.getItem(position) historyAdapter.remove(data) // todo: strings.xml showSnackBar("你正在刪除該歷史記錄", Snackbar.LENGTH_LONG) { setAction("撤銷") { historyAdapter.addData(position, data) } addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() { override fun onDismissed(transientBottomBar: Snackbar?, event: Int) { if (event != DISMISS_EVENT_ACTION) { viewModel.deleteWatchHistory(data) } } }) } } }).attachToRecyclerView(binding.rvList) } override fun liveDataObserve() { viewLifecycleOwner.lifecycleScope.launch { viewModel.loadAllWatchHistories() .flowWithLifecycle(viewLifecycleOwner.lifecycle) .collect { if (it.isEmpty()) { historyAdapter.setEmptyView(R.layout.layout_empty_view) } else { historyAdapter.setDiffNewData(it) } } } } }
1
Kotlin
3
71
7e84333d37871c1fee0ec262e697d65c1e68a409
4,490
Han1meViewer
Apache License 2.0
app/src/main/java/com/example/jokeappeasycoderu/JokeRealmModel.kt
blastka
568,419,344
false
null
package com.example.jokeappeasycoderu interface JokeRealmModel { }
0
Kotlin
0
0
5144bdbc9d423755753501779fed5abf5b1ea17b
67
joke_easyCodeRu
Apache License 2.0
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/autoscaling/v2/scaleTargetRef.kt
fkorotkov
84,911,320
false
null
// GENERATED package com.fkorotkov.kubernetes.autoscaling.v2 import io.fabric8.kubernetes.api.model.autoscaling.v2.CrossVersionObjectReference as v2_CrossVersionObjectReference import io.fabric8.kubernetes.api.model.autoscaling.v2.HorizontalPodAutoscalerSpec as v2_HorizontalPodAutoscalerSpec fun v2_HorizontalPodAutoscalerSpec.`scaleTargetRef`(block: v2_CrossVersionObjectReference.() -> Unit = {}) { if(this.`scaleTargetRef` == null) { this.`scaleTargetRef` = v2_CrossVersionObjectReference() } this.`scaleTargetRef`.block() }
6
Kotlin
19
317
ef8297132e6134b6f65ace3e50869dbb2b686b21
545
k8s-kotlin-dsl
MIT License
domain/src/main/java/com/technicalassigments/movieapp/domain/repository/reviews/ReviewsRepository.kt
anang2602
380,973,246
false
null
package com.technicalassigments.movieapp.domain.repository.reviews import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.technicalassigments.movieapp.domain.usecase.FetchReviewsUseCase import com.technicalassigments.movieapp.network.dto.ReviewsResponse import com.technicalassigments.movieapp.network.services.ReviewsService import kotlinx.coroutines.flow.Flow class ReviewsRepository(private val apiService: ReviewsService) : FetchReviewsUseCase { override fun fetchReviewsByMovieId(movieId: Int): Flow<PagingData<ReviewsResponse.Reviews>> { return Pager( config = PagingConfig( pageSize = 20, enablePlaceholders = false ), pagingSourceFactory = { ReviewsPagingSource(apiService, movieId) } ).flow } }
0
Kotlin
0
0
2d746afeb8ca41c4ef78b78e0ba2e0af8c3c3163
855
movie-app
Apache License 2.0
server/src/main/kotlin/au/com/codeka/warworlds/server/world/StarSimulatorQueue.kt
codeka
12,893,073
false
{"Kotlin": 1027286, "HTML": 346676, "CSS": 256900, "JavaScript": 250865, "Python": 11974, "PHP": 2232, "Shell": 911}
package au.com.codeka.warworlds.server.world import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.Time import au.com.codeka.warworlds.common.sim.SuspiciousModificationException import au.com.codeka.warworlds.server.store.DataStore import au.com.codeka.warworlds.server.store.StarsStore import com.google.api.client.util.Lists import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock /** * This class manages the star simulation queue, and schedules stars to be simulated at the * appropriate time. */ class StarSimulatorQueue private constructor() { private val thread: Thread private val stars: StarsStore = DataStore.i.stars() private var running = false private val lock = ReentrantLock() private val pinger = lock.newCondition() fun start() { log.info("Starting star simulation queue.") running = true thread.start() } fun stop() { running = false ping() try { thread.join() } catch (e: InterruptedException) { // Ignore. } } fun ping() { lock.withLock { pinger.signal() } } private fun run() { try { log.info("Star simulator queue starting up.") while (running) { val star = stars.nextStarForSimulate() var waitTime: Long waitTime = if (star == null) { log.info("No stars to simulate, sleeping for a bit.") 10 * Time.MINUTE } else { val nextSimulation = star.next_simulation if (nextSimulation == null) { log.warning("Star #%d (%s) next_simulation is null.", star.id, star.name) 0 } else { nextSimulation - System.currentTimeMillis() } } if (waitTime <= 0) { waitTime = 1 // 1 millisecond to ensure that we actually sleep at least a little. } // Don't sleep for more than 10 minutes, we'll just loop around and check again. if (waitTime > 10 * Time.MINUTE) { waitTime = 10 * Time.MINUTE } log.info("Star simulator sleeping for %d ms.", waitTime) try { lock.withLock { pinger.await(waitTime, TimeUnit.MILLISECONDS) } } catch (e: InterruptedException) { // Ignore. } if (star != null) { val startTime = System.nanoTime() val watchableStar = StarManager.i.getStarOrError(star.id) try { StarManager.i.modifyStar(watchableStar, Lists.newArrayList()) } catch (e: SuspiciousModificationException) { // Shouldn't ever happen, as we're passing an empty list of modifications. log.warning("Unexpected suspicious modification.", e) } val endTime = System.nanoTime() log.info("Star #%d (%s) simulated in %dms", star.id, star.name, (endTime - startTime) / 1000000L) } } log.info("Star simulator queue shut down.") } catch (e: Exception) { log.error("Error in star simulation queue, star simulations are paused!", e) } } companion object { val i = StarSimulatorQueue() private val log = Log("StarSimulatorQueue") } init { thread = Thread(Runnable { this.run() }, "StarSimulateQueue") } }
56
Kotlin
202
291
536e37f83577b5cdad1e374a36281368ba868c83
3,331
wwmmo
MIT License
app/src/main/java/com/singhgeetgovind/notes/di/module/DatabaseModule.kt
singhgeetgovind
618,067,094
false
{"Kotlin": 88152}
package com.singhgeetgovind.notes.di.module import android.app.Application import androidx.room.Room import com.singhgeetgovind.notes.dao.NotesDao import com.singhgeetgovind.notes.database.Migration import com.singhgeetgovind.notes.database.NotesDatabase import com.singhgeetgovind.notes.repository.Repository import com.singhgeetgovind.notes.retrofit.MyRetrofitBuilder import com.singhgeetgovind.notes.retrofit.RetrofitApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Singleton @Provides fun provideDatabase(application: Application): NotesDatabase = Room.databaseBuilder( application, NotesDatabase::class.java, "NotesDatabase" ) .addMigrations(*Migration.DataBaseMigration) .build() @Singleton @Provides fun provideDao(notesDatabase: NotesDatabase) : NotesDao = notesDatabase.getDaoInstance() @Singleton @Provides fun provideApiBuilder(retrofitBuilder: MyRetrofitBuilder) : RetrofitApi = retrofitBuilder.getRetrofitApi() @Singleton @Provides fun provideRepository(notesDao: NotesDao/*, retrofitApi: RetrofitApi*/) : Repository = Repository(notesDao/*, retrofitApi*/) }
0
Kotlin
1
2
e2ca545b18af5584fb26b485146a2eaba7665580
1,405
Notes
MIT License
core/domain/src/main/kotlin/com/xeladevmobile/medicalassistant/core/domain/GetAudioRecordUseCase.kt
Alexminator99
702,145,143
false
{"Kotlin": 534097}
package com.xeladevmobile.medicalassistant.core.domain import com.xeladevmobile.medicalassistant.core.data.repository.AudioRecordsRepository import javax.inject.Inject class GetAudioRecordUseCase @Inject constructor( private val audioRecordsRepository: AudioRecordsRepository, ) { operator fun invoke(audioId: String) = audioRecordsRepository.getAudio(audioId) }
0
Kotlin
0
0
37a35835a2562b0c6b4129e7b86cfca081a24783
372
Medical_Assistant
MIT License
smart-form/src/main/java/com/teleclinic/kabdo/smartform/EditText/SmartEditText.kt
TeleClinic
115,118,851
false
null
package com.teleclinic.kabdo.smartform import android.content.Context import android.util.AttributeSet import android.util.Patterns import android.view.View import android.widget.FrameLayout import java.util.regex.Pattern import com.pawegio.kandroid.d import android.text.InputType import com.pawegio.kandroid.textWatcher import com.teleclinic.kabdo.smartform.R import kotlinx.android.synthetic.main.smart_edittext.view.* /** * Created by karimabdo on 12/20/17. */ class SmartEditText : FrameLayout { private var mContext: Context? = null private var attrs: AttributeSet? = null private var styleAttr: Int? = null private var view = View.inflate(context, R.layout.smart_edittext, null) var mandatory: Boolean = true var mandatoryErrorMessage: String = "Mandatory Field" var regex: Pattern? = null var regexErrorMessage: String = "Wrong Format" var validateOnKeyPressed: Boolean = true val passwordLength = 8 fun editText() = editText fun setLabel(label: String) { smartTextInputLayout.hint = label } fun setError(error: String) { smartTextInputLayout.error = error } fun text() = editText.text.toString().trim() fun setHelperText(text: String) { smartTextInputLayout.setHelperText(text) } constructor(context: Context) : super(context) { init(context, null, null) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context, attrs, null) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context, attrs, defStyleAttr) } private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int?) { this.mContext = context this.attrs = attrs this.styleAttr = defStyleAttr addView(view) editText.textWatcher { afterTextChanged { smartTextInputLayout.isErrorEnabled = false } } readAttributes() } private fun readAttributes() { val arr = mContext?.theme?.obtainStyledAttributes(attrs, R.styleable.SmartEditText, 0, 0) arr?.let { it.getString(R.styleable.SmartEditText_setLabel)?.let { smartTextInputLayout.hint = it } it.getString(R.styleable.SmartEditText_setMandatoryErrorMsg)?.let { mandatoryErrorMessage = it } it.getString(R.styleable.SmartEditText_setRegexErrorMsg)?.let { regexErrorMessage = it } if (it.getInt(R.styleable.SmartEditText_setRegexType, -1) != -1) { setValidationType(ValidationType.values()[it.getInt(R.styleable.SmartEditText_setRegexType, -1)]) } it.getString(R.styleable.SmartEditText_setRegexString)?.let { setValidationRegex(it) } if (it.getBoolean(R.styleable.SmartEditText_setValidateOnKey, false)) { editText.textWatcher { afterTextChanged { check(false) } } } if (it.getBoolean(R.styleable.SmartEditText_setPasswordField, false)) { smartTextInputLayout.isPasswordVisibilityToggleEnabled = true editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD } val color = it.getColor(R.styleable.SmartEditText_setTextColor, resources.getColor(R.color.textGray)) changeTextColor(color) mandatory = it.getBoolean(R.styleable.SmartEditText_setMandatory, true) arr.recycle() } } fun changeTextColor(color: Int) { editText.setHintTextColor(color) editText.setTextColor(color) } fun check() = check(true) private fun check(error: Boolean): Boolean { if (mandatory) if (editText.text.trim().isEmpty()) { if (error) smartTextInputLayout.error = mandatoryErrorMessage else { smartTextInputLayout.setHelperText(mandatoryErrorMessage) } return false } regex?.let { if (!it.matcher(editText.text.toString()).find()) { if (error) smartTextInputLayout.error = regexErrorMessage else { smartTextInputLayout.setHelperText(regexErrorMessage) } return false } } smartTextInputLayout.isErrorEnabled = false return true } private val small = ".*[a-z].*" private val capital = ".*[A-Z].*" private val digit = ".*\\d.*" private val sign = ".*[^A-Za-z0-9].*" private val mediumPassword = Pattern.compile("^(((?=$small)(?=$digit))|((?=$small)(?=$capital))|((?=$digit)(?=$capital))|((?=$small)(?=$sign))|((?=$sign)(?=$capital))|((?=$digit)(?=$sign)))(?=.{$passwordLength,})") private val complexPassword = Pattern.compile("^(?=$small)(?=$capital)(?=$digit)(?=$sign)(?=.{$passwordLength,})") private val namePattern = Pattern.compile("^((?=$small)|(?=$capital))(?=.{2,})") fun setValidationType(type: ValidationType) { regex = when (type) { ValidationType.EMAIL_VALIDATION -> Patterns.EMAIL_ADDRESS ValidationType.MEDIUM_PASSWORD_VALIDATION -> mediumPassword ValidationType.COMPLEX_PASSWORD_VALIDATION -> complexPassword ValidationType.PHONE_NUMBER_VALIDATION -> Patterns.PHONE ValidationType.NAME_VALIDATION -> namePattern } d("REGEX ::::", regex.toString()) } fun setValidationRegex(regexString: String) { regex = Pattern.compile(regexString) } } enum class ValidationType { EMAIL_VALIDATION, MEDIUM_PASSWORD_VALIDATION, COMPLEX_PASSWORD_VALIDATION, PHONE_NUMBER_VALIDATION, NAME_VALIDATION, }
2
null
1
9
180a444afc48a1c98ffb2f2920a22959ebd0d88b
5,915
SmartForm
Apache License 2.0
skiko/src/jsWasmMain/kotlin/org/jetbrains/skiko/OsArch.js.kt
JetBrains
282,864,178
false
{"C++": 1770795, "Kotlin": 1745014, "Objective-C++": 43079, "JavaScript": 6932, "Dockerfile": 4676, "Shell": 4522, "C": 1440, "Java": 1235, "Objective-C": 471}
package org.jetbrains.skiko import org.jetbrains.skiko.w3c.window actual val hostOs: OS = detectHostOs() actual val hostArch: Arch = Arch.Unknown actual val hostId by lazy { "${hostOs.id}-${hostArch.id}" } actual val kotlinBackend: KotlinBackend get() = KotlinBackend.JS /** * A string identifying the platform on which the user's browser is running; for example: * "MacIntel", "Win32", "Linux x86_64", "Linux x86_64". * See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform - deprecated * * A string containing the platform brand. For example, "Windows". * See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/platform - new API, * but not supported in all browsers */ internal expect fun getNavigatorInfo(): String /** * In a browser, user platform can be obtained from different places: * - we attempt to use not-deprecated but experimental option first (not available in all browsers) * - then we attempt to use a deprecated option * - if both above return an empty string, we attempt to get `Platform` from `userAgent` * * Note: a client can spoof these values, so it's okay only for non-critical use cases. */ internal fun detectHostOs(): OS { val platformInfo = getNavigatorInfo().takeIf { it.isNotEmpty() } ?: window.navigator.userAgent return when { platformInfo.contains("Android", true) -> OS.Android platformInfo.contains("iPhone", true) -> OS.Ios platformInfo.contains("iOS", true) -> OS.Ios platformInfo.contains("iPad", true) -> OS.Ios platformInfo.contains("Linux", true) -> OS.Linux platformInfo.contains("Mac", true) -> OS.MacOS platformInfo.contains("Win", true) -> OS.Windows else -> OS.Unknown } }
23
C++
95
1,821
bbfaf62256fcf0255ac2b5846223f27c43dbfb00
1,771
skiko
Apache License 2.0
consumer/src/main/kotlin/au/com/dius/pact/consumer/dsl/PactDslJsonArrayContaining.kt
pact-foundation
15,750,847
false
null
package au.com.dius.pact.consumer.dsl import au.com.dius.pact.core.model.generators.Category import au.com.dius.pact.core.model.matchingrules.ArrayContainsMatcher import au.com.dius.pact.core.model.matchingrules.MatchingRuleCategory import au.com.dius.pact.core.model.matchingrules.MatchingRuleGroup import kotlin.math.max class PactDslJsonArrayContaining( val root: String, rootName: String, parent: DslPart ): PactDslJsonArray("", rootName, parent) { override fun closeArray(): DslPart { val groupBy: (Map.Entry<String, Any>) -> Int = { val index = prefixRegex.find(it.key)?.groups?.get(1)?.value index?.toInt() ?: -1 } val matchingRules = this.matchers.matchingRules.entries.groupBy(groupBy).map { (key, value) -> key to MatchingRuleCategory("body", value.associate { it.key.replace(prefixRegex, "\\$") to it.value }.toMutableMap()) } val generators = generators.categoryFor(Category.BODY)?.entries?.groupBy(groupBy)?.map { (key, value) -> key to value.associate { it.key.replace(prefixRegex, "\\$") to it.value } } this.matchers = MatchingRuleCategory("", mutableMapOf(root + rootName to MatchingRuleGroup(mutableListOf(ArrayContainsMatcher( (0 until body.size()).map { index -> Triple( index, matchingRules.find { it.first == index }?.second ?: MatchingRuleCategory("body"), generators?.find { it.first == index }?.second ?: emptyMap() ) } ))))) this.generators.categoryFor(Category.BODY)?.clear() return super.closeArray()!! } companion object { val prefixRegex = Regex("^\\[(\\d+)]") } }
338
Kotlin
466
998
74cd39cc2d2717abce6b44025dd40fc86fc64a74
1,669
pact-jvm
Apache License 2.0
features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/components/TimelineItemReactionsLayout.kt
element-hq
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.messages.impl.timeline.components import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.SubcomposeLayout import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import io.element.android.features.messages.impl.R import io.element.android.libraries.designsystem.icons.CompoundDrawables import io.element.android.libraries.designsystem.preview.ElementPreview import io.element.android.libraries.designsystem.preview.PreviewsDayNight /** * A flow layout for reactions that will show a collapse/expand button when the layout wraps over a defined number of rows. * It displays an add more button when there are greater than 0 reactions and always displays the reaction and add more button * on the same row (moving them both to a new row if necessary). * @param expandButton The expand button * @param addMoreButton The add more button * @param modifier The modifier to apply to this layout * @param itemSpacing The horizontal spacing between items * @param rowSpacing The vertical spacing between rows * @param expanded Whether the layout should display in expanded or collapsed state * @param rowsBeforeCollapsible The number of rows before the collapse/expand button is shown * @param reactions The reaction buttons */ @Composable fun TimelineItemReactionsLayout( expandButton: @Composable () -> Unit, addMoreButton: (@Composable () -> Unit)?, modifier: Modifier = Modifier, itemSpacing: Dp = 0.dp, rowSpacing: Dp = 0.dp, expanded: Boolean = false, rowsBeforeCollapsible: Int? = 2, reactions: @Composable () -> Unit, ) { SubcomposeLayout(modifier) { constraints -> // Given the placeables and returns a structure representing // how they should wrap on to multiple rows given the constraints max width. fun calculateRows(placeables: List<Placeable>): List<List<Placeable>> { val rows = mutableListOf<List<Placeable>>() var currentRow = mutableListOf<Placeable>() var rowX = 0 placeables.forEach { placeable -> val horizontalSpacing = if (currentRow.isEmpty()) 0 else itemSpacing.toPx().toInt() // If the current view does not fit on this row bump to the next if (rowX + placeable.width > constraints.maxWidth) { rows.add(currentRow) currentRow = mutableListOf() rowX = 0 } rowX += horizontalSpacing + placeable.width currentRow.add(placeable) } // If there are items in the current row remember to append it to the returned value if (currentRow.size > 0) { rows.add(currentRow) } return rows } // Used to render the collapsed state, this takes the rows inputted and adds the extra button to the last row, // removing only as many trailing reactions as needed to make space for it. fun replaceTrailingItemsWithButtons(rowsIn: List<List<Placeable>>, expandButton: Placeable, addMoreButton: Placeable?): List<List<Placeable>> { val rows = rowsIn.toMutableList() val lastRow = rows.last() val buttonsWidth = expandButton.width + itemSpacing.toPx().toInt() + (addMoreButton?.width ?: 0) var rowX = 0 lastRow.forEachIndexed { i, placeable -> val horizontalSpacing = if (i == 0) 0 else itemSpacing.toPx().toInt() rowX += placeable.width + horizontalSpacing if (rowX > constraints.maxWidth - (buttonsWidth + horizontalSpacing)) { val lastRowWithButton = lastRow.take(i) + listOfNotNull(expandButton, addMoreButton) rows[rows.size - 1] = lastRowWithButton return rows } } val lastRowWithButton = lastRow + listOfNotNull(expandButton, addMoreButton) rows[rows.size - 1] = lastRowWithButton return rows } // To prevent the add more and expand buttons from wrapping on to separate lines. // If there is one item on the last line, it moves the expand button down. fun ensureCollapseAndAddMoreButtonsAreOnTheSameRow(rowsIn: List<List<Placeable>>): List<List<Placeable>> { val lastRow = rowsIn.last().toMutableList() if (lastRow.size != 1) { return rowsIn } val rows = rowsIn.toMutableList() val secondLastRow = rows[rows.size - 2].toMutableList() val expandButtonPlaceable = secondLastRow.removeAt(secondLastRow.lastIndex) lastRow.add(0, expandButtonPlaceable) rows[rows.size - 2] = secondLastRow rows[rows.size - 1] = lastRow return rows } // Given a list of rows place them in the layout. fun layoutRows(rows: List<List<Placeable>>): MeasureResult { var width = 0 var height = 0 val placeables = rows.mapIndexed { i, row -> var rowX = 0 var rowHeight = 0 val verticalSpacing = if (i == 0) 0 else rowSpacing.toPx().toInt() val rowWithPoints = row.mapIndexed { j, placeable -> val horizontalSpacing = if (j == 0) 0 else itemSpacing.toPx().toInt() val point = IntOffset(rowX + horizontalSpacing, height + verticalSpacing) rowX += placeable.width + horizontalSpacing rowHeight = maxOf(rowHeight, placeable.height) Pair(placeable, point) } height += rowHeight + verticalSpacing width = maxOf(width, rowX) rowWithPoints }.flatten() return layout(width = width, height = height) { placeables.forEach { val (placeable, origin) = it placeable.placeRelative(origin.x, origin.y) } } } var reactionsPlaceables = subcompose(0, reactions).map { it.measure(constraints) } if (reactionsPlaceables.isEmpty()) { return@SubcomposeLayout layoutRows(listOf()) } var expandPlaceable = subcompose(1, expandButton).first().measure(constraints) // Enforce all reaction buttons have the same height val maxHeight = (reactionsPlaceables + listOf(expandPlaceable)).maxOf { it.height } val newConstrains = constraints.copy(minHeight = maxHeight) reactionsPlaceables = subcompose(2, reactions).map { it.measure(newConstrains) } expandPlaceable = subcompose(3, expandButton).first().measure(newConstrains) val addMorePlaceable = addMoreButton?.let { subcompose(4, addMoreButton).first().measure(newConstrains) } // Calculate the layout of the rows with the reactions button and add more button val reactionsAndAddMore = calculateRows(reactionsPlaceables + listOfNotNull(addMorePlaceable)) // If we have extended beyond the defined number of rows we are showing the expand/collapse ui if (rowsBeforeCollapsible?.let { reactionsAndAddMore.size > it } == true) { if (expanded) { // Show all subviews with the add more button at the end var reactionsAndButtons = calculateRows(reactionsPlaceables + listOfNotNull(expandPlaceable, addMorePlaceable)) reactionsAndButtons = ensureCollapseAndAddMoreButtonsAreOnTheSameRow(reactionsAndButtons) layoutRows(reactionsAndButtons) } else { // Truncate to `rowsBeforeCollapsible` number of rows and replace the reactions at the end of the last row with the buttons val collapsedRows = reactionsAndAddMore.take(rowsBeforeCollapsible) val collapsedRowsWithButtons = replaceTrailingItemsWithButtons(collapsedRows, expandPlaceable, addMorePlaceable) layoutRows(collapsedRowsWithButtons) } } else { // Otherwise we are just showing all items without the expand button layoutRows(reactionsAndAddMore) } } } @PreviewsDayNight @Composable internal fun TimelineItemReactionsLayoutPreview() = ElementPreview { TimelineItemReactionsLayout( expanded = false, expandButton = { MessagesReactionButton( content = MessagesReactionsButtonContent.Text( text = stringResource(id = R.string.screen_room_timeline_less_reactions) ), onClick = {}, onLongClick = {} ) }, addMoreButton = { MessagesReactionButton( content = MessagesReactionsButtonContent.Icon(CompoundDrawables.ic_compound_reaction_add), onClick = {}, onLongClick = {} ) }, reactions = { io.element.android.features.messages.impl.timeline.aTimelineItemReactions(count = 18).reactions.forEach { MessagesReactionButton( content = MessagesReactionsButtonContent.Reaction( it ), onClick = {}, onLongClick = {} ) } } ) }
263
null
75
955
31d0621fa15fe153bfd36104e560c9703eabe917
10,274
element-x-android
Apache License 2.0
app/src/main/java/io/github/ytam/jetcoinlist/extensions/DateExtension.kt
ytam
428,447,176
false
{"Kotlin": 50515}
package io.github.ytam.jetcoinlist.data.remote.extensions import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale fun Date.formatToTruncatedDateTime(): String { val sdf = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()) return sdf.format(this) } /** * Pattern: dd/MM/yyyy HH:mm:ss */ fun Date.formatToViewDateTimeDefaults(): String { val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault()) return sdf.format(this) } /** * Pattern: dd/MM/yyyy */ fun Date.formatToViewDateDefaults(): String { val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) return sdf.format(this) } /** * Pattern: HH:mm:ss */ fun Date.formatToViewTimeDefaults(): String { val sdf = SimpleDateFormat("HH:mm:ss", Locale.getDefault()) return sdf.format(this) } /** * Add field date to current date */ fun Date.add(field: Int, amount: Int): Date { Calendar.getInstance().apply { time = this@add add(field, amount) return time } }
0
Kotlin
5
20
0e865dced03932518dc9076c91120f9f85e4c528
1,056
Jet-CoinList
Apache License 2.0
Kotlin/Code/Kotlin-Encipher/src/main/java/me/ztiany/kotlin/encipher/06_AESCrypt.kt
hiloWang
203,300,702
false
null
package me.ztiany.kotlin.encipher import javax.crypto.Cipher import javax.crypto.spec.SecretKeySpec /** * AES加密解密 */ object AESCrypt { //AES加密 fun encrypt(input: String, password: String): String { //1.创建cipher对象 val cipher = Cipher.getInstance("AES") //2.初始化cipher:告诉cipher加密还是解密 //通过秘钥工厂生成秘钥 val keySpec = SecretKeySpec(password.toByteArray(), "AES") cipher.init(Cipher.ENCRYPT_MODE, keySpec) //3.加密/解密 val encrypt = cipher.doFinal(input.toByteArray()) return Base64.encode(encrypt) } //AES解密 fun decrypt(input: String, password: String): String { //1.创建cipher对象 val cipher = Cipher.getInstance("AES") //2.初始化cipher:告诉cipher加密还是解密 //通过秘钥工厂生成秘钥 val keySpec = SecretKeySpec(password.toByteArray(), "AES") cipher.init(Cipher.DECRYPT_MODE, keySpec) //3.加密/解密 val encrypt = cipher.doFinal(Base64.decode(input)) return String(encrypt) } } fun main() { val password = "<PASSWORD>"//长度16位 println("AES秘钥字节长度=" + password.toByteArray().size) //AES/CBC/NoPadding (128) :16个字节,16 * 8 = 128 位 val input = "我是原文" val encrypt = AESCrypt.encrypt(input, password) val decrypt = AESCrypt.decrypt(encrypt, password) println("加密=$encrypt") println("解密=$decrypt") }
0
null
15
4
64a637a86f734e4e80975f4aa93ab47e8d7e8b64
1,358
notes
Apache License 2.0
src/jsMain/kotlin/com/github/doyaaaaaken/kotlincsv/client/CsvReader.kt
jsoizo
200,859,123
false
null
package com.github.doyaaaaaken.kotlincsv.client import com.github.doyaaaaaken.kotlincsv.dsl.context.CsvReaderContext import com.github.doyaaaaaken.kotlincsv.dsl.context.ICsvReaderContext /** * CSV Reader class * * @author doyaaaaaken */ actual class CsvReader actual constructor( private val ctx: CsvReaderContext ) : ICsvReaderContext by ctx { /** * read csv data as String, and convert into List<List<String>> */ actual fun readAll(data: String): List<List<String>> { return CsvFileReader(ctx, StringReaderImpl(data), logger).readAllAsSequence().toList() } /** * read csv data with header, and convert into List<Map<String, String>> */ actual fun readAllWithHeader(data: String): List<Map<String, String>> { return CsvFileReader(ctx, StringReaderImpl(data), logger).readAllWithHeaderAsSequence().toList() } }
8
null
50
638
19c28835a7bde791c808fe8a7b05818122e0e28d
883
kotlin-csv
Apache License 2.0
airback-web/src/main/java/com/airback/module/project/view/risk/IRiskAddView.kt
mng222n
246,276,311
false
{"Java": 5840305, "Kotlin": 1765034, "CSS": 412765, "FreeMarker": 52912, "Shell": 10186, "HTML": 6680, "JavaScript": 5560, "Batchfile": 3219, "Dockerfile": 540}
package com.airback.module.project.view.risk import com.airback.module.project.domain.SimpleRisk import com.airback.vaadin.mvp.IFormAddView import com.airback.vaadin.web.ui.field.AttachmentUploadField /** * @author airback Ltd * @since 7.0 */ interface IRiskAddView : IFormAddView<SimpleRisk> { fun getAttachUploadField(): AttachmentUploadField }
9
null
1
1
782b1ac49b343d8c497d3dae5be3eb812d151772
356
airback
MIT License
data/reissuetoken/src/main/java/com/hankki/data/reissuetoken/service/ReissueTokenService.kt
Team-Hankki
816,081,730
false
{"Kotlin": 597927}
package com.hankki.data.reissuetoken.service import com.hankki.core.network.BaseResponse import com.hankki.data.reissuetoken.response.ReissueTokenResponseDto import retrofit2.http.Header import retrofit2.http.POST interface ReissueTokenService { @POST("/api/v1/auth/reissue") suspend fun postReissueToken( @Header("Authorization") refreshToken: String ): BaseResponse<ReissueTokenResponseDto> }
1
Kotlin
0
43
959b647e3b42fe1ae96d85c87ea7cc7ebfb74266
417
hankki-android
Apache License 2.0
app/src/main/java/com/enginebai/project/di/AppModule.kt
enginebai
213,871,671
false
null
package com.enginebai.project.di import com.enginebai.project.utils.ExceptionHandler import com.google.gson.Gson import org.koin.dsl.module val appModule = module { single { Gson() } single(createdAtStart = true) { ExceptionHandler() } }
4
Kotlin
17
133
45093866c87c5ebacb3109ca5883cfff53545a46
247
AndroidBase
MIT License
app/src/main/java/com/android/example/popularmovies/ui/detail/DetailViewModel.kt
mowdownjoe
259,617,614
false
null
package com.android.example.popularmovies.ui.detail import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.android.example.popularmovies.database.FavMovieDatabase import com.android.example.popularmovies.database.MovieEntry import kotlinx.coroutines.launch class DetailViewModel(private val app: Application, movie: MovieEntry) : AndroidViewModel(app) { private val _movie: MutableLiveData<MovieEntry> = MutableLiveData(movie) val movie: LiveData<MovieEntry> get() = _movie private val _isFav: MutableLiveData<Boolean> = MutableLiveData() val isFav: LiveData<Boolean> get() = _isFav private fun initializeIsFav() { viewModelScope.launch { val id = requireNotNull(movie.value).id _isFav.postValue(requireNotNull(FavMovieDatabase.getInstance(requireNotNull(app.applicationContext)) .favMovieDao().countMovieById(id)) > 0) } } @Synchronized fun addToFavs() { if (_isFav.value != null && !_isFav.value!!) { viewModelScope.launch { FavMovieDatabase.getInstance(app.applicationContext).favMovieDao() .addMovieToFavorites(movie.value!!) _isFav.postValue(true) } } } @Synchronized fun removeFromFavs() { if (_isFav.value != null && _isFav.value!!) { viewModelScope.launch { FavMovieDatabase.getInstance(app.applicationContext).favMovieDao() .removeMovieFromFavorites(movie.value!!) _isFav.postValue(false) } } } init { initializeIsFav() } }
0
Kotlin
0
1
81830d6741a81037933cd536eb38492869c8972a
1,818
PopularMovies
Creative Commons Attribution 4.0 International
app/src/main/java/com/example/qrcodescanner/QRcodeMainActivity.kt
kodeflap
441,297,941
false
null
package com.example.qrcodescanner import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.util.Size import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST import androidx.camera.core.Preview import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat import com.example.qrcodescanner.theme.QrCodeScannerComposeTheme class QRcodeMainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { QrCodeScannerComposeTheme { var code by remember { mutableStateOf("") } val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current val cameraProvider = remember { ProcessCameraProvider.getInstance(context) } var hasCamPermission by remember { mutableStateOf( ContextCompat.checkSelfPermission( context, Manifest.permission.CAMERA )== PackageManager.PERMISSION_GRANTED ) } val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.RequestPermission(), onResult = { granted -> hasCamPermission = granted } ) LaunchedEffect(key1 = true) { launcher.launch(Manifest.permission.CAMERA) } Column (modifier = Modifier.fillMaxSize()) { if (hasCamPermission) { AndroidView( factory = { context -> val previewView = PreviewView(context) val preview = Preview.Builder().build() val selector = CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build() preview.setSurfaceProvider(previewView.surfaceProvider) val imageAnalysis = ImageAnalysis.Builder() .setTargetResolution( Size( previewView.width, previewView.height ) ) .setBackpressureStrategy(STRATEGY_KEEP_ONLY_LATEST) .build() imageAnalysis.setAnalyzer( ContextCompat.getMainExecutor(context), QrCodeAnalyzer { result -> code = result } ) try { cameraProvider.get().bindToLifecycle( lifecycleOwner, selector, preview, imageAnalysis ) } catch (e: Exception) { e.printStackTrace() } previewView }, modifier = Modifier.weight(1f) ) Text( text = code, fontSize = 20.sp, fontWeight = FontWeight.Bold, modifier = Modifier .fillMaxWidth() .padding(32.dp) ) } } } } } }
0
Kotlin
0
0
7431a09a7325880407048fada1697337df52a195
5,233
QRCodeScanner
MIT License
src/main/kotlin/icu/windea/pls/script/codeInsight/ParadoxDefinitionDeclarationRangeHandler.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.script.codeInsight import com.intellij.codeInsight.hint.* import com.intellij.openapi.util.* import com.intellij.refactoring.suggested.* import icu.windea.pls.* import icu.windea.pls.script.psi.* /** * 定义成员的上下文信息(如:`definitionKey = {`)。 */ class ParadoxDefinitionDeclarationRangeHandler :DeclarationRangeHandler<ParadoxScriptProperty>{ override fun getDeclarationRange(container: ParadoxScriptProperty): TextRange? { if(container.definitionInfo == null) return null val valueElement = container.propertyValue ?: return null val startOffset = container.propertyKey.startOffset val endOffset = when{ valueElement is ParadoxScriptBlock -> valueElement.startOffset + 1 //包括" = {" else -> valueElement.startOffset } return TextRange.create(startOffset, endOffset) } }
9
null
5
7
037b9b4ba467ed49ea221b99efb0a26cd630bb67
810
Paradox-Language-Support
MIT License
app/src/main/java/com/example/marketnews/data/repository/MarketNewsRepository.kt
KalpeshJadvani
746,054,539
false
{"Kotlin": 30532}
package com.example.marketnews.data.repository import com.example.marketnews.data.datasource.remote.ApiService import com.example.marketnews.data.model.ApiModel import com.example.marketnews.utils.network.DataState import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject class MarketNewsRepository @Inject constructor( private val apiService: ApiService ): MarketNewsRepositoryInterface { override suspend fun getNews(): Flow<DataState<ApiModel>> = flow { emit(DataState.Loading) try { val searchResult = apiService.getNews() emit(DataState.Success(searchResult)) } catch (e: Exception) { emit(DataState.Error(e)) } } }
0
Kotlin
0
0
0a12974f3ecfd791ab262baad7bd54d619f7af2f
757
MarketNews
MIT License
db/src/main/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/db/InntektsmeldingRepository.kt
navikt
495,713,363
false
{"Kotlin": 740167, "Dockerfile": 68}
package no.nav.helsearbeidsgiver.inntektsmelding.db import io.prometheus.client.Summary import no.nav.helsearbeidsgiver.domene.inntektsmelding.Inntektsmelding import no.nav.helsearbeidsgiver.felles.EksternInntektsmelding import no.nav.helsearbeidsgiver.inntektsmelding.db.config.InntektsmeldingEntitet import no.nav.helsearbeidsgiver.inntektsmelding.db.config.InntektsmeldingEntitet.forespoerselId import no.nav.helsearbeidsgiver.inntektsmelding.db.config.InntektsmeldingEntitet.innsendt import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.and import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.update import java.time.LocalDateTime class InntektsmeldingRepository(private val db: Database) { private val requestLatency = Summary.build() .name("simba_db_inntektsmelding_repo_latency_seconds") .help("database inntektsmeldingRepo latency in seconds") .labelNames("method") .register() fun lagreInntektsmelding(forespørselId: String, inntektsmeldingDokument: Inntektsmelding) { val requestTimer = requestLatency.labels("lagreInntektsmelding").startTimer() transaction(db) { InntektsmeldingEntitet.run { insert { it[forespoerselId] = forespørselId it[dokument] = inntektsmeldingDokument it[innsendt] = LocalDateTime.now() } } }.also { requestTimer.observeDuration() } } fun hentNyeste(forespørselId: String): Inntektsmelding? { val requestTimer = requestLatency.labels("hentNyeste").startTimer() return transaction(db) { InntektsmeldingEntitet.run { select { (forespoerselId eq forespørselId) and dokument.isNotNull() }.orderBy(innsendt, SortOrder.DESC) } .firstOrNull() ?.getOrNull(InntektsmeldingEntitet.dokument) }.also { requestTimer.observeDuration() } } fun hentNyesteEksternEllerInternInntektsmelding(forespørselId: String): Pair<Inntektsmelding?, EksternInntektsmelding?>? { val requestTimer = requestLatency.labels("hentNyesteInternEllerEkstern").startTimer() return transaction(db) { InntektsmeldingEntitet.slice(InntektsmeldingEntitet.dokument, InntektsmeldingEntitet.eksternInntektsmelding).run { select { (forespoerselId eq forespørselId) }.orderBy(innsendt, SortOrder.DESC) }.limit(1).map { Pair( it[InntektsmeldingEntitet.dokument], it[InntektsmeldingEntitet.eksternInntektsmelding] ) }.firstOrNull().also { requestTimer.observeDuration() } } } fun oppdaterJournalpostId(journalpostId: String, forespørselId: String) { val requestTimer = requestLatency.labels("oppdaterJournalpostId").startTimer() transaction(db) { InntektsmeldingEntitet.update( where = { (InntektsmeldingEntitet.forespoerselId eq forespørselId) and (InntektsmeldingEntitet.journalpostId eq null) } ) { it[InntektsmeldingEntitet.journalpostId] = journalpostId } }.also { requestTimer.observeDuration() } } fun lagreEksternInntektsmelding(forespørselId: String, eksternIm: EksternInntektsmelding) { transaction(db) { InntektsmeldingEntitet.run { insert { it[forespoerselId] = forespørselId it[eksternInntektsmelding] = eksternIm it[innsendt] = LocalDateTime.now() } } } } }
13
Kotlin
0
2
5ce627827059c5f7045943ff9f2eb421b7a1db65
3,919
helsearbeidsgiver-inntektsmelding
MIT License
src/commonMain/kotlin/dev/datlag/k2k/connect/ConnectionClient.kt
DatL4g
465,054,141
false
{"Kotlin": 28200}
package dev.datlag.k2k.connect import io.ktor.network.selector.SelectorManager import io.ktor.network.sockets.aSocket import dev.datlag.k2k.Dispatcher import dev.datlag.k2k.Host import dev.datlag.tooling.async.scopeCatching import dev.datlag.tooling.async.suspendCatching import io.ktor.network.sockets.InetSocketAddress import io.ktor.network.sockets.Socket import io.ktor.network.sockets.openWriteChannel import io.ktor.network.sockets.tcpNoDelay import io.ktor.utils.io.close import io.ktor.utils.io.writeFully internal class ConnectionClient : AutoCloseable { private var socket = scopeCatching { aSocket(SelectorManager(Dispatcher.IO)).tcp() }.getOrNull() private var connectedSocket: Socket? = null suspend fun send( byteArray: ByteArray, host: Host, port: Int ) = suspendCatching { val socketAddress = InetSocketAddress(host.hostAddress, port) val useSocket = socket ?: suspendCatching { aSocket(SelectorManager(Dispatcher.IO)).tcp() }.getOrNull()?.also { socket = it } ?: return@suspendCatching connectedSocket = useSocket.connect(socketAddress) { reuseAddress = true }.also { val channel = it.openWriteChannel(autoFlush = true) channel.writeFully(byteArray, 0, byteArray.size) channel.flushAndClose() } } override fun close() { connectedSocket?.close() connectedSocket = null socket = scopeCatching { aSocket(SelectorManager(Dispatcher.IO)).tcp() }.getOrNull() } }
1
Kotlin
0
20
e67077832fd74845fdb8d0c1dcc052d40eb58dc5
1,597
Klient2Klient
Apache License 2.0
main/src/commonTest/kotlin/org/ooverkommelig/ObjectlessLifecycleTest.kt
squins
74,140,237
false
null
package org.ooverkommelig import org.ooverkommelig.definition.ObjectlessLifecycle import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertSame import kotlin.test.assertTrue class ObjectlessLifecycleTest { @Test fun initIsNotInvokedWhenSubGraphDefinitionIsCreated() { class InitNotInvokedWhenSubGraphDefinitionCreatedTestSgd : SubGraphDefinition() { var wasInitOfLifecycleInvoked = false init { lifecycle("Not invoked during sub graph definition creation test", { wasInitOfLifecycleInvoked = true }, {}) } } val sgd = InitNotInvokedWhenSubGraphDefinitionCreatedTestSgd() assertFalse(sgd.wasInitOfLifecycleInvoked) } @Test fun initIsNotInvokedWhenObjectGraphDefinitionIsCreated() { class InitNotInvokedWhenObjectGraphDefinitionCreatedTestSgd : SubGraphDefinition() { var wasInitOfLifecycleInvoked = false init { lifecycle("Not invoked during object graph definition creation test", { wasInitOfLifecycleInvoked = true }, {}) } } class InitNotInvokedWhenObjectGraphDefinitionCreatedTestOgd : ObjectGraphDefinition() { val sgd = add(InitNotInvokedWhenObjectGraphDefinitionCreatedTestSgd()) } val ogd = InitNotInvokedWhenObjectGraphDefinitionCreatedTestOgd() assertFalse(ogd.sgd.wasInitOfLifecycleInvoked) } @Test fun initIsInvokedWhenGraphIsCreated() { class InitInvokedWhenGraphCreatedTestSgd : SubGraphDefinition() { var wasInitOfLifecycleInvoked = false init { lifecycle("Invoked during graph creation test", { wasInitOfLifecycleInvoked = true }, {}) } } class InitInvokedWhenGraphCreatedTestOgd : ObjectGraphDefinition() { val sgd = add(InitInvokedWhenGraphCreatedTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = InitInvokedWhenGraphCreatedTestOgd() ogd.Graph() assertTrue(ogd.sgd.wasInitOfLifecycleInvoked) } @Test fun initsAreInvokedInDefinitionOrder() { class InitInvokedWhenGraphCreatedTestSgd : SubGraphDefinition() { val initInvocationOrderBuilder = StringBuilder() init { lifecycle("Invoked first", { initInvocationOrderBuilder.append('a') }, {}) lifecycle("Invoked second", { initInvocationOrderBuilder.append('b') }, {}) } } class InitInvokedWhenGraphCreatedTestOgd : ObjectGraphDefinition() { val sgd = add(InitInvokedWhenGraphCreatedTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = InitInvokedWhenGraphCreatedTestOgd() ogd.Graph() assertEquals("ab", ogd.sgd.initInvocationOrderBuilder.toString()) } @Test fun followingInitNotInvokedIfPrecedingFailed() { class InitInvokedWhenGraphCreatedTestSgd : SubGraphDefinition() { var wasSecondInitInvoked = false init { lifecycle("Failing init", { throw Exception() }, {}) lifecycle("Not invoked because preceding failed", { wasSecondInitInvoked = false }, {}) } } class InitInvokedWhenGraphCreatedTestOgd : ObjectGraphDefinition() { val sgd = add(InitInvokedWhenGraphCreatedTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = InitInvokedWhenGraphCreatedTestOgd() try { ogd.Graph() } catch (e: Exception) { // This is expected to happen: The first init fails. } assertFalse(ogd.sgd.wasSecondInitInvoked) } @Test fun disposeNotInvokedWhenSubGraphDefinitionIsCreated() { class DisposeNotInvokedWhenSubGraphDefinitionCreatedTestSgd : SubGraphDefinition() { var wasDisposeInvoked = false init { lifecycle("Dispose not invoked when sub graph definition created", {}, { wasDisposeInvoked = true }) } } val sgd = DisposeNotInvokedWhenSubGraphDefinitionCreatedTestSgd() assertFalse(sgd.wasDisposeInvoked) } @Test fun disposeNotInvokedWhenObjectGraphDefinitionIsCreated() { class DisposeNotInvokedWhenObjectGraphDefinitionCreatedTestSgd : SubGraphDefinition() { var wasDisposeInvoked = false init { lifecycle("Dispose not invoked when object graph definition created", {}, { wasDisposeInvoked = true }) } } class DisposeNotInvokedWhenObjectGraphDefinitionCreatedTestOgd : ObjectGraphDefinition() { val sgd = add(DisposeNotInvokedWhenObjectGraphDefinitionCreatedTestSgd()) } val ogd = DisposeNotInvokedWhenObjectGraphDefinitionCreatedTestOgd() assertFalse(ogd.sgd.wasDisposeInvoked) } @Test fun disposeNotInvokedWhenGraphIsCreated() { class DisposeNotInvokedWhenGraphCreatedTestSgd : SubGraphDefinition() { var wasDisposeInvoked = false init { lifecycle("Dispose not invoked when graph created", {}, { wasDisposeInvoked = true }) } } class DisposeNotInvokedWhenGraphCreatedTestOgd : ObjectGraphDefinition() { val sgd = add(DisposeNotInvokedWhenGraphCreatedTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = DisposeNotInvokedWhenGraphCreatedTestOgd() ogd.Graph() assertFalse(ogd.sgd.wasDisposeInvoked) } @Test fun disposeInvokedWhenGraphIsClosed() { class DisposeInvokedWhenGraphClosedTestSgd : SubGraphDefinition() { var wasDisposeInvoked = false init { lifecycle("Dispose invoked when graph closed", {}, { wasDisposeInvoked = true }) } } class DisposeInvokedWhenGraphClosedTestOgd : ObjectGraphDefinition() { val sgd = add(DisposeInvokedWhenGraphClosedTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = DisposeInvokedWhenGraphClosedTestOgd() ogd.Graph().close() assertTrue(ogd.sgd.wasDisposeInvoked) } @Test fun disposesAreInvokedInReverseDefinitionOrder() { class DisposesInvokedInReverseDefinitionOrderTestSgd : SubGraphDefinition() { val disposeInvocationOrderBuilder = StringBuilder() init { lifecycle("Invoked second", {}, { disposeInvocationOrderBuilder.append('a') }) lifecycle("Invoked first", {}, { disposeInvocationOrderBuilder.append('b') }) } } class DisposesInvokedInReverseDefinitionOrderTestOgd : ObjectGraphDefinition() { val sgd = add(DisposesInvokedInReverseDefinitionOrderTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = DisposesInvokedInReverseDefinitionOrderTestOgd() ogd.Graph().close() assertEquals("ba", ogd.sgd.disposeInvocationOrderBuilder.toString()) } @Test fun disposeIsNotInvokedIfInitFailed() { class DisposeNotInvokedIfInitFailedTestSgd : SubGraphDefinition() { var wasDisposeInvoked = false init { lifecycle("Dispose not invoked because init failed", { throw Exception() }, { wasDisposeInvoked = true }) } } class DisposeNotInvokedIfInitFailedTestOgd : ObjectGraphDefinition() { val sgd = add(DisposeNotInvokedIfInitFailedTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = DisposeNotInvokedIfInitFailedTestOgd() try { ogd.Graph().close() } catch (e: Exception) { // This is expected to happen: The first init fails. } assertFalse(ogd.sgd.wasDisposeInvoked) } @Test fun disposeOfPrecedingInitIsInvokedIfFollowingInitFails() { class DisposeOfPrecedingInitInvokedIfFollowingInitFailsTestSgd : SubGraphDefinition() { var wasDisposeOfFirstInitInvoked = false init { lifecycle("Dispose will be invoked", {}, { wasDisposeOfFirstInitInvoked = true }) lifecycle("Failing init", { throw Exception() }, {}) } } class DisposeOfPrecedingInitInvokedIfFollowingInitFailsTestOgd : ObjectGraphDefinition() { val sgd = add(DisposeOfPrecedingInitInvokedIfFollowingInitFailsTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = DisposeOfPrecedingInitInvokedIfFollowingInitFailsTestOgd() try { ogd.Graph().close() } catch (e: Exception) { // This is expected to happen: The second init fails. } assertTrue(ogd.sgd.wasDisposeOfFirstInitInvoked) } @Test fun disposeOfPrecedingLifecycleIsInvokedIfDisposeOfFollowingFails() { class DisposeOfPrecedingLifecycleInvokedIfDisposeOfFollowingFailsTestSgd : SubGraphDefinition() { var wasDisposeOfFirstInitInvoked = false init { lifecycle("Dispose will be invoked", {}, { wasDisposeOfFirstInitInvoked = true }) lifecycle("Failing dispose", {}, { throw Exception() }) } } class DisposeOfPrecedingLifecycleInvokedIfDisposeOfFollowingFailsTestOgd : ObjectGraphDefinition() { val sgd = add(DisposeOfPrecedingLifecycleInvokedIfDisposeOfFollowingFailsTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = DisposeOfPrecedingLifecycleInvokedIfDisposeOfFollowingFailsTestOgd() try { ogd.Graph().close() } catch (e: Exception) { // This is expected to happen: The second init fails. } assertTrue(ogd.sgd.wasDisposeOfFirstInitInvoked) } @Test fun errorIsLoggedIfDisposeFails() { class DisposeFailureWasErrorLoggedSpy : ObjectGraphLogger { var wasErrorLogged = false override fun errorDuringCleanUp(sourceObject: Any, operation: String, exception: Exception) { wasErrorLogged = true } } val disposeFailureSpy = DisposeFailureWasErrorLoggedSpy() class ErrorIsLoggedIfDisposeFailsTestSgd : SubGraphDefinition() { init { lifecycle("Dispose fails", {}, { throw Exception() }) } } class ErrorIsLoggedIfDisposeFailsTestOgd : ObjectGraphDefinition(ObjectGraphConfiguration(disposeFailureSpy)) { val sgd = add(ErrorIsLoggedIfDisposeFailsTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = ErrorIsLoggedIfDisposeFailsTestOgd() ogd.Graph().close() assertTrue(disposeFailureSpy.wasErrorLogged) } @Test fun sourceObjectIsObjectlessLifecycleIfDisposeFails() { class DisposeFailureSourceSpy : ObjectGraphLogger { var sourceObject: Any? = null override fun errorDuringCleanUp(sourceObject: Any, operation: String, exception: Exception) { this.sourceObject = sourceObject } } val disposeFailureSpy = DisposeFailureSourceSpy() class SourceObjectIsObjectlessLifecycleIfDisposeFailsTestSgd : SubGraphDefinition() { init { lifecycle("Dispose fails", {}, { throw Exception() }) } } class SourceObjectIsObjectlessLifecycleIfDisposeFailsTestOgd : ObjectGraphDefinition(ObjectGraphConfiguration(disposeFailureSpy)) { val sgd = add(SourceObjectIsObjectlessLifecycleIfDisposeFailsTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = SourceObjectIsObjectlessLifecycleIfDisposeFailsTestOgd() ogd.Graph().close() assertEquals(ObjectlessLifecycle::class, disposeFailureSpy.sourceObject?.let { it::class }) } @Test fun operationIsDisposeIfDisposeFails() { class DisposeFailureOperationSpy : ObjectGraphLogger { var operation: String? = null override fun errorDuringCleanUp(sourceObject: Any, operation: String, exception: Exception) { this.operation = operation } } val disposeFailureSpy = DisposeFailureOperationSpy() class OperationIsDisposeIfDisposeFailsTestSgd : SubGraphDefinition() { init { lifecycle("Dispose fails", {}, { throw Exception() }) } } class OperationIsDisposeIfDisposeFailsTestOgd : ObjectGraphDefinition(ObjectGraphConfiguration(disposeFailureSpy)) { val sgd = add(OperationIsDisposeIfDisposeFailsTestSgd()) inner class Graph : DefinitionObjectGraph() } val ogd = OperationIsDisposeIfDisposeFailsTestOgd() ogd.Graph().close() assertEquals("dispose", disposeFailureSpy.operation) } @Test fun exceptionIsNullIfDisposeFails() { class DisposeFailureExceptionSpy : ObjectGraphLogger { var exception: Exception? = null override fun errorDuringCleanUp(sourceObject: Any, operation: String, exception: Exception) { this.exception = exception } } val disposeFailureSpy = DisposeFailureExceptionSpy() val exception = Exception() // Passing "exception" explicitly because of: https://youtrack.jetbrains.com/issue/KT-8120 class ExceptionIsNullIfDisposeFailsTestSgd(private val exception: Exception) : SubGraphDefinition() { init { lifecycle("Dispose fails", {}, { throw this.exception }) } } // Passing "exception" explicitly because of: https://youtrack.jetbrains.com/issue/KT-8120 class ExceptionIsNullIfDisposeFailsTestOgd(exception: Exception) : ObjectGraphDefinition(ObjectGraphConfiguration(disposeFailureSpy)) { val sgd = add(ExceptionIsNullIfDisposeFailsTestSgd(exception)) inner class Graph : DefinitionObjectGraph() } val ogd = ExceptionIsNullIfDisposeFailsTestOgd(exception) ogd.Graph().close() assertSame(exception, disposeFailureSpy.exception) } }
1
Kotlin
0
1
fb1713f35a78f487da409f1e45ce446a5eb5461b
14,484
ooverkommelig
MIT License
compose/ui/ui-graphics/src/desktopMain/kotlin/androidx/compose/ui/graphics/DesktopCanvas.desktop.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.graphics import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.graphics.vectormath.Matrix4 import androidx.compose.ui.graphics.vectormath.isIdentity import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.util.fastForEach import org.jetbrains.skija.ClipMode as SkijaClipMode import org.jetbrains.skija.IRect as SkijaIRect import org.jetbrains.skija.Matrix33 as SkijaMatrix33 import org.jetbrains.skija.RRect as SkijaRRect import org.jetbrains.skija.Rect as SkijaRect actual typealias NativeCanvas = org.jetbrains.skija.Canvas @Suppress("UNUSED_PARAMETER") internal actual fun ActualCanvas(image: ImageAsset): Canvas { TODO("Canvas(image: ImageAsset) isn't implemented yet") } actual val Canvas.nativeCanvas: NativeCanvas get() = (this as DesktopCanvas).skija class DesktopCanvas(val skija: org.jetbrains.skija.Canvas) : Canvas { private val Paint.skija get() = (this as DesktopPaint).skija override fun save() { skija.save() } override fun restore() { skija.restore() } override fun saveLayer(bounds: Rect, paint: Paint) { skija.saveLayer( bounds.left, bounds.top, bounds.right, bounds.bottom, paint.skija ) } override fun translate(dx: Float, dy: Float) { skija.translate(dx, dy) } override fun scale(sx: Float, sy: Float) { skija.scale(sx, sy) } override fun rotate(degrees: Float) { skija.rotate(degrees) } override fun skew(sx: Float, sy: Float) { skija.skew(sx, sy) } /** * @throws IllegalStateException if an arbitrary transform is provided */ override fun concat(matrix4: Matrix4) { if (!matrix4.isIdentity()) { if (matrix4[2, 0] != 0f || matrix4[2, 1] != 0f || matrix4[2, 0] != 0f || matrix4[2, 1] != 0f || matrix4[2, 2] != 1f || matrix4[2, 3] != 0f || matrix4[3, 2] != 0f ) { throw IllegalStateException("Desktop does not support arbitrary transforms") } skija.concat( SkijaMatrix33( matrix4[0, 0], matrix4[1, 0], matrix4[3, 0], matrix4[0, 1], matrix4[1, 1], matrix4[3, 1], matrix4[0, 3], matrix4[1, 3], matrix4[3, 3] ) ) } } override fun clipRect(left: Float, top: Float, right: Float, bottom: Float, clipOp: ClipOp) { skija.clipRect(SkijaRect.makeLTRB(left, top, right, bottom), clipOp.toSkija()) } fun clipRoundRect(rect: RoundRect, clipOp: ClipOp = ClipOp.Intersect) { skija.clipRRect(rect.toSkijaRRect(), clipOp.toSkija()) } override fun clipPath(path: Path, clipOp: ClipOp) { skija.clipPath(path.asDesktopPath(), clipOp.toSkija()) } override fun drawLine(p1: Offset, p2: Offset, paint: Paint) { skija.drawLine(p1.x, p1.y, p2.x, p2.y, paint.skija) } override fun drawRect(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) { skija.drawRect(SkijaRect.makeLTRB(left, top, right, bottom), paint.skija) } override fun drawRoundRect( left: Float, top: Float, right: Float, bottom: Float, radiusX: Float, radiusY: Float, paint: Paint ) { skija.drawRRect( SkijaRRect.makeLTRB( left, top, right, bottom, radiusX, radiusY ), paint.skija ) } override fun drawOval(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) { skija.drawOval(SkijaRect.makeLTRB(left, top, right, bottom), paint.skija) } override fun drawCircle(center: Offset, radius: Float, paint: Paint) { skija.drawCircle(center.x, center.y, radius, paint.skija) } override fun drawArc( left: Float, top: Float, right: Float, bottom: Float, startAngle: Float, sweepAngle: Float, useCenter: Boolean, paint: Paint ) { skija.drawArc( left, top, right, bottom, startAngle, sweepAngle, useCenter, paint.skija ) } override fun drawPath(path: Path, paint: Paint) { skija.drawPath(path.asDesktopPath(), paint.skija) } override fun drawImage(image: ImageAsset, topLeftOffset: Offset, paint: Paint) { skija.drawImageRect( image.asDesktopImage(), SkijaIRect.makeXYWH( 0, 0, image.width, image.height ), SkijaRect.makeXYWH( topLeftOffset.x, topLeftOffset.y, image.width.toFloat(), image.height.toFloat() ), paint.skija ) } override fun drawImageRect( image: ImageAsset, srcOffset: IntOffset, srcSize: IntSize, dstOffset: IntOffset, dstSize: IntSize, paint: Paint ) { skija.drawImageRect( image.asDesktopImage(), SkijaIRect.makeXYWH( srcOffset.x, srcOffset.y, srcSize.width, srcSize.height ), SkijaRect.makeXYWH( dstOffset.x.toFloat(), dstOffset.y.toFloat(), dstSize.width.toFloat(), dstSize.height.toFloat() ), paint.skija ) } override fun drawPoints(pointMode: PointMode, points: List<Offset>, paint: Paint) { when (pointMode) { // Draw a line between each pair of points, each point has at most one line // If the number of points is odd, then the last point is ignored. PointMode.Lines -> drawLines(points, paint, 2) // Connect each adjacent point with a line PointMode.Polygon -> drawLines(points, paint, 1) // Draw a point at each provided coordinate PointMode.Points -> drawPoints(points, paint) } } override fun enableZ() = Unit override fun disableZ() = Unit private fun drawPoints(points: List<Offset>, paint: Paint) { points.fastForEach { point -> skija.drawPoint( point.x, point.y, paint.skija ) } } /** * Draw lines connecting points based on the corresponding step. * * ex. 3 points with a step of 1 would draw 2 lines between the first and second points * and another between the second and third * * ex. 4 points with a step of 2 would draw 2 lines between the first and second and another * between the third and fourth. If there is an odd number of points, the last point is * ignored * * @see drawRawLines */ private fun drawLines(points: List<Offset>, paint: Paint, stepBy: Int) { if (points.size >= 2) { for (i in 0 until points.size - 1 step stepBy) { val p1 = points[i] val p2 = points[i + 1] skija.drawLine( p1.x, p1.y, p2.x, p2.y, paint.skija ) } } } /** * @throws IllegalArgumentException if a non even number of points is provided */ override fun drawRawPoints(pointMode: PointMode, points: FloatArray, paint: Paint) { if (points.size % 2 != 0) { throw IllegalArgumentException("points must have an even number of values") } when (pointMode) { PointMode.Lines -> drawRawLines(points, paint, 2) PointMode.Polygon -> drawRawLines(points, paint, 1) PointMode.Points -> drawRawPoints(points, paint, 2) } } private fun drawRawPoints(points: FloatArray, paint: Paint, stepBy: Int) { if (points.size % 2 == 0) { for (i in 0 until points.size - 1 step stepBy) { val x = points[i] val y = points[i + 1] skija.drawPoint(x, y, paint.skija) } } } /** * Draw lines connecting points based on the corresponding step. The points are interpreted * as x, y coordinate pairs in alternating index positions * * ex. 3 points with a step of 1 would draw 2 lines between the first and second points * and another between the second and third * * ex. 4 points with a step of 2 would draw 2 lines between the first and second and another * between the third and fourth. If there is an odd number of points, the last point is * ignored * * @see drawLines */ private fun drawRawLines(points: FloatArray, paint: Paint, stepBy: Int) { // Float array is treated as alternative set of x and y coordinates // x1, y1, x2, y2, x3, y3, ... etc. if (points.size >= 4 && points.size % 2 == 0) { for (i in 0 until points.size - 3 step stepBy * 2) { val x1 = points[i] val y1 = points[i + 1] val x2 = points[i + 2] val y2 = points[i + 3] skija.drawLine( x1, y1, x2, y2, paint.skija ) } } } override fun drawVertices(vertices: Vertices, blendMode: BlendMode, paint: Paint) { // TODO(demin): implement drawVertices println("Canvas.drawVertices not implemented yet") } private fun ClipOp.toSkija() = when (this) { ClipOp.Difference -> SkijaClipMode.DIFFERENCE ClipOp.Intersect -> SkijaClipMode.INTERSECT } }
6
null
950
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
11,010
androidx
Apache License 2.0
sample/src/main/kotlin/pl/codesamurai/latte/sample/MainFragment.kt
malloth
198,045,075
false
{"Kotlin": 39223}
package pl.codesamurai.latte.sample import android.content.Intent import android.os.Bundle import android.view.View import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import pl.codesamurai.latte.sample.databinding.FragmentMainBinding class MainFragment : Fragment(R.layout.fragment_main) { private val spinnerAdapter by lazy { ArrayAdapter.createFromResource( requireContext(), R.array.items, android.R.layout.simple_spinner_item ).also { it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } } private val binding by lazy { FragmentMainBinding.bind(requireView()) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { with(binding) { with(spinner1) { adapter = spinnerAdapter setSelection(2) } button1.setOnClickListener { showSupplementaryActivity() } button2.setOnClickListener { showSupplementaryFragment() } } } private fun showSupplementaryActivity() { Intent(requireContext(), SupplementaryActivity::class.java) .also { startActivity(it) } } private fun showSupplementaryFragment() { parentFragmentManager.beginTransaction() .addToBackStack(null) .replace( R.id.fragment_container, SupplementaryFragment(), FRAGMENT_SUPPLEMENTARY ) .commit() } private companion object { const val FRAGMENT_SUPPLEMENTARY = "fragment:supl" } }
0
Kotlin
0
6
38fa56a340db59869152c4c9c86b57490da4dedb
1,732
latte
Apache License 2.0
canvas/src/main/java/com/angcyo/canvas/core/component/ControlHandler.kt
angcyo
229,037,615
false
null
package com.angcyo.canvas.core.component import android.graphics.PointF import android.graphics.RectF import android.view.MotionEvent import androidx.core.graphics.contains import com.angcyo.canvas.CanvasDelegate import com.angcyo.canvas.core.CanvasViewBox import com.angcyo.canvas.core.ICanvasTouch import com.angcyo.canvas.core.component.control.DeleteControlPoint import com.angcyo.canvas.core.component.control.LockControlPoint import com.angcyo.canvas.core.component.control.RotateControlPoint import com.angcyo.canvas.core.component.control.ScaleControlPoint import com.angcyo.canvas.core.renderer.ICanvasStep import com.angcyo.canvas.core.renderer.SelectGroupRenderer import com.angcyo.canvas.items.renderer.BaseItemRenderer import com.angcyo.canvas.items.renderer.IItemRenderer import com.angcyo.canvas.utils.mapPoint import com.angcyo.library.component.DoubleGestureDetector2 import com.angcyo.library.ex.* import kotlin.math.absoluteValue /** * 控制渲染的数据组件, 用来实现拖拽元素, 操作控制点等 * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2022/04/08 */ class ControlHandler(val canvasDelegate: CanvasDelegate) : BaseComponent(), ICanvasTouch { /**当前选中的[IItemRenderer]*/ var selectedItemRender: BaseItemRenderer<*>? = null /**绘制宽高时的偏移量*/ var sizeOffset = 4 * dp /**当前按下的控制点*/ var touchControlPoint: ControlPoint? = null //<editor-fold desc="控制点"> /**所有的控制点*/ val controlPointList = mutableListOf<ControlPoint>() /**控制点的大小, 背景圆的直径*/ var controlPointSize = 22 * dp /**图标padding的大小*/ var controlPointPadding: Int = 4 * dpi /**相对于目标点的偏移距离*/ var controlPointOffset = 2 * dp /**手指移动多少距离后, 才算作移动了*/ var translateThreshold = 3 //缓存 val _controlPointOffsetRect = emptyRectF() //按下的坐标 val _touchPoint = PointF() val _moveStartPoint = PointF() val _movePoint = PointF() var touchPointerId: Int = -1 //是否双击在同一个[BaseItemRenderer]中 var isDoubleTouch: Boolean = false /**按下时, 记录bounds 用于恢复*/ val touchItemBounds = emptyRectF() //通过bounds的计算, 来实现平移距离的计算 val moveItemBounds = emptyRectF() //是否移动过 var isTranslated = false /**双击检测*/ val doubleGestureDetector = DoubleGestureDetector2() { val itemRenderer = canvasDelegate.findItemRenderer(_touchPoint) if (itemRenderer != null) { isDoubleTouch = true canvasDelegate.dispatchDoubleTapItem(itemRenderer) } } //</editor-fold desc="控制点"> /**手势处理 * [com.angcyo.canvas.CanvasView.onTouchEvent]*/ override fun onCanvasTouchEvent(canvasDelegate: CanvasDelegate, event: MotionEvent): Boolean { doubleGestureDetector.onTouchEvent(event) var handle = isDoubleTouch var holdControlPoint = touchControlPoint val selectedItemRender = selectedItemRender when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { touchItemBounds.setEmpty() isTranslated = false touchPointerId = event.getPointerId(0) _touchPoint.set(event.x, event.y) _moveStartPoint.set(event.x, event.y) val touchPoint = _touchPoint if (selectedItemRender != null) { //已经有选中, 则查找控制点 val controlPoint = findItemControlPoint(touchPoint) touchControlPoint = controlPoint holdControlPoint = controlPoint //notify if (controlPoint != null) { selectedItemRender.onControlStart(controlPoint) } } if (touchControlPoint == null) { //未点在控制点上, 则检查是否点在[BaseItemRenderer]中 val itemRenderer = canvasDelegate.findItemRenderer(touchPoint) if (itemRenderer != null) { touchItemBounds.set(itemRenderer.getBounds()) } canvasDelegate.selectedItem(itemRenderer) } } MotionEvent.ACTION_POINTER_DOWN -> { touchControlPoint = null touchPointerId = -1 } MotionEvent.ACTION_MOVE -> { _movePoint.set(event.x, event.y) if (touchPointerId == event.getPointerId(0)) { //L.d("\ntouch:${_touchPoint}\nmove:${_movePoint}") if (touchControlPoint == null) { //没有在控制点上按压时, 才处理本体的移动 if (selectedItemRender != null) { //canvasView.canvasViewBox.matrix.invert(_tempMatrix) //canvasView.canvasViewBox.matrix.mapPoint(_movePointList[0]) //val p1 = _tempMatrix.mapPoint(_movePointList[0]) //_movePointList[0] //canvasView.canvasViewBox.matrix.mapPoint(_touchPointList[0]) //val p2 = _tempMatrix.mapPoint(_touchPointList[0])//_touchPointList[0] val p1 = canvasDelegate.getCanvasViewBox() .mapCoordinateSystemPoint(_movePoint) val p1x = p1.x val p1y = p1.y val p2 = canvasDelegate.getCanvasViewBox() .mapCoordinateSystemPoint(_moveStartPoint) val p2x = p2.x val p2y = p2.y val dx1 = p1x - p2x val dy1 = p1y - p2y if (dx1.absoluteValue > translateThreshold || dy1.absoluteValue > translateThreshold) { handle = true isTranslated = true //移动的时候不绘制控制点 canvasDelegate.controlRenderer.drawControlPoint = false canvasDelegate.smartAssistant.smartTranslateItemBy( selectedItemRender, dx1, dy1 ).apply { if (this[0]) { _moveStartPoint.x = _movePoint.x } if (this[1]) { _moveStartPoint.y = _movePoint.y } } } } } else { handle = true } } } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { //移动的时候不绘制控制点 canvasDelegate.controlRenderer.drawControlPoint = true //notify if (holdControlPoint != null) { //控制点操作结束回调 selectedItemRender?.let { it.onControlFinish(holdControlPoint) } } //平移的撤销 selectedItemRender?.let { if (!touchItemBounds.isNoSize() && isTranslated) { val itemList = mutableListOf<BaseItemRenderer<*>>() if (it is SelectGroupRenderer) { itemList.addAll(it.selectItemList) } canvasDelegate.getCanvasUndoManager().addUndoAction(object : ICanvasStep { val item = it val originBounds = RectF(touchItemBounds) val newBounds = RectF(item.getBounds()) override fun runUndo() { if (item is SelectGroupRenderer) { canvasDelegate.boundsOperateHandler.changeBoundsItemList( itemList, newBounds, originBounds ) if (canvasDelegate.getSelectedRenderer() == item) { item.updateSelectBounds() } } else { item.changeBounds { set(originBounds) } } } override fun runRedo() { if (item is SelectGroupRenderer) { canvasDelegate.boundsOperateHandler.changeBoundsItemList( itemList, originBounds, newBounds ) if (canvasDelegate.getSelectedRenderer() == item) { item.updateSelectBounds() } } else { item.changeBounds { set(newBounds) } } } }) } } isDoubleTouch = false touchControlPoint = null touchPointerId = -1 } } //控制点 selectedItemRender?.let { holdControlPoint?.onTouch(canvasDelegate, it, event) } //result val result = selectedItemRender != null || holdControlPoint != null return result && handle } /**通过坐标, 找到控制点 * [touchPoint] 视图坐标点*/ fun findItemControlPoint(touchPoint: PointF): ControlPoint? { //val point = canvasViewBox.mapCoordinateSystemPoint(touchPoint, _tempPoint) controlPointList.forEach { if (it.enable && it.bounds.contains(touchPoint)) { return it } } return null } /**计算4个控制点的矩形位置坐标 * [itemRect] 目标元素坐标系的矩形坐标*/ fun calcControlPointLocation(canvasViewBox: CanvasViewBox, itemRenderer: BaseItemRenderer<*>) { //将[bounds]转换成视图坐标 val visualBounds = itemRenderer.getVisualBounds() _controlPointOffsetRect.set(visualBounds) //在原目标位置, 进行矩形的放大 val inset = controlPointOffset + controlPointSize / 2 _controlPointOffsetRect.inset(-inset, -inset) val closeControl = controlPointList.find { it.type == ControlPoint.POINT_TYPE_DELETE } ?: createControlPoint(ControlPoint.POINT_TYPE_DELETE) val rotateControl = controlPointList.find { it.type == ControlPoint.POINT_TYPE_ROTATE } ?: createControlPoint(ControlPoint.POINT_TYPE_ROTATE) val scaleControl = controlPointList.find { it.type == ControlPoint.POINT_TYPE_SCALE } ?: createControlPoint(ControlPoint.POINT_TYPE_SCALE) val lockControl = controlPointList.find { it.type == ControlPoint.POINT_TYPE_LOCK } ?: createControlPoint(ControlPoint.POINT_TYPE_LOCK) //矩形是否翻转了 val bounds = itemRenderer.getBounds() val isFlipHorizontal = bounds.isFlipHorizontal val isFlipVertical = bounds.isFlipVertical val left = if (isFlipHorizontal) _controlPointOffsetRect.right else _controlPointOffsetRect.left val right = if (isFlipHorizontal) _controlPointOffsetRect.left else _controlPointOffsetRect.right val top = if (isFlipVertical) _controlPointOffsetRect.bottom else _controlPointOffsetRect.top val bottom = if (isFlipVertical) _controlPointOffsetRect.top else _controlPointOffsetRect.bottom updateControlPoint( closeControl, canvasViewBox, itemRenderer, left, top ) updateControlPoint( rotateControl, canvasViewBox, itemRenderer, right, top, ) updateControlPoint( scaleControl, canvasViewBox, itemRenderer, right, bottom, ) updateControlPoint( lockControl, canvasViewBox, itemRenderer, left, bottom, ) closeControl.enable = itemRenderer.isSupportControlPoint(ControlPoint.POINT_TYPE_DELETE) rotateControl.enable = itemRenderer.isSupportControlPoint(ControlPoint.POINT_TYPE_ROTATE) scaleControl.enable = itemRenderer.isSupportControlPoint(ControlPoint.POINT_TYPE_SCALE) lockControl.enable = itemRenderer.isSupportControlPoint(ControlPoint.POINT_TYPE_LOCK) controlPointList.clear() controlPointList.add(closeControl) controlPointList.add(rotateControl) controlPointList.add(scaleControl) controlPointList.add(lockControl) } fun <T : ControlPoint> findControlPoint(type: Int): T? { return controlPointList.find { it.type == type } as? T } /**是否锁定了宽高缩放比例*/ fun isLockScaleRatio(): Boolean { return findControlPoint<LockControlPoint>(ControlPoint.POINT_TYPE_LOCK)?.isLockScaleRatio ?: true } fun setLockScaleRatio(lock: Boolean = true) { findControlPoint<LockControlPoint>(ControlPoint.POINT_TYPE_LOCK)?.isLockScaleRatio = lock findControlPoint<ScaleControlPoint>(ControlPoint.POINT_TYPE_SCALE)?.isLockScaleRatio = lock selectedItemRender?.updateLockScaleRatio(lock) } /**创建一个控制点*/ fun createControlPoint(type: Int): ControlPoint { return when (type) { ControlPoint.POINT_TYPE_DELETE -> DeleteControlPoint() ControlPoint.POINT_TYPE_ROTATE -> RotateControlPoint() ControlPoint.POINT_TYPE_SCALE -> ScaleControlPoint() ControlPoint.POINT_TYPE_LOCK -> LockControlPoint() else -> ControlPoint() }.apply { this.type = type } } /**更新控制点的位置*/ fun updateControlPoint( controlPoint: ControlPoint, canvasViewBox: CanvasViewBox, itemRenderer: BaseItemRenderer<*>, x: Float, y: Float ) { _tempPoint.set(x, y) //旋转后的点坐标 _tempMatrix.reset() _tempMatrix.postRotate( itemRenderer.rotate, _controlPointOffsetRect.centerX(), _controlPointOffsetRect.centerY() ) _tempMatrix.mapPoint(_tempPoint, _tempPoint) val point = _tempPoint controlPoint.bounds.set( point.x - controlPointSize / 2, point.y - controlPointSize / 2, point.x + controlPointSize / 2, point.y + controlPointSize / 2 ) } }
0
Kotlin
4
1
d36e194a268a40c63c23c6a3088661a4fd0e02aa
15,139
UICore
MIT License
src/main/java/com/vladsch/md/nav/vcs/GitHubLinkResolver.kt
vsch
32,095,357
false
{"Kotlin": 2420465, "Java": 2294749, "HTML": 131988, "JavaScript": 68307, "CSS": 64158, "Python": 486}
// Copyright (c) 2015-2020 <NAME> <<EMAIL>> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("MemberVisibilityCanBePrivate") package com.vladsch.md.nav.vcs import com.intellij.ide.BrowserUtil import com.intellij.openapi.file.exclude.ProjectPlainTextFileTypeManager import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.fileTypes.PlainTextFileType import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import com.vladsch.flexmark.util.sequence.Escaping import com.vladsch.md.nav.parser.api.MdLinkMapProvider import com.vladsch.md.nav.parser.cache.MdCachedResolvedLinks import com.vladsch.md.nav.parser.cache.data.transaction.IndentingLogger import com.vladsch.md.nav.psi.element.MdFile import com.vladsch.md.nav.psi.element.MdLinkElement import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.settings.MdRenderingProfile import com.vladsch.md.nav.settings.MdRenderingProfileManager import com.vladsch.md.nav.util.* import com.vladsch.plugin.util.* import icons.MdIcons import java.util.* import java.util.regex.Pattern import javax.swing.Icon import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.text.endsWith import kotlin.text.removePrefix import kotlin.text.removeSuffix import kotlin.text.startsWith class GitHubLinkResolver(projectResolver: ProjectResolver , containingFile: FileRef , renderingProfile: MdRenderingProfile? = null , branchOrTag: String? = null ) : MdLinkResolver(projectResolver, containingFile, branchOrTag) { companion object { private val LOG_CACHE_DETAIL = IndentingLogger.LOG_COMPUTE_DETAIL const val GITHUB_BLOB_NAME: String = "blob" const val GITHUB_FORK_NAME: String = "fork" const val GITHUB_GRAPHS_NAME: String = "graphs" const val GITHUB_ISSUES_NAME: String = "issues" const val GITHUB_LABELS_NAME: String = "labels" const val GITHUB_MILESTONES_NAME: String = "milestones" const val GITHUB_PULLS_NAME: String = "pulls" const val GITHUB_PULSE_NAME: String = "pulse" const val GITHUB_RAW_NAME: String = "raw" const val GITHUB_WIKI_NAME: String = "wiki" // NOTE: keep alphabetically sorted. These are not re-sorted after match @JvmField val GITHUB_LINKS: Array<String> = arrayOf( GITHUB_BLOB_NAME, GITHUB_FORK_NAME, GITHUB_GRAPHS_NAME, GITHUB_ISSUES_NAME, GITHUB_LABELS_NAME, GITHUB_MILESTONES_NAME, GITHUB_PULLS_NAME, GITHUB_PULSE_NAME, GITHUB_RAW_NAME, GITHUB_WIKI_NAME ) @JvmField val GITHUB_NON_FILE_LINKS: Array<String> = arrayOf( GITHUB_FORK_NAME, GITHUB_GRAPHS_NAME, GITHUB_ISSUES_NAME, GITHUB_LABELS_NAME, GITHUB_MILESTONES_NAME, GITHUB_PULLS_NAME, GITHUB_PULSE_NAME ) @JvmField val GITHUB_TARGET_LINKS: Array<String> = arrayOf( GITHUB_FORK_NAME, GITHUB_GRAPHS_NAME, GITHUB_ISSUES_NAME, GITHUB_LABELS_NAME, GITHUB_MILESTONES_NAME, GITHUB_PULLS_NAME, GITHUB_PULSE_NAME, GITHUB_WIKI_NAME ) @JvmStatic fun isGitHubLink(link: String): Boolean { return link in GITHUB_LINKS } @JvmStatic fun isGitHubNonFileLink(link: String): Boolean { return link in GITHUB_NON_FILE_LINKS } @JvmStatic fun wantFlags(linkRef: LinkRef): Int { return if (linkRef.isURI && linkRef.isLocal) Want.invoke(Local.URI, Remote.URI) else if (linkRef.isURL) Want.invoke(Local.URL, Remote.URL, Links.URL) else if (linkRef.isLocal && linkRef.isAbsolute) Want.invoke(Local.ABS, Remote.ABS) else Want(Local.REL, Remote.REL, Links.REL) } @JvmStatic fun wantFlagsWithRaw(linkRef: LinkRef): Int { return if (linkRef.isLocal && linkRef.isAbsolute) Want.invoke(Local.ABS, Remote.ABS) else if (linkRef.isURI && linkRef.isLocal) Want.invoke(Local.URI, Remote.URI) else if (linkRef.isURL) Want.invoke(Local.URI, Remote.RAW) // FIX: add RAW_REL and change RAW to RAW_URL else Want(Local.REL, Remote.REL, Links.REL) } // FEATURE: add ignored sites to annotation config private val IGNORED_SITES = Pattern.compile("^https?://(?:[a-zA-z_-]+\\.)*(?:example\\.com)") @JvmStatic fun isIgnoredSite(url: String): Boolean { return IGNORED_SITES.matcher(url).find() } @JvmStatic fun getIcon(url: String): Icon? { @Suppress("NAME_SHADOWING") return when { url.startsWith("ftp://") -> MdIcons.LinkTypes.Ftp url.startsWith("jetbrains://") -> MdIcons.LinkTypes.JetBrains url.startsWith("upsource://") -> MdIcons.LinkTypes.Upsource url.startsWith("https://upsource.jetbrains.com/") -> MdIcons.LinkTypes.Upsource url.startsWith("https://github.com/") || url == "https://github.com" -> MdIcons.LinkTypes.GitHub url.startsWith("http://github.com/") || url == "http://github.com" -> MdIcons.LinkTypes.GitHub url.startsWith("https://raw.githubusercontent.com/") -> MdIcons.LinkTypes.GitHub url.startsWith("http://raw.githubusercontent.com/") -> MdIcons.LinkTypes.GitHub url.startsWith("mailto:") -> MdIcons.LinkTypes.Mail url.matches("^.+@.+\\.\\+$".toRegex()) -> MdIcons.LinkTypes.Mail PathInfo.isURL(url) -> MdIcons.LinkTypes.Web PathInfo.isCustomURI(url) -> MdIcons.LinkTypes.CustomUri else -> { MdIcons.LinkTypes.Unknown } } } } fun getIcon(linkRef: LinkRef): Icon? { @Suppress("NAME_SHADOWING") var linkRef = linkRef if (linkRef.isRelative || linkRef.isRepoRelative) { // should be a github link or unresolved for (link in GITHUB_NON_FILE_LINKS) { if (linkRef.filePath.matches("^.*../$link\\b.*$".toRegex())) { val resolved = resolve(linkRef, Want(Local.NONE, Remote.NONE, Links.URL), null) if (resolved is LinkRef) linkRef = resolved break } } } return getIcon(linkRef.filePath) } constructor(virtualFile: VirtualFile, project: Project) : this(MdLinkResolverManager.getInstance(project), FileRef(virtualFile.path, virtualFile), null) constructor(virtualFile: VirtualFile, project: Project, renderingProfile: MdRenderingProfile? = null) : this(MdLinkResolverManager.getInstance(project), FileRef(virtualFile.path, virtualFile), renderingProfile) constructor(projectFileRef: ProjectFileRef) : this(MdLinkResolverManager.getInstance(projectFileRef.project), projectFileRef, null) constructor(projectFileRef: ProjectFileRef, renderingProfile: MdRenderingProfile? = null) : this(MdLinkResolverManager.getInstance(projectFileRef.project), projectFileRef, renderingProfile) constructor(psiFile: PsiFile) : this(MdLinkResolverManager.getInstance(psiFile.originalFile.project), FileRef(MdPsiImplUtil.getVirtualFilePath(psiFile), MdPsiImplUtil.getVirtualFile(psiFile)), null) constructor(psiFile: PsiFile, renderingProfile: MdRenderingProfile? = null) : this(MdLinkResolverManager.getInstance(psiFile.originalFile.project), FileRef(MdPsiImplUtil.getVirtualFilePath(psiFile), MdPsiImplUtil.getVirtualFile(psiFile)), renderingProfile) constructor(psiElement: PsiElement) : this(psiElement.containingFile.originalFile, null) constructor(psiElement: PsiElement, renderingProfile: MdRenderingProfile? = null) : this(psiElement.containingFile.originalFile, renderingProfile) internal val linkInspector: GitHubLinkInspector by lazy { GitHubLinkInspector(this) } private var matcher: GitHubLinkMatcher? = null val renderingProfile: MdRenderingProfile by lazy { renderingProfile ?: MdRenderingProfileManager.getInstance(project).getRenderingProfile(containingFile.virtualFile) } private val includeDirsInCompletion: Boolean by lazy { var includeDirsInCompletion = false for (provider in MdLinkMapProvider.EXTENSIONS.value) { val includeDirs = provider.getIncludeDirsInCompletion(renderingProfile) if (includeDirs != null) { includeDirsInCompletion = includeDirs break } } includeDirsInCompletion } val linkEncodingExclusionMap: Map<String, String>? by lazy { var linkExclusionMap: Map<String, String>? = null if (project != null) { val psiFile = containingFile.psiFile(project) if (psiFile != null) { for (provider in MdLinkMapProvider.EXTENSIONS.value) { linkExclusionMap = provider.getLinkExclusionMap(renderingProfile) if (linkExclusionMap != null) { break } } } } linkExclusionMap } override fun linkEncodingExclusionMap(): Map<String, String>? { return linkEncodingExclusionMap } override fun renderingProfile(): MdRenderingProfile? { return renderingProfile } fun getAltLinkFormatText(linkElement: MdLinkElement<*>, options: Int, wantShorter: Boolean, nullifyIfSame: Boolean, destResolver: GitHubLinkResolver): String? { val linkRef = linkElement.linkRef val altLinkFormatText = getAltLinkFormatText(linkRef, options, wantShorter, destResolver) return altLinkFormatText.nullIf(nullifyIfSame && altLinkFormatText == linkRef.filePathWithAnchor) } fun getAltLinkFormatText(linkRef: LinkRef, options: Int, wantShorter: Boolean, destResolver: GitHubLinkResolver): String { assertContainingFile(linkRef) val altRef = getAltLinkFormat(linkRef, options, wantShorter, destResolver) ?: return linkRef.filePathWithAnchor var wantExtension = true if (altRef is LinkRef && altRef.targetRef != null && altRef.targetRef.isWikiPage) { val anchorInfo = PathInfo(linkRef.anchor.orEmpty()) if (linkRef.anchor != null && anchorInfo.isWikiPageExt) { if (!wasAnchorUsedInMatch(linkRef, altRef.targetRef)) { wantExtension = false } } } val linkRefText = if (altRef is LinkRef && !altRef.anchorText.isEmpty() && altRef.anchorText != "#") if (wantExtension) altRef.filePathWithAnchor else altRef.filePathNoExtWithAnchor else if (wantExtension) altRef.filePath else altRef.filePathNoExt val mapped = denormalizedLinkRef(linkRefText) return mapped } fun getAltLinkFormat(linkRef: LinkRef, options: Int, wantShorter: Boolean, destResolver: GitHubLinkResolver): PathInfo? { assertContainingFile(linkRef) var useLinkRef = linkRef var altRef = resolve(useLinkRef, options, null) ?: return null if (altRef.isFileURI && wantLocalType(options) == Local.URI) { return altRef } else if (altRef.isURL && wantRemoteType(options) == Remote.URL) { return altRef } if (altRef is LinkRef) { if (destResolver !== this && altRef.targetRef != null) { // need to map to another target file useLinkRef = destResolver.createLinkRefForTarget(linkRef, altRef.targetRef!!, false) altRef = destResolver.resolve(useLinkRef, options, null) ?: return altRef } } if (useLinkRef.containingFile.isWikiHomePage && altRef.filePath.startsWith("../")) { altRef = PathInfo(altRef.filePath.removePrefix("../")) } val altLinkText = if (altRef is LinkRef && !altRef.anchorText.isEmpty() && altRef.anchorText != "#") altRef.filePathWithAnchor else altRef.filePath if (altLinkText == linkRef.filePathWithAnchor) return altRef val oldFormat = wantFlags(useLinkRef) if (oldFormat == options && destResolver === this && (!wantShorter || altLinkText.length >= linkRef.filePathWithAnchor.length)) return null // it is a reference and it has an image target then only raw should be used // here we need to add this to the intention that handles references, it needs to change the linkref // if (linkRefInfo.isImageExt) { // val imageLinkRef = ImageLinkRef.from(linkRefInfo) // // if (imageLinkRef != null) { // altRef = resolver.resolve(imageLinkRef, Want.invoke(Local.URL, Remote.URL), looseTargetRefs) // if (altRef != null) linkVarieties.put(if (altRef is LinkRef) (altRef as LinkRef).filePathWithAnchor else altRef.filePath, Want.FileType.URL) // } // } else { // altRef = resolver.resolve(linkRefInfo, Want.invoke(Local.URL, Remote.URL), looseTargetRefs) // if (altRef != null) linkVarieties.put(if (altRef is LinkRef) (altRef as LinkRef).filePathWithAnchor else altRef.filePath, Want.FileType.URL) // } return altRef } fun changeLinkRefContainingFile(linkRef: LinkRef, destinationResolver: GitHubLinkResolver, wikiToLinkRef: Boolean): LinkRef { val targetRef = resolve(linkRef, Want(Local.REF, Remote.REF, Links.URL), null) as? FileRef ?: return linkRef return destinationResolver.createLinkRefForTarget(linkRef, targetRef, wikiToLinkRef) } // call on destination file's resolver fun createLinkRefForTarget(linkRef: LinkRef, targetRef: FileRef, wikiToLinkRef: Boolean): LinkRef { var newLinkRef: LinkRef = linkRef if (!linkRef.isURL && !linkRef.isURI) { // update the link ref according to the new destination for the file var makeLinkRef = false newLinkRef = linkRef.withTargetRef(targetRef) // now we can change the links based on change of target path and new containing file reference if (linkRef is WikiLinkRef) { // the file can be moved out of reach, we may need to change the wiki link to explicit when that happens if (!wikiToLinkRef && containingFile.isUnderWikiDir && targetRef.isUnderWikiDir && containingFile.wikiDir == targetRef.wikiDir) return newLinkRef // no change, still in same wiki directory // change to explicit link newLinkRef = LinkRef.from(newLinkRef, linkEncodingExclusionMap) makeLinkRef = true } var denormalizeLink = true val movedLink = if (makeLinkRef) { if (containingFile.fileName == targetRef.fileName) { // self reference, keep anchor, wiki links don't use directory paths LinkRef(containingFile, "", newLinkRef.anchor, targetRef, false) } else { // create new link ref LinkRef(containingFile, "", null, targetRef, false) } } else if (containingFile.filePath == targetRef.filePath) { // self reference if (containingFile.isWikiPage) { denormalizeLink = false // self reference in wiki page, ignore path LinkRef(containingFile, "", newLinkRef.anchor, targetRef, false) } else { LinkRef(containingFile, "", newLinkRef.anchor, targetRef, false) } } else if (targetRef.isWikiPage && containingFile.isWikiPage && newLinkRef.fileName == targetRef.fileName) { // reference in wiki page, ignore path denormalizeLink = false LinkRef(containingFile, "", newLinkRef.anchor, targetRef, false) } else { LinkRef(containingFile, "", newLinkRef.anchor, targetRef, false) } newLinkRef = if (denormalizeLink) { val preservedLinkFormat = preserveLinkFormat(linkRef, movedLink) denormalizedLinkRef(preservedLinkFormat) } else movedLink } return newLinkRef } fun getMatcher(linkRef: LinkRef): GitHubLinkMatcher { var matcher_ = matcher val normLinkRef = normalizedLinkRef(linkRef) if (matcher_ === null || matcher_.originalLinkRef != normLinkRef) { matcher_ = GitHubLinkMatcher(projectResolver, normLinkRef, linkEncodingExclusionMap) matcher = matcher_ } return matcher_ } fun getLastMatcher(): GitHubLinkMatcher? { return matcher } fun resetLastMatcher() { matcher = null } // TEST: this needs tests to make sure it works override fun isResolvedTo(linkRef: LinkRef, targetRef: FileRef, withExtForWikiPage: Boolean?, branchOrTag: String?): Boolean { assertContainingFile(linkRef) val linkRefText = linkAddress(linkRef, targetRef, withExtForWikiPage, branchOrTag, "", true) return linkRef.filePath.equals(linkRefText, ignoreCase = targetRef.isWikiPage && !linkRef.hasExt) } override fun isResolved(linkRef: LinkRef, options: Int, inList: List<PathInfo>?): Boolean { assertContainingFile(linkRef) return resolve(linkRef, options, inList) != null } fun preserveLinkFormat(linkRef: LinkRef, newLinkRef: LinkRef): LinkRef { assertContainingFile(newLinkRef) // FIX: when cross repository resolution is implemented, try to preserve the format but use one that will resolve if preserving it will not resolve the link var flags = wantFlags(linkRef) if (newLinkRef.targetRef == null) { val resolvedLinkRef = resolve(newLinkRef, flags, null) if (resolvedLinkRef is LinkRef) return resolvedLinkRef } else { // have target, do we have a link path? var useLinkRef = newLinkRef var useRaw = false if (newLinkRef.filePath.isEmpty()) { // no, make it from the linkRef but to the new target stored in newLinkRef // strip extension from links to markdown files when they move from non-wiki to wiki directory // here we need to know if the target file has not gone from non-wiki to wiki status, because it has an extension, in which case we have to preserve it // if it went from non-wiki to wiki, either the containing file is a wiki page and the link does not leave the wiki, there is no blob/ or raw/ in it, or the old link would have contained /wiki/ or ended in /wiki, in either case // we keep the extension val hasExt = if (newLinkRef.targetRef.isUnderWikiDir) wikiLinkHasRealExt(linkRef, newLinkRef.targetRef) else linkRef.hasExt useRaw = newLinkRef.targetRef.isRawFile || linkRef.filePath.contains("/raw/") || if (linkRef.containingFile.isWikiPage) hasExt && !linkRef.contains("/blob/") else hasExt && (linkRef.filePath.contains("/wiki/") || linkRef.filePath.endsWith("/wiki")) val useExtForWiki = useRaw || !newLinkRef.targetRef.isWikiPage if (useRaw) flags = wantFlagsWithRaw(linkRef) val linkAddress = linkAddress(newLinkRef.replaceFilePath(linkRef.filePath, true), newLinkRef.targetRef, useExtForWiki, null, newLinkRef.anchor, linkRef.filePath.isEmpty()) useLinkRef = newLinkRef.replaceFilePath(linkAddress, true, false) } if (linkRef.isURI || linkRef.isAbsolute && linkRef.isLocal) { return processMatchOptions(useLinkRef, newLinkRef.targetRef, flags) as LinkRef? ?: useLinkRef } else if (useRaw) { // here we change ../blob/ to ../raw/ if (useLinkRef.filePath.contains("../blob/")) { useLinkRef = useLinkRef.replaceFilePath(useLinkRef.filePath.replace("../blob/", "../raw/"), true) } else if (!useLinkRef.filePath.startsWith('/') && !newLinkRef.targetRef.isUnderWikiDir && !useLinkRef.containingFile.isWikiPage && !useLinkRef.isURI) { // need to prefix it ../../raw/ but only after the initial ../../, would be nice if I added a comment on when this is needed if (!useLinkRef.filePath.startsWith("../../../")) { val pos = useLinkRef.filePath.lastIndexOf("../") if (pos < 0) { useLinkRef = useLinkRef.replaceFilePath("../../raw/master/" + useLinkRef.filePath, true) } else { useLinkRef = useLinkRef.replaceFilePath(useLinkRef.filePath.substring(0, pos + "../".length) + "../../raw/master/" + useLinkRef.filePath.substring(pos + "../".length), true) } } } } // must be correct as is return useLinkRef } return linkRef } override fun resolve(linkRef: LinkRef, options: Int, inList: List<PathInfo>?): PathInfo? { assertContainingFile(linkRef) // FIX: if only want local, then can try to resolve external links to local file refs if they map, for that need to parse the // LinkRef's URL file path and remove the repoPrefix for non-Wiki and wikiRepoPrefix for wiki files, then prefix the result with the corresponding basePath var linkRef_ = normalizedLinkRef(linkRef) var targetRef: PathInfo = linkRef_ var opts = options if (linkRef_.isSelfAnchor) { if (linkRef_ is WikiLinkRef && linkRef_.filePath.isEmpty()) { // here it is a pure anchor wiki link, which does not resolve if (!wantCompletionMatch(options)) return null } targetRef = linkRef_.containingFile linkRef_ = linkRef_.replaceFilePath(if (linkRef_.hasExt || !linkRef_.containingFile.isUnderWikiDir) targetRef.fileName else targetRef.fileNameNoExt, true, true) } if (linkRef_.isURI || linkRef_.isAbsolute) { val relPath = absoluteToRelativeLink(linkRef_) if (!linkRef_.isURI) opts = opts or LINK_REF_WAS_REPO_REL else opts = opts or LINK_REF_WAS_URI linkRef_ = relPath } val file = if (project != null) containingFile.psiFile(project) as? MdFile else null if (file != null) { var cachedLink = MdCachedResolvedLinks.getCachedLink(file, linkRef) if (cachedLink == null && linkRef != linkRef_) { // try mapped cachedLink = MdCachedResolvedLinks.getCachedLink(file, linkRef_) } if (cachedLink != null) { val resolved: PathInfo? = processMatchOptions(linkRef_, cachedLink, opts) if (resolved != null) { LOG_CACHE_DETAIL.debug { "Resolved cached link: ${cachedLink.filePath} to ${resolved.filePath}" } // FIX: the cached link may have the wrong address format since this is not saved during caching return resolved } } else if (MdCachedResolvedLinks.hasCachedLink(file, linkRef)) { // this one is not defined so we save time by not resolving return null; } } if (!linkRef_.isAbsolute || !linkRef_.isURI || linkRef_.filePath.startsWith("/")) { // resolve the relative link as per requested options // FIX: use cached resolved links and update values if none were found there val matches = getMatchedRefs(linkRef_, null, opts, inList) val resolvedRef = (if (matches.isNotEmpty()) matches[0] else null) ?: return null if (file != null) { MdCachedResolvedLinks.addCachedLink(file, linkRef, resolvedRef) } return resolvedRef } if (file != null) { MdCachedResolvedLinks.addCachedLink(file, linkRef, targetRef) } return processMatchOptions(linkRef_, targetRef, opts) } override fun isAbsoluteUnchecked(linkRef: PathInfo): Boolean { if (linkRef.isURL && linkRef is LinkRef) { val normalized = absoluteToRelativeLink(linkRef) if (!normalized.isURL) return false } if (linkRef.isFileURI && !linkRef.isURL) { // file:// only check if part of module or project if (linkRef is LinkRef) { if (PathInfo.removeFileUriPrefix(linkRef.path).startsWith(projectResolver.projectBasePath.suffixWith("/"))) { return false } else { // use the modules val virtualFile = linkRef.virtualFile val project = projectResolver.project if (virtualFile != null && project != null) { val fileIndex = com.intellij.openapi.roots.ProjectRootManager.getInstance(project).fileIndex val module = fileIndex.getModuleForFile(virtualFile) if (module != null) { // if target ref in module under module root dir then it can be relative return false } } } } return true } else { if (BrowserUtil.isAbsoluteURL(linkRef.filePath)) { return true } } return false } override fun isExternalUnchecked(linkRef: LinkRef): Boolean { val vcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) return linkRef.isExternal && (vcsRoot == null || vcsRoot.baseUrl == null || !linkRef.filePath.toLowerCase().startsWith(vcsRoot.baseUrl.toLowerCase())) } override fun multiResolve(linkRef: LinkRef, options: Int, inList: List<PathInfo>?): List<PathInfo> { assertContainingFile(linkRef) var relLink = normalizedLinkRef(linkRef) var opts = options if (relLink.isURI || relLink.isAbsolute) { val relPath = absoluteToRelativeLink(relLink) if (relPath.isURL) { return listOf<PathInfo>(relPath) } else { opts = if (!relLink.isURI) opts or LINK_REF_WAS_REPO_REL else opts or LINK_REF_WAS_URI relLink = relPath } } return getMatchedRefs(relLink, null, opts, inList) } // FIX: change this to take an exact resolve list and a loose matched list so that // all types of issues could be analyzed, not just based on single target override fun inspect(linkRef: LinkRef, targetRef: FileRef, referenceId: Any?): List<InspectionResult> { assertContainingFile(linkRef) val normLinkRef = normalizedLinkRef(linkRef) return linkInspector.inspect(normLinkRef, targetRef, referenceId) } fun getTargetFileTypes(extensions: List<String>?, completionMatch: Boolean, includeNoExtFiles: Boolean): HashSet<FileType> { val typeSet = HashSet<FileType>() if (extensions == null || project == null) return typeSet val typeManager = FileTypeManager.getInstance() as FileTypeManagerImpl val registeredFileTypes = FileTypeRegistry.getInstance().registeredFileTypes var allExtensionResolved = true val unresolvedExtensions: HashSet<String> = HashSet() for (fileType in registeredFileTypes) { val typeExtensions = typeManager.getAssociations(fileType) outer@ for (ext in extensions) { if (ext.isEmpty()) { allExtensionResolved = false unresolvedExtensions.add(ext) continue } val bareExt = if (ext[0] == '.') ext.substring(1) else ext val extSuffix = ".$bareExt" // does not work for nested extensions such as blade.php, will not find it since we are looking for .php // val targetFileType = typeManager.getFileTypeByExtension(ext.removePrefix(".")) // typeSet.add(targetFileType) val extensionResolved = false for (typeExt in typeExtensions) { val typeText = typeExt.presentableString if (typeText.isEmpty()) { typeSet.add(fileType) break@outer } else { if (typeText.endsWith(extSuffix, ignoreCase = true)) { typeSet.add(fileType) break@outer } if (completionMatch && typeText.length > bareExt.length) { val pos = typeText.lastIndexOf('.') if (pos >= 0 && typeText.substring(pos + 1).startsWith(bareExt, ignoreCase = true)) { typeSet.add(fileType) break@outer } } } } if (!extensionResolved && ext != "md") { allExtensionResolved = false unresolvedExtensions.add(ext) } } } if (includeNoExtFiles || !allExtensionResolved) { // these are text val targetFileType = typeManager.getFileTypeByExtension("txt") typeSet.add(targetFileType) } return typeSet } internal class MatchList() : MutableList<PathInfo> { private val list = ArrayList<PathInfo>() private val matchSet = HashMap<String, PathInfo>() override val size: Int get() = list.size private fun adding(element: PathInfo) { matchSet[element.filePath] = element } private fun addingAll(elements: Collection<PathInfo>) { elements.forEach { matchSet[it.filePath] = it } } fun getList(): ArrayList<PathInfo> { return list } override fun contains(element: PathInfo): Boolean { return matchSet.containsKey(element.filePath) } override fun containsAll(elements: Collection<PathInfo>): Boolean = list.containsAll(elements) override fun get(index: Int): PathInfo = list[index] override fun indexOf(element: PathInfo): Int = list.indexOf(element) override fun isEmpty(): Boolean = list.isEmpty() override fun iterator(): MutableIterator<PathInfo> = list.iterator() override fun lastIndexOf(element: PathInfo): Int = list.lastIndexOf(element) override fun add(element: PathInfo): Boolean { adding(element) return list.add(element) } override fun add(index: Int, element: PathInfo) { adding(element) list.add(index, element) } override fun addAll(index: Int, elements: Collection<PathInfo>): Boolean { addingAll(elements) return list.addAll(index, elements) } override fun addAll(elements: Collection<PathInfo>): Boolean { addingAll(elements) return list.addAll(elements) } override fun clear() { matchSet.clear() list.clear() } override fun listIterator(): MutableListIterator<PathInfo> = list.listIterator() override fun listIterator(index: Int): MutableListIterator<PathInfo> = list.listIterator(index) override fun remove(element: PathInfo): Boolean { matchSet.remove(element.filePath) return list.remove(element) } override fun removeAll(elements: Collection<PathInfo>): Boolean { elements.forEach { matchSet.remove(it.filePath) } return list.removeAll(elements) } override fun removeAt(index: Int): PathInfo { matchSet.remove(list[index].filePath) return list.removeAt(index) } override fun retainAll(elements: Collection<PathInfo>): Boolean { matchSet.removeIf { key, value -> !elements.contains(value) } return list.retainAll(elements) } override fun set(index: Int, element: PathInfo): PathInfo { matchSet.remove(list[index].filePath) adding(element) return list.set(index, element) } override fun subList(fromIndex: Int, toIndex: Int): MutableList<PathInfo> { throw NotImplementedError() } } fun getMatchedRefs(linkRef: LinkRef, linkMatcher: GitHubLinkMatcher?, options: Int, fromList: List<PathInfo>?): List<PathInfo> { assert(linkRef.isNormalized) @Suppress("NAME_SHADOWING") val linkMatcher = linkMatcher ?: getMatcher(linkRef) // process the files that match the pattern and put them in the list var matches = MatchList() linkMatcher.computeMatchText(options and LINK_REF_WAS_URI != 0, options and LINK_REF_WAS_REPO_REL != 0) val completionMatch = linkMatcher.isCompletionMatch if ((linkMatcher.isOnlyCompletionMatchValid || (completionMatch && !linkMatcher.gitHubLinks)) && !wantCompletionMatch(options)) return matches val linkLooseMatch = linkMatcher.linkLooseMatch val linkCompletionMatch = linkMatcher.linkCompletionMatch val linkAllMatch = linkMatcher.linkAllMatch if (linkLooseMatch == null || linkAllMatch == null || linkCompletionMatch == null) return matches // FIX: need to have a flag or to modify the regex to exclude wiki matches when exact matching in the repo val allMatchWiki = if (wantLooseMatch(options)) linkLooseMatch.toRegex(RegexOption.IGNORE_CASE) else if (wantCompletionMatch(options)) linkCompletionMatch.toRegex(RegexOption.IGNORE_CASE) else if (linkMatcher.wikiMatchingRules) linkAllMatch.toRegex(RegexOption.IGNORE_CASE) else linkMatcher.linkFileMatch!!.toRegex() val allMatchNonWiki = if (wantLooseMatch(options)) allMatchWiki else if (wantCompletionMatch(options)) allMatchWiki else if (linkMatcher.wikiMatchingRules) linkAllMatch.toRegex() else allMatchWiki val fixedPrefix = linkMatcher.fixedPrefix if (!linkMatcher.gitHubLinks) { val allExtensions = if (wantLooseMatch(options)) linkMatcher.linkLooseMatchExtensions else if (wantCompletionMatch(options)) linkMatcher.linkCompletionMatchExtensions else linkMatcher.linkAllMatchExtensions val rawGitHubLink = linkMatcher.gitHubLink == "raw" // see if we have cached files set if (fromList == null) { // NOTE: cannot use empty extension to search for directories since directories can have extensions val includeNoExtFiles = linkRef !is ImageLinkRef && linkRef !is WikiLinkRef val targetFileTypes = getTargetFileTypes(allExtensions, wantCompletionMatch(options), includeNoExtFiles) if (targetFileTypes.isEmpty() || project == null) { // Only used in testing, runtime uses FileBasedIndex if (project != null || allExtensions == null) return ArrayList(0) // here extensions need to be expanded to include equivalent extensions as done at runtime using IDE code val extensions = hashSetOf(*allExtensions.toTypedArray()) if (extensions.contains("md")) { extensions.add("mkd") extensions.add("markdown") } val fileTypes = extensions.toList() val projectFileList = projectResolver.projectFileList(fileTypes) if (projectFileList != null) { for (fileRef in projectFileList) { if (fileRef.filePath.startsWith(fixedPrefix) && fileRef.filePath.matches(if (fileRef.isWikiPage) allMatchWiki else allMatchNonWiki)) { // here we need to test for wiki page links that resolve to raw files, these have to match case sensitive if (allMatchNonWiki === allMatchWiki || !linkMatcher.wikiMatchingRules || !linkRef.hasExt || fileRef.filePath.matches(allMatchNonWiki)) { val newFileRef = if (rawGitHubLink) FileRef(fileRef) else fileRef if (rawGitHubLink) newFileRef.isRawFile = true matches.add(newFileRef) } } } } } else { val projectScope = GlobalSearchScope.projectScope(project) val matchPattern = if (allMatchNonWiki === allMatchWiki || !linkMatcher.wikiMatchingRules || !linkRef.hasExt) allMatchWiki else allMatchNonWiki val fileNameNoDot = linkMatcher.fileName val fileNameDot = linkMatcher.fileName + "." var triedQuickMatch: Long = 0 var triedPrefixMatch: Long = 0 var triedMatch: Long = 0 for (type in targetFileTypes) { FileTypeIndex.processFiles(type, { virtualFile -> //println("checking file type: $type, path: ${virtualFile.path}") val fileName = virtualFile.name triedQuickMatch++ if (completionMatch || linkMatcher.wikiMatchingRules || fileName.length == fileNameNoDot.length && fileName == fileNameNoDot || fileName.length >= fileNameDot.length && fileName.startsWith(fileNameDot)) { triedPrefixMatch++ if (virtualFile.path.startsWith(fixedPrefix)) { triedMatch++ if (virtualFile.path.matches(matchPattern)) { val fileRef = ProjectFileRef(virtualFile, project) val newFileRef = if (rawGitHubLink) FileRef(fileRef) else fileRef if (rawGitHubLink) newFileRef.isRawFile = true matches.add(newFileRef) } } } true }, projectScope) if (includeNoExtFiles && type == PlainTextFileType.INSTANCE) { // #741, links // add plain text marked files, these do not show up as original extension or as plain text indexed val projectPlainTextFileTypeManager: ProjectPlainTextFileTypeManager? = ProjectPlainTextFileTypeManager.getInstance(project) if (projectPlainTextFileTypeManager != null) { for (virtualFile in projectPlainTextFileTypeManager.files) { val fileName = virtualFile.name triedQuickMatch++ if (completionMatch || linkMatcher.wikiMatchingRules || fileName.length == fileNameNoDot.length && fileName == fileNameNoDot || fileName.length >= fileNameDot.length && fileName.startsWith(fileNameDot)) { triedPrefixMatch++ if (virtualFile.path.startsWith(fixedPrefix)) { triedMatch++ if (virtualFile.path.matches(matchPattern)) { val fileRef = ProjectFileRef(virtualFile, project) val newFileRef = if (rawGitHubLink) FileRef(fileRef) else fileRef if (rawGitHubLink) newFileRef.isRawFile = true matches.add(newFileRef) } } } } } } } // need to try all directories under the project tree and modules because without loose matching does not get any hits if (includeDirsInCompletion && includeNoExtFiles && !rawGitHubLink) { // create a list of directories by removing file name from collected files val projectDirectories = MdLinkResolverManager.getInstance(project).getProjectDirectories() // NOTE: the returned array has nulls so should be checked. for (virtualFile: VirtualFile? in projectDirectories) { virtualFile ?: continue val fileName = virtualFile.name triedQuickMatch++ if (completionMatch || linkMatcher.wikiMatchingRules || fileName.length == fileNameNoDot.length && fileName == fileNameNoDot || fileName.length >= fileNameDot.length && fileName.startsWith(fileNameDot)) { triedPrefixMatch++ if (virtualFile.path.startsWith(fixedPrefix)) { triedMatch++ if (virtualFile.path.matches(matchPattern)) { val fileRef = ProjectFileRef(virtualFile, project) if (!fileRef.isUnderWikiDir) { if (!matches.contains(fileRef)) { matches.add(fileRef) } } } } } } } } } else { // filter from a pre-created list, used to get looseMatch, then from that list get exact matches for (fileRef in fromList) { // here we can have both fileRefs and linkRefs, we only handle fileRefs, linkRefs are silently dropped if (fileRef is FileRef) { if (fileRef.filePath.startsWith(fixedPrefix) && fileRef.filePath.matches(if (fileRef.isWikiPage) allMatchWiki else allMatchNonWiki)) { // here we need to test for wiki page links that resolve to raw files, these have to match case sensitive if (allMatchNonWiki === allMatchWiki || !linkMatcher.wikiMatchingRules || !fileRef.isWikiPage || !linkRef.hasExt || fileRef.filePath.matches(allMatchNonWiki)) { // if isRawFile is set we cannot reuse it, since in our case it may no longer be raw access if (fileRef.isRawFile == rawGitHubLink) matches.add(fileRef) else if (!rawGitHubLink) matches.add(FileRef(fileRef)) else { val newFileRef = FileRef(fileRef) newFileRef.isRawFile = true matches.add(newFileRef) } } } } } } if (matches.size == 0 && linkRef.filePath.isEmpty()) { // add its own reference otherwise scratch file self ref link don't resolve because these files are not part of the project val fileRef = linkRef.containingFile matches.add(fileRef) } val rawWikiFileRefMatches = HashSet<FileRef>() // now we need to weed out the matches that will not work, unless this is a loose match if (linkMatcher.wikiMatchingRules) { // here some will be case sensitive some not, // anchor and ext based matches are to wiki pages if (linkRef is WikiLinkRef) { // these match wiki pages, also have priority over the non-pages, ie. if Test.kt and Test.kt.md exists, then the .md will be matched first // not case sensitive: linkSubExtMatch = "^$fixedPrefix$subDirPattern$filenamePattern$extensionPattern$" // not case sensitive: linkSubAnchorExtMatch = "^$fixedPrefix$subDirPattern$filenamePattern$anchorPattern$extensionPattern$" //val pageMatch = (linkMatcher.linkSubExtMatch + "|" + linkMatcher.linkSubAnchorExtMatch).toRegex(RegexOption.IGNORE_CASE) // these match raw file content // case sensitive: linkFileMatch = "^$fixedPrefix$filenamePattern$" // case sensitive: linkFileAnchorMatch = "^$fixedPrefix$filenamePattern$anchorPattern$" val fileOrAnchorMatch = (if (linkMatcher.linkFileAnchorMatch == null) linkMatcher.linkFileMatch else linkMatcher.linkFileMatch + "|" + linkMatcher.linkFileAnchorMatch)?.toRegex() if (fileOrAnchorMatch != null) { for (fileRef in matches) { if (fileRef is FileRef && fileRef.filePath.matches(fileOrAnchorMatch)) { rawWikiFileRefMatches.add(fileRef) if (fileRef.isUnderWikiDir && !fileRef.isMarkdownExt) fileRef.isRawFile = true } } } } else { // these match wiki pages, also have priority over the non-pages, ie. if Test.kt and Test.kt.md exists, then the .md will be matched first // not case sensitive: linkSubExtMatch = "^$fixedPrefix$subDirPattern$filenamePattern$extensionPattern$" // these match raw file content and images // case sensitive: linkFileMatch = "^$fixedPrefix$filenamePattern$" val fileMatch = linkMatcher.linkFileMatch?.toRegex() if (fileMatch != null) { for (fileRef in matches) { if (fileRef is FileRef) { // it will be raw access if it is under the wiki directory and has a 'real' extension if (!fileRef.isWikiPageExt || fileRef.filePath.matches(fileMatch)) { rawWikiFileRefMatches.add(fileRef) if (fileRef.isUnderWikiDir && !fileRef.isMarkdownExt) fileRef.isRawFile = true } } } } } } else { // case sensitive: linkFileMatch = "^$fixedPrefix$filenamePattern$" // these are already set for raw if taken from the raw/ access URL and all are exact matches for (fileRef in matches) { if (fileRef is FileRef) { rawWikiFileRefMatches.add(fileRef) if (fileRef.isUnderWikiDir && !fileRef.isMarkdownExt) fileRef.isRawFile = true } } } if (linkRef is ImageLinkRef) { // have to remove all that will not resolve, unless loose matching val resolved = if (linkRefWasURI(options) || !linkRef.containingFile.isWikiPage) matches else MatchList() val unresolved = ArrayList<PathInfo>() if (!linkRefWasURI(options) && linkRef.containingFile.isWikiPage) { for (it in matches) { // if it is an image it should only resolve for raw if (it is FileRef) { val resolvedLinkAddress = linkAddress(linkRef, it, null, null, null, true) if (linkRef.filePath.equals(resolvedLinkAddress, ignoreCase = true) || (linkRef.containingFile.isWikiHomePage && linkRef.filePath.equals("wiki/$resolvedLinkAddress", ignoreCase = true))) resolved.add(it) else unresolved.add(it) } else { unresolved.add(it) } } } val linkFileMatchRegex = linkMatcher.linkFileMatch?.toRegex() ?: linkAllMatch.toRegex() resolved.sortWith(Comparator { self, other -> val selfMatch = self.filePath.matches(linkFileMatchRegex) val otherMatch = other.filePath.matches(linkFileMatchRegex) if (selfMatch && !otherMatch) -1 else if (!selfMatch && otherMatch) 1 else self.compareTo(other) }) if (wantLooseMatch(options) || wantCompletionMatch(options)) { unresolved.sortWith(Comparator { self, other -> val selfMatch = self.filePath.matches(linkFileMatchRegex) val otherMatch = other.filePath.matches(linkFileMatchRegex) if (selfMatch && !otherMatch) -1 else if (!selfMatch && otherMatch) 1 else self.compareTo(other) }) matches = resolved matches.addAll(unresolved) } else { matches = resolved } } else if (matches.size > 1) { if (linkMatcher.wikiMatchingRules) { matches.sortWith(Comparator { self, other -> if (self is FileRef && other is FileRef) { if (self in rawWikiFileRefMatches && other !in rawWikiFileRefMatches) 1 else if (self !in rawWikiFileRefMatches && other in rawWikiFileRefMatches) -1 else if (self in rawWikiFileRefMatches && other in rawWikiFileRefMatches) { if (self.isWikiPageExt && !other.isWikiPageExt) -1 else if (!self.isWikiPageExt && other.isWikiPageExt) 1 else self.compareTo(other) } else self.compareTo(other) } else self.compareTo(other) }) } else { matches.sortWith(Comparator { self, other -> if (self is FileRef && other is FileRef) { if (!self.isUnderWikiDir && other.isUnderWikiDir) -1 else if (self.isUnderWikiDir && !other.isUnderWikiDir) 1 else if (self in rawWikiFileRefMatches && other !in rawWikiFileRefMatches) 1 else if (self !in rawWikiFileRefMatches && other in rawWikiFileRefMatches) -1 else if (self in rawWikiFileRefMatches && other in rawWikiFileRefMatches) { if (self.isWikiPageExt && !other.isWikiPageExt) -1 else if (!self.isWikiPageExt && other.isWikiPageExt) 1 else self.compareTo(other) } else self.compareTo(other) } else self.compareTo(other) }) } } // here we post process for other than just vanilla fileRef result type && filter out not accessible via repo relative links / if (!wantLocalREF(options) || !wantRemoteREF(options) || linkRefWasRepoRel(options)) { val postProcessedMatches = MatchList() val fileVcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) for (fileRef in matches) { if (linkRefWasRepoRel(options)) { if (fileRef is FileRef) { val targetVcsRoot = projectResolver.getVcsRoot(fileRef) if (targetVcsRoot?.basePath != fileVcsRoot?.basePath) continue } } val pathInfo = processMatchOptions(linkRef, fileRef, options) if (pathInfo != null && !postProcessedMatches.contains(pathInfo)) { postProcessedMatches.add(pathInfo) } } matches = postProcessedMatches } } if (wantLinks(options) && linkRef !is WikiLinkRef && linkRef !is ImageLinkRef) { if (linkMatcher.gitHubLinks) { // no need to check for links, the matcher has the link already set and we even pass all the stuff after the link val gitHubLinkRef = when (wantLinksType(options)) { Links.ABS -> LinkRef.parseLinkRef(linkRef.containingFile, linkMatcher.gitHubLinkWithParams.prefixWith('/'), null) Links.REL -> { val basePath = projectResolver.getVcsRoot(linkRef.containingFile)?.basePath val containingFilePath = if (linkRef.containingFile.isUnderWikiDir) if (linkRef.containingFile.isWikiHomePage) linkRef.path else linkRef.containingFile.filePath else PathInfo.appendParts(linkRef.containingFile.path, "blob", "master", linkRef.containingFile.fileName).filePath val linkAddress = PathInfo.relativePath(containingFilePath, basePath.suffixWith('/') + linkMatcher.gitHubLink, withPrefix = true, blobRawEqual = false) LinkRef.parseLinkRef(linkRef.containingFile, linkAddress + linkMatcher.gitHubLinkParams, null) } Links.URL -> { val remoteUrl = projectResolver.getVcsRoot(linkRef.containingFile)?.baseUrl if (remoteUrl != null) { LinkRef.parseLinkRef(linkRef.containingFile, remoteUrl.suffixWith('/') + linkMatcher.gitHubLinkWithParams, null) } else null } else -> throw IllegalArgumentException("Want.Links can only be REL, ABS or URL got ${wantLinksType(options)}") } if (gitHubLinkRef != null) matches.add(gitHubLinkRef) } else { if (!linkMatcher.isOnlyCompletionMatchValid && linkMatcher.effectiveExt.isNullOrEmpty()) { val vcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) if (vcsRoot != null) { val remoteUrl = vcsRoot.baseUrl val basePath = vcsRoot.basePath.suffixWith('/') val isWikiPage = linkRef.containingFile.isWikiPage // val isWikiHomePage = linkRef.containingFile.isWikiHomePage for (link in GITHUB_NON_FILE_LINKS) { if ((basePath + link).matches(allMatchWiki)) { val gitHubLinkRef = when (wantLinksType(options)) { Links.ABS -> if (isWikiPage) null else LinkRef.parseLinkRef(linkRef.containingFile, link.prefixWith('/'), null) Links.REL -> { if (isWikiPage) LinkRef(linkRef.containingFile, "../$link", null, null, false) else { val containingFilePath = PathInfo.appendParts(linkRef.containingFile.path, "blob", "master", linkRef.containingFile.fileName).filePath val linkAddress = PathInfo.relativePath(containingFilePath, basePath + link, withPrefix = true, blobRawEqual = false) LinkRef.parseLinkRef(linkRef.containingFile, linkAddress, null) } } Links.URL -> LinkRef.parseLinkRef(linkRef.containingFile, remoteUrl.suffixWith('/') + link, null) else -> throw IllegalArgumentException("Want.Links can only be REL, ABS or URL got ${wantLinksType(options)}") } if (gitHubLinkRef != null) matches.add(gitHubLinkRef) } } } } } } return matches.getList() } fun fileRefAsURL(linkRef: LinkRef, targetRef: FileRef, vcsRoot: GitHubVcsRoot?, wantRaw: Boolean?): LinkRef? { val gitHubLink = if (wantRaw == true || (wantRaw == null && (linkRef is ImageLinkRef || targetRef.isRawFile))) "raw" else null val remoteUrl = vcsRoot?.urlForVcsRemote(targetRef, targetRef.isRawFile || wikiLinkHasRealExt(linkRef, targetRef), linkRef.anchor, branchOrTag, gitHubLink) if (remoteUrl != null) { // putting an if () in to select parameter crashes the compiler: // val urlRef = LinkRef.parseLinkRef(linkRef.containingFile, remoteUrl, targetRef, if (linkRef is ImageLinkRef) ::ImageLinkRef else ::LinkRef) val urlRef = if (linkRef is ImageLinkRef) LinkRef.parseLinkRef(linkRef.containingFile, remoteUrl, targetRef, ::ImageLinkRef) else LinkRef.parseLinkRef(linkRef.containingFile, remoteUrl, targetRef, ::LinkRef) assert(urlRef.isExternal) { "expected to get URL, instead got $urlRef" } return urlRef } else { return null } } fun fileRefAsURI(linkRef: LinkRef, targetRef: PathInfo): LinkRef { val urlEncoded = urlEncode(targetRef.filePath) // windows path needs file:/ the rest file:// val fullPath = PathInfo.prefixWithFileURI(urlEncoded) return if (targetRef is FileRef) linkRef.replaceFilePath(fullPath, targetRef) else linkRef.replaceFilePath(fullPath, true) } fun fileRefAsABS(linkRef: LinkRef, targetRef: FileRef, vcsRoot: GitHubVcsRoot?): LinkRef? { return if (linkRef.containingFile.isUnderWikiDir) { null } else { val containingFileVcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) if (vcsRoot?.basePath != containingFileVcsRoot?.basePath || containingFileVcsRoot?.basePath == null) { if (vcsRoot == null) { if (containingFileVcsRoot != null) null else { // the path is relative to project or null if (targetRef.filePath.startsWith(projectBasePath.suffixWith('/'), ignoreCase = true)) { val result = linkRef.replaceFilePath(PathInfo.relativePath(projectBasePath.suffixWith('/'), targetRef.filePath, false, false).prefixWith('/'), targetRef, false) result } else null } } else { null } } else { val relativePath = vcsRoot?.rootRelativeForVcsRemote( targetRef, targetRef.isRawFile || wikiLinkHasRealExt(linkRef, targetRef), linkRef.anchor, branchOrTag, if (linkRef is ImageLinkRef || targetRef.isRawFile) "raw" else null ) if (relativePath != null && !relativePath.startsWith("../")) { // putting an if () in to select parameter crashes the compiler: // val urlRef = LinkRef.parseLinkRef(linkRef.containingFile, relativePath, targetRef, if (linkRef is ImageLinkRef) ::ImageLinkRef else ::LinkRef) val fullPath = relativePath.prefixWith('/') val urlRef = if (linkRef is ImageLinkRef) LinkRef.parseLinkRef(linkRef.containingFile, fullPath, targetRef, ::ImageLinkRef) else LinkRef.parseLinkRef(linkRef.containingFile, fullPath, targetRef, ::LinkRef) assert(urlRef.isLocal && urlRef.isAbsolute) { "expected to get vcsRoot Relative for ABS, instead got $urlRef" } urlRef } else { null } } } } fun processMatchOptions(linkRef: LinkRef, targetRef: PathInfo, options: Int): PathInfo? { if (targetRef is FileRef) { val vcsRoot: GitHubVcsRoot? = projectResolver.getVcsRoot(targetRef) val isUnderVcs: Boolean = vcsRoot.ifNotNull { projectResolver.isUnderVcs(targetRef) } ?: false if (vcsRoot != null && isUnderVcs) { // it is a remote reference return when (wantRemoteType(options)) { Remote.NONE -> null Remote.URI -> fileRefAsURI(linkRef, targetRef) Remote.URL -> fileRefAsURL(linkRef, targetRef, vcsRoot, null) Remote.RAW -> fileRefAsURL(linkRef, targetRef, vcsRoot, true) Remote.ABS -> fileRefAsABS(linkRef, targetRef, vcsRoot) Remote.REL -> { val newLinkRef = linkRef(linkRef, targetRef, null, null, null) if (PathInfo.isRelative(newLinkRef.filePath)) newLinkRef else null } else -> { assert(wantRemoteType(options) == Remote.REF) { "Not all RemoteTypes are handled, expected Remote.REF got ${wantRemoteType(options).testData()}" } targetRef } } } else { // local file return when (wantLocalType(options)) { Local.NONE -> null Local.URI -> fileRefAsURI(linkRef, targetRef) Local.URL -> fileRefAsURL(linkRef, targetRef, vcsRoot, null) Local.RAW -> fileRefAsURL(linkRef, targetRef, vcsRoot, true) Local.ABS -> fileRefAsABS(linkRef, targetRef, vcsRoot) Local.REL -> { val newLinkRef = linkRef(linkRef, targetRef, null, null, null) if (PathInfo.isRelative(newLinkRef.filePath)) newLinkRef else null } else -> { assert(wantLocalType(options) == Local.REF) { "Not all LocalTypes are handled, expected Local.REF got ${wantLocalType(options).testData()}" } targetRef } } } } else if (targetRef is LinkRef && targetRef.isExternal) { // see if has the right format val vcsRoot = projectResolver.getVcsRootForUrl(targetRef.filePath) if (vcsRoot?.baseUrl != null) { val linkPath = targetRef.filePath.substring(vcsRoot.baseUrl.length) if (linkPath in GITHUB_NON_FILE_LINKS) { val linksType = wantLinksType(options) if (linksType == Links.URL || linksType == Links.ABS) { return linkRef } } } } return null } fun logicalRemotePath(fileRef: FileRef, useWikiPageActualLocation: Boolean, isSourceRef: Boolean, isImageLinkRef: Boolean, branchOrTag: String?): PathInfo { val filePathInfo: PathInfo if (fileRef.isUnderWikiDir) { if (useWikiPageActualLocation && !isSourceRef) filePathInfo = PathInfo(fileRef.path) // GitHub Wiki Home Change: No longer true //else if (fileRef.isWikiHomePage && isSourceRef && isImageLinkRef) filePathInfo = PathInfo.appendParts(fullPath = fileRef.wikiDir, parts = "..") else filePathInfo = PathInfo(fileRef.wikiDir) } else { val gitHubVcsRoot = projectResolver.getVcsRoot(fileRef) if (fileRef.filePath.startsWith(projectBasePath.suffixWith('/'))) { val vcsMainRepoBase = (gitHubVcsRoot?.mainRepoBaseDir ?: projectBasePath).suffixWith('/') filePathInfo = PathInfo(vcsMainRepoBase + (if (isImageLinkRef || fileRef.isRawFile) "raw/" else "blob/") + (branchOrTag ?: "master").suffixWith('/') + PathInfo.relativePath(vcsMainRepoBase, fileRef.path, withPrefix = false, blobRawEqual = false)) } else { filePathInfo = PathInfo(fileRef.path) } } return filePathInfo } override fun relativePath(linkRef: LinkRef, targetRef: FileRef, withExtForWikiPage: Boolean, branchOrTag: String?): String? { assertContainingFile(linkRef) val containingFilePath = logicalRemotePath(containingFile, useWikiPageActualLocation = false, isSourceRef = true, isImageLinkRef = linkRef is ImageLinkRef, branchOrTag = branchOrTag).filePath.suffixWith('/') val targetFilePath = logicalRemotePath(targetRef, useWikiPageActualLocation = withExtForWikiPage, isSourceRef = false, isImageLinkRef = linkRef is ImageLinkRef, branchOrTag = branchOrTag).filePath.suffixWith('/') val containingFileGitHubVcsRoot = projectResolver.getVcsRoot(containingFile) val targetFileGitHubVcsRoot = projectResolver.getVcsRoot(targetRef) // if not under VCS and both roots are null then get relative path also if (containingFileGitHubVcsRoot == null && targetFileGitHubVcsRoot == null || targetFileGitHubVcsRoot != null && containingFileGitHubVcsRoot != null && (containingFileGitHubVcsRoot.mainRepoBaseDir == targetFileGitHubVcsRoot.mainRepoBaseDir)) { val relativePath = PathInfo.relativePath(containingFilePath, targetFilePath, withPrefix = true, blobRawEqual = true) return relativePath } else { return null } } fun linkAddress(targetRef: PathInfo, withExtForWikiPage: Boolean? = null, branchOrTag: String?, anchor: String?): String { val linkRef = LinkRef(containingFile, targetRef.fileNameNoExt, anchor, null, false) return linkAddress(linkRef, targetRef, withExtForWikiPage, branchOrTag, anchor, true) } @Suppress("UNUSED_PARAMETER") fun wikiLinkAddress(targetRef: PathInfo, withExtForWikiPage: Boolean? = null, branchOrTag: String?, anchor: String?): String { val fileRef = when (targetRef) { is FileRef -> if (project != null) targetRef.projectFileRef(project) else null is LinkRef -> targetRef.targetRef else -> null } val fullPath = if (targetRef.isWikiPageExt && withExtForWikiPage != true) targetRef.fileNameNoExt else targetRef.fileName val wikiLinkRef = WikiLinkRef(containingFile, LinkRef.urlDecode(fullPath), anchor, targetRef as? FileRef, false) if (fileRef?.isUnderWikiDir != true) { return "" } return wikiLinkRef.filePathWithAnchor } fun imageLinkAddress(targetRef: PathInfo, withExtForWikiPage: Boolean? = null, branchOrTag: String?, anchor: String?): String { val linkRef = ImageLinkRef(containingFile, targetRef.fileNameNoExt, anchor, null, false) return linkAddress(linkRef, targetRef, withExtForWikiPage, branchOrTag, anchor, true) } fun linkRef(targetRef: PathInfo, withExtForWikiPage: Boolean? = null, branchOrTag: String?, anchor: String?): LinkRef { return LinkRef.parseLinkRef(containingFile, linkAddress(targetRef, withExtForWikiPage, branchOrTag, anchor), targetRef as? FileRef, ::LinkRef) } fun wikiLinkRef(targetRef: PathInfo, withExtForWikiPage: Boolean? = null, branchOrTag: String?, anchor: String?): WikiLinkRef { return LinkRef.parseLinkRef(containingFile, wikiLinkAddress(targetRef, withExtForWikiPage, branchOrTag, anchor), targetRef as? FileRef, ::WikiLinkRef) as WikiLinkRef } fun imageLinkRef(targetRef: PathInfo, withExtForWikiPage: Boolean? = null, branchOrTag: String?, anchor: String?): ImageLinkRef { return LinkRef.parseLinkRef(containingFile, imageLinkAddress(targetRef, withExtForWikiPage, branchOrTag, anchor), targetRef as? FileRef, ::ImageLinkRef) as ImageLinkRef } fun linkRef(linkRef: LinkRef, targetRef: PathInfo, withExtForWikiPage: Boolean?, branchOrTag: String?, anchor: String?): LinkRef { assert(linkRef.isNormalized) return when (linkRef) { is WikiLinkRef -> LinkRef.parseLinkRef(containingFile, linkAddress(linkRef, targetRef, withExtForWikiPage, branchOrTag, anchor, true), targetRef as? FileRef, ::WikiLinkRef) is ImageLinkRef -> LinkRef.parseLinkRef(containingFile, linkAddress(linkRef, targetRef, withExtForWikiPage, branchOrTag, anchor, true), targetRef as? FileRef, ::ImageLinkRef) else -> LinkRef.parseLinkRef(containingFile, linkAddress(linkRef, targetRef, withExtForWikiPage, branchOrTag, anchor, true), targetRef as? FileRef, ::LinkRef) } } fun wikiLinkHasRealExt(linkRef: LinkRef, targetRef: PathInfo): Boolean { return linkRef.hasExt && linkRef.fileNameNoExt.equals(linkRef.fileToLink(targetRef.fileNameNoExt, linkEncodingExclusionMap), ignoreCase = true) } @Suppress("NAME_SHADOWING") override fun linkAddress(linkRef: LinkRef, targetRef: PathInfo, withExtForWikiPage: Boolean?, branchOrTag: String?, anchor: String?, reduceToAnchor: Boolean): String { assertContainingFile(linkRef) val normLinkRef = normalizedLinkRef(linkRef) // need to make sure that the extension in the link is a real extension and not part of the file name, otherwise it will add the .md extension erroneously val withExtForWikiPage = withExtForWikiPage ?: wikiLinkHasRealExt(normLinkRef, targetRef) if (targetRef is FileRef) { var prefix = relativePath(normLinkRef, targetRef, withExtForWikiPage || normLinkRef is ImageLinkRef, branchOrTag) if (prefix == null) { // only full address will work or relative to containing file if in a module if (project != null) { val virtualFile = containingFile.virtualFile val virtualFile1 = targetRef.virtualFile if (virtualFile != null && virtualFile1 != null) { val fileIndex = ProjectRootManager.getInstance(project).fileIndex val module = fileIndex.getModuleForFile(virtualFile) val anchorText = if (anchor == null || anchor.isEmpty()) "" else if (anchor[0] == '#') anchor else "#${LinkRef.urlEncode(anchor, null)}" if (module != null) { // if target ref in module under module root dir then it can be relative val path = PathInfo(module.moduleFilePath).path val projectComponent = MdLinkResolverManager.getInstance(project) val targetVcsRoot = projectComponent.getVcsRoot(targetRef) val containingVcsRoot = projectComponent.getVcsRoot(containingFile) if (targetVcsRoot?.mainRepoBaseDir == containingVcsRoot?.mainRepoBaseDir) { if (virtualFile.path.startsWith(path) && virtualFile1.path.startsWith(path)) { return urlEncode(PathInfo.relativePath(containingFile.filePath, targetRef.filePath, blobRawEqual = true)) + anchorText } val scope = module.moduleScope if (MdPsiImplUtil.inScope(scope, virtualFile1)) { return urlEncode(PathInfo.relativePath(containingFile.filePath, targetRef.filePath, blobRawEqual = true)) + anchorText } } } // in this case it takes a full path so we change it to file:// if (targetRef.isURI) { return targetRef.filePath + anchorText } else { return "file://" + urlEncode(targetRef.filePath) + anchorText } } } return targetRef.filePath } else { if (normLinkRef is WikiLinkRef) { return prefix.suffixWith('/') + normLinkRef.fileToLink(if (withExtForWikiPage) targetRef.fileName else targetRef.fileNameNoExt, linkEncodingExclusionMap) + (anchor ?: if (wasAnchorUsedInMatch(normLinkRef, targetRef)) "" else normLinkRef.anchor).prefixWith("#") } else { if (prefix.isNotEmpty() && targetRef.isUnderWikiDir) { // if the prefix starts with the wiki dir change it to the generic wiki used in links val wikiDirName = targetRef.wikiDir.substring(targetRef.mainRepoDir.length + 1).suffixWith('/') if (containingFile.isUnderWikiDir && prefix.startsWith(wikiDirName)) prefix = "wiki/" + prefix.substring(wikiDirName.length) else if (!containingFile.isUnderWikiDir) { val vcsRoot = projectResolver.getVcsRoot(containingFile) val repoBasePath = vcsRoot?.basePath ?: projectBasePath val backDirsToRepoRoot = PathInfo.relativePath(containingFile.path, repoBasePath, withPrefix = true, blobRawEqual = false) val prefixWithWikiDirName = "$backDirsToRepoRoot../../$wikiDirName" if (prefix.startsWith(prefixWithWikiDirName)) prefix = backDirsToRepoRoot + "../../wiki/" + prefix.substring(prefixWithWikiDirName.length) } } val selfRef = isSelfRef(normLinkRef, targetRef, withExtForWikiPage) val optimizedAnchor = (anchor ?: optimizedLinkAnchor(normLinkRef, targetRef, withExtForWikiPage)).prefixWith('#') if (targetRef.isWikiPage) { if (selfRef && reduceToAnchor) return optimizedAnchor else { val fileName = prefix.suffixWith('/') + if (!withExtForWikiPage) (if (targetRef.isWikiHomePage) (if (linkRef.containingFile.isWikiPage) "Home" else "") else targetRef.fileNameNoExt) else targetRef.fileName return normLinkRef.fileToLink(fileName, linkEncodingExclusionMap).removeSuffix("/") + optimizedAnchor } } else { if (selfRef && reduceToAnchor) return optimizedAnchor.ifEmpty(targetRef.fileName) else return normLinkRef.fileToLink(prefix.suffixWith('/') + targetRef.fileName, linkEncodingExclusionMap) + optimizedAnchor } } } } else if (targetRef.isURI) { // convert git hub links to relative links val vcsRoot = projectResolver.getVcsRoot(normLinkRef.containingFile) val remoteUrl = vcsRoot?.baseUrl val repoBasePath = vcsRoot?.basePath if (remoteUrl != null && repoBasePath != null) { assert(remoteUrl.startsWith("http://", "https://")) { "remote vcsRepoBase has to start with http:// or https://, instead got $remoteUrl" } if (targetRef.path.startsWith(remoteUrl.suffixWith('/'))) { val fileName = targetRef.filePath.substring(remoteUrl.suffixWith('/').length) if (fileName in GITHUB_NON_FILE_LINKS) { return when { containingFile.isWikiHomePage || containingFile.isUnderWikiDir -> "../$fileName" else -> PathInfo.relativePath(containingFile.path, repoBasePath.suffixWith('/'), withPrefix = true, blobRawEqual = false) + "../../" + fileName } } else { if (fileName.startsWith("wiki/")) { // trying for wiki page val filePath = when { // GitHub Wiki Home Change: No longer true //containingFile.isWikiHomePage && normLinkRef is ImageLinkRef -> fileName containingFile.isWikiHomePage || containingFile.isUnderWikiDir -> fileName.substring("wiki/".length) else -> PathInfo.relativePath(containingFile.path, repoBasePath.suffixWith('/'), withPrefix = true, blobRawEqual = false).suffixWith("/") + "../../" + fileName } return filePath } else { // main repo file, if it starts with blob/something/ or raw/something then we can handle it val repoPrefixPathPattern = ("^([^/]+)\\Q/\\E([^/]+)\\Q/\\E").toRegex() if (fileName.matches(repoPrefixPathPattern)) { val match = repoPrefixPathPattern.find(fileName) if (match != null) { val oldGitHubLink = match.groups[0] val oldBranchOrTag = match.groups[1] // we throw out the branch if one is given to us or if linking from another file in the repo, its branch or tag will be used by GitHub val fileNamePart = fileName.substring(match.range.endInclusive + 1) val filePath = when { // GitHub Wiki Home Change: No longer true //containingFile.isWikiHomePage -> "$oldGitHubLink/${branchOrTag ?: oldBranchOrTag ?: "master"}/" + fileNamePart containingFile.isWikiHomePage || containingFile.isUnderWikiDir -> "../$oldGitHubLink/${branchOrTag ?: oldBranchOrTag ?: "master"}/" + fileNamePart else -> PathInfo.relativePath(containingFile.path, repoBasePath.suffixWith('/'), withPrefix = true, blobRawEqual = false).suffixWith("/") + fileNamePart } return filePath } } } } } } } return "" } fun urlEncode(url: String): String { return LinkRef.urlEncode(url, linkEncodingExclusionMap) } fun absoluteToRelativeLink(linkRef: LinkRef): LinkRef { val normLinkRef = normalizedLinkRef(linkRef) if (!normLinkRef.isURI && !normLinkRef.isAbsolute) return normLinkRef if (normLinkRef.isLocal) { if (!normLinkRef.isURI) { val vcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) // need to suffix projectBasePath with /, vcsRoot does that val baseDir = vcsRoot?.fileProjectBaseDirectory(linkRef.containingFile) ?: projectBasePath.suffixWith("/") if (!linkRef.containingFile.filePath.startsWith(baseDir)) { return normLinkRef } val containingFileRelPath = linkRef.containingFile.filePath.substring(baseDir.length) val subDirs = containingFileRelPath.count('/') // we add .. for every subDir the file is under its base directory so that relative resolves to the right baseDir val fullPath = "../".repeat(subDirs) + linkRef.filePath.substring(1) val relRef = linkRef.replaceFilePath(fullPath, linkRef.isNormalized) return relRef } else { val targetRef = FileRef(LinkRef.urlDecode(normLinkRef.filePath.removeAnyPrefix("file://", "file:/"))) val containingFileVcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) val targetFileVcsRoot = projectResolver.getVcsRoot(targetRef) if (containingFileVcsRoot === targetFileVcsRoot && targetFileVcsRoot != null) { val linkAddress = linkAddress(normLinkRef, targetRef, null, null, "", true) // GitHub Wiki Home Change: No longer true // if (containingFile.isWikiHomePage && linkAddress.startsWith("../")) { // linkAddress = linkAddress.removePrefix("../") // } val relRefNoAnchor = normLinkRef.replaceFilePath(linkAddress, true) val relRef = normLinkRef.replaceFilePathAndAnchor(relRefNoAnchor.filePath, true, normLinkRef.anchor, linkRef.isNormalized) return relRef } else { // keep file reference val relLink = normLinkRef.replaceFilePath(targetRef.filePath, false, linkRef.isNormalized) return relLink } } } else if (normLinkRef.isExternal) { // search for VCS root based on the URL!!! val gitHubVcsRoot = projectResolver.getVcsRootForUrl(normLinkRef.filePath) val containingVcsRoot = projectResolver.getVcsRoot(containingFile) if (gitHubVcsRoot != null && containingVcsRoot != null && gitHubVcsRoot.mainRepoBaseDir == containingVcsRoot.mainRepoBaseDir) { val gitHubRepoBaseUrl = gitHubVcsRoot.baseUrl if (gitHubRepoBaseUrl != null && normLinkRef.filePath.startsWith(gitHubRepoBaseUrl)) { val linkToFile = normLinkRef.linkToFile(normLinkRef.filePath.substring(gitHubRepoBaseUrl.suffixWith('/').length)) if (linkToFile.startsWith("blob/") || linkToFile.startsWith("raw/")) { val targetFilePath = gitHubVcsRoot.mainRepoBaseDir.suffixWith('/') + linkToFile val containingFilePath = logicalRemotePath(containingFile, useWikiPageActualLocation = false, isSourceRef = true, isImageLinkRef = normLinkRef is ImageLinkRef, branchOrTag = null).filePath.suffixWith('/') val containingFileVcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) var fullPath: String if (containingFileVcsRoot === gitHubVcsRoot) { fullPath = PathInfo.relativePath(containingFilePath, targetFilePath, blobRawEqual = true) // GitHub Wiki Home Change: No longer true //if (containingFile.isWikiHomePage && fullPath.startsWith("../")) { // fullPath = fullPath.removePrefix("../") //} val relLink = normLinkRef.replaceFilePath(fullPath, false, linkRef.isNormalized) return relLink } else { fullPath = PathInfo.relativePath(gitHubVcsRoot.basePath, targetFilePath, blobRawEqual = true) fullPath = fullPath.removePrefix("../") fullPath = fullPath.removeAnyPrefix("blob/", "raw/") // remove the next path part which is branch fullPath = fullPath.removePrefixIncluding("/") // now add the vcs base root fullPath = gitHubVcsRoot.basePath.suffixWith('/') + fullPath val relLink = normLinkRef.replaceFilePath(fullPath, false, linkRef.isNormalized) return relLink } } else if (linkToFile.startsWith("wiki/") || linkToFile == "wiki" || linkToFile == "wiki/") { val isWikiHome = linkToFile == "wiki" || linkToFile == "wiki/" val targetFilePath = if (isWikiHome) gitHubVcsRoot.mainRepoBaseDir.suffixWith('/') + "wiki/Home" else gitHubVcsRoot.mainRepoBaseDir.suffixWith('/') + linkToFile val containingFilePath = logicalRemotePath(containingFile, useWikiPageActualLocation = false, isSourceRef = true, isImageLinkRef = normLinkRef is ImageLinkRef, branchOrTag = null).filePath.suffixWith('/') val fullPath = PathInfo.relativePath(containingFilePath, targetFilePath, blobRawEqual = true) val relLink = normLinkRef.replaceFilePath(fullPath, false, linkRef.isNormalized) return relLink } else if (linkToFile.startsWith("issues/") || linkToFile == "issues" || linkToFile == "issues/") { val targetFilePath = gitHubVcsRoot.mainRepoBaseDir.suffixWith('/') + linkToFile val containingFilePath = logicalRemotePath(containingFile, useWikiPageActualLocation = false, isSourceRef = true, isImageLinkRef = normLinkRef is ImageLinkRef, branchOrTag = null).filePath.suffixWith('/') // val containingFileVcsRoot = projectResolver.getVcsRoot(linkRef.containingFile) val fullPath = PathInfo.relativePath(containingFilePath, targetFilePath, blobRawEqual = false) return normLinkRef.replaceFilePath(fullPath, false, linkRef.isNormalized) } } } } return linkRef } fun denormalizedLinkRef(linkRef: LinkRef): LinkRef { var mappedLinkRef = linkRef // from "https://raw.githubusercontent.com/vsch/idea-multimarkdown/master/assets/images/ScreenShot_source_preview.png" // to "https://github.com/vsch/idea-multimarkdown/raw/master/assets/images/ScreenShot_source_preview.png" // from "https://raw.githubusercontent.com/wiki/vsch/idea-multimarkdown/img/ScreenShot_source_preview_Large.png?token=AJ0mzve3jxMArvfYq7nKkL1ZaYZbPVxXks5Was-1wA%3D%3D" // to "https://github.com/vsch/idea-multimarkdown/wiki/img/ScreenShot_source_preview.png" val linkRefText = denormalizedLinkRef(mappedLinkRef.filePath) if (linkRefText !== mappedLinkRef.filePath) { // was mapped mappedLinkRef = mappedLinkRef.replaceFilePath(linkRefText, true, false) } return mappedLinkRef } fun denormalizedLinkRef(linkRefText: String): String { for (provider in MdLinkMapProvider.EXTENSIONS.value) { val url = provider.mapLinkRef(linkRefText, renderingProfile) if (url != null) return url } return linkRefText; } fun normalizedLinkRef(linkRef: LinkRef): LinkRef { if (linkRef.isNormalized) return linkRef var mappedLinkRef = linkRef // from "https://raw.githubusercontent.com/vsch/idea-multimarkdown/master/assets/images/ScreenShot_source_preview.png" // to "https://github.com/vsch/idea-multimarkdown/raw/master/assets/images/ScreenShot_source_preview.png" // from "https://raw.githubusercontent.com/wiki/vsch/idea-multimarkdown/img/ScreenShot_source_preview_Large.png?token=AJ0mzve3jxMArvfYq7nKkL1ZaYZbPVxXks5Was-1wA%3D%3D" // to "https://github.com/vsch/idea-multimarkdown/wiki/img/ScreenShot_source_preview.png" val linkRefText = if (project == null) mappedLinkRef.filePath else { var text: String? = null val unescapeString = Escaping.unescapeString(mappedLinkRef.filePath) for (provider in MdLinkMapProvider.EXTENSIONS.value) { text = provider.mapLinkText(unescapeString, renderingProfile) if (text != null) break } text ?: unescapeString } if (linkRefText !== mappedLinkRef.filePath) { // was mapped mappedLinkRef = mappedLinkRef.replaceFilePath(linkRefText, true, true) } if (mappedLinkRef.filePath.startsWith("https://raw.githubusercontent.com/") || mappedLinkRef.filePath.startsWith("http://raw.githubusercontent.com/")) { val noRawContentPrefix = mappedLinkRef.filePath.removeAnyPrefix("https://raw.githubusercontent.com/", "http://raw.githubusercontent.com/") val linkParts = noRawContentPrefix.split("?", limit = 2)[0].split("/") if (linkParts.size >= 3 && (linkParts[0] != "wiki" || linkParts.size >= 4)) { val normLinkParts: List<String> if (linkParts[0] == "wiki") { // we have a user and repo match normLinkParts = arrayListOf(linkParts[1], linkParts[2], "wiki", *linkParts.subList(3, linkParts.size).toTypedArray()) } else { // we have a user and repo match normLinkParts = arrayListOf(linkParts[0], linkParts[1], "raw", *linkParts.subList(2, linkParts.size).toTypedArray()) } val changedUrlPath = PathInfo.appendParts("https://github.com", normLinkParts).filePath val normalizedLinkRef = mappedLinkRef.replaceFilePath(changedUrlPath, true, true) return normalizedLinkRef } } if (!mappedLinkRef.isNormalized) { // make a mapped version val normalized = mappedLinkRef.replaceFilePath(mappedLinkRef.filePath, true, true) return normalized } return mappedLinkRef } private fun assertContainingFile(linkRef: LinkRef) { assert(linkRef.containingFile.compareTo(containingFile) == 0) { "likRef containingFile differs from LinkResolver containingFile, need new Resolver for each containing file" } } private fun assertContainingFile(fileRef: FileRef) { assert(fileRef.compareTo(containingFile) == 0) { "fileRef differs from LinkResolver containingFile, need new Resolver for each containing file" } } fun optimizedLinkAnchor(linkRef: LinkRef, targetRef: FileRef, withExtForWikiPage: Boolean): String { val anchorUsedInMatch = wasAnchorUsedInMatch(linkRef, targetRef) val selfRef = isSelfRef(linkRef, targetRef, withExtForWikiPage) return if (anchorUsedInMatch) (if (selfRef) "#" else "") else (if (selfRef) "#" + linkRef.anchor.orEmpty() else linkRef.anchorText) } fun isSelfRef(linkRef: LinkRef, targetRef: FileRef, withExtForWikiPage: Boolean): Boolean { return if ((targetRef.isWikiPage && withExtForWikiPage) || (!targetRef.isWikiPage && linkRef.hasExt && !linkRef.isImageExt)) linkRef.containingFile.filePathNoExt == targetRef.filePathNoExt else linkRef.containingFile.filePath == targetRef.filePath } fun wasAnchorUsedInMatch(linkRef: LinkRef, targetRef: PathInfo): Boolean { return linkRef.hasAnchor && (linkRef.linkToFile(linkRef.fileName) != targetRef.fileName && targetRef.fileName.endsWith(linkRef.anchorText) || linkRef.linkToFile(linkRef.fileNameNoExt) != targetRef.fileNameNoExt && targetRef.fileNameNoExt.endsWith(linkRef.anchorText)) } fun equalLinks(fileName: String, wikiLinkAddress: String, ignoreCase: Boolean = true): Boolean { return WikiLinkRef.fileAsLink(fileName).equals(WikiLinkRef.fileAsLink(wikiLinkAddress), ignoreCase) } }
134
Kotlin
131
809
ec413c0e1b784ff7309ef073ddb4907d04345073
93,716
idea-multimarkdown
Apache License 2.0
plugins/dependencies/src/test/kotlin/de/fayard/refreshVersions/RemovedDependencyNotationsHistoryCorrectnessTest.kt
Splitties
150,827,271
false
{"Kotlin": 808317, "Shell": 2793, "Just": 1182, "Java": 89, "Groovy": 24}
package de.fayard.refreshVersions import io.kotest.assertions.withClue import io.kotest.matchers.ints.shouldBeGreaterThan import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContainOnlyOnce import io.kotest.matchers.string.shouldHaveMinLength import org.junit.jupiter.api.Test class RemovedDependencyNotationsHistoryCorrectnessTest { @Test fun `Mapping of version to removals revision should have correct format`() { val separator = "->" val fileName = "version-to-removals-revision-mapping.txt" val file = mainResources.resolve(fileName) file.useLines { lines -> val nonEmptyLines = lines.withIndex().sumBy { (index, line) -> if (line.isEmpty()) return@sumBy 0 withClue("Line $index of $file") { line shouldContainOnlyOnce separator val version = line.substringBefore(separator) val revision = line.substringAfter(separator).toInt() revision shouldBeGreaterThan 0 version shouldHaveMinLength 1 withClue("Unexpected character in the version") { version.all { it.isLetterOrDigit() || it in ".-" } shouldBe true } } 1 } withClue("File must not be empty $file") { nonEmptyLines shouldBeGreaterThan 0 } } } }
113
Kotlin
109
1,606
df624c0fb781cb6e0de054a2b9d44808687e4fc8
1,474
refreshVersions
MIT License
echo-swing/src/main/kotlin/io/github/andrewbgm/echo/swing/SwingNode.kt
AndrewBGM
458,292,305
false
{"Kotlin": 34288}
package io.github.andrewbgm.echo.swing interface SwingNode<out T : Any, in P : SwingProps> { val ref: T fun update( previousProps: P?, nextProps: P, ) { // NOOP } fun appendChild( child: Any, ) { // NOOP } fun removeChild( child: Any, ) { // NOOP } fun insertChild( child: Any, beforeChild: Any, ) { // NOOP } }
0
Kotlin
0
2
437dae185785751a82e7e5929bc1002716dc5a5f
383
echo
MIT License
app/src/main/java/com/example/speedrun/domain/interactor/GetGameRunInteractor.kt
alejandromr92
171,358,320
false
null
package com.example.speedrun.domain.interactor import com.example.speedrun.domain.model.GameRunData interface GetGameRunInteractor { fun execute(gameId: String, onComplete: (GameRunData) -> Unit, onError: (Throwable) -> Unit) }
0
Kotlin
0
0
56654f13567957711e39b08405f3d305bb997dfc
233
SpeedRun
Apache License 2.0
src/main/java/top/fpsmaster/gui/element/RectangleType.kt
SuperSkidder
672,267,802
false
null
package top.fpsmaster.gui.element enum class RectangleType { ROUND, CIRCLE, NORMAL }
0
null
2
10
a0fefea67f46bf0d48ffca7de7238781ed92028f
89
FPSMasterOpenSourceProject
Apache License 2.0
plugins/src/main/kotlin/com/freeletics/gradle/setup/Gr8Setup.kt
freeletics
611,205,691
false
{"Kotlin": 154536, "Shell": 1815}
package com.freeletics.gradle.setup import com.gradleup.gr8.Gr8Extension import org.gradle.api.Project import org.gradle.api.attributes.Usage import org.gradle.api.attributes.Usage.JAVA_API internal fun Project.setupGr8() { val shadeConfiguration = configurations.create("shade") // make all shaded dependencies available during compilation configurations.named("compileClasspath").configure { it.extendsFrom(shadeConfiguration) } // make all shaded dependencies available during tests configurations.named("testImplementation").configure { it.extendsFrom(shadeConfiguration) } // add compileOnly dependencies to r8's classpath to avoid class not found warnings // needs to be an extra configuration because we want to filter it and compileOnly can't be resolved val shadeClassPathConfiguration = configurations.create("shadeClassPath") { it.extendsFrom(configurations.getByName("compileOnly")) it.extendsFrom(configurations.getByName("runtimeClasspath")) it.attributes { attributes -> attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class.java, JAVA_API)) } // already added to shade it.exclude(mapOf("group" to "org.jetbrains.kotlin", "module" to "kotlin-stdlib")) // included in gradle-api and would cause duplicate class issues it.exclude(mapOf("group" to "org.jetbrains", "module" to "annotations")) // included in gradle-api and would cause duplicate class issues it.exclude(mapOf("group" to "javax.inject", "module" to "javax.inject")) // included in gradle-api and would cause duplicate class issues it.exclude(mapOf("group" to "com.google.code.findbugs", "module" to "jsr305")) } extensions.configure(Gr8Extension::class.java) { extension -> val shadowedJar = extension.create("gr8") { it.configuration(shadeConfiguration.name) it.classPathConfiguration(shadeClassPathConfiguration.name) it.stripGradleApi(true) if (rootProject.file(FILE_NAME).exists()) { it.proguardFile(rootProject.file(FILE_NAME)) } if (project.file(FILE_NAME).exists()) { it.proguardFile(project.file(FILE_NAME)) } } extension.replaceOutgoingJar(shadowedJar) extension.removeGradleApiFromApi() } } private const val FILE_NAME = "rules.pro"
6
Kotlin
1
5
c962bfb0f9e2a4223de1ff1fa2b4afd0bfa582ed
2,469
freeletics-gradle-plugins
Apache License 2.0
src/main/java/com/github/housepower/jdbc/ClickHouseConnection.kt
Left
489,957,394
true
{"Kotlin": 231104}
package com.github.housepower.jdbc import com.github.housepower.jdbc.connect.PhysicalConnection import com.github.housepower.jdbc.connect.PhysicalInfo import com.github.housepower.jdbc.connect.PhysicalInfo.ServerInfo import com.github.housepower.jdbc.data.Block import com.github.housepower.jdbc.misc.Validate import com.github.housepower.jdbc.protocol.QueryRequest.ClientInfo import com.github.housepower.jdbc.protocol.QueryResponse import com.github.housepower.jdbc.settings.ClickHouseConfig import com.github.housepower.jdbc.settings.ClickHouseDefines import com.github.housepower.jdbc.statement.AbstractPreparedStatement import com.github.housepower.jdbc.statement.ClickHousePreparedInsertStatement import com.github.housepower.jdbc.statement.ClickHousePreparedQueryStatement import com.github.housepower.jdbc.statement.ClickHouseStatement import com.github.housepower.jdbc.wrapper.SQLConnection import java.net.InetSocketAddress import java.sql.SQLException import java.sql.Struct import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import java.util.regex.Pattern class ClickHouseConnection protected constructor(configure: ClickHouseConfig, info: PhysicalInfo) : SQLConnection() { // Just to be variable private val isClosed: AtomicBoolean private val configure: ClickHouseConfig private val atomicInfo: AtomicReference<PhysicalInfo> private var state = ConnectionState.IDLE override suspend fun close() { if (!isClosed() && isClosed.compareAndSet(false, true)) { val connection = atomicInfo.get().connection() connection.disPhysicalConnection() } } fun isClosed(): Boolean { return isClosed.get() } fun createStatement(): ClickHouseStatement { Validate.isTrue(!isClosed(), "Unable to create Statement, because the connection is closed.") return ClickHouseStatement(this) } val LOG = (System.getenv("CLICKHOUSE_LOGGING") ?: "") suspend fun prepareStatement(query: String): AbstractPreparedStatement { if (LOG == "ALL" || (LOG == "SOME" && !query.contains("log_queries=0"))) { println("clickhouse-client -h ${ this.configure.address() } -d ${ this.configure.database() } --user \"${ this.configure.username() }\" --password \"${ this.configure.password() }\" --query \"${ query.lineSequence() .filter { it.isNotEmpty() } .joinToString(" ") { it.trim().replace("\"", "\\\"") } }\"") } Validate.isTrue(!isClosed(), "Unable to create PreparedStatement, because the connection is closed.") val matcher = VALUES_REGEX.matcher(query) return if (matcher.find()) ClickHousePreparedInsertStatement(matcher.end() - 1, query, this).coroInit() else ClickHousePreparedQueryStatement(this, query) } suspend fun prepareStatement(sql: String, resultSetType: Int, resultSetConcurrency: Int): AbstractPreparedStatement { return this.prepareStatement(sql) } fun setClientInfo(properties: Properties) { configure.parseJDBCProperties(properties) } fun setClientInfo(name: String, value: String) { val properties = Properties() properties[name] = value configure.parseJDBCProperties(properties) } fun createArrayOf(typeName: String, elements: Array<Any>): java.sql.Array { Validate.isTrue(!isClosed(), "Unable to create Array, because the connection is closed.") return ClickHouseArray(elements) } fun createStruct(typeName: String, attributes: Array<Any>): Struct { Validate.isTrue(!isClosed(), "Unable to create Struct, because the connection is closed.") return ClickHouseStruct(typeName, attributes) } suspend fun isValid(timeout: Int): Boolean { val validConfigure = configure.copy() validConfigure.setQueryTimeout(timeout * 1000) var connection: ClickHouseConnection? = null var statement: ClickHouseStatement? = null return try { connection = ClickHouseConnection(validConfigure, atomicInfo.get()) statement = connection.createStatement() statement.execute("SELECT 1") statement.close() true } finally { statement?.close() connection?.close() } } suspend fun getSampleBlock(insertQuery: String): Block { val connection = getHealthyPhysicalConnection() connection.sendQuery(insertQuery, atomicInfo.get().client(), configure.settings()!!) state = ConnectionState.WAITING_INSERT return connection.receiveSampleBlock(configure.queryTimeout(), atomicInfo.get().server()) } suspend fun sendQueryRequest(query: String): QueryResponse { if (state == ConnectionState.WAITING_INSERT) { throw RuntimeException("Connection is currently waiting for an insert operation, check your previous InsertStatement.") } val connection = getHealthyPhysicalConnection() connection.sendQuery(query, atomicInfo.get().client(), configure.settings()!!) return QueryResponse { connection.receiveResponse(configure.queryTimeout(), atomicInfo.get().server()) } } // when sendInsertRequest we must ensure the connection is healthy // the sampleblock mus be called before this method suspend fun sendInsertRequest(block: Block): Int { if (state != ConnectionState.WAITING_INSERT) { throw RuntimeException("Call getSampleBlock before insert.") } val connection = getPhysicalConnection() connection.sendData(block) connection.sendData(Block()) connection.receiveEndOfStream(configure.queryTimeout(), atomicInfo.get().server()) state = ConnectionState.IDLE return block.rows() } private suspend fun getHealthyPhysicalConnection(): PhysicalConnection { val oldInfo = atomicInfo.get() if (!oldInfo.connection().ping(configure.queryTimeout(), atomicInfo.get().server())) { val newInfo = createPhysicalInfo(configure) val closeableInfo = if (atomicInfo.compareAndSet(oldInfo, newInfo)) oldInfo else newInfo closeableInfo.connection().disPhysicalConnection() } return atomicInfo.get().connection() } private fun getPhysicalConnection() = atomicInfo.get().connection() companion object { val VALUES_REGEX = Pattern.compile("[V|v][A|a][L|l][U|u][E|e][S|s]\\s*\\(") @JvmStatic suspend fun createClickHouseConnection(configure: ClickHouseConfig): ClickHouseConnection { return ClickHouseConnection(configure, createPhysicalInfo(configure)) } private suspend fun createPhysicalInfo(configure: ClickHouseConfig): PhysicalInfo { val physical = PhysicalConnection.openPhysicalConnection(configure) return PhysicalInfo(clientInfo(physical, configure), serverInfo(physical, configure), physical) } private fun clientInfo(physical: PhysicalConnection, configure: ClickHouseConfig): ClientInfo { Validate.isTrue(physical.address() is InetSocketAddress) val address = physical.address() as InetSocketAddress val clientName = String.format("%s %s", ClickHouseDefines.NAME, "client") val initialAddress = "[::ffff:127.0.0.1]:0" return ClientInfo(initialAddress, address.hostName, clientName) } private suspend fun serverInfo(physical: PhysicalConnection, configure: ClickHouseConfig): ServerInfo { return try { val reversion = ClickHouseDefines.CLIENT_REVERSION.toLong() physical.sendHello("client", reversion, configure.database()!!, configure.username()!!, configure.password()!!) val response = physical.receiveHello(configure.queryTimeout(), null) val timeZone = TimeZone.getTimeZone(response.serverTimeZone()) ServerInfo(configure, response.reversion(), timeZone, response.serverDisplayName()) } catch (rethrows: SQLException) { physical.disPhysicalConnection() throw rethrows } } } init { isClosed = AtomicBoolean(false) this.configure = configure atomicInfo = AtomicReference(info) } }
0
null
0
0
185b48569d980e4ee84e79f4c392bb4610f25e61
8,658
ClickHouse-Native-JDBC
Apache License 2.0
chess/src/main/java/com/ajcm/chess/game/GameSource.kt
jassielcastro
364,715,505
false
null
package com.ajcm.chess.game import com.ajcm.chess.data.Game import com.ajcm.chess.domain.Color import com.ajcm.chess.domain.Player import com.ajcm.chess.domain.board.Board import com.ajcm.chess.domain.board.Position import com.ajcm.chess.domain.piece.* class GameSource(private val playerOne: Player, private val playerTwo: Player, private val board: Board) : Game { override fun updateMovement(chessPiece: Piece, newPosition: Position, playerRequest: Player) { chessPiece.position = newPosition if (chessPiece is King && newPosition.x == 7) { // Castling movement val y = if (playerRequest.color == Color.WHITE) 1 else 8 getChessPieceFrom(playerRequest, Position(8, y))?.let { rook -> updateMovement(rook, Position(6, y), playerRequest) } return } enemyOf(playerRequest).apply { if (existPieceOn(newPosition, this) && !isKingEnemyOn(newPosition, this)) { getChessPieceFrom(this, newPosition)?.let { piece -> availablePieces.remove(piece) } } } } override fun enemyOf(playerRequest: Player): Player = if (playerRequest.color == playerOne.color) playerTwo else playerOne override fun updateTurn() { with(whoIsMoving()) { enemyOf(this).apply { isMoving = true } isMoving = false } } override fun whoIsMoving(): Player = if (playerOne.isMoving) playerOne else playerTwo override fun existPieceOn(position: Position, player: Player): Boolean = with(player) { availablePieces.map { it.position }.contains(position) } override fun getChessPieceFrom(player: Player, position: Position): Piece? = player.availablePieces.find { position == it.position } override fun isKingEnemyOn(position: Position, enemyPlayer: Player): Boolean = getChessPieceFrom(enemyPlayer, position) is King override fun hasNoOwnMovements(playerRequest: Player, playerWaiting: Player): Boolean { return playerWaiting.availablePieces.map { Pair(it, it.getAllPossibleMovements(playerWaiting, this)) }.filterNot { it.second.isEmpty() }.map { it.second.map { newPosition -> isValidMadeFakeMovement(it.first.position, newPosition, playerRequest) } }.flatten().all { it } } override fun isKingCheckedOf(playerRequest: Player, playerWaiting: Player, game: com.ajcm.chess.data.Game?): Boolean { val kingPosition = getKingPositionFrom(playerWaiting) return playerRequest.availablePieces.any { it.getAllPossibleMovements(playerRequest, game ?: this).contains(kingPosition) } } private fun getKingPositionFrom(player: Player): Position? = player.availablePieces.filterIsInstance<King>().map { it.position }.firstOrNull() override fun isValidMadeFakeMovement(currentPosition: Position, newPosition: Position, playerRequest: Player): Boolean { val player = enemyOf(playerRequest).copy() val enemyPlayerCopy = playerRequest.copy() val mockedPiece = getChessPieceFrom(player, currentPosition) ?: return false val mockedGame = GameSource( if (player.color == playerOne.color) player else enemyPlayerCopy, if (player.color == playerOne.color) enemyPlayerCopy else player, board ) mockedPiece.position = newPosition if (existPieceOn(newPosition, enemyPlayerCopy) && !isKingEnemyOn(newPosition, enemyPlayerCopy)) { getChessPieceFrom(enemyPlayerCopy, newPosition)?.let { piece -> enemyPlayerCopy.availablePieces.remove(piece) } } return isKingCheckedOf(enemyPlayerCopy, player, mockedGame) } override fun getPiecesOnBord(position: Position): Piece? = playerOne.availablePieces.find { position == it.position } ?: playerTwo.availablePieces.find { position == it.position } override fun getBoard(): Board = board override fun convert(currentPawn: Pawn, to: PawnTransform) { val piece = when (to) { PawnTransform.BISHOP -> Bishop(currentPawn.position, currentPawn.color) PawnTransform.KNIGHT -> Knight(currentPawn.position, currentPawn.color) PawnTransform.QUEEN -> Queen(currentPawn.position, currentPawn.color) PawnTransform.ROOK -> Rook(currentPawn.position, currentPawn.color) } with(whoIsMoving().availablePieces) { remove(currentPawn) add(piece) } } }
0
Kotlin
0
5
313b2303116feea477b850b73dd23f7ecce0cb3e
4,699
ChessApp
MIT License
app/src/main/java/com/fkuper/metronome/MetronomeApplication.kt
fkuper
729,506,173
false
{"Kotlin": 142954}
package com.fkuper.metronome import android.app.Application import android.app.NotificationChannel import android.app.NotificationManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Build import android.os.IBinder import com.fkuper.metronome.data.AppContainer import com.fkuper.metronome.data.AppDataContainer import com.fkuper.metronome.service.MetronomeService class MetronomeApplication : Application() { /** * AppContainer instance used by the rest of classes to obtain dependencies */ lateinit var container: AppContainer private set lateinit var metronomeService: MetronomeService private set private var bound: Boolean = false override fun onCreate() { super.onCreate() container = AppDataContainer(this) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } // Bind to MetronomeService Intent(this, MetronomeService::class.java).also { bindService(it, connection, Context.BIND_AUTO_CREATE) } } private val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, binder: IBinder?) { val localBinder = binder as MetronomeService.LocalBinder metronomeService = localBinder.getService() bound = true } override fun onServiceDisconnected(name: ComponentName?) { bound = false } } companion object { const val NOTIFICATION_CHANNEL_ID = "metronome_channel" const val NOTIFICATION_CHANNEL_NAME = "Metronome Notifications" const val METRONOME_RUNNING_NOTIFICATION_ID = 1 const val PRACTICE_REMINDER_NOTIFICATION_ID = 2 } }
0
Kotlin
0
0
e76354d53990b1e114dc3c27d1ad444ea2eb3456
2,206
Metronome
MIT License
compiler/testData/diagnostics/tests/functionAsExpression/ReceiverByExpectedType.kt
IVIanuu
333,718,537
true
null
// !WITH_NEW_INFERENCE fun foo(<!UNUSED_PARAMETER!>f<!>: String.() -> Int) {} val test = foo(<!TYPE_MISMATCH{NI}, TYPE_MISMATCH{NI}, TYPE_MISMATCH!>fun <!EXPECTED_PARAMETERS_NUMBER_MISMATCH{NI}!>()<!> = <!UNRESOLVED_REFERENCE!>length<!><!>)
1
null
1
1
f49cf2d5cabf8fb9833ec95e1151a00b8b53d087
241
kotlin
Apache License 2.0
DataStructures/src/main/kotlin/Queue.kt
paulosabaini
320,322,636
false
null
import kotlin.system.exitProcess class Queue ( private val size: Int, private var head: Int = -1, private var tail: Int = -1, private var arr: IntArray = IntArray(size) ) { fun enqueue(x: Int) { if (head == -1) head ++ if (tail == size - 1) { println("Overflow error. The Queue is full!") exitProcess(0) } else { tail++ arr[tail] = x } } fun dequeueAndShift(): Int { if(isEmpty()) { println("Underflow error. The Queue is empty!") exitProcess(0) } else { val n = arr[0] for (i in 0..tail) { arr[i] = arr[i+1] } tail-- return n } } fun dequeue(): Int { if(isEmpty()) { println("Underflow error. The Queue is empty!") exitProcess(0) } else { val n = arr[head] if (head == tail) { head = -1 tail = -1 } else head++ return n } } fun isEmpty(): Boolean { return (tail == -1 && head == -1) } fun display() { println("\nQueue Print\n") arr.forEach { println(it) } } } fun main() { val q = Queue(10) q.enqueue(10) q.enqueue(100) q.enqueue(1000) q.enqueue(1001) q.enqueue(1002) println("removed ${q.dequeue()}") q.enqueue(1003) println("removed ${q.dequeue()}") println("removed ${q.dequeue()}") q.enqueue(1004) q.display() }
0
Kotlin
0
0
00f7fa16e502f15cec570c31f544c001cfe20934
1,597
kotlin-data-structures-algorithms
MIT License
DataStructures/src/main/kotlin/Queue.kt
paulosabaini
320,322,636
false
null
import kotlin.system.exitProcess class Queue ( private val size: Int, private var head: Int = -1, private var tail: Int = -1, private var arr: IntArray = IntArray(size) ) { fun enqueue(x: Int) { if (head == -1) head ++ if (tail == size - 1) { println("Overflow error. The Queue is full!") exitProcess(0) } else { tail++ arr[tail] = x } } fun dequeueAndShift(): Int { if(isEmpty()) { println("Underflow error. The Queue is empty!") exitProcess(0) } else { val n = arr[0] for (i in 0..tail) { arr[i] = arr[i+1] } tail-- return n } } fun dequeue(): Int { if(isEmpty()) { println("Underflow error. The Queue is empty!") exitProcess(0) } else { val n = arr[head] if (head == tail) { head = -1 tail = -1 } else head++ return n } } fun isEmpty(): Boolean { return (tail == -1 && head == -1) } fun display() { println("\nQueue Print\n") arr.forEach { println(it) } } } fun main() { val q = Queue(10) q.enqueue(10) q.enqueue(100) q.enqueue(1000) q.enqueue(1001) q.enqueue(1002) println("removed ${q.dequeue()}") q.enqueue(1003) println("removed ${q.dequeue()}") println("removed ${q.dequeue()}") q.enqueue(1004) q.display() }
0
Kotlin
0
0
00f7fa16e502f15cec570c31f544c001cfe20934
1,597
kotlin-data-structures-algorithms
MIT License
src/commonMain/kotlin/org/petitparser/core/parser/consumer/String.kt
petitparser
541,100,427
false
null
package org.petitparser.core.parser.consumer import org.petitparser.core.context.Input import org.petitparser.core.context.Output import org.petitparser.core.parser.Parser /** Returns a parser that accepts the [string]. */ fun string(string: String, message: String = "'$string' expected", ignoreCase: Boolean = false) = string({ string.equals(it, ignoreCase) }, string.length, message) /** Returns a parser that accepts string satisfying the given [predicate]. */ fun string(predicate: (String) -> Boolean, length: Int, message: String) = object : Parser<String> { override fun parseOn(input: Input): Output<String> { val stop = input.position + length if (stop <= input.buffer.length) { val string = input.buffer.substring(input.position, stop) if (predicate(string)) { return input.success(string, stop) } } return input.failure(message) } }
1
null
1
5
349522c37813e7714f66af4ed27db0b5750dd6f0
896
kotlin-petitparser
MIT License
use-case-app/core/src/main/kotlin/de/gransoftware/core/usecase/UseCaseEngine.kt
gran-software-solutions
616,888,843
false
null
package de.gransoftware.core.usecase interface UseCase<in Input, out T : Any> { suspend operator fun invoke(input: Input): Outcome<T> } enum class ErrorType { WEATHER_API_ERROR, PLACE_INFO_API_ERROR } sealed class Outcome<out T : Any> { data class Success<out T : Any>(val value: T) : Outcome<T>() data class Error(val errorType: ErrorType, val exception: Throwable? = null) : Outcome<Nothing>() } object UseCaseExecutor { // some params - some response suspend fun <Request, Response, Input, T : Any> execute( useCase: UseCase<Input, T>, toContext: suspend () -> Request, toInput: (Request) -> Input, toResponse: (Outcome<T>) -> Response ) = toContext.invoke() .let(toInput) .let { useCase(it) } .let(toResponse) // some params - no response suspend fun <Request, Input> execute( useCase: UseCase<Input, Unit>, toContext: () -> Request, toInput: (Request) -> Input ) = execute(useCase, toContext, toInput) {} // no params - no response suspend fun execute(useCase: UseCase<Unit, Unit>) = execute(useCase, { }) { } // no params - some response suspend fun <Response, T : Any> execute( useCase: UseCase<Unit, T>, toResponse: (Outcome<T>) -> Response ) = execute(useCase, {}, { }, toResponse) }
0
Kotlin
0
0
7673af95a4b52bd04295d0dc333857dc076559af
1,396
code-samples
Apache License 2.0
htmlAnnotator-view/src/main/java/com/ravenl/htmlannotator/view/handler/MultipleSpanHandler.kt
RavenLiao
772,909,415
false
null
package com.ravenl.htmlannotator.view.handler import com.ravenl.htmlannotator.core.TextStyler import com.ravenl.htmlannotator.core.css.model.CSSDeclaration import com.ravenl.htmlannotator.core.handler.NewLineHandler import com.ravenl.htmlannotator.view.styler.SpannedStyler import org.jsoup.nodes.Node open class MultipleSpanHandler(addNewLineAtBefore: Boolean = true, val newSpans: () -> List<Any>) : NewLineHandler(addNewLineAtBefore) { private val spans by lazy { newSpans() } override fun handleTagNode( builder: StringBuilder, rangeList: MutableList<TextStyler>, cssDeclarations: List<CSSDeclaration>?, node: Node, start: Int, end: Int ) { rangeList.addAll(getTagStylers(node, start, end)) } open fun getTagStylers(node: Node, start: Int, end: Int): List<TextStyler> = spans.map { SpannedStyler(start, end, it) } }
0
null
0
3
b60aec48b44be2cfefb797376a74f05c52a98bce
917
HtmlAnnotator
Apache License 2.0
project/common-script-api/src/main/kotlin/ink/ptms/artifex/scripting/Backend.kt
TabooLib
492,563,163
false
null
package ink.ptms.artifex.scripting import taboolib.common.platform.ProxyCommandSender import taboolib.common.platform.ProxyPlayer import taboolib.common.platform.command.CommandContext import taboolib.common.platform.command.component.CommandComponent import taboolib.common.platform.command.component.CommandComponentDynamic fun CommandComponent.execute(function: (sender: ProxyCommandSender, args: CommandContext<ProxyCommandSender>) -> Unit) = execute<ProxyCommandSender> { sender, context, _ -> function(sender, context) } fun CommandComponent.executeAsPlayer(function: (sender: ProxyPlayer, args: CommandContext<ProxyPlayer>) -> Unit) = execute<ProxyPlayer> { sender, context, _ -> function(sender, context) } fun CommandComponentDynamic.suggest(uncheck: Boolean = false, function: () -> List<String>?) = suggestion<ProxyCommandSender>(uncheck) { _, _ -> function() } fun CommandComponentDynamic.suggestAsPlayer(uncheck: Boolean = false, function: () -> List<String>?) = suggestion<ProxyPlayer>(uncheck) { _, _ -> function() } fun CommandComponentDynamic.restrict(function: (argument: String) -> Boolean) = restrict<ProxyCommandSender> { _, _, argument -> function(argument) } fun CommandComponentDynamic.restrictAsPlayer(function: (argument: String) -> Boolean) = restrict<ProxyPlayer> { _, _, argument -> function(argument) } fun CommandContext<*>.argument(): String { return argument(0) }
1
null
6
24
b6fe7716c0730a9b197ca009f22ee179041a22ec
1,432
artifex
Creative Commons Zero v1.0 Universal
src/main/java/ru/hollowhorizon/hollowengine/common/recipes/RecipeHelper.kt
HollowHorizon
586,593,959
false
{"Kotlin": 945627, "Java": 23246, "GLSL": 2628}
/* * MIT License * * Copyright (c) 2024 HollowHorizon * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ru.hollowhorizon.hollowengine.common.recipes import net.minecraft.resources.ResourceLocation import ru.hollowhorizon.hollowengine.HollowEngine.Companion.MODID import ru.hollowhorizon.hollowengine.common.scripting.content.ContentScriptBase object RecipeHelper { var currentScript: ContentScriptBase? = null var latestId = 0 fun createRecipeId() = ResourceLocation(MODID, "custom/recipe_${latestId++}") }
0
Kotlin
6
27
a81eb9337c22e97c950528d2e5b638ff81ce2d2e
1,562
HollowEngine
MIT License
app/src/main/java/org/mydaily/util/CalendarUtil.kt
TeamMyDaily
325,142,861
false
null
package org.mydaily.util import java.text.SimpleDateFormat import java.util.* object CalendarUtil { private val simpleDateFormat = SimpleDateFormat("yy년 MM월 dd일", Locale.KOREA) private val simpleDateFormatWithWeek = SimpleDateFormat("yy년 MM월 W주", Locale.KOREA) fun convertCalendarToString(calendar: Calendar): String = simpleDateFormat.format(calendar.time) fun convertCalendarToWeekString(calendar: Calendar): String = simpleDateFormatWithWeek.format(calendar.time) fun convertMilliSecToWeekString(millisec: Long): String = simpleDateFormatWithWeek.format(millisec) fun convertCalendarToString(year: Int, month: Int, day: Int): String { val calendar = Calendar.getInstance() calendar.set(year, month, day) return simpleDateFormat.format(calendar.time) } fun Calendar.compareDateTo(c1: Calendar): Boolean { return get(Calendar.YEAR) == c1.get(Calendar.YEAR) && get(Calendar.MONTH) == c1.get(Calendar.MONTH) && get(Calendar.DAY_OF_MONTH) == c1.get(Calendar.DAY_OF_MONTH) } fun Calendar.isWeekSame(c1: Calendar): Boolean { return get(Calendar.YEAR) == c1.get(Calendar.YEAR) && get(Calendar.MONTH) == c1.get(Calendar.MONTH) && get(Calendar.WEEK_OF_MONTH) == c1.get(Calendar.WEEK_OF_MONTH) } fun Calendar.copyYMDFrom(c1: Calendar) { set(c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DATE)) } }
4
Kotlin
1
9
d820795fe1a6332de9ceb6b69ad1d137038d0910
1,495
4most-Android
Apache License 2.0
src/main/kotlin/icu/windea/pls/config/config/CwtConfigMatchType.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.config.config /** * CWT规则的匹配类型。 */ object CwtConfigMatchType { /** * 静态匹配:带参数、需要访问索引等场合,直接认为匹配。 */ const val STATIC = 0x01 /** * 非精确匹配:不需要匹配数字范围、作用域等。 */ const val NOT_EXACT = 0x02 /** * 需要访问文件路径索引。 * @see icu.windea.pls.core.index.ParadoxFilePathIndex */ const val FILE_PATH = 0x04 /** * 需要访问定义索引。 * @see icu.windea.pls.core.index.ParadoxDefinitionNameIndex * @see icu.windea.pls.core.index.ParadoxDefinitionTypeIndex */ const val DEFINITION = 0x08 /** * 需要访问本地化索引。 * @see icu.windea.pls.core.index.ParadoxLocalisationNameIndex * @see icu.windea.pls.core.index.ParadoxSyncedLocalisationNameIndex */ const val LOCALISATION = 0x10 /** * 需要访问复杂枚举值索引。 * @see icu.windea.pls.core.index.ParadoxComplexEnumValueIndex * @see icu.windea.pls.core.index.ParadoxComplexEnumIndex */ const val COMPLEX_ENUM_VALUE = 0x20 const val DEFAULT = FILE_PATH or DEFINITION or LOCALISATION or COMPLEX_ENUM_VALUE const val INSPECTION = DEFINITION or LOCALISATION or COMPLEX_ENUM_VALUE }
2
Kotlin
2
14
a3816071d500f8cf993240885895966be67ef5c8
1,054
Paradox-Language-Support
MIT License
app/src/main/java/bruhcollective/itaysonlab/cobalt/ui/theme/Theme.kt
iTaysonLab
529,265,880
false
{"Kotlin": 451014}
package bruhcollective.itaysonlab.jetisteam.ui.theme import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.graphics.luminance import androidx.compose.ui.platform.LocalContext import com.google.accompanist.systemuicontroller.rememberSystemUiController private val DarkColorScheme = darkColorScheme( primary = Accent, onPrimary = Color.Black, secondary = Accent, tertiary = Accent, background = Color.Black, surface = Color.Black, surfaceVariant = Color.White.copy(alpha = 0.15f).compositeOver(Color.Black), outline = Color.White.copy(alpha = 0.25f).compositeOver(Color.Black), outlineVariant = Color.White.copy(alpha = 0.35f).compositeOver(Color.Black), secondaryContainer = Color.White.copy(alpha = 0.35f).compositeOver(Color.Black), surfaceTint = Color.White, onSecondaryContainer = Color.White, ) private val LightColorScheme = lightColorScheme() @Composable fun CobaltTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val sysUiController = rememberSystemUiController() val colorScheme = when { darkTheme -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { dynamicDarkColorScheme(LocalContext.current) } else { DarkColorScheme } } else -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { dynamicLightColorScheme(LocalContext.current) } else { LightColorScheme } } } SideEffect { sysUiController.setSystemBarsColor(color = Color.Transparent, darkIcons = colorScheme.background.luminance() > 0.5f) } MaterialTheme( colorScheme = colorScheme, typography = CobaltTypography, content = content ) }
2
Kotlin
5
97
78a9d963893e0b675cb0e3b1a2b6b936c0be3d19
2,331
jetisteam
Apache License 2.0
server-testing/src/main/kotlin/com/lightningkite/lightningdb/test/models.kt
lightningkite
512,032,499
false
{"Kotlin": 2189721, "TypeScript": 38628, "Ruby": 873, "JavaScript": 118}
@file:UseContextualSerialization(UUID::class, Instant::class, ServerFile::class) package com.lightningkite.lightningdb.test import com.lightningkite.GeoCoordinate import com.lightningkite.lightningdb.* import com.lightningkite.lightningdb.HasId import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable import kotlinx.serialization.UseContextualSerialization import kotlinx.datetime.Instant import java.util.* import com.lightningkite.lightningdb.* import com.lightningkite.UUID import com.lightningkite.uuid @GenerateDataClassPaths() @Serializable data class User( override val _id: UUID = uuid(), @Unique override var email: String, @Unique override val phoneNumber: String, var age: Long = 0, var friends: List<UUID> = listOf() ) : HasId<UUID>, HasEmail, HasPhoneNumber { companion object } @GenerateDataClassPaths @Serializable data class ValidatedModel( @ExpectedPattern("[a-zA-Z ]+") @MaxLength(15) val name: String, ) @GenerateDataClassPaths @Serializable data class CompoundKeyTestModel( override val _id: CompoundTestKey = CompoundTestKey("first", "second"), val value: Int = 0, ): HasId<CompoundTestKey> @GenerateDataClassPaths @Serializable data class CompoundTestKey( val first: String, val second: String, ): Comparable<CompoundTestKey> { companion object { val comparator = compareBy<CompoundTestKey> { it.first }.thenBy { it.second } } override fun compareTo(other: CompoundTestKey): Int = comparator.compare(this, other) } @GenerateDataClassPaths() @Serializable data class Post( override val _id: UUID = uuid(), var author: UUID, var content: String, var at: Long? = null ) : HasId<UUID> { companion object } @GenerateDataClassPaths() @Serializable data class Employee( override val _id: UUID = uuid(), var dictionary: Map<String, Int> = mapOf(), ) : HasId<UUID> { companion object } @GenerateDataClassPaths @Serializable data class EmbeddedObjectTest( override val _id: UUID = uuid(), var name: String = "", var embed1: ClassUsedForEmbedding = ClassUsedForEmbedding("value1", 1), var embed2: ClassUsedForEmbedding = ClassUsedForEmbedding("value2", 2), ) : HasId<UUID> { companion object } @GenerateDataClassPaths @Serializable data class ClassUsedForEmbedding( var value1:String = "default", var value2:Int = 1 ) @Serializable data class RecursiveEmbed( var embedded:RecursiveEmbed? = null, var value2:String = "value2" ) @GenerateDataClassPaths @Serializable data class HasServerFiles( val file: ServerFile, val optionalFile: ServerFile? = null ) @GenerateDataClassPaths @Serializable data class EmbeddedNullable( override val _id: UUID = uuid(), var name: String = "", var embed1: ClassUsedForEmbedding? = null, ) : HasId<UUID> { companion object } @GenerateDataClassPaths @Serializable data class LargeTestModel( override val _id: UUID = uuid(), var boolean: Boolean = false, var byte: Byte = 0, var short: Short = 0, @Index var int: Int = 0, var long: Long = 0, var float: Float = 0f, var double: Double = 0.0, var char: Char = ' ', var string: String = "", var uuid: UUID = UUID(0L, 0L), var instant: Instant = Instant.fromEpochMilliseconds(0L), var list: List<Int> = listOf(), var listEmbedded: List<ClassUsedForEmbedding> = listOf(), var set: Set<Int> = setOf(), var setEmbedded: Set<ClassUsedForEmbedding> = setOf(), var map: Map<String, Int> = mapOf(), var embedded: ClassUsedForEmbedding = ClassUsedForEmbedding(), var booleanNullable: Boolean? = null, var byteNullable: Byte? = null, var shortNullable: Short? = null, var intNullable: Int? = null, var longNullable: Long? = null, var floatNullable: Float? = null, var doubleNullable: Double? = null, var charNullable: Char? = null, var stringNullable: String? = null, var uuidNullable: UUID? = null, var instantNullable: Instant? = null, var listNullable: List<Int>? = null, var mapNullable: Map<String, Int>? = null, var embeddedNullable: ClassUsedForEmbedding? = null, ) : HasId<UUID> { companion object } @GenerateDataClassPaths @Serializable data class GeoTest( override val _id: UUID = uuid(), @Index val geo: GeoCoordinate = GeoCoordinate(41.727019, -111.8443002) ) : HasId<UUID> { companion object } @GenerateDataClassPaths @Serializable data class EmbeddedMap( override val _id: UUID = uuid(), var map: Map<String, RecursiveEmbed>, ) : HasId<UUID> @GenerateDataClassPaths @Serializable data class MetaTestModel( override val _id: UUID = uuid(), val condition: Condition<LargeTestModel>, val modification: Modification<LargeTestModel> ) : HasId<UUID> { }
3
Kotlin
1
5
f404cc57cbdbe2a90b4e59d4ecd5ad22e008a730
4,800
lightning-server
MIT License
app/src/main/java/com/example/bomber/presentation/GameViewModel.kt
dmitriismirnov
396,307,187
false
null
package com.example.bomber.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.bomber.domain.GameEngine import com.example.bomber.game.GameState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class GameViewModel @Inject constructor( private val gameEngine: GameEngine, ) : ViewModel() { val gameState: StateFlow<GameState> = gameEngine.gameFlow.stateIn(viewModelScope, SharingStarted.Lazily, GameState.INITIAL) // TODO: use coroutines in proper way val moveUpdates = gameEngine.moveUpdates.launchIn(viewModelScope) val bombUpdates = gameEngine.bombsUpdates.launchIn(viewModelScope) fun pressUp() { gameEngine.goUp() } fun releaseUp() { gameEngine.stopMoving() } fun pressDown() { gameEngine.goDown() } fun releaseDown() { gameEngine.stopMoving() } fun pressLeft() { gameEngine.goLeft() } fun releaseLeft() { gameEngine.stopMoving() } fun pressRight() { gameEngine.goRight() } fun releaseRight() { gameEngine.stopMoving() } fun pressBomb() { gameEngine.placeBomb() } fun releaseBomb() = Unit fun pauseGame() { gameEngine.pauseGame() } fun runGame() { gameEngine.runGame() } fun restartGame() { gameEngine.restartGame() } }
0
Kotlin
0
1
e732ccf9cffe4008d76949038d58f604059e2f0c
1,461
bomber
Apache License 2.0
compiler/tests-spec/testData/psi/linked/when-expression/p-7/neg/3.1.kt
tnorbye
162,147,688
false
null
/* * KOTLIN PSI SPEC TEST (NEGATIVE) * * SECTIONS: when-expression * PARAGRAPH: 7 * SENTENCE: [3] Contains test condition: containment operator followed by an expression. * NUMBER: 1 * DESCRIPTION: 'When' with bound value and 'when condition' with range expression, but without contains operator. */ fun case_1() { when (value) { in -> return "" } when (value) { in -> return "" in -> return "" } }
0
null
2
2
b6be6a4919cd7f37426d1e8780509a22fa49e1b1
448
kotlin
Apache License 2.0
sample/src/androidTest/java/com/freeletics/rxredux/PopularRepositoriesActivityTest.kt
freeletics
138,705,451
false
null
package com.freeletics.coredux import android.content.Intent import android.support.test.espresso.Espresso import android.support.test.espresso.ViewAction import android.support.test.espresso.action.GeneralLocation import android.support.test.espresso.action.GeneralSwipeAction import android.support.test.espresso.action.Press import android.support.test.espresso.action.Swipe import android.support.test.espresso.action.ViewActions import android.support.test.espresso.contrib.RecyclerViewActions import android.support.test.espresso.matcher.ViewMatchers import android.support.test.rule.ActivityTestRule import android.support.test.rule.GrantPermissionRule import android.support.test.runner.AndroidJUnit4 import android.support.v7.widget.RecyclerView import com.freeletics.coredux.businesslogic.pagination.PaginationStateMachine import io.reactivex.Observable import io.victoralbertos.device_animation_test_rule.DeviceAnimationTestRule import okhttp3.mockwebserver.MockWebServer import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import tools.fastlane.screengrab.Screengrab import tools.fastlane.screengrab.UiAutomatorScreenshotStrategy import tools.fastlane.screengrab.locale.LocaleTestRule @RunWith(AndroidJUnit4::class) class PopularRepositoriesActivityTest { @get:Rule val activityTestRule = ActivityTestRule(PopularRepositoriesActivity::class.java, false, false) @get:Rule val permission = GrantPermissionRule.grant(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) companion object { @get:ClassRule @JvmStatic val localeTestRule = LocaleTestRule() @get:ClassRule @JvmStatic var deviceAnimationTestRule = DeviceAnimationTestRule() } @Test fun runTests() { // Setup test environment Screengrab.setDefaultScreenshotStrategy(UiAutomatorScreenshotStrategy()) PopularRepositoriesSpec( screen = AndroidScreen(activityTestRule), stateHistory = StateHistory(AndroidStateRecorder()), config = ScreenConfig(mockWebServer = MockWebServer().setupForHttps()) ).runTests("Failed to connect to /127.0.0.1:$MOCK_WEB_SERVER_PORT") } class AndroidScreen( private val activityRule: ActivityTestRule<PopularRepositoriesActivity> ) : Screen { override fun scrollToEndOfList() { Espresso .onView(ViewMatchers.withId(R.id.recyclerView)) .perform( RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>( RecordingPopularRepositoriesViewBinding.INSTANCE.lastPositionInAdapter() - 1 ) ) Espresso .onView(ViewMatchers.withId(R.id.recyclerView)) .perform(swipeFromBottomToTop()) } override fun retryLoadingFirstPage() { Espresso.onView(ViewMatchers.withId(R.id.error)) .perform(ViewActions.click()) } override fun loadFirstPage() { activityRule.launchActivity(Intent()) } private fun swipeFromBottomToTop(): ViewAction { return GeneralSwipeAction( Swipe.FAST, GeneralLocation.BOTTOM_CENTER, GeneralLocation.TOP_CENTER, Press.FINGER ) } } inner class AndroidStateRecorder : StateRecorder { override fun renderedStates(): Observable<PaginationStateMachine.State> = RecordingPopularRepositoriesViewBinding.INSTANCE.recordedStates } }
10
Kotlin
6
572
6326055ac3097f5eea3f7262a5c312eee40d895d
3,617
RxRedux
Apache License 2.0
compiler/ir/ir.tree/gen/org/jetbrains/kotlin/ir/declarations/IrReturnTarget.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ // This file was generated automatically. See compiler/ir/ir.tree/tree-generator/ReadMe.md. // DO NOT MODIFY IT MANUALLY. package org.jetbrains.kotlin.ir.declarations import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol /** * A non-leaf IR tree element. * @sample org.jetbrains.kotlin.ir.generator.IrTree.returnTarget */ interface IrReturnTarget : IrSymbolOwner { @ObsoleteDescriptorBasedAPI val descriptor: FunctionDescriptor override val symbol: IrReturnTargetSymbol }
181
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
824
kotlin
Apache License 2.0
shared/src/main/kotlin/xlitekt/shared/buffer/ByteBuffer.kt
runetopic
448,110,155
false
null
package xlitekt.shared.buffer import xlitekt.shared.toInt import java.nio.ByteBuffer /** * @author <NAME> * Extension functions for the ByteBuffer class for unpacking cache data. * Extension functions for the ByteBuffer class used for building packets. */ fun ByteBuffer.readStringCp1252NullTerminated() = String(readUChars(duplicate().discardUntilDelimiter(0))).also { discard(1) } fun ByteBuffer.readStringCp1252NullCircumfixed(): String { if (readByte() != 0) throw IllegalArgumentException() return readStringCp1252NullTerminated() } fun ByteBuffer.readUChars(n: Int) = CharArray(n) { readUByte().toChar() } fun ByteBuffer.readByte() = get().toInt() fun ByteBuffer.readUByte() = get().toInt() and 0xff fun ByteBuffer.readUByteSubtract() = readUByte() - 128 and 0xff fun ByteBuffer.readUByteAdd() = readUByte() + 128 and 0xff fun ByteBuffer.readUByteNegate() = -readUByte() and 0xff fun ByteBuffer.readShort() = short.toInt() fun ByteBuffer.readUShort() = short.toInt() and 0xffff fun ByteBuffer.readUShortAdd() = (readUByte() shl 8) or readUByteAdd() fun ByteBuffer.readUShortSubtract() = (readUByte() shl 8) or readUByteSubtract() fun ByteBuffer.readUShortLittleEndian() = readUByte() or (readUByte() shl 8) fun ByteBuffer.readUShortLittleEndianSubtract() = readUByteSubtract() or (readUByte() shl 8) fun ByteBuffer.readUShortLittleEndianAdd() = readUByteAdd() or (readUByte() shl 8) fun ByteBuffer.readUMedium() = (readUByte() shl 16) or readUShort() fun ByteBuffer.readInt() = int fun ByteBuffer.readIntLittleEndian() = readUShortLittleEndian() or (readUByte() shl 16) or (readUByte() shl 24) fun ByteBuffer.readIntV1() = readUShort() or (readUByte() shl 24) or (readUByte() shl 16) fun ByteBuffer.readIntV2() = (readUByte() shl 16) or (readUByte() shl 24) or readUShortLittleEndian() fun ByteBuffer.readLong(): Long { val f = readInt().toLong() and 0xffffffff val s = readInt().toLong() and 0xffffffff return (f shl 32) + s } tailrec fun ByteBuffer.readIncrSmallSmart(increment: Int = readUShortSmart(), offset: Int = 0): Int { if (increment != Short.MAX_VALUE.toInt()) return offset + increment return readIncrSmallSmart(offset = offset + Short.MAX_VALUE) } fun ByteBuffer.readShortSmart(): Int { val peek = readUByte() return if (peek < 128) peek - 64 else (peek shl 8 or readUByte()) - 49152 } fun ByteBuffer.readUShortSmart(): Int { val peek = readUByte() return if (peek < 128) peek else (peek shl 8 or readUByte()) - 32768 } fun ByteBuffer.readUIntSmart(): Int { val peek = readUByte() return if (peek < 0) ((peek shl 24) or (readUByte() shl 16) or (readUByte() shl 8) or readUByte()) and Integer.MAX_VALUE else { (peek shl 8 or readUByte()).toShort().let { if (it == Short.MAX_VALUE) -1 else it }.toInt() } } tailrec fun ByteBuffer.readVarInt(increment: Int = readByte(), offset: Int = 0): Int { if (increment >= 0) return offset or increment return readVarInt(offset = (offset or (increment and 127)) shl 7) } tailrec fun ByteBuffer.method7754(opcode: Int = readUByte(), offset: Int = 0, value: Int = 0): Int { if (opcode <= Byte.MAX_VALUE) return value return method7754(opcode, offset = offset + 7, value = value or ((opcode and 127) shl offset)) } fun ByteBuffer.writeStringCp1252NullTerminated(value: String) { value.toByteArray().forEach(::put) put(0) } fun ByteBuffer.writeBytes(bytes: ByteArray) { bytes.forEach(::put) } fun ByteBuffer.writeBytesAdd(bytes: ByteArray) { bytes.forEach { writeByteAdd(it.toInt()) } } fun ByteBuffer.writeSmart(value: Int) { if (value > 128) putShort(value.toShort()) else put(value.toByte()) } fun ByteBuffer.writeByte(value: Int) { put(value.toByte()) } fun ByteBuffer.writeByteSubtract(value: Int) { put((128 - value.toByte()).toByte()) } fun ByteBuffer.writeByteAdd(value: Int) { put((value.toByte() + 128).toByte()) } fun ByteBuffer.writeByteNegate(value: Int) { put((-value.toByte()).toByte()) } fun ByteBuffer.writeShort(value: Int) { putShort(value.toShort()) } fun ByteBuffer.writeShortAdd(value: Int) { put((value shr 8).toByte()) writeByteAdd(value) } fun ByteBuffer.writeShortLittleEndian(value: Int) { put(value.toByte()) put((value shr 8).toByte()) } fun ByteBuffer.writeShortLittleEndianAdd(value: Int) { writeByteAdd(value) put((value shr 8).toByte()) } fun ByteBuffer.writeMedium(value: Int) { put((value shr 16).toByte()) putShort(value.toShort()) } fun ByteBuffer.writeInt(value: Int) { putInt(value) } fun ByteBuffer.writeIntLittleEndian(value: Int) { writeShortLittleEndian(value) put((value shr 16).toByte()) put((value shr 24).toByte()) } fun ByteBuffer.writeIntV1(value: Int) { putShort(value.toShort()) put((value shr 24).toByte()) put((value shr 16).toByte()) } fun ByteBuffer.writeIntV2(value: Int) { put((value shr 16).toByte()) put((value shr 24).toByte()) writeShortLittleEndian(value) } fun ByteBuffer.fill(n: Int, value: Int) { repeat(n) { put(value.toByte()) } } fun ByteBuffer.tryPeek() = this[position()].toInt() and 0xff fun ByteBuffer.discard(n: Int) { position(position() + n) } fun ByteBuffer.discardUntilDelimiter(delimiter: Int): Int { var count = 0 while (readByte() != delimiter) { count++ } return count } inline fun ByteBuffer.withBitAccess(block: BitAccess.() -> Unit) { val bitAccess = BitAccess(this) block.invoke(bitAccess) position((bitAccess.bitIndex + 7) / 8) } class BitAccess(val buffer: ByteBuffer) { var bitIndex = buffer.position() * 8 fun writeBit(value: Boolean) { writeBits(1, value.toInt()) } fun writeBits(count: Int, value: Int) { var numBits = count var byteIndex = bitIndex shr 3 var bitOffset = 8 - (bitIndex and 7) bitIndex += numBits while (numBits > bitOffset) { val max = masks[bitOffset] val tmp = buffer.get(byteIndex).toInt() and max.inv() or (value shr numBits - bitOffset and max) buffer.put(byteIndex++, tmp.toByte()) numBits -= bitOffset bitOffset = 8 } var dataValue = buffer.get(byteIndex).toInt() val mask = masks[numBits] if (numBits == bitOffset) { dataValue = dataValue and mask.inv() or (value and mask) } else { dataValue = dataValue and (mask shl bitOffset - numBits).inv() dataValue = dataValue or (value and mask shl bitOffset - numBits) } buffer.put(byteIndex, dataValue.toByte()) } companion object { val masks = IntArray(32) init { masks.indices.forEach { masks[it] = (1 shl it) - 1 } } } }
0
Kotlin
3
8
c896a2957470769a212961ba3e4331f04fc785df
6,788
xlitekt
MIT License
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/compiler.kt
mogahed0118
142,181,323
true
{"Kotlin": 28617854, "Java": 7550039, "JavaScript": 153376, "HTML": 65397, "Lex": 18269, "ANTLR": 9797, "IDL": 8755, "Shell": 6769, "CSS": 4679, "Batchfile": 4437, "Groovy": 4358}
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.ir.backend.js import com.intellij.openapi.project.Project import org.jetbrains.kotlin.backend.common.lower.* import org.jetbrains.kotlin.backend.common.runOnFilePostfix import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.ir.backend.js.lower.* import org.jetbrains.kotlin.ir.backend.js.lower.inline.* import org.jetbrains.kotlin.ir.backend.js.transformers.irToJs.IrModuleToJsTransformer import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.util.ExternalDependenciesGenerator import org.jetbrains.kotlin.ir.util.patchDeclarationParents import org.jetbrains.kotlin.js.analyze.TopDownAnalyzerFacadeForJS import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi2ir.Psi2IrTranslator data class Result(val moduleDescriptor: ModuleDescriptor, val generatedCode: String) fun compile( project: Project, files: List<KtFile>, configuration: CompilerConfiguration, export: FqName? = null, dependencies: List<ModuleDescriptor> = listOf() ): Result { val analysisResult = TopDownAnalyzerFacadeForJS.analyzeFiles(files, project, configuration, dependencies.filterIsInstance(), emptyList()) ProgressIndicatorAndCompilationCanceledStatus.checkCanceled() TopDownAnalyzerFacadeForJS.checkForErrors(files, analysisResult.bindingContext) val psi2IrTranslator = Psi2IrTranslator() val psi2IrContext = psi2IrTranslator.createGeneratorContext(analysisResult.moduleDescriptor, analysisResult.bindingContext) val moduleFragment = psi2IrTranslator.generateModuleFragment(psi2IrContext, files).removeDuplicates() val context = JsIrBackendContext( analysisResult.moduleDescriptor, psi2IrContext.irBuiltIns, psi2IrContext.symbolTable, moduleFragment ) ExternalDependenciesGenerator(psi2IrContext.moduleDescriptor, psi2IrContext.symbolTable, psi2IrContext.irBuiltIns) .generateUnboundSymbolsAsDependencies(moduleFragment) context.performInlining(moduleFragment) moduleFragment.files.forEach { context.lower(it) } val transformer = SecondaryCtorLowering.CallsiteRedirectionTransformer(context) moduleFragment.files.forEach { it.accept(transformer, null) } val program = moduleFragment.accept(IrModuleToJsTransformer(context), null) return Result(analysisResult.moduleDescriptor, program.toString()) } private fun JsIrBackendContext.performInlining(moduleFragment: IrModuleFragment) { FunctionInlining(this).inline(moduleFragment) moduleFragment.referenceAllTypeExternalClassifiers(symbolTable) do { @Suppress("DEPRECATION") moduleFragment.replaceUnboundSymbols(this) moduleFragment.referenceAllTypeExternalClassifiers(symbolTable) } while (symbolTable.unboundClasses.isNotEmpty()) moduleFragment.patchDeclarationParents() moduleFragment.files.forEach { file -> RemoveInlineFunctionsWithReifiedTypeParametersLowering.runOnFilePostfix(file) } } private fun JsIrBackendContext.lower(file: IrFile) { LateinitLowering(this, true).lower(file) DefaultArgumentStubGenerator(this).runOnFilePostfix(file) DefaultParameterInjector(this).runOnFilePostfix(file) SharedVariablesLowering(this).runOnFilePostfix(file) ReturnableBlockLowering(this).lower(file) LocalDeclarationsLowering(this).runOnFilePostfix(file) InnerClassesLowering(this).runOnFilePostfix(file) InnerClassConstructorCallsLowering(this).runOnFilePostfix(file) PropertiesLowering().lower(file) InitializersLowering(this, JsLoweredDeclarationOrigin.CLASS_STATIC_INITIALIZER, false).runOnFilePostfix(file) MultipleCatchesLowering(this).lower(file) BridgesConstruction(this).runOnFilePostfix(file) TypeOperatorLowering(this).lower(file) BlockDecomposerLowering(this).runOnFilePostfix(file) SecondaryCtorLowering(this).runOnFilePostfix(file) CallableReferenceLowering(this).lower(file) IntrinsicifyCallsLowering(this).lower(file) } // TODO find out why duplicates occur private fun IrModuleFragment.removeDuplicates(): IrModuleFragment { fun <T> MutableList<T>.removeDuplicates() { val tmp = toSet() clear() addAll(tmp) } dependencyModules.removeDuplicates() dependencyModules.forEach { it.externalPackageFragments.removeDuplicates() } return this }
1
Kotlin
1
1
7b6df0a7cc8494dc43409535adce4880092ce393
4,798
kotlin
Apache License 2.0
payment-api/payment-domain/src/main/kotlin/org/collaborators/paymentslab/payment/domain/repository/TossPaymentsRepository.kt
f-lab-edu
665,758,863
false
{"Kotlin": 165334, "HTML": 1979, "Shell": 1679, "Dockerfile": 298}
package org.collaborators.paymentslab.payment.domain.repository import org.collaborators.paymentslab.payment.domain.entity.TossPayments interface TossPaymentsRepository { fun save(entity: TossPayments): TossPayments }
0
Kotlin
1
9
9455e02b6a962a363b5aaf32dbd4fbde7d52a477
223
payment-lab
MIT License
app/src/main/java/com/analytics/device/utils/UsageUtils.kt
niyiomotoso
662,027,110
false
null
package com.analytics.device.utils import android.app.usage.UsageEvents import android.app.usage.UsageStatsManager import android.content.Context import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.analytics.device.helpers.DateTimeHelper import com.analytics.device.migrations.AppUsageDatabase import com.analytics.device.models.AppDetails import com.analytics.device.models.AppStats import com.analytics.device.models.AppUsage import com.analytics.device.models.CustomActivityMap import java.time.ZonedDateTime class UsageUtils (var context: Context) { val appUsageDatabase by lazy { AppUsageDatabase.getDatabase(context).appUsageDao() } inner class Usage { suspend fun syncAppUsageInDB(appDetails: AppDetails) { val currentSystemTimeNow = DateTimeHelper.getSystemCurrentTimeNow() val newUsageInstance = AppUsage( appName = appDetails.appName, packageName = appDetails.packageName, frequency = 0, lastOpenTime = appDetails.lastTimeUsed, createdAt = currentSystemTimeNow ) val savedAppUsage = appUsageDatabase.getMostRecentAppUsage(appDetails.packageName) if (savedAppUsage == null) { appUsageDatabase.addAppUsage(newUsageInstance) } else { // has an existing entry val savedLastTimeOpen = savedAppUsage.lastOpenTime val currentLastTimeOpen = appDetails.lastTimeUsed val usageCreatedAt = savedAppUsage.createdAt // check if within the last hour if (DateTimeHelper.isWithInLastMinutes(usageCreatedAt, currentSystemTimeNow, 60)) { // time changed if (savedLastTimeOpen != currentLastTimeOpen && !DateTimeHelper.isWithInLastMinutes(savedLastTimeOpen, currentSystemTimeNow, 1)) { savedAppUsage.frequency = savedAppUsage.frequency + 1 savedAppUsage.lastOpenTime = currentLastTimeOpen appUsageDatabase.updateAppUsage(savedAppUsage) } } else { // last update was not within the last 1 hour, add a new entry appUsageDatabase.addAppUsage(newUsageInstance) } } } suspend fun cleanUpAppUsageInDB() { val timeString = DateTimeHelper.getDateTimeStringDaysFromNow(7) appUsageDatabase.deleteOldAppUsages(timeString) } /** * load the usage stats within a time range */ fun loadGeneralAppEvents(timeInMinutes: Int): HashMap<String, AppStats> { // get all non-system apps val nonSystemApps = GeneralUtils().Utils().getNonSystemAppsList(context) val usm = context.getSystemService(AppCompatActivity.USAGE_STATS_SERVICE) as UsageStatsManager val milliSecondMultiplier: Long = 60000 val start: Long = (ZonedDateTime.now().toInstant().toEpochMilli() - (milliSecondMultiplier * timeInMinutes)) val usageEvents = usm.queryEvents(start, System.currentTimeMillis()) // reset appPackage Map val appPackageMap: HashMap<String, ArrayList<UsageEvents.Event>> = HashMap() while ( usageEvents.hasNextEvent() ) { val usageEvent = UsageEvents.Event() usageEvents.getNextEvent( usageEvent ) if ((usageEvent.eventType == 1 || usageEvent.eventType == 2 || usageEvent.eventType == 23 || usageEvent.eventType == 24)) { // check to skip all system apps if (nonSystemApps[usageEvent.packageName] == null) { continue } val currentList = appPackageMap[usageEvent.packageName] var newAppList = ArrayList<UsageEvents.Event>() if (currentList != null) { newAppList = currentList newAppList.add(usageEvent) } else { newAppList.add(usageEvent) } appPackageMap[usageEvent.packageName] = newAppList } } // send the appPackage Map into a sorting algorithm to extract the stats return sortEachPackageEvent(appPackageMap) } private fun sortEachPackageEvent(appPackageMap: HashMap<String, ArrayList<UsageEvents.Event>>): HashMap<String, AppStats> { val appPackageStats: HashMap<String, AppStats> = HashMap() for ((packageName, appEventList) in appPackageMap) { val classActivityEventMap = HashMap<String, CustomActivityMap>() for(appEvent in appEventList) { Log.e("APPL", "class name is ".plus(appEvent.className).plus(" event type is ").plus(appEvent.eventType).plus(" in time ").plus(DateTimeHelper.getDateTimeBreakdown(appEvent.timeStamp))) val className = appEvent.className if (appEvent.eventType == 1) { // ACTIVITY_RESUMED, reset the current event map for this class classActivityEventMap[className] = CustomActivityMap(appEvent.timeStamp, appEvent.eventType) if (appPackageStats[packageName] == null) { appPackageStats[packageName] = AppStats(packageName, 0, appEvent.timeStamp, 0) } } else if (appEvent.eventType == 2 || appEvent.eventType == 23 || appEvent.eventType == 24) { // ACTIVITY_PAUSED or ACTIVITY_STOPPED or DESTROYED if (classActivityEventMap[className] != null) { // compute the time difference between ACTIVITY_RESUMED/STARTED and this event val existingActivityMap = classActivityEventMap[className] if (existingActivityMap?.eventType == 1) { val timeDiff = appEvent.timeStamp - existingActivityMap.timeStamp if (timeDiff > 0) { // add it to the total time spent on the app if (appPackageStats[packageName] != null) { val currentStat = appPackageStats[packageName] currentStat?.totalTimeSpent = timeDiff + currentStat?.totalTimeSpent!! currentStat.lastTimeUsed = appEvent.timeStamp currentStat.usageCount++ appPackageStats[packageName] = currentStat } else { appPackageStats[packageName] = AppStats(packageName, timeDiff, appEvent.timeStamp, 0) } } } // reset the current event map for the class classActivityEventMap[className] = CustomActivityMap(appEvent.timeStamp, appEvent.eventType) } } } } return appPackageStats } } }
0
Kotlin
0
0
3944728990dbbde2a7ec7bab5f1c71902c709de7
7,352
device-analytics
MIT License
lib/src/main/java/net/imoya/android/preference/controller/editor/list/MultiSelectionStringListFragmentEditor.kt
IceImo-P
392,544,118
false
null
/* * Copyright (C) 2022 IceImo-P * * 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 net.imoya.android.preference.controller.editor.list import android.content.SharedPreferences import android.os.Bundle import net.imoya.android.fragment.roundtrip.RoundTripManager import net.imoya.android.preference.Constants import net.imoya.android.preference.fragment.editor.list.MultiSelectionListEditorFragment import net.imoya.android.preference.model.result.list.MultiSelectionListEditorFragmentResult import net.imoya.android.preference.model.state.ScreenEditorState import net.imoya.android.preference.model.state.list.MultiSelectionStringListEditorState import net.imoya.android.preference.view.PreferenceView import net.imoya.android.preference.view.list.MultiSelectionStringListPreferenceView /** * 文字列値選択設定コントローラ([]) * * [MultiSelectionStringListPreferenceView] と組み合わせて使用することを想定しています。 */ @Suppress("unused") open class MultiSelectionStringListFragmentEditor( /** * [RoundTripManager] */ roundTripManager: RoundTripManager? = null, /** * [SharedPreferences] to read current value and write result */ preferences: SharedPreferences? = null, /** * 編集画面の識別に使用するリクエストキー */ requestKey: String? = null ) : MultiSelectionListFragmentEditor(roundTripManager, preferences, requestKey) { override fun isCompatibleView(view: PreferenceView): Boolean { return view is MultiSelectionStringListPreferenceView } override fun createState(): ScreenEditorState { return MultiSelectionStringListEditorState() } override fun setupState(view: PreferenceView) { super.setupState(view) if (view !is MultiSelectionStringListPreferenceView) { throw IllegalArgumentException("View must be StringListPreferenceView") } (state as MultiSelectionStringListEditorState).entryValues = view.entryValues } override fun startEditorUI(view: PreferenceView) { val fragment = MultiSelectionListEditorFragment() val arguments = Bundle() arguments.putBundle( Constants.KEY_EDITOR_STATE, (state as MultiSelectionStringListEditorState).toBundle() ) fragment.arguments = arguments checkRoundTripManager().start(checkRequestKey(), fragment) } override fun onEditorResult(result: Bundle) { val currentPreferences = checkPreferences() val key = checkKey() val checkedList = MultiSelectionListEditorFragmentResult(result).checkedList val entryValues = (state as MultiSelectionStringListEditorState).entryValues ListEditorUtil.saveInput( currentPreferences, key, entryValues, checkedList ) { e, c -> createPreferenceValue(e, c) } } /** * [SharedPreferences] へ保存する値を生成して返します。 * * @param entryValues 各項目の設定値リスト * @param checkedList 各項目の選択状態リスト * @return [SharedPreferences] へ保存する値 */ open fun createPreferenceValue(entryValues: Array<String>, checkedList: BooleanArray): String { return ListEditorUtil.createPreferenceValue(entryValues, checkedList) } companion object { // /** // * Tag for log // */ // private const val TAG = "MSelStrListFPrefEditor" } }
0
Kotlin
0
0
ca648efb181731411ed2f793497417fb2e94efc6
3,847
ImoyaAndroidPreferenceLib
Apache License 2.0
src/shmp/simulation/culture/group/request/ResourceRequest.kt
ShMPMat
212,499,539
false
null
package shmp.simulation.culture.group.request import shmp.simulation.culture.group.centers.Group import shmp.simulation.space.resource.Resource class ResourceRequest(private val resource: Resource, core: RequestCore) : Request(core) { override fun reducedAmountCopy(amount: Double) = ResourceRequest(resource, core.copy(floor = 0.0, ceiling = amount)) override val evaluator = resourceEvaluator(resource) override fun reassign(group: Group) = ResourceRequest(resource, core.copy(group = group)) override fun toString() = "Resource ${resource.baseName}" }
0
Kotlin
0
0
43fbb9f6db25f651cb7328408468513491296fb0
589
CulturesSim
MIT License
app/src/main/java/info/tuver/todo/ui/todo/todoTagSelect/TodoTagSelectAdapterViewHolderItem.kt
berkcosar
233,477,029
false
{"Kotlin": 89679}
package info.tuver.todo.ui.todo.todoTagSelect import androidx.databinding.ViewDataBinding import info.tuver.todo.model.TagSelectModel import kotlinx.android.synthetic.main.item_todo_tag_select.view.* class TodoTagSelectAdapterViewHolderItem(viewDataBinding: ViewDataBinding) : TodoTagSelectAdapterViewHolder(viewDataBinding) { override fun onBind(item: TagSelectModel?, adapterActions: TodoTagSelectAdapterActions) { itemView.item_todo_tag_select_tag_chip?.setOnLongClickListener { item?.let { adapterActions.onTodoTagSelectLongClicked(it) } true } } }
0
null
0
0
bc024f3fb49bc3c450aa6c7050a0d3696845f6a3
633
android-mvvm-todo
MIT License
app/src/main/java/top/easelink/lcg/ui/search/source/SearchService.kt
vivicai
238,866,992
true
{"Kotlin": 229971, "Java": 150577, "HTML": 656}
package top.easelink.lcg.ui.search.source import androidx.annotation.WorkerThread import org.jsoup.nodes.Element import org.jsoup.select.Elements import timber.log.Timber import top.easelink.lcg.R import top.easelink.lcg.network.ApiClient import top.easelink.lcg.ui.search.model.SearchResult import top.easelink.lcg.ui.search.model.SearchResults import top.easelink.lcg.utils.showMessage /** * author : junzhang * date : 2019-07-04 16:22 * desc : */ object SearchService { @WorkerThread fun doSearchRequest(requestUrl: String): SearchResults { try { val doc = ApiClient.sendGetRequestWithUrl(requestUrl) val list: List<SearchResult> = doc?.select("div.result") ?.map { try { val title = extractFrom(it, "h3.c-title", "a") val url = extractAttrFrom(it, "href", "h3.c-title", "a") val content = extractFrom(it, "div.c-abstract") return@map SearchResult(title, content, url) } catch (nbe: NumberFormatException) { Timber.v(nbe) } catch (e: Exception) { Timber.e(e) } null } ?.filterNotNull() .orEmpty() if (list.isNullOrEmpty()) { throw Exception("Empty Result") } return SearchResults(list).also { try { it.nextPageUrl = doc?. selectFirst("a.pager-next-foot") ?.attr("href") it.totalResult = doc ?.getElementsByClass("support-text-top") ?.first() ?.text() } catch (e: Exception) { // mute it.nextPageUrl = null } } } catch (e: Exception) { Timber.e(e) showMessage(R.string.error) } return SearchResults(emptyList()) } private fun extractFrom(element: Element, vararg tags: String): String { if (tags.isNullOrEmpty()) { return element.text() } var e = Elements(element) for (tag in tags) { e = e.select(tag) if (e.isEmpty()) { break } } return e.text() } private fun extractAttrFrom(element: Element, attr: String, vararg tags: String): String { if (tags.isNullOrEmpty()) { return element.text() } var e = Elements(element) for (tag in tags) { e = e.select(tag) if (e.isEmpty()) { break } } return e.attr(attr) } }
0
null
0
0
fed971cb745fa7845c799573c1d847d35a253bd0
2,858
lcg
MIT License
app/src/main/java/com/coding/zxm/wanandroid/login/LoginActivity.kt
ZhangXinmin528
283,199,248
false
null
package com.coding.zxm.wanandroid.login import android.app.Activity import android.text.TextPaint import android.text.TextUtils import android.text.style.ClickableSpan import android.view.View import android.widget.Toast import androidx.activity.viewModels import androidx.lifecycle.Observer import com.coding.zxm.core.base.BaseActivity import com.coding.zxm.util.SPConfig import com.coding.zxm.wanandroid.MainActivity import com.coding.zxm.wanandroid.R import com.zxm.utils.core.sp.SharedPreferencesUtil import com.zxm.utils.core.text.ClickableMovementMethod import com.zxm.utils.core.text.SpanUtils import kotlinx.android.synthetic.main.activity_login.* /** * Created by ZhangXinmin on 2020/8/2. * Copyright (c) 2020 . All rights reserved. * For login */ class LoginActivity : BaseActivity(), View.OnClickListener { private val mLoginViewModel: LoginViewModel by viewModels { LoginViewModel.LoginViewModelFactory } override fun setLayoutId(): Int { return R.layout.activity_login } override fun initParamsAndValues() { setStatusBarDark() } override fun initViews() { tv_login.setOnClickListener(this) iv_login_close.setOnClickListener(this) val spannableStringBuilder = SpanUtils.getBuilder(mContext!!, getString(R.string.all_tips_not_register), false) .setTextColor(resources.getColor(R.color.colorPrimary)) .setClickSpan(object : ClickableSpan() { override fun onClick(widget: View) { //TODO:跳转到注册页面 } override fun updateDrawState(ds: TextPaint) { ds.color = resources.getColor(R.color.colorPrimary) ds.isUnderlineText = true } }) .setBold() .append(getString(R.string.all_register), true) .create() tv_tips_register.text = spannableStringBuilder tv_tips_register.movementMethod = ClickableMovementMethod.getInstance() val userName: String = SharedPreferencesUtil.get( mContext!!, SPConfig.CONFIG_USER_NAME, "" ) as String if (!TextUtils.isEmpty(userName)) { et_user_name.setText(userName) } } override fun onClick(v: View?) { when (v?.id) { R.id.tv_login -> { val userName = et_user_name.editableText.toString().trim() if (userName.isEmpty()) { Toast.makeText(mContext!!, "请输入用户名~", Toast.LENGTH_SHORT).show() return } val password = et_password.editableText.toString().trim() if (password.isEmpty()) { Toast.makeText(mContext!!, "请输入密码~", Toast.LENGTH_SHORT).show() return } mLoginViewModel.login(userName, password) .observe(this, Observer { if (it != null) { SharedPreferencesUtil.put( mContext!!, SPConfig.CONFIG_USER_NAME, it.username ) SharedPreferencesUtil.put( mContext!!, SPConfig.CONFIG_STATE_LOGIN, true ) setResult(Activity.RESULT_OK, intent) finish() } }) } R.id.iv_login_close -> { jumpActivity(MainActivity::class.java) finish() } } } }
0
Kotlin
1
3
226f612382444b8853651590d6ef019363f536f1
3,875
WanAndroid
Apache License 2.0
2018/2018110901.kt
maku693
87,369,916
false
{"C++": 763488, "JavaScript": 136237, "CMake": 53855, "Go": 29487, "Jupyter Notebook": 28868, "HTML": 11927, "GLSL": 10187, "C": 4193, "CSS": 4155, "C#": 3754, "Kotlin": 1848, "TypeScript": 1840, "PowerShell": 1281, "Swift": 879, "HLSL": 774, "Clojure": 671, "Rust": 370, "Common Lisp": 263, "Processing": 256, "F#": 157, "Shell": 151, "Dockerfile": 104, "Perl": 83, "OCaml": 30}
import kotlin.math.sqrt data class Vec3(var x: Double, var y: Double, var z: Double) { fun unaryMinus() = Vec3(-x, -y, -z) fun plus(other: Vec3) = Vec3(x + other.x, y + other.y, z + other.z) fun minus(other: Vec3) = Vec3(x - other.x, y - other.y, z - other.z) infix fun scale(multiplier: Double) = Vec3( x * multiplier, y * multiplier, z * multiplier ) infix fun dot(other: Vec3) = x * other.x + y * other.y + z * other.z infix fun cross(other: Vec3) = Vec3( y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x ) fun length2() = this dot this fun length() = sqrt(length2()) fun normalized() = this scale 1 / length() } fun main() { println(Vec3(1.0, 0.0, 0.0) dot Vec3(1.0, 0.0, 0.0)) println(Vec3(4.2, 0.0, 0.0).normalized()) }
0
C++
0
0
53e3a516eeb293b3c11055db1b87d54284e6ac52
862
daily-snippets
MIT License
code/core/src/test/java/com/adobe/marketing/mobile/internal/util/EventDataMergerTests.kt
adobe
458,293,389
false
null
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util import org.junit.Test import kotlin.test.assertEquals class EventDataMergerTests { @Test fun testSimpleMerge() { val fromMap = mapOf( "key" to "oldValue" ) val toMap = mapOf( "newKey" to "newValue" ) val expectedMap = mapOf( "key" to "oldValue", "newKey" to "newValue" ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testConflictAndNotOverwrite() { val toMap = mapOf( "key" to "oldValue", "donotdelete" to "value" ) val fromMap = mapOf( "newKey" to "newValue", "donotdelete" to null ) val expectedMap = mapOf( "key" to "oldValue", "donotdelete" to "value", "newKey" to "newValue" ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, false)) } @Test fun testNestedMapSimpleMerge() { val toMap = mapOf( "nested" to mapOf( "key" to "oldValue" ) ) val fromMap = mapOf( "nested" to mapOf( "newKey" to "newValue" ) ) val expectedMap = mapOf( "nested" to mapOf( "key" to "oldValue", "newKey" to "newValue" ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testNestedMapConflictAndOverwrite() { val toMap = mapOf( "nested" to mapOf( "key" to "oldValue", "toBeDeleted" to "value" ) ) val fromMap = mapOf( "nested" to mapOf( "newKey" to "newValue", "toBeDeleted" to null ) ) val expectedMap = mapOf( "nested" to mapOf( "key" to "oldValue", "newKey" to "newValue" ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testListSimpleMerge() { val fromMap = mapOf( "key" to listOf("abc", "def") ) val toMap = mapOf( "key" to listOf("0", "1") ) val expectedMap = mapOf( "key" to listOf("abc", "def", "0", "1") ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testListWithDuplicatedItems() { val fromMap = mapOf( "key" to listOf("abc", "def") ) val toMap = mapOf( "key" to listOf("abc", "1") ) val expectedMap = mapOf( "key" to listOf("abc", "def", "abc", "1") ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testListWithDifferentTypes() { val fromMap = mapOf( "key" to listOf("abc", "def") ) val toMap = mapOf( "key" to listOf(0, 1) ) val expectedMap = mapOf( "key" to listOf("abc", "def", 0, 1) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardMergeBasic() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1" ), mapOf( "k2" to "v2" ) ) ) val fromMap = mapOf( "list[*]" to mapOf( "newKey" to "newValue" ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "newKey" to "newValue" ), mapOf( "k2" to "v2", "newKey" to "newValue" ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardMergeNotAtRootLevel() { val toMap = mapOf( "inner" to mapOf( "list" to listOf( mapOf( "k1" to "v1" ), mapOf( "k2" to "v2" ) ) ) ) val fromMap = mapOf( "inner" to mapOf( "list[*]" to mapOf( "newKey" to "newValue" ) ) ) val expectedMap = mapOf( "inner" to mapOf( "list" to listOf( mapOf( "k1" to "v1", "newKey" to "newValue" ), mapOf( "k2" to "v2", "newKey" to "newValue" ) ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardMergeWithoutTarget() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1" ), mapOf( "k2" to "v2" ) ) ) val fromMap = mapOf( "lists[*]" to mapOf( "newKey" to "newValue" ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1" ), mapOf( "k2" to "v2" ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardMergeOverwrite() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "key" to "oldValue" ), mapOf( "k2" to "v2" ) ) ) val fromMap = mapOf( "list[*]" to mapOf( "key" to "newValue" ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "key" to "newValue" ), mapOf( "k2" to "v2", "key" to "newValue" ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardMergeOverwriteWithNoneMapItem() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "key" to "oldValue" ), "none_map_item" ) ) val fromMap = mapOf( "list[*]" to mapOf( "key" to "newValue" ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "key" to "newValue" ), "none_map_item" ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardMergeNotOverwrite() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "key" to "oldValue" ), mapOf( "k2" to "v2" ) ) ) val fromMap = mapOf( "list[*]" to mapOf( "key" to "newValue" ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "key" to "oldValue" ), mapOf( "k2" to "v2", "key" to "newValue" ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, false)) } @Test fun testWildCardNestedMapMergeOverwrite() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "inner" to mapOf( "inner_k1" to "oldValue", "key" to "oldValue" ) ), mapOf( "k2" to "v2" ) ) ) val fromMap = mapOf( "list[*]" to mapOf( "key" to "newValue", "inner" to mapOf( "inner_k1" to "newValue", "newKey" to "newValue" ) ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "inner" to mapOf( "inner_k1" to "newValue", "key" to "oldValue", "newKey" to "newValue" ), "key" to "newValue" ), mapOf( "k2" to "v2", "key" to "newValue", "inner" to mapOf( "inner_k1" to "newValue", "newKey" to "newValue" ) ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testWildCardNestedMapMergeNotOverwrite() { val toMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "inner" to mapOf( "inner_k1" to "oldValue", "key" to "oldValue" ) ), mapOf( "k2" to "v2" ) ) ) val fromMap = mapOf( "list[*]" to mapOf( "key" to "newValue", "inner" to mapOf( "inner_k1" to "newValue", "newKey" to "newValue" ) ) ) val expectedMap = mapOf( "list" to listOf( mapOf( "k1" to "v1", "inner" to mapOf( "inner_k1" to "oldValue", "key" to "oldValue", "newKey" to "newValue" ), "key" to "newValue" ), mapOf( "k2" to "v2", "key" to "newValue", "inner" to mapOf( "inner_k1" to "newValue", "newKey" to "newValue" ) ) ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, false)) } @Test fun testFromMapWithNonStringKey() { val toMap = mapOf( "k1" to "v1", "k2" to "v2", "nested" to mapOf( 1 to "ValueForIntKey", "k1" to "v1" ) ) val fromMap = mapOf( "nested" to mapOf( "k1" to "v11", "k2" to "v2" ) ) val expectedMap = mapOf( "k1" to "v1", "k2" to "v2", "nested" to mapOf( 1 to "ValueForIntKey", "k1" to "v1" ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } @Test fun testToMapWithNonStringKey() { val toMap = mapOf( "k1" to "v1", "k2" to "v2", "nested" to mapOf( "k1" to "v1", "k2" to "v2" ) ) val fromMap = mapOf( "nested" to mapOf( 1 to "ValueForIntKey", "k1" to "v11" ) ) val expectedMap = mapOf( "k1" to "v1", "k2" to "v2", "nested" to mapOf( "k1" to "v1", "k2" to "v2" ) ) assertEquals(expectedMap, EventDataMerger.merge(fromMap, toMap, true)) } }
15
null
24
9
d3e61e63f80799942171e04e7d1b79a3a1a7c717
13,256
aepsdk-core-android
Apache License 2.0
idea/tests/org/jetbrains/kotlin/idea/debugger/MockSourcePosition.kt
damenez
189,964,139
true
{"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1}
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger import com.intellij.debugger.SourcePosition import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile class MockSourcePosition( val _file: PsiFile? = null, val _elementAt: PsiElement? = null, val _line: Int? = null, val _offset: Int? = null, val _editor: Editor? = null ): SourcePosition() { override fun getFile() = _file ?: throw UnsupportedOperationException("Parameter file isn't set for MockSourcePosition") override fun getElementAt() = _elementAt ?: throw UnsupportedOperationException("Parameter elementAt isn't set for MockSourcePosition") override fun getLine() = _line ?: throw UnsupportedOperationException("Parameter line isn't set for MockSourcePosition") override fun getOffset() = _offset ?: throw UnsupportedOperationException("Parameter offset isn't set for MockSourcePosition") override fun openEditor(requestFocus: Boolean) = _editor ?: throw UnsupportedOperationException("Parameter editor isn't set for MockSourcePosition") override fun navigate(requestFocus: Boolean) = throw UnsupportedOperationException("navigate() isn't supported for MockSourcePosition") override fun canNavigate() = throw UnsupportedOperationException("canNavigate() isn't supported for MockSourcePosition") override fun canNavigateToSource() = throw UnsupportedOperationException("canNavigateToSource() isn't supported for MockSourcePosition") }
0
Kotlin
1
2
dca23f871cc22acee9258c3d58b40d71e3693858
1,655
kotlin
Apache License 2.0
src/main/kotlin/novah/data/PLabelMap.kt
stackoverflow
255,379,925
false
null
/** * Copyright 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 novah.data import io.lacuna.bifurcan.List import io.lacuna.bifurcan.SortedMap import novah.Util.joinToStr typealias PList<V> = List<V> typealias KList<T> = kotlin.collections.List<T> typealias Labels<V> = KList<Pair<String, V>> typealias LabelMap<V> = SortedMap<String, PList<V>> private val labelRegex = Regex("""[a-z](?:\w+|_)*""") fun isValidLabel(ident: String): Boolean = ident.matches(labelRegex) fun showLabel(label: String): String = if (isValidLabel(label)) label else "\"$label\"" fun <V> Labels<V>.show(fn: (String, V) -> String): String = joinToStr { (k, v) -> fn(showLabel(k), v)} fun <V> LabelMap<V>.show(fn: (String, V) -> String): String { val builder = StringBuilder() var addComma = false forEach { kv -> kv.value().forEach { v -> if (addComma) builder.append(", ") builder.append(fn(showLabel(kv.key()), v)) addComma = true } } return builder.toString() } fun <V> singletonPMap(k: String, v: V): LabelMap<V> = LabelMap<V>().put(k, PList.of(v)) fun <V, R> PList<V>.map(fn: (V) -> R): PList<R> { val nlist = List.empty<R>().linear() return fold(nlist) { acc, v -> acc.addLast(fn(v)) }.forked() } fun <V> PList<V>.isEmpty() = size() == 0L fun <V> LabelMap<V>.isEmpty() = size() == 0L fun <V, R> LabelMap<V>.mapList(fn: (V) -> R): LabelMap<R> { return mapValues { _, l -> l.map(fn) } } fun <V, R> LabelMap<V>.mapAllValues(fn: (V) -> R): List<R> { val res = List.empty<R>().linear() forEachList { res.addLast(fn(it)) } return res.forked() } fun <V, R> LabelMap<V>.forEachKeyList(fn: (String, V) -> R) { forEach { kv -> kv.value().forEach { fn(kv.key(), it) } } } fun <V> LabelMap<V>.forEachList(fn: (V) -> Unit) { forEach { kv -> kv.value().forEach(fn) } } fun <V, R> LabelMap<V>.flatMapList(fn: (V) -> Iterable<R>): List<R> { return PList.from(flatMap { kv -> kv.value().flatMap(fn) }) } fun <V> LabelMap<V>.allList(fn: (V) -> Boolean): Boolean { return fold(true) { acc, v -> acc && v.value().all(fn) } } fun <V> LabelMap<V>.putMulti(key: String, value: V): LabelMap<V> { val list = get(key, null) return if (list != null) put(key, list.addFirst(value)) else put(key, PList.of(value)) } fun <V> LabelMap<V>.assocat(key: String, values: PList<V>): LabelMap<V> { val list = get(key, null) return if (list != null) put(key, list.concat(values) as PList<V>) else put(key, values) } fun <V> LabelMap<V>.toPList(): List<Pair<String, PList<V>>> { val list = PList.empty<Pair<String, PList<V>>>().linear() return fold(list) { acc, kv -> acc.addLast(kv.key() to kv.value()) }.forked() } fun <V> labelMapWith(kvs: kotlin.collections.List<Pair<String, V>>): LabelMap<V> { return kvs.fold(LabelMap()) { acc, el -> acc.putMulti(el.first, el.second) } } fun <V> LabelMap<V>.merge(other: LabelMap<V>): LabelMap<V> { val m = forked().linear() return other.fold(m) { acc, kv -> acc.assocat(kv.key(), kv.value()) }.forked() } /** * Don't join the values together, just replace them with the values from `other`. */ fun <V> LabelMap<V>.mergeReplace(other: LabelMap<V>): LabelMap<V> { val m = forked().linear() return other.fold(m) { acc, kv -> acc.put(kv.key(), kv.value()) }.forked() }
0
Kotlin
1
9
f3f2b12e178c5288197f6c6d591e8d304f5baf5d
3,971
novah
Apache License 2.0
app/src/p_app/main/java/com/llj/architecturedemo/ui/module/MineFragmentModule.kt
liulinjie1990823
133,350,610
false
{"Gradle": 94, "Python": 7, "JSON": 2, "Java Properties": 40, "Shell": 54, "Text": 149, "JavaScript": 32, "Ignore List": 72, "Markdown": 59, "Java": 651, "INI": 17, "Proguard": 56, "XML": 352, "Groovy": 16, "CMake": 13, "C++": 49, "C": 704, "Kotlin": 304, "Roff Manpage": 30, "YAML": 11, "CSS": 6, "JAR Manifest": 1, "HTML": 65, "Rich Text Format": 2, "SQL": 1, "Assembly": 94, "Pascal": 3, "Unix Assembly": 3, "Dart": 96, "AIDL": 4, "SVG": 4, "Gradle Kotlin DSL": 1, "GLSL": 24, "Makefile": 27, "M4Sugar": 119, "sed": 11, "Batchfile": 6, "Roff": 1, "Texinfo": 1, "M4": 1, "Diff": 2, "Gettext Catalog": 37}
package com.llj.architecturedemo.ui.module import com.llj.architecturedemo.ui.fragment.MineFragment import com.llj.architecturedemo.ui.view.IMineView import dagger.Module import dagger.Provides /** * ArchitectureDemo. * describe: * author llj * date 2018/10/24 */ @Module class MineFragmentModule { @Provides internal fun providePasswordLoginFragment(fragment: MineFragment): IMineView { return fragment } }
1
null
1
1
7c5d7fe1e5e594baba19778e0ed857325ce58095
436
ArchitectureDemo
Apache License 2.0
packages/graalvm/src/main/kotlin/elide/runtime/gvm/VMFacade.kt
elide-dev
506,113,888
false
{"Kotlin": 4544382, "JavaScript": 1201497, "Java": 302542, "Protocol Buffer": 276092, "Shell": 84860, "Dockerfile": 51144, "Cap'n Proto": 35188, "Makefile": 30147, "CSS": 14730, "Python": 5989, "C": 4348, "Batchfile": 3016, "Ruby": 2474, "Handlebars": 1954, "HTML": 1010, "Rust": 525, "Swift": 23}
/* * Copyright (c) 2024 Elide Technologies, Inc. * * Licensed under the MIT license (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://opensource.org/license/mit/ * * 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 elide.runtime.gvm import io.micronaut.http.HttpRequest import kotlinx.coroutines.Deferred import kotlinx.coroutines.Job /** * TBD. */ public interface VMFacade { /** * TBD. */ public fun language(): GuestLanguage /** * TBD. */ public suspend fun prewarmScript(script: ExecutableScript) /** * TBD. */ public suspend fun executeStreaming(script: ExecutableScript, args: ExecutionInputs, receiver: StreamingReceiver): Job /** * TBD. */ public suspend fun executeRender( script: ExecutableScript, request: HttpRequest<*>, context: Any?, receiver: StreamingReceiver, ): Job /** * Suspension execution of the provided [script] within an embedded JavaScript VM, by way of GraalVM's runtime engine; * de-serialize the result [R] and provide it as the return value. * * @param script Executable script spec to execute within the embedded JS VM. * @return Deferred task which evaluates to the return value [R] when execution finishes. */ public suspend fun <R> execute(script: ExecutableScript, returnType: Class<R>, args: ExecutionInputs?): R? /** * Asynchronously execute the provided [script] within an embedded JavaScript VM, by way of GraalVM's runtime engine; * de-serialize the result [R] and provide it as the return value. * * @param script Executable script spec to execute within the embedded JS VM. * @return Deferred task which evaluates to the return value [R] when execution finishes. */ public suspend fun <R> executeAsync(script: ExecutableScript, returnType: Class<R>, args: ExecutionInputs?): Deferred<R?> /** * Blocking execution of the provided [script] within an embedded JavaScript VM, by way of GraalVM's runtime engine; * de-serialize the result [R] and provide it as the return value. * * @param script Executable script spec to execute within the embedded JS VM. * @return Deferred task which evaluates to the return value [R] when execution finishes. */ public fun <R> executeBlocking(script: ExecutableScript, returnType: Class<R>, args: ExecutionInputs?): R? }
75
Kotlin
15
86
bd9f5aed8523648256c9e9a29d87bd3c2b09ac54
2,706
elide
MIT License
alkemy/src/main/kotlin/io/alkemy/internals/system-properties.kt
cosmin-marginean
630,394,204
false
null
package io.alkemy.internals inline fun <reified T> sysProp(name: String, default: T): T { val sysProp = System.getProperty(name) ?: return default return when (T::class) { String::class -> sysProp as T Boolean::class -> sysProp.toBoolean() as T Int::class -> sysProp.toInt() as T Long::class -> sysProp.toLong() as T else -> throw IllegalArgumentException("No convertor for class ${T::class}") } } inline fun <reified T : Enum<T>> enumSysProp(name: String, default: T): T { val sysProp = System.getProperty(name) ?: return default return enumValueOf<T>(sysProp.trim().uppercase()) }
0
Kotlin
1
14
5e44af08c010170373651cc7ade9d4e209f1262b
645
alkemy
Apache License 2.0
src/main/kotlin/no/nav/paw/situasjon/repository/SituasjonRepository.kt
navikt
628,963,942
false
null
package no.nav.paw.situasjon.repository import kotliquery.Row import kotliquery.queryOf import kotliquery.sessionOf import no.nav.paw.situasjon.domain.Foedselsnummer import no.nav.paw.situasjon.domain.SituasjonDto import javax.sql.DataSource class SituasjonRepository(private val dataSource: DataSource) { fun hentSiste(foedselsnummer: Foedselsnummer): SituasjonDto? { sessionOf(dataSource).use { session -> val query = queryOf( "SELECT * FROM $SITUASJON_TABELL WHERE foedselsnummer = ? ORDER BY endret DESC LIMIT 1", foedselsnummer.foedselsnummer ).map { it.tilSituasjon() }.asSingle return session.run(query) } } private fun Row.tilSituasjon() = SituasjonDto( int("id"), localDateTime("opprettet"), localDateTime("endret") ) companion object { const val SITUASJON_TABELL = "situasjon" } }
0
Kotlin
0
0
258aa6a70b520e11a7cf8a7e6850d1f95336440c
963
paw-arbeidssoker-situasjon
MIT License
src/backend/job/boot-job-worker/src/main/kotlin/com/tencent/bkrepo/job/worker/JobWorkerApplication.kt
TencentBlueKing
548,243,758
false
{"Kotlin": 13657594, "Vue": 1261332, "JavaScript": 683823, "Shell": 124343, "Lua": 100415, "SCSS": 34137, "Python": 25877, "CSS": 17382, "HTML": 13052, "Dockerfile": 4483, "Smarty": 3661, "Java": 423}
package com.tencent.bkrepo.job.worker import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.data.mongodb.repository.config.EnableMongoRepositories @SpringBootApplication(scanBasePackages = ["com.tencent.bkrepo.job"]) @EnableMongoRepositories(basePackages = ["com.tencent.bkrepo.job"]) class JobWorkerApplication fun main(args: Array<String>) { runApplication<JobWorkerApplication>(*args) }
363
Kotlin
38
70
54b0c7ab20ddbd988387bac6c9143b594681e73c
485
bk-repo
MIT License
app/src/main/java/chat/rocket/android/authentication/infraestructure/TokenMapper.kt
lucasmontano
128,559,523
true
{"Kotlin": 556415, "Shell": 2737}
package chat.rocket.android.authentication.infraestructure import chat.rocket.android.authentication.domain.model.TokenModel import chat.rocket.android.util.DataToDomain import chat.rocket.common.model.Token object TokenMapper : DataToDomain<Token, TokenModel> { override fun translate(data: Token): TokenModel { return TokenModel(data.userId, data.authToken) } }
0
Kotlin
0
3
83b14b60deade340b1b2b05e20f10fb7d3772280
381
Rocket.Chat.Android
MIT License
jps/jps-plugin/src/org/jetbrains/kotlin/jps/build/TestingBuildLogger.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.jps.build import org.jetbrains.jps.incremental.CompileContext import org.jetbrains.jps.incremental.ModuleLevelBuilder import org.jetbrains.kotlin.jps.incremental.CacheAttributesDiff import org.jetbrains.kotlin.jps.targets.KotlinModuleBuildTarget import java.io.File /** * Used for assertions in tests. */ interface TestingBuildLogger { fun invalidOrUnusedCache(chunk: KotlinChunk?, target: KotlinModuleBuildTarget<*>?, attributesDiff: CacheAttributesDiff<*>) fun chunkBuildStarted(context: CompileContext, chunk: org.jetbrains.jps.ModuleChunk) fun afterChunkBuildStarted(context: CompileContext, chunk: org.jetbrains.jps.ModuleChunk) fun addCustomMessage(message: String) fun buildFinished(exitCode: ModuleLevelBuilder.ExitCode) fun markedAsDirtyBeforeRound(files: Iterable<File>) fun markedAsDirtyAfterRound(files: Iterable<File>) }
181
null
5748
71
b6789690db56407ae2d6d62746fb69dc99d68c84
1,497
intellij-kotlin
Apache License 2.0
lol/app/src/main/java/com/tyhoo/android/lol/ui/ItemScreen.kt
cnwutianhao
600,592,169
false
null
package com.tyhoo.android.lol.ui import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import coil.compose.rememberAsyncImagePainter import com.tyhoo.android.lol.domain.Item @Composable fun ItemScreen(item: Item?) { item?.let { data -> val name = data.name val iconPath = data.iconPath val price = data.price val maps = data.maps val plaintext = data.plaintext Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = rememberAsyncImagePainter(iconPath), contentDescription = null, modifier = Modifier .size(100.dp) .padding(top = 16.dp) .align(Alignment.CenterHorizontally) ) Text( text = "物品:$name", modifier = Modifier .padding(top = 16.dp, start = 16.dp) .align(Alignment.Start) ) Text( text = "金额:$price", modifier = Modifier .padding(top = 8.dp, start = 16.dp) .align(Alignment.Start) ) Text( text = "描述:$plaintext", modifier = Modifier .padding(top = 8.dp, start = 16.dp) .align(Alignment.Start) ) Text( text = "地图:${maps.joinToString(",")}", modifier = Modifier .padding(top = 8.dp, start = 16.dp) .align(Alignment.Start) ) } } }
0
Kotlin
0
0
90797aa1c354092b72ed5fc910f2c4838f1e0577
1,935
android
MIT License
app/src/main/java/com/hfut/schedule/ui/Activity/success/search/Search/TotalCourse/CourseTotal.kt
Chiu-xaH
705,508,343
false
null
package com.hfut.schedule.ui.Activity.success.search.Search.TotalCourse import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable 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 androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.google.gson.Gson import com.hfut.schedule.R import com.hfut.schedule.ViewModel.LoginSuccessViewModel import com.hfut.schedule.logic.datamodel.Community.CourseTotalResponse import com.hfut.schedule.logic.datamodel.Community.courseBasicInfoDTOList import com.hfut.schedule.logic.utils.SharePrefs.prefs import com.hfut.schedule.ui.UIUtils.Round import com.hfut.schedule.ui.UIUtils.ScrollText @OptIn(ExperimentalMaterial3Api::class) @Composable fun CourseTotal(vm :LoginSuccessViewModel) { val sheetState_Total = rememberModalBottomSheetState() var showBottomSheet_Total by remember { mutableStateOf(false) } val CommuityTOKEN = prefs.getString("TOKEN","") val json = prefs.getString("courses","") ListItem( headlineContent = { Text(text = "课程汇总") }, leadingContent = { Icon( painterResource(R.drawable.category), contentDescription = "Localized description", ) }, modifier = Modifier.clickable { showBottomSheet_Total = true } ) if (showBottomSheet_Total) { ModalBottomSheet( onDismissRequest = { showBottomSheet_Total = false }, sheetState = sheetState_Total, shape = Round(sheetState_Total) ) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { TopAppBar( colors = TopAppBarDefaults.mediumTopAppBarColors( containerColor = Color.Transparent, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text("课程汇总") } ) }, ) { innerPadding -> Column( modifier = Modifier .padding(innerPadding) .fillMaxSize() ){ CourseTotalUI(json,false) Spacer(modifier = Modifier.height(20.dp)) } } } } } fun periodsSum() : Double { var num = 0.0 val json = prefs.getString("courses","") for(i in 0 until getTotalCourse(json).size) { val credit = getTotalCourse(json)[i].course.credits if (credit != null) { num += credit } } return num } @Composable fun SemsterInfo(json : String?) { val semsterInfo = getTotalCourse(json)[0].semester Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { Column() { Card( elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), modifier = Modifier .fillMaxWidth() .padding( horizontal = 15.dp, vertical = 5.dp ), shape = MaterialTheme.shapes.medium, ){ ListItem( overlineContent = { Text(text = semsterInfo.startDate + " ~ " + semsterInfo.endDate)}, headlineContent = { ScrollText(semsterInfo.nameZh) }, leadingContent = { Icon( painterResource(R.drawable.category), contentDescription = "Localized description", ) }, modifier = Modifier.clickable {}, colors = ListItemDefaults.colors(MaterialTheme.colorScheme.primaryContainer), trailingContent = { if (json != null) { if(json.contains("lessonIds"))Text(text = "学分 ${periodsSum()}") } } ) } } } }
0
null
1
3
81117c0954b1853847ec09a10d55c55db4a8e284
5,328
HFUT-Schedule
Apache License 2.0
server/src/main/kotlin/org/kryptonmc/krypton/pack/PackType.kt
KryptonMC
255,582,002
false
null
/* * This file is part of the Krypton project, licensed under the Apache License v2.0 * * Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kryptonmc.krypton.pack import org.kryptonmc.krypton.KryptonPlatform enum class PackType(val directory: String) { CLIENT_RESOURCES("assets"), SERVER_DATA("data"); fun version(): Int = if (this == SERVER_DATA) KryptonPlatform.dataPackVersion else KryptonPlatform.resourcePackVersion }
27
Kotlin
11
233
a9eff5463328f34072cdaf37aae3e77b14fcac93
1,044
Krypton
Apache License 2.0
common/build/generated/sources/schemaCode/kotlin/main/io/portone/sdk/server/schemas/RegisterStoreReceiptBodyItem.kt
portone-io
809,427,199
false
{"Kotlin": 385115, "Java": 331}
package io.portone.sdk.server.schemas import kotlin.Long import kotlin.String import kotlinx.serialization.Serializable /** * 하위 상점 거래 정보 */ @Serializable public data class RegisterStoreReceiptBodyItem( /** * 하위 상점 사업자등록번호 */ public val storeBusinessRegistrationNumber: String, /** * 하위 상점명 */ public val storeName: String, /** * 결제 총 금액 */ public val totalAmount: Long, /** * 면세액 */ public val taxFreeAmount: Long? = null, /** * 부가세액 */ public val vatAmount: Long? = null, /** * 공급가액 */ public val supplyAmount: Long? = null, /** * 통화 */ public val currency: Currency, )
0
Kotlin
0
2
f984c4cc31aa64aad5cd0fa0497bdd490a0fe33a
646
server-sdk-jvm
MIT License
app/src/main/java/com/ingjuanocampo/enfila/android/ui/common/Activity+Ext.kt
ingjuanocampo
387,043,993
false
{"Kotlin": 247926}
package com.ingjuanocampo.enfila.android.ui.common import android.app.Activity import android.content.Context import android.view.inputmethod.InputMethodManager fun Activity.hideKeyboard() { val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(window.decorView.windowToken, 0) }
2
Kotlin
0
0
31011df678fd6379247957c74de1e4940b0ad2e6
373
EnFila-Android
MIT License
app/src/main/java/com/alpriest/energystats/ui/statsgraph/StatsDatePickerView.kt
alpriest
606,081,400
false
{"Kotlin": 878318}
package com.alpriest.energystats.ui.statsgraph import android.widget.CalendarView import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowForward import androidx.compose.material.icons.filled.BarChart import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.ChevronLeft import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Done import androidx.compose.material3.Button import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.window.Dialog import com.alpriest.energystats.R import com.alpriest.energystats.ui.settings.SlimButton import kotlinx.coroutines.flow.MutableStateFlow import java.text.SimpleDateFormat import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.ZoneId import java.util.Calendar import java.util.Locale sealed class DatePickerRange { object DAY : DatePickerRange() object MONTH : DatePickerRange() object YEAR : DatePickerRange() data class CUSTOM(val start: LocalDate, val end: LocalDate) : DatePickerRange() fun isCustom(): Boolean { return !(this == DAY || this == MONTH || this == YEAR) } } @Composable fun StatsDatePickerView(viewModel: StatsDatePickerViewModel, graphShowingState: MutableStateFlow<Boolean>, modifier: Modifier = Modifier) { val range = viewModel.rangeStream.collectAsState().value Row(modifier = modifier) { DateRangePicker(viewModel, range, graphShowingState) when (range) { is DatePickerRange.DAY -> CalendarView(viewModel.dateStream) is DatePickerRange.MONTH -> { MonthPicker(viewModel) YearPicker(viewModel) } is DatePickerRange.YEAR -> YearPicker(viewModel) is DatePickerRange.CUSTOM -> CustomRangePicker(viewModel) } Spacer(modifier = Modifier.weight(1.0f)) if (!range.isCustom()) { Button( modifier = Modifier .padding(end = 14.dp) .padding(vertical = 6.dp) .size(36.dp), onClick = { viewModel.decrease() }, contentPadding = PaddingValues(0.dp) ) { Icon(imageVector = Icons.Default.ChevronLeft, contentDescription = "Left") } Button( modifier = Modifier .padding(vertical = 6.dp) .size(36.dp), onClick = { viewModel.increase() }, contentPadding = PaddingValues(0.dp) ) { Icon(imageVector = Icons.Default.ChevronRight, contentDescription = "Right") } } } } @Composable private fun MonthPicker(viewModel: StatsDatePickerViewModel) { var showing by remember { mutableStateOf(false) } val month = viewModel.monthStream.collectAsState().value val calendar = Calendar.getInstance() calendar.set(Calendar.DAY_OF_MONTH, 1) val monthFormat = SimpleDateFormat("MMMM", Locale.getDefault()) Box( modifier = Modifier .wrapContentSize(Alignment.TopStart) .padding(end = 14.dp) ) { SlimButton( onClick = { showing = true } ) { calendar.set(Calendar.MONTH, month) Text(monthFormat.format(calendar.time)) } DropdownMenu(expanded = showing, onDismissRequest = { showing = false }) { for (monthIndex in 0 until 12) { calendar.set(Calendar.MONTH, monthIndex) val monthName = monthFormat.format(calendar.time) DropdownMenuItem(onClick = { viewModel.monthStream.value = monthIndex showing = false }, text = { Text(monthName) }, trailingIcon = { if (monthIndex == month) { Icon(imageVector = Icons.Default.Done, contentDescription = "checked") } }) if (monthIndex < 11) { HorizontalDivider() } } } } } @Composable private fun YearPicker(viewModel: StatsDatePickerViewModel) { var showing by remember { mutableStateOf(false) } val year = viewModel.yearStream.collectAsState().value val currentYear = Calendar.getInstance().get(Calendar.YEAR) Box( modifier = Modifier .wrapContentSize(Alignment.TopStart) .padding(end = 14.dp) ) { SlimButton( onClick = { showing = true } ) { Text(year.toString()) } DropdownMenu(expanded = showing, onDismissRequest = { showing = false }) { for (yearIndex in 2021..currentYear) { DropdownMenuItem(onClick = { viewModel.yearStream.value = yearIndex showing = false }, text = { Text(yearIndex.toString()) }, trailingIcon = { if (yearIndex == year) { Icon(imageVector = Icons.Default.Done, contentDescription = "checked") } }) if (yearIndex < currentYear) { HorizontalDivider() } } } } } @Composable private fun DateRangePicker( viewModel: StatsDatePickerViewModel, range: DatePickerRange, graphShowingState: MutableStateFlow<Boolean> ) { var showing by remember { mutableStateOf(false) } val graphShowing = graphShowingState.collectAsState() Box( modifier = Modifier .wrapContentSize(Alignment.TopStart) .padding(end = 14.dp) ) { Button( onClick = { showing = true }, modifier = Modifier .padding(vertical = 6.dp) .size(36.dp), contentPadding = PaddingValues(0.dp) ) { Icon( imageVector = Icons.Default.CalendarMonth, contentDescription = null ) } DropdownMenu( expanded = showing, onDismissRequest = { showing = false } ) { DropdownMenuItem(onClick = { viewModel.rangeStream.value = DatePickerRange.DAY showing = false }, text = { Text(stringResource(R.string.day)) }, trailingIcon = { if (range == DatePickerRange.DAY) { Icon(imageVector = Icons.Default.Done, contentDescription = "checked") } }) HorizontalDivider() DropdownMenuItem(onClick = { viewModel.rangeStream.value = DatePickerRange.MONTH showing = false }, text = { Text(stringResource(R.string.month)) }, trailingIcon = { if (range == DatePickerRange.MONTH) { Icon(imageVector = Icons.Default.Done, contentDescription = "checked") } }) HorizontalDivider() DropdownMenuItem(onClick = { viewModel.rangeStream.value = DatePickerRange.YEAR showing = false }, text = { Text(stringResource(R.string.year)) }, trailingIcon = { if (range == DatePickerRange.YEAR) { Icon(imageVector = Icons.Default.Done, contentDescription = "checked") } }) HorizontalDivider() DropdownMenuItem(onClick = { viewModel.rangeStream.value = DatePickerRange.CUSTOM(LocalDate.now().minusDays(30), LocalDate.now()) showing = false }, text = { Text(stringResource(R.string.custom_range)) }, trailingIcon = { if (range.isCustom()) { Icon(imageVector = Icons.Default.Done, contentDescription = "checked") } }) HorizontalDivider(thickness = 4.dp) DropdownMenuItem(onClick = { graphShowingState.value = !graphShowing.value showing = false }, text = { Text(if (graphShowing.value) stringResource(R.string.hide_graph) else stringResource(R.string.show_graph)) }, trailingIcon = { Icon(imageVector = Icons.Default.BarChart, contentDescription = "graph") }) } } } @Composable fun CustomRangePicker(viewModel: StatsDatePickerViewModel) { Row( verticalAlignment = Alignment.CenterVertically ) { CalendarView(viewModel.customStartDate) Icon( imageVector = Icons.Filled.ArrowForward, contentDescription = null, modifier = Modifier.padding(end = 14.dp) ) CalendarView(viewModel.customEndDate) } } @Composable fun CalendarView(dateStream: MutableStateFlow<LocalDate>) { var showingDatePicker by remember { mutableStateOf(false) } val dateState = dateStream.collectAsState().value val millis = localDateToMillis(dateState) Box( modifier = Modifier .wrapContentSize(Alignment.BottomCenter) .padding(end = 14.dp) ) { SlimButton( onClick = { showingDatePicker = true } ) { Text(dateState.toString()) } if (showingDatePicker) { Dialog( onDismissRequest = { showingDatePicker = false }, ) { Column( modifier = Modifier .background(Color.White) ) { AndroidView( { CalendarView(it) }, modifier = Modifier.wrapContentWidth(), update = { views -> views.date = millis views.setOnDateChangeListener { _, year, month, dayOfMonth -> val cal = Calendar.getInstance() cal.set(year, month, dayOfMonth) dateStream.value = millisToLocalDate(cal.timeInMillis) showingDatePicker = false } } ) } } } } } fun localDateToMillis(localDate: LocalDate): Long { val localDateTime = LocalDateTime.of(localDate, LocalTime.MIDNIGHT) val zoneId = ZoneId.systemDefault() return localDateTime.atZone(zoneId).toInstant().toEpochMilli() } fun millisToLocalDate(millis: Long): LocalDate { val instant = Instant.ofEpochMilli(millis) val zoneId = ZoneId.systemDefault() val localDateTime = LocalDateTime.ofInstant(instant, zoneId) return localDateTime.toLocalDate() } @Preview(widthDp = 500, heightDp = 500) @Composable fun StatsDatePickerViewPreview() { StatsDatePickerView( viewModel = StatsDatePickerViewModel(MutableStateFlow(StatsDisplayMode.Day(LocalDate.now()))), graphShowingState = MutableStateFlow(false) ) }
8
Kotlin
3
3
e4e6d594040924730408a6e8e9d4c8d919770d1f
12,630
EnergyStats-Android
MIT License
features/novel/novel_domain/src/main/kotlin/jp/sadashi/narou/reader/novel/domain/NovelCode.kt
sadashi-ota
193,362,372
false
null
package jp.sadashi.narou.reader.novel.domain inline class NovelCode(val value: String)
0
Kotlin
0
0
e1c0178f5cfdc8641a53834e7eddd19f2936266a
87
narou-reader
Apache License 2.0
src/main/kotlin/dev/kdrag0n/patreondl/external/patreon/Webhooks.kt
kdrag0n
353,524,278
false
{"Kotlin": 65248, "Handlebars": 4629, "CSS": 3200}
package dev.kdrag0n.patreondl.external.patreon import dev.kdrag0n.patreondl.config.Config import dev.kdrag0n.patreondl.external.telegram.TelegramInviteManager import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.koin.ktor.ext.inject @OptIn(DelicateCoroutinesApi::class) fun Application.webhooksModule() { val config: Config by inject() val patreonApi: PatreonApi by inject() val inviteManager: TelegramInviteManager by inject() GlobalScope.launch { inviteManager.startBot() } routing { post("/_webhooks/patreon/${config.external.patreon.webhookKey}/{event_type}") { val event = call.receive<MemberPledgeEvent>() val eventType = call.parameters["event_type"]!! val userId = event.data.relationships.user.data.id val email = event.data.attributes.email <EMAIL>info("Invalidating cache for user $userId") patreonApi.invalidateUser(userId) val user = event.included .find { it is PatreonUser && it.id == userId } as PatreonUser when (eventType) { // New users "members:pledge:create", "members:pledge:update" -> { // Send Telegram invite inviteManager.sendTelegramInvite(user, email) } // Canceled users "members:pledge:delete" -> { // TODO: only remove users after access expiration inviteManager.removeTelegramUser(user.id) } // Invalid events else -> <EMAIL>warn("Patreon webhook: unknown event type $eventType") } call.respond(HttpStatusCode.OK) } } }
2
Kotlin
3
23
f11d7edbe0db8f011a361912529de70ab2439676
1,990
earlypilot
MIT License