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/academy/android/data/network/ServerApi.kt
mik629
377,047,782
true
{"Kotlin": 118816}
package com.academy.android.data.network import com.academy.android.data.network.models.CourseDTO import com.academy.android.data.network.models.LectureDTO import com.academy.android.data.network.models.LoginRequestDTO import com.academy.android.data.network.models.LoginResponseDTO import com.academy.android.data.network.models.RegisterRequestDTO import com.academy.android.data.network.models.UpdateCourseRequestDTO import com.academy.android.data.network.models.UpdateLectureRequestDTO import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Query interface ServerApi { @POST("login") suspend fun login( @Body loginRequest: LoginRequestDTO ): LoginResponseDTO @POST("register") suspend fun register( @Body registerRequestDTO: RegisterRequestDTO ): LoginResponseDTO @GET("courses/favorite") suspend fun getFavouriteCourses(): List<CourseDTO> @GET("courses/all") suspend fun getAllCourses(): List<CourseDTO> @POST("courses/update") suspend fun updateCourse( @Body updateCourseRequestDTO: UpdateCourseRequestDTO ) @POST("lectures/update") suspend fun updateLecture( @Body updateLectureRequestDTO: UpdateLectureRequestDTO ) @GET("lectures/all") suspend fun getAllLectures( @Query(value = "courseId") courseId: Long ): List<LectureDTO> @GET("lectures/by-id") suspend fun getLectureById( @Query(value = "lectureId") lectureId: Long ): LectureDTO @POST("user/update-fcm-token") suspend fun updateFcmToken( @Body fcmToken: String ) }
19
Kotlin
0
1
4b6265571643fc7a8f346a31e12309bbc7a4d42b
1,641
AndroidAcademyClient
Apache License 2.0
app/src/main/java/com/duckduckgo/app/browser/remotemessage/RemoteMessagingViewModel.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.app.browser.remotemessage import com.duckduckgo.app.pixels.AppPixelName import com.duckduckgo.app.statistics.pixels.Pixel import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.ViewScope import com.duckduckgo.remote.messaging.api.Action import com.duckduckgo.remote.messaging.api.Content import com.duckduckgo.remote.messaging.api.RemoteMessage import com.duckduckgo.remote.messaging.api.RemoteMessagingRepository import dagger.SingleInstanceIn import javax.inject.Inject import kotlinx.coroutines.withContext @SingleInstanceIn(ViewScope::class) class RemoteMessagingModel @Inject constructor( private val remoteMessagingRepository: RemoteMessagingRepository, private val pixel: Pixel, private val dispatchers: DispatcherProvider, ) { val activeMessages = remoteMessagingRepository.messageFlow() suspend fun onMessageShown(remoteMessage: RemoteMessage) { withContext(dispatchers.io()) { tryToFireUniquePixel(remoteMessage) pixel.fire(AppPixelName.REMOTE_MESSAGE_SHOWN, remoteMessage.asPixelParams()) } } private fun tryToFireUniquePixel(remoteMessage: RemoteMessage) { val didShow = remoteMessagingRepository.didShow(remoteMessage.id) if (!didShow) { pixel.fire(AppPixelName.REMOTE_MESSAGE_SHOWN_UNIQUE, remoteMessage.asPixelParams()) remoteMessagingRepository.markAsShown(remoteMessage) } } suspend fun onMessageDismissed(remoteMessage: RemoteMessage) { pixel.fire(AppPixelName.REMOTE_MESSAGE_DISMISSED, remoteMessage.asPixelParams()) withContext(dispatchers.io()) { remoteMessagingRepository.dismissMessage(remoteMessage.id) } } suspend fun onPrimaryActionClicked(remoteMessage: RemoteMessage): Action? { pixel.fire(AppPixelName.REMOTE_MESSAGE_PRIMARY_ACTION_CLICKED, remoteMessage.asPixelParams()) withContext(dispatchers.io()) { remoteMessagingRepository.dismissMessage(remoteMessage.id) } return remoteMessage.content.getPrimaryAction() } suspend fun onSecondaryActionClicked(remoteMessage: RemoteMessage): Action? { pixel.fire(AppPixelName.REMOTE_MESSAGE_SECONDARY_ACTION_CLICKED, remoteMessage.asPixelParams()) withContext(dispatchers.io()) { remoteMessagingRepository.dismissMessage(remoteMessage.id) } return remoteMessage.content.getSecondaryAction() } fun onActionClicked(remoteMessage: RemoteMessage): Action? { pixel.fire(AppPixelName.REMOTE_MESSAGE_ACTION_CLICKED, remoteMessage.asPixelParams()) return remoteMessage.content.getAction() } private fun Content.getPrimaryAction(): Action? { return when (this) { is Content.BigSingleAction -> { this.primaryAction } is Content.BigTwoActions -> { this.primaryAction } else -> null } } private fun Content.getSecondaryAction(): Action? { return when (this) { is Content.BigTwoActions -> { this.secondaryAction } else -> null } } private fun Content.getAction(): Action? { return when (this) { is Content.PromoSingleAction -> { this.action } else -> null } } private fun RemoteMessage.asPixelParams(): Map<String, String> = mapOf(Pixel.PixelParameter.MESSAGE_SHOWN to this.id) }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
3,570
DuckDuckGo
Apache License 2.0
src/main/kotlin/org/ageseries/libage/parsers/falstad/components/generic/OutputProbe.kt
age-series
414,408,529
false
null
package org.eln2.parsers.falstad.components.generic import org.eln2.parsers.falstad.CCData import org.eln2.parsers.falstad.IComponentConstructor import org.eln2.parsers.falstad.PinRef import org.eln2.parsers.falstad.PosSet import org.eln2.sim.electrical.mna.component.Resistor /** * Output Probe * * Falstad's Output Probe - shows the voltage of a particular node in the circuit. */ class OutputProbe : IComponentConstructor { companion object { val HIGH_IMPEDANCE = Double.POSITIVE_INFINITY } override fun construct(ccd: CCData) { val r = Resistor() r.resistance = HIGH_IMPEDANCE ccd.circuit.add(r) r.ground(1) val pp = (ccd.falstad.getPin(ccd.pos).representative as PosSet) val pr = PinRef(r, 0) ccd.falstad.addPinRef(pp, pr) ccd.falstad.addOutput(pr) ccd.pins = 1 } }
5
null
1
1
0ce1c5a1d7eff41a0dbee389d50c6eaa10cac7c0
876
libage
MIT License
alchemy-core/src/commonMain/kotlin/com/alchemy/sdk/core/model/BlockCount.kt
tguerin
534,856,094
false
null
package com.alchemy.sdk.core.model import com.alchemy.sdk.core.adapter.KBlockCountSerializer import kotlinx.serialization.Serializable import kotlin.jvm.JvmInline @JvmInline @Serializable(with = KBlockCountSerializer::class) value class BlockCount constructor(val value: Int) { companion object { val Int.blockCount: BlockCount get() { check(this > 0) return BlockCount(this) } } }
4
Kotlin
0
3
9768a7ab07d9955e3036c32b1f4497527f237b34
456
alchemy-sdk-kotlin
MIT License
app/src/main/java/de/comobi/Constants.kt
Sheroziy-CODE
428,068,297
false
{"Kotlin": 44271}
package de.comobi /** Constants are used in ChatVideModel.kt and Chat.kt to store adn sort date. **/ object Constants { const val TAG = "comobi-chat" const val MESSAGES = "messages_android" const val MESSAGE = "message" const val SENT_BY = "sent_by" const val SENT_ON = "sent_on" const val IS_CURRENT_USER = "is_current_user" }
0
Kotlin
0
0
9e90e55078208c1e5250af27fe5b3d9f6eb85ac4
354
comobi
Open Market License
shared/gamelogic/src/commonMain/kotlin/dmitry/molchanov/gamelogic/domain/SnakeHelper.kt
MolchanovDmitry
548,285,365
false
{"Kotlin": 107173, "HTML": 334}
package dmitry.molchanov.gamelogic.domain import dmitry.molchanov.gamelogic.GameInputParams import dmitry.molchanov.gamelogic.domain.gameoverstrategy.GameOverStrategy import kotlin.random.Random class SnakeHelper( gameInputParams: GameInputParams, private val screenHelper: ScreenHelper, private val gameOverStrategies: List<GameOverStrategy>, ) { val chainSize = getRoundedChainSize(notOptimizeChainSize = gameInputParams.inputChainSize) private val maxHorizontalChains: Int = gameInputParams.inputWidth / chainSize private val maxVerticalChains: Int = gameInputParams.inputHeight / chainSize private val width = maxHorizontalChains * chainSize private val height = maxVerticalChains * chainSize val startChains: List<SnakeChain> get() = listOf(startChain) private val startChain: SnakeChain get() { val roundedVerticalChains = if (maxVerticalChains % 2 == 0) maxVerticalChains / 2 else maxVerticalChains / 2 + 1 return SnakeChain(x = 0, y = roundedVerticalChains * chainSize) } fun getNewChainToTail(chains: List<SnakeChain>, direct: Direct): SnakeChain = when (chains.size) { 0 -> error("Zero chain") 1 -> chains.first().getNewChainDirect(direct) else -> chains.getNewChainBy2LastChain() } fun getMovedChains(chains: List<SnakeChain>, direct: Direct): List<SnakeChain> { var lastXYPair = 0 to 0 return chains.mapIndexed { index, snakeChain -> if (index == 0) { getNewHeadChain(currentChain = snakeChain, direct = direct) } else { SnakeChain(x = lastXYPair.first, y = lastXYPair.second) }.also { lastXYPair = snakeChain.x to snakeChain.y } } } fun isGameOver(prefChains: List<SnakeChain>, newChains: List<SnakeChain>): Boolean = gameOverStrategies.find { gameOverStrategy -> gameOverStrategy.isGameOver( prefChains = prefChains, newChains = newChains, chainSize = chainSize ) } != null fun getFreeChain(chains: List<SnakeChain>): SnakeChain { val randomHorizontalChainCount = Random.nextInt(0, maxHorizontalChains) val randomVerticalChainCount = Random.nextInt(0, maxVerticalChains) val freeChainX = randomHorizontalChainCount * chainSize val freeChainY = randomVerticalChainCount * chainSize val shouldSkip = !screenHelper.isPointOnScreen( width = width, height = height, x = freeChainX, y = freeChainY ) || chains.contains(SnakeChain(x = freeChainX, y = freeChainY)) return if (shouldSkip) { getFreeChain(chains) } else { SnakeChain(x = freeChainX, y = freeChainY) } } private fun getRoundedChainSize(notOptimizeChainSize: Int): Int { if (notOptimizeChainSize == 1) { return 1 } val chainSizeDivRest = notOptimizeChainSize % 5 return if (chainSizeDivRest == 0) { notOptimizeChainSize } else { notOptimizeChainSize + 5 - chainSizeDivRest } } private fun SnakeChain.getNewChainDirect(direct: Direct): SnakeChain { return when (direct) { Direct.TOP -> { val newY = y + chainSize SnakeChain(x = x, y = if (newY >= height) 0 else newY) } Direct.RIGHT -> { val newX = x - chainSize SnakeChain(x = if (newX <= 0) width - chainSize else newX, y = y) } Direct.DOWN -> { val newY = y - chainSize SnakeChain(x = x, y = if (newY <= 0) height - chainSize else newY) } Direct.LEFT -> { val newX = x + chainSize SnakeChain(x = if (newX >= width) 0 else newX, y = y) } } } private fun List<SnakeChain>.getNewChainBy2LastChain(): SnakeChain { val lastChain = last() val preLastChain = get(size - 2) val tailDirect = when { lastChain.x == preLastChain.x && lastChain.y < preLastChain.y -> Direct.DOWN lastChain.x == preLastChain.x && lastChain.y > preLastChain.y -> Direct.TOP lastChain.x > preLastChain.x && lastChain.y == preLastChain.y -> Direct.LEFT lastChain.x < preLastChain.x && lastChain.y == preLastChain.y -> Direct.RIGHT else -> error("Uncatched chain difference") } return lastChain.getNewChainDirect(tailDirect) } private fun getNewHeadChain(currentChain: SnakeChain, direct: Direct): SnakeChain { val x = currentChain.x val y = currentChain.y return when (direct) { Direct.RIGHT -> { val newX = x + chainSize SnakeChain(x = if (newX >= width) 0 else newX, y = y) } Direct.LEFT -> { val newX = x - chainSize SnakeChain(x = if (newX < 0) width else newX, y = y) } Direct.TOP -> { val newY = y - chainSize SnakeChain(x = x, y = if (newY < 0) height else newY) } Direct.DOWN -> { val newY = y + chainSize SnakeChain(x = x, y = if (newY >= height) 0 else newY) } } } }
0
Kotlin
0
0
dee62070a223c64236ea397a48fa11b469dc585e
5,541
SnakeKmp
Apache License 2.0
processor/src/main/kotlin/com/casadetasha/kexp/petals/processor/outputgenerator/renderer/accessor/templates/functions/LoadFunctionTemplates.kt
Path-to-plunder
505,638,891
false
null
package com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.templates.functions import addIf import com.casadetasha.kexp.petals.processor.model.columns.PetalReferenceColumn import com.casadetasha.kexp.petals.processor.model.AccessorClassInfo import com.casadetasha.kexp.generationdsl.dsl.CodeTemplate import com.casadetasha.kexp.generationdsl.dsl.FunctionTemplate import com.casadetasha.kexp.generationdsl.dsl.ParameterTemplate import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.LoadMethodNames.LAZY_LOAD_ALL_METHOD_SIMPLE_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.LoadMethodNames.LOAD_ALL_METHOD_SIMPLE_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.LoadMethodNames.LOAD_METHOD_SIMPLE_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.LoadMethodNames.MAP_LAZY_MEMBER_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.CreateMethodNames.TRANSACTION_MEMBER_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.EagerLoadDependenciesMethodNames.COMPANION_EAGER_LOAD_DEPENDENCIES_METHOD_SIMPLE_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.ExportMethodNames.EXPORT_PETAL_METHOD_SIMPLE_NAME import com.casadetasha.kexp.petals.processor.outputgenerator.renderer.accessor.LoadMethodNames.LOAD_FROM_QUERY_METHOD_SIMPLE_NAME import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.asClassName import org.jetbrains.exposed.sql.Op import org.jetbrains.exposed.sql.SizedIterable internal fun createLoadFunctionTemplate(accessorClassInfo: AccessorClassInfo): FunctionTemplate = FunctionTemplate( name = LOAD_METHOD_SIMPLE_NAME, returnType = accessorClassInfo.className.copy(nullable = true), ) { collectParameterTemplates { accessorClassInfo.getLoadMethodParameters() } generateMethodBody(accessorClassInfo.getLoadMethodBody()) } private fun AccessorClassInfo.getLoadMethodParameters(): List<ParameterTemplate> { return mutableListOf( ParameterTemplate(name = "id", typeName = idKotlinClassName), ).addIf(petalReferenceColumns.isNotEmpty()) { ParameterTemplate(name = "eagerLoad", typeName = Boolean::class.asClassName()) { defaultValue { CodeTemplate("false") } } } } private fun AccessorClassInfo.getLoadMethodBody(): CodeTemplate { val entitySimpleName = entityClassName.simpleName return when (petalColumns.any { it is PetalReferenceColumn }) { true -> CodeTemplate { generateControlFlowCode("return %M", TRANSACTION_MEMBER_NAME, endFlowString = "}") { generateControlFlowCode("when (eagerLoad)") { generateCode ( format = "true -> %L.findById(id)?.$COMPANION_EAGER_LOAD_DEPENDENCIES_METHOD_SIMPLE_NAME()", entitySimpleName ) generateCode("false -> %L.findById(id)?.$EXPORT_PETAL_METHOD_SIMPLE_NAME()", entitySimpleName) } } } false -> CodeTemplate { generateControlFlowCode ( prefix = "return %M", TRANSACTION_MEMBER_NAME, suffix = "?.$EXPORT_PETAL_METHOD_SIMPLE_NAME()", endFlowString = "\n}" ) { generateCode("%L.findById(id)", entitySimpleName) } } } } internal fun createLoadAllFunctionTemplate(accessorClassInfo: AccessorClassInfo): FunctionTemplate = FunctionTemplate( name = LOAD_ALL_METHOD_SIMPLE_NAME, returnType = List::class.asClassName() .parameterizedBy(accessorClassInfo.className) ) { generateMethodBody { generateControlFlowCode("return %M", TRANSACTION_MEMBER_NAME) { generateCode ( "%L.all().map { it.$EXPORT_PETAL_METHOD_SIMPLE_NAME() }", accessorClassInfo.entityClassName.simpleName ) } } } internal fun createLazyLoadAllFunctionTemplate(accessorClassInfo: AccessorClassInfo) = FunctionTemplate( name = LAZY_LOAD_ALL_METHOD_SIMPLE_NAME, returnType = SizedIterable::class.asClassName() .parameterizedBy(accessorClassInfo.className) ) { generateMethodBody { generateControlFlowCode("return %L.all().%M", accessorClassInfo.entityClassName.simpleName, MAP_LAZY_MEMBER_NAME ) { generateCode("it.$EXPORT_PETAL_METHOD_SIMPLE_NAME()") } } } internal fun createLoadWhereFunctionTemplate(accessorClassInfo: AccessorClassInfo) = FunctionTemplate( name = LOAD_FROM_QUERY_METHOD_SIMPLE_NAME, returnType = List::class.asClassName() .parameterizedBy(accessorClassInfo.className) ) { collectParameterTemplates { accessorClassInfo.getLoadWithQueryMethodParameters() } generateMethodBody { generateControlFlowCode("return %M", TRANSACTION_MEMBER_NAME) { generateCode( "%L.find(op(%L)).map { it.%L() }", accessorClassInfo.entityClassName.simpleName, accessorClassInfo.tableClassName.simpleName, EXPORT_PETAL_METHOD_SIMPLE_NAME ) } } } private fun AccessorClassInfo.getLoadWithQueryMethodParameters(): List<ParameterTemplate> { val lambdaReturnType = Op::class.asClassName().parameterizedBy(Boolean::class.asClassName()) val lambdaParameters = arrayOf(tableClassName) val lambdaTypeName = LambdaTypeName.get(returnType = lambdaReturnType, parameters = lambdaParameters) return listOf( ParameterTemplate(name = "op", typeName = lambdaTypeName) ) }
0
Kotlin
0
0
6e393bbd1ca09e4922260f0e383bf00f7926c166
6,025
petals
Apache License 2.0
app/src/main/java/com/zeynelerdi/mackolik/di/module/NewsFragmentModule.kt
ZeynelErdiKarabulut
320,010,103
false
{"Kotlin": 116012}
package com.zeynelerdi.mackolik.ui.news import com.zeynelerdi.mackolik.di.ViewModelKey import dagger.Module @Module abstract class NewsFragmentModule { @ViewModelKey(NewsViewModel::class) internal abstract fun provideMainViewModel(viewModel: NewsViewModel): NewsViewModel }
0
Kotlin
0
1
4b40e57d2193706e15e18dd77fbb459e960f35db
286
Mackolik
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/ui/source/browse/BrowseSourceGridHolder.kt
Jays2Kings
175,908,029
false
null
package eu.kanade.tachiyomi.ui.source.browse import android.app.Activity import android.view.View import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import coil.Coil import coil.clear import coil.request.ImageRequest import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.IFlexible import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.image.coil.CoverViewTarget import eu.kanade.tachiyomi.databinding.MangaGridItemBinding import eu.kanade.tachiyomi.ui.library.LibraryCategoryAdapter import eu.kanade.tachiyomi.util.view.setCards /** * Class used to hold the displayed data of a manga in the library, like the cover or the title. * All the elements from the layout file "item_catalogue_grid" are available in this class. * * @param view the inflated view for this holder. * @param adapter the adapter handling this holder. * @param listener a listener to react to single tap and long tap events. * @constructor creates a new library holder. */ class BrowseSourceGridHolder( private val view: View, private val adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, compact: Boolean, showOutline: Boolean, private val isFollows: Boolean = false, ) : BrowseSourceHolder(view, adapter) { private val binding = MangaGridItemBinding.bind(view) init { if (compact) { binding.textLayout.isVisible = false } else { binding.compactTitle.isVisible = false binding.gradient.isVisible = false } setCards(showOutline, binding.card, binding.unreadDownloadBadge.badgeView) } /** * Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this * holder with the given manga. * * @param manga the manga item to bind. */ override fun onSetValues(manga: Manga) { // Update the title of the manga. binding.title.text = manga.title binding.compactTitle.text = binding.title.text when (isFollows) { true -> binding.unreadDownloadBadge.root.setStatus( manga.follow_status!!, manga.favorite ) false -> binding.unreadDownloadBadge.root.setInLibrary(manga.favorite) } // Update the cover. setImage(manga) } override fun setImage(manga: Manga) { if ((view.context as? Activity)?.isDestroyed == true) return if (manga.thumbnail_url == null) { binding.coverThumbnail.clear() } else { manga.id ?: return val request = ImageRequest.Builder(view.context).data(manga) .target(CoverViewTarget(binding.coverThumbnail, binding.progress)).build() Coil.imageLoader(view.context).enqueue(request) } } }
84
null
73
974
928f7553bf800cbbc9006e7242f78741dfd64179
2,881
tachiyomiJ2K
Apache License 2.0
HexCodeK/src/main/kotlin/risky/hexcode/Main.kt
risky098
314,912,693
false
null
package risky.hexcode import org.bukkit.Bukkit import org.bukkit.plugin.java.JavaPlugin import risky.hexcode.pack.ChatEvent class Main : JavaPlugin() { var prefix = "§b[HexCode] §f: " override fun onEnable() { Bukkit.getLogger().info(prefix + "플러그인이 활성화 되었습니다.") Bukkit.getLogger().info(prefix + "사용 버전 (1.16)") Bukkit.getLogger().info(prefix + "기능추가 및 오류보고 연락처: 이준명#1139") Bukkit.getPluginManager().registerEvents(ChatEvent(), this) } }
0
Kotlin
0
1
b1776b471fa39b0bd73d06037f2a60b3bd417ad0
484
HexCodeK
MIT License
core/data/src/main/java/bivano/apps/data/di/RepositoryModule.kt
bimovall
255,101,239
false
null
package bivano.apps.data.di import bivano.apps.data.local.LocalDataSource import bivano.apps.data.local.LocalDataSourceImpl import bivano.apps.data.remote.RemoteDataSource import bivano.apps.data.remote.RemoteDataSourceImpl import bivano.apps.data.repository.achieved.AchievedRepository import bivano.apps.data.repository.achieved.AchievedRepositoryImpl import bivano.apps.data.repository.article.ArticleRepository import bivano.apps.data.repository.article.ArticleRepositoryImpl import bivano.apps.data.repository.headline.HeadlineRepository import bivano.apps.data.repository.headline.HeadlineRepositoryImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) abstract class RepositoryModule { /*@Singleton @Binds abstract fun bindsDataManager(dataManager: DataManagerImpl): DataManager*/ @Singleton @Binds abstract fun bindsLocalDataSource(localDataSourceImpl: LocalDataSourceImpl): LocalDataSource @Singleton @Binds abstract fun bindsRemoteDataSource(remoteDataSourceImpl: RemoteDataSourceImpl): RemoteDataSource @Singleton @Binds abstract fun bindsArticleRepository(articleRepositoryImpl: ArticleRepositoryImpl): ArticleRepository @Singleton @Binds abstract fun bindsHeadlineRepository(headlineRepositoryImpl: HeadlineRepositoryImpl): HeadlineRepository @Singleton @Binds abstract fun bindsAchievedRepository(repositoryImpl: AchievedRepositoryImpl): AchievedRepository }
0
Kotlin
0
1
e5ac2b34063d282738961fe9213b769234f1453e
1,611
YourNews
Apache License 2.0
compiler/testData/codegen/box/inlineClasses/functionNameMangling/propertySetterWithInlineClassTypeArgument.kt
JetBrains
3,432,266
false
null
// WITH_RUNTIME @Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE") @kotlin.jvm.JvmInline value class Str(val string: String) class C { var s = Str("") } fun box(): String { val x = C() x.s = Str("OK") return x.s.string }
125
null
4813
39,375
83d2d2cfcfc3d9903c902ca348f331f89bed1076
249
kotlin
Apache License 2.0
app/src/main/java/com/zacharee1/systemuituner/views/WriteSettingsView.kt
zacharee
221,786,635
false
{"Kotlin": 681812, "AIDL": 1172}
package com.zacharee1.systemuituner.views import android.content.Context import android.util.AttributeSet import androidx.constraintlayout.widget.ConstraintLayout import com.zacharee1.systemuituner.data.SettingsType import com.zacharee1.systemuituner.databinding.DialogWriteSettingBinding import com.zacharee1.systemuituner.util.launch import com.zacharee1.systemuituner.util.writeSetting class WriteSettingsView(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) { private val binding by lazy { DialogWriteSettingBinding.bind(this) } override fun onFinishInflate() { super.onFinishInflate() binding.apply.setOnClickListener { val key = binding.keyEntry.text?.toString() val value = binding.valueEntry.text?.toString() val type = SettingsType.fromValue(binding.settingsType.selectedItemPosition) if (!key.isNullOrBlank()) { launch { context.writeSetting(type, key, value, true) } } } } }
25
Kotlin
174
994
27672d3a0ad7caf1dce360dc1a0651926903b8a8
1,063
Tweaker
MIT License
ui/src/main/kotlin/gq/kirmanak/mealient/ui/Theme.kt
kirmanak
431,195,533
false
null
package gq.kirmanak.mealient 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.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.google.android.material.color.DynamicColors @Composable fun AppTheme( isDarkTheme: Boolean = isSystemInDarkTheme(), isDynamicColor: Boolean = DynamicColors.isDynamicColorAvailable(), content: @Composable () -> Unit ) { val colorScheme = when { Build.VERSION.SDK_INT < Build.VERSION_CODES.S || !isDynamicColor -> { if (isDarkTheme) darkColorScheme() else lightColorScheme() } isDarkTheme -> { dynamicDarkColorScheme(LocalContext.current) } else -> { dynamicLightColorScheme(LocalContext.current) } } MaterialTheme( colorScheme = colorScheme, content = content ) } object Dimens { val Small = 8.dp val Medium = 16.dp val Large = 24.dp }
9
null
2
99
6f8a9520f3736ae641e4541d24afb0dcf9623ea0
1,291
Mealient
MIT License
sketch-core/src/androidTest/kotlin/com/github/panpf/sketch/core/test/request/internal/EngineRequestInterceptorTest.kt
panpf
14,798,941
false
null
/* * Copyright (C) 2022 panpf <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.core.test.request.internal import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.request.DisplayData import com.github.panpf.sketch.request.DisplayRequest import com.github.panpf.sketch.request.DownloadData import com.github.panpf.sketch.request.DownloadRequest import com.github.panpf.sketch.request.ImageData import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.LoadData import com.github.panpf.sketch.request.LoadRequest import com.github.panpf.sketch.request.internal.EngineRequestInterceptor import com.github.panpf.sketch.request.internal.RequestInterceptorChain import com.github.panpf.sketch.test.utils.TestAssets import com.github.panpf.sketch.test.utils.TestHttpStack import com.github.panpf.sketch.test.utils.TestHttpUriFetcher import com.github.panpf.sketch.test.utils.TestRequest import com.github.panpf.sketch.core.test.getTestContextAndNewSketch import com.github.panpf.sketch.core.test.newSketch import com.github.panpf.sketch.test.utils.toRequestContext import com.github.panpf.sketch.util.asOrThrow import com.github.panpf.tools4j.test.ktx.assertThrow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class EngineRequestInterceptorTest { @Test fun testIntercept() { val (context, sketch) = getTestContextAndNewSketch { httpStack(TestHttpStack(it)) } val executeRequest: (ImageRequest) -> ImageData = { request -> runBlocking(Dispatchers.Main) { RequestInterceptorChain( sketch = sketch, initialRequest = request, request = request, requestContext = request.toRequestContext(), interceptors = listOf(EngineRequestInterceptor()), index = 0, ).proceed(request) }.getOrThrow() } executeRequest(DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI)).asOrThrow<DisplayData>() executeRequest(LoadRequest(context, TestAssets.SAMPLE_JPEG_URI)).asOrThrow<LoadData>() executeRequest(DownloadRequest(context, TestHttpStack.testImages.first().uriString)) .asOrThrow<DownloadData>() assertThrow(UnsupportedOperationException::class) { executeRequest(TestRequest(context, TestAssets.SAMPLE_JPEG_URI)) } val sketch1 = newSketch { components { addFetcher(TestHttpUriFetcher.Factory()) } } val executeRequest1: (ImageRequest) -> ImageData = { request -> runBlocking(Dispatchers.Main) { RequestInterceptorChain( sketch = sketch1, initialRequest = request, request = request, requestContext = request.toRequestContext(), interceptors = listOf(EngineRequestInterceptor()), index = 0, ).proceed(request) }.getOrThrow() } assertThrow(UnsupportedOperationException::class) { executeRequest1(DownloadRequest(context, TestHttpStack.testImages.first().uriString)) } } @Test fun testSortWeight() { EngineRequestInterceptor().apply { Assert.assertEquals(100, sortWeight) } } @Test fun testEqualsAndHashCode() { val element1 = EngineRequestInterceptor() val element11 = EngineRequestInterceptor() val element2 = EngineRequestInterceptor() Assert.assertNotSame(element1, element11) Assert.assertNotSame(element1, element2) Assert.assertNotSame(element2, element11) Assert.assertEquals(element1, element1) Assert.assertEquals(element1, element11) Assert.assertEquals(element1, element2) Assert.assertEquals(element2, element11) Assert.assertNotEquals(element1, null) Assert.assertNotEquals(element1, Any()) Assert.assertEquals(element1.hashCode(), element1.hashCode()) Assert.assertEquals(element1.hashCode(), element11.hashCode()) Assert.assertEquals(element1.hashCode(), element2.hashCode()) Assert.assertEquals(element2.hashCode(), element11.hashCode()) } @Test fun testToString() { Assert.assertEquals("EngineRequestInterceptor(sortWeight=100)", EngineRequestInterceptor().toString()) } }
7
null
309
1,978
82ffde1ff148311bb5b36eb70a4c82224d1f3af4
5,201
sketch
Apache License 2.0
app/src/main/java/com/m3rc/beerbox/app/beer/BeerDetailsBottomDialog.kt
M3rcur14l
171,579,998
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 41, "XML": 46, "Java": 5}
package com.m3rc.beerbox.app.beer import android.content.res.ColorStateList import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.m3rc.beerbox.R import com.m3rc.beerbox.app.beer.viewholder.BeerViewHolder.Companion.glideOptions import com.m3rc.beerbox.data.Beer import com.m3rc.beerbox.kx.color import kotlinx.android.synthetic.main.fragment_beer_details.* class BeerDetailsBottomDialog : BottomSheetDialogFragment() { companion object { private const val BEER_EXTRA = "BEER_EXTRA" fun newInstance(beer: Beer): BeerDetailsBottomDialog { val fragment = BeerDetailsBottomDialog() val extras = Bundle() extras.putParcelable(BEER_EXTRA, beer) fragment.arguments = extras return fragment } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_beer_details, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { b -> val beer = b.getParcelable<Beer?>(BEER_EXTRA) beer?.apply { Glide.with(beerImage) .load(image) .transition(DrawableTransitionOptions.withCrossFade()) .apply(glideOptions) .into(beerImage) beerName.text = name beerTagLine.text = tagLine beerDescription.text = description color()?.let { beerEbc.imageTintList = ColorStateList.valueOf(it) } } } } override fun getTheme(): Int = R.style.BottomSheetDialogTheme }
1
null
1
1
7647e42d4c1011ee125b6f848e914b8d090d795b
2,059
Beer-Box
Apache License 2.0
src/main/kotlin/org/parchmentmc/scribe/action/MapParameterAction.kt
ParchmentMC
400,296,571
false
null
/* * Scribe * Copyright (C) 2021 ParchmentMC * * 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 org.parchmentmc.scribe.action import com.intellij.codeInsight.navigation.targetPresentation import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.ui.InputValidatorEx import com.intellij.openapi.ui.Messages import com.intellij.psi.PsiMethod import com.intellij.psi.PsiParameter import com.intellij.ui.list.createTargetPopup import com.intellij.util.text.nullize import org.parchmentmc.scribe.ParchmentMappings import org.parchmentmc.scribe.util.findAllSuperConstructors import org.parchmentmc.scribe.util.findAllSuperMethods class MapParameterAction : MappingAction() { override fun actionPerformed(e: AnActionEvent) { val parameter = e.getData(CommonDataKeys.PSI_ELEMENT) as? PsiParameter ?: return val mapFun = fun(parameter: PsiParameter) { val currentName = ParchmentMappings.getParameterMapping(parameter, searchSupers = true) // Return early if they canceled (null), but then make null if it's empty or only has spaces val mapped = (Messages.showInputDialog( e.project, "Enter a new parameter name:", "Map Parameter", Messages.getQuestionIcon(), currentName, inputValidator ) ?: return).nullize(nullizeSpaces = true) if (mapped == currentName) return val parameterData = ParchmentMappings.getParameterData(parameter, create = true) ?: return parameterData.name = mapped ParchmentMappings.modified = true ParchmentMappings.invalidateHints() } mapParameter(e, parameter, mapFun) } companion object { private val parameterRegex = Regex("[a-z][a-zA-Z0-9]*") private val inputValidator = object : InputValidatorEx { override fun checkInput(inputString: String?) = isValid(inputString) override fun canClose(inputString: String?) = isValid(inputString) override fun getErrorText(inputString: String?): String? = if (isValid(inputString)) { null } else { "$inputString does not conform to the mapping standards. It must start with a lowercase letter and then only contain alphanumeric characters afterwards." } private fun isValid(inputString: String?) = inputString?.nullize(nullizeSpaces = true)?.let { parameterRegex matches it } ?: true } internal fun mapParameter( e: AnActionEvent, parameter: PsiParameter, mapFun: (PsiParameter) -> Unit ) { val containingMethod = parameter.declarationScope as? PsiMethod ?: return val allSuperMethods = if (containingMethod.isConstructor) { containingMethod.findAllSuperConstructors() } else { containingMethod.findAllSuperMethods() } if (allSuperMethods.isNotEmpty()) { allSuperMethods.add(0, containingMethod) @Suppress("UnstableApiUsage") val popup = createTargetPopup("Choose method in inheritance structure to map", allSuperMethods, ::targetPresentation) { targetMethod -> val newParam = targetMethod.parameterList.parameters.getOrNull(containingMethod.parameterList.getParameterIndex(parameter)) ?: return@createTargetPopup mapFun(newParam) } popup.showInBestPositionFor(e.getData(CommonDataKeys.EDITOR) ?: return) } else { mapFun(parameter) } } } }
1
Kotlin
2
4
abb07e6575a74f952e61b0857a3ce65a950a6933
4,769
Scribe
MIT License
AndroidKotlinDemo/app/src/main/java/com/yueban/androidkotlindemo/demo/paging/ui/SearchRepositoriesActivity.kt
yueban
27,426,345
false
null
package com.yueban.androidkotlindemo.demo.paging.ui import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.view.View import android.view.inputmethod.EditorInfo import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.yueban.androidkotlindemo.R import com.yueban.androidkotlindemo.demo.paging.Injection import kotlinx.android.synthetic.main.activity_search_repositories.* /** * @author yueban * @date 2018/12/10 * @email <EMAIL> */ class SearchRepositoriesActivity : AppCompatActivity() { private lateinit var viewModel: SearchRepositoriesViewModel private val adapter = ReposAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search_repositories) viewModel = ViewModelProviders.of(this, Injection.provideViewModelFactory(this)) .get(SearchRepositoriesViewModel::class.java) val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL) list.addItemDecoration(decoration) setupScrollListener() initAdapter() val query = savedInstanceState?.getString(LAST_SEARCH_QUERY) ?: DEFAULT_QUERY viewModel.searchRepo(query) initSearch(query) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(LAST_SEARCH_QUERY, viewModel.lastQueryValue()) } private fun initAdapter() { list.adapter = adapter viewModel.repos.observe(this, Observer { Log.d(TAG, "list: ${it?.size}") showEmptyList(it?.size == 0) adapter.submitList(it) }) viewModel.networkErrors.observe(this, Observer { Toast.makeText(this, "\uD83D\uDE28 Wooops ${it}", Toast.LENGTH_LONG).show() }) } private fun initSearch(query: String) { search_repo.setText(query) search_repo.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_GO) { updateRepoListFromInput() true } else { false } } search_repo.setOnKeyListener { _, keyCode, event -> if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { updateRepoListFromInput() true } else { false } } } private fun updateRepoListFromInput() { search_repo.text.trim().let { if (it.isNotEmpty()) { list.scrollToPosition(0) viewModel.searchRepo(it.toString()) adapter.submitList(null) } } } private fun showEmptyList(show: Boolean) { if (show) { emptyList.visibility = View.VISIBLE list.visibility = View.GONE } else { emptyList.visibility = View.GONE list.visibility = View.VISIBLE } } private fun setupScrollListener() { val layoutManager = list.layoutManager as LinearLayoutManager list.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) val totalItemCount = layoutManager.itemCount val visibleItemCount = layoutManager.childCount val lastVisibleItem = layoutManager.findLastVisibleItemPosition() viewModel.listScrolled(visibleItemCount, lastVisibleItem, totalItemCount) } }) } companion object { private const val TAG = "Search Repo Activity" private const val LAST_SEARCH_QUERY: String = "last_search_query" private const val DEFAULT_QUERY = "Android" } }
0
Java
4
16
9ff75adc009aadedba4d05850af8a7748afbb6e2
4,193
AndroidExercise
Apache License 2.0
backend/src/test/kotlin/fr/gouv/cacem/monitorenv/domain/use_cases/controlUnit/CanDeleteControlUnitUTests.kt
MTES-MCT
462,794,012
false
{"TypeScript": 1358478, "Kotlin": 815514, "Python": 209694, "Shell": 21375, "CSS": 19997, "JavaScript": 8409, "Makefile": 8169, "Dockerfile": 6554, "PLpgSQL": 4966, "HTML": 864}
package fr.gouv.cacem.monitorenv.domain.use_cases.controlUnit import com.nhaarman.mockitokotlin2.given import fr.gouv.cacem.monitorenv.domain.entities.mission.MissionEntity import fr.gouv.cacem.monitorenv.domain.entities.mission.MissionSourceEnum import fr.gouv.cacem.monitorenv.domain.entities.reporting.ReportingEntity import fr.gouv.cacem.monitorenv.domain.repositories.IMissionRepository import fr.gouv.cacem.monitorenv.domain.repositories.IReportingRepository import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.junit.jupiter.SpringExtension import java.time.ZonedDateTime val FAKE_MISSION = MissionEntity( id = 1, missionTypes = listOf(), controlUnits = listOf(), openBy = null, closedBy = null, observationsCacem = null, observationsCnsp = null, facade = null, geom = null, startDateTimeUtc = ZonedDateTime.now(), endDateTimeUtc = null, envActions = listOf(), isClosed = false, isDeleted = false, isGeometryComputedFromControls = false, missionSource = MissionSourceEnum.MONITORENV, hasMissionOrder = false, isUnderJdp = false, ) val FAKE_REPORTING = ReportingEntity( id = 1, reportingId = null, sourceType = null, semaphoreId = null, controlUnitId = null, sourceName = null, targetType = null, vehicleType = null, targetDetails = null, geom = null, seaFront = null, description = null, reportType = null, themeId = null, subThemeIds = null, actionTaken = null, isControlRequired = null, hasNoUnitAvailable = null, createdAt = ZonedDateTime.now(), validityTime = null, isArchived = false, isDeleted = false, openBy = null, missionId = null, attachedToMissionAtUtc = null, detachedFromMissionAtUtc = null, attachedEnvActionId = null, ) @ExtendWith(SpringExtension::class) class CanDeleteControlUnitUTests { @MockBean private lateinit var missionRepository: IMissionRepository @MockBean private lateinit var reportingRepository: IReportingRepository @Test fun `execute should return TRUE there are neither missions nor reportings attached to this control unit`() { val controlUnitId = 1 given(missionRepository.findByControlUnitId(controlUnitId)).willReturn(listOf()) given(reportingRepository.findByControlUnitId(controlUnitId)).willReturn(listOf()) val result = CanDeleteControlUnit(missionRepository, reportingRepository).execute(controlUnitId) assertThat(result).isTrue() } @Test fun `execute should return FALSE when there are non-deleted missions attached to this control unit`() { val controlUnitId = 1 given(missionRepository.findByControlUnitId(controlUnitId)).willReturn( listOf(FAKE_MISSION), ) given(reportingRepository.findByControlUnitId(controlUnitId)).willReturn(listOf()) val result = CanDeleteControlUnit(missionRepository, reportingRepository).execute(controlUnitId) assertThat(result).isFalse() } @Test fun `execute should return TRUE when there are only deleted missions attached to this control unit`() { val controlUnitId = 1 given(missionRepository.findByControlUnitId(controlUnitId)).willReturn( listOf(FAKE_MISSION.copy(isDeleted = true)), ) given(reportingRepository.findByControlUnitId(controlUnitId)).willReturn(listOf()) val result = CanDeleteControlUnit(missionRepository, reportingRepository).execute(controlUnitId) assertThat(result).isTrue() } @Test fun `execute should return FALSE when there are non-deleted reportings attached to this control unit`() { val controlUnitId = 1 given(missionRepository.findByControlUnitId(controlUnitId)).willReturn(listOf()) given(reportingRepository.findByControlUnitId(controlUnitId)).willReturn( listOf(FAKE_REPORTING), ) val result = CanDeleteControlUnit(missionRepository, reportingRepository).execute(controlUnitId) assertThat(result).isFalse() } @Test fun `execute should return TRUE when there are only deleted reportings attached to this control unit`() { val controlUnitId = 1 given(missionRepository.findByControlUnitId(controlUnitId)).willReturn(listOf()) given(reportingRepository.findByControlUnitId(controlUnitId)).willReturn( listOf(FAKE_REPORTING.copy(isDeleted = true)), ) val result = CanDeleteControlUnit(missionRepository, reportingRepository).execute(controlUnitId) assertThat(result).isTrue() } }
190
TypeScript
1
3
f755ce65909e473e564ff5e273b9b4930e82ad4d
5,031
monitorenv
MIT License
common/src/main/java/org/anti_ad/mc/common/Interfaces.kt
blackd
351,481,591
false
null
package org.anti_ad.mc.common interface Savable { fun save() fun load() } interface IInputHandler { fun onInput(lastKey: Int, lastAction: Int): Boolean } interface ScreenEventListener { // eavesdrop event/input fun resize( /* minecraftClient: Any, */ width: Int, height: Int) { } // fun mouseMoved(x: Double, y: Double) {} fun mouseClicked(x: Double, y: Double, button: Int) = false fun mouseRelease(x: Double, y: Double, button: Int) = false fun mouseDragged(x: Double, y: Double, button: Int, dx: Double, dy: Double) = false fun mouseScrolled(x: Double, y: Double, amount: Double) = false fun keyPressed(keyCode: Int, scanCode: Int, modifiers: Int) = false fun keyReleased(keyCode: Int, scanCode: Int, modifiers: Int) = false fun charTyped(charIn: Char, modifiers: Int) = false }
12
null
12
47
d8ff23dd59d58b22b4dc1684f081b7139a0dd42e
1,198
Inventory-Profiles
MIT License
app/src/main/java/com/lvp/autodownloader/ui/theme/Color.kt
LuongPV
770,756,923
false
{"Kotlin": 224582}
package com.lvp.autodownloader.ui.theme import androidx.compose.ui.graphics.Color val MainThemeColor = Color(0xFFCFA435) val DisableColor = Color(0xFFC5C5C5) val EnableColor = Color(0xFF141414) val SuggestColor = Color(0xFF1E7917) val GreenColor = Color(0xFF1E7917) val BackgroundColor = Color(0xFFF0F0F0) const val RedColor = 0xFFD61515
0
Kotlin
0
0
202996200152e344a90a07c2c69588d0263a9496
339
AutoDownloader
Apache License 1.1
compiler/testData/writeSignature/declarationSiteVariance/OutInOutPosition.kt
JakeWharton
99,388,807
false
null
fun f(): List<String> = throw Exception() // method: OutInOutPositionKt::f // jvm signature: ()Ljava/util/List; // generic signature: ()Ljava/util/List<Ljava/lang/String;>;
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
177
kotlin
Apache License 2.0
src/commonMain/kotlin/app/thelema/ui/ScissorStack.kt
zeganstyl
275,550,896
false
null
/* * Copyright 2020-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 app.thelema.ui import app.thelema.app.APP import app.thelema.gl.GL import app.thelema.gl.GL_SCISSOR_TEST import app.thelema.math.* import kotlin.math.max import kotlin.math.min /** A stack of [Rectangle] objects to be used for clipping via [GL.glScissor]. When a new * Rectangle is pushed onto the stack, it will be merged with the current top of stack. The minimum area of overlap is then set as * the real top of the stack. * @author mzechner */ object ScissorStack { private val scissors = ArrayList<IRectangle>() internal val tmp = Vec3() var isLogicalCoordinates: Boolean = true /** Pushes a new scissor [Rectangle] onto the stack, merging it with the current top of the stack. The minimal area of * overlap between the top of stack rectangle and the provided rectangle is pushed onto the stack. This will invoke * [GL.glScissor] with the final top of stack rectangle. In case no scissor is yet on the stack * this will also enable [GL_SCISSOR_TEST] automatically. * * * Any drawing should be flushed before pushing scissors. * @return true if the scissors were pushed. false if the scissor area was zero, in this case the scissors were not pushed and * no drawing should occur. */ fun pushScissors(scissor: IRectangle): Boolean { fix(scissor) if (scissors.size == 0) { if (scissor.width < 1 || scissor.height < 1) return false GL.glEnable(GL_SCISSOR_TEST) } else { // merge scissors val parent = scissors[scissors.size - 1] val minX = max(parent.x, scissor.x) val maxX = min(parent.x + parent.width, scissor.x + scissor.width) if (maxX - minX < 1) return false val minY = max(parent.y, scissor.y) val maxY = min(parent.y + parent.height, scissor.y + scissor.height) if (maxY - minY < 1) return false scissor.x = minX scissor.y = minY scissor.width = maxX - minX scissor.height = max(1f, maxY - minY) } scissors.add(scissor) glScissor(scissor.x.toInt(), scissor.y.toInt(), scissor.width.toInt(), scissor.height.toInt()) return true } /** Calls glScissor, expecting the coordinates and sizes given in logical coordinates and * automatically converts them to backbuffer coordinates, which may be bigger on HDPI screens. */ fun glScissor(x: Int, y: Int, width: Int, height: Int, isLogicalCoordinates: Boolean = this.isLogicalCoordinates) { if (isLogicalCoordinates && (APP.width != GL.mainFrameBufferWidth || APP.height != GL.mainFrameBufferHeight)) { GL.glScissor( toBackBufferX(x), toBackBufferY(y), toBackBufferX(width), toBackBufferY(height) ) } else { GL.glScissor(x, y, width, height) } } /** Converts an x-coordinate given in logical screen coordinates to backbuffer coordinates. */ private fun toBackBufferX(logicalX: Int): Int { return (logicalX * GL.mainFrameBufferWidth / APP.width.toFloat()).toInt() } /** Convers an y-coordinate given in backbuffer coordinates to logical screen coordinates */ private fun toBackBufferY(logicalY: Int): Int { return (logicalY * GL.mainFrameBufferHeight / APP.height.toFloat()).toInt() } /** Pops the current scissor rectangle from the stack and sets the new scissor area to the new top of stack rectangle. In case * no more rectangles are on the stack, [GL_SCISSOR_TEST] is disabled. * * * Any drawing should be flushed before popping scissors. */ fun popScissors(): IRectangle { val last = scissors.last() scissors.remove(last) if (scissors.size == 0) GL.glDisable(GL_SCISSOR_TEST) else { val scissor = scissors.last() glScissor(scissor.x.toInt(), scissor.y.toInt(), scissor.width.toInt(), scissor.height.toInt()) } return last } /** @return null if there are no scissors. */ fun peekScissors(): IRectangle? { return if (scissors.size == 0) null else scissors.last() } private fun fix(rect: IRectangle) { rect.x = rect.x.toInt().toFloat() rect.y = rect.y.toInt().toFloat() rect.width = rect.width.toInt().toFloat() rect.height = rect.height.toInt().toFloat() if (rect.width < 0) { rect.width = -rect.width rect.x -= rect.width } if (rect.height < 0) { rect.height = -rect.height rect.y -= rect.height } } }
3
Kotlin
5
61
8e2943b6d2de3376ce338025b58ff31c14097caf
5,309
thelema-engine
Apache License 2.0
app/src/main/java/com/hfut/schedule/ui/Activity/success/cube/Settings/Items/MyAPIItem.kt
Chiu-xaH
705,508,343
false
null
package com.hfut.schedule.ui.ComposeUI.Settings.Items import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.google.gson.Gson import com.hfut.schedule.App.MyApplication import com.hfut.schedule.R import com.hfut.schedule.logic.utils.SharePrefs.prefs import com.hfut.schedule.logic.datamodel.MyAPIResponse import com.hfut.schedule.logic.utils.GetDate @Composable fun MyAPIItem() { val my = prefs.getString("my", MyApplication.NullMy) val data = Gson().fromJson(my, MyAPIResponse::class.java).SettingsInfo var title = data.title var content = data.info val version = data.version val celebration = data.celebration val id = prefs.getString("ChineseId", "") if (id != null) { if (id.length == 18) { val birthday = id.substring(10, 14) val today = GetDate.Date_MM_dd.replace("-", "") if (today == birthday) { content = Birthday() title = "Happy Birthday !" } } } Card( elevation = CardDefaults.cardElevation( defaultElevation = 3.dp ), modifier = Modifier .fillMaxWidth() .padding(horizontal = 15.dp, vertical = 5.dp), shape = MaterialTheme.shapes.medium ){ ListItem( headlineContent = { Text(text = title, fontWeight = FontWeight.Bold) }, supportingContent = { Text(text = content) }, leadingContent = { APIIcons(celebration = celebration)}, modifier = Modifier.clickable{} ) } } @Composable fun APIIcons(celebration: Boolean) { when { celebration -> Icon(painterResource(R.drawable.celebration), contentDescription = "Localized description",) Birthday().contains("生日") -> Icon(painterResource(R.drawable.cake), contentDescription = "Localized description",) else -> Icon(painterResource(R.drawable.error), contentDescription = "Localized description",) } } @Composable fun Birthday() : String { val id = prefs.getString("ChineseId", "") var age = "" var info = "" if (id != null) { if (id.length == 18) { val year = id.substring(6, 10) val birthday = id.substring(10, 14) val todayYear = GetDate.Date_yyyy.toInt() val today = GetDate.Date_MM_dd.replace("-", "") if (today == birthday) { age = " " + (todayYear - year.toInt()).toString() + " 岁" info = "祝你${age}生日快乐" } } } return info }
0
null
1
3
aead3d3e437531c52a0ba99d71fae27d4ea0fe4f
3,142
HFUT-Schedule
Apache License 2.0
SingleModuleApp/app/src/main/java/com/github/yamamotoj/singlemoduleapp/package51/Foo05117.kt
yamamotoj
163,851,411
false
null
package com.github.yamamotoj.singlemoduleapp.package51 class Foo05117 { fun method0() { Foo05116().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
355
android_multi_module_experiment
Apache License 2.0
reduks/src/main/kotlin/com/beyondeye/reduks/Action.kt
beyondeye
59,747,728
false
{"Kotlin": 505882, "Java": 192306}
package com.beyondeye.reduks /** * base interface for all standard Reduks actions * Created by daely on 8/28/2016. */ interface Action /** * default start action sent when reduks starts up */ class INIT:Action
5
Kotlin
10
111
80b84d221b92aef0b172938c2e6efaef973269b1
218
Reduks
Apache License 2.0
schema-server-core/src/test/java/com/orbitalhq/schemaServer/core/file/packages/FileSystemTaxiPackageLoaderTest.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.schemaServer.core.file.packages import com.winterbe.expekt.should import com.orbitalhq.schemaServer.packages.TaxiPackageLoaderSpec import com.orbitalhq.schemaServer.core.file.FileProjectSpec import com.orbitalhq.schemaServer.core.file.deployProject import org.junit.Test import reactor.kotlin.test.test import java.nio.file.Files class FileSystemTaxiPackageLoaderTest : BaseFileSystemPackageLoaderTest() { @Test fun `can load a taxi package from disk`() { projectHome.deployProject("sample-project") val packageSpec = FileProjectSpec( projectHome.root.toPath(), TaxiPackageLoaderSpec ) val (fileMonitor, loader) = buildLoader(packageSpec) loader.start() .test() .expectSubscription() .expectNextMatches { schemaPackage -> schemaPackage.sourcesWithPackageIdentifier.should.be.empty true } .then { val createdFile = Files.createFile(projectHome.root.toPath().resolve("src/hello.taxi")) createdFile.toFile().writeText("type Name inherits String") fileMonitor.pollNow() } .expectNextMatches { schemaPackage -> schemaPackage.sourcesWithPackageIdentifier.should.have.size(1) true } .thenCancel() .verify() } @Test fun `can load an openapi package from disk`() { } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
1,431
orbital
Apache License 2.0
fingerprint/src/main/java/com/fingerprintjs/android/fingerprint/device_id_providers/MediaDrmIdProvider.kt
fingerprintjs
305,740,280
false
null
package com.fingerprintjs.android.fingerprint.device_id_providers import android.media.MediaDrm import android.os.Build import com.fingerprintjs.android.fingerprint.tools.DeprecationMessages import com.fingerprintjs.android.fingerprint.tools.executeSafe import java.security.MessageDigest import java.util.UUID @Deprecated(message = DeprecationMessages.UNREACHABLE_SYMBOL_UNINTENDED_PUBLIC_API) public class MediaDrmIdProvider { public fun getMediaDrmId(): String? = executeSafe({ mediaDrmId() }, null) private fun mediaDrmId(): String { val widevineUUID = UUID(WIDEWINE_UUID_MOST_SIG_BITS, WIDEWINE_UUID_LEAST_SIG_BITS) val wvDrm: MediaDrm? wvDrm = MediaDrm(widevineUUID) val mivevineId = wvDrm.getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID) releaseMediaDRM(wvDrm) val md: MessageDigest = MessageDigest.getInstance("SHA-256") md.update(mivevineId) return md.digest().toHexString() } private fun releaseMediaDRM(drmObject: MediaDrm) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { drmObject.close() } else { drmObject.release() } } } private fun ByteArray.toHexString(): String { return this.joinToString("") { java.lang.String.format("%02x", it) } } private const val WIDEWINE_UUID_MOST_SIG_BITS = -0x121074568629b532L private const val WIDEWINE_UUID_LEAST_SIG_BITS = -0x5c37d8232ae2de13L
6
null
72
467
563fbbccac04c2903851d5840cf60f8d67beafa7
1,477
fingerprintjs-android
MIT License
save-orchestrator-common/src/main/kotlin/com/saveourtool/save/orchestrator/controller/AgentsController.kt
saveourtool
300,279,336
false
{"Kotlin": 3427161, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
package com.saveourtool.save.orchestrator.controller import com.saveourtool.common.execution.ExecutionStatus import com.saveourtool.common.request.RunExecutionRequest import com.saveourtool.common.utils.EmptyResponse import com.saveourtool.common.utils.info import com.saveourtool.save.orchestrator.runner.ContainerRunnerException import com.saveourtool.save.orchestrator.service.AgentService import com.saveourtool.save.orchestrator.service.ContainerService import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException import reactor.core.publisher.Mono /** * Controller used to start agents with needed information */ @RestController class AgentsController( private val agentService: AgentService, private val containerService: ContainerService, ) { /** * Schedules tasks to build base images, create a number of containers and put their data into the database. * * @param request a request to run execution * @return OK if everything went fine. * @throws ResponseStatusException */ @Suppress("TOO_LONG_FUNCTION", "LongMethod", "UnsafeCallOnNullableType") @PostMapping("/initializeAgents") fun initialize(@RequestBody request: RunExecutionRequest): Mono<EmptyResponse> { val response = agentService.updateExecution(request.executionId, ExecutionStatus.INITIALIZATION) .thenReturn(ResponseEntity<Void>(HttpStatus.ACCEPTED)) .subscribeOn(agentService.scheduler) return response.doOnSuccess { log.info { "Starting preparations for launching execution id=${request.executionId}" } Mono.fromCallable { containerService.prepareConfiguration(request) } .subscribeOn(agentService.scheduler) .map { configuration -> containerService.createAndStartContainers(request.executionId, configuration) } .onErrorResume(ContainerRunnerException::class.java) { ex -> reportExecutionError(request.executionId, ex) } .flatMap { log.info("Sending request to make execution.id=${request.executionId} RUNNING") agentService.updateExecution(request.executionId, ExecutionStatus.RUNNING) } .flatMap { containerService.validateContainersAreStarted(request.executionId) } .subscribe() } } private fun <T> reportExecutionError( executionId: Long, ex: ContainerRunnerException, ): Mono<T> { log.error("${ex.message} for executionId=$executionId, will mark it as ERROR", ex) return agentService.updateExecution(executionId, ExecutionStatus.ERROR, ex.message) .then(Mono.empty()) } /** * Delete containers and images associated with execution [executionId] * * @param executionId id of execution * @return empty response */ @PostMapping("/cleanup") fun cleanup(@RequestParam executionId: Long): Mono<EmptyResponse> = Mono.fromCallable { containerService.cleanupAllByExecution(executionId) } .flatMap { Mono.just(ResponseEntity.ok().build()) } companion object { private val log = LoggerFactory.getLogger(AgentsController::class.java) } }
201
Kotlin
3
38
e101105f8e449253d5fbe81ece2668654d08639f
3,773
save-cloud
MIT License
ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/ValidationStampFilterCreate.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.model.security /** * Allowing the creation of validation stamp filters. */ @CoreFunction interface ValidationStampFilterCreate : ProjectFunction
57
Kotlin
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
177
ontrack
MIT License
src/advanced_control_flow/Range.kt
tumininucodes
326,037,478
false
null
package advanced_control_flow fun main() { val closedRange = 0..5 println(closedRange) val halfOpenRange = 0 until 5 println(halfOpenRange) val decreasingRange = 5 downTo 0 println(decreasingRange) }
0
Kotlin
0
1
cd7f87ebaabde14000879097a912f796f971ba90
226
kotlin
MIT License
app/src/main/java/com/example/achadin/adapter/ChatsAdapter.kt
Francisco-Jean
798,323,342
false
{"Kotlin": 361718, "Java": 455}
package com.example.achadin.adapter import android.content.Context import android.content.DialogInterface import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.recyclerview.widget.RecyclerView import com.example.achadin.R import com.example.achadin.models.ChatModel import com.example.achadin.repositories.AuthRepository import com.example.achadin.viewModels.ChatViewModel import com.example.achadin.views.chat.MessageChatActivity import com.example.achadin.views.chat.ViewFullImageActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.FirebaseDatabase import com.squareup.picasso.Picasso import de.hdodenhof.circleimageview.CircleImageView import com.google.android.material.snackbar.Snackbar class ChatsAdapter( context:Context, chatList:List<ChatModel>, imageUrl: String ):RecyclerView.Adapter<ChatsAdapter.ViewHolder?>() { private val context: Context? private val chatList: List<ChatModel> private val imageUrl: String private val chatViewModel = ChatViewModel() var firebaseUser: FirebaseUser? = AuthRepository().getCurrentUser() init { this.context = context this.chatList = chatList this.imageUrl = imageUrl } override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder { return if (position == 1) { val view: View = LayoutInflater.from(context).inflate(R.layout.message_item_right, parent, false) ViewHolder(view) } else { val view: View = LayoutInflater.from(context).inflate(R.layout.message_item_left, parent, false) ViewHolder(view) } } override fun getItemCount(): Int { return chatList!!.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val chat: ChatModel = chatList[position] if (imageUrl.isNotEmpty()) { Picasso.get().load(imageUrl).into(holder.profileImage) } else { holder.profileImage!!.setImageResource(R.drawable.profile_circle) } if (!chat.message.equals("Imagem enviada.") && chat.url.isEmpty()) { holder.leftImageView?.visibility = View.GONE holder.rightImageView?.visibility = View.GONE } if (chat.message.equals("Imagem enviada.") && chat.url.isNotEmpty()) { // imagem no lado direito if (chat.sender.equals(firebaseUser!!.uid)) { holder.showTextMessage!!.visibility = View.GONE holder.rightImageView!!.visibility = View.VISIBLE Picasso.get().load(chat.url).into(holder.rightImageView) holder.rightImageView!!.setOnClickListener { val options = arrayOf<CharSequence>( "Expandir imagem", "Deletar Imagem", "Cancelar" ) var builder: AlertDialog.Builder = AlertDialog.Builder(holder.itemView.context) builder.setTitle("O que deseja fazer?") builder.setItems(options, DialogInterface.OnClickListener { dialog, which -> if (which == 0) { val intent = Intent(context, ViewFullImageActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP intent.putExtra("url", chat.url) context!!.startActivity(intent) } else if (which == 1) { deleteSentMessage(position, chatList, holder) } }) builder.show() } } // imagem no lado esquerdo else if (!chat.sender.equals(firebaseUser!!.uid)) { holder.showTextMessage!!.visibility = View.GONE holder.leftImageView!!.visibility = View.VISIBLE Picasso.get().load(chat.url).into(holder.leftImageView) holder.leftImageView!!.setOnClickListener { val options = arrayOf<CharSequence>( "Expandir imagem", "Cancelar" ) var builder: AlertDialog.Builder = AlertDialog.Builder(holder.itemView.context) builder.setTitle("O que deseja fazer?") builder.setItems(options, DialogInterface.OnClickListener { dialog, which -> if (which == 0) { val intent = Intent(context, ViewFullImageActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP intent.putExtra("url", chat.url) context!!.startActivity(intent) } }) builder.show() } } } else { holder.showTextMessage!!.text = chat.message if (firebaseUser!!.uid == chat.sender) { holder.showTextMessage!!.setOnClickListener { val options = arrayOf<CharSequence>( "Deletar Mensagem", "Cancelar" ) var builder: AlertDialog.Builder = AlertDialog.Builder(holder.itemView.context) builder.setTitle("O que deseja fazer?") builder.setItems(options, DialogInterface.OnClickListener { dialog, which -> if (which == 0) { deleteSentMessage(position, chatList, holder) } }) builder.show() } } } if (position == chatList.size - 1) { if (chat.isSeen) { holder.textSeen!!.visibility = View.VISIBLE holder.textSeen!!.text = "Visto" if (chat.message.equals("Imagem enviada.") && chat.url.isNotEmpty()) { val lp: RelativeLayout.LayoutParams? = holder.textSeen!!.layoutParams as RelativeLayout.LayoutParams? lp!!.setMargins(0, 385, 10, 0) holder.textSeen!!.layoutParams = lp } } else { holder.textSeen!!.visibility = View.VISIBLE holder.textSeen!!.text = "Enviado" if (chat.message.equals("Imagem enviada.") && chat.url.isNotEmpty()) { val lp: RelativeLayout.LayoutParams? = holder.textSeen!!.layoutParams as RelativeLayout.LayoutParams? lp!!.setMargins(0, 385, 10, 0) holder.textSeen!!.layoutParams = lp } } } else { holder.textSeen!!.visibility = View.GONE } } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var profileImage: CircleImageView? = null var showTextMessage: TextView? = null var leftImageView: ImageView? = null var textSeen: TextView? = null var rightImageView: ImageView? = null init { profileImage = itemView.findViewById(R.id.profile_image) showTextMessage = itemView.findViewById(R.id.showTextMessage) leftImageView = itemView.findViewById(R.id.leftImageView) textSeen = itemView.findViewById(R.id.textSeen) rightImageView = itemView.findViewById(R.id.rightImageView) } } override fun getItemViewType(position: Int): Int { return if (chatList[position].sender.equals(firebaseUser!!.uid)) { 1 } else { 0 } } private fun deleteSentMessage(position: Int, chatList: List<ChatModel>, holder: ChatsAdapter.ViewHolder) { chatViewModel.deleteSentMessage(position, chatList).thenAccept { if (it) { Toast.makeText(holder.itemView.context, "Mensagem deletada", Toast.LENGTH_SHORT) .show() } else { Snackbar.make(holder.itemView, "Erro ao deletar mensagem", Snackbar.LENGTH_LONG) .show() } } } }
0
Kotlin
0
5
acf7d6545abd9b10abbd6054ea92c653904f23e3
8,835
AchadinApp
MIT License
backend/app/src/test/kotlin/io/tolgee/dialects/postgres/CustomPostgreSQLDialectTest.kt
tolgee
303,766,501
false
null
package io.tolgee.dialects.postgres import io.tolgee.model.UserAccount import io.tolgee.testing.assertions.Assertions.assertThat import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests import org.testng.annotations.Test import javax.persistence.EntityManager @SpringBootTest class CustomPostgreSQLDialectTest : AbstractTransactionalTestNGSpringContextTests() { @Autowired lateinit var entityManager: EntityManager @Test fun `similarity function works`() { // Hibernate queries doesn't work without FROM clause, so we have // to create a dummy entity to select from entityManager.persist(UserAccount(username = "aaa", password = "<PASSWORD>", name = "aaaaa")) val query = entityManager.createQuery( "select similarity('I am so funny!', 'You are so funny!') from UserAccount" ) assertThat(query.singleResult).isEqualTo(0.47619048f) } }
28
Kotlin
4
132
6f73e5fba815674b470098949577406f3d75a171
1,037
server
Apache License 2.0
core/src/main/java/com/example/core/di/components/CoreComponent.kt
princessdharmy
171,189,157
false
null
package com.example.core.di.components import android.content.Context import com.example.core.di.modules.CoreModule import com.example.core.di.modules.DatabaseModule import com.example.data.di.DataModule import com.example.domain.repository.CompetitionsRepository import dagger.BindsInstance import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [CoreModule::class, DataModule::class, DatabaseModule::class]) interface CoreComponent { @Component.Factory interface Factory { fun create(@BindsInstance context: Context): CoreComponent } val competitionsRepository: CompetitionsRepository }
1
null
10
93
2e5e64a084af5e3d64ecd97087c176185287605a
649
FootballFixturesApp
MIT License
stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/image/BitmapExtensions.kt
stripe
6,926,049
false
null
package com.stripe.android.stripecardscan.framework.image import android.graphics.Bitmap import androidx.annotation.CheckResult /** * Convert a [Bitmap] to an [MLImage] for use in ML models. */ @CheckResult internal fun Bitmap.toMLImage(mean: Float = 0F, std: Float = 255F) = MLImage(this, mean, std) /** * Convert a [Bitmap] to an [MLImage] for use in ML models. */ @CheckResult internal fun Bitmap.toMLImage(mean: ImageTransformValues, std: ImageTransformValues) = MLImage(this, mean, std)
64
Kotlin
522
935
bec4fc5f45b5401a98a310f7ebe5d383693936ea
503
stripe-android
MIT License
app/src/main/java/com/metoer/clocktracker/data/repositories/ClockRepository.kt
etokoc
510,835,828
false
null
package com.metoer.clocktracker.data.repositories import com.metoer.clocktracker.data.db.ClockDatabase import com.metoer.clocktracker.data.db.ClockItem class ClockRepository( private val db: ClockDatabase ) { fun updateAdd(item: ClockItem) = db.getClockDao().updateAdd(item) fun delete(item: ClockItem) = db.getClockDao().delete(item) fun getAllClockItems() = db.getClockDao().getAllClockItems() }
0
Kotlin
0
1
07e918b66d3d3d9f3aae077ceec047a99a8142f2
418
ClockTracker
MIT License
client/viewmodel/calculator/src/commonMain/kotlin/com/oztechan/ccc/client/viewmodel/calculator/util/CalculatorUtil.kt
Oztechan
102,633,334
false
null
package com.oztechan.ccc.client.viewmodel.calculator.util import com.github.submob.scopemob.whetherNot import com.oztechan.ccc.client.core.shared.util.getRateFromCode import com.oztechan.ccc.client.core.shared.util.toStandardDigits import com.oztechan.ccc.client.core.shared.util.toSupportedCharacters import com.oztechan.ccc.common.core.model.Conversion import com.oztechan.ccc.common.core.model.Currency internal fun Conversion?.calculateRate(code: String, input: String?) = this ?.whetherNot { input.isNullOrEmpty() } ?.getRateFromCode(code) ?.times(input?.toSupportedCharacters()?.toStandardDigits()?.toDouble() ?: 0.0) ?: 0.0 internal fun Currency.getConversionStringFromBase( base: String, conversion: Conversion? ) = "1 $base = ${conversion?.getRateFromCode(code)} ${getVariablesOneLine()}" fun List<Currency>?.toValidList(currentBase: String) = this?.filter { it.code != currentBase && it.isActive && it.rate != "NaN" && it.rate != "0.0" && it.rate != "0" } ?: mutableListOf()
28
null
30
331
a94168d623b6ffd50e142e0afe9f601db6ed7632
1,049
CCC
Apache License 2.0
app/src/main/java/com/kickstarter/ui/activities/compose/login/KSLoginDropdownMenu.kt
kickstarter
76,278,501
false
{"Kotlin": 5269841, "Java": 317201, "Ruby": 22177, "Shell": 6325, "Makefile": 3750}
package com.kickstarter.ui.activities.compose.login import androidx.compose.foundation.background import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import com.kickstarter.R import com.kickstarter.ui.compose.designsystem.KSTheme enum class LoginDropdownTestTag { OPTIONS_MENU, OPTIONS_TERMS, OPTIONS_PRIVACY_POLICY, OPTIONS_COOKIE, OPTIONS_HELP } @Composable fun KSLoginDropdownMenu( expanded: Boolean, onDismissed: () -> Unit, onTermsOfUseClicked: () -> Unit, onPrivacyPolicyClicked: () -> Unit, onCookiePolicyClicked: () -> Unit, onHelpClicked: () -> Unit ) { DropdownMenu( modifier = Modifier .background(color = KSTheme.colors.kds_support_100) .testTag(LoginDropdownTestTag.OPTIONS_MENU.name), expanded = expanded, onDismissRequest = { onDismissed.invoke() } ) { DropdownMenuItem( onClick = { onTermsOfUseClicked.invoke() onDismissed.invoke() } ) { Text( modifier = Modifier.testTag(LoginDropdownTestTag.OPTIONS_TERMS.name), text = stringResource(id = R.string.login_tout_help_sheet_terms), color = KSTheme.colors.kds_support_700 ) } DropdownMenuItem( onClick = { onPrivacyPolicyClicked.invoke() onDismissed.invoke() } ) { Text( modifier = Modifier.testTag(LoginDropdownTestTag.OPTIONS_PRIVACY_POLICY.name), text = stringResource(id = R.string.login_tout_help_sheet_privacy), color = KSTheme.colors.kds_support_700 ) } DropdownMenuItem( onClick = { onCookiePolicyClicked.invoke() onDismissed.invoke() } ) { Text( modifier = Modifier.testTag(LoginDropdownTestTag.OPTIONS_COOKIE.name), text = stringResource(id = R.string.login_tout_help_sheet_cookie), color = KSTheme.colors.kds_support_700 ) } DropdownMenuItem( onClick = { onHelpClicked.invoke() onDismissed.invoke() } ) { Text( modifier = Modifier.testTag(LoginDropdownTestTag.OPTIONS_HELP.name), text = stringResource(id = R.string.general_navigation_buttons_help), color = KSTheme.colors.kds_support_700 ) } } }
8
Kotlin
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
2,838
android-oss
Apache License 2.0
app/src/main/java/dev/olog/fortnightly/presentation/base/DataBoundViewHolder.kt
ologe
216,835,412
false
null
package dev.olog.fortnightly.presentation.base import android.view.View import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.recyclerview.widget.RecyclerView class DataBoundViewHolder(view: View) : RecyclerView.ViewHolder(view), LifecycleOwner { private val lifecycleRegistry = LifecycleRegistry(this) init { lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED } fun onAppear() { lifecycleRegistry.currentState = Lifecycle.State.CREATED lifecycleRegistry.currentState = Lifecycle.State.STARTED lifecycleRegistry.currentState = Lifecycle.State.RESUMED } fun onDisappear() { lifecycleRegistry.currentState = Lifecycle.State.STARTED lifecycleRegistry.currentState = Lifecycle.State.CREATED lifecycleRegistry.currentState = Lifecycle.State.DESTROYED } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } }
0
Kotlin
4
14
b29f0aa845ee41b81bc01661a9ca739c6e940cda
1,024
fortnightly
MIT License
app/src/main/java/com/telenav/osv/map/viewmodel/MapViewModelFactory.kt
kartaview
63,806,526
false
null
package com.telenav.osv.map.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.data.location.datasource.LocationLocalDataSource import com.telenav.osv.data.user.datasource.UserDataSource import com.telenav.osv.manager.network.GeometryRetriever import com.telenav.osv.map.render.mapbox.grid.loader.GridsLoader import com.telenav.osv.ui.fragment.camera.controls.viewmodel.RecordingViewModel class MapViewModelFactory(private val locationLocalDataSource: LocationLocalDataSource, private val userDataSource: UserDataSource, private val gridsLoader: GridsLoader, private val geometryRetriever: GeometryRetriever, private val applicationPreferences: ApplicationPreferences, private val recordingViewModel: RecordingViewModel) : ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return MapViewModel(locationLocalDataSource, userDataSource, gridsLoader, geometryRetriever, applicationPreferences, recordingViewModel) as T } }
76
Java
30
130
66eb0ee1ab093562e2867087084b26803fe58174
1,272
android
MIT License
react-query-kotlin/src/jsMain/kotlin/tanstack/query/core/resolveEnabled.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! @file:JsModule("@tanstack/query-core") package tanstack.query.core external fun <TQueryFnData, TError, TData, TQueryKey : QueryKey> resolveEnabled( enabled: Enabled<TQueryFnData, TError, TData, TQueryKey>?, query: Query<TQueryFnData, TError, TData, TQueryKey>, ): Boolean?
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
328
types-kotlin
Apache License 2.0
partiql-lang/src/main/kotlin/org/partiql/lang/eval/visitors/AggregateSupportVisitorTransform.kt
partiql
186,474,394
false
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at: * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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.partiql.lang.eval.visitors import com.amazon.ionelement.api.MetaContainer import com.amazon.ionelement.api.metaContainerOf import org.partiql.lang.ast.AggregateCallSiteListMeta import org.partiql.lang.ast.AggregateRegisterIdMeta import org.partiql.lang.domains.PartiqlAst /** * Allocates registerIds to all aggregate call-sites, storing the allocated registerId in an instance of * [AggregateRegisterIdMeta]. * * Also collects a list of all aggregate functions used in the `SELECT` of the current query (excluding subqueries) * and stores them in an instance of [AggregateCallSiteListMeta] on the [PartiqlAst.Expr.Select] instance. */ class AggregateSupportVisitorTransform : VisitorTransformBase() { private val aggregateCallSites = ArrayList<PartiqlAst.Expr.CallAgg>() /** * Nests another [AggregateSupportVisitorTransform] within this transform to avoid operating on * [aggregateCallSites] of a nested `SELECT`. */ override fun transformExprSelect(node: PartiqlAst.Expr.Select): PartiqlAst.Expr { return AggregateSupportVisitorTransform().transformExprSelectEvaluationOrder(node) } override fun transformExprCallAgg(node: PartiqlAst.Expr.CallAgg): PartiqlAst.Expr { val transformedCallAgg = PartiqlAst.build { callAgg_( setq = node.setq, funcName = node.funcName, arg = transformExpr(node.arg), metas = transformMetas(node.metas) + metaContainerOf(AggregateRegisterIdMeta.TAG to AggregateRegisterIdMeta(aggregateCallSites.size))) } aggregateCallSites.add(transformedCallAgg) return transformedCallAgg } /** * Applies a new instance of [AggregateSupportVisitorTransform] to [PartiqlAst.Projection.ProjectValue] nodes so * that a different instance of [aggregateCallSites] is used. */ override fun transformProjectionProjectValue_value(node: PartiqlAst.Projection.ProjectValue): PartiqlAst.Expr = AggregateSupportVisitorTransform().transformExpr(node.value) override fun transformExprSelect_metas(node: PartiqlAst.Expr.Select): MetaContainer = transformMetas(node.metas) + metaContainerOf(AggregateCallSiteListMeta.TAG to AggregateCallSiteListMeta(aggregateCallSites.toList())) }
311
null
60
539
ac6cdfff46ba5749d4fc850b1a30bf625034bfc9
2,893
partiql-lang-kotlin
Apache License 2.0
app/src/main/kotlin/com/coredocker/android/data/inject/Modules.kt
rolfwessels
256,949,423
false
null
package com.coredocker.android.data.inject import org.koin.dsl.module.module import java.util.Calendar val appModule = module { single { provideCalendar() } } private fun provideCalendar() = Calendar.getInstance()
0
Kotlin
0
0
7efd0255dcc6b3de93ea65428e3fcebd2538b016
221
coredocker-droid
MIT License
common/src/main/java/me/wcy/common/ext/ContextEx.kt
wangchenyan
625,252,978
false
null
package me.wcy.common.ext import android.app.Activity import android.content.Context import androidx.viewbinding.ViewBinding fun Activity?.setAlpha(alpha: Float) { if (this == null) { return } val lp = window.attributes lp.alpha = alpha window.attributes = lp } val ViewBinding.context: Context get() = root.context
0
Kotlin
0
3
f82e6a282e25dd26608320aee23f7c9124cd2d88
351
android-common
Apache License 2.0
fixed-point/src/main/kotlin/fixie/Mass.kt
knokko
865,591,691
false
{"Kotlin": 243384}
// Generated by fixie at 04-09-2024 16:25 package fixie import kotlin.math.min import kotlin.math.max import kotlin.math.abs @JvmInline value class Mass internal constructor(val value: Double) : Comparable<Mass> { fun toDouble(unit: MassUnit) = when (unit) { MassUnit.MILLIGRAM -> value * 1000000.0 MassUnit.GRAM -> value * 1000.0 MassUnit.OUNCE -> value * 35.27396194958041 MassUnit.POUND -> value * 2.2046226218487757 MassUnit.KILOGRAM -> value MassUnit.TON -> value * 0.001 } fun toString(unit: MassUnit) = String.format("%.3f%s", toDouble(unit), unit.abbreviation) override fun toString() = toString(MassUnit.KILOGRAM) override operator fun compareTo(other: Mass) = this.value.compareTo(other.value) operator fun unaryMinus() = Mass(-value) operator fun plus(right: Mass) = Mass(this.value + right.value) operator fun minus(right: Mass) = Mass(this.value - right.value) operator fun div(right: Mass) = this.value / right.value operator fun times(right: Int) = Mass(this.value * right) operator fun div(right: Int) = Mass(this.value / right) operator fun times(right: Long) = Mass(this.value * right) operator fun div(right: Long) = Mass(this.value / right) operator fun times(right: Float) = Mass(this.value * right) operator fun div(right: Float) = Mass(this.value / right) operator fun times(right: Double) = Mass(this.value * right) operator fun div(right: Double) = Mass(this.value / right) operator fun div(right: Density) = Volume.LITER * value / right.toDouble() operator fun div(right: Volume) = Density.KGPL * value / right.toDouble(VolumeUnit.LITER) operator fun times(right: Speed) = Momentum.NEWTON_SECOND * value * right.toDouble(SpeedUnit.METERS_PER_SECOND) companion object { fun raw(value: Double) = Mass(value) val MILLIGRAM = Mass(1.0E-6) val GRAM = Mass(0.001) val OUNCE = Mass(0.028349523125) val POUND = Mass(0.45359237) val KILOGRAM = Mass(1.0) val TON = Mass(1000.0) } } operator fun Int.times(right: Mass) = right * this val Int.mg get() = Mass.MILLIGRAM * this val Int.g get() = Mass.GRAM * this val Int.oz get() = Mass.OUNCE * this val Int.lbs get() = Mass.POUND * this val Int.kg get() = Mass.KILOGRAM * this val Int.t get() = Mass.TON * this operator fun Long.times(right: Mass) = right * this val Long.mg get() = Mass.MILLIGRAM * this val Long.g get() = Mass.GRAM * this val Long.oz get() = Mass.OUNCE * this val Long.lbs get() = Mass.POUND * this val Long.kg get() = Mass.KILOGRAM * this val Long.t get() = Mass.TON * this operator fun Float.times(right: Mass) = right * this val Float.mg get() = Mass.MILLIGRAM * this val Float.g get() = Mass.GRAM * this val Float.oz get() = Mass.OUNCE * this val Float.lbs get() = Mass.POUND * this val Float.kg get() = Mass.KILOGRAM * this val Float.t get() = Mass.TON * this operator fun Double.times(right: Mass) = right * this val Double.mg get() = Mass.MILLIGRAM * this val Double.g get() = Mass.GRAM * this val Double.oz get() = Mass.OUNCE * this val Double.lbs get() = Mass.POUND * this val Double.kg get() = Mass.KILOGRAM * this val Double.t get() = Mass.TON * this fun abs(x: Mass) = Mass(abs(x.value)) fun min(a: Mass, b: Mass) = Mass(min(a.value, b.value)) fun max(a: Mass, b: Mass) = Mass(max(a.value, b.value))
0
Kotlin
0
0
f193e50f0a384a2d792d7bcb195aa5d1ca183fb9
3,321
balls2d
MIT License
src/main/kotlin/org/veupathdb/vdi/lib/common/async/ShutdownSignal.kt
VEuPathDB
619,968,031
false
{"Kotlin": 610256, "Java": 211932, "RAML": 89266, "Makefile": 2225, "Dockerfile": 994, "Shell": 428}
package org.veupathdb.vdi.lib.common.async import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.channels.Channel class ShutdownSignal { private val channel = Channel<Unit>(1, BufferOverflow.DROP_OLDEST) @Volatile private var triggered = false suspend fun trigger() { channel.send(Unit) } @OptIn(ExperimentalCoroutinesApi::class) suspend fun isTriggered(): Boolean { return if (triggered) true else if (channel.isEmpty) false else { await() true } } suspend fun await() { channel.receive() triggered = true } }
25
Kotlin
0
0
fec065ed6b7a9f81c16e7738df0d4296fda1ad43
662
vdi-service
Apache License 2.0
src/main/kotlin/org/veupathdb/vdi/lib/common/async/ShutdownSignal.kt
VEuPathDB
619,968,031
false
{"Kotlin": 610256, "Java": 211932, "RAML": 89266, "Makefile": 2225, "Dockerfile": 994, "Shell": 428}
package org.veupathdb.vdi.lib.common.async import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.channels.Channel class ShutdownSignal { private val channel = Channel<Unit>(1, BufferOverflow.DROP_OLDEST) @Volatile private var triggered = false suspend fun trigger() { channel.send(Unit) } @OptIn(ExperimentalCoroutinesApi::class) suspend fun isTriggered(): Boolean { return if (triggered) true else if (channel.isEmpty) false else { await() true } } suspend fun await() { channel.receive() triggered = true } }
25
Kotlin
0
0
fec065ed6b7a9f81c16e7738df0d4296fda1ad43
662
vdi-service
Apache License 2.0
app/shared/keybox/public/src/commonMain/kotlin/build/wallet/keybox/wallet/AppSpendingWalletProvider.kt
proto-at-block
761,306,853
false
{"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.keybox.wallet import build.wallet.bitcoin.wallet.SpendingWallet import build.wallet.bitkey.spending.SpendingKeyset import com.github.michaelbull.result.Result /** * Provides [SpendingWallet] for app. */ interface AppSpendingWalletProvider { /** * Creates [SpendingWallet] instance for the given [keyset]. * * Requires app private key for the keyset to be present in the app keystore, otherwise an error * is returned. * * Warn: If you need to a [SpendingWallet] for an active account, do not use [getSpendingWallet]. * Instead, use [TransactionsService.spendingWallet]. The service is responsible for creating * and caching a [SpendingWallet] for the active account. */ suspend fun getSpendingWallet(keyset: SpendingKeyset): Result<SpendingWallet, Throwable> }
3
C
16
113
694c152387c1fdb2b6be01ba35e0a9c092a81879
817
bitkey
MIT License
lib/src/main/java/com/github/carousels/callback/OnCarouselsPageLongClickListener.kt
jhwsx
295,915,363
false
null
package com.github.carousels.callback /** * Carousels 页面常按点击监听器 * * @author wangzhichao * @date 2020-9-23 */ interface OnCarouselsPageLongClickListener { fun onCarouselsPageLongClicked(position: Int): Boolean }
1
null
1
1
2b1e42ef86ce142986c2ef0995f9df8d40b348e7
220
Carousels
Apache License 2.0
app/src/main/java/yoga/coder/infinijoke/ui/Presenter.kt
peternagy1332
178,799,770
false
null
package yoga.coder.infinijoke.ui abstract class Presenter<S> { protected var screen: S? = null open fun attachScreen(screen: S) { this.screen = screen } open fun detachScreen() { this.screen = null } }
0
Kotlin
0
0
ce744ef43cd4de169333ae220edb2f2ba301a289
240
infinijoke
Creative Commons Attribution 3.0 Unported
plugin/src/org/jetbrains/cabal/psi/RepoType.kt
Atsky
12,811,746
false
null
package org.jetbrains.cabal.psi import com.intellij.lang.ASTNode import com.intellij.extapi.psi.ASTWrapperPsiElement import org.jetbrains.cabal.parser.* import org.jetbrains.cabal.psi.PropertyValue class RepoType(node: ASTNode) : PropertyValue(node), RangedValue { override fun getAvailableValues(): List<String> { return REPO_TYPE_VALS } }
47
null
22
205
a9be4e8c41202cba50f6f9aa72eb912f1fa92b8c
359
haskell-idea-plugin
Apache License 2.0
app/src/main/java/com/example/test_ci_cd/MainActivity.kt
JoshBogin
775,663,807
false
{"Kotlin": 7280}
package com.example.test_ci_cd import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import com.example.test_ci_cd.ui.theme.TestCICDTheme class MainActivity : ComponentActivity() { private val viewModel: MainViewModel = MainViewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TestCICDTheme { val greeting = viewModel.getGreeting(stringResource(id = R.string.hello_world)) // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting(greeting) } } } } } @Composable fun Greeting( greeting: String, modifier: Modifier = Modifier ) { Box( contentAlignment = Alignment.Center, modifier = modifier.fillMaxSize() ) { Text( text = greeting, fontSize = 48.sp, fontWeight = FontWeight.Bold, ) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { TestCICDTheme { Greeting("Hello, World!") } }
0
Kotlin
0
0
352e7508150d222b6745eefaf4c2a457ebed7bcd
1,863
CI-CD-Test-Repo
MIT License
android_okmock/samples/app/src/main/java/nolambda/gadb/okmock/sample/GreetServer.kt
esafirm
294,098,158
false
null
package nolambda.gadb.okmock.sample import nolambda.gadb.okmock.server.Const import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintWriter import java.net.ServerSocket import java.net.Socket class GreetServer { private lateinit var serverSocket: ServerSocket private lateinit var clientSocket: Socket private var writer: PrintWriter? = null private var reader: BufferedReader? = null fun start(port: Int) { serverSocket = ServerSocket(port) clientSocket = serverSocket.accept() writer = PrintWriter(clientSocket.getOutputStream(), true) // reader = BufferedReader(InputStreamReader(clientSocket.getInputStream())) val greeting = "A" // val greeting = reader?.readLine() // println("Receive greeting: $greeting") while (true) { if (greeting == "halo") { writer?.println("hello client") } else { writer?.println("unrecognised greeting") } } } fun stop() { reader?.close() writer?.close() clientSocket.close() serverSocket.close() } companion object { @JvmStatic fun main(args: Array<String>) { val server = GreetServer() server.start(Const.DEFAULT_PORT) } } } class GreetClient { private var clientSocket: Socket? = null private var out: PrintWriter? = null private var reader: BufferedReader? = null fun startConnection(ip: String?, port: Int) { clientSocket = Socket(ip, port) out = PrintWriter(clientSocket!!.getOutputStream(), true) reader = BufferedReader(InputStreamReader(clientSocket!!.getInputStream())) } fun sendMessage(msg: String?): String { out!!.println(msg) return reader!!.readLine() } fun stopConnection() { reader!!.close() out!!.close() clientSocket!!.close() } companion object { @JvmStatic fun main(args: Array<String>) { val client = GreetClient() client.startConnection("localhost", Const.DEFAULT_PORT) println("Connected! Sending message …") val response = client.sendMessage("halo") println("Got response: $response") } } }
2
Kotlin
0
16
2f893b96f9156c29b8beb69425744ee3c28a4935
2,337
okmock
MIT License
runtime/src/jsMain/kotlin/space/jetbrains/api/runtime/stacktrace/RequestStacktraceJs.kt
JetBrains
239,972,147
false
null
package space.jetbrains.api.runtime.stacktrace public actual fun rethrow(cause: Exception, stackTraceInfo: StackTraceInfo): Nothing { throw cause }
2
Kotlin
2
43
c928e2e0d21d302ebc4a5d191a1a6cf50f7d31f0
153
space-kotlin-sdk
Apache License 2.0
app/src/main/java/com/zmj/relearnandroid/view/lesson13textmeasure/SportView.kt
ZmjDns
353,241,624
false
null
package com.zmj.relearnandroid.view.lesson13textmeasure import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import androidx.core.content.res.ResourcesCompat import com.zmj.relearnandroid.R import com.zmj.relearnandroid.view.dp /** * Author : Zmj * Blog : https://blog.csdn.net/Zmj_Dns * GitHub : https://github.com/ZmjDns * Time : 2021-04-10 * Description : */ class SportView(context: Context,attrs: AttributeSet): View(context, attrs) { private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textSize = 100.dp typeface = ResourcesCompat.getFont(context, R.font.font) textAlign = Paint.Align.CENTER } private val BG_COLOR = Color.GRAY private val DONE_COLOR =Color.parseColor("#FF4081") private val STROKE_WIDTH = 14.dp private val RADIUS = 140.dp private var text = "abab" private var textBounds = Rect() private val fontMetrics = Paint.FontMetrics() override fun onDraw(canvas: Canvas) { paint.strokeWidth = STROKE_WIDTH paint.style = Paint.Style.STROKE paint.strokeCap = Paint.Cap.ROUND //绘制背景环 paint.color = BG_COLOR canvas.drawCircle(width/2f, height/2f, RADIUS, paint) //绘制进度条 paint.color = DONE_COLOR canvas.drawArc(width/2-RADIUS,height/2-RADIUS,width/2+RADIUS,height/2+RADIUS,-100f,200f,false,paint) //绘制文字 paint.textSize = 100.dp paint.textAlign = Paint.Align.CENTER paint.style = Paint.Style.FILL // paint.getTextBounds(text,0,text.length,textBounds) //适合金静态文字 // canvas.drawText(text,width/2f,height/2f - (textBounds.top + textBounds.bottom)/2f,paint) paint.getFontMetrics(fontMetrics) //适合动态文字 canvas.drawText(text,width/2f,height/2f - (fontMetrics.ascent + fontMetrics.descent)/2f, paint) //文字的贴边1 paint.textSize = 100.dp paint.textAlign = Paint.Align.LEFT // paint.getFontMetrics(fontMetrics) paint.getTextBounds(text,0,text.length,textBounds) canvas.drawText(text,0f-textBounds.left,0f - textBounds.top,paint) //文字的贴边2 paint.textSize = 15.dp paint.textAlign = Paint.Align.LEFT // paint.getFontMetrics(fontMetrics) paint.getTextBounds(text,0,text.length,textBounds) canvas.drawText(text,0f-textBounds.left,0f - textBounds.top,paint) } }
0
Kotlin
0
0
e4d008d3d23bb5b68b954679ab8d8c86ebfe4890
2,434
relearnandroid
Apache License 2.0
src/test/java/uk/gov/justice/digital/hmpps/cmd/api/model/NotificationTest.kt
nickmcmahon01
310,653,680
false
null
package uk.gov.justice.digital.hmpps.cmd.api.model import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import uk.gov.justice.digital.hmpps.cmd.api.client.CsrModifiedDetailDto import uk.gov.justice.digital.hmpps.cmd.api.domain.DetailModificationType import uk.gov.justice.digital.hmpps.cmd.api.domain.ShiftType import java.time.LocalDate class NotificationTest { @Test fun `Should return a valid shift notification`() { val shiftDate = LocalDate.now() val quantumId = "XYZ" val shiftModified = shiftDate.plusDays(3).atStartOfDay().minusDays(3) val taskStart = shiftDate.atStartOfDay().plusSeconds(123L) val taskEnd = shiftDate.atStartOfDay().plusSeconds(456L) val task = "Any Activity" val shiftType = ShiftType.SHIFT val actionType = DetailModificationType.ADD val processed = false val notification = Notification( 1L, quantumId, shiftModified, taskStart, taskEnd, task, shiftType, actionType, processed, ) Assertions.assertThat(notification.quantumId).isEqualTo(quantumId) Assertions.assertThat(notification.shiftModified).isEqualTo(shiftModified) Assertions.assertThat(notification.detailStart).isEqualTo(taskStart) Assertions.assertThat(notification.detailEnd).isEqualTo(taskEnd) Assertions.assertThat(notification.activity).isEqualTo(task) Assertions.assertThat(notification.parentType).isEqualTo(shiftType) Assertions.assertThat(notification.actionType).isEqualTo(actionType) Assertions.assertThat(notification.processed).isEqualTo(processed) } @Test fun `Can convert from DTO`() { val shiftDate = LocalDate.now() val quantumId = "XYZ" val shiftModified = shiftDate.plusDays(3).atStartOfDay().minusDays(3) val taskStart = shiftDate.atStartOfDay().plusSeconds(123L) val taskEnd = shiftDate.atStartOfDay().plusSeconds(456L) val task = "Any Activity" val shiftType = ShiftType.SHIFT val actionType = DetailModificationType.ADD val processed = false val shiftNotificationDto = CsrModifiedDetailDto( null, quantumId, shiftModified, shiftType, taskStart, taskEnd, task, actionType, ) val shiftNotification = Notification.fromDto(shiftNotificationDto) Assertions.assertThat(shiftNotification.quantumId).isEqualTo(quantumId) Assertions.assertThat(shiftNotification.shiftModified).isEqualTo(shiftModified) Assertions.assertThat(shiftNotification.detailStart).isEqualTo(taskStart) Assertions.assertThat(shiftNotification.detailEnd).isEqualTo(taskEnd) Assertions.assertThat(shiftNotification.activity).isEqualTo(task) Assertions.assertThat(shiftNotification.parentType).isEqualTo(shiftType) Assertions.assertThat(shiftNotification.actionType).isEqualTo(actionType) Assertions.assertThat(shiftNotification.processed).isEqualTo(processed) } @Test fun `Can convert a collection from DTO`() { val shiftDate = LocalDate.now() val quantumId = "XYZ" val shiftModified = shiftDate.plusDays(3).atStartOfDay().minusDays(3) val taskStart = shiftDate.atStartOfDay().plusSeconds(123L) val taskEnd = shiftDate.atStartOfDay().plusSeconds(456L) val task = "Any Activity" val shiftType = ShiftType.SHIFT val actionType = DetailModificationType.ADD val processed = false val shiftNotificationDto = CsrModifiedDetailDto( null, quantumId, shiftModified, shiftType, taskStart, taskEnd, task, actionType, ) val lisfOfDtos = listOf(shiftNotificationDto) val shiftNotifications = Notification.fromDto(lisfOfDtos) val shiftNotification = shiftNotifications.elementAt(0) Assertions.assertThat(shiftNotification.quantumId).isEqualTo(quantumId) Assertions.assertThat(shiftNotification.shiftModified).isEqualTo(shiftModified) Assertions.assertThat(shiftNotification.detailStart).isEqualTo(taskStart) Assertions.assertThat(shiftNotification.detailEnd).isEqualTo(taskEnd) Assertions.assertThat(shiftNotification.activity).isEqualTo(task) Assertions.assertThat(shiftNotification.parentType).isEqualTo(shiftType) Assertions.assertThat(shiftNotification.actionType).isEqualTo(actionType) Assertions.assertThat(shiftNotification.processed).isEqualTo(processed) } }
1
Kotlin
2
0
bab214869d0d9fb171d5dd4bf3356bc1dba9cb19
4,375
cmd-api
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/app/database/jpa/JpaActionPlanPersistenceAdapterTest.kt
ministryofjustice
653,598,082
false
{"Kotlin": 1214907, "Mustache": 2705, "Dockerfile": 1375}
package uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.any import org.mockito.kotlin.given import org.mockito.kotlin.verify import uk.gov.justice.digital.hmpps.educationandworkplanapi.aValidPrisonNumber import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.entity.ActionPlanEntity import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.entity.aValidActionPlanEntity import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.entity.aValidActionPlanSummaryProjection import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.mapper.ActionPlanEntityMapper import uk.gov.justice.digital.hmpps.educationandworkplanapi.app.database.jpa.repository.ActionPlanRepository import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.goal.aValidActionPlan import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.goal.aValidActionPlanSummary import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.goal.dto.aValidCreateActionPlanDto @ExtendWith(MockitoExtension::class) class JpaActionPlanPersistenceAdapterTest { @InjectMocks private lateinit var persistenceAdapter: JpaActionPlanPersistenceAdapter @Mock private lateinit var actionPlanRepository: ActionPlanRepository @Mock private lateinit var actionPlanMapper: ActionPlanEntityMapper @Test fun `should save Action Plan`() { // Given val prisonNumber = aValidPrisonNumber() val actionPlanDomain = aValidActionPlan(prisonNumber = prisonNumber) val actionPlanEntity = aValidActionPlanEntity(prisonNumber = prisonNumber) given(actionPlanMapper.fromDtoToEntity(any())).willReturn(actionPlanEntity) given(actionPlanRepository.save(any<ActionPlanEntity>())).willReturn(actionPlanEntity) given(actionPlanMapper.fromEntityToDomain(any())).willReturn(actionPlanDomain) val createActionPlanDto = aValidCreateActionPlanDto(prisonNumber = prisonNumber) // When val actual = persistenceAdapter.createActionPlan(createActionPlanDto) // Then assertThat(actual).isEqualTo(actionPlanDomain) verify(actionPlanRepository).save(actionPlanEntity) verify(actionPlanMapper).fromDtoToEntity(createActionPlanDto) verify(actionPlanMapper).fromEntityToDomain(actionPlanEntity) } @Test fun `should retrieve Action Plan`() { // Given val prisonNumber = aValidPrisonNumber() val actionPlanEntity = aValidActionPlanEntity(prisonNumber = prisonNumber) val expectedActionPlanDomain = aValidActionPlan(prisonNumber = prisonNumber) given(actionPlanRepository.findByPrisonNumber(any())).willReturn(actionPlanEntity) given(actionPlanMapper.fromEntityToDomain(any())).willReturn(expectedActionPlanDomain) // When val actual = persistenceAdapter.getActionPlan(prisonNumber) // Then assertThat(actual).isEqualTo(expectedActionPlanDomain) verify(actionPlanRepository).findByPrisonNumber(prisonNumber) verify(actionPlanMapper).fromEntityToDomain(actionPlanEntity) } @Test fun `should retrieve Action Plan Summaries`() { // Given val prisonNumber = aValidPrisonNumber() val prisonNumbers = listOf(prisonNumber) val actionPlanSummaryProjections = listOf(aValidActionPlanSummaryProjection(prisonNumber = prisonNumber)) val expectedActionPlanSummaries = listOf(aValidActionPlanSummary(prisonNumber = prisonNumber)) given(actionPlanRepository.findByPrisonNumberIn(any())).willReturn(actionPlanSummaryProjections) given(actionPlanMapper.fromEntitySummariesToDomainSummaries(any())).willReturn(expectedActionPlanSummaries) // When val actual = persistenceAdapter.getActionPlanSummaries(prisonNumbers) // Then assertThat(actual).isEqualTo(expectedActionPlanSummaries) verify(actionPlanRepository).findByPrisonNumberIn(prisonNumbers) verify(actionPlanMapper).fromEntitySummariesToDomainSummaries(actionPlanSummaryProjections) } }
5
Kotlin
0
2
95ca727cfdde32bc66348dc697440952751deee0
4,224
hmpps-education-and-work-plan-api
MIT License
app/src/main/java/com/kvl/cyclotrack/TripDetailsUtilities.kt
kevinvanleer
311,970,003
false
null
package com.kvl.cyclotrack import android.graphics.Color import android.location.Location import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.AxisBase import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.formatter.ValueFormatter import com.google.android.gms.maps.model.LatLng import com.kvl.cyclotrack.data.CadenceSpeedMeasurement import com.kvl.cyclotrack.data.HeartRateMeasurement import kotlin.math.roundToInt fun configureLineChart(chart: LineChart, yMin: Float = 0f) { chart.setTouchEnabled(false) chart.setDrawBorders(true) chart.setBorderColor(Color.GRAY) chart.setNoDataText("Looking for data...") chart.legend.isEnabled = false chart.setDrawGridBackground(false) chart.xAxis.setDrawLabels(true) chart.xAxis.axisMinimum = 0f chart.xAxis.setDrawGridLines(true) chart.xAxis.textColor = Color.WHITE chart.xAxis.position = XAxis.XAxisPosition.BOTTOM chart.xAxis.valueFormatter = object : ValueFormatter() { override fun getAxisLabel(value: Float, axis: AxisBase?): String { return if (value == 0f) "" else formatDuration(value.toDouble()) } } chart.axisLeft.setDrawLabels(true) chart.axisLeft.textColor = Color.WHITE chart.axisLeft.axisMinimum = yMin chart.axisLeft.setDrawGridLines(true) chart.axisRight.setDrawLabels(true) chart.axisRight.textColor = Color.WHITE chart.axisRight.axisMinimum = yMin chart.axisRight.setDrawGridLines(false) } fun getElevationChange(measurements: Array<Measurements>): Pair<Double, Double> = accumulateAscentDescent(measurements.map { Pair( it.altitude, it.verticalAccuracyMeters.toDouble() ) }) fun getAverageSpeedRpm(measurements: Array<CadenceSpeedMeasurement>): Float? { return try { val totalRevs = measurements.lastOrNull()?.revolutions?.let { getDifferenceRollover( it, measurements.first().revolutions ) } val duration = (measurements.last().timestamp - measurements.first().timestamp) / 1000 / 60 totalRevs?.toFloat()?.div(duration).takeIf { it?.isFinite() ?: false } } catch (e: Exception) { null } } fun getRotation(start: LatLng, end: LatLng): Float { val results = FloatArray(2) Location.distanceBetween( start.latitude, start.longitude, end.latitude, end.longitude, results ) return results[1] } fun getAverageHeartRate(measurements: Array<HeartRateMeasurement>): Short? { var sum = 0f var count = 0 measurements.forEach { sum += it.heartRate ++count } return if (count == 0) { null } else { (sum / count).roundToInt().toShort() } }
0
Kotlin
0
7
e62bbb39eec10d2f3c327c024f1462e3a6736987
2,873
cyclotrack
The Unlicense
app/src/main/java/hu/csabapap/seriesreminder/utils/PicassoTransformation.kt
csabapap
112,928,453
false
null
package hu.csabapap.seriesreminder.utils import android.graphics.* import com.squareup.picasso.Transformation class RoundedTransformation(private val radius: Float? = null, private val margin: Float = 0f) : Transformation { override fun transform(source: Bitmap): Bitmap { val paint = Paint().apply { isAntiAlias = true shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) } val output = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888) Canvas(output).drawRoundRect(margin, margin, source.width - margin, source.height - margin, radius ?: source.width.toFloat() / 2, radius ?: source.height.toFloat() / 2, paint) if (source != output) { source.recycle() } return output } override fun key(): String { return "rounded(radius=$radius, margin=$margin)" } }
0
null
0
1
5e63b26f5ec8a1cf8d19f40f44fcb8a39325f34d
953
SeriesReminder
MIT License
src/main/kotlin/io/slama/core/commands.kt
eKonis-src
467,679,930
true
{"Kotlin": 83429}
package io.slama.core import io.slama.utils.command import io.slama.utils.invoke import io.slama.utils.option import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.interactions.commands.Command import net.dv8tion.jda.api.interactions.commands.OptionType fun JDA.registerGlobalCommands() { this { command("eval", "Évaluer une expression mathématique.") { option(OptionType.STRING, name = "expression", "Expression à évaluer.") } command("call", "Lancer un appel dans le salon courant.") { option(OptionType.INTEGER, name = "timeout", "Temps imparti pour répondre à l'appel en minutes.") option(OptionType.ROLE, name = "role", "Groupe d'étudiants visé.") } command("poll", "Lancer un sondage dans le salon courant.") { option(OptionType.STRING, name = "question", "Question sur laquelle porte le sondage.", required = true) option( OptionType.BOOLEAN, name = "log", "Sauvegarde un fichier log du résultat du sondage. (Défaut = false)" ) option( OptionType.INTEGER, name = "timeout", "Temps imparti pour répondre au sondage en minutes. (Défaut = 2 minutes)" ) option(OptionType.STRING, name = "a", "Première réponse possible.") option(OptionType.STRING, name = "b", "Seconde réponse possible.") option(OptionType.STRING, name = "c", "Troisième réponse possible.") option(OptionType.STRING, name = "d", "Quatrième réponse possible.") } command("changen", "Lier un salon à un générateur de salons temporaires.") { option(OptionType.CHANNEL, name = "channel", "Salon qui servira de point de départ.", required = true) } command("table", "Générer un tableau en caractères ASCII.") { option(OptionType.STRING, name = "content", "Contenu du tableau. Laisser vide pour obtenir un example.") } } } fun Guild.registerGuildCommands() { this { command("autorole", "Créer un attributeur automatique de rôle.") { option(OptionType.STRING, name = "name", "Nom de l'attributeur.") { BotConfiguration.guilds[this@registerGuildCommands.idLong]?.let { it.autoRoles.keys.map { name -> Command.Choice(name, name) } } ?: listOf() } } } }
0
Kotlin
0
0
a0b293f20f175f36035778dba6f3eeb70946727d
2,559
UGE-Bot-1
MIT License
src/Day02.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
const val SCORE_WIN = 6 const val SCORE_DRAW = 3 val selectScore = listOf(1, 2, 3) fun Char.toIntNum() = when (this) { in "AX" -> 0 in "BY" -> 1 else -> 2 } fun getScore(a: Int, b: Int): Int { val matchScore = when { a == b -> SCORE_DRAW a + 1 == b || (a == 2 && b == 0) -> SCORE_WIN else -> 0 } return matchScore + selectScore[b] } fun part1(input: List<String>): Int { return input.sumOf { getScore(it[0].toIntNum(), it[2].toIntNum()) } } fun part2(input: List<String>): Int { return input.sumOf { val a = it[0].toIntNum() val b = when (it[2]) { 'X' -> (3 + a - 1) % 3 'Y' -> a else -> (a + 1) % 3 } getScore(a, b) } } fun main() { println(part1(readInput("Day02_test"))) println(part1(readInput("Day02_part1"))) println(part2(readInput("Day02_test"))) println(part2(readInput("Day02_part1"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
879
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
const val SCORE_WIN = 6 const val SCORE_DRAW = 3 val selectScore = listOf(1, 2, 3) fun Char.toIntNum() = when (this) { in "AX" -> 0 in "BY" -> 1 else -> 2 } fun getScore(a: Int, b: Int): Int { val matchScore = when { a == b -> SCORE_DRAW a + 1 == b || (a == 2 && b == 0) -> SCORE_WIN else -> 0 } return matchScore + selectScore[b] } fun part1(input: List<String>): Int { return input.sumOf { getScore(it[0].toIntNum(), it[2].toIntNum()) } } fun part2(input: List<String>): Int { return input.sumOf { val a = it[0].toIntNum() val b = when (it[2]) { 'X' -> (3 + a - 1) % 3 'Y' -> a else -> (a + 1) % 3 } getScore(a, b) } } fun main() { println(part1(readInput("Day02_test"))) println(part1(readInput("Day02_part1"))) println(part2(readInput("Day02_test"))) println(part2(readInput("Day02_part1"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
879
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/theoparis/cw/entity/util/IExplosiveEntity.kt
theoparis
484,579,728
false
null
package com.theoparis.cw.entity.util interface IExplosiveEntity { /** * Explosion fuse in ticks */ var fuseTime: Int var fuseSpeed: Int fun ignite() }
4
Kotlin
0
0
7fa941855f7a99c18a361a1e3c92ab0c09cfbf94
178
cursed-insanity-mod
MIT License
app/src/main/java/com/padc/ecommerce/views/items/ProductDetailsViewItem.kt
thihaphyo
183,603,029
false
null
package com.padc.ecommerce.views.items import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import com.bumptech.glide.Glide import com.padc.ecommerce.data.vos.ProductImageVO import kotlinx.android.synthetic.main.view_item_product.view.* class ProductDetailsViewItem : FrameLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun setData(data: ProductImageVO) { Glide.with(context) .load(data.imageUrl) .into(ivProduct) } override fun onFinishInflate() { super.onFinishInflate() } }
1
null
1
1
18e730e1d342f63bf1bd404ed989643ba96dedfe
792
ECommerce
MIT License
app/src/main/java/vn/loitp/app/activity/customviews/viewpager/refreshviewpager/RefreshViewPagerActivity.kt
tplloi
126,578,283
false
null
package vn.loitp.app.activity.customviews.viewpager.refreshviewpager import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import com.annotation.IsFullScreen import com.annotation.LogTag import com.core.base.BaseFontActivity import com.core.common.Constants import com.core.utilities.LUIUtil import kotlinx.android.synthetic.main.activity_viewpager_refresh.* import vn.loitp.app.R @LogTag("RefreshViewPagerActivity") @IsFullScreen(false) class RefreshViewPagerActivity : BaseFontActivity() { override fun setLayoutResourceId(): Int { return R.layout.activity_viewpager_refresh } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) vp.adapter = SamplePagerAdapter(supportFragmentManager) LUIUtil.setPullLikeIOSHorizontal(vp) tabLayout.setupWithViewPager(vp) LUIUtil.changeTabsFont(tabLayout, Constants.FONT_PATH) } @Suppress("DEPRECATION") private inner class SamplePagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_SET_USER_VISIBLE_HINT) { override fun getItem(position: Int): Fragment { val frmRefresh = FrmRefresh() val bundle = Bundle() bundle.putInt(FrmRefresh.KEY_POSITION, position) frmRefresh.arguments = bundle return frmRefresh } override fun getCount(): Int { return 5 } override fun getPageTitle(position: Int): CharSequence { return "Page Title $position" } } }
0
Kotlin
0
6
55fb45b20a95b924d74f364ecad5101235eba7b8
1,668
basemaster
Apache License 2.0
app/src/main/java/com/flaquir4/codetest/presentation/main/MainView.kt
flaquir4
280,842,506
false
null
package com.flaquir4.codetest.presentation.main interface MainView { fun navigateToLoginScreen() fun showLogoutError() }
0
Kotlin
0
1
0be17adc9a7a9c67aad2f8e0ccf19431185b466e
131
BorjaGonzalezCodeTest
Apache License 2.0
core/testing/src/main/java/com/hisui/kanna/core/testing/repository/TestBookRepository.kt
okumusashi
570,818,154
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hisui.kanna.core.testing.repository import com.hisui.kanna.core.data.repository.BookRepository import com.hisui.kanna.core.model.Author import com.hisui.kanna.core.model.Book import com.hisui.kanna.core.model.BookSorter import com.hisui.kanna.core.model.NewBook import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update class TestBookRepository : BookRepository { private val books = MutableStateFlow<Map<Long, Book>>(emptyMap()) override suspend fun save(book: NewBook): Result<Unit> { val newBook = Book( id = books.firstOrNull()?.keys?.maxOrNull()?.plus(1) ?: 1, title = book.title, readDate = book.readDate, thought = book.thought, memo = book.memo ?: "", rating = book.rating, author = Author(id = book.authorId, name = book.authorId, memo = null, isFavourite = false), genre = book.genreId ) updateBook(book = newBook) return Result.success(Unit) } override fun getAllStream(sort: BookSorter, isAsc: Boolean): Flow<List<Book>> = books.map { map -> map.values.toList().let { books -> when (sort) { BookSorter.READ_DATE -> if (isAsc) books.sortedBy { it.readDate } else books.sortedByDescending { it.readDate } BookSorter.TITLE -> if (isAsc) books.sortedBy { it.title } else books.sortedByDescending { it.title } else -> books } } } override fun countStream(): Flow<Int> = books.map { it.size } override fun getStream(id: Long): Flow<Book?> = books.map { books -> books.getOrDefault(id, null) } override fun getListStreamByQuery(q: String): Flow<List<Book>> = books.map { books -> books .filterValues { it.title.contains(q) } .values .toList() } override suspend fun update(book: Book): Result<Unit> { updateBook(book = book) return Result.success(Unit) } private fun updateBook(book: Book) { books.update { it.toMutableMap().apply { this[book.id] = book }.toMap() } } }
17
Kotlin
0
0
2cc6ff428680d0d2d4f56be5db2f5b57d92648ec
3,108
kanna
Apache License 2.0
src/commonMain/kotlin/com/dxc/ssi/agent/model/PeerConnection.kt
dxc-technology
259,322,339
false
{"Kotlin": 598967, "Objective-C": 537589, "Objective-C++": 442889, "C": 238203, "Ruby": 12614, "Shell": 7187, "Swift": 1114}
package com.dxc.ssi.agent.model import com.dxc.ssi.agent.utils.UrlSerializer import io.ktor.http.* import kotlinx.serialization.Serializable //TODO: replace String state with some proper enum or reuse DIDExchangeState //TODO: see if UUID type can be used instead of String for id @Serializable data class PeerConnection( val id: String, val state: PeerConnectionState, val invitation: String, val isSelfInitiated: Boolean, val peerRecipientKeys: List<String>, val peerVerkey: String? = null, val peerDid: String? = null, @Serializable(with = UrlSerializer::class) val endpoint: Url, val keepTransportAlive: Boolean, val transportState: ConnectionTransportState )
3
Kotlin
6
5
9bede83e0358b16d6dc9459ccc2fd85541027b6c
709
ssi-mobile-sdk
Apache License 2.0
app/src/main/java/com/example/towntrekker/pagini/main/vizualizare_urmareste_urmaritori_recyclerview/VizualizareUrmaresteUrmaritoriAdapter.kt
Silviu1409
608,188,637
false
null
package com.example.towntrekker.pagini.main.vizualizare_urmareste_urmaritori_recyclerview import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.towntrekker.ActivityMain import com.example.towntrekker.R import com.example.towntrekker.pagini.main.VizualizareDetaliiUser class VizualizareUrmaresteUrmaritoriAdapter(context: Context?, private val lista_useri: List<String>) : RecyclerView.Adapter<VizualizareUrmaresteUrmaritoriViewHolder>(){ private val mainActivityContext = (context as ActivityMain) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VizualizareUrmaresteUrmaritoriViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.urmareste_urmaritori_user, parent, false) return VizualizareUrmaresteUrmaritoriViewHolder(view) } override fun onBindViewHolder(holder: VizualizareUrmaresteUrmaritoriViewHolder, position: Int) { val userRef = lista_useri[position] mainActivityContext.getDB().collection("useri").document(userRef).get() .addOnSuccessListener { doc -> holder.numeUser.text = doc.getString("alias") ?: "" val userIconRef = mainActivityContext.getStorage().child("useri").child(userRef).child("icon.jpg") userIconRef.metadata.addOnSuccessListener { Glide.with(mainActivityContext) .load(userIconRef) .override(35, 35) .centerCrop() .into(holder.iconUser) } } holder.cardUser.setOnClickListener { val docVizUser = mainActivityContext.getSharedPreferences("vizUser", Context.MODE_PRIVATE) docVizUser.edit().putString("refUser", userRef).apply() val dialog = VizualizareDetaliiUser() dialog.show(mainActivityContext.supportFragmentManager, "Vizualizează detalii user") } } override fun getItemCount() = lista_useri.size }
1
Kotlin
0
0
fe96f42086463cd7f48d6eb7aeedb491db14ae42
2,150
TownTrekker
MIT License
src/main/kotlin/me/jakejmattson/discordkt/api/TypeContainers.kt
DiscordKt
271,063,846
false
null
package me.jakejmattson.discordkt.api /** A container for data that saves type information. */ interface TypeContainer class NoArgs : TypeContainer data class Args1<A>(val first: A) : TypeContainer data class Args2<A, B>(val first: A, val second: B) : TypeContainer data class Args3<A, B, C>(val first: A, val second: B, val third: C) : TypeContainer data class Args4<A, B, C, D>(val first: A, val second: B, val third: C, val fourth: D) : TypeContainer data class Args5<A, B, C, D, E>(val first: A, val second: B, val third: C, val fourth: D, val fifth: E) : TypeContainer internal fun bundleToContainer(arguments: List<Any?>) = when (arguments.size) { 0 -> NoArgs() 1 -> Args1(arguments[0]) 2 -> Args2(arguments[0], arguments[1]) 3 -> Args3(arguments[0], arguments[1], arguments[2]) 4 -> Args4(arguments[0], arguments[1], arguments[2], arguments[3]) 5 -> Args5(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]) else -> throw IllegalArgumentException("Cannot handle (${arguments.size}) arguments.") }
2
Kotlin
9
51
cd7b9cd4e8b1d0270f0f99006e76df2abcf6e905
1,052
DiscordKt
MIT License
wow-api/src/main/kotlin/me/ahoo/wow/api/query/Condition.kt
Ahoo-Wang
628,167,080
false
null
/* * Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.wow.api.query enum class Operator { /** * 对提供的条件列表执行逻辑与 */ AND, /** * 对提供的条件列表执行逻辑或 */ OR, /** * 匹配`id`字段值等于指定值的所有文档 */ ID, /** * 匹配`id`字段值等于指定值列表中的任何值的所有文档 */ IDS, /** * 匹配`tenantId`字段值等于指定值的所有文档 */ TENANT_ID, /** * 匹配`deleted`字段值等于指定值的所有文档 */ DELETED, /** * 匹配所有文档 */ ALL, /** * 匹配字段名称值等于指定值的所有文档 */ EQ, /** * 匹配字段名称值不等于指定值的所有文档 */ NE, /** * 匹配给定字段的值大于指定值的所有文档 */ GT, /** * 匹配给定字段的值小于指定值的所有文档 */ LT, /** * 匹配给定字段的值大于或等于指定值的所有文档 */ GTE, /** * 匹配给定字段的值小于或等于指定值的所有文档 */ LTE, /** * 匹配给定字段的值包含指定值的所有文档 */ CONTAINS, /** * 匹配字段值等于指定值列表中的任何值的所有文档 */ IN, /** * 匹配字段值不等于任何指定值或不存在的所有文档 */ NOT_IN, /** * 匹配字段值在指定值范围区间的所有文档 */ BETWEEN, /** * 匹配所有文档,其中字段值是包含所有指定值的数组 */ ALL_IN, /** * 匹配字段值以指定字符串开头的文档 */ STARTS_WITH, /** * 匹配字段值以指定字符串结尾的文档 */ ENDS_WITH, /** * 条件与包含数组字段的所有文档相匹配,其中数组中至少有一个成员与给定的条件匹配。 */ ELEM_MATCH, /** * 匹配字段值在指定值为`null`的所有文档 */ NULL, /** * 匹配字段值在指定值不为`null`的所有文档 */ NOT_NULL, /** * 匹配字段值在指定值为`true`的所有文档 */ TRUE, /** * 匹配字段值在指定值为`false`的所有文档 */ FALSE, /** * 原始操作符,将条件值直接作为原始的数据库查询条件 */ RAW, // #region 日期类型筛选条件,字段要求:以毫秒为单位的 `long` 类型时间戳 /** * 匹配*数值类型时间戳*字段在今天范围区间的所有文档 * > 比如:`today` 为 `2024-06-06`,则匹配范围 `2024-06-06 00:00:00.000` ~ `2024-06-06 23:59:59.999` 的所有文档 * */ TODAY, /** * 匹配*数值类型时间戳*字段在昨天范围区间的所有文档 * > 比如:`today` 为 `2024-06-06`,则匹配范围 `2024-06-05 00:00:00.000` ~ `2024-06-05 23:59:59.999` 的所有文档 * */ TOMORROW, /** * 匹配*数值类型时间戳*字段在本周范围区间的所有文档 */ THIS_WEEK, /** * 匹配*数值类型时间戳*字段在下周范围区间的所有文档 */ NEXT_WEEK, /** * 匹配*数值类型时间戳*字段在上周范围区间的所有文档 */ LAST_WEEK, /** * 匹配*数值类型时间戳*字段在本月范围区间的所有文档 * > 比如: * - `today` : `2024-06-06` * - 匹配范围 : `2024-06-01 00:00:00.000` ~ `2024-06-30 23:59:59.999` 的所有文档 * */ THIS_MONTH, /** * 匹配*数值类型时间戳*字段在上月范围区间的所有文档 * > 比如: * - `today` : `2024-06-06` * - 匹配范围 : `2024-05-01 00:00:00.000` ~ `2024-05-31 23:59:59.999` 的所有文档 * */ LAST_MONTH, /** * 匹配*数值类型时间戳*字段在指定值最近天数范围区间的所有文档 * > 比如:近三天 * - `today` : `2024-06-06` * - 匹配范围 : `2024-06-04 00:00:00.000` ~ `2024-06-06 23:59:59.999` 的所有文档 * - 即 : 今天、昨天、前天 */ RECENT_DAYS, // #endregion } data class Condition( val field: String, val operator: Operator, val value: Any = EMPTY_VALUE, /** * When `operator` is `AND` or `OR`, `children` cannot be empty. */ val children: List<Condition> = emptyList(), /** * 匹配所有与传入条件不匹配的文档 */ val not: Boolean = false, ) : RewritableCondition<Condition> { override fun withCondition(newCondition: Condition): Condition { return newCondition } override fun appendCondition(append: Condition): Condition { if (this.operator == Operator.ALL) { return append } return and(this, append) } fun not(not: Boolean = true): Condition { if (this.not == not) { return this } return copy(not = not) } companion object { const val EMPTY_VALUE = "" val ALL = Condition(field = EMPTY_VALUE, operator = Operator.ALL, value = EMPTY_VALUE) fun and(vararg conditions: Condition) = Condition(EMPTY_VALUE, Operator.AND, children = conditions.toList()) fun and(conditions: List<Condition>) = Condition(EMPTY_VALUE, Operator.AND, children = conditions) fun or(vararg conditions: Condition) = Condition(EMPTY_VALUE, Operator.OR, children = conditions.toList()) fun or(conditions: List<Condition>) = Condition(EMPTY_VALUE, Operator.OR, children = conditions) fun all() = ALL fun eq(field: String, value: Any) = Condition(field, Operator.EQ, value) fun ne(field: String, value: Any) = Condition(field, Operator.NE, value) fun gt(field: String, value: Any) = Condition(field, Operator.GT, value) fun lt(field: String, value: Any) = Condition(field, Operator.LT, value) fun gte(field: String, value: Any) = Condition(field, Operator.GTE, value) fun lte(field: String, value: Any) = Condition(field, Operator.LTE, value) fun contains(field: String, value: Any) = Condition(field, Operator.CONTAINS, value) fun isIn(field: String, value: List<Any>) = Condition(field, Operator.IN, value) fun notIn(field: String, value: List<Any>) = Condition(field, Operator.NOT_IN, value) fun <V> between(field: String, start: V, end: V) = Condition(field, Operator.BETWEEN, listOf(start, end)) fun all(field: String, value: List<Any>) = Condition(field, Operator.ALL_IN, value) fun startsWith(field: String, value: Any) = Condition(field, Operator.STARTS_WITH, value) fun endsWith(field: String, value: Any) = Condition(field, Operator.ENDS_WITH, value) fun elemMatch(field: String, value: Condition) = Condition(field, Operator.ELEM_MATCH, children = listOf(value)) fun isNull(field: String) = Condition(field, Operator.NULL) fun notNull(field: String) = Condition(field, Operator.NOT_NULL) fun isTrue(field: String) = Condition(field, Operator.TRUE) fun isFalse(field: String) = Condition(field, Operator.FALSE) fun id(value: String) = Condition(field = EMPTY_VALUE, operator = Operator.ID, value = value) fun ids(value: List<String>) = Condition(field = EMPTY_VALUE, operator = Operator.IDS, value = value) fun ids(vararg value: String) = Condition(field = EMPTY_VALUE, operator = Operator.IDS, value = value.toList()) fun tenantId(value: String) = Condition(field = EMPTY_VALUE, operator = Operator.TENANT_ID, value = value) fun deleted(value: Boolean) = Condition(field = EMPTY_VALUE, operator = Operator.DELETED, value = value) fun today(field: String) = Condition(field = field, operator = Operator.TODAY) fun tomorrow(field: String) = Condition(field = field, operator = Operator.TOMORROW) fun thisWeek(field: String) = Condition(field = field, operator = Operator.THIS_WEEK) fun nextWeek(field: String) = Condition(field = field, operator = Operator.NEXT_WEEK) fun lastWeek(field: String) = Condition(field = field, operator = Operator.LAST_WEEK) fun thisMonth(field: String) = Condition(field = field, operator = Operator.THIS_MONTH) fun lastMonth(field: String) = Condition(field = field, operator = Operator.LAST_MONTH) fun recentDays(field: String, days: Int) = Condition(field = field, operator = Operator.RECENT_DAYS, value = days) fun raw(value: Any) = Condition(field = EMPTY_VALUE, operator = Operator.RAW, value = value) } }
8
null
23
187
4fb54c314c31a7cd3c9515554879a2ca8fade764
7,788
Wow
Apache License 2.0
composeApp/src/commonMain/kotlin/screens/DevicesScreen.kt
MrJovanovic13
745,615,039
false
{"Kotlin": 35130, "Swift": 594}
package screens import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column 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.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Settings 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.text.input.ImeAction import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.screen.Screen import com.russhwolf.settings.Settings import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import model.Device import org.koin.core.component.KoinComponent import org.koin.core.component.inject import screens.composables.DashboardItem import screens.composables.LoadingIndicator import service.DeviceService class DevicesScreen : Screen, KoinComponent { private var availableDevices = mutableStateOf<List<Device>>(emptyList()) private var isLoading = mutableStateOf(true) private val deviceService: DeviceService by inject() private val settings = Settings() private val groupName = settings.getString("groupName", "UNKNOWN") @Composable override fun Content() { MaterialTheme {} var devices: List<Device> CoroutineScope(Dispatchers.IO).launch { deviceService.postCurrentDevice() // TODO Implement indicator showing current device among the list devices = deviceService.getAllDevicesByGroupId() availableDevices.value = devices isLoading.value = false } if (isLoading.value) { LoadingIndicator() } else { Dashboard() } } @Composable fun Dashboard() { Surface( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { var textFieldText by remember { mutableStateOf("") } var searchResults by remember { mutableStateOf(availableDevices.value) } TopAppBar( title = { Text(groupName) }, actions = { IconButton(onClick = { /* Handle settings click */ }) { Icon( imageVector = Icons.Default.Settings, contentDescription = "Settings" ) } } ) Spacer(modifier = Modifier.height(16.dp)) BasicTextField( value = textFieldText, onValueChange = { textFieldText = it searchResults = filterListByNamesAndReturn(textFieldText) }, keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = { } ), modifier = Modifier .fillMaxWidth() .background(Color.Gray) .padding(8.dp) ) Spacer(modifier = Modifier.height(16.dp)) LazyColumn { items(searchResults) { result -> DashboardItem(item = result) } } } } } private fun filterListByNamesAndReturn(query: String): List<Device> { return availableDevices.value.filter { it.name.contains(query, ignoreCase = true) } } }
0
Kotlin
0
0
f08c3d23885c6bbde74584e6e3fec44a9bee1677
4,711
threads-nexus-kmm-client
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/DriverWoman.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Filled.DriverWoman: ImageVector get() { if (_driverWoman != null) { return _driverWoman!! } _driverWoman = Builder(name = "DriverWoman", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(12.0f, 14.0f) curveToRelative(-5.103f, 0.0f, -9.375f, 3.822f, -9.936f, 8.89f) curveToRelative(-0.031f, 0.283f, 0.06f, 0.565f, 0.249f, 0.777f) curveToRelative(0.19f, 0.212f, 0.461f, 0.333f, 0.745f, 0.333f) horizontalLineToRelative(2.941f) curveToRelative(0.0f, -3.309f, 2.691f, -6.0f, 6.0f, -6.0f) reflectiveCurveToRelative(6.0f, 2.691f, 6.0f, 6.0f) horizontalLineToRelative(2.941f) curveToRelative(0.284f, 0.0f, 0.555f, -0.121f, 0.745f, -0.333f) curveToRelative(0.189f, -0.212f, 0.28f, -0.494f, 0.249f, -0.777f) curveToRelative(-0.561f, -5.068f, -4.833f, -8.89f, -9.936f, -8.89f) close() moveTo(12.0f, 20.0f) curveToRelative(-2.206f, 0.0f, -4.0f, 1.794f, -4.0f, 4.0f) horizontalLineToRelative(8.0f) curveToRelative(0.0f, -2.206f, -1.794f, -4.0f, -4.0f, -4.0f) close() moveTo(7.827f, 5.0f) horizontalLineToRelative(-2.088f) curveToRelative(0.059f, -0.239f, 0.1f, -0.395f, 0.117f, -0.45f) curveTo(6.71f, 1.829f, 9.203f, 0.0f, 12.058f, 0.0f) reflectiveCurveToRelative(5.347f, 1.829f, 6.202f, 4.55f) curveToRelative(0.076f, 0.242f, 1.039f, 4.222f, 1.948f, 8.016f) curveToRelative(0.25f, 1.043f, -0.892f, 1.862f, -1.797f, 1.287f) curveToRelative(-0.352f, -0.223f, -0.716f, -0.429f, -1.092f, -0.614f) curveToRelative(-0.507f, -2.03f, -1.091f, -4.346f, -1.153f, -4.606f) curveToRelative(-0.824f, 1.415f, -2.357f, 2.368f, -4.108f, 2.368f) curveToRelative(-2.364f, 0.0f, -4.329f, -1.736f, -4.69f, -3.999f) curveToRelative(0.28f, 0.0f, 0.652f, 0.0f, 0.69f, 0.0f) curveToRelative(1.243f, 0.0f, 2.771f, -0.346f, 3.852f, -1.02f) curveToRelative(0.93f, -0.58f, 1.688f, -1.359f, 2.229f, -2.276f) curveToRelative(0.318f, -0.538f, 0.034f, -1.226f, -0.553f, -1.438f) curveToRelative(-0.006f, -0.002f, -0.013f, -0.005f, -0.019f, -0.007f) curveToRelative(-0.437f, -0.156f, -0.921f, 0.041f, -1.158f, 0.44f) curveToRelative(-0.38f, 0.637f, -0.909f, 1.18f, -1.557f, 1.584f) curveToRelative(-0.81f, 0.506f, -1.775f, 0.717f, -3.025f, 0.717f) close() moveTo(5.475f, 13.933f) curveToRelative(-0.802f, 0.518f, -1.821f, -0.198f, -1.601f, -1.126f) curveToRelative(0.534f, -2.25f, 1.12f, -4.713f, 1.409f, -5.921f) curveToRelative(0.227f, 2.427f, 1.738f, 4.479f, 3.848f, 5.472f) curveToRelative(-1.315f, 0.323f, -2.548f, 0.859f, -3.656f, 1.575f) close() } } .build() return _driverWoman!! } private var _driverWoman: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,152
icons
MIT License
wallet/src/main/java/com/android/identity_credential/wallet/SelfSignedMdlIssuingAuthority.kt
openwallet-foundation-labs
248,844,077
false
{"Kotlin": 2791449, "Java": 682956, "Python": 85755, "JavaScript": 28064, "HTML": 841, "CSS": 286, "Dockerfile": 267}
package com.android.identity_credential.wallet import android.graphics.Bitmap import android.graphics.BitmapFactory import com.android.identity.cbor.Cbor import com.android.identity.cbor.CborArray import com.android.identity.cbor.toDataItemDateTimeString import com.android.identity.cbor.toDataItemFullDate import com.android.identity.credential.NameSpacedData import com.android.identity.credentialtype.CredentialType import com.android.identity.credentialtype.knowntypes.DrivingLicense import com.android.identity.credentialtype.knowntypes.EUPersonalID import com.android.identity.issuance.CredentialConfiguration import com.android.identity.issuance.CredentialPresentationFormat import com.android.identity.issuance.IssuingAuthorityConfiguration import com.android.identity.issuance.evidence.EvidenceResponse import com.android.identity.issuance.evidence.EvidenceResponseIcaoNfcTunnelResult import com.android.identity.issuance.evidence.EvidenceResponseIcaoPassiveAuthentication import com.android.identity.issuance.evidence.EvidenceResponseMessage import com.android.identity.issuance.evidence.EvidenceResponseQuestionMultipleChoice import com.android.identity.issuance.simple.SimpleIcaoNfcTunnelDriver import com.android.identity.issuance.simple.SimpleIssuingAuthorityProofingGraph import com.android.identity.storage.StorageEngine import com.android.identity_credential.mrtd.MrtdNfcData import com.android.identity_credential.mrtd.MrtdNfcDataDecoder import kotlinx.datetime.Clock import kotlinx.datetime.LocalDate import java.io.ByteArrayOutputStream import kotlin.time.Duration.Companion.days class SelfSignedMdlIssuingAuthority( application: WalletApplication, storageEngine: StorageEngine ) : SelfSignedMdocIssuingAuthority(application, storageEngine) { companion object { private const val MDL_DOCTYPE = DrivingLicense.MDL_DOCTYPE private const val MDL_NAMESPACE = DrivingLicense.MDL_NAMESPACE private const val AAMVA_NAMESPACE = DrivingLicense.AAMVA_NAMESPACE } override val docType: String = MDL_DOCTYPE override lateinit var configuration: IssuingAuthorityConfiguration private val tosAssets: Map<String, ByteArray>; init { val baos = ByteArrayOutputStream() BitmapFactory.decodeResource( application.applicationContext.resources, R.drawable.utopia_dmv_issuing_authority_logo ).compress(Bitmap.CompressFormat.PNG, 90, baos) val icon: ByteArray = baos.toByteArray() configuration = IssuingAuthorityConfiguration( identifier = "mDL_Utopia", issuingAuthorityName = resourceString(R.string.utopia_mdl_issuing_authority_name), issuingAuthorityLogo = icon, description = resourceString(R.string.utopia_mdl_issuing_authority_description), credentialFormats = setOf(CredentialPresentationFormat.MDOC_MSO), pendingCredentialInformation = createCredentialConfiguration(null) ) tosAssets = mapOf("utopia_logo.png" to resourceBytes(R.drawable.utopia_dmv_issuing_authority_logo)) } override fun getProofingGraphRoot(): SimpleIssuingAuthorityProofingGraph.Node { return SimpleIssuingAuthorityProofingGraph.create { message( "tos", resourceString(R.string.utopia_mdl_issuing_authority_tos), tosAssets, resourceString(R.string.utopia_mdl_issuing_authority_accept), resourceString(R.string.utopia_mdl_issuing_authority_reject), ) choice( id = "path", message = resourceString(R.string.utopia_mdl_issuing_authority_hardcoded_or_derived), assets = mapOf(), acceptButtonText = "Continue" ) { on(id = "hardcoded", text = resourceString(R.string.utopia_mdl_issuing_authority_hardcoded_option)) { } on(id = "passport", text = resourceString(R.string.utopia_mdl_issuing_authority_passport_option)) { icaoTunnel("tunnel", listOf(1, 2, 7)) { whenChipAuthenticated {} whenActiveAuthenticated {} whenNotAuthenticated {} } } } message( "message", message = resourceString(R.string.utopia_mdl_issuing_authority_application_finish), assets = mapOf(), acceptButtonText = resourceString(R.string.utopia_mdl_issuing_authority_continue), null ) requestNotificationPermission( "notificationPermission", permissionNotAvailableMessage = resourceString(R.string.permission_post_notifications_rationale_md), grantPermissionButtonText = resourceString(R.string.permission_post_notifications_grant_permission_button_text), continueWithoutPermissionButtonText = resourceString(R.string.permission_post_notifications_continue_without_permission_button_text), assets = mapOf() ) } } override fun createNfcTunnelHandler(): SimpleIcaoNfcTunnelDriver { return NfcTunnelDriver() } override fun checkEvidence(collectedEvidence: Map<String, EvidenceResponse>): Boolean { return (collectedEvidence["tos"] as EvidenceResponseMessage).acknowledged } override fun generateCredentialConfiguration(collectedEvidence: Map<String, EvidenceResponse>): CredentialConfiguration { return createCredentialConfiguration(collectedEvidence) } private fun createCredentialConfiguration(collectedEvidence: Map<String, EvidenceResponse>?): CredentialConfiguration { val baos = ByteArrayOutputStream() BitmapFactory.decodeResource( application.applicationContext.resources, R.drawable.utopia_driving_license_card_art ).compress(Bitmap.CompressFormat.PNG, 90, baos) val cardArt: ByteArray = baos.toByteArray() if (collectedEvidence == null) { return CredentialConfiguration( resourceString(R.string.utopia_mdl_issuing_authority_pending_credential_title), cardArt, MDL_DOCTYPE, NameSpacedData.Builder().build() ) } val staticData: NameSpacedData val now = Clock.System.now() val issueDate = now val expiryDate = now + 365.days * 5 val credType = application.credentialTypeRepository.getCredentialTypeForMdoc(MDL_DOCTYPE)!! val path = (collectedEvidence["path"] as EvidenceResponseQuestionMultipleChoice).answerId if (path == "hardcoded") { staticData = getSampleData(credType).build() } else { val icaoPassiveData = collectedEvidence["passive"] val icaoTunnelData = collectedEvidence["tunnel"] val mrtdData = if (icaoTunnelData is EvidenceResponseIcaoNfcTunnelResult) MrtdNfcData(icaoTunnelData.dataGroups, icaoTunnelData.securityObject) else if (icaoPassiveData is EvidenceResponseIcaoPassiveAuthentication) MrtdNfcData(icaoPassiveData.dataGroups, icaoPassiveData.securityObject) else throw IllegalStateException("Should not happen") val decoder = MrtdNfcDataDecoder(application.cacheDir) val decoded = decoder.decode(mrtdData) val firstName = decoded.firstName val lastName = decoded.lastName val sex = when (decoded.gender) { "MALE" -> 1L "FEMALE" -> 2L else -> 0L } val portrait = bitmapData(decoded.photo, R.drawable.img_erika_portrait) val signatureOrUsualMark = bitmapData(decoded.signature, R.drawable.img_erika_signature) // Make sure we set at least all the mandatory data elements // // TODO: get birth_date from passport // staticData = NameSpacedData.Builder() .putEntryString(MDL_NAMESPACE, "given_name", firstName) .putEntryString(MDL_NAMESPACE, "family_name", lastName) .putEntry(MDL_NAMESPACE, "birth_date", Cbor.encode(LocalDate.parse("1970-01-01").toDataItemFullDate)) .putEntryByteString(MDL_NAMESPACE, "portrait", portrait) .putEntryByteString(MDL_NAMESPACE, "signature_usual_mark", signatureOrUsualMark) .putEntryNumber(MDL_NAMESPACE, "sex", sex) .putEntry(MDL_NAMESPACE, "issue_date", Cbor.encode(issueDate.toDataItemDateTimeString)) .putEntry(MDL_NAMESPACE, "expiry_date", Cbor.encode(expiryDate.toDataItemDateTimeString) ) .putEntryString(MDL_NAMESPACE, "issuing_authority", resourceString(R.string.utopia_mdl_issuing_authority_name),) .putEntryString(MDL_NAMESPACE, "issuing_country", "UT") .putEntryString(MDL_NAMESPACE, "un_distinguishing_sign", "UTO") .putEntryString(MDL_NAMESPACE, "document_number", "1234567890") .putEntryString(MDL_NAMESPACE, "administrative_number", "123456789") .putEntry(MDL_NAMESPACE, "driving_privileges", Cbor.encode(CborArray.builder().end().build())) .putEntryBoolean(MDL_NAMESPACE, "age_over_18", true) .putEntryBoolean(MDL_NAMESPACE, "age_over_21", true) .putEntryString(AAMVA_NAMESPACE, "DHS_compliance", "F") .putEntryNumber(AAMVA_NAMESPACE, "EDL_credential", 1) .putEntryNumber(AAMVA_NAMESPACE, "sex", sex) .build() } val firstName = staticData.getDataElementString(MDL_NAMESPACE, "given_name") return CredentialConfiguration( resourceString(R.string.utopia_mdl_issuing_authority_credential_title, firstName), cardArt, MDL_DOCTYPE, staticData ) } override fun developerModeRequestUpdate(currentConfiguration: CredentialConfiguration): CredentialConfiguration { // The update consists of just slapping an extra 0 at the end of `administrative_number` val newAdministrativeNumber = try { currentConfiguration.staticData .getDataElementString(MDL_NAMESPACE, "administrative_number") } catch (e: Throwable) { "" } + "0" val builder = NameSpacedData.Builder(currentConfiguration.staticData) builder.putEntryString( MDL_NAMESPACE, "administrative_number", newAdministrativeNumber ) return CredentialConfiguration( displayName = currentConfiguration.displayName, cardArt = currentConfiguration.cardArt, mdocDocType = currentConfiguration.mdocDocType, staticData = builder.build(), ) } private fun getSampleData(credentialType: CredentialType): NameSpacedData.Builder { val portrait = bitmapData(null, R.drawable.img_erika_portrait) val signatureOrUsualMark = bitmapData(null, R.drawable.img_erika_signature) val builder = NameSpacedData.Builder() for ((namespaceName, namespace) in credentialType.mdocCredentialType!!.namespaces) { for ((dataElementName, dataElement) in namespace.dataElements) { if (dataElement.attribute.sampleValue != null) { builder.putEntry( namespaceName, dataElementName, Cbor.encode(dataElement.attribute.sampleValue!!) ) } } } // Sample data currently doesn't have portrait or signature_usual_mark builder .putEntryByteString(MDL_NAMESPACE, "portrait", portrait) .putEntryByteString(MDL_NAMESPACE, "signature_usual_mark", signatureOrUsualMark) return builder } }
101
Kotlin
69
134
c2b00dc60ed11a46334da37521acd89a100f3d2e
12,216
identity-credential
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/TemperatureDown.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.TemperatureDown: ImageVector get() { if (_temperatureDown != null) { return _temperatureDown!! } _temperatureDown = Builder(name = "TemperatureDown", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 12.11f) curveTo(16.334f, 16.363f, 13.079f, 24.117f, 7.0f, 24.0f) curveToRelative(-6.078f, 0.117f, -9.335f, -7.638f, -5.0f, -11.89f) verticalLineTo(5.0f) curveToRelative(0.211f, -6.609f, 9.791f, -6.6f, 10.0f, 0.0f) close() moveTo(10.0f, 17.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, false, -2.0f, -2.816f) verticalLineTo(12.0f) horizontalLineTo(6.0f) verticalLineToRelative(2.184f) arcTo(2.995f, 2.995f, 0.0f, true, false, 10.0f, 17.0f) close() moveTo(15.707f, 6.707f) lineTo(14.293f, 8.121f) lineToRelative(3.293f, 3.293f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.828f, 0.0f) lineToRelative(3.293f, -3.293f) lineTo(22.293f, 6.707f) lineTo(20.0f, 9.0f) verticalLineTo(0.0f) horizontalLineTo(18.0f) verticalLineTo(9.0f) close() } } .build() return _temperatureDown!! } private var _temperatureDown: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,390
icons
MIT License
on_audio_query/android/src/main/kotlin/com/lucasjosino/on_audio_query/interfaces/OnPermissionManagerInterface.kt
TrendingTechnology
399,523,003
true
{"Dart": 103841, "Kotlin": 74032, "Swift": 43331, "HTML": 7456, "Ruby": 2328, "Objective-C": 723}
package com.lucasjosino.on_audio_query.interfaces import android.content.Context /** OnPermissionManagerInterface */ interface OnPermissionManagerInterface { fun onPermissionStatus(context: Context? = null) : Boolean fun onRequestPermission() fun onRetryRequestPermission() }
0
null
0
0
a1cdb8022c758fabe6fd55ac16290141bf1b2c74
289
on_audio_query
Linux Kernel Variant of OpenIB.org license
bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/repository/generic/ConfidenceCriteriaRepository.kt
eclipse-tractusx
526,621,398
false
null
/******************************************************************************* * Copyright (c) 2021,2024 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.eclipse.tractusx.bpdm.gate.repository.generic import org.eclipse.tractusx.bpdm.gate.entity.generic.ConfidenceCriteria import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository interface ConfidenceCriteriaRepository : JpaRepository<ConfidenceCriteria, Long>, CrudRepository<ConfidenceCriteria, Long> { @Query("SELECT AVG(c.numberOfBusinessPartners) FROM ConfidenceCriteria AS c") fun averageNumberOfBusinessPartners(): Float? @Query("SELECT COUNT(c.numberOfBusinessPartners) FROM ConfidenceCriteria AS c WHERE c.numberOfBusinessPartners <= 1") fun countUnique(): Long? @Query("SELECT COUNT(c.sharedByOwner) FROM ConfidenceCriteria AS c") fun countSharedByOwner(): Long? @Query("SELECT COUNT(c.checkedByExternalDataSource) FROM ConfidenceCriteria AS c") fun countCheckedByExternalDataSource(): Long? @Query("SELECT AVG(c.confidenceLevel) FROM ConfidenceCriteria AS c") fun averageConfidenceLevel(): Float? }
39
null
9
6
c0c0ccfb385772381a06068d648327291d6ff194
1,984
bpdm
Apache License 2.0
multi-vlayout/src/main/java/com/yoxin/multivlayout/MultiTypePool.kt
zhengyoxin
128,705,782
false
null
package com.yoxin.multivlayout /** * Created by zhengyongxin on 2018/2/25. * An List implementation of TypePool. */ class MultiTypePool( private val classes: MutableList<Class<*>> = mutableListOf(), private val adapters: MutableList<Class<out MultiAdapter<*, *>>> = mutableListOf(), private val linkers: MutableList<Linker<*>> = mutableListOf()) : TypePool { override fun register(clazz: Class<*>, adapter: Class<out MultiAdapter<*, *>>, linker: Linker<*>) { classes.add(clazz) adapters.add(adapter) linkers.add(linker) } override fun unregister(clazz: Class<*>): Boolean { var removed = false while (true) { val index = classes.indexOf(clazz) if (index != -1) { classes.removeAt(index) adapters.removeAt(index) linkers.removeAt(index) removed = true } else { break } } return removed } override fun size(): Int { return classes.size } override fun firstIndexOf(clazz: Class<*>): Int { val index = classes.indexOf(clazz) if (index != -1) { return index } // classes.indices.forEach { // classes[it].isAssignableFrom(clazz) // return it // } return -1 } override fun getClass(index: Int): Class<*> { return classes[index] } override fun getItemViewAdapter(index: Int): Class<out MultiAdapter<*, *>> { return adapters[index] } override fun getLinker(index: Int): Linker<*> { return linkers[index] } }
0
Kotlin
0
2
d9ccb1639241923504a1f01b548b4031116fe727
1,690
multiVLayout
Apache License 2.0
multi-vlayout/src/main/java/com/yoxin/multivlayout/MultiTypePool.kt
zhengyoxin
128,705,782
false
null
package com.yoxin.multivlayout /** * Created by zhengyongxin on 2018/2/25. * An List implementation of TypePool. */ class MultiTypePool( private val classes: MutableList<Class<*>> = mutableListOf(), private val adapters: MutableList<Class<out MultiAdapter<*, *>>> = mutableListOf(), private val linkers: MutableList<Linker<*>> = mutableListOf()) : TypePool { override fun register(clazz: Class<*>, adapter: Class<out MultiAdapter<*, *>>, linker: Linker<*>) { classes.add(clazz) adapters.add(adapter) linkers.add(linker) } override fun unregister(clazz: Class<*>): Boolean { var removed = false while (true) { val index = classes.indexOf(clazz) if (index != -1) { classes.removeAt(index) adapters.removeAt(index) linkers.removeAt(index) removed = true } else { break } } return removed } override fun size(): Int { return classes.size } override fun firstIndexOf(clazz: Class<*>): Int { val index = classes.indexOf(clazz) if (index != -1) { return index } // classes.indices.forEach { // classes[it].isAssignableFrom(clazz) // return it // } return -1 } override fun getClass(index: Int): Class<*> { return classes[index] } override fun getItemViewAdapter(index: Int): Class<out MultiAdapter<*, *>> { return adapters[index] } override fun getLinker(index: Int): Linker<*> { return linkers[index] } }
0
Kotlin
0
2
d9ccb1639241923504a1f01b548b4031116fe727
1,690
multiVLayout
Apache License 2.0
plugins/ksp/src/org/jetbrains/kotlin/ksp/symbol/impl/kotlin/KSTypeParameterImpl.kt
android
263,405,600
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.ksp.symbol.impl.kotlin import org.jetbrains.kotlin.ksp.symbol.* import org.jetbrains.kotlin.ksp.symbol.impl.KSObjectCache import org.jetbrains.kotlin.ksp.symbol.impl.toKSModifiers import org.jetbrains.kotlin.ksp.symbol.impl.toLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject class KSTypeParameterImpl private constructor(val ktTypeParameter: KtTypeParameter, val owner: KtTypeParameterListOwner) : KSTypeParameter, KSDeclarationImpl(ktTypeParameter), KSExpectActual by KSExpectActualNoImpl() { companion object : KSObjectCache<Pair<KtTypeParameter, KtTypeParameterListOwner>, KSTypeParameterImpl>() { fun getCached(ktTypeParameter: KtTypeParameter, owner: KtTypeParameterListOwner) = cache.getOrPut(Pair(ktTypeParameter, owner)) { KSTypeParameterImpl(ktTypeParameter, owner) } } override val name: KSName by lazy { KSNameImpl.getCached(ktTypeParameter.name!!) } override val isReified: Boolean by lazy { ktTypeParameter.modifierList?.hasModifier(KtTokens.REIFIED_KEYWORD) ?: false } override val variance: Variance by lazy { when { ktTypeParameter.modifierList == null -> Variance.INVARIANT ktTypeParameter.modifierList!!.hasModifier(KtTokens.OUT_KEYWORD) -> Variance.COVARIANT ktTypeParameter.modifierList!!.hasModifier(KtTokens.IN_KEYWORD) -> Variance.CONTRAVARIANT else -> Variance.INVARIANT } } override val bounds: List<KSTypeReference> by lazy { val list = mutableListOf(ktTypeParameter.extendsBound) list.addAll( owner.typeConstraints .filter { it.subjectTypeParameterName!!.getReferencedName() == ktTypeParameter.nameAsSafeName.asString() } .map { it.boundTypeReference } ) list.filterNotNull().map { KSTypeReferenceImpl.getCached(it) } } override val simpleName: KSName by lazy { KSNameImpl.getCached(ktTypeParameter.name ?: "_") } override val typeParameters: List<KSTypeParameter> = emptyList() override val parentDeclaration: KSDeclaration? by lazy { when (owner) { is KtClassOrObject -> KSClassDeclarationImpl.getCached(owner) is KtFunction -> KSFunctionDeclarationImpl.getCached(owner) is KtProperty -> KSPropertyDeclarationImpl.getCached(owner) else -> throw IllegalStateException() } } override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitTypeParameter(this, data) } }
1
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
2,899
kotlin
Apache License 2.0
src/main/kotlin/dev/aaronhowser/mods/geneticsresequenced/recipes/brewing/BrewingRecipes.kt
aaronhowser1
780,170,281
false
{"Kotlin": 564933}
package dev.aaronhowser.mods.geneticsresequenced.recipes.brewing import dev.aaronhowser.mods.geneticsresequenced.genes.ModGenes import dev.aaronhowser.mods.geneticsresequenced.items.DnaHelixItem.Companion.getGene import dev.aaronhowser.mods.geneticsresequenced.items.DnaHelixItem.Companion.setBasic import dev.aaronhowser.mods.geneticsresequenced.items.DnaHelixItem.Companion.setGene import dev.aaronhowser.mods.geneticsresequenced.items.EntityDnaItem import dev.aaronhowser.mods.geneticsresequenced.registries.ModItems import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.CELL_GROWTH import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.MUTATION import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.POTION_REGISTRY import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.SUBSTRATE import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.THE_CURE import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.VIRAL_AGENTS import dev.aaronhowser.mods.geneticsresequenced.registries.ModPotions.ZOMBIFY_VILLAGER import dev.aaronhowser.mods.geneticsresequenced.util.OtherUtil.itemStack import net.minecraft.ChatFormatting import net.minecraft.network.chat.Component import net.minecraft.world.entity.EntityType import net.minecraft.world.item.Item import net.minecraft.world.item.ItemStack import net.minecraft.world.item.Items import net.minecraft.world.item.alchemy.Potion import net.minecraft.world.item.alchemy.PotionUtils import net.minecraft.world.item.alchemy.Potions import net.minecraft.world.item.crafting.Ingredient import net.minecraftforge.common.brewing.BrewingRecipe import net.minecraftforge.common.brewing.BrewingRecipeRegistry import net.minecraftforge.common.brewing.IBrewingRecipe import net.minecraftforge.event.entity.player.ItemTooltipEvent object BrewingRecipes { private val modPotions: List<Potion> by lazy { POTION_REGISTRY.entries.map { it.get() } } fun tooltip(event: ItemTooltipEvent) { val stack = event.itemStack val itemPotion = PotionUtils.getPotion(stack) if (itemPotion == Potions.EMPTY || itemPotion == ZOMBIFY_VILLAGER) return if (itemPotion in modPotions && stack.item != Items.POTION) { event.toolTip.add( Component.translatable("tooltip.geneticsresequenced.potion.ignore") .withStyle { it.withColor(ChatFormatting.RED) } ) } val itemGene = stack.getGene() val itemEntity = EntityDnaItem.getEntityType(stack) if (itemGene != null) { event.toolTip.add( Component .translatable("tooltip.geneticsresequenced.gene", itemGene.nameComponent) .withStyle { it.withColor(ChatFormatting.GRAY) } ) } if (itemEntity != null) { event.toolTip.add( Component .translatable("tooltip.geneticsresequenced.dna_item.filled", itemEntity.description) .withStyle { it.withColor(ChatFormatting.GRAY) } ) } } private val Potion.ingredient: Ingredient get() = Ingredient.of(PotionUtils.setPotion(ItemStack(Items.POTION), this)) private val ItemStack.ingredient: Ingredient get() = Ingredient.of(this) private val Item.ingredient: Ingredient get() = Ingredient.of(ItemStack(this)) val allRecipes: MutableList<IBrewingRecipe> = mutableListOf() fun potionStack(potion: Potion): ItemStack { return PotionUtils.setPotion( ItemStack(Items.POTION), potion ) } val substratePotionStack by lazy { potionStack(SUBSTRATE) } val cellGrowthPotionStack by lazy { potionStack(CELL_GROWTH) } val mutationPotionStack by lazy { potionStack(MUTATION) } val viralAgentsPotionStack by lazy { potionStack(VIRAL_AGENTS) } val curePotionStack by lazy { potionStack(THE_CURE) } fun addRecipes() { val substrateRecipe = BrewingRecipe( Potions.MUNDANE.ingredient, ModItems.ORGANIC_MATTER.get().ingredient, substratePotionStack ) val cellGrowthRecipe = BrewingRecipe( SUBSTRATE.ingredient, ModItems.DNA_HELIX.itemStack.setBasic().ingredient, cellGrowthPotionStack ) val mutationRecipe = BrewingRecipe( CELL_GROWTH.ingredient, Items.FERMENTED_SPIDER_EYE.ingredient, mutationPotionStack ) val viralRecipe = BrewingRecipe( MUTATION.ingredient, Items.CHORUS_FRUIT.ingredient, viralAgentsPotionStack ) val cureRecipe = BrewingRecipe( VIRAL_AGENTS.ingredient, ModItems.DNA_HELIX.itemStack.setGene(ModGenes.emeraldHeart).ingredient, curePotionStack ) allRecipes.addAll( listOf( substrateRecipe, cellGrowthRecipe, mutationRecipe, viralRecipe, cureRecipe ) ) val substrateDuplicationRecipe = SubstrateCellRecipe() allRecipes.add(substrateDuplicationRecipe) val setPcgEntityRecipe = SetPotionEntityRecipe() allRecipes.add(setPcgEntityRecipe) val geneFocusBrews = listOf( GmoRecipe(EntityType.BLAZE, Items.GLOWSTONE_DUST, ModGenes.bioluminescence, 0.85f), GmoRecipe(EntityType.MAGMA_CUBE, Items.GLOWSTONE_DUST, ModGenes.bioluminescence, 0.85f), GmoRecipe(EntityType.VILLAGER, Items.EMERALD, ModGenes.emeraldHeart, 0.85f), GmoRecipe(EntityType.SHULKER, Items.EMERALD_BLOCK, ModGenes.keepInventory, 0.45f), GmoRecipe(EntityType.RABBIT, Items.GOLDEN_BOOTS, ModGenes.speed, 0.65f), GmoRecipe(EntityType.RABBIT, Items.EMERALD, ModGenes.luck, 0.75f), GmoRecipe(EntityType.IRON_GOLEM, Items.GOLDEN_APPLE, ModGenes.regeneration, 0.3f), GmoRecipe(EntityType.CHICKEN, Items.EGG, ModGenes.layEgg, 1f), GmoRecipe(EntityType.PIG, Items.PORKCHOP, ModGenes.meaty, 1f), GmoRecipe(EntityType.ENDERMAN, Items.ENDER_PEARL, ModGenes.teleport, 0.45f), GmoRecipe(EntityType.ENDERMAN, Items.GOLDEN_APPLE, ModGenes.moreHearts, 0.2f), GmoRecipe(EntityType.MOOSHROOM, Items.MUSHROOM_STEM, ModGenes.photosynthesis, 0.7f), ) allRecipes.addAll(geneFocusBrews) val mutationBrews = listOf( GmoRecipe(EntityType.ENDER_DRAGON, Items.ELYTRA, ModGenes.flight, 0.55f, isMutation = true), GmoRecipe(EntityType.POLAR_BEAR, Items.NETHERITE_SWORD, ModGenes.strengthTwo, 0.5f, isMutation = true), GmoRecipe(EntityType.SHULKER, Items.NETHERITE_CHESTPLATE, ModGenes.resistanceTwo, 0.5f, isMutation = true), GmoRecipe(EntityType.POLAR_BEAR, Items.DIAMOND_SWORD, ModGenes.clawsTwo, 0.75f, isMutation = true), GmoRecipe(EntityType.RABBIT, Items.DIAMOND_BOOTS, ModGenes.speedTwo, 0.5f, isMutation = true), GmoRecipe(EntityType.OCELOT, Items.NETHERITE_BOOTS, ModGenes.speedFour, 0.5f, isMutation = true), GmoRecipe(EntityType.RABBIT, Items.NETHERITE_PICKAXE, ModGenes.hasteTwo, 0.35f, isMutation = true), GmoRecipe(EntityType.SILVERFISH, Items.NETHERITE_PICKAXE, ModGenes.efficiencyFour, 0.25f, isMutation = true), GmoRecipe(EntityType.ZOMBIE, Items.FERMENTED_SPIDER_EYE, ModGenes.scareZombies, 0.5f, isMutation = true), GmoRecipe(EntityType.SPIDER, Items.FERMENTED_SPIDER_EYE, ModGenes.scareSpiders, 0.5f, isMutation = true), GmoRecipe(EntityType.ENDER_DRAGON, Items.ENCHANTED_GOLDEN_APPLE, ModGenes.regenerationFour, 0.35f, isMutation = true), GmoRecipe(EntityType.PIG, Items.BLAZE_POWDER, ModGenes.meatyTwo, 0.75f, isMutation = true), GmoRecipe(EntityType.ENDERMAN, Items.GOLDEN_APPLE, ModGenes.moreHeartsTwo, 0.25f, true) ) allRecipes.addAll(mutationBrews) val virusBrews = listOf( VirusRecipe(ModGenes.poisonImmunity, ModGenes.poison), VirusRecipe(ModGenes.witherHit, ModGenes.poisonFour), VirusRecipe(ModGenes.witherProof, ModGenes.wither), VirusRecipe(ModGenes.strength, ModGenes.weakness), VirusRecipe(ModGenes.nightVision, ModGenes.blindness), VirusRecipe(ModGenes.speed, ModGenes.slowness), VirusRecipe(ModGenes.speedTwo, ModGenes.slownessFour), VirusRecipe(ModGenes.speedFour, ModGenes.slownessSix), VirusRecipe(ModGenes.milky, ModGenes.nausea), VirusRecipe(ModGenes.meaty, ModGenes.nausea), VirusRecipe(ModGenes.layEgg, ModGenes.nausea), VirusRecipe(ModGenes.noHunger, ModGenes.hunger), VirusRecipe(ModGenes.fireProof, ModGenes.flambe), VirusRecipe(ModGenes.luck, ModGenes.cursed), VirusRecipe(ModGenes.haste, ModGenes.miningFatigue), VirusRecipe(ModGenes.scareCreepers, ModGenes.greenDeath), VirusRecipe(ModGenes.scareSkeletons, ModGenes.unUndeath), VirusRecipe(ModGenes.scareZombies, ModGenes.unUndeath), VirusRecipe(ModGenes.resistance, ModGenes.grayDeath), VirusRecipe(ModGenes.dragonsBreath, ModGenes.whiteDeath), BlackDeathRecipe(), BrewingRecipe( viralAgentsPotionStack.ingredient, ModItems.DNA_HELIX.itemStack.setGene(ModGenes.emeraldHeart).ingredient, potionStack(ZOMBIFY_VILLAGER) ) ) allRecipes.addAll(virusBrews) for (recipe in allRecipes) { BrewingRecipeRegistry.addRecipe(recipe) } } }
5
Kotlin
0
1
11d035ab2a3f002ac6f2ebb392c242ce3d16636c
9,839
Genetics-Resequenced
MIT License
Core/src/main/kotlin/org/brightify/reactant/controller/ViewController.kt
Brightify
67,879,703
false
null
package org.brightify.reactant.controller import android.app.Activity import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import org.brightify.reactant.core.ReactantActivity import org.brightify.reactant.core.util.onChange import kotlin.properties.Delegates import kotlin.properties.ObservableProperty import kotlin.reflect.KProperty /** * TODO Fix childViewControllers * TODO Fix that ViewController hierarchy (NavigationController, TabBarController, etc.) is not correctly setup before call to activated(). * @author <a href="mailto:<EMAIL>"><NAME></a> */ open class ViewController(title: String = "") { val visibleDisposeBag = CompositeDisposable() val viewLifetimeDisposeBag = CompositeDisposable() val activeDisposeBag = CompositeDisposable() var activity: ReactantActivity get() = activity_ ?: throw IllegalStateException("activity cannot be accessed when controller is not activated.") set(value) { activity_ = value } var view: View get() = view_ ?: viewNotLoadedError() set(value) { view_ = value } var navigationController: NavigationController? by onChange<NavigationController?>(null) { _, _, _ -> if (tabBarItem != null) { navigationController?.tabBarItem = tabBarItem } if (hamburgerMenuItem != null) { navigationController?.hamburgerMenuItem = hamburgerMenuItem } } internal set var tabBarController: TabBarController? by onChange<TabBarController?>(null) { _, _, _ -> if (tabBarItem != null) { tabBarController?.updateTabBarItem(this) } if (hamburgerMenuItem != null) { tabBarController?.hamburgerMenuItem = hamburgerMenuItem } } internal set var hamburgerMenuController: HamburgerMenuController? by onChange<HamburgerMenuController?>(null) { _, _, _ -> if (tabBarItem != null) { hamburgerMenuController?.tabBarItem = tabBarItem } if (hamburgerMenuItem != null) { hamburgerMenuController?.updateMenuItem(this) } } internal set var title: String by Delegates.observable(title) { _, _, newValue -> activity.title = newValue } open var hidesBottomBarWhenPushed: Boolean = false var tabBarItem: MenuItem? by onChange<MenuItem?>(null) { _, _, _ -> navigationController?.tabBarItem = tabBarItem tabBarController?.updateTabBarItem(this) hamburgerMenuController?.tabBarItem = tabBarItem } var hamburgerMenuItem: MenuItem? by onChange<MenuItem?>(null) { _, _, _ -> navigationController?.hamburgerMenuItem = hamburgerMenuItem tabBarController?.hamburgerMenuItem = hamburgerMenuItem hamburgerMenuController?.updateMenuItem(this) } var statusBarColor: Int get() = activity.window.statusBarColor set(value) { lastStatusBarColor = value activity.window.statusBarColor = value } var screenOrientation: Int get() = activity.screenOrientation set(value) { lastScreenOrientation = value activity.screenOrientation = value activity.updateScreenOrientation() } var isVisible = false private set val isViewLoaded: Boolean get() = view_ != null val isActivated: Boolean get() = activity_ != null private var childViewControllers_ = ArrayList<ViewController>() val childViewControllers: List<ViewController> get() = childViewControllers_ private var parentViewController_: ViewController? = null val parentViewController: ViewController? get() = parentViewController_ private var initialized = false private var lastStatusBarColor: Int? = null private var lastScreenOrientation: Int? = null internal var activity_: ReactantActivity? by object: ObservableProperty<ReactantActivity?>(null) { override fun beforeChange(property: KProperty<*>, oldValue: ReactantActivity?, newValue: ReactantActivity?): Boolean { if (oldValue == newValue) { return false } activityWillChange(newValue) childViewControllers_.forEach { it.activity_ = newValue } view_ = null if (isActivated && newValue == null) { deactivated() } return true } override fun afterChange(property: KProperty<*>, oldValue: ReactantActivity?, newValue: ReactantActivity?) { if (oldValue == null && newValue != null) { activated() } activityChanged() activityDidChange(oldValue) childViewControllers_.forEach { it.activity_ = newValue } } } internal var view_: View? by object: ObservableProperty<View?>(null) { override fun beforeChange(property: KProperty<*>, oldValue: View?, newValue: View?): Boolean { if (oldValue == newValue) { return false } if (isViewLoaded && newValue == null) { if (isVisible) { viewWillDisappear() (view.parent as? ViewGroup)?.removeView(view) viewDidDisappear() } viewDestroyed() } return true } override fun afterChange(property: KProperty<*>, oldValue: View?, newValue: View?) { if (view_ != null) { if (isVisible) { when { navigationController != null -> navigationController?.invalidateChild() tabBarController != null -> tabBarController?.invalidateChild() hamburgerMenuController != null -> hamburgerMenuController?.invalidateChild() else -> activity.invalidateChildren() } } view_?.isClickable = true } } } open fun activated() { activeDisposeBag.clear() } @Deprecated(message = "Use activityDidChange instead", replaceWith = ReplaceWith(expression = "activityDidChange()")) open fun activityChanged() { } open fun activityWillChange(newActivity: Activity?) { } open fun activityDidChange(oldActivity: Activity?) { } open fun loadView() { view_ = FrameLayout(activity) viewLifetimeDisposeBag.clear() } open fun viewDidLoad() { childViewControllers.forEach(ViewController::viewDidLoad) } open fun viewWillAppear() { if (view_ == null) { loadView() viewDidLoad() } visibleDisposeBag.clear() title = title if (this !is NavigationController && this !is TabBarController && this !is HamburgerMenuController && parentViewController == null) { invalidateGlobalSettings() activity.updateScreenOrientation() } childViewControllers.forEach(ViewController::viewWillAppear) } open fun viewDidAppear() { isVisible = true childViewControllers.forEach(ViewController::viewDidAppear) } open fun viewWillDisappear() { activity.let { val inputManager = it.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(view.windowToken, 0) } childViewControllers.forEach(ViewController::viewWillDisappear) } open fun viewDidDisappear() { isVisible = false visibleDisposeBag.clear() childViewControllers.forEach(ViewController::viewDidDisappear) } open fun viewDestroyed() { viewLifetimeDisposeBag.clear() } open fun deactivated() { activeDisposeBag.clear() } /** * Returns true if event is handled. */ open fun onBackPressed(): Boolean { return false } open fun destroyViewHierarchy() { view_ = null childViewControllers.forEach(ViewController::destroyViewHierarchy) } fun addChildViewController(child: ViewController) { if (child.parentViewController != null) { child.removeFromParentViewController() } child.parentViewController_ = this if (isVisible) { child.viewWillAppear() } childViewControllers_.add(child) if (isVisible) { child.viewDidAppear() } } fun removeFromParentViewController() { parentViewController?.removeChildViewController(this) parentViewController_ = null } internal fun removeChildViewController(child: ViewController) { val childVisible = child.isVisible if (childVisible) { child.viewWillDisappear() } childViewControllers_.remove(this) if (childVisible) { child.viewDidDisappear() } child.activity_ = null } fun present(controller: ViewController, animated: Boolean = true): Observable<Unit> { return activity.present(controller, animated) } fun dismiss(animated: Boolean = true): Observable<Unit> { return activity.dismiss(animated) } fun <C: ViewController> present(controller: Observable<C>, animated: Boolean = true): Observable<C> { return activity.present(controller, animated) } fun resetRememberedStatusBarColor() { lastStatusBarColor = null } internal fun invalidateGlobalSettings() { navigationController?.invalidateGlobalSettings() tabBarController?.invalidateGlobalSettings() hamburgerMenuController?.invalidateGlobalSettings() lastStatusBarColor?.let { statusBarColor = it } lastScreenOrientation?.let { activity.screenOrientation = it } } protected fun viewNotLoadedError(): Nothing { throw IllegalStateException("view cannot be accessed before it is loaded.") } }
10
Kotlin
1
2
3066d1c003b4a01447ccfa9bc3efbe8ab52a5c81
10,315
ReactantAndroid
MIT License
welite-core/src/test/java/com/ealva/welite/db/expr/ConditionsTests.kt
ealva-com
265,936,796
false
null
/* * Copyright 2020 eAlva.com * * 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. */ @file:Suppress( "NO_EXPLICIT_VISIBILITY_IN_API_MODE_WARNING", "NO_EXPLICIT_RETURN_TYPE_IN_API_MODE_WARNING" ) package com.ealva.welite.db.expr import android.content.Context import android.os.Build import androidx.test.core.app.ApplicationProvider import com.ealva.welite.test.shared.CoroutineRule import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import com.ealva.welite.test.db.expr.CommonConditionsTests as Common @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.LOLLIPOP]) class ConditionsTests { @get:Rule var coroutineRule = CoroutineRule() @Suppress("DEPRECATION") @get:Rule var thrown: ExpectedException = ExpectedException.none() private lateinit var appCtx: Context @Before fun setup() { appCtx = ApplicationProvider.getApplicationContext() } @Test fun `test ops TRUE and FALSE`() = coroutineRule.runBlockingTest { Common.testOpsTRUEAndFALSE(appCtx, coroutineRule.testDispatcher) } @Test fun `test selecting same column`() = coroutineRule.runBlockingTest { Common.testSelectingSameColumn(appCtx, coroutineRule.testDispatcher) } @Test fun `compare with nullable column`() = coroutineRule.runBlockingTest { Common.testCompareWithNullableColumn(appCtx, coroutineRule.testDispatcher) } @Test fun `test inList`() = coroutineRule.runBlockingTest { Common.testInList(appCtx, coroutineRule.testDispatcher) } @Test fun `test notInList`() = coroutineRule.runBlockingTest { Common.testNotInList(appCtx, coroutineRule.testDispatcher) } }
0
Kotlin
0
3
7d9c5a82c289b04fad34ecc484e5fb3224f41699
2,394
welite
Apache License 2.0
app/src/main/java/com/hoangtien2k3/themoviedb/common/MyCountDownTimer.kt
hoangtien2k3
781,918,819
false
{"Kotlin": 385191}
package com.hoangtien2k3.themoviedb.common import android.os.CountDownTimer class MyCountDownTimer(startTime: Long, interval: Long, private val func: () -> Unit) : CountDownTimer(startTime, interval) { override fun onFinish() = func() override fun onTick(timer: Long) {} }
1
Kotlin
0
3
0ef347135c141cc49cb1e9d27fde6fdeedf71471
286
movie
MIT License
core/domain/src/main/kotlin/com/ngapps/phototime/core/domain/GetRecentSearchQueriesUseCase.kt
ngapp-dev
752,386,763
false
null
/* * Copyright 2023 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.domain import com.google.samples.apps.nowinandroid.core.data.model.RecentSearchQuery import com.google.samples.apps.nowinandroid.core.data.repository.RecentSearchRepository import kotlinx.coroutines.flow.Flow import javax.inject.Inject /** * A use case which returns the recent search queries. */ class GetRecentSearchQueriesUseCase @Inject constructor( private val recentSearchRepository: RecentSearchRepository, ) { operator fun invoke(limit: Int = 10): Flow<List<RecentSearchQuery>> = recentSearchRepository.getRecentSearchQueries(limit) }
12
null
2
3
bc1990bccd9674c6ac210fa72a56ef5318bf7241
1,230
phototime
Apache License 2.0
shared/src/commonMain/kotlin/com/daro/kmmtest/data/remote/HttpRoutes.kt
daroltidan
526,176,679
false
{"Kotlin": 39683, "Ruby": 1706, "Swift": 1254}
package com.daro.kmmtest.data.remote const val BASE_URL = "https://api.thedogapi.com/v1/" object HttpRoutes { const val breedsPath = "${BASE_URL}breeds" }
0
Kotlin
0
0
4f414994fca12cbbace56076313b57d86d29959b
161
kmm
Apache License 2.0
src/main/kotlin/no/nav/omsorgsdageroverforingsoknad/mellomlagring/Mellomlagring.kt
navikt
254,004,238
false
null
package no.nav.omsorgsdageroverforingsoknad.mellomlagring import io.ktor.application.call import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.locations.* import io.ktor.request.receive import io.ktor.response.respond import io.ktor.response.respondText import io.ktor.routing.Route import no.nav.omsorgsdageroverforingsoknad.general.auth.IdTokenProvider import org.slf4j.Logger import org.slf4j.LoggerFactory private val logger: Logger = LoggerFactory.getLogger("nav.soknadApis") @KtorExperimentalLocationsAPI fun Route.mellomlagringApis( mellomlagringService: MellomlagringService, idTokenProvider: IdTokenProvider ) { @Location("/mellomlagring") class mellomlagring post { _: mellomlagring -> val midlertidigSøknad = call.receive<String>() val idToken = idTokenProvider.getIdToken(call) mellomlagringService.setMellomlagring(idToken.getSubject()!!, midlertidigSøknad) call.respond(HttpStatusCode.NoContent) } get { _: mellomlagring -> val idToken = idTokenProvider.getIdToken(call) val mellomlagring = mellomlagringService.getMellomlagring(idToken.getSubject()!!) if (mellomlagring != null) { call.respondText( contentType = ContentType.Application.Json, text = mellomlagring, status = HttpStatusCode.OK ) } else { call.respondText( contentType = ContentType.Application.Json, text = "{}", status = HttpStatusCode.OK ) } } delete { _: mellomlagring -> val idToken = idTokenProvider.getIdToken(call) mellomlagringService.deleteMellomlagring(idToken.getSubject()!!) call.respond(HttpStatusCode.Accepted) } }
0
Kotlin
0
0
f29def54a3488c072bd01fbfe7469b93e6653809
1,824
omsorgsdageroverforingsoknad-api
MIT License
src/commonTest/kotlin/dev/folomeev/kotgl/matrix/matrices/mutables/ProjectionTest.kt
folomeev
487,706,128
false
null
package dev.folomeev.kotgl.matrix.matrices.mutables import dev.folomeev.kotgl.matrix.matrices.identityMat4 import dev.folomeev.kotgl.matrix.matrices.mat4 import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertEquals class ProjectionTest { private fun randomMutableMat4(): MutableMat4 = Random(1234).let { mutableMat4 { _, _ -> it.nextFloat() } } @Test fun orthogonal_defaultParams() = assertEquals( identityMat4(), orthogonal() ) @Test fun orthogonal_nonDefaultParams() = assertEquals( mat4( 2f, 0f, 0f, 0f, 0f, 2f, 0f, 0f, 0f, 0f, -2f, 0f, -3f, -7f, -11f, 1f ), orthogonal(1f, 2f, 3f, 4f, 5f, 6f) ) @Test fun orthogonalTo_defaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( identityMat4(), orthogonalTo(out = mutableMat4) ) } } @Test fun orthogonalTo_nonDefaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 2f, 0f, 0f, 0f, 0f, 2f, 0f, 0f, 0f, 0f, -2f, 0f, -3f, -7f, -11f, 1f ), orthogonalTo(1f, 2f, 3f, 4f, 5f, 6f, mutableMat4) ) } } @Test fun orthogonalSelf_defaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( identityMat4(), mutableMat4.orthogonalSelf() ) } } @Test fun orthogonalSelf_nonDefaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 2f, 0f, 0f, 0f, 0f, 2f, 0f, 0f, 0f, 0f, -2f, 0f, -3f, -7f, -11f, 1f ), mutableMat4.orthogonalSelf(1f, 2f, 3f, 4f, 5f, 6f) ) } } @Test fun perspective_nonDefaultParams() = assertEquals( mat4( 0.9152438f, 0f, 0f, 0f, 0f, 1.830487f, 0f, 0f, 0f, 0f, -7f, -1f, 0f, 0f, -24f, 0f ), perspective(1f, 2f, 3f, 4f) ) @Test fun perspectiveTo_nonDefaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 0.9152438f, 0f, 0f, 0f, 0f, 1.830487f, 0f, 0f, 0f, 0f, -7f, -1f, 0f, 0f, -24f, 0f ), perspectiveTo(1f, 2f, 3f, 4f, mutableMat4) ) } } @Test fun perspectiveSelf_nonDefaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 0.9152438f, 0f, 0f, 0f, 0f, 1.830487f, 0f, 0f, 0f, 0f, -7f, -1f, 0f, 0f, -24f, 0f ), mutableMat4.perspectiveSelf(1f, 2f, 3f, 4f) ) } } @Test fun frustum_defaultParams() = assertEquals( mat4( 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, -1f, 0f, 0f, -1f, 0f ), frustum() ) @Test fun frustumTo_defaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, -1f, 0f, 0f, -1f, 0f ), frustumTo(out = mutableMat4) ) } } @Test fun frustumSelf_defaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, -1f, 0f, 0f, -1f, 0f ), mutableMat4.frustumSelf() ) } } @Test fun frustum_nonDefaultParams() = assertEquals( mat4( 10f, 0f, 0f, 0f, 0f, 10f, 0f, 0f, 3f, 7f, -11f, -1f, 0f, 0f, -60f, 0f ), frustum(1f, 2f, 3f, 4f, 5f, 6f) ) @Test fun frustumTo_nonDefaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 10f, 0f, 0f, 0f, 0f, 10f, 0f, 0f, 3f, 7f, -11f, -1f, 0f, 0f, -60f, 0f ), frustumTo(1f, 2f, 3f, 4f, 5f, 6f, mutableMat4) ) } } @Test fun frustumSelf_nonDefaultParams() { randomMutableMat4().also { mutableMat4 -> assertEquals( mat4( 10f, 0f, 0f, 0f, 0f, 10f, 0f, 0f, 3f, 7f, -11f, -1f, 0f, 0f, -60f, 0f ), mutableMat4.frustumSelf(1f, 2f, 3f, 4f, 5f, 6f) ) } } }
0
Kotlin
0
1
e4fee9e2647579825c05c1976e15a4469dc9633e
5,406
kotgl-matrix
MIT License
app/src/main/java/com/finalproject/group14/noteapp/utility/StoreRetrieveData.kt
quynhle97
191,822,085
false
null
package com.finalproject.group14.noteapp.utility import android.content.Context import org.json.JSONArray import org.json.JSONException import org.json.JSONTokener import java.io.BufferedReader import java.io.FileInputStream import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.util.ArrayList class StoreRetrieveData(private val mContext: Context, private val mFileName: String) { @Throws(JSONException::class, IOException::class) fun saveToFile(items: ArrayList<ToDoItem>) { val fileOutputStream: FileOutputStream val outputStreamWriter: OutputStreamWriter fileOutputStream = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE) outputStreamWriter = OutputStreamWriter(fileOutputStream) outputStreamWriter.write(toJSONArray(items).toString()) outputStreamWriter.close() fileOutputStream.close() } @Throws(IOException::class, JSONException::class) fun loadFromFile(): ArrayList<ToDoItem> { val items = ArrayList<ToDoItem>() var bufferedReader: BufferedReader? = null var fileInputStream: FileInputStream? = null try { fileInputStream = mContext.openFileInput(mFileName) val builder = StringBuilder() var line: String? = null bufferedReader = BufferedReader(InputStreamReader(fileInputStream!!)) while (bufferedReader.readLine().also { line = it } != null) { builder.append(line) } val jsonArray = JSONTokener(builder.toString()).nextValue() as JSONArray for (i in 0 until jsonArray.length()) { val item = ToDoItem(jsonArray.getJSONObject(i)) items.add(item) } } catch (fnfe: FileNotFoundException) { //do nothing about it //file won't exist first time app is run } finally { bufferedReader?.close() fileInputStream?.close() } return items } companion object { @Throws(JSONException::class) fun toJSONArray(items: ArrayList<ToDoItem>): JSONArray { val jsonArray = JSONArray() for (item in items) { val jsonObject = item.toJSON() jsonArray.put(jsonObject) } return jsonArray } } }
0
Kotlin
0
0
509bf1179713f40b14598ad0030e937f2efa2212
2,479
NoteApp
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/ArrowMaximizeVertical.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.ArrowMaximizeVertical: ImageVector get() { if (_arrowMaximizeVertical != null) { return _arrowMaximizeVertical!! } _arrowMaximizeVertical = fluentIcon(name = "Filled.ArrowMaximizeVertical") { fluentPath { moveTo(15.2f, 6.2f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.4f, 0.0f) lineToRelative(-0.8f, -0.79f) verticalLineTo(9.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f) verticalLineTo(5.41f) lineToRelative(-0.8f, 0.8f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.4f, -1.42f) lineToRelative(2.5f, -2.5f) arcTo(1.0f, 1.0f, 0.0f, false, true, 12.0f, 2.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.7f, 0.3f) lineToRelative(2.5f, 2.5f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, 1.4f) close() } fluentPath { moveTo(5.0f, 11.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, 2.0f) horizontalLineToRelative(14.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 0.0f, -2.0f) horizontalLineTo(5.0f) close() } fluentPath { moveTo(12.0f, 22.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 0.7f, -0.3f) lineToRelative(2.5f, -2.5f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.4f, -1.4f) lineToRelative(-0.8f, 0.79f) verticalLineTo(15.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) verticalLineToRelative(3.59f) lineToRelative(-0.8f, -0.8f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.4f, 1.42f) lineToRelative(2.5f, 2.5f) curveToRelative(0.19f, 0.19f, 0.44f, 0.29f, 0.7f, 0.29f) } } return _arrowMaximizeVertical!! } private var _arrowMaximizeVertical: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,422
compose-fluent-ui
Apache License 2.0
app/src/main/java/za/co/varsitycollege/st10204772/opsc7312_poe/Register_Image_Upload.kt
Allana-Morris
849,370,322
false
{"Kotlin": 161039}
package za.co.varsitycollege.st10204772.opsc7312_poe import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.widget.Button import android.widget.ImageView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.FirebaseStorage import java.io.ByteArrayOutputStream class Register_Image_Upload : AppCompatActivity() { private var imageList: MutableList<Bitmap?> = MutableList(6) { null } // Six placeholders for six images private var currentImageViewIndex: Int = -1 private val storage = FirebaseStorage.getInstance().reference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_register_image_upload) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } val btnContinue = findViewById<Button>(R.id.btnContinueImage) val imageViews = listOf<ImageView>( findViewById(R.id.imgUpload1), findViewById(R.id.imgUpload2), findViewById(R.id.imgUpload3), findViewById(R.id.imgUpload4), findViewById(R.id.imgUpload5), findViewById(R.id.imgUpload6) ) val pickImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { val selectedImageUri: Uri? = result.data?.data selectedImageUri?.let { uri -> val bitmap = uriToBitmap(uri) if (currentImageViewIndex != -1 && bitmap != null) { imageViews[currentImageViewIndex].setImageResource(0) imageViews[currentImageViewIndex].setBackgroundResource(0) imageViews[currentImageViewIndex].setImageBitmap(bitmap) imageList[currentImageViewIndex] = bitmap } else { Toast.makeText(this, "Failed to load selected image", Toast.LENGTH_SHORT).show() } } } else { Toast.makeText(this, "Image selection cancelled", Toast.LENGTH_SHORT).show() } } for (i in imageViews.indices) { imageViews[i].setOnClickListener { currentImageViewIndex = i // Keep track of which ImageView is clicked val intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" pickImage.launch(intent) // Launch the image picker } } btnContinue.setOnClickListener { // Ensure the user is authenticated before uploading val userId = loggedUser.user?.Email if (userId == null) { Toast.makeText(this, "Error: User not authenticated", Toast.LENGTH_SHORT).show() return@setOnClickListener } val selectedImages = imageList.filterNotNull() // Get only selected images (non-null) if (selectedImages.isEmpty()) { Toast.makeText(this, "Please select at least one image", Toast.LENGTH_SHORT).show() return@setOnClickListener } val imageUrls = mutableListOf<String>() var imagesUploaded = 0 selectedImages.forEachIndexed { index, bitmap -> uploadImageToFirebaseStorage(bitmap, "image_$index") { downloadUrl -> if (downloadUrl != null) { imageUrls.add(downloadUrl) imagesUploaded++ // Proceed to the next activity once all images are uploaded if (imagesUploaded == selectedImages.size) { saveProfileImageUrls(imageUrls) startActivity(Intent(this, Register_Spotify_Link::class.java)) } } else { Toast.makeText(this, "Failed to upload image $index", Toast.LENGTH_SHORT).show() } } } } } private fun uriToBitmap(uri: Uri): Bitmap? { return try { contentResolver.openInputStream(uri)?.use { inputStream -> BitmapFactory.decodeStream(inputStream) } } catch (e: Exception) { e.printStackTrace() null } } private fun uploadImageToFirebaseStorage(bitmap: Bitmap, fileName: String, callback: (String?) -> Unit) { val storageRef = storage.child("profile_images/$fileName.png") val byteArrayOutputStream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream) val imageData = byteArrayOutputStream.toByteArray() val uploadTask = storageRef.putBytes(imageData) uploadTask.addOnSuccessListener { storageRef.downloadUrl.addOnSuccessListener { uri -> callback(uri.toString()) } }.addOnFailureListener { exception -> Log.e("FirebaseUpload", "Failed to upload image: ${exception.message}") callback(null) } } private fun saveProfileImageUrls(imageUrls: List<String>) { val db = FirebaseFirestore.getInstance() val userEmail = loggedUser.user?.Email // Check if the user email is not null if (userEmail == null) { Log.e("Firestore", "Error: User not authenticated") Toast.makeText(this, "User not authenticated", Toast.LENGTH_SHORT).show() return } // Query to find the document with the email field matching the logged user's email db.collection("Users") .whereEqualTo("email", userEmail) .get() .addOnCompleteListener { task -> if (task.isSuccessful) { val userDocuments = task.result if (userDocuments != null && !userDocuments.isEmpty) { // Assuming there is only one user document for the email val userDoc = userDocuments.documents[0] // Update the user's profile image URLs userDoc.reference.update(mapOf("profileImageUrls" to imageUrls)) .addOnSuccessListener { Log.d("Firestore", "Profile image URLs updated successfully") // Navigate to Register_Spotify_Link after successful upload startActivity(Intent(this, Register_Spotify_Link::class.java)) } .addOnFailureListener { e -> Log.e("Firestore", "Error updating profile image URLs", e) Toast.makeText(this, "Failed to save profile images. Try again.", Toast.LENGTH_SHORT).show() } } else { Log.e("Firestore", "No user document found for email: $userEmail") Toast.makeText(this, "No user found with the given email.", Toast.LENGTH_SHORT).show() } } else { Log.e("Firestore", "Error querying user by email", task.exception) Toast.makeText(this, "Error querying user by email: ${task.exception?.message}", Toast.LENGTH_SHORT).show() } } } }
0
Kotlin
0
1
9f1f78dd5bee8c360759465f1e6802ed08c32865
8,406
OPSC7312_POE
MIT License
src/main/kotlin/io/jawg/geojson/Feature.kt
jawg
163,869,070
false
null
package io.jawg.geojson import com.fasterxml.jackson.annotation.JsonInclude class Feature( @JsonInclude(JsonInclude.Include.ALWAYS) val geometry: Geometry<*>?, @JsonInclude(JsonInclude.Include.ALWAYS) val properties: Map<String, Any>? = null, var id: String? = null, val bbox: BBox? = null ) : GeoJsonObject("Feature")
0
null
2
5
375e81a00188d37c23c00ca473eff63c09e55036
344
geojson-jackson
Apache License 2.0
src/rider/main/kotlin/me/fornever/avaloniarider/controlmessages/AvaloniaMessages.kt
ForNeVeR
154,947,241
false
null
package me.fornever.avaloniarider.controlmessages import com.jetbrains.rd.platform.util.application import com.jetbrains.rd.platform.util.getComponent import me.fornever.avaloniarider.toUUID import java.util.* class AvaloniaMessages { companion object { fun getInstance(): AvaloniaMessages = application.getComponent() } val incomingTypeRegistry = mutableMapOf<UUID, Class<*>>() val outgoingTypeRegistry = mutableMapOf<Class<*>, UUID>() init { val declaredMessageTypes = AvaloniaMessage::class.sealedSubclasses for (type in declaredMessageTypes) { for (annotation in type.annotations) { when (annotation) { is AvaloniaIncomingMessage -> incomingTypeRegistry[annotation.uuid.toUUID()] = type.java is AvaloniaOutgoingMessage -> outgoingTypeRegistry[type.java] = annotation.uuid.toUUID() } } } } } sealed class AvaloniaMessage @AvaloniaIncomingMessage("854887cf-2694-4eb6-b499-7461b6fb96c7") data class StartDesignerSessionMessage( val sessionId: String = "" ) : AvaloniaMessage() @AvaloniaOutgoingMessage("9aec9a2e-6315-4066-b4ba-e9a9efd0f8cc") data class UpdateXamlMessage( val xaml: String = "", val assemblyPath: String = "", val xamlFileProjectPath: String = "" ) : AvaloniaMessage() data class ExceptionDetails( val exceptionType: String? = "", val message: String? = "", val lineNumber: Int? = null, val linePosition: Int? = null ) @AvaloniaIncomingMessage("b7a70093-0c5d-47fd-9261-22086d43a2e2") data class UpdateXamlResultMessage( val error: String? = "", val handle: String? = "", val exception: ExceptionDetails? = null ) : AvaloniaMessage() @AvaloniaIncomingMessage("F58313EE-FE69-4536-819D-F52EDF201A0E") data class FrameMessage( val sequenceId: Long = 0L, val format: Int = 0, val data: ByteArray = byteArrayOf(), val width: Int = 0, val height: Int = 0, val stride: Int = 0 ) : AvaloniaMessage() @AvaloniaIncomingMessage("9b47b3d8-61df-4c38-acd4-8c1bb72554ac") data class RequestViewportResizeMessage( val width: Double = 0.0, val height: Double = 0.0 ) : AvaloniaMessage() @AvaloniaIncomingMessage("53778004-78fa-4381-8ec3-176a6f2328b6") data class HtmlTransportStartedMessage( val uri: String = "" ) : AvaloniaMessage() @AvaloniaOutgoingMessage("63481025-7016-43FE-BADC-F2FD0F88609E") data class ClientSupportedPixelFormatsMessage( val formats: IntArray ) : AvaloniaMessage() @AvaloniaOutgoingMessage("7A3c25d3-3652-438D-8EF1-86E942CC96C0") data class ClientRenderInfoMessage( val dpiX: Double, val dpiY: Double ) : AvaloniaMessage() @AvaloniaOutgoingMessage("BD7A8DE6-3DB8-4A13-8583-D6D4AB189A31") data class ClientViewportAllocatedMessage( val width: Double, val height: Double, val dpiX: Double, val dpiY: Double ) : AvaloniaMessage() @AvaloniaOutgoingMessage("68014F8A-289D-4851-8D34-5367EDA7F827") data class FrameReceivedMessage( val sequenceId: Long ) : AvaloniaMessage()
36
null
8
449
f68cbcf1298c87a0bb702e1733bffbfc8be896f7
3,121
AvaloniaRider
MIT License
platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectFrameAllocator.kt
xiewenya
302,138,931
false
{"Text": 4114, "XML": 4824, "Ant Build System": 13, "Shell": 544, "Markdown": 426, "Ignore List": 80, "Git Attributes": 9, "Batchfile": 30, "SVG": 2134, "Java": 66996, "C++": 20, "HTML": 2344, "Kotlin": 6511, "DTrace": 1, "Gradle": 1091, "Java Properties": 119, "INI": 289, "JFlex": 27, "CSS": 53, "Objective-C": 19, "Groovy": 3398, "XSLT": 112, "JavaScript": 170, "JSON": 1112, "desktop": 1, "Python": 10892, "JAR Manifest": 14, "PHP": 47, "YAML": 388, "C#": 37, "Smalltalk": 17, "Diff": 129, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "CoffeeScript": 3, "JSON with Comments": 59, "EditorConfig": 220, "Vue": 17, "OpenStep Property List": 43, "Tcl": 1, "PlantUML": 4, "Protocol Buffer": 2, "fish": 1, "Dockerfile": 2, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 86, "Vim Script": 7, "Vim Snippet": 3, "Vim Help File": 2, "Gradle Kotlin DSL": 808, "Starlark": 2, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Maven POM": 1, "Java Server Pages": 8, "GraphQL": 44, "C": 46, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 6, "Microsoft Visual Studio Solution": 6, "VBScript": 1, "NSIS": 6, "TOML": 2, "Thrift": 3, "Cython": 14, "reStructuredText": 54, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.project.impl import com.intellij.configurationStore.saveSettings import com.intellij.conversion.CannotConvertException import com.intellij.diagnostic.PluginException import com.intellij.diagnostic.runActivity import com.intellij.diagnostic.runMainActivity import com.intellij.ide.RecentProjectsManager import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.SaveAndSyncHandler import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.plugins.StartupAbortedException import com.intellij.idea.SplashManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerEx import com.intellij.openapi.wm.impl.* import com.intellij.platform.ProjectSelfieUtil import com.intellij.ui.ComponentUtil import com.intellij.ui.IdeUICustomization import com.intellij.ui.ScreenUtil import com.intellij.ui.scale.ScaleContext import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.runBlocking import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import java.awt.Frame import java.awt.Image import java.io.EOFException import java.nio.file.Path import kotlin.math.min internal open class ProjectFrameAllocator(private val options: OpenProjectTask) { open fun <T : Any> run(task: () -> T?): T? { if (options.isNewProject && options.useDefaultProjectAsTemplate && options.project == null) { runBlocking { saveSettings(ProjectManager.getInstance().defaultProject, forceSavingAllSettings = true) } } return task() } /** * Project is loaded and is initialized, project services and components can be accessed. */ open fun projectLoaded(project: Project) {} open fun projectNotLoaded(error: CannotConvertException?) { error?.let { throw error } } open fun projectOpened(project: Project) {} } internal class ProjectUiFrameAllocator(private val options: OpenProjectTask, private val projectStoreBaseDir: Path) : ProjectFrameAllocator(options) { // volatile not required because created in run (before executing run task) private var frameHelper: ProjectFrameHelper? = null private var isFrameBoundsCorrect = false private var isFrameBoundsRestored = false @Volatile private var cancelled = false override fun <T : Any> run(task: () -> T?): T? { var result: T? = null val frame = invokeAndWaitIfNeeded { if (options.isNewProject && options.useDefaultProjectAsTemplate && options.project == null) { SaveAndSyncHandler.getInstance().saveSettingsUnderModalProgress(ProjectManager.getInstance().defaultProject) } createFrameIfNeeded() } val progressTask = object : Runnable { override fun run() { if (frameHelper == null) { ApplicationManager.getApplication().invokeLater { if (cancelled) { return@invokeLater } runActivity("project frame initialization") { initNewFrame(frame) } } } try { result = task() } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { if (e is StartupAbortedException || e is PluginException) { StartupAbortedException.logAndExit(e) } else { logger<ProjectFrameAllocator>().error(e) projectNotLoaded(e as? CannotConvertException) } } } } if (ApplicationManagerEx.getApplicationEx().runProcessWithProgressSynchronously(progressTask, getProgressTitle(), false, true, null, frame.rootPane, null)) { return result } // cancelled return null } @NlsContexts.ProgressTitle private fun getProgressTitle(): String { val projectName = options.projectName ?: (projectStoreBaseDir.fileName ?: projectStoreBaseDir).toString() return IdeUICustomization.getInstance().projectMessage("progress.title.project.loading.name", projectName) } @RequiresEdt private fun initNewFrame(frame: IdeFrameImpl) { if (frame.isVisible) { val frameHelper = ProjectFrameHelper(frame, null) frameHelper.init() // otherwise not painted if frame already visible frame.validate() this.frameHelper = frameHelper isFrameBoundsCorrect = true return } val options = options var frameInfo = options.frame val bounds = frameInfo?.bounds var projectWorkspaceId = options.projectWorkspaceId if (bounds == null) { val info = (RecentProjectsManager.getInstance() as? RecentProjectsManagerBase)?.getProjectMetaInfo(projectStoreBaseDir) if (info != null) { projectWorkspaceId = info.projectWorkspaceId frameInfo = info.frame } } var projectSelfie: Image? = null if (options.projectWorkspaceId != null && Registry.`is`("ide.project.loading.show.last.state", false)) { try { projectSelfie = ProjectSelfieUtil.readProjectSelfie(projectWorkspaceId!!, ScaleContext.create(frame)) } catch (e: Throwable) { if (e.cause !is EOFException) { logger<ProjectFrameAllocator>().warn(e) } } } val frameHelper = ProjectFrameHelper(frame, projectSelfie) // must be after preInit (frame decorator is required to set full screen mode) if (frameInfo?.bounds == null) { isFrameBoundsCorrect = false (WindowManager.getInstance() as WindowManagerImpl).defaultFrameInfoHelper.info?.let { restoreFrameState(frameHelper, it) } } else { isFrameBoundsCorrect = true if (isFrameBoundsRestored) { if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) { frameHelper.toggleFullScreen(true) } } else { restoreFrameState(frameHelper, frameInfo) } } if (options.sendFrameBack && frame.isAutoRequestFocus) { logger<ProjectFrameAllocator>().error("isAutoRequestFocus must be false") } frame.isVisible = true frameHelper.init() this.frameHelper = frameHelper } private fun createFrameIfNeeded(): IdeFrameImpl { val freeRootFrame = (WindowManager.getInstance() as WindowManagerImpl).removeAndGetRootFrame() if (freeRootFrame != null) { isFrameBoundsCorrect = true frameHelper = freeRootFrame return freeRootFrame.frame!! } runMainActivity("create a frame") { val preAllocated = SplashManager.getAndUnsetProjectFrame() as IdeFrameImpl? if (preAllocated == null) { isFrameBoundsRestored = options.frame?.bounds != null return createNewProjectFrame(forceDisableAutoRequestFocus = options.sendFrameBack, frameInfo = options.frame) } else { isFrameBoundsRestored = true return preAllocated } } } override fun projectLoaded(project: Project) { ApplicationManager.getApplication().invokeLater(Runnable { val frameHelper = frameHelper ?: return@Runnable val windowManager = WindowManager.getInstance() as WindowManagerImpl runActivity("project frame assigning") { val projectFrameBounds = ProjectFrameBounds.getInstance(project) if (isFrameBoundsCorrect) { // update to ensure that project stores correct frame bounds val frame = frameHelper.frame!! projectFrameBounds.markDirty(if (FrameInfoHelper.isMaximized(frame.extendedState)) null else frame.bounds) } else { val frameInfo = projectFrameBounds.getFrameInfoInDeviceSpace() if (frameInfo?.bounds != null) { restoreFrameState(frameHelper, frameInfo) } } windowManager.assignFrame(frameHelper, project) } runActivity("tool window pane creation") { ToolWindowManagerEx.getInstanceEx(project).init(frameHelper) } }, project.disposed) } override fun projectNotLoaded(error: CannotConvertException?) { cancelled = true ApplicationManager.getApplication().invokeLater { val frame = frameHelper frameHelper = null if (error != null) { ProjectManagerImpl.showCannotConvertMessage(error, frame?.frame) } if (frame != null) { Disposer.dispose(frame) } } } override fun projectOpened(project: Project) { if (options.sendFrameBack) { frameHelper?.frame?.isAutoRequestFocus = true } } } private fun restoreFrameState(frameHelper: ProjectFrameHelper, frameInfo: FrameInfo) { val deviceBounds = frameInfo.bounds val bounds = if (deviceBounds == null) null else FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(deviceBounds) val state = frameInfo.extendedState val isMaximized = FrameInfoHelper.isMaximized(state) val frame = frameHelper.frame!! if (bounds != null && isMaximized && frame.extendedState == Frame.NORMAL) { frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds) } if (bounds != null) { frame.bounds = bounds } frame.extendedState = state if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) { frameHelper.toggleFullScreen(true) } } @ApiStatus.Internal fun createNewProjectFrame(forceDisableAutoRequestFocus: Boolean, frameInfo: FrameInfo?): IdeFrameImpl { val frame = IdeFrameImpl() SplashManager.hideBeforeShow(frame) val deviceBounds = frameInfo?.bounds if (deviceBounds == null) { val size = ScreenUtil.getMainScreenBounds().size size.width = min(1400, size.width - 20) size.height = min(1000, size.height - 40) frame.size = size frame.setLocationRelativeTo(null) } else { val bounds = FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(deviceBounds) val state = frameInfo.extendedState val isMaximized = FrameInfoHelper.isMaximized(state) if (isMaximized && frame.extendedState == Frame.NORMAL) { frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds) } frame.bounds = bounds frame.extendedState = state } if (forceDisableAutoRequestFocus || (!ApplicationManager.getApplication().isActive && ComponentUtil.isDisableAutoRequestFocus())) { frame.isAutoRequestFocus = false } frame.minimumSize = Dimension(340, frame.minimumSize.height) return frame }
1
null
1
1
e1c5d097ee05bdb7a7352becb9037f1094de7817
11,005
intellij-community
Apache License 2.0
composeApp/src/commonMain/kotlin/jp/albites/btree/view/screen/theme/ThemeScreen.kt
kaleidot725
665,943,634
false
{"Kotlin": 105825, "Batchfile": 2675, "Ruby": 1769, "Swift": 622}
package jp.albites.btree.view.screen.theme import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.DarkMode import androidx.compose.material.icons.filled.LightMode import androidx.compose.material.icons.filled.Sync import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import cafe.adriel.lyricist.LocalStrings import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import jp.albites.btree.model.domain.Theme import jp.albites.btree.util.getScreenModel import jp.albites.btree.view.screen.setting.component.SettingCheckItem class ThemeScreen : Screen { @OptIn(ExperimentalMaterial3Api::class) @Composable override fun Content() { val navigator = LocalNavigator.currentOrThrow val screenModel = getScreenModel<ThemeScreenModel>() val selectedTheme by screenModel.selectedTheme.collectAsState() val strings = LocalStrings.current Scaffold( topBar = { TopAppBar( title = { Text(strings.settingThemeTitle) }, navigationIcon = { IconButton(onClick = { navigator.pop() }) { Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null) } }, ) }, ) { Column(modifier = Modifier.padding(it)) { SettingCheckItem( title = strings.settingThemeLight, icon = Icons.Default.LightMode, checked = selectedTheme == Theme.LIGHT, onCheckedChange = { screenModel.selectTheme(Theme.LIGHT) }, iconDescription = "LightMode", modifier = Modifier .fillMaxWidth() .height(64.dp) .padding(12.dp), ) Divider() SettingCheckItem( title = strings.settingThemeDark, icon = Icons.Default.DarkMode, checked = selectedTheme == Theme.DARK, onCheckedChange = { screenModel.selectTheme(Theme.DARK) }, iconDescription = "DarkMode", modifier = Modifier .fillMaxWidth() .height(64.dp) .padding(12.dp), ) Divider() SettingCheckItem( title = strings.settingThemeSync, icon = Icons.Default.Sync, checked = selectedTheme == Theme.SYSTEM, onCheckedChange = { screenModel.selectTheme(Theme.SYSTEM) }, iconDescription = "Sync", modifier = Modifier .fillMaxWidth() .height(64.dp) .padding(12.dp), ) } } } }
0
Kotlin
0
3
d6b9fc60d668a23049c02315b2e2fa218e638ee1
3,813
BTree
MIT License
vscode/src/jsMain/kotlin/vscode/SourceControlResourceThemableDecorations.kt
lppedd
761,812,661
false
{"Kotlin": 1887051}
package vscode import kotlin.ts.Union3 /** * The theme-aware decorations for a [SourceControlResourceState]. */ external interface SourceControlResourceThemableDecorations { /** * The icon path for a specific [SourceControlResourceState]. */ val iconPath: Union3<String, Uri, ThemeIcon>? }
0
Kotlin
0
3
0f493d3051afa3de2016e5425a708c7a9ed6699a
304
kotlin-externals
MIT License
src/main/kotlin/com/pedrorodrepo/gamerepo/service/ClientConsumeService.kt
pedrorodrepo
722,278,123
false
{"Kotlin": 7882}
package com.pedrorodrepo.gamerepo.service import com.google.gson.Gson import com.pedrorodrepo.gamerepo.model.InfoGame import java.net.URI import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse class ClientConsumeService { fun searchGame(search: String): InfoGame { val baseAPIUrl = "https://www.cheapshark.com/api/1.0/games?id=" val fullUrl = "$baseAPIUrl$search" val client: HttpClient = HttpClient.newHttpClient() val request = HttpRequest.newBuilder() .uri(URI.create(fullUrl)) .build() val response = client .send(request, HttpResponse.BodyHandlers.ofString()) val jsonBody = response.body() val gson = Gson() return gson.fromJson(jsonBody, InfoGame::class.java) } }
0
Kotlin
0
0
3802d0aea22b4432886f3b463b499ddb9827a05c
830
GameRepo
MIT License
ldk-bukkit/ldk-bukkit-gui/src/main/kotlin/com/lgou2w/ldk/bukkit/gui/GuiBuilder.kt
fossabot
219,468,022
true
{"Kotlin": 1346841}
/* * Copyright (C) 2016-2019 The lgou2w <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lgou2w.ldk.bukkit.gui import com.lgou2w.ldk.bukkit.item.ItemBuilder import com.lgou2w.ldk.common.Applicator import com.lgou2w.ldk.common.Builder import com.lgou2w.ldk.common.Consumer import com.lgou2w.ldk.common.letIfNotNull import org.bukkit.Material import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryCloseEvent import org.bukkit.event.inventory.InventoryOpenEvent import org.bukkit.inventory.ItemStack import org.bukkit.plugin.Plugin /** * @since LDK 0.1.7-rc5 */ interface GuiBuilder : Builder<Gui> { fun parent(parent: Gui?): GuiBuilder fun opened(block: ((gui: Gui, event: InventoryOpenEvent) -> Unit)?): GuiBuilder fun closed(block: ((gui: Gui, event: InventoryCloseEvent) -> Unit)?): GuiBuilder fun clicked(block: ((gui: Gui, event: InventoryClickEvent) -> Unit)?): GuiBuilder fun allowMove(flag: Boolean): GuiBuilder fun property(key: String, value: Any): GuiBuilder @Throws(IllegalStateException::class) fun button(): ButtonBuilder @Throws(IllegalArgumentException::class) fun button(index: Int): ButtonBuilder @Throws(IllegalArgumentException::class) fun button(x: Int, y: Int): ButtonBuilder @Throws(IllegalArgumentException::class) fun buttonSame(indexes: IntArray): ButtonBuilder @Throws(IllegalArgumentException::class) fun buttonSame(vararg indexRanges: IntProgression): ButtonBuilder companion object { @JvmStatic fun of(plugin: Plugin, type: GuiType, title: String = type.title): GuiBuilder = SimpleGuiBuilder(plugin, type, title) /** * @since LDK 0.1.7-rc6 */ @JvmStatic fun of(gui: Gui): GuiBuilder = SimpleGuiBuilder(gui) } } /** * @since LDK 0.1.7-rc5 */ open class SimpleGuiBuilder(protected open val gui: Gui) : GuiBuilder { constructor(plugin: Plugin, type: GuiType, title: String = type.title) : this(SimpleGui(plugin, type, title)) override fun build(): Gui = gui override fun parent(parent: Gui?): GuiBuilder { gui.parent = parent return this } override fun opened(block: ((gui: Gui, event: InventoryOpenEvent) -> Unit)?): GuiBuilder { gui.onOpened = block return this } override fun closed(block: ((gui: Gui, event: InventoryCloseEvent) -> Unit)?): GuiBuilder { gui.onClosed = block return this } override fun clicked(block: ((gui: Gui, event: InventoryClickEvent) -> Unit)?): GuiBuilder { gui.onClicked = block return this } override fun allowMove(flag: Boolean): GuiBuilder { gui.isAllowMove = flag return this } override fun property(key: String, value: Any): GuiBuilder { gui.setProperty(key, value) return this } protected open fun buttonBuilder(origin: GuiBuilder, button: Button): ButtonBuilder { return SimpleButtonBuilder(origin as SimpleGuiBuilder, button) } override fun button(): ButtonBuilder = buttonBuilder(this, gui.addButton()) override fun button(index: Int): ButtonBuilder = buttonBuilder(this, gui.setButton(index)) override fun button(x: Int, y: Int): ButtonBuilder = buttonBuilder(this, gui.setButton(x, y)) override fun buttonSame(indexes: IntArray): ButtonBuilder = buttonBuilder(this, gui.setSameButton(indexes)) override fun buttonSame(vararg indexRanges: IntProgression): ButtonBuilder { val indexes = indexRanges.flatMap { it.toList() } return buttonSame(indexes.toIntArray()) } } /** * @since LDK 0.1.7-rc5 */ interface ButtonBuilder : Builder<Button> { val button : Button fun origin(): GuiBuilder fun stack(stack: ItemStack?): ButtonBuilder fun stack(material: Material): ButtonBuilder fun stack(stack: ItemStack?, builder: Applicator<ItemBuilder>): ButtonBuilder fun stack(material: Material, builder: Applicator<ItemBuilder>): ButtonBuilder fun stackModify(modifier: Applicator<ItemBuilder>): ButtonBuilder fun clicked(block: Consumer<ButtonEvent>?): ButtonBuilder fun clickedAndCancel(block: Consumer<ButtonEvent>): ButtonBuilder fun clickedAndClosed(block: Consumer<ButtonEvent>): ButtonBuilder fun clickedGotoPrevious(): ButtonBuilder fun clickedGotoNext(): ButtonBuilder } /** * @since LDK 0.1.7-rc5 */ open class SimpleButtonBuilder( protected open val origin: SimpleGuiBuilder, override val button: Button ) : ButtonBuilder { override fun build(): Button = button override fun origin(): GuiBuilder = origin override fun stack(stack: ItemStack?): ButtonBuilder { button.stack = stack return this } override fun stack(material: Material): ButtonBuilder { button.stack = ItemStack(material) return this } override fun stack(stack: ItemStack?, builder: Applicator<ItemBuilder>): ButtonBuilder { button.stack = stack.letIfNotNull { ItemBuilder.of(it).also(builder).build() } return this } override fun stack(material: Material, builder: Applicator<ItemBuilder>): ButtonBuilder { button.stack = ItemBuilder.of(material).also(builder).build() return this } override fun stackModify(modifier: Applicator<ItemBuilder>): ButtonBuilder { button.stackModify(modifier) return this } override fun clicked(block: Consumer<ButtonEvent>?): ButtonBuilder { button.onClicked = block return this } override fun clickedAndCancel(block: Consumer<ButtonEvent>): ButtonBuilder { button.onClicked = ButtonEvent.cancelThen(block) return this } override fun clickedAndClosed(block: Consumer<ButtonEvent>): ButtonBuilder { button.onClicked = ButtonEvent.cancelThenConsumeAndClose(block) return this } override fun clickedGotoPrevious(): ButtonBuilder { button.onClicked = PageableGui.previousPage() return this } override fun clickedGotoNext(): ButtonBuilder { button.onClicked = PageableGui.nextPage() return this } }
0
null
0
0
906641be162efb3a3fa36a6256ae332aa4c4fdc5
6,755
ldk
Apache License 2.0
app/src/main/java/com/example/githubapp/common/di/AppModule.kt
Gaganpreet1993
766,262,536
false
{"Kotlin": 21253}
package com.example.githubapp.common.di import com.example.githubapp.domain.RepoInteractor import com.example.githubapp.domain.RepoInteractorImpl import com.example.githubapp.domain.UserInteractor import com.example.githubapp.domain.UserInteractorImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent @Module @InstallIn(ViewModelComponent::class) interface AppModule { @Binds fun bindUserInteractor(impl: UserInteractorImpl): UserInteractor @Binds fun bindRepoInteractor(impl: RepoInteractorImpl): RepoInteractor }
0
Kotlin
0
0
68a311f427ab7dc1b97dc40bec3fc195fe90cca8
611
github_app
MIT License
core/src/commonMain/kotlin/com/maxkeppeker/sheets/core/utils/TestTags.kt
maxkeppeler
523,345,776
false
null
/* * Copyright (C) 2022-2023. <NAME> (https://www.maxkeppeler.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.maxkeppeker.sheets.core.utils /** * Test tags that used for the compose UI tests. */ object TestTags { /* * Test tags for CoreView */ const val DIALOG_BASE_CONTAINER = "dialog_base_container" const val DIALOG_BASE_CONTENT = "dialog_base_content" const val FRAME_BASE_CONTENT = "frame_base_content" const val FRAME_BASE_HEADER = "frame_base_header" const val FRAME_BASE_NO_HEADER = "frame_base_no_header" const val FRAME_BASE_BUTTONS = "frame_base_buttons" const val FRAME_BASE_NO_BUTTONS = "frame_base_no_buttons" const val HEADER_DEFAULT = "header_default" const val HEADER_DEFAULT_TEXT = "header_default_text" const val HEADER_DEFAULT_ICON = "header_default_icon" const val BUTTON_EXTRA = "button_extra" const val BUTTON_POSITIVE = "button_positive" const val BUTTON_NEGATIVE = "button_negative" const val BUTTON_ICON = "button_icon" /* * Test tags for CalendarView */ const val CALENDAR_DATE_SELECTION = "calendar_date" /* * Test tags for ColorView */ const val COLOR_TEMPLATE_SELECTION = "color_template" const val COLOR_CUSTOM_SELECTION = "color_custom" const val COLOR_CUSTOM_VALUE_SLIDER = "color_custom_value_slider" /* * Test tags for ClockView */ const val CLOCK_12_HOUR_FORMAT = "12_hour_format" /* * Test tags for ClockView & DurationView */ const val KEYBOARD_KEY = "keyboard_key" /* * Test tags for EmojiView */ const val EMOJI_SELECTION = "emoji_selection" const val EMOJI_CATEGORY = "emoji_category" const val EMOJI_CATEGORY_TAB = "emoji_category_tab" /* * Test tags for DateTimeView */ const val DATE_TIME_VALUE_SELECTION = "date_time_value_selection" const val DATE_TIME_VALUE_CONTAINER_SELECTION = "date_time_value_container_selection" /* * Test tags for InputView */ const val LIST_VIEW_SELECTION = "list_view_selection" const val OPTION_VIEW_SELECTION = "option_view_selection" /* * Test tags for InfoView */ const val INFO_BODY_DEFAULT = "info_body_default" const val INFO_BODY_DEFAULT_TEXT = "info_body_default_text" /* * Test tags for StateView */ const val STATE_LOADING_CIRCULAR = "state_loading_circular" const val STATE_LOADING_LINEAR = "state_loading_linear" const val STATE_LOADING_LABEL_PERCENTAGE = "state_loading_label_percentage" const val STATE_FAILURE = "state_failure" const val STATE_SUCCESS = "state_success" const val STATE_VIEW_LABEL_TEXT = "state_view_label_text" /* * Test tags for InputView */ const val INPUT_ITEM_HEADER = "input_header" const val INPUT_ITEM_HEADER_TITLE = "input_header_title" const val INPUT_ITEM_HEADER_BODY = "input_header_body" const val INPUT_ITEM_HEADER_ICON = "input_header_icon" const val INPUT_ITEM_OVERLAY = "input_overlay" const val INPUT_ITEM_RADIOBUTTON_GROUP = "input_button_group" const val INPUT_ITEM_RADIOBUTTON_GROUP_ITEM = "input_button_group_item" const val INPUT_ITEM_RADIOBUTTON_GROUP_ITEM_RADIOBUTTON = "input_button_group_item_radio" const val INPUT_ITEM_RADIOBUTTON_GROUP_ITEM_TEXT = "input_button_group_item_text" const val INPUT_ITEM_CHECKBOX_GROUP = "input_checkbox_group" const val INPUT_ITEM_CHECKBOX_GROUP_ITEM = "input_checkbox_group_item" const val INPUT_ITEM_CHECKBOX_GROUP_ITEM_CHECKBOX = "input_checkbox_group_item_checkbox" const val INPUT_ITEM_CHECKBOX_GROUP_ITEM_TEXT = "input_checkbox_group_item_text" const val INPUT_ITEM_CHECKBOX = "input_checkbox" const val INPUT_ITEM_CHECKBOX_CHECKBOX = "input_checkbox_checkbox" const val INPUT_ITEM_CHECKBOX_TEXT = "input_checkbox_text" const val INPUT_ITEM_TEXT_FIELD = "input_text_field" const val INPUT_ITEM_TEXT_FIELD_TYPE = "input_text_field_type" const val INPUT_ITEM_TEXT_FIELD_ERROR_TEXT = "input_text_field_error_text" const val INPUT_ITEM_TEXT = "input_text" const val INPUT_ITEM_TEXT_TEXT = "input_text_text" const val INPUT_ITEM_DIVIDER = "input_divider" }
8
null
9
816
2af41f317228e982e261522717b6ef5838cd8b58
4,794
sheets-compose-dialogs
Apache License 2.0