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/hfad/finalproject_team_temp/ui/dashboard/DashboardFragment.kt
slythe6
732,185,961
false
{"Kotlin": 53965}
package com.hfad.finalproject_team_temp.ui.dashboard import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.hfad.finalproject_team_temp.R import com.hfad.finalproject_team_temp.databinding.FragmentDashboardBinding import com.hfad.finalproject_team_temp.databinding.FragmentQuizzesBinding import com.hfad.finalproject_team_temp.ui.quizzes.QuizzesViewModel import androidx.fragment.app.activityViewModels class DashboardFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private val dashboardViewModel: DashboardViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { //val galleryViewModel = //ViewModelProvider(this).get(DashboardViewModel::class.java) _binding = FragmentDashboardBinding.inflate(inflater, container, false) val root: View = binding.root /* val textView: TextView = binding.textGallery galleryViewModel.text.observe(viewLifecycleOwner) { textView.text = it } */ val textView: TextView = binding.textGallery dashboardViewModel.welcomeMessage.observe(viewLifecycleOwner) { message -> textView.text = message } return root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val username = arguments?.getString("username") if (dashboardViewModel.welcomeMessage.value.isNullOrEmpty()) { username?.let { dashboardViewModel.setWelcomeMessage(it)} } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
0
595eca7edaed8faaecf4924eda0d1e58c0fda836
2,059
LearnIt
The Unlicense
core/src/main/kotlin/materialui/components/listsubheader/listSubheader.kt
taylor009
238,072,665
true
{"Kotlin": 331539}
package materialui.components.listsubheader import kotlinx.html.LI import kotlinx.html.Tag import kotlinx.html.TagConsumer import materialui.components.StandardProps import materialui.components.listsubheader.enums.ListSubheaderStyle import react.RBuilder import react.RClass @JsModule("@material-ui/core/ListSubheader") private external val listSubheaderModule: dynamic external interface ListSubheaderProps : StandardProps { var color: String? var disableGutters: Boolean? var disableSticky: Boolean? var inset: Boolean? } @Suppress("UnsafeCastFromDynamic") private val listSubheaderComponent: RClass<ListSubheaderProps> = listSubheaderModule.default fun RBuilder.listSubheader(vararg classMap: Pair<ListSubheaderStyle, String>, block: ListSubheaderElementBuilder<LI>.() -> Unit) = child(ListSubheaderElementBuilder(listSubheaderComponent, classMap.toList()) { LI(mapOf(), it) }.apply(block).create()) fun <T: Tag> RBuilder.listSubheader(vararg classMap: Pair<ListSubheaderStyle, String>, factory: (TagConsumer<Unit>) -> T, block: ListSubheaderElementBuilder<T>.() -> Unit) = child(ListSubheaderElementBuilder(listSubheaderComponent, classMap.toList(), factory).apply(block).create())
0
null
0
0
2f791e239447519131573369f50c7895d60539e0
1,221
kotlin-material-ui
MIT License
app/src/main/java/com/luteapp/timerpx/database/TimerViewModel.kt
anfreelancer
406,802,148
false
{"Kotlin": 17820, "Java": 11920}
package com.luteapp.timerpx.database import android.app.Application import androidx.lifecycle.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class TimerViewModel(application: Application) : AndroidViewModel(application) { private val repository: TimerRepository val allTimers: LiveData<List<TimerDef>> init { val timerDao = Database.getDatabase(application.applicationContext).timerDao() repository = TimerRepository(timerDao) allTimers = repository.allTimers } fun insert(timerDef: TimerDef) = viewModelScope.launch(Dispatchers.IO) { repository.insert(timerDef) } fun delete(timerDef: TimerDef) = viewModelScope.launch(Dispatchers.IO) { repository.delete(timerDef) } class Factory constructor(private val application: Application) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { return if (modelClass.isAssignableFrom(TimerViewModel::class.java)) { TimerViewModel(this.application) as T } else { throw IllegalArgumentException("ViewModel not found") } } } }
0
Kotlin
0
0
8a272b349df671a7405bc7b02971f252e626afc2
1,237
timerx
Apache License 2.0
app/src/main/java/jp/cordea/gene/ListItemDecoration.kt
CORDEA
93,741,813
false
null
package jp.cordea.gene import android.content.Context import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View /** * Created by <NAME> on 2017/06/06. */ class ListItemDecoration(private val context: Context) : RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { view?.let { parent?.let { parent -> val lp = it.layoutParams as RecyclerView.LayoutParams lp.topMargin = if (parent.getChildAdapterPosition(it) == 0) { context.resources.getDimension(R.dimen.card_margin).toInt() } else { 0 } } } } }
0
Kotlin
0
0
a048af5f1e83f7a847fee71f60ba94b276d79dab
842
Gene
Apache License 2.0
app/src/main/java/com/puyo/kapas/feature_kapas/presentation/home/HomeViewModel.kt
fanggadewangga
543,134,542
false
{"Kotlin": 332814}
package com.puyo.kapas.feature_kapas.presentation.home import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.puyo.kapas.feature_kapas.data.repository.Repository import com.puyo.kapas.feature_kapas.data.source.remote.api.response.job.JobListResponse import com.puyo.kapas.feature_kapas.data.source.remote.api.response.user.UserResponse import kotlinx.coroutines.delay import kotlinx.coroutines.launch class HomeViewModel(private val repository: Repository): ViewModel() { var jobs: MutableState<List<JobListResponse>> = mutableStateOf(ArrayList()) var user:MutableState<UserResponse?> = mutableStateOf(null) var query = mutableStateOf("") var isLoading = mutableStateOf(false) fun searchJobs(query: String) { viewModelScope.launch { isLoading.value = true val result = repository.fetchSearchJobs(query).data if (result != null) jobs.value = result delay(1500L) isLoading.value = false } } init { viewModelScope.launch { isLoading.value = true val jobsResult = repository.fetchJobs() val userResult = repository.fetchUserDetail("1") if (jobsResult != null) { jobs.value = jobsResult } if (userResult != null) user.value = userResult delay(3000L) isLoading.value = false } } }
0
Kotlin
1
2
4cc893485a6dffe678471cc0b9d62ac84413b2ee
1,571
Kapas
Apache License 2.0
native/frontend/src/org/jetbrains/kotlin/resolve/konan/diagnostics/ErrorsNative.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.resolve.konan.diagnostics import com.intellij.psi.PsiElement import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.diagnostics.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement object ErrorsNative { @JvmField val THROWS_LIST_EMPTY = DiagnosticFactory0.create<KtElement>(Severity.ERROR) @JvmField val INCOMPATIBLE_THROWS_OVERRIDE = DiagnosticFactory1.create<KtElement, DeclarationDescriptor>(Severity.ERROR) @JvmField val INCOMPATIBLE_THROWS_INHERITED = DiagnosticFactory1.create<KtDeclaration, Collection<DeclarationDescriptor>>(Severity.ERROR) @JvmField val MISSING_EXCEPTION_IN_THROWS_ON_SUSPEND = DiagnosticFactory1.create<KtElement, FqName>(Severity.ERROR) @JvmField val INAPPLICABLE_SHARED_IMMUTABLE_PROPERTY = DiagnosticFactory0.create<KtElement>(Severity.ERROR) @JvmField val INAPPLICABLE_SHARED_IMMUTABLE_TOP_LEVEL = DiagnosticFactory0.create<KtElement>(Severity.ERROR) @JvmField val VARIABLE_IN_SINGLETON_WITHOUT_THREAD_LOCAL = DiagnosticFactory0.create<KtElement>(Severity.INFO) @JvmField val INAPPLICABLE_THREAD_LOCAL = DiagnosticFactory0.create<KtElement>(Severity.ERROR) @JvmField val INAPPLICABLE_THREAD_LOCAL_TOP_LEVEL = DiagnosticFactory0.create<KtElement>(Severity.ERROR) @JvmField val VARIABLE_IN_ENUM = DiagnosticFactory0.create<KtElement>(Severity.INFO) @JvmField val INVALID_CHARACTERS_NATIVE = DiagnosticFactoryForDeprecation1.create<PsiElement, String>(LanguageFeature.ProhibitInvalidCharsInNativeIdentifiers) init { Errors.Initializer.initializeFactoryNames(ErrorsNative::class.java) } }
157
Kotlin
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
2,024
kotlin
Apache License 2.0
correlation/core/test/utils/src/main/kotlin/org/sollecitom/chassis/correlation/core/test/utils/access/AccessTestFactory.kt
sollecitom
669,483,842
false
{"Kotlin": 676990}
package org.sollecitom.chassis.correlation.core.test.utils.access import org.sollecitom.chassis.core.utils.CoreDataGenerator import org.sollecitom.chassis.correlation.core.domain.access.Access import org.sollecitom.chassis.correlation.core.domain.access.actor.Actor import org.sollecitom.chassis.correlation.core.domain.access.authorization.AuthorizationPrincipal import org.sollecitom.chassis.correlation.core.domain.access.origin.Origin import org.sollecitom.chassis.correlation.core.test.utils.access.actor.direct import org.sollecitom.chassis.correlation.core.test.utils.access.authorization.create import org.sollecitom.chassis.correlation.core.test.utils.access.authorization.withoutRoles import org.sollecitom.chassis.correlation.core.test.utils.access.origin.create context(CoreDataGenerator) fun Access.Companion.unauthenticated(origin: Origin = Origin.create(), authorization: AuthorizationPrincipal = AuthorizationPrincipal.withoutRoles()): Access.Unauthenticated = Access.Unauthenticated(origin, authorization) context(CoreDataGenerator) fun Access.Unauthenticated.Companion.create(origin: Origin = Origin.create(), authorization: AuthorizationPrincipal = AuthorizationPrincipal.withoutRoles()): Access.Unauthenticated = Access.Unauthenticated(origin, authorization) context(CoreDataGenerator) fun Access.Companion.authenticated(actor: Actor = Actor.direct(), origin: Origin = Origin.create(), authorization: AuthorizationPrincipal = AuthorizationPrincipal.create()): Access.Authenticated = Access.Authenticated(actor, origin, authorization) context(CoreDataGenerator) fun Access.Authenticated.Companion.authenticated(actor: Actor = Actor.direct(), origin: Origin = Origin.create(), authorization: AuthorizationPrincipal = AuthorizationPrincipal.create()): Access.Authenticated = Access.Authenticated(actor, origin, authorization)
0
Kotlin
0
1
c967fe32c1133e98cf3bfc4d1990ced79da0c395
1,847
chassis
MIT License
idea/idea-jps-common/src/org/jetbrains/kotlin/config/CompilerSettings.kt
ppamorim
72,680,282
true
null
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.config class CompilerSettings { var additionalArguments: String = DEFAULT_ADDITIONAL_ARGUMENTS var scriptTemplates: String = "" var scriptTemplatesClasspath: String = "" var copyJsLibraryFiles: Boolean = true var outputDirectoryForJsLibraryFiles: String = DEFAULT_OUTPUT_DIRECTORY constructor() constructor(settings: CompilerSettings) { additionalArguments = settings.additionalArguments scriptTemplates = settings.scriptTemplates scriptTemplatesClasspath = settings.scriptTemplatesClasspath copyJsLibraryFiles = settings.copyJsLibraryFiles outputDirectoryForJsLibraryFiles = settings.outputDirectoryForJsLibraryFiles } companion object { private val DEFAULT_ADDITIONAL_ARGUMENTS = "-version" private val DEFAULT_OUTPUT_DIRECTORY = "lib" } }
0
Java
0
0
6a3597fa0f33f52e9e8c168cde02a635e0be2b6e
1,473
kotlin
Apache License 2.0
fabric/src/main/kotlin/io/github/techtastic/tisvs/fabric/TISVSFabric.kt
TechTastic
868,461,476
false
{"Kotlin": 38190, "Java": 2448}
package io.github.techtastic.tisvs.fabric import io.github.techtastic.tisvs.TISVS.init import io.github.techtastic.tisvs.TISVS.initClient import net.fabricmc.api.ClientModInitializer import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import net.fabricmc.api.ModInitializer import org.valkyrienskies.mod.fabric.common.ValkyrienSkiesModFabric object TISVSFabric: ModInitializer { override fun onInitialize() { // force VS2 to load before TIS: VS ValkyrienSkiesModFabric().onInitialize() init() } @Environment(EnvType.CLIENT) class Client : ClientModInitializer { override fun onInitializeClient() { initClient() } } }
0
Kotlin
0
0
bc1671c056243d3361c1e133db3b412f978cc395
709
TIS-VS
Apache License 2.0
src/main/kotlin/com/freewill/repository/jpa/RecommendationRepository.kt
free-wiII
685,840,987
false
{"Kotlin": 117508, "HTML": 76338}
package com.freewill.repository.jpa import com.freewill.entity.Cafe import com.freewill.entity.Recommendation import com.freewill.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface RecommendationRepository : JpaRepository<Recommendation, Long> { fun findByUserAndCafe(user: User, cafe: Cafe): Recommendation?; }
0
Kotlin
0
2
1dfee10b9bcd740abaaa418e9be71e11bf11f4da
411
synergy-be
MIT License
core/src/commonMain/kotlin/dev/carlsen/flagkit/flagicons/TT.kt
acarlsen
722,319,804
false
{"Kotlin": 1629077, "Batchfile": 2673, "Swift": 590}
package dev.carlsen.flagkit.flagicons import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush.Companion.linearGradient import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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 dev.carlsen.flagkit.FlagIcons val FlagIcons.TT: ImageVector get() { if (_tt != null) { return _tt!! } _tt = Builder(name = "Tt", defaultWidth = 21.0.dp, defaultHeight = 15.0.dp, viewportWidth = 21.0f, viewportHeight = 15.0f).apply { path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start = Offset(10.5f,0.0f), end = Offset(10.5f,15.0f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(0.0f, 0.0f) horizontalLineToRelative(21.0f) verticalLineToRelative(15.0f) horizontalLineToRelative(-21.0f) close() } path(fill = linearGradient(0.0f to Color(0xFFED233C), 1.0f to Color(0xFFCC162C), start = Offset(10.495501f,0.0046f), end = Offset(10.495501f,15.0046f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(-0.0045f, 0.0046f) horizontalLineToRelative(21.0f) verticalLineToRelative(15.0f) horizontalLineToRelative(-21.0f) close() } path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0), start = Offset(10.749949f,-4.0607f), end = Offset(10.749949f,19.070099f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(-1.5f, -1.0f) lineToRelative(7.1437f, -3.0607f) lineToRelative(15.1003f, 17.9959f) lineToRelative(2.2559f, 2.0649f) lineToRelative(-7.6527f, 3.07f) lineToRelative(-14.8247f, -17.6674f) close() } path(fill = linearGradient(0.0f to Color(0xFF262626), 1.0f to Color(0xFF0D0D0D), start = Offset(10.495501f,-5.2099996f), end = Offset(10.495501f,20.2192f)), stroke = SolidColor(Color(0x00000000)), strokeLineWidth = 1.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(17.9008f, 20.2192f) lineToRelative(-18.6408f, -22.2153f) lineToRelative(3.8302f, -3.2139f) lineToRelative(18.6408f, 22.2153f) lineToRelative(-3.8302f, 3.2139f) close() } } .build() return _tt!! } private var _tt: ImageVector? = null
0
Kotlin
1
21
a630a5cdbb9749db3d83ad3b751740da42d84e16
3,600
kmp-flagkit
MIT License
ServerApplication/app/src/main/java/com/chi/serverapplication/aidl/Book.kt
Chi-Account
287,475,924
false
null
package com.chi.serverapplication.aidl import android.os.Parcel import android.os.Parcelable data class Book(val name: String) : Parcelable { constructor(parcel: Parcel) : this(parcel.readString() ?: "") override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeString(name) } override fun describeContents(): Int = 0 companion object CREATOR : Parcelable.Creator<Book> { override fun createFromParcel(parcel: Parcel): Book { return Book(parcel) } override fun newArray(size: Int): Array<Book?> { return arrayOfNulls(size) } } }
0
Kotlin
0
0
455ca512d4caa6fa17213c7aaa178648c115edfa
632
IPC
Apache License 2.0
meistercharts-demos/meistercharts-demos/src/commonMain/kotlin/com/meistercharts/demo/descriptors/TankDemoDescriptor.kt
Neckar-IT
599,079,962
false
null
/** * Copyright 2023 Neckar IT GmbH, Mössingen, Germany * * 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.meistercharts.demo.descriptors import com.meistercharts.algorithms.layers.AbstractLayer import com.meistercharts.algorithms.layers.LayerPaintingContext import com.meistercharts.algorithms.layers.LayerType import com.meistercharts.algorithms.layers.addClearBackground import com.meistercharts.algorithms.paintable.ObjectFit import com.meistercharts.canvas.paintable.TankPaintable import com.meistercharts.canvas.saved import com.meistercharts.demo.ChartingDemo import com.meistercharts.demo.ChartingDemoDescriptor import com.meistercharts.demo.DemoCategory import com.meistercharts.demo.PredefinedConfiguration import com.meistercharts.demo.configurableDouble import com.meistercharts.model.Direction /** * A demo for the [TankPaintable] */ class TankDemoDescriptor : ChartingDemoDescriptor<Nothing> { override val name: String = "Water Tank" override val category: DemoCategory = DemoCategory.Paintables override fun createDemo(configuration: PredefinedConfiguration<Nothing>?): ChartingDemo { return ChartingDemo { val tankPaintable = TankPaintable() meistercharts { configure { layers.addClearBackground() layers.addLayer(object : AbstractLayer() { override val type: LayerType = LayerType.Content override fun paint(paintingContext: LayerPaintingContext) { val gc = paintingContext.gc val targetTankSize = tankPaintable.size.scaleToHeight(800.0) gc.saved { tankPaintable.paintInBoundingBox(paintingContext, 5.0, 5.0, Direction.TopLeft, 0.0, 0.0, targetTankSize.width, targetTankSize.height, ObjectFit.Contain) } } }) } configurableDouble("Fill level", tankPaintable::fillLevel) { min = 0.0 max = 1.0 } } } } }
0
Kotlin
0
4
af73f0e09e3e7ac9437240e19974d0b1ebc2f93c
2,475
meistercharts
Apache License 2.0
compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/IncrementalCachesManager.kt
haaami01
364,875,385
true
{"Kotlin": 69686329, "Java": 7040677, "Swift": 4240529, "C": 2633594, "C++": 2415282, "Objective-C": 580704, "JavaScript": 209639, "Objective-C++": 165277, "Groovy": 103211, "Python": 43460, "Shell": 31275, "TypeScript": 22854, "Lex": 18369, "Batchfile": 11692, "CSS": 11259, "EJS": 5241, "Ruby": 4878, "HTML": 4793, "CMake": 4448, "Dockerfile": 2787, "Pascal": 1698, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.incremental import com.google.common.io.Closer import org.jetbrains.kotlin.build.report.ICReporter import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner import org.jetbrains.kotlin.incremental.storage.IncrementalFileToPathConverter import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol import java.io.Closeable import java.io.File abstract class IncrementalCachesManager<PlatformCache : AbstractIncrementalCache<*>>( cachesRootDir: File, rootProjectDir: File?, protected val reporter: ICReporter, storeFullFqNamesInLookupCache: Boolean = false, trackChangesInLookupCache: Boolean = false ) : Closeable { val pathConverter = IncrementalFileToPathConverter(rootProjectDir) private val caches = arrayListOf<BasicMapsOwner>() private var isClosed = false @Synchronized protected fun <T : BasicMapsOwner> T.registerCache() { check(!isClosed) { "This cache storage has already been closed" } caches.add(this) } private val inputSnapshotsCacheDir = File(cachesRootDir, "inputs").apply { mkdirs() } private val lookupCacheDir = File(cachesRootDir, "lookups").apply { mkdirs() } val inputsCache: InputsCache = InputsCache(inputSnapshotsCacheDir, reporter, pathConverter).apply { registerCache() } val lookupCache: LookupStorage = LookupStorage(lookupCacheDir, pathConverter, storeFullFqNamesInLookupCache, trackChangesInLookupCache).apply { registerCache() } abstract val platformCache: PlatformCache @Suppress("UnstableApiUsage") @Synchronized override fun close() { check(!isClosed) { "This cache storage has already been closed" } val closer = Closer.create() caches.forEach { closer.register(CacheCloser(it)) } closer.close() isClosed = true } private class CacheCloser(private val cache: BasicMapsOwner) : Closeable { override fun close() { // It's important to flush the cache when closing (see KT-53168) cache.flush(memoryCachesOnly = false) cache.close() } } } class IncrementalJvmCachesManager( cacheDirectory: File, rootProjectDir: File?, outputDir: File, reporter: ICReporter, storeFullFqNamesInLookupCache: Boolean = false, trackChangesInLookupCache: Boolean = false ) : IncrementalCachesManager<IncrementalJvmCache>( cacheDirectory, rootProjectDir, reporter, storeFullFqNamesInLookupCache, trackChangesInLookupCache ) { private val jvmCacheDir = File(cacheDirectory, "jvm").apply { mkdirs() } override val platformCache = IncrementalJvmCache(jvmCacheDir, outputDir, pathConverter).apply { registerCache() } } class IncrementalJsCachesManager( cachesRootDir: File, rootProjectDir: File?, reporter: ICReporter, serializerProtocol: SerializerExtensionProtocol, storeFullFqNamesInLookupCache: Boolean ) : IncrementalCachesManager<IncrementalJsCache>(cachesRootDir, rootProjectDir, reporter, storeFullFqNamesInLookupCache) { private val jsCacheFile = File(cachesRootDir, "js").apply { mkdirs() } override val platformCache = IncrementalJsCache(jsCacheFile, pathConverter, serializerProtocol).apply { registerCache() } }
7
Kotlin
0
1
4af0f110c7053d753c92fd9caafb4be138fdafba
3,892
kotlin
Apache License 2.0
app/src/main/java/com/leperlier/quinquis/lentz/imdb/ui/movieList/MovieAdapter.kt
RomainLENTZ
773,319,710
false
{"Kotlin": 119708}
package com.leperlier.quinquis.lentz.imdb.ui import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.gmail.eamosse.imdb.databinding.MovieHorizontalItemBinding import com.gmail.eamosse.imdb.databinding.MovieVerticalItemBinding import com.leperlier.quinquis.lentz.imdb.data.Movie import com.leperlier.quinquis.lentz.imdb.data.MovieDesignType class MovieAdapter(private var movies: List<Movie>, private val onItemClick: (Movie) -> Unit, private val designType: MovieDesignType) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { class MovieViewHolderHorizontal(val binding: MovieHorizontalItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(movie: Movie, onItemClick: (Movie) -> Unit) { binding.movieName.text = movie.title binding.root.setOnClickListener { onItemClick(movie) } } } class MovieViewHolderVertical(val binding: MovieVerticalItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(movie: Movie, onItemClick: (Movie) -> Unit) { binding.movieName.text = movie.title binding.root.setOnClickListener { onItemClick(movie) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return when (designType) { MovieDesignType.HORIZONTAL -> { val binding = MovieHorizontalItemBinding.inflate(inflater, parent, false) MovieViewHolderHorizontal(binding) } MovieDesignType.VERTICAL -> { val binding = MovieVerticalItemBinding.inflate(inflater, parent, false) MovieViewHolderVertical(binding) } } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val movie = movies[position] when (holder) { is MovieViewHolderHorizontal -> holder.bind(movie, onItemClick) is MovieViewHolderVertical -> holder.bind(movie, onItemClick) } } override fun getItemViewType(position: Int): Int { return designType.ordinal } fun updateMovies(movies: List<Movie>) { this.movies = movies notifyDataSetChanged() } override fun getItemCount(): Int = movies.size }
0
Kotlin
0
0
674e161a282db8794a306806779fd18b0099380b
2,490
mini-projet-group_quinquis_leperlier_lentz
Apache License 2.0
common/src/main/kotlin/deepstream/Handler.kt
deepstreamIO
125,635,530
false
null
package deepstream interface Handler { }
0
Kotlin
2
1
96651ad88f1809c75cb591b3fa6403c55c93d42b
43
deepstream.io-client-kotlin
Apache License 2.0
matrix-sdk-android/src/rustCrypto/java/org/matrix/android/sdk/internal/crypto/verification/VerificationRequest.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2022 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.internal.crypto.verification import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import org.matrix.android.sdk.api.MatrixCoroutineDispatchers import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.session.crypto.verification.CancelCode import org.matrix.android.sdk.api.session.crypto.verification.EVerificationState import org.matrix.android.sdk.api.session.crypto.verification.PendingVerificationRequest import org.matrix.android.sdk.api.session.crypto.verification.VerificationMethod import org.matrix.android.sdk.api.session.crypto.verification.safeValueOf import org.matrix.android.sdk.api.util.fromBase64 import org.matrix.android.sdk.api.util.toBase64NoPadding import org.matrix.android.sdk.internal.crypto.OlmMachine import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_QR_CODE_SCAN import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_QR_CODE_SHOW import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_RECIPROCATE import org.matrix.android.sdk.internal.crypto.model.rest.VERIFICATION_METHOD_SAS import org.matrix.android.sdk.internal.crypto.network.RequestSender import org.matrix.android.sdk.internal.crypto.verification.qrcode.QrCodeVerification import org.matrix.android.sdk.internal.util.time.Clock import org.matrix.rustcomponents.sdk.crypto.VerificationRequestListener import org.matrix.rustcomponents.sdk.crypto.VerificationRequestState import timber.log.Timber import org.matrix.rustcomponents.sdk.crypto.VerificationRequest as InnerVerificationRequest fun InnerVerificationRequest.dbgString(): String { val that = this return buildString { append("(") append("flowId=${that.flowId()}") append("state=${that.state()},") append(")") } } /** A verification request object * * This represents a verification flow that starts with a m.key.verification.request event * * Once the VerificationRequest gets to a ready state users can transition into the different * concrete verification flows. */ internal class VerificationRequest @AssistedInject constructor( @Assisted private var innerVerificationRequest: InnerVerificationRequest, olmMachine: OlmMachine, private val requestSender: RequestSender, private val coroutineDispatchers: MatrixCoroutineDispatchers, private val verificationListenersHolder: VerificationListenersHolder, private val sasVerificationFactory: SasVerification.Factory, private val qrCodeVerificationFactory: QrCodeVerification.Factory, private val clock: Clock, ) : VerificationRequestListener { private val innerOlmMachine = olmMachine.inner() @AssistedFactory interface Factory { fun create(innerVerificationRequest: InnerVerificationRequest): VerificationRequest } init { innerVerificationRequest.setChangesListener(this) } fun startQrCode() { innerVerificationRequest.startQrVerification() } // internal fun dispatchRequestUpdated() { // val tx = toPendingVerificationRequest() // verificationListenersHolder.dispatchRequestUpdated(tx) // } /** Get the flow ID of this verification request * * This is either the transaction ID if the verification is happening * over to-device events, or the event ID of the m.key.verification.request * event that initiated the flow. */ internal fun flowId(): String { return innerVerificationRequest.flowId() } fun innerState() = innerVerificationRequest.state() /** The user ID of the other user that is participating in this verification flow. */ internal fun otherUser(): String { return innerVerificationRequest.otherUserId() } /** The device ID of the other user's device that is participating in this verification flow * * This will we null if we're initiating the request and the other side * didn't yet accept the verification flow. * */ internal fun otherDeviceId(): String? { return innerVerificationRequest.otherDeviceId() } /** Did we initiate this verification flow. */ internal fun weStarted(): Boolean { return innerVerificationRequest.weStarted() } /** Get the id of the room where this verification is happening * * Will be null if the verification is not happening inside a room. */ internal fun roomId(): String? { return innerVerificationRequest.roomId() } /** Did the non-initiating side respond with a m.key.verification.read event * * Once the verification request is ready, we're able to transition into a * concrete verification flow, i.e. we can show/scan a QR code or start emoji * verification. */ // internal fun isReady(): Boolean { // return innerVerificationRequest.isReady() // } /** Did we advertise that we're able to scan QR codes. */ internal fun canScanQrCodes(): Boolean { return innerVerificationRequest.ourSupportedMethods()?.contains(VERIFICATION_METHOD_QR_CODE_SCAN) ?: false } /** Accept the verification request advertising the given methods as supported * * This will send out a m.key.verification.ready event advertising support for * the given verification methods to the other side. After this method call, the * verification request will be considered to be ready and will be able to transition * into concrete verification flows. * * The method turns into a noop, if the verification flow has already been accepted * and is in the ready state, which can be checked with the isRead() method. * * @param methods The list of VerificationMethod that we wish to advertise to the other * side as supported. */ suspend fun acceptWithMethods(methods: List<VerificationMethod>) { val stringMethods = prepareMethods(methods) val request = innerVerificationRequest.accept(stringMethods) ?: return // should throw here? try { requestSender.sendVerificationRequest(request) } catch (failure: Throwable) { cancel() } } // var activeQRCode: QrCode? = null /** Transition from a ready verification request into emoji verification * * This method will move the verification forward into emoji verification, * it will send out a m.key.verification.start event with the method set to * m.sas.v1. * * Note: This method will be a noop and return null if the verification request * isn't considered to be ready, you can check if the request is ready using the * isReady() method. * * @return A freshly created SasVerification object that represents the newly started * emoji verification, or null if we can't yet transition into emoji verification. */ internal suspend fun startSasVerification(): SasVerification? { return withContext(coroutineDispatchers.io) { val result = innerVerificationRequest.startSasVerification() ?: return@withContext null.also { Timber.w("Failed to start verification") } try { requestSender.sendVerificationRequest(result.request) sasVerificationFactory.create(result.sas) } catch (failure: Throwable) { cancel() null } } } /** Scan a QR code and transition into QR code verification * * This method will move the verification forward into QR code verification. * It will send out a m.key.verification.start event with the method * set to m.reciprocate.v1. * * Note: This method will be a noop and return null if the verification request * isn't considered to be ready, you can check if the request is ready using the * isReady() method. * * @return A freshly created QrCodeVerification object that represents the newly started * QR code verification, or null if we can't yet transition into QR code verification. */ internal suspend fun scanQrCode(data: String): QrCodeVerification? { // TODO again, what's the deal with ISO_8859_1? val byteArray = data.toByteArray(Charsets.ISO_8859_1) val encodedData = byteArray.toBase64NoPadding() // val result = innerOlmMachine.scanQrCode(otherUser(), flowId(), encodedData) ?: return null val result = innerVerificationRequest.scanQrCode(encodedData) ?: return null try { requestSender.sendVerificationRequest(result.request) } catch (failure: Throwable) { cancel() return null } return qrCodeVerificationFactory.create(result.qr) } /** Cancel the verification flow * * This will send out a m.key.verification.cancel event with the cancel * code set to m.user. * * Cancelling the verification request will also cancel any QrcodeVerification and * SasVerification objects that are related to this verification request. * * The method turns into a noop, if the verification flow has already been cancelled. */ internal suspend fun cancel() = withContext(NonCancellable) { val request = innerVerificationRequest.cancel() ?: return@withContext tryOrNull("Fail to send cancel request") { requestSender.sendVerificationRequest(request, retryCount = Int.MAX_VALUE) } } private fun state(): EVerificationState { Timber.v("Verification state() ${innerVerificationRequest.state()}") when (innerVerificationRequest.state()) { VerificationRequestState.Requested -> { return if (weStarted()) { EVerificationState.WaitingForReady } else { EVerificationState.Requested } } is VerificationRequestState.Ready -> { val started = innerOlmMachine.getVerification(otherUser(), flowId()) if (started != null) { val asSas = started.asSas() if (asSas != null) { return if (asSas.weStarted()) { EVerificationState.WeStarted } else { EVerificationState.Started } } val asQR = started.asQr() if (asQR != null) { if (asQR.reciprocated() || asQR.hasBeenScanned()) { return if (weStarted()) { EVerificationState.WeStarted } else EVerificationState.Started } } } return EVerificationState.Ready } VerificationRequestState.Done -> { return EVerificationState.Done } is VerificationRequestState.Cancelled -> { return if (innerVerificationRequest.cancelInfo()?.cancelCode == CancelCode.AcceptedByAnotherDevice.value) { EVerificationState.HandledByOtherSession } else { EVerificationState.Cancelled } } } // // if (innerVerificationRequest.isCancelled()) { // return if (innerVerificationRequest.cancelInfo()?.cancelCode == CancelCode.AcceptedByAnotherDevice.value) { // EVerificationState.HandledByOtherSession // } else { // EVerificationState.Cancelled // } // } // if (innerVerificationRequest.isPassive()) { // return EVerificationState.HandledByOtherSession // } // if (innerVerificationRequest.isDone()) { // return EVerificationState.Done // } // // val started = innerOlmMachine.getVerification(otherUser(), flowId()) // if (started != null) { // val asSas = started.asSas() // if (asSas != null) { // return if (asSas.weStarted()) { // EVerificationState.WeStarted // } else { // EVerificationState.Started // } // } // val asQR = started.asQr() // if (asQR != null) { // if (asQR.reciprocated() || asQR.hasBeenScanned()) { // return if (weStarted()) { // EVerificationState.WeStarted // } else EVerificationState.Started // } // } // } // if (innerVerificationRequest.isReady()) { // return EVerificationState.Ready // } } /** Convert the VerificationRequest into a PendingVerificationRequest * * The public interface of the VerificationService dispatches the data class * PendingVerificationRequest, this method allows us to easily transform this * request into the data class. It fetches fresh info from the Rust side before * it does the transform. * * @return The PendingVerificationRequest that matches data from this VerificationRequest. */ internal fun toPendingVerificationRequest(): PendingVerificationRequest { val cancelInfo = innerVerificationRequest.cancelInfo() val cancelCode = if (cancelInfo != null) { safeValueOf(cancelInfo.cancelCode) } else { null } val ourMethods = innerVerificationRequest.ourSupportedMethods() val theirMethods = innerVerificationRequest.theirSupportedMethods() val otherDeviceId = innerVerificationRequest.otherDeviceId() return PendingVerificationRequest( // Creation time ageLocalTs = clock.epochMillis(), state = state(), // Who initiated the request isIncoming = !innerVerificationRequest.weStarted(), // Local echo id, what to do here? otherDeviceId = innerVerificationRequest.otherDeviceId(), // other user otherUserId = innerVerificationRequest.otherUserId(), // room id roomId = innerVerificationRequest.roomId(), // transaction id transactionId = innerVerificationRequest.flowId(), // cancel code if there is one cancelConclusion = cancelCode, isFinished = innerVerificationRequest.isDone() || innerVerificationRequest.isCancelled(), // did another device answer the request handledByOtherSession = innerVerificationRequest.isPassive(), // devices that should receive the events we send out targetDevices = otherDeviceId?.let { listOf(it) }, qrCodeText = getQrCode(), isSasSupported = ourMethods.canSas() && theirMethods.canSas(), weShouldDisplayQRCode = theirMethods.canScanQR() && ourMethods.canShowQR(), weShouldShowScanOption = ourMethods.canScanQR() && theirMethods.canShowQR() ) } private fun getQrCode(): String? { return innerOlmMachine.getVerification(otherUser(), flowId())?.asQr()?.generateQrCode()?.fromBase64()?.let { String(it, Charsets.ISO_8859_1) } } override fun onChange(state: VerificationRequestState) { verificationListenersHolder.dispatchRequestUpdated(this) } override fun toString(): String { return super.toString() + "\n${innerVerificationRequest.dbgString()}" } private fun List<String>?.canSas() = orEmpty().contains(VERIFICATION_METHOD_SAS) private fun List<String>?.canShowQR() = orEmpty().contains(VERIFICATION_METHOD_RECIPROCATE) && orEmpty().contains(VERIFICATION_METHOD_QR_CODE_SHOW) private fun List<String>?.canScanQR() = orEmpty().contains(VERIFICATION_METHOD_RECIPROCATE) && orEmpty().contains(VERIFICATION_METHOD_QR_CODE_SCAN) }
68
null
6
9
5aa86fe9d36ad8087f289152d5e718fdfad65a2c
17,040
tchap-android
Apache License 2.0
app/src/main/java/com/jawnnypoo/openmeh/model/ParsedTheme.kt
Jawnnypoo
34,304,113
false
null
package com.jawnnypoo.openmeh.model import android.graphics.Color import android.os.Parcelable import com.jawnnypoo.openmeh.shared.model.Theme import kotlinx.android.parcel.Parcelize /** * [Theme], but parsed into colors that are safe and make sense */ @Parcelize data class ParsedTheme( val accentColor: String? = null, val foreground: String? = null, val backgroundColor: String? = null, val backgroundImage: String? = null ) : Parcelable { companion object { private const val EXPECTED_FORMAT = "#FFFFFF" private fun safeParseColor(color: String?): Int { color ?: return Color.BLACK return if (color.length == EXPECTED_FORMAT.length) { Color.parseColor(color) } else { //This seems kinda terrible... var rrggbb = "#" for (i in 1 until color.length) { rrggbb += color[i] + "" + color[i] } Color.parseColor(rrggbb) } } fun fromTheme(theme: Theme?): ParsedTheme? { if (theme == null) { return null } return ParsedTheme( accentColor = theme.accentColor, foreground = theme.foreground, backgroundColor = theme.backgroundColor, backgroundImage = theme.backgroundImage ) } } fun safeForegroundColor(): Int { return if (foreground == Theme.FOREGROUND_LIGHT) Color.WHITE else Color.BLACK } fun safeForegroundColorInverse(): Int { return if (foreground == Theme.FOREGROUND_LIGHT) Color.BLACK else Color.WHITE } fun safeAccentColor(): Int { return safeParseColor(accentColor) } fun safeBackgroundColor(): Int { return safeParseColor(backgroundColor) } }
1
Kotlin
5
47
a755150042ff1a6de94b911451117d8534151f73
1,909
open-meh
Apache License 2.0
src/commonMain/kotlin/tech/thatgravyboat/jukebox/impl/foobar/state/FoobarPlaybackState.kt
ThatGravyBoat
531,897,224
false
{"Kotlin": 71776}
package tech.thatgravyboat.jukebox.impl.foobar.state import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class FoobarPlaybackState { @SerialName("playing") PLAYING, @SerialName("stopped") STOPPED, @SerialName("paused") PAUSED, }
0
Kotlin
0
7
48f6a7936447a4924f40b699b0dee946774fb800
291
Jukebox
MIT License
app/src/main/java/com/wuhenzhizao/mvp/net/OkHttpClientFactory.kt
wuhenzhizao
142,847,078
false
{"Java": 47385, "Kotlin": 40556}
package com.wuhenzhizao.mvp.net import android.content.Context import com.wuhenzhizao.mvp.net.intercepter.HeaderFileParamsInterceptor import com.wuhenzhizao.mvp.net.intercepter.HeaderParamsInterceptor import com.wuhenzhizao.mvp.BuildConfig import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import timber.log.Timber /** * Created by liufei on 2017/10/11. */ object OkHttpClientFactory { fun newHttp(context: Context): OkHttpClient = HttpFactoryWrapper(HttpFactory()).onCreate(context) fun newHttps(context: Context): OkHttpClient = HttpFactoryWrapper(HttpsFactory()).onCreate(context) fun newFile(context: Context): OkHttpClient = FileFactoryWrapper(HttpFactory()).onCreate(context) private abstract class Factory { fun onCreate(context: Context): OkHttpClient { var builder = OkHttpClient.Builder() buildOkHttpClient(context, builder) return builder.build() } abstract fun buildOkHttpClient(context: Context, builder: OkHttpClient.Builder) } private class HttpFactory : Factory() { override fun buildOkHttpClient(context: Context, builder: OkHttpClient.Builder) { } } private class HttpsFactory : Factory() { override fun buildOkHttpClient(context: Context, builder: OkHttpClient.Builder) { } } private open class FactoryWrapper(val factory: Factory) : Factory() { override fun buildOkHttpClient(context: Context, builder: OkHttpClient.Builder) { if (BuildConfig.DEBUG) { builder.addInterceptor(HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Timber.d(message) }).setLevel(HttpLoggingInterceptor.Level.BODY)) } factory.buildOkHttpClient(context, builder) } } private class HttpFactoryWrapper(factory: Factory) : FactoryWrapper(factory) { override fun buildOkHttpClient(context: Context, builder: OkHttpClient.Builder) { super.buildOkHttpClient(context, builder) builder.addInterceptor(HeaderParamsInterceptor(context)) } } private class FileFactoryWrapper(factory: Factory) : FactoryWrapper(factory) { override fun buildOkHttpClient(context: Context, builder: OkHttpClient.Builder) { super.buildOkHttpClient(context, builder) builder.addInterceptor(HeaderFileParamsInterceptor(context)) } } }
1
Java
1
6
f256612a6d8eadd1b93cf2c3a3ed653b85ace846
2,530
kotlin-mvp-framework
Apache License 2.0
src/Day11.kt
dmarcato
576,511,169
false
{"Kotlin": 36664}
import java.util.* data class Monkey( val items: Queue<Long>, val operation: (Long, Long) -> Long, val operationValue: Long?, val testValue: Long, val ifTrueDestination: Int, val ifFalseDestination: Int, var itemsInspected: Long = 0L ) fun makeMonkeys(input: List<String>): Pair<Int, Monkey> { val index = "\\s(\\d+):".toRegex().find(input[0])!!.groupValues[1].toInt() val items = input[1].split(": ")[1].split(", ").map { it.toLong() } val (_, op, valueString) = "old\\s([+*])\\s(\\d+|old)".toRegex().find(input[2])!!.groupValues val opValue = when (valueString) { "old" -> null else -> valueString.toLong() } val operation: (Long, Long) -> Long = when (op) { "+" -> Long::plus "*" -> Long::times else -> throw RuntimeException() } val testValue = input[3].split(" ").last().toLong() val ifTrue = input[4].split(" ").last().toInt() val ifFalse = input[5].split(" ").last().toInt() val queue = LinkedList<Long>() queue.addAll(items) return index to Monkey(queue, operation, opValue, testValue, ifTrue, ifFalse) } fun monkeyBusiness(monkeys: Map<Int, Monkey>, worryLevel: Long?, rounds: Int): Long { val monkeyOrder = monkeys.keys.sorted() val commonDivisor = monkeys.values.fold(1L) { acc, monkey -> acc * monkey.testValue } (0 until rounds).forEach { _ -> monkeyOrder.forEach { num -> val monkey = monkeys[num]!! monkey.items.forEach { item -> var newItem = monkey.operation(item, monkey.operationValue ?: item) newItem = worryLevel?.let { newItem / it } ?: (newItem % commonDivisor) val destMonkey = if (newItem.mod(monkey.testValue) == 0L) { monkey.ifTrueDestination } else { monkey.ifFalseDestination } monkeys[destMonkey]!!.items.offer(newItem) monkey.itemsInspected++ } monkey.items.clear() } } val (m1, m2) = monkeys.values.sortedByDescending { it.itemsInspected }.take(2) return m1.itemsInspected * m2.itemsInspected } fun main() { fun part1(input: List<String>): Long { val monkeys = input.windowed(6, 7, true) { makeMonkeys(it) }.toMap() return monkeyBusiness(monkeys, 3L, 20) } fun part2(input: List<String>): Long { val monkeys = input.windowed(6, 7, true) { makeMonkeys(it) }.toMap() return monkeyBusiness(monkeys, null, 10000) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) { "part1 check failed" } check(part2(testInput) == 2713310158L) { "part2 check failed" } val input = readInput("Day11") part1(input).println() part2(input).println() }
0
Kotlin
0
0
6abd8ca89a1acce49ecc0ca8a51acd3969979464
2,974
aoc2022
Apache License 2.0
text_world/src/main/kotlin/cubes/motion/interpolator/BounceInterpolator.kt
sentinelweb
228,927,082
false
{"Gradle": 6, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "JSON": 2, "Kotlin": 205, "SubRip Text": 1, "Java": 14, "Java Properties": 1, "Wavefront Object": 1, "GLSL": 69, "SVG": 8, "XML": 7}
package cubes.motion.interpolator class BounceInterpolator(private val type: EasingType) : Interpolator { override fun getInterpolation(t: Float): Float { return when (type) { EasingType.IN -> `in`(t) EasingType.OUT -> out(t) EasingType.INOUT -> inout(t) } } private fun out(t: Float): Float { var t = t return if (t < 1 / 2.75) { 7.5625f * t * t } else if (t < 2 / 2.75) { t -= (1.5f / 2.75f) 7.5625f * t * t + .75f } else if (t < 2.5 / 2.75) { t -= (2.25f / 2.75f) 7.5625f * t * t + .9375f } else { t -= (2.625f / 2.75f) 7.5625f * t * t + .984375f } } private fun `in`(t: Float): Float { return 1 - out(1 - t) } private fun inout(t: Float): Float { return if (t < 0.5f) { `in`(t * 2) * .5f } else { out(t * 2 - 1) * .5f + .5f } } }
14
Kotlin
0
0
623fd9f4d860b61dfc5b5dfbc5a8f536d978d9f6
1,011
processink
Apache License 2.0
spring-data-graphql-r2dbc-autoconfigure/src/main/kotlin/io/github/wickedev/graphql/spring/data/r2dbc/configuration/GraphQLR2dbcDataAutoConfiguration.kt
wickedev
439,584,762
false
{"Kotlin": 269467, "JavaScript": 6748, "Java": 2439, "CSS": 1699}
package io.github.wickedev.graphql.spring.data.r2dbc.configuration import io.github.wickedev.graphql.repository.GraphQLDataLoaderByIdRepository import io.github.wickedev.graphql.repository.GraphQLNodeRepository import io.github.wickedev.graphql.spring.data.r2dbc.converter.GraphQLMappingR2dbcConverter import io.github.wickedev.graphql.spring.data.r2dbc.converter.IDToLongWritingConverter import io.github.wickedev.graphql.spring.data.r2dbc.converter.LongToIDReadingConverter import io.github.wickedev.graphql.spring.data.r2dbc.mapping.GraphQLR2dbcMappingContext import io.github.wickedev.graphql.spring.data.r2dbc.repository.SimpleGraphQLNodeRepository import io.github.wickedev.graphql.spring.data.r2dbc.strategy.AdditionalIsNewStrategy import io.github.wickedev.graphql.spring.data.r2dbc.strategy.DefaultIDTypeStrategy import io.github.wickedev.graphql.spring.data.r2dbc.strategy.GraphQLAdditionalIsNewStrategy import io.github.wickedev.graphql.spring.data.r2dbc.strategy.IDTypeStrategy import org.springframework.beans.factory.ObjectProvider import org.springframework.boot.autoconfigure.AutoConfigureAfter import org.springframework.boot.autoconfigure.AutoConfigureBefore import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate import org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration import org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.convert.CustomConversions import org.springframework.data.r2dbc.convert.MappingR2dbcConverter import org.springframework.data.r2dbc.convert.R2dbcConverter import org.springframework.data.r2dbc.convert.R2dbcCustomConversions import org.springframework.data.r2dbc.core.GraphQLR2dbcEntityTemplate import org.springframework.data.r2dbc.core.R2dbcEntityTemplate import org.springframework.data.r2dbc.dialect.DialectResolver import org.springframework.data.r2dbc.dialect.R2dbcDialect import org.springframework.data.r2dbc.mapping.R2dbcMappingContext import org.springframework.data.relational.core.mapping.NamingStrategy import org.springframework.r2dbc.core.DatabaseClient @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DatabaseClient::class, R2dbcEntityTemplate::class) @ConditionalOnSingleCandidate(DatabaseClient::class) @AutoConfigureBefore(R2dbcDataAutoConfiguration::class) @AutoConfigureAfter(R2dbcAutoConfiguration::class) class GraphQLR2dbcDataAutoConfiguration(private val databaseClient: DatabaseClient) { val dialect: R2dbcDialect = DialectResolver.getDialect(this.databaseClient.connectionFactory) @Bean @ConditionalOnMissingBean fun r2dbcEntityTemplate(r2dbcConverter: R2dbcConverter): R2dbcEntityTemplate? { return GraphQLR2dbcEntityTemplate(databaseClient, dialect, r2dbcConverter) } @Bean @ConditionalOnMissingBean fun r2dbcMappingContext( namingStrategy: ObjectProvider<NamingStrategy>, r2dbcCustomConversions: R2dbcCustomConversions, idTypeStrategy: IDTypeStrategy, ): R2dbcMappingContext { val relationalMappingContext = GraphQLR2dbcMappingContext( namingStrategy.getIfAvailable { NamingStrategy.INSTANCE }, idTypeStrategy ) relationalMappingContext.setSimpleTypeHolder(r2dbcCustomConversions.simpleTypeHolder) return relationalMappingContext } @Bean @ConditionalOnMissingBean fun additionalIsNewStrategy(): AdditionalIsNewStrategy = GraphQLAdditionalIsNewStrategy() @Bean @ConditionalOnMissingBean fun idTypeStrategy(): IDTypeStrategy = DefaultIDTypeStrategy() @Bean @ConditionalOnMissingBean fun r2dbcConverter( context: R2dbcMappingContext, conversions: CustomConversions, additionalIsNewStrategy: AdditionalIsNewStrategy, ): MappingR2dbcConverter { return GraphQLMappingR2dbcConverter(context, conversions, additionalIsNewStrategy) } @Bean @ConditionalOnMissingBean fun r2dbcCustomConversions(): R2dbcCustomConversions? { val converters: MutableList<Any> = ArrayList(dialect.converters) converters.addAll(R2dbcCustomConversions.STORE_CONVERTERS) return R2dbcCustomConversions( CustomConversions.StoreConversions.of(dialect.simpleTypeHolder, converters), listOf( IDToLongWritingConverter(), LongToIDReadingConverter(), ) ) } @Bean @ConditionalOnMissingBean fun graphQLNodeRepository( repositories: ObjectProvider<GraphQLDataLoaderByIdRepository<*>>, idTypeStrategy: IDTypeStrategy, ): GraphQLNodeRepository { return SimpleGraphQLNodeRepository(repositories, idTypeStrategy) } }
0
Kotlin
0
19
d6913beaecf9e7ef065acdb1805794a10b07d55e
4,992
graphql-jetpack
The Unlicense
src/main/kotlin/org/mechdancer/algebra/implement/matrix/builder/SpecialBuilder.kt
MechDancer
128,765,281
false
null
package org.mechdancer.algebra.implement.matrix.builder import org.mechdancer.algebra.implement.matrix.special.DiagonalMatrix import org.mechdancer.algebra.implement.matrix.special.NumberMatrix import org.mechdancer.algebra.implement.matrix.special.ZeroMatrix // super shortcut typealias O = ZeroMatrix typealias N = NumberMatrix typealias I = IdentityMatrix object IdentityMatrix { @JvmStatic operator fun get(n: Int) = N[n, 1.0] } fun Iterable<Number>.toDiagonalMatrix() = DiagonalMatrix(map(Number::toDouble)) fun DoubleArray.toDiagonalMatrix() = DiagonalMatrix(map(Number::toDouble))
1
Kotlin
1
6
2cbc7e60b3cd32f46a599878387857f738abda46
595
linearalgebra
Do What The F*ck You Want To Public License
idea-plugin/src/main/kotlin/io/github/composegears/valkyrie/ui/screen/mode/iconpack/destination/IconPackDestinationScreen.kt
ComposeGears
778,162,113
false
{"Kotlin": 433943}
package io.github.composegears.valkyrie.ui.screen.mode.iconpack.destination import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import com.composegears.tiamat.koin.koinTiamatViewModel import com.composegears.tiamat.navController import com.composegears.tiamat.navDestination import io.github.composegears.valkyrie.ui.foundation.AppBarTitle import io.github.composegears.valkyrie.ui.foundation.BackAction import io.github.composegears.valkyrie.ui.foundation.DragAndDropBox import io.github.composegears.valkyrie.ui.foundation.TopAppBar import io.github.composegears.valkyrie.ui.foundation.VerticalSpacer import io.github.composegears.valkyrie.ui.foundation.WeightSpacer import io.github.composegears.valkyrie.ui.foundation.dnd.rememberDragAndDropFolderHandler import io.github.composegears.valkyrie.ui.foundation.icons.Folder import io.github.composegears.valkyrie.ui.foundation.icons.ValkyrieIcons import io.github.composegears.valkyrie.ui.foundation.picker.rememberDirectoryPicker import io.github.composegears.valkyrie.ui.foundation.theme.PreviewTheme import io.github.composegears.valkyrie.ui.screen.mode.iconpack.creation.IconPackCreationScreen import kotlinx.coroutines.launch val IconPackDestinationScreen by navDestination<Unit> { val navController = navController() val viewModel = koinTiamatViewModel<IconPackDestinationViewModel>() val state by viewModel.state.collectAsState() val dragAndDropHandler = rememberDragAndDropFolderHandler(onDrop = viewModel::updateDestination) val isDragging by remember(dragAndDropHandler.isDragging) { mutableStateOf(dragAndDropHandler.isDragging) } val scope = rememberCoroutineScope() val directoryPicker = rememberDirectoryPicker() IconPackDestinationScreenUI( state = state, isDragging = isDragging, onChooseDirectory = { scope.launch { val path = directoryPicker.launch() if (path != null) { viewModel.updateDestination(path) } } }, onBack = navController::back, onNext = { viewModel.saveSettings() navController.navigate(IconPackCreationScreen) }, ) } @Composable private fun IconPackDestinationScreenUI( state: IconPackDestinationState, isDragging: Boolean, onChooseDirectory: () -> Unit, onBack: () -> Unit, onNext: () -> Unit, ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()), ) { TopAppBar { BackAction(onBack = onBack) AppBarTitle(title = "IconPack destination") } VerticalSpacer(36.dp) DragAndDropBox( modifier = Modifier.align(Alignment.CenterHorizontally), isDragging = isDragging, onChoose = onChooseDirectory, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp), ) { Icon( imageVector = ValkyrieIcons.Folder, contentDescription = null, ) Text( modifier = Modifier.padding(horizontal = 16.dp), textAlign = TextAlign.Center, text = "Drag & Drop folder\nor browse", style = MaterialTheme.typography.titleSmall, ) } } VerticalSpacer(36.dp) Row( modifier = Modifier .fillMaxWidth(0.8f) .align(Alignment.CenterHorizontally), ) { Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(24.dp), ) { if (state.iconPackDestination.isNotEmpty()) { Column { Text( modifier = Modifier.align(Alignment.Start), text = "Export path:", style = MaterialTheme.typography.bodyMedium, ) Text( modifier = Modifier.align(Alignment.Start), text = state.iconPackDestination, textDecoration = TextDecoration.Underline, style = MaterialTheme.typography.bodySmall, ) } } if (state.predictedPackage.isNotEmpty()) { Column { Text( modifier = Modifier.align(Alignment.Start), text = "Predicted package:", style = MaterialTheme.typography.bodyMedium, ) Text( modifier = Modifier.align(Alignment.Start), textDecoration = TextDecoration.Underline, text = state.predictedPackage, style = MaterialTheme.typography.bodySmall, ) } } Button( modifier = Modifier.align(Alignment.End), enabled = state.nextButtonEnabled, onClick = onNext, ) { Text(text = "Next") } } } WeightSpacer() } } @Preview @Composable private fun IconPackDestinationScreenPreview() = PreviewTheme { IconPackDestinationScreenUI( state = IconPackDestinationState( nextButtonEnabled = true, iconPackDestination = "Users/Downloads/IconPackDestination", predictedPackage = "com.example.iconpack", ), onChooseDirectory = {}, isDragging = false, onBack = {}, onNext = {}, ) }
6
Kotlin
2
128
e5ea7af5153b383c106c354cd42d6d2ac03ed23b
7,101
Valkyrie
Apache License 2.0
src/main/kotlin/trees/AVLTree.kt
spbu-coding-2023
771,631,209
false
{"Kotlin": 27943}
package trees import primitives.Tree import nodes.AVLNode class AVLTree<K : Comparable<K>, V>: Tree<K, V, AVLNode<K, V>>() { override fun insert(key: K, value: V) { root = insertRec(root, key, value) } override fun delete(key: K) { root = deleteRec(root, key) } private fun insertRec(current: AVLNode<K, V>?, key: K, value: V): AVLNode<K, V>? { if (current == null) return AVLNode(key, value) if (key < current.key) current.left = insertRec(current.left, key, value) else if (key > current.key) current.right = insertRec(current.right, key, value) else { current.value = value return current } return balance(current) } private fun deleteRec(node: AVLNode<K, V>?, key: K): AVLNode<K, V>? { if (node == null) return null if (key < node.key) node.left = deleteRec(node.left, key) else if (key > node.key) node.right = deleteRec(node.right, key) else { if (node.left == null || node.right == null) { val temp = if (node.left != null)node.left else node.right return temp } else { val t = findMin(node.right!!) node.key = t.key node.value = t.value node.right = deleteRec(node.right, t.key) } } return balance(node) } private fun findMin(node: AVLNode<K, V>): AVLNode<K, V> { var current = node while (current.left != null) { current = current.left!! } return current } private fun updateNodeHeight(node: AVLNode<K, V>?) { node?.height = 1 + maxOf((node?.left?.height?: 0), (node?.right?.height?: 0)) } private fun balanceFactor(node: AVLNode<K, V>?): Int{ return (node?.left?.height?: 0) - (node?.right?.height?: 0) } private fun balance(node: AVLNode<K, V>?): AVLNode<K, V>? { updateNodeHeight(node) val t = balanceFactor(node) if (t > 1) { if (balanceFactor(node?.left) < 0) { node?.left = rotateLeft(node?.left) } return rotateRight(node) } if (t < -1) { if (balanceFactor(node?.right) > 0) { node?.right = rotateRight(node?.right) } return rotateLeft(node) } return node } private fun rotateRight(node: AVLNode<K, V>?): AVLNode<K, V>? { val leftChild = node?.left node?.left = leftChild?.right leftChild?.right = node updateNodeHeight(node) updateNodeHeight(leftChild) return leftChild } private fun rotateLeft(node: AVLNode<K, V>?): AVLNode<K, V>? { val rightChild = node?.right node?.right = rightChild?.left rightChild?.left = node updateNodeHeight(node) updateNodeHeight(rightChild) return rightChild } }
1
Kotlin
0
0
da087b0081b2ffaf87d47d0dd9e7892f07edc823
3,073
trees-10
MIT License
modules/domain/sources/api/RaptorIndividualAggregateStore.kt
fluidsonic
246,018,343
false
{"Kotlin": 752712}
package io.fluidsonic.raptor.domain /** * Doesn't support concurrent access. */ public interface RaptorIndividualAggregateStore<Id : RaptorAggregateId, Change : RaptorAggregateChange<Id>> { public suspend fun lastEventId(): RaptorAggregateEventId? public suspend fun load(id: Id): List<RaptorAggregateEvent<Id, Change>> public suspend fun reload(): List<RaptorAggregateEvent<Id, Change>> public suspend fun save(id: Id, events: List<RaptorAggregateEvent<Id, Change>>) public companion object }
0
Kotlin
2
5
628ae6ab533db1514288e060b92eef5612311939
506
raptor
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/sak/arbeidsfordeling/Arbeidsfordelingsenhet.kt
navikt
206,805,010
false
{"Kotlin": 3927402, "Gherkin": 163948, "Dockerfile": 187}
package no.nav.familie.ef.sak.arbeidsfordeling data class Arbeidsfordelingsenhet( val enhetId: String, val enhetNavn: String, )
4
Kotlin
2
0
0c7e4ed75167f02c46680a0b4b5aa1227fcfea49
137
familie-ef-sak
MIT License
app/src/main/java/com/example/taskplanner/domain/ChangeProductsWithListUseCase.kt
kikichechka
781,460,462
false
{"Kotlin": 102736}
package com.example.taskplanner.domain import com.example.taskplanner.data.model.entity.Product import com.example.taskplanner.data.model.entity.ProductsWithList import com.example.taskplanner.data.model.repository.AddTaskRepository import com.example.taskplanner.data.model.repository.DeleteTaskRepository import com.example.taskplanner.data.model.repository.GetTaskRepository import com.example.taskplanner.data.model.repository.UpdateTaskRepository import javax.inject.Inject class ChangeProductsWithListUseCase @Inject constructor( private val updateTaskRepository: UpdateTaskRepository, private val getTaskRepository: GetTaskRepository, private val deleteTaskRepository: DeleteTaskRepository, private val addTaskRepository: AddTaskRepository ) { suspend fun changeProductList( productsWithList: ProductsWithList, newListTitle: MutableList<String>, ) { val products = productsWithList.productsName products.dateProducts = productsWithList.date updateTaskRepository.updateProducts(products) if (productsWithList.listProducts != null) { deleteOldListProduct(productsWithList.listProducts.toList()) val newListProduct = mutableListOf<Product>() productsWithList.listProducts.forEach { prod -> if (newListTitle.contains(prod.title)) { newListProduct.add(prod) newListTitle.remove(prod.title) } } newListTitle.forEach { title -> newListProduct.add( Product( productsId = productsWithList.productsName.idProducts ?: 0, id = null, title = title ) ) } productsWithList.listProducts.clear() productsWithList.listProducts.addAll(newListProduct) productsWithList.listProducts.forEach { addTaskRepository.addProduct(it) } checkFinishedProducts(productsWithList.listProducts) } } private suspend fun deleteOldListProduct(listProduct: List<Product>) { listProduct.forEach { deleteTaskRepository.deleteProduct(it) } } private suspend fun checkFinishedProducts(productList: List<Product>) { val sizeFinishedProductList = productList.filter { p -> !p.finished }.size val products = getTaskRepository.getProductsById(productList.first().productsId) if (sizeFinishedProductList == 0 && !products.finishedProducts) { products.finishedProducts = true updateTaskRepository.updateProducts(products) } if (sizeFinishedProductList > 0 && products.finishedProducts) { products.finishedProducts = false updateTaskRepository.updateProducts(products) } } }
0
Kotlin
0
0
c28ced0192cdd7cb298ff9e737a1ce4b47680041
2,929
Diploma
Apache License 2.0
app/src/main/java/com/example/recipe_app/data/RecipeResponse.kt
HauntedMilkshake
686,373,197
false
{"Kotlin": 79858}
package com.example.recipe_app.data import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class ApiRecipeResponse( @JsonProperty("results") val results: List<RecipeResponse?> = emptyList(), ) @JsonIgnoreProperties(ignoreUnknown = true) data class RecipeResponse( @JsonProperty("id") val id: Int, @JsonProperty("title") val title: String? = null, @JsonProperty("image") val image: String? = null, )
0
Kotlin
0
4
55d630b9983b1f433a85b2cb19d13dbbbd66d384
525
recipe_app
MIT License
app/src/main/java/com/tiparo/tripway/posting/api/dto/PointApi.kt
suvorovandr
370,462,258
false
{"Gradle": 3, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Kotlin": 95, "XML": 54, "Java": 3}
package com.tiparo.tripway.posting.api.dto import com.google.gson.annotations.SerializedName data class PointApi( @SerializedName("name") val name: String, @SerializedName("description") val description: String?, @SerializedName("trip_id") val tripId: Long?, @SerializedName("trip_name") val tripName: String?, @SerializedName("lat") val lat: Double, @SerializedName("lng") val lng: Double, @SerializedName("address") val address: String, @SerializedName("address_components") val addressComponents: String )
0
Kotlin
0
2
0d01ff8055c8843ead1dd6a72812f6af98c87600
542
Tripway_android
MIT License
app/src/main/java/com/tiparo/tripway/posting/api/dto/PointApi.kt
suvorovandr
370,462,258
false
{"Gradle": 3, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 4, "Proguard": 1, "Kotlin": 95, "XML": 54, "Java": 3}
package com.tiparo.tripway.posting.api.dto import com.google.gson.annotations.SerializedName data class PointApi( @SerializedName("name") val name: String, @SerializedName("description") val description: String?, @SerializedName("trip_id") val tripId: Long?, @SerializedName("trip_name") val tripName: String?, @SerializedName("lat") val lat: Double, @SerializedName("lng") val lng: Double, @SerializedName("address") val address: String, @SerializedName("address_components") val addressComponents: String )
0
Kotlin
0
2
0d01ff8055c8843ead1dd6a72812f6af98c87600
542
Tripway_android
MIT License
app/src/main/java/com/mateuszcholyn/wallet/backend/impl/infrastructure/sqlite/searchservice/SearchServiceDao.kt
mateusz-nalepa
467,673,984
false
{"Kotlin": 643422}
package com.mateuszcholyn.wallet.backend.impl.infrastructure.sqlite.searchservice import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.RawQuery import androidx.sqlite.db.SupportSQLiteQuery @Dao interface SearchServiceDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun save(searchServiceEntity: SearchServiceEntity) @RawQuery(observedEntities = [SearchServiceEntity::class]) suspend fun getAll(query: SupportSQLiteQuery): List<SearchServiceEntity> @Query( """SELECT * FROM search_service WHERE expense_id =:expenseId """ ) suspend fun findByExpenseId(expenseId: String): SearchServiceEntity? @Query("delete from search_service where expense_id = :expenseId") suspend fun remove(expenseId: String): Int @Query("delete from search_service") suspend fun removeAll() }
0
Kotlin
0
0
3213bca91abc9aae68f43b5b2b627561ee1437b9
973
wallet
Apache License 2.0
app/src/main/java/com/example/exoplayer/PlayerActivity.kt
amalalbert
712,886,790
false
{"Kotlin": 43299}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.exoplayer import UnzipUtils import android.annotation.SuppressLint import android.app.DownloadManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.WindowManager import android.widget.ImageButton import android.widget.ImageView import android.widget.PopupMenu import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.ContextThemeWrapper import androidx.core.net.toUri import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.media3.common.C import androidx.media3.common.Format import androidx.media3.common.MediaItem import androidx.media3.common.MimeTypes import androidx.media3.common.Player import androidx.media3.common.TrackSelectionParameters import androidx.media3.common.Tracks import androidx.media3.datasource.DefaultDataSource import androidx.media3.datasource.okhttp.OkHttpDataSource import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.hls.HlsMediaSource import androidx.media3.exoplayer.mediacodec.MediaCodecSelector import androidx.media3.exoplayer.source.MediaSource import androidx.media3.exoplayer.trackselection.TrackSelectionArray import androidx.media3.ui.PlayerView.SHOW_BUFFERING_ALWAYS import com.bumptech.glide.Glide import com.example.exoplayer.databinding.ActivityPlayerBinding import com.example.exoplayer.models.Audio import com.example.exoplayer.models.Resolution import com.example.exoplayer.utils.ExoUtils.cookieBuilder import com.example.exoplayer.utils.ExoUtils.downloadAndSaveFile import com.example.exoplayer.utils.ExoUtils.generateMediaSource import com.example.exoplayer.utils.LoggingInterceptor import com.franmontiel.persistentcookiejar.PersistentCookieJar import com.franmontiel.persistentcookiejar.cache.SetCookieCache import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor import com.github.rubensousa.previewseekbar.PreviewBar import com.github.rubensousa.previewseekbar.PreviewBar.OnScrubListener import com.github.rubensousa.previewseekbar.media3.PreviewTimeBar import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.Cache import okhttp3.Cookie import okhttp3.CookieJar import okhttp3.HttpUrl import okhttp3.OkHttpClient import java.io.File import java.time.Instant import java.util.Date private const val TAG = "PlayerActivity" /** * A fullscreen activity to play audio or video streams. */ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) class PlayerActivity : AppCompatActivity() { private val viewBinding by lazy(LazyThreadSafetyMode.NONE) { ActivityPlayerBinding.inflate(layoutInflater) } lateinit var downloadCompleteLiveData :LiveData<Boolean> lateinit var subtitleSelectionPopup : PopupMenu lateinit var resolutionSelectorPopup : PopupMenu lateinit var audioSelectorPopup : PopupMenu private var lastSelectedAudioTrack : MenuItem? = null private var lastSelectedVideoTrack : MenuItem? = null private var lastSelectedSubtitleTrack : MenuItem? = null private val playbackStateListener : Player.Listener = playbackStateListener() private var player : ExoPlayer? = null private var playWhenReady = true private var downloadPath : File? = null private var mediaItemIndex = 0 private var playbackPosition = 0L private var previewTimeBar : PreviewTimeBar? = null private var mediaCodecSelector : MediaCodecSelector? = null private lateinit var mediaSource : MediaSource private var sublist : ArrayList<String>? = arrayListOf() private var reslist : ArrayList<Resolution>? = arrayListOf() private var audiolist : ArrayList<Audio>? = arrayListOf() private var resumeVideoOnPreviewStop : Boolean = false private var thumbnailCache : File? = null private lateinit var downloadManager : DownloadManager private var reference : Long = 0L companion object { val cookies: ArrayList<Cookie?> = arrayListOf() private val httpurl = HttpUrl.Builder() .scheme("https") .host("d2ikp5103loz36.cloudfront.net") .addPathSegment("/trailer") .build() private val expiryDate: Date = Date.from(Instant.parse("2024-11-06T08:37:10Z")) init { cookies.add( cookieBuilder( "CloudFront-Policy", "<KEY> expiryDate, httpurl ) ) cookies.add( cookieBuilder( "CloudFront-Signature", "<KEY> expiryDate, httpurl ) ) cookies.add( cookieBuilder( "CloudFront-Key-Pair-Id", "<KEY>", expiryDate, httpurl ) ) } } @RequiresApi(Build.VERSION_CODES.Q) @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val zipPath = File(filesDir,"download.zip") val fileUrl = "htps://drive.google.com/u/0/uc?id=1kJBRwxxcLHCkkqZbAGJ5LGttR5fCDTNw&export=download" downloadPath = File(filesDir,"thumbnails") if(downloadPath?.exists() == true){ downloadPath?.delete() } lifecycleScope.launch { downloadCompleteLiveData = downloadAndSaveFile(this@PlayerActivity, fileUrl, filesDir!!.absolutePath) downloadCompleteLiveData.observe(this@PlayerActivity, Observer { downloadComplete -> if (downloadComplete) { // Download is complete Log.d("DownloadStatus", "Download complete") try { File(filesDir, "").also { it.mkdir() thumbnailCache = File(it, "thumbnails") if (!thumbnailCache!!.exists()){ thumbnailCache!!.mkdir() } thumbnailCache?.listFiles()?.forEach { prevThumbs-> prevThumbs.delete() } downloadPath?.let { downloadPath -> downloadPath.mkdir() UnzipUtils.unzip(zipPath, it.absolutePath) } } } catch (e:Exception){ e.printStackTrace() } // Update the UI accordingly } else { // Download failed Log.e("DownloadStatus", "Download failed") lifecycleScope.launch { downloadCompleteLiveData = downloadAndSaveFile( this@PlayerActivity, fileUrl, filesDir!!.absolutePath ) } // Handle download failure } }) } viewBinding.button.isEnabled = false viewBinding.etLink.setTextColor(resources.getColor(R.color.white)) viewBinding.etLink.clearFocus() previewTimeBar = viewBinding.videoView.findViewById(androidx.media3.ui.R.id.exo_progress) previewTimeBar?.setPreviewLoader { currentPosition, max -> if (player?.isPlaying == true) { player?.playWhenReady = true; } val imageView:ImageView = viewBinding.videoView.findViewById(R.id.imageView) try { Glide.with(imageView) .load(thumbnailBasedOnPositionFromFile(thumbnailCache,10000,currentPosition)) .into(imageView) } catch (e:Exception){ Glide.with(imageView) .load(R.color.black) .into(imageView) lifecycleScope.launch { downloadCompleteLiveData = downloadAndSaveFile(this@PlayerActivity, fileUrl, filesDir!!.absolutePath) downloadCompleteLiveData.observe(this@PlayerActivity, Observer { downloadComplete -> if (downloadComplete) { // Download is complete Log.d("DownloadStatus", "Download complete") try { File(filesDir, "").also { it.mkdir() thumbnailCache = File(it, "thumbnails") if (thumbnailCache?.exists() == false){ thumbnailCache?.mkdir() } thumbnailCache?.listFiles()?.forEach { prevThumbs-> prevThumbs.delete() } downloadPath?.let { downloadPath -> downloadPath.mkdir() UnzipUtils.unzip(zipPath, it.absolutePath) } } } catch (e:Exception){ e.printStackTrace() } // Update the UI accordingly } else { // Download failed Log.e("DownloadStatus", "Download failed") lifecycleScope.launch { downloadCompleteLiveData = downloadAndSaveFile( this@PlayerActivity, fileUrl, filesDir!!.absolutePath ) } // Handle download failure } }) } } } previewTimeBar?.addOnPreviewVisibilityListener { previewBar, isPreviewShowing -> Log.d("PreviewShowing", "$isPreviewShowing") } previewTimeBar?.addOnScrubListener(object : OnScrubListener { override fun onScrubStart(previewBar: PreviewBar?) { Log.d("Scrub", "START"); } override fun onScrubMove(previewBar: PreviewBar?, progress: Int, fromUser: Boolean) { Log.d("Scrub", "MOVE to " + progress / 1000 + " FROM USER: " + fromUser); } override fun onScrubStop(previewBar: PreviewBar?) { Log.d("Scrub", "STOP"); } }) viewBinding.etLink.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { //no op } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { viewBinding.button.isEnabled = s?.contains(".mpd") == true || s?.contains(".m3u8") == true } override fun afterTextChanged(s: Editable?) { //no op } }) // generate source on click viewBinding.button.setOnClickListener { viewBinding.etLink.text.let {text-> generateMediaSource( text.toString(), this, cookies, httpurl )?.let { mediaSource = it releasePlayer() initializePlayer() } } } // set the media source generateMediaSource(getString(R.string.media_url_encrypted),this, cookies, httpurl )?.let { mediaSource = it } } override fun onStart() { super.onStart() if (player == null) { initializePlayer() } } override fun onResume() { super.onResume() hideSystemUi() if (player == null) { initializePlayer() } } override fun onPause() { super.onPause() player?.pause() } override fun onDestroy() { releasePlayer() super.onDestroy() } /** * Function to initialize the player, set the source and */ private fun initializePlayer() { // ExoPlayer implements the Player interface player = ExoPlayer.Builder(this) .build() .also { exoPlayer -> viewBinding.videoView.player = exoPlayer // Update the track selection parameters to only pick standard definition tracks exoPlayer.trackSelectionParameters = exoPlayer.trackSelectionParameters .buildUpon() .setMaxVideoSize(1921,828) .setPreferredTextLanguage("en") .build() exoPlayer.setMediaSource(mediaSource) exoPlayer.playWhenReady = playWhenReady exoPlayer.addListener(playbackStateListener) this.resumeVideoOnPreviewStop = true exoPlayer.prepare() } player?.trackSelectionParameters = player?.trackSelectionParameters ?.buildUpon()?.setPreferredTextLanguage("en") ?.build()!! viewBinding.videoView.findViewById<ImageButton>(androidx.media3.ui.R.id.exo_pause) .setOnClickListener { player?.pause() } viewBinding.videoView.findViewById<ImageButton>(androidx.media3.ui.R.id.exo_play) .setOnClickListener { player?.play() } val wrapper: Context = ContextThemeWrapper(this, androidx.appcompat.R.style.ThemeOverlay_AppCompat_Dark_ActionBar) //audio selector audioSelectorPopup = PopupMenu(wrapper,viewBinding.videoView.findViewById(R.id.audio)) audioSelectorPopup.menuInflater.inflate(R.menu.popup_menu,audioSelectorPopup.menu) audioSelectorPopup.menu.setGroupCheckable(0,true,true) audioSelectorPopup.setOnMenuItemClickListener { item -> if(lastSelectedAudioTrack != null){ lastSelectedAudioTrack?.isChecked = false } lastSelectedAudioTrack = item item.isCheckable = true item.isChecked = true lateinit var selectedAudioTrack:Audio audiolist?.forEach { audio-> if(audio.trackId == item.title){ selectedAudioTrack = audio } } player?.trackSelectionParameters = player?.trackSelectionParameters ?.buildUpon()?.setPreferredAudioLanguage(selectedAudioTrack.trackName) ?.build()!! true } audioSelectorPopup.setOnDismissListener { lastSelectedAudioTrack?.let { it1 -> it.menu.findItem(it1.itemId).isChecked = true } } //subtitle selector subtitleSelectionPopup = PopupMenu(wrapper,viewBinding.videoView.findViewById(R.id.sub)) subtitleSelectionPopup.menuInflater.inflate(R.menu.popup_menu,subtitleSelectionPopup.menu) subtitleSelectionPopup.menu.setGroupCheckable(0,true,true) subtitleSelectionPopup.setOnMenuItemClickListener { item -> if(lastSelectedSubtitleTrack != null){ lastSelectedSubtitleTrack?.isChecked = false } lastSelectedSubtitleTrack = item item.isCheckable = true item.isChecked = true player?.trackSelectionParameters = player?.trackSelectionParameters ?.buildUpon()?.setPreferredTextLanguage(item.title.toString()) ?.build()!! true } //resolution selector resolutionSelectorPopup = PopupMenu(wrapper,viewBinding.videoView.findViewById(R.id.resolution)) resolutionSelectorPopup.menuInflater.inflate(R.menu.popup_menu,subtitleSelectionPopup.menu) resolutionSelectorPopup.menu.setGroupCheckable(0,true,true) resolutionSelectorPopup.setOnMenuItemClickListener {item -> Log.d("amal", "initializePlayer:${item.itemId} ") if(lastSelectedVideoTrack != null){ lastSelectedVideoTrack?.isChecked = false } lastSelectedVideoTrack = item item.isCheckable = true val selectedItemId = item.itemId lateinit var selectedResolution:Resolution reslist?.forEach { if(it.id?.toInt() == selectedItemId){ selectedResolution = it } } selectedResolution.let { player?.trackSelectionParameters = player?.trackSelectionParameters ?.buildUpon()?. setMaxVideoSize(selectedResolution.width,selectedResolution.height) ?.build()!! } item.isChecked = true true } viewBinding.videoView.setShowSubtitleButton(true) viewBinding.videoView.showController() viewBinding.videoView.setShowBuffering(SHOW_BUFFERING_ALWAYS) viewBinding.videoView.controllerShowTimeoutMs = 2000 viewBinding.videoView.controllerHideOnTouch = true Handler(Looper.getMainLooper()).postDelayed({ viewBinding.videoView.hideController() },500) viewBinding.videoView.setOnClickListener { } viewBinding.videoView.findViewById<ImageButton>(R.id.sub) .setOnClickListener { lastSelectedSubtitleTrack?.itemId?.let { it1 -> subtitleSelectionPopup.menu.findItem(it1).setChecked(true) } subtitleSelectionPopup.show() } viewBinding.videoView.findViewById<ImageButton>(R.id.resolution) .setOnClickListener { lastSelectedVideoTrack?.itemId?.let {it2-> resolutionSelectorPopup.menu.findItem(it2).setChecked(true) } resolutionSelectorPopup.show() } viewBinding.videoView.findViewById<ImageButton>(R.id.audio).setOnClickListener { lastSelectedAudioTrack?.itemId?.let {it2-> audioSelectorPopup.menu.findItem(it2).setChecked(true) } audioSelectorPopup.show() } } /** * Releases the already initialized player. */ private fun releasePlayer() { player?.let { player -> playbackPosition = player.currentPosition mediaItemIndex = player.currentMediaItemIndex playWhenReady = player.playWhenReady player.removeListener(playbackStateListener) player.release() } player = null } @SuppressLint("InlinedApi") /** * Hides the System Navbar */ private fun hideSystemUi() { WindowCompat.setDecorFitsSystemWindows(window, false) WindowInsetsControllerCompat(window, viewBinding.videoView).let { controller -> controller.hide(WindowInsetsCompat.Type.systemBars()) controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } /** *@return object of Player.Listener */ private fun playbackStateListener() = object : Player.Listener { override fun onPlaybackStateChanged(playbackState: Int) { if (playbackState == ExoPlayer.STATE_READY){ viewBinding.videoView. findViewById<PreviewTimeBar>(androidx.media3.ui.R.id.exo_progress).hidePreview() } val stateString: String = when (playbackState) { ExoPlayer.STATE_IDLE -> "ExoPlayer.STATE_IDLE -" ExoPlayer.STATE_BUFFERING -> "ExoPlayer.STATE_BUFFERING -" ExoPlayer.STATE_READY -> "ExoPlayer.STATE_READY -" ExoPlayer.STATE_ENDED -> "ExoPlayer.STATE_ENDED -" else -> "UNKNOWN_STATE -" } Log.d(TAG, "changed state to $stateString") } override fun onTracksChanged(tracks: Tracks) { if (sublist?.isNotEmpty() == true){ sublist?.clear() } if (reslist?.isNotEmpty() == true){ reslist?.clear() } if (audiolist?.isNotEmpty() == true){ audiolist?.clear() } super.onTracksChanged(tracks) val trackGroupList = tracks.groups for (trackGroup in trackGroupList) { // Group level information. val trackType: @C.TrackType Int = trackGroup.type if (trackType == C.TRACK_TYPE_TEXT) { val videoTrackGroup = trackGroup.mediaTrackGroup for (i in 0 until trackGroup.mediaTrackGroup.length) { val trackFormat: Format = videoTrackGroup.getFormat(i) trackFormat.language?.let { sublist?.add(it) } } } if(trackType == C.TRACK_TYPE_AUDIO){ val audioTrackGroup = trackGroup.mediaTrackGroup for (i in 0 until audioTrackGroup.length) { val trackFormat: Format = audioTrackGroup.getFormat(i) audiolist?.add(Audio(trackFormat.language,trackFormat.label, trackFormat.id )) } } if(trackType == C.TRACK_TYPE_VIDEO){ val audioTrackGroup = trackGroup.mediaTrackGroup for (i in 0 until audioTrackGroup.length) { val trackFormat: Format = audioTrackGroup.getFormat(i) reslist?.add(Resolution(trackFormat.width,trackFormat.height ,trackFormat.id)) } } } audioSelectorPopup.menu.clear() audiolist?.forEach { it.trackId?.let {trackid-> audioSelectorPopup.menu.add(Menu.NONE, audiolist!!.indexOf(it),Menu.NONE,trackid).apply { this.isCheckable = true } } } subtitleSelectionPopup.menu.clear() sublist?.forEach { subtitleSelectionPopup.menu.add(it).apply { this.isCheckable = true } } resolutionSelectorPopup.menu.clear() reslist?.forEach { it.id?.toInt()?.let { it1 -> resolutionSelectorPopup.menu.add(Menu.NONE, it1,Menu.NONE,"${it.width}p").apply { this.isCheckable = true } } } } } /** * @param file File representation of current thumbnail directory. * @param threshold The value of the aggregate used to calculate the index of file to be * shown as thumbnail. * @param currentPosition The value of current position in millis. * @return File at the calculated index */ private fun thumbnailBasedOnPositionFromFile (file:File?, threshold:Int, currentPosition:Long):File?{ return file?.listFiles()?.get((currentPosition/threshold).toInt()) } private fun cloudFrontHttpsSource(url: String, context: Context): HlsMediaSource { val mediaItem = MediaItem.Builder() .setUri(Uri.parse(url)) .setMimeType(MimeTypes.APPLICATION_M3U8) .build() cookies.add( cookieBuilder( "CloudFront-Policy", "<KEY>", expiryDate, httpurl ) ) cookies.add( cookieBuilder( "CloudFront-Signature", "<KEY> expiryDate, httpurl ) ) cookies.add(cookieBuilder("CloudFront-Key-Pair-Id", "<KEY>", expiryDate, httpurl)) val interceptor = LoggingInterceptor() val cookieJar: CookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(context)) cookieJar.saveFromResponse( httpurl, cookies.toList() as List<Cookie> ) val client = OkHttpClient.Builder() .addInterceptor(interceptor) .cookieJar(cookieJar) .cache(Cache(cacheDir, 4096)) .build() val httpDataSourceFactory = OkHttpDataSource.Factory(client) val dataSourceFactory = DefaultDataSource.Factory( context, httpDataSourceFactory ) return HlsMediaSource.Factory(dataSourceFactory) .createMediaSource(mediaItem) } }
0
Kotlin
0
0
db33d51e233f428226a0ba88ca2ed973fc99532c
26,958
exoplayer_streaming
Apache License 2.0
app/src/main/java/com/moriswala/booking/data/local/CityDao.kt
moriswala
423,035,445
false
{"Kotlin": 58609}
package com.moriswala.booking.data.local import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.moriswala.booking.data.entities.Booking import com.moriswala.booking.data.entities.City @Dao interface CityDao { @Query("SELECT * FROM cities") fun getAllCities() : LiveData<List<City>> @Query("SELECT * FROM cities WHERE id = :id") fun getCity(id: Int): LiveData<City> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(cities: List<City>) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(city: City) }
0
Kotlin
0
2
d86c6966951a27e20f464d230ed46cac672af430
688
android-mvvm-architecture-sample
Apache License 2.0
plugins/bin/main/Com_escodro_androidLibraryPlugin.kt
AuriStark
595,647,251
false
null
/** * Precompiled [com.escodro.android-library.gradle.kts][Com_escodro_android_library_gradle] script plugin. * * @see Com_escodro_android_library_gradle */ public class Com_escodro_androidLibraryPlugin : org.gradle.api.Plugin<org.gradle.api.Project> { override fun apply(target: org.gradle.api.Project) { try { Class .forName("Com_escodro_android_library_gradle") .getDeclaredConstructor(org.gradle.api.Project::class.java, org.gradle.api.Project::class.java) .newInstance(target, target) } catch (e: java.lang.reflect.InvocationTargetException) { throw e.targetException } } }
0
Kotlin
0
0
dcfe329d1f9af11da3fc99e29945797fa7bfebb9
687
alkaa-main
Apache License 2.0
common/common-fast-serialization/src/main/kotlin/com/testerum/common_fast_serialization/debug/DumpSerializedFile.kt
testerum
241,460,788
false
{"Text": 47, "Gradle Kotlin DSL": 62, "Shell": 17, "Batchfile": 16, "Maven POM": 71, "Java Properties": 2, "Ignore List": 8, "Git Attributes": 1, "EditorConfig": 5, "Markdown": 8, "Kotlin": 1089, "Java": 27, "JSON": 161, "INI": 3, "XML": 30, "JavaScript": 36, "Gherkin": 1, "HTML": 232, "JSON with Comments": 11, "Browserslist": 4, "SVG": 4, "SCSS": 222, "CSS": 12, "YAML": 2, "Dotenv": 1, "Groovy": 1, "Ant Build System": 1}
package com.testerum.common_fast_serialization.debug import com.testerum.common_fast_serialization.read_write.FastInput import com.testerum.common_kotlin.doesNotExist import java.io.BufferedInputStream import java.nio.file.Files import java.nio.file.Paths import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.size != 1) { System.err.println("SYNTAX: DumpSerializedFileKt </path/to/file.tfsf>") exitProcess(1) } val filePath = Paths.get(args[0]) .toAbsolutePath() .normalize() if (filePath.doesNotExist) { System.err.println("ERROR: file at path [$filePath] does not exist") exitProcess(2) } val fastInput = BufferedInputStream(Files.newInputStream(filePath)).use { inputStream -> FastInput.readFrom(inputStream) } val sortedMap = fastInput.asSortedMap() if (sortedMap.isEmpty()) { println(">>>>> the file is empty <<<<<") return } for ((key, value) in sortedMap) { val keyForDisplay = "[$key]" val valueForDisplay = "[$value]" println("$keyForDisplay = $valueForDisplay") } }
33
Kotlin
3
22
0a53c71b5f659e41282114127f595aad5ab1e4fb
1,148
testerum
Apache License 2.0
app/src/main/java/com/koleff/kare_android/domain/wrapper/ExerciseListWrapper.kt
MartinKoleff
741,013,199
false
{"Kotlin": 655085}
package com.koleff.kare_android.domain.wrapper import com.koleff.kare_android.data.model.response.GetExercisesResponse class ExerciseListWrapper(getExercisesResponse: GetExercisesResponse) : ServerResponseData(getExercisesResponse) { val exercises = getExercisesResponse.exercises }
15
Kotlin
0
4
e31db6fb293ae0b00fd9c4526b1f8d5c2be64b67
292
KareFitnessApp
MIT License
app/src/test/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsUtilsTest.kt
s-buvaka
229,900,052
true
{"Kotlin": 83865}
package com.example.android.architecture.blueprints.todoapp.statistics import com.example.android.architecture.blueprints.todoapp.data.Task import org.hamcrest.MatcherAssert import org.hamcrest.core.Is import org.junit.Test class StatisticsUtilsTest { @Test fun getActiveAndCompletedStats_noCompleted_returnsHundredZero() { val tasks = listOf(Task("title", "desc", isCompleted = false)) val result = getActiveAndCompletedStats(tasks) MatcherAssert.assertThat(result.activeTasksPercent, Is.`is`(100f)) MatcherAssert.assertThat(result.completedTasksPercent, Is.`is`(0f)) } @Test fun getActiveAndCompletedStats_noActive_returnsZeroHundred() { val tasks = listOf(Task("title", "desc", isCompleted = true)) val result = getActiveAndCompletedStats(tasks) MatcherAssert.assertThat(result.activeTasksPercent, Is.`is`(0f)) MatcherAssert.assertThat(result.completedTasksPercent, Is.`is`(100f)) } @Test fun getActiveAndCompletedStats_noCompleted_returnsForSixty() { val tasks = listOf( Task(title = "Title1", description = "Description1", isCompleted = true), Task(title = "Title2", description = "Description2", isCompleted = false), Task(title = "Title3", description = "Description3", isCompleted = false), Task(title = "Title4", description = "Description4", isCompleted = true), Task(title = "Title5", description = "Description5", isCompleted = true)) val result = getActiveAndCompletedStats(tasks) MatcherAssert.assertThat(result.completedTasksPercent, Is.`is`(60F)) MatcherAssert.assertThat(result.activeTasksPercent, Is.`is`(40F)) } @Test fun getActiveAndCompletedStats_empty_returnsZeros() { val tasks = emptyList<Task>() val result = getActiveAndCompletedStats(tasks) MatcherAssert.assertThat(result.completedTasksPercent, Is.`is`(0F)) MatcherAssert.assertThat(result.activeTasksPercent, Is.`is`(0F)) } @Test fun getActiveAndCompletedStats_empty_returnsNull() { val tasks = null val result = getActiveAndCompletedStats(tasks) MatcherAssert.assertThat(result.completedTasksPercent, Is.`is`(0F)) MatcherAssert.assertThat(result.activeTasksPercent, Is.`is`(0F)) } }
0
Kotlin
0
0
695c55106384c6cd5e305b0850fdeaa89379d1ed
2,375
android-testing
Apache License 2.0
src/main/kotlin/ceribe/distributed_monitor/DistributedMonitor.kt
ceribe
484,787,493
false
{"Kotlin": 10805}
package ceribe.distributed_monitor import org.zeromq.SocketType import org.zeromq.ZMQ import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.thread import kotlin.concurrent.withLock /** * @param index index of the process which uses this monitor * @param addresses list of addresses of all processes * @param startDelay amount of milliseconds that monitor will wait before executing the first task * @param finishTimeout amount of milliseconds that monitor will wait after [die] is called before dying */ class DistributedMonitor<T>( constructor: () -> T, private val index: Int, addresses: List<String>, private val startDelay: Long = 5000, private val finishTimeout: Long = 2000 ) where T : SerializableState { private val state: T = constructor() private val numberOfProcesses = addresses.size private var token: Token? = null private val rn: MutableList<Int> private val lock = ReentrantLock() private val condition = lock.newCondition() private val pubSocket: ZMQ.Socket private val subSocket: ZMQ.Socket private lateinit var communicationThread: Thread init { // Init Suzuki-Kasami algorithm if (index == 0) { token = Token(mutableListOf(), MutableList(numberOfProcesses) { 0 }) } rn = MutableList(numberOfProcesses) { 0 } // Init publishing socket val context = ZMQ.context(1) pubSocket = context.socket(SocketType.PUB) pubSocket.bind("tcp://${addresses[index]}") // Init subscribing socket subSocket = ZMQ.context(1).socket(SocketType.SUB) subSocket.subscribe("".toByteArray()) val otherProcessesAddresses = addresses.filterIndexed { i, _ -> i != index } otherProcessesAddresses.forEach { subSocket.connect("tcp://$it") } startCommunicationThread() // Give other processes time to start Thread.sleep(startDelay) } private fun startCommunicationThread() { communicationThread = thread(start = true) { while (true) { val message = subSocket.recv() val firstInt = message.getInt(0) if (firstInt == 0) { processRequestMessage(message) } else if (firstInt - 1 == index) { lock.withLock { processTokenMessage(message) condition.signalAll() } } } } } /** * Tries to execute given [task]. * If [canTaskBeExecuted] returns true, then [task] is executed. * Otherwise, gives token up and requests it again. * Will try until it succeeds. After finishing [task] token will be sent to other process or * if queue is empty, token will stay in this monitor. */ fun execute(canTaskBeExecuted: T.() -> Boolean = { true }, task: T.() -> Unit) { var executed = false while (!executed) { if (token == null) { rn[index]++ pubSocket.send(composeRequestMessage()) } lock.withLock { while (token == null) { condition.await() } if (state.canTaskBeExecuted()) { state.apply(task) executed = true } updateQueueAndTryToSendToken() } } } /** * Adds all processes which requested token to queue and * sends it to first process in queue. If queue is empty, * token stays in this monitor. Should only be called * if this process holds token. */ private fun updateQueueAndTryToSendToken() { token!!.ln[index] = rn[index] for (i in 0 until numberOfProcesses) { val isIndexInQueue = token!!.queue.contains(i+1) val isWaitingForCriticalSection = token!!.ln[i] + 1 == rn[i] if (!isIndexInQueue && isWaitingForCriticalSection) { token!!.queue.add(i+1) } } val processNumber = token!!.queue.removeFirstOrNull() if (processNumber != null) { pubSocket.send(composeTokenMessage(processNumber)) token = null } } /** * Waits until someone requests the token and sends it. After timeout communication thread dies forcibly. * Monitor should not be used after calling this method. */ fun die() { var remainingTimeout = finishTimeout while (token != null && remainingTimeout > 0) { updateQueueAndTryToSendToken() Thread.sleep(50) remainingTimeout -= 50 } communicationThread.setUncaughtExceptionHandler { _: Thread, _: Throwable -> } communicationThread.interrupt() } /** * Returns a ByteArray containing 0, this process's number and its request number. */ private fun composeRequestMessage(): ByteArray { return listOf(0, index + 1, rn[index]).toByteArray() } /** * Returns a ByteArray containing processNumber, serialized token and serialized state. */ private fun composeTokenMessage(processNumber: Int): ByteArray { token?.let { return processNumber.toByteArray() + it.serialize() + state.serialize() } throw NullPointerException("Token is null") } /** * Reads given [message] and updates rn list. */ private fun processRequestMessage(message: ByteArray) { val senderNumber = message.getInt(1) val requestNumber = message.getInt(2) rn[senderNumber - 1] = maxOf(rn[senderNumber - 1], requestNumber) } /** * Reads given [message] and updates token and state. */ private fun processTokenMessage(message: ByteArray) { token = Token() val messageWithoutProcessNumber = message.copyOfRange(4, message.size) val offset = token!!.deserialize(messageWithoutProcessNumber, numberOfProcesses) val stateBytes = message.sliceArray(4 + offset until message.size) state.deserialize(stateBytes) } }
0
Kotlin
0
0
f774bdbe5a3248f1edffe51745a9bac2bee249df
6,210
distributed-monitor
The Unlicense
src/main/kotlin/ps/api/module/session/endpoint/TicketEndpoint.kt
marek-hanzal
394,701,910
false
null
package ps.api.module.session.endpoint import io.ktor.application.* import io.ktor.auth.* import leight.client.sdk.annotation.Sdk import leight.client.sdk.annotation.TypeClass import leight.container.IContainer import leight.rest.* import leight.session.SessionTicket import leight.storage.lazyStorage import ps.session.dto.SessionDto import ps.session.mapper.lazyTicketToSessionMapper import ps.storage.module.session.repository.lazyTicketRepository import ps.user.mapper.lazyUserToSessionMapper @Sdk( response = TypeClass(SessionDto::class), ) @Endpoint( public = true, method = EndpointMethod.GET, ) class TicketEndpoint(container: IContainer) : AbstractEndpoint(container) { private val storage by container.lazyStorage() private val ticketRepository by container.lazyTicketRepository() private val ticketToSessionMapper by container.lazyTicketToSessionMapper() private val userToSessionMapper by container.lazyUserToSessionMapper() override suspend fun handle(call: ApplicationCall): Response<*> = call.authentication.principal<SessionTicket>()?.let { sessionTicket -> storage.read { ticketRepository.findByTicket(sessionTicket.id)?.let { ticketEntity -> ok(ticketToSessionMapper.map(ticketEntity)) } } } ?: ok(userToSessionMapper.public()) }
10
Kotlin
0
0
1eb59387ac54d0799b5805b905b2488a2bca48ca
1,274
puff-smith
Apache License 2.0
src/main/kotlin/com/mqgateway/core/gatewayconfig/homeassistant/HomeAssistantConverter.kt
alemoke
407,462,631
false
{"Groovy": 189986, "Kotlin": 162270, "Shell": 3776}
package com.mqgateway.core.gatewayconfig.homeassistant import com.mqgateway.core.device.EmulatedSwitchButtonDevice import com.mqgateway.core.device.MotionSensorDevice import com.mqgateway.core.device.ReedSwitchDevice import com.mqgateway.core.device.RelayDevice import com.mqgateway.core.device.ShutterDevice import com.mqgateway.core.device.SingleButtonsGateDevice import com.mqgateway.core.device.SwitchButtonDevice import com.mqgateway.core.device.mysensors.MySensorsDevice import com.mqgateway.core.gatewayconfig.DeviceConfig import com.mqgateway.core.gatewayconfig.DevicePropertyType import com.mqgateway.core.gatewayconfig.DeviceType import com.mqgateway.core.gatewayconfig.Gateway import com.mqgateway.core.gatewayconfig.homeassistant.HomeAssistantComponentType.LIGHT import com.mqgateway.core.gatewayconfig.homeassistant.HomeAssistantCover.DeviceClass import com.mqgateway.core.gatewayconfig.homeassistant.HomeAssistantTrigger.TriggerType.BUTTON_LONG_PRESS import com.mqgateway.core.gatewayconfig.homeassistant.HomeAssistantTrigger.TriggerType.BUTTON_LONG_RELEASE import com.mqgateway.core.gatewayconfig.homeassistant.HomeAssistantTrigger.TriggerType.BUTTON_SHORT_PRESS import com.mqgateway.core.gatewayconfig.homeassistant.HomeAssistantTrigger.TriggerType.BUTTON_SHORT_RELEASE import com.mqgateway.homie.HOMIE_PREFIX import mu.KotlinLogging private val LOGGER = KotlinLogging.logger {} class HomeAssistantConverter(private val gatewayFirmwareVersion: String) { fun convert(gateway: Gateway): List<HomeAssistantComponent> { LOGGER.info { "Converting Gateway configuration to HomeAssistant auto-discovery config" } val devices = gateway.rooms .flatMap { it.points } .flatMap { it.devices } val mqGatewayCoreComponents = convertMqGatewayRootDeviceToHaSensors(gateway) return mqGatewayCoreComponents + devices.flatMap { device -> val haDevice = HomeAssistantDevice( identifiers = listOf("${gateway.name}_${device.id}"), name = device.name, manufacturer = "Aetas", viaDevice = gateway.name, firmwareVersion = gatewayFirmwareVersion, model = "MqGateway ${device.type.name}" ) val basicProperties = HomeAssistantComponentBasicProperties(haDevice, gateway.name, device.id) return@flatMap toHomeAssistantComponents(device, haDevice, basicProperties, gateway) } } private fun toHomeAssistantComponents( device: DeviceConfig, haDevice: HomeAssistantDevice, basicProperties: HomeAssistantComponentBasicProperties, gateway: Gateway ): List<HomeAssistantComponent> { val components = when (device.type) { DeviceType.REFERENCE -> { toHomeAssistantComponents(device.dereferenceIfNeeded(gateway), haDevice, basicProperties, gateway) } DeviceType.RELAY -> { val stateTopic = homieStateTopic(gateway, device.id, DevicePropertyType.STATE) val commandTopic = homieCommandTopic(gateway, device, DevicePropertyType.STATE) if (device.config[DEVICE_CONFIG_HA_COMPONENT].equals(LIGHT.value, true)) { listOf(HomeAssistantLight(basicProperties, device.name, stateTopic, commandTopic, true, RelayDevice.STATE_ON, RelayDevice.STATE_OFF)) } else { listOf(HomeAssistantSwitch(basicProperties, device.name, stateTopic, commandTopic, true, RelayDevice.STATE_ON, RelayDevice.STATE_OFF)) } } DeviceType.SWITCH_BUTTON -> { val homieStateTopic = homieStateTopic(gateway, device.id, DevicePropertyType.STATE) when { device.config[DEVICE_CONFIG_HA_COMPONENT].equals(HomeAssistantComponentType.TRIGGER.value, true) -> { listOf( HomeAssistantTrigger( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_PRESS"), homieStateTopic, SwitchButtonDevice.PRESSED_STATE_VALUE, BUTTON_SHORT_PRESS, "button" ), HomeAssistantTrigger( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_RELEASE"), homieStateTopic, SwitchButtonDevice.RELEASED_STATE_VALUE, BUTTON_SHORT_RELEASE, "button" ), HomeAssistantTrigger( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_LONG_PRESS"), homieStateTopic, SwitchButtonDevice.LONG_PRESSED_STATE_VALUE, BUTTON_LONG_PRESS, "button" ), HomeAssistantTrigger( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_LONG_RELEASE"), homieStateTopic, SwitchButtonDevice.LONG_RELEASED_STATE_VALUE, BUTTON_LONG_RELEASE, "button" ) ) } device.config[DEVICE_CONFIG_HA_COMPONENT].equals(HomeAssistantComponentType.SENSOR.value, true) -> { listOf( HomeAssistantSensor( basicProperties = basicProperties, name = device.name, stateTopic = homieStateTopic, deviceClass = HomeAssistantSensor.DeviceClass.NONE ) ) } else -> { listOf( HomeAssistantBinarySensor( basicProperties, device.name, homieStateTopic, SwitchButtonDevice.PRESSED_STATE_VALUE, SwitchButtonDevice.RELEASED_STATE_VALUE, HomeAssistantBinarySensor.DeviceClass.NONE ) ) } } } DeviceType.REED_SWITCH -> { listOf( HomeAssistantBinarySensor( basicProperties, device.name, homieStateTopic(gateway, device.id, DevicePropertyType.STATE), ReedSwitchDevice.OPEN_STATE_VALUE, ReedSwitchDevice.CLOSED_STATE_VALUE, HomeAssistantBinarySensor.DeviceClass.OPENING ) ) } DeviceType.MOTION_DETECTOR -> { listOf( HomeAssistantBinarySensor( basicProperties, device.name, homieStateTopic(gateway, device.id, DevicePropertyType.STATE), MotionSensorDevice.MOVE_START_STATE_VALUE, MotionSensorDevice.MOVE_STOP_STATE_VALUE, HomeAssistantBinarySensor.DeviceClass.MOTION ) ) } DeviceType.EMULATED_SWITCH -> { val stateTopic = homieStateTopic(gateway, device.id, DevicePropertyType.STATE) val commandTopic = homieCommandTopic(gateway, device, DevicePropertyType.STATE) listOf( HomeAssistantSwitch( basicProperties, device.name, stateTopic, commandTopic, false, EmulatedSwitchButtonDevice.PRESSED_STATE_VALUE, EmulatedSwitchButtonDevice.RELEASED_STATE_VALUE ) ) } DeviceType.BME280 -> { val availabilityTopic = homieStateTopic(gateway, device.id, DevicePropertyType.STATE) listOf( HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_TEMPERATURE"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.TEMPERATURE, homieStateTopic(gateway, device.id, DevicePropertyType.TEMPERATURE), device.type.property(DevicePropertyType.TEMPERATURE).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_HUMIDITY"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.HUMIDITY, homieStateTopic(gateway, device.id, DevicePropertyType.HUMIDITY), device.type.property(DevicePropertyType.HUMIDITY).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_PRESSURE"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.PRESSURE, homieStateTopic(gateway, device.id, DevicePropertyType.PRESSURE), device.type.property(DevicePropertyType.PRESSURE).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_LAST_PING"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.TIMESTAMP, homieStateTopic(gateway, device.id, DevicePropertyType.LAST_PING), device.type.property(DevicePropertyType.LAST_PING).unit.value ) ) } DeviceType.DHT22 -> { val availabilityTopic = homieStateTopic(gateway, device.id, DevicePropertyType.STATE) listOf( HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_TEMPERATURE"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.TEMPERATURE, homieStateTopic(gateway, device.id, DevicePropertyType.TEMPERATURE), device.type.property(DevicePropertyType.TEMPERATURE).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_HUMIDITY"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.HUMIDITY, homieStateTopic(gateway, device.id, DevicePropertyType.HUMIDITY), device.type.property(DevicePropertyType.HUMIDITY).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_LAST_PING"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.TIMESTAMP, homieStateTopic(gateway, device.id, DevicePropertyType.LAST_PING), device.type.property(DevicePropertyType.LAST_PING).unit.value ) ) } DeviceType.SCT013 -> { val availabilityTopic = homieStateTopic(gateway, device.id, DevicePropertyType.STATE) listOf( HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_POWER"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.POWER, homieStateTopic(gateway, device.id, DevicePropertyType.POWER), device.type.property(DevicePropertyType.POWER).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(haDevice, gateway.name, "${device.id}_LAST_PING"), device.name, availabilityTopic, MySensorsDevice.AVAILABILITY_ONLINE_STATE, MySensorsDevice.AVAILABILITY_OFFLINE_STATE, HomeAssistantSensor.DeviceClass.TIMESTAMP, homieStateTopic(gateway, device.id, DevicePropertyType.LAST_PING), device.type.property(DevicePropertyType.LAST_PING).unit.value ) ) } DeviceType.SHUTTER -> listOf( HomeAssistantCover( basicProperties, device.name, homieStateTopic(gateway, device.id, DevicePropertyType.STATE), homieCommandTopic(gateway, device, DevicePropertyType.STATE), homieStateTopic(gateway, device.id, DevicePropertyType.POSITION), homieCommandTopic(gateway, device, DevicePropertyType.POSITION), DeviceClass.SHUTTER, ShutterDevice.Command.OPEN.name, ShutterDevice.Command.CLOSE.name, ShutterDevice.Command.STOP.name, ShutterDevice.POSITION_OPEN, ShutterDevice.POSITION_CLOSED, ShutterDevice.State.OPEN.name, ShutterDevice.State.CLOSED.name, ShutterDevice.State.OPENING.name, ShutterDevice.State.CLOSING.name, null, false ) ) DeviceType.TIMER_SWITCH -> listOf() DeviceType.GATE -> listOf( HomeAssistantCover( basicProperties, device.name, homieStateTopic(gateway, device.id, DevicePropertyType.STATE), homieCommandTopic(gateway, device, DevicePropertyType.STATE), null, null, if (device.config[DEVICE_CONFIG_HA_DEVICE_CLASS].equals(DeviceClass.GATE.name, true)) DeviceClass.GATE else DeviceClass.GARAGE, SingleButtonsGateDevice.Command.OPEN.name, SingleButtonsGateDevice.Command.CLOSE.name, SingleButtonsGateDevice.Command.STOP.name, null, null, SingleButtonsGateDevice.State.OPEN.name, SingleButtonsGateDevice.State.CLOSED.name, SingleButtonsGateDevice.State.OPENING.name, SingleButtonsGateDevice.State.CLOSING.name, null, false ) ) DeviceType.MQGATEWAY -> throw IllegalArgumentException("MqGateway should not be configured as a device") } LOGGER.debug { "Device ${device.id} (${device.type}) converted to HA components types: ${components.map { it.componentType }}" } LOGGER.trace { "Device $device converted to HA components: $components" } return components } private fun convertMqGatewayRootDeviceToHaSensors(gateway: Gateway): List<HomeAssistantSensor> { val rootHaDevice = HomeAssistantDevice( identifiers = listOf(gateway.name), name = gateway.name, manufacturer = "Aetas", firmwareVersion = gatewayFirmwareVersion, model = "MqGateway" ) val availabilityTopic = "$HOMIE_PREFIX/${gateway.name}/\$state" val availabilityOnline = "ready" val availabilityOffline = "lost" return listOf( HomeAssistantSensor( HomeAssistantComponentBasicProperties(rootHaDevice, gateway.name, "${gateway.name}_CPU_TEMPERATURE"), "CPU temperature", availabilityTopic, availabilityOnline, availabilityOffline, HomeAssistantSensor.DeviceClass.TEMPERATURE, homieStateTopic(gateway, gateway.name, DevicePropertyType.TEMPERATURE), DeviceType.MQGATEWAY.property(DevicePropertyType.TEMPERATURE).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(rootHaDevice, gateway.name, "${gateway.name}_MEMORY_FREE"), "Free memory", availabilityTopic, availabilityOnline, availabilityOffline, HomeAssistantSensor.DeviceClass.NONE, homieStateTopic(gateway, gateway.name, DevicePropertyType.MEMORY), DeviceType.MQGATEWAY.property(DevicePropertyType.MEMORY).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(rootHaDevice, gateway.name, "${gateway.name}_UPTIME"), "Uptime", availabilityTopic, availabilityOnline, availabilityOffline, HomeAssistantSensor.DeviceClass.NONE, homieStateTopic(gateway, gateway.name, DevicePropertyType.UPTIME), DeviceType.MQGATEWAY.property(DevicePropertyType.UPTIME).unit.value ), HomeAssistantSensor( HomeAssistantComponentBasicProperties(rootHaDevice, gateway.name, "${gateway.name}_IP_ADDRESS"), "IP address", availabilityTopic, availabilityOnline, availabilityOffline, HomeAssistantSensor.DeviceClass.NONE, homieStateTopic(gateway, gateway.name, DevicePropertyType.IP_ADDRESS), DeviceType.MQGATEWAY.property(DevicePropertyType.IP_ADDRESS).unit.value ) ) } private fun homieStateTopic(gateway: Gateway, deviceId: String, propertyType: DevicePropertyType): String { return "$HOMIE_PREFIX/${gateway.name}/$deviceId/$propertyType" } private fun homieCommandTopic(gateway: Gateway, device: DeviceConfig, propertyType: DevicePropertyType): String { return homieStateTopic(gateway, device.id, propertyType) + "/set" } companion object { const val DEVICE_CONFIG_HA_COMPONENT: String = "haComponent" const val DEVICE_CONFIG_HA_DEVICE_CLASS: String = "haDeviceClass" } }
0
null
0
0
076a162d0e2f9f86256b4e146d6ae33243e11cc6
17,228
mqgateway
MIT License
app/src/main/java/com/matthew/sportiliapp/admin/UtenteScreen.kt
matthew-2000
809,730,971
false
{"Kotlin": 167133}
package com.matthew.sportiliapp.admin import android.util.Log import android.widget.Toast import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.matthew.sportiliapp.model.Giorno import com.matthew.sportiliapp.model.GruppoMuscolare import com.matthew.sportiliapp.model.GymViewModel import com.matthew.sportiliapp.model.Scheda import com.matthew.sportiliapp.model.Utente import java.util.Locale @OptIn(ExperimentalMaterial3Api::class) @Composable fun UtenteScreen( navController: NavController, utenteCode: String, gymViewModel: GymViewModel = viewModel() ) { val users by gymViewModel.users.observeAsState(initial = emptyList()) val context = LocalContext.current val utente = users.firstOrNull { it.code == utenteCode } if (utente != null) { var editedNome by remember { mutableStateOf(utente.nome) } var editedCognome by remember { mutableStateOf(utente.cognome) } var showEliminaAlert by remember { mutableStateOf(false) } Scaffold( topBar = { TopAppBar(title = { Text("Modifica Utente") }) } ) { padding -> Column( modifier = Modifier .padding(padding) .padding(16.dp) .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { // Sezione per i dettagli dell'utente Card( modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium ) { Column( modifier = Modifier.padding(16.dp) ) { Text("Dettagli Utente", style = MaterialTheme.typography.titleMedium) Spacer(modifier = Modifier.height(16.dp)) FormSection(title = "Codice", content = utente.code) Divider(modifier = Modifier.padding(vertical = 8.dp)) CustomTextField("Nome", editedNome) { editedNome = it } Spacer(modifier = Modifier.height(8.dp)) CustomTextField("Cognome", editedCognome) { editedCognome = it } } } Spacer(modifier = Modifier.height(24.dp)) // Sezione per la gestione della scheda Card( modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium ) { Column( modifier = Modifier.padding(16.dp) ) { Text("Gestione Scheda", style = MaterialTheme.typography.titleLarge) Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { navController.navigate("editScheda") }, modifier = Modifier.fillMaxWidth() ) { Text(if (utente.scheda != null) "Modifica scheda" else "Aggiungi scheda") } } } Spacer(modifier = Modifier.height(24.dp)) // Sezione per le azioni sugli utenti Card( modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium ) { Column( modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Button( onClick = { // Gestisce la modifica e il salvataggio dell'utente editedCognome = editedCognome.trim().replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } editedNome = editedNome.trim().replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ROOT) else it.toString() } val updatedUtente = Utente( code = utente.code, cognome = editedCognome, nome = editedNome, scheda = utente.scheda ) gymViewModel.updateUser(utente = updatedUtente) Toast.makeText(context, "Utente aggiornato", Toast.LENGTH_SHORT).show() }, modifier = Modifier.fillMaxWidth() ) { Text("Salva modifiche") } Spacer(modifier = Modifier.height(16.dp)) Button( onClick = { showEliminaAlert = true }, colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error), modifier = Modifier.fillMaxWidth() ) { Text("Elimina Utente", color = MaterialTheme.colorScheme.onError) } } } if (showEliminaAlert) { AlertDialog( onDismissRequest = { showEliminaAlert = false }, title = { Text("Conferma Eliminazione") }, text = { Text("Sei sicuro di voler eliminare questo utente?") }, confirmButton = { Button(onClick = { gymViewModel.removeUser(utente.code) showEliminaAlert = false navController.popBackStack() }) { Text("Elimina") } }, dismissButton = { Button(onClick = { showEliminaAlert = false }) { Text("Annulla") } } ) } } } } else { // Gestione del caso in cui l'utente non viene trovato o la lista è vuota Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text("Utente non trovato", style = MaterialTheme.typography.titleLarge) } } } @Composable fun UtenteNavHost( navController: NavController, utenteCode: String, gymViewModel: GymViewModel = viewModel() // Utilizziamo viewModel() per ottenere l'istanza ) { val internalNavController = rememberNavController() val users by gymViewModel.users.observeAsState(initial = emptyList()) // Controlla se la lista users è vuota o se contiene l'utente cercato val utente = users.firstOrNull { utente -> utente.code == utenteCode } val context = LocalContext.current if (utente != null) { val scheda = utente.scheda ?: Scheda() NavHost( navController = internalNavController, startDestination = "utenteScreen" ) { composable("utenteScreen") { UtenteScreen(navController = internalNavController, utenteCode) } composable("editScheda") { EditSchedaScreen( navController = internalNavController, GymViewModel(), utenteCode ) { internalNavController.popBackStack() } } composable("addGruppoMuscolareScreen/{giornoName}") { backStackEntry -> val giornoName = backStackEntry.arguments?.getString("giornoName") ?: return@composable val giorno = scheda.giorni[giornoName] ?: Giorno(giornoName) AddGruppoMuscolareScreen( navController = internalNavController, giorno = giorno, onGruppoMuscolareAdded = { newGruppoMuscolare -> val updatedGruppiMuscolari = giorno.gruppiMuscolari.toMutableMap() updatedGruppiMuscolari["gruppo${giorno.gruppiMuscolari.size + 1}"] = newGruppoMuscolare giorno.gruppiMuscolari = updatedGruppiMuscolari val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } }, onGruppoMuscolareMoved = { oldIndex, newIndex -> val updatedGruppiMuscolari = giorno.gruppiMuscolari.toList().toMutableList() val movedItem = updatedGruppiMuscolari.removeAt(oldIndex) updatedGruppiMuscolari.add(newIndex, movedItem) val updatedGruppiMuscolari2 = updatedGruppiMuscolari.mapIndexed { index, entry -> "gruppo${index + 1}" to entry.second }.toMap() giorno.gruppiMuscolari = updatedGruppiMuscolari2 val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } }, onGruppoMuscolareDeleted = { index -> val updatedGruppiMuscolari = giorno.gruppiMuscolari.toList().toMutableList() // Rimuove il gruppo muscolare all'indice specificato updatedGruppiMuscolari.removeAt(index) // Rinumerazione delle chiavi rimanenti val renumberedGruppiMuscolari = updatedGruppiMuscolari.mapIndexed { newIndex, entry -> "gruppo${newIndex + 1}" to entry.second }.toMap() // Aggiorna i gruppi muscolari e salva la scheda giorno.gruppiMuscolari = renumberedGruppiMuscolari val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } } ) } composable("editGruppoMuscolareScreen/{nomeGruppo}/{nomeGiorno}") { backStackEntry -> val nomeGruppo = backStackEntry.arguments?.getString("nomeGruppo") ?: return@composable val nomeGiorno = backStackEntry.arguments?.getString("nomeGiorno") ?: return@composable // Cerca il gruppo muscolare all'interno della scheda dell'utente val giorno = scheda.giorni.values.firstOrNull { it.name == nomeGiorno } if (giorno == null) { return@composable } val gruppo = giorno.gruppiMuscolari.values .firstOrNull { it.nome == nomeGruppo } if (gruppo != null) { EditGruppoMuscolareScreen( navController = internalNavController, gruppoMuscolare = gruppo, onEsercizioAdded = { newEsercizio -> // Aggiungi l'esercizio al gruppo muscolare val updatedEsercizi = gruppo.esercizi.toMutableMap() updatedEsercizi["esercizio${gruppo.esercizi.size+1}"] = newEsercizio gruppo.esercizi = updatedEsercizi // Aggiorna la scheda dell'utente con il nuovo gruppo muscolare scheda.giorni.forEach { (giornoName, giorno) -> if (giorno.gruppiMuscolari.containsKey(nomeGruppo)) { val updatedGruppiMuscolari = giorno.gruppiMuscolari.toMutableMap() updatedGruppiMuscolari[nomeGruppo] = gruppo giorno.gruppiMuscolari = updatedGruppiMuscolari val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni } } // Salva la scheda aggiornata gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } }, onEsercizioMoved = { oldIndex, newIndex -> // Sposta l'esercizio all'interno del gruppo muscolare val updatedEsercizi = gruppo.esercizi.toList().toMutableList() val movedItem = updatedEsercizi.removeAt(oldIndex) updatedEsercizi.add(newIndex, movedItem) val updatedEserciziMap = updatedEsercizi.mapIndexed { index, entry -> "esercizio${index + 1}" to entry.second }.toMap() gruppo.esercizi = updatedEserciziMap // Aggiorna la scheda dell'utente con il nuovo gruppo muscolare scheda.giorni.forEach { (giornoName, giorno) -> if (giorno.gruppiMuscolari.containsKey(nomeGruppo)) { val updatedGruppiMuscolari = giorno.gruppiMuscolari.toMutableMap() updatedGruppiMuscolari[nomeGruppo] = gruppo giorno.gruppiMuscolari = updatedGruppiMuscolari val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni } } // Salva la scheda aggiornata gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } }, onEsercizioDeleted = { index -> // Rimuovi l'esercizio dal gruppo muscolare val updatedEsercizi = gruppo.esercizi.toMutableMap() updatedEsercizi.remove("esercizio${index + 1}") gruppo.esercizi = updatedEsercizi // Aggiorna la scheda dell'utente con il nuovo gruppo muscolare scheda.giorni.forEach { (giornoName, giorno) -> if (giorno.gruppiMuscolari.containsKey(nomeGruppo)) { val updatedGruppiMuscolari = giorno.gruppiMuscolari.toMutableMap() updatedGruppiMuscolari[nomeGruppo] = gruppo giorno.gruppiMuscolari = updatedGruppiMuscolari val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni } } // Salva la scheda aggiornata gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } }, onEsercizioEdited = { index, esercizio -> // Modifica l'esercizio esistente nel gruppo muscolare val updatedEsercizi = gruppo.esercizi.toMutableMap() updatedEsercizi["esercizio${index + 1}"] = esercizio gruppo.esercizi = updatedEsercizi // Aggiorna la scheda dell'utente con il nuovo gruppo muscolare scheda.giorni.forEach { (giornoName, giorno) -> if (giorno.gruppiMuscolari.containsKey(nomeGruppo)) { val updatedGruppiMuscolari = giorno.gruppiMuscolari.toMutableMap() updatedGruppiMuscolari[nomeGruppo] = gruppo giorno.gruppiMuscolari = updatedGruppiMuscolari val updatedGiorni = scheda.giorni.toMutableMap() updatedGiorni[giornoName] = giorno scheda.giorni = updatedGiorni } } // Salva la scheda aggiornata gymViewModel.saveScheda(scheda, utenteCode) { exception -> Toast.makeText(context, "ERRORE: ${exception.message} ", Toast.LENGTH_SHORT).show() } } ) } } } } } @Composable fun CustomTextField(label: String, value: String, onValueChange: (String) -> Unit) { OutlinedTextField( value = value, onValueChange = onValueChange, label = { Text(label) }, modifier = Modifier.fillMaxWidth() ) } @Composable fun FormSection(title: String, content: String) { Column { Text(title, style = MaterialTheme.typography.headlineMedium) Text(content) Divider() } }
0
Kotlin
0
0
df0c386b8a36cdff2c86e7c77620b40e20c7ed3b
19,808
SportiliApp_Android
MIT License
android/app/src/main/kotlin/io/actingweb/firstapp/MainActivity.kt
oizhaolei
442,965,896
false
{"Dart": 84541, "HTML": 4276, "JavaScript": 1725, "Ruby": 1353, "Swift": 495, "Kotlin": 126, "Objective-C": 38}
package io.actingweb.firstapp import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
1
9a5195d6628998206a535d1998ebd22c5e788f2b
126
actingweb_firstapp
Apache License 2.0
src/main/kotlin/io/reactivex/rxjava3/kotlin/single.kt
ReactiveX
23,095,938
false
{"Kotlin": 141592, "Shell": 1041}
@file:Suppress("HasPlatformType", "unused") package io.reactivex.rxjava3.kotlin import io.reactivex.rxjava3.annotations.BackpressureKind import io.reactivex.rxjava3.annotations.BackpressureSupport import io.reactivex.rxjava3.annotations.CheckReturnValue import io.reactivex.rxjava3.annotations.SchedulerSupport import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.core.SingleSource inline fun <reified R : Any> Single<*>.cast(): Single<R> = cast(R::class.java) // EXTENSION FUNCTION OPERATORS /** * Merges the emissions of a Observable<Single<T>>. Same as calling `flatMapSingle { it }`. */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) fun <T : Any> Observable<Single<T>>.mergeAllSingles(): Observable<T> = flatMapSingle { it } /** * Merges the emissions of a Flowable<Single<T>>. Same as calling `flatMap { it }`. */ @CheckReturnValue @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @SchedulerSupport(SchedulerSupport.NONE) fun <T : Any> Flowable<Single<T>>.mergeAllSingles(): Flowable<T> = flatMapSingle { it } /** * Concats an Iterable of singles into flowable. Same as calling `Single.concat(this)` */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @BackpressureSupport(BackpressureKind.FULL) fun <T : Any> Iterable<SingleSource<T>>.concatAll(): Flowable<T> = Single.concat(this)
32
Kotlin
472
6,984
88176f6691de8de39d092f144671341bec30d4f8
1,429
RxKotlin
Apache License 2.0
adapter-out/rdb/src/main/kotlin/com/yapp/bol/season/SeasonQueryRepositoryImpl.kt
YAPP-Github
634,125,780
false
null
package com.yapp.bol.season import com.yapp.bol.group.GroupId import org.springframework.stereotype.Repository @Repository internal class SeasonQueryRepositoryImpl( private val seasonRepository: SeasonRepository, ) : SeasonQueryRepository { override fun getSeason(groupId: GroupId): Season? { return seasonRepository.findByGroupId(groupId.value)?.toDomain() } }
4
Kotlin
0
13
9a142c690763910b0a8cc48e9ec7f6b664ed2fc4
384
onboard-server
Apache License 2.0
dlang/psi-impl/src/main/kotlin/io/github/intellij/dlanguage/psi/resolve/processor/LabelProcessor.kt
intellij-dlanguage
27,922,930
false
{"D": 1787183, "Kotlin": 1068238, "Java": 834373, "Lex": 22913, "DTrace": 3220, "HTML": 1386, "Makefile": 457}
package io.github.intellij.dlanguage.psi.resolve.processor import com.intellij.psi.PsiElement import com.intellij.psi.ResolveResult import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.util.SmartList import com.intellij.util.containers.toArray import io.github.intellij.dlanguage.psi.DResolveResult import io.github.intellij.dlanguage.utils.LabeledStatement class LabelProcessor(private val elementName: String) : PsiScopeProcessor { private var candidates: MutableList<DResolveResult>? = null private var resolveResult = ResolveResult.EMPTY_ARRAY override fun execute(element: PsiElement, state: ResolveState): Boolean { if (element !is LabeledStatement) return true if (element.name != elementName) return true candidates = SmartList() (candidates as SmartList<DResolveResult>).add(DResolveResult(element)) resolveResult = null return false } fun getResult(): Array<ResolveResult> { if (resolveResult != null) return resolveResult if (candidates == null) { resolveResult = ResolveResult.EMPTY_ARRAY return resolveResult } resolveResult = candidates!!.toArray(ResolveResult.EMPTY_ARRAY) return resolveResult } }
160
D
51
328
298d1db45d2b35c1715a1b1b2e1c548709101f05
1,304
intellij-dlanguage
MIT License
app/src/main/java/com/example/coderadar/contestTabs/TabFragment1.kt
thekuldeep07
430,311,480
false
null
package com.example.coderadar.contestTabs import android.os.Bundle import android.util.Log import android.view.* import android.widget.Toast import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.example.CodeRadar.R import com.example.CodeRadar.databinding.FragmentTab1Binding import com.example.coderadar.mvvm.LoginViewModel import com.example.coderadar.presentation.adapter.ContestAdapter import com.example.coderadar.presentation.viewmodel.ContestsViewModel import com.example.coderadar.ui.ContestActivity import java.time.LocalDateTime class TabFragment1 : Fragment() { private lateinit var viewmodel: ContestsViewModel private lateinit var loginViewModel: LoginViewModel private lateinit var tab1Binding: FragmentTab1Binding private lateinit var contestAdapter: ContestAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_tab1, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) tab1Binding = FragmentTab1Binding.bind(view) viewmodel = (activity as ContestActivity).viewModel loginViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)) .get(LoginViewModel::class.java) initRecyclerView() viewNewsList() } private fun viewNewsList() { showProgressbar() val currentDateTimeMin = LocalDateTime.now().minusWeeks(2).withHour(0).withMinute(0).withSecond(0) val currentDateTime = LocalDateTime.now() Log.i("date", "" + currentDateTimeMin) val resource = "codechef.com" val responseLiveData = viewmodel.getContest(resource, currentDateTimeMin, currentDateTime) responseLiveData.observe(this.viewLifecycleOwner, Observer { if (it != null) { tab1Binding.errorLayout.visibility=View.GONE contestAdapter.setList(it) contestAdapter.notifyDataSetChanged() if(it.isEmpty()){ tab1Binding.noDataLayout.visibility=View.VISIBLE } else{ tab1Binding.contestRv1.visibility=View.VISIBLE } hideProgressbar() } else { hideProgressbar() tab1Binding.contestRv1.visibility=View.GONE tab1Binding.errorLayout.visibility=View.VISIBLE } }) } private fun initRecyclerView() { contestAdapter = ContestAdapter(requireActivity(), loginViewModel, this) tab1Binding.contestRv1.apply{ adapter = contestAdapter layoutManager = LinearLayoutManager(activity) } } private fun showProgressbar(){ tab1Binding.contestPb1.visibility = View.VISIBLE tab1Binding.contestRv1.visibility = View.GONE tab1Binding.errorLayout.visibility =View.GONE tab1Binding.noDataLayout.visibility=View.GONE } private fun hideProgressbar(){ tab1Binding.contestPb1.visibility = View.INVISIBLE } override fun onOptionsItemSelected(item: MenuItem): Boolean { //get item id to handle item clicks val id = item.itemId //handle item clicks if (id == R.id.refresh){ refresh() } return super.onOptionsItemSelected(item) } private fun refresh() { showProgressbar() val currentDateTimeMin = LocalDateTime.now().minusWeeks(2).withHour(0).withMinute(0).withSecond(0) val currentDateTime = LocalDateTime.now() Log.d("date", "" + currentDateTime) val resource = "codechef.com" val responseLiveData = viewmodel.updateContest(resource, currentDateTimeMin, currentDateTime) responseLiveData.observe(this.viewLifecycleOwner, Observer { if (it != null) { tab1Binding.errorLayout.visibility=View.GONE contestAdapter.setList(it) contestAdapter.notifyDataSetChanged() if(it.isEmpty()){ tab1Binding.noDataLayout.visibility=View.VISIBLE } else{ tab1Binding.contestRv1.visibility=View.VISIBLE } hideProgressbar() } else { hideProgressbar() tab1Binding.contestRv1.visibility=View.GONE tab1Binding.errorLayout.visibility=View.VISIBLE } }) } }
0
Kotlin
3
0
028f4624a72c78b84ae1e5df2aa989e1f893ea7c
4,895
CodeRadar
MIT License
src/runtimeMain/kotlin/com/epam/drill/test/agent/instrumentation/http/selenium/ChromeDevTool.kt
Drill4J
250,085,937
false
null
/** * Copyright 2020 EPAM Systems * * 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.epam.drill.test.agent.instrumentation.http.selenium import com.epam.drill.logger.* import com.epam.drill.test.agent.config.* import com.epam.drill.test.agent.util.* import com.github.kklisura.cdt.services.* import com.github.kklisura.cdt.services.config.* import com.github.kklisura.cdt.services.impl.* import com.github.kklisura.cdt.services.invocation.* import com.github.kklisura.cdt.services.utils.* import kotlinx.serialization.* import kotlinx.serialization.json.* import org.java_websocket.client.* import org.java_websocket.framing.CloseFrame.* import org.java_websocket.handshake.* import java.lang.reflect.* import java.net.* import java.util.* import java.util.concurrent.* private const val CAPABILITY_NAME = "debuggerAddress" private const val DEV_TOOL_PROPERTY_NAME = "webSocketDebuggerUrl" private const val SELENOID_WS_TIMEOUT_SEC: Long = 2 private const val RETRY_ADD_HEADERS_SLEEP_MILLIS: Long = 2000 object DevToolsClientThreadStorage { private val logger = Logging.logger(ChromeDevTool::class.java.name) private val threadLocalChromeDevTool: InheritableThreadLocal<ChromeDevTool> = InheritableThreadLocal() fun addHeaders(headers: Map<*, *>) { try { logger.debug { "try to add headers: $headers" } @Suppress("UNCHECKED_CAST") getDevTool()?.addHeaders(headers as Map<String, String>) logger.debug { "Chrome Tool activated: ${threadLocalChromeDevTool.get() != null}. Headers: $headers" } } catch (ex: Exception) { //todo refactor and remove this workaround EPMDJ-9354 logger.debug { "try to resend because of exception: $ex" } Thread.sleep(RETRY_ADD_HEADERS_SLEEP_MILLIS) logger.debug { "[Second try] after sleep try to add headers: $headers" } try { @Suppress("UNCHECKED_CAST") getDevTool()?.addHeaders(headers as Map<String, String>) logger.debug { "[Second try] Chrome Tool activated: ${threadLocalChromeDevTool.get() != null}. Headers: $headers" } } catch (ex: Exception){ logger.warn { "cannot resend for $headers because of exception: $ex" } } } } fun setDevTool(devTool: ChromeDevTool) { getDevTool()?.close() threadLocalChromeDevTool.set(devTool) logger.debug { "DevTool inited for: Thread id=${Thread.currentThread().id}, DevTool instance=$devTool" } } fun getDevTool(): ChromeDevTool? = threadLocalChromeDevTool.get() fun isHeadersAdded() = threadLocalChromeDevTool.get()?.isHeadersAdded ?: false fun resetHeaders() = getDevTool()?.addHeaders(emptyMap()) } /** * Works with local or Selenoid DevTools by websocket */ class ChromeDevTool { private val logger = Logging.logger(ChromeDevTool::class.java.name) private var localDevToolsWs: ChromeDevToolWs? = null private var selenoidDevToolsWs: ChromeDevToolsService? = null lateinit var localUrl: String internal var isHeadersAdded: Boolean = false init { DevToolsClientThreadStorage.setDevTool(this) } fun addHeaders(headers: Map<String, String>) { trackTime("send headers") { localDevToolsWs?.addHeaders(headers) selenoidDevToolsWs?.network?.let { it.setExtraHTTPHeaders(headers) it.enable() } } } /** * connect to remote Selenoid or local webDriver */ fun connect(capabilities: Map<*, *>?, sessionId: String?, remoteHost: String?) = kotlin.runCatching { logger.debug { "starting connectToDevTools with cap='$capabilities' sessionId='$sessionId' remote='$remoteHost'..." } trackTime("connect to selenoid") { remoteHost?.connectToSelenoid(sessionId) } if (selenoidDevToolsWs == null || selenoidDevToolsWs?.isClosed == true) { trackTime("connect to local") { connectToLocal(capabilities) } } }.getOrNull() private fun connectToLocal(capabilities: Map<*, *>?) { capabilities?.let { cap -> val debuggerURL = cap[CAPABILITY_NAME].toString() val con = doDevToolsRequest(debuggerURL) val responseCode = con.responseCode if (responseCode == HttpURLConnection.HTTP_OK) { val response = con.inputStream.reader().readText() logger.debug { "Chrome info: $response" } val chromeInfo = Json.parseToJsonElement(response) as JsonObject chromeInfo[DEV_TOOL_PROPERTY_NAME]?.jsonPrimitive?.contentOrNull?.let { url -> this.localUrl = url connectWs() } ?: logger.warn { "Can't get DevTools URL" } } else { logger.warn { "Can't get chrome info: code=$responseCode" } } } } private fun String.connectToSelenoid(sessionId: String?) { logger.debug { "connect to selenoid by ws..." } val webSocketService = WebSocketServiceImpl.create(URI("ws://$this/devtools/$sessionId/page")) val commandInvocationHandler = CommandInvocationHandler() val commandsCache: MutableMap<Method, Any> = ConcurrentHashMap() val configuration = ChromeDevToolsServiceConfiguration() configuration.readTimeout = SELENOID_WS_TIMEOUT_SEC selenoidDevToolsWs = ProxyUtils.createProxyFromAbstract( ChromeDevToolsServiceImpl::class.java, arrayOf<Class<*>>( WebSocketService::class.java, ChromeDevToolsServiceConfiguration::class.java ), arrayOf(webSocketService, configuration) ) { _, method: Method, _ -> commandsCache.computeIfAbsent(method) { ProxyUtils.createProxy(method.returnType, commandInvocationHandler) } } commandInvocationHandler.setChromeDevToolsService(selenoidDevToolsWs) } fun close() { localDevToolsWs?.let { logger.debug { "${this.localUrl} closing..." } it.close() } selenoidDevToolsWs?.let { logger.debug { "closing Selenoid ws..." } it.close() } } internal fun connectWs(): Boolean { logger.debug { "DevTools URL: ${this.localUrl}" } val cdl = CountDownLatch(4) localDevToolsWs = ChromeDevToolWs(URI(this.localUrl), cdl, this) localDevToolsWs?.connect() return cdl.await(5, TimeUnit.SECONDS) } private fun doDevToolsRequest(debuggerURL: String): HttpURLConnection { val obj = URL("http://$debuggerURL/json/version") logger.debug { "Try to get chrome info [${obj.path}]" } val con = obj.openConnection() as HttpURLConnection con.requestMethod = "GET" return con } } /** * WS for local DevTools */ class ChromeDevToolWs( private val url: URI, private val cdl: CountDownLatch, private val chromeDevTool: ChromeDevTool, ) : WebSocketClient(url) { private val json = Json { ignoreUnknownKeys = true } private val logger = Logging.logger(ChromeDevToolWs::class.java.name) private lateinit var sessionId: SessionId override fun onOpen(handshakedata: ServerHandshake?) { logger.trace { "Ws was opened" } send(DevToolsRequest(1, "Target.getTargets", emptyMap())) } override fun onMessage(message: String) = runCatching { logger.trace { message } val parsedMessage = json.parseToJsonElement(message) as JsonObject val id = parsedMessage["id"] ?: return@runCatching val result = (parsedMessage["result"] as JsonObject).toString() val step = (id as JsonPrimitive).int when (step) { 1 -> sendCreateSessionRequest(result) 2 -> sendAttachRequest(result) 3 -> sendLogClearRequest() 4 -> sendEnableNetworkRequest() else -> logger.debug { "unprocessed step: $step" } } }.getOrElse { logger.error(it) { "skipped message: $message" } } fun addHeaders(headers: Map<String, String>) { sendHeadRequest(mapOf("headers" to headers)) } private fun sendHeadRequest(params: Map<String, Map<String, String>>) { send(DevToolsHeaderRequest(6, "Network.setExtraHTTPHeaders", params, sessionId.sessionId)) } private fun sendEnableNetworkRequest() { send(DevToolsRequest(5, "Network.enable", emptyMap(), sessionId.sessionId)) cdl.countDown() } private fun sendLogClearRequest() { send(DevToolsRequest(4, "Log.clear", emptyMap(), sessionId.sessionId)) cdl.countDown() } private fun sendAttachRequest(result: String) { logger.debug { "DevTools session created" } sessionId = json.decodeFromString(SessionId.serializer(), result) val params = mapOf("autoAttach" to true, "waitForDebuggerOnStart" to false).toOutput() send(DevToolsRequest(3, "Target.setAutoAttach", params, sessionId.sessionId)) cdl.countDown() } private fun sendCreateSessionRequest(result: String) { val targetId = retrieveTargetId(result) val params = mapOf("targetId" to targetId, "flatten" to true).toOutput() send(DevToolsRequest(2, "Target.attachToTarget", params)) cdl.countDown() } private fun retrieveTargetId(result: String) = json.decodeFromString(TargetInfos.serializer(), result).targetInfos .filter { it.type == "page" } .map { it.targetId } .first() .uppercase(Locale.getDefault()) override fun onError(ex: java.lang.Exception?) { logger.error(ex) { "socket ${this.url} closed by error:" } } private fun send(value: DevToolsRequest) { if (isOpen) { send(json.encodeToString(DevToolsRequest.serializer(), value)) } } private fun send(value: DevToolsHeaderRequest) { if (isOpen) { send(json.encodeToString(DevToolsHeaderRequest.serializer(), value)) chromeDevTool.isHeadersAdded = true } } override fun onClose(code: Int, reason: String?, remote: Boolean) = when (code) { NORMAL -> logger.debug { "socket closed. Code: $code, reason: $reason, remote: $remote" } else -> { Thread.sleep(1000) logger.debug { "try reconnect to ${this.url}" }.also { chromeDevTool.connectWs() } } } } fun Map<String, Any>.toOutput(): Map<String, JsonElement> = mapValues { (_, value) -> val serializer = value::class.serializer().cast() json.encodeToJsonElement(serializer, value) } @Suppress("NOTHING_TO_INLINE", "UNCHECKED_CAST") internal inline fun <T> KSerializer<out T>.cast(): KSerializer<T> = this as KSerializer<T> @Serializable data class TargetInfos(val targetInfos: List<Target>) @Serializable data class SessionId(val sessionId: String) @Serializable data class Target( val targetId: String, val type: String, val title: String, val url: String, val attached: Boolean, val browserContextId: String, ) @Serializable data class DevToolsRequest( val id: Int, val method: String, val params: Map<String, JsonElement> = emptyMap(), val sessionId: String? = null, ) @Serializable data class DevToolsHeaderRequest( val id: Int, val method: String, val params: Map<String, Map<String, String>> = emptyMap(), val sessionId: String? = null, )
2
Kotlin
4
4
c2c9f83660ea156f555645371ab8031c7a944fe3
12,112
autotest-agent
Apache License 2.0
capturable/src/test/java/dev/shreyaspatil/capturable/controller/CaptureControllerTest.kt
PatilShreyas
443,739,632
false
{"Kotlin": 37166}
/* * MIT License * * Copyright (c) 2022 <NAME> * * 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 dev.shreyaspatil.capturable.controller import android.graphics.Bitmap import androidx.compose.runtime.ExperimentalComposeApi import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.take import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Test @Suppress("DeferredResultUnused") @OptIn(ExperimentalComposeApi::class) class CaptureControllerTest { private val controller = CaptureController() @Test fun captureAsync_validConfig_withNoParameters() = runTest { // Before capturing, make sure to collect flow request eagerly val captureRequestDeferred = asyncOnUnconfinedDispatcher { getRecentCaptureRequest() } // When: Captured controller.captureAsync() val captureRequest = captureRequestDeferred.await() val expectedConfig = Bitmap.Config.ARGB_8888 // Then: Capture request should be get emitted with default bitmap config assertEquals(captureRequest.config, expectedConfig) } @Test fun captureAsync_validConfig_withCustomParameters() = runTest { // Before capturing, make sure to collect flow request eagerly val captureRequestDeferred = asyncOnUnconfinedDispatcher { getRecentCaptureRequest() } // Given: The customized config val expectedConfig = Bitmap.Config.RGB_565 // When: Captured controller.captureAsync(expectedConfig) val captureRequest = captureRequestDeferred.await() // Then: Capture request should be get emitted with default bitmap config assertEquals(captureRequest.config, expectedConfig) } @OptIn(ExperimentalCoroutinesApi::class) private fun <T> TestScope.asyncOnUnconfinedDispatcher(block: suspend CoroutineScope.() -> T) = async(UnconfinedTestDispatcher(testScheduler), block = block) private suspend fun getRecentCaptureRequest() = controller.captureRequests.take(1).first() }
13
Kotlin
31
993
7a6683503692d965dace6ddb69f0ffa34d61f837
3,288
Capturable
MIT License
src/commonMain/eco/KProduct_v1.kt
pallocate
410,322,434
false
null
package pef.eco import kotlinx.serialization.Serializable import kotlinx.serialization.SerialName import pef.toLong import pef.toInt import pef.Voidable @Serializable @SerialName("Product") open class KProduct_v1 ( val id : Long = 0L, val name : String = "", val desc : String = "", val amount : Float = 0F, val prefix : Prefix = Prefix.NONE, val unit : Units = Units.NONE, val change : Int = 0, val price : Long = 0L, val sensitive : Boolean = false, val analogue : Boolean = false ) : Voidable { /** @constructor Does some parameter checking/conversion and calls primary constructor. */ constructor (id : String, name : String, desc : String, amount : String, prefix : String, unit : String, change : String, price : String, sensitive : String, analogue : String) : this ( id.toLong(), name, desc, amount.toFloat(), prefix.toPrefix(), unit.toUnit(), change.toInt(), price.toLong(), sensitive.toBool(), analogue.toBool() ) companion object { fun void () = KProduct_v1() } fun apu () : String { val stringBuilder = StringBuilder() if (prefix > Prefix.NONE) stringBuilder.append( prefix.tag() ) if (unit > Units.NONE) stringBuilder.append( unit.tag() ) if (!stringBuilder.isEmpty()) if (amount > 0F) stringBuilder.insert( 0, amount ) else stringBuilder.insert( 0, 1 ) return stringBuilder.toString() } override fun isVoid () = (id == 0L) override fun toString () = name }
0
Kotlin
0
0
5a551a7c12ac22f517a8e6c386ae666c22c181ae
1,599
pef
MIT License
src/test/kotlin/bybit/sdk/rest/OrderClientTest.kt
alleyway
650,567,178
false
{"Kotlin": 141711}
package bybit.sdk.rest import bybit.sdk.RateLimitReachedException import bybit.sdk.properties.ByBitProperties import bybit.sdk.rest.order.* import bybit.sdk.shared.Category import bybit.sdk.shared.OrderType import bybit.sdk.shared.Side import kotlinx.coroutines.* import org.junit.jupiter.api.assertDoesNotThrow import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue internal class OrderClientTest { private val scope = CoroutineScope(Dispatchers.Default + Job()) private val jobs = mutableListOf<Job>() private var restClient: ByBitRestClient = ByBitRestClient( apiKey = System.getenv("BYBIT_API_KEY") ?: ByBitProperties.APIKEY, secret = System.getenv("BYBIT_SECRET") ?: ByBitProperties.SECRET, testnet = true, // httpClientProvider = okHttpClientProvider ) fun add(block: suspend CoroutineScope.() -> Unit): Job { val job = scope.launch(block = block) jobs.add(job) return job } @Test fun orderHistoryTest() { val resp = restClient.orderClient.orderHistoryBlocking( OrderHistoryParams(Category.spot, "BTCUSDT") ) assertEquals(0, resp.retCode) assertEquals("OK", resp.retMsg) } @Test fun orderHistoryPaginatedTest() { val resp = restClient.orderClient.orderHistoryPaginated( OrderHistoryParams(Category.spot, "BTCUSD", limit = 10) ).asStream().toList() resp.forEach { println(it.orderId) } } @Test fun placeOrderTest() { val resp = restClient.orderClient.placeOrderBlocking( PlaceOrderParams( Category.inverse, "BTCUSD", Side.Buy, OrderType.Limit, "1.0", price = 5_000.toString() ) ) val orderId = resp.result.orderId assertEquals(0, resp.retCode) assertEquals("OK", resp.retMsg) Thread.sleep(5000) val cancelOrderResp = restClient.orderClient.cancelOrderBlocking( CancelOrderParams( Category.inverse, "BTCUSD", orderId ) ) assertEquals(0, cancelOrderResp.retCode) assertEquals("OK", cancelOrderResp.retMsg) } @Test fun ordersOpenTest() { restClient.orderClient.placeOrderBlocking( PlaceOrderParams( Category.inverse, "BTCUSD", Side.Buy, OrderType.Limit, "1.0", price = 5_000.toString() ) ) val resp = restClient.orderClient.ordersOpenPaginated( OrdersOpenParams(Category.inverse) ) val items = resp.asStream().toList() assertTrue(items.size > 0) } @Test fun cancelAllOrdersTest() { val spotResponse = restClient.orderClient.cancelAllOrdersBlocking( CancelAllOrdersParams(Category.spot) ) assertTrue(spotResponse.retCode == 0) assertTrue(spotResponse is CancelAllOrdersResponse.CancelAllOrdersResponseSpot) val linearResponse = restClient.orderClient.cancelAllOrdersBlocking( CancelAllOrdersParams(Category.linear, settleCoin = "USDT") ) assertTrue(linearResponse.retCode == 0) assertTrue(linearResponse is CancelAllOrdersResponse.CancelAllOrdersResponseOther) } @Test @Ignore fun orderRateLimitTest() { val nThreads = 10 val loop = 100 Thread.sleep(4_000) val random = java.util.Random() restClient.orderClient.cancelAllOrdersBlocking( CancelAllOrdersParams(Category.inverse, "BTCUSD") ) val resp = restClient.orderClient.placeOrderBlocking( PlaceOrderParams( Category.inverse, "BTCUSD", Side.Buy, OrderType.Limit, "1.0", price = 6_000.toString() ) ) val orderId = resp.result.orderId assertEquals(0, resp.retCode) assertEquals("OK", resp.retMsg) Thread.sleep(5000) repeat(nThreads) { jobs.add( scope.launch { assertDoesNotThrow { repeat(loop) { // try { val r = restClient.orderClient.amendOrderBlocking( AmendOrderParams( Category.inverse, "BTCUSD", orderId = orderId, qty = random.nextInt(100, 200).toString(), price = 10_100.toString() ) ) println(r.result.orderId) } catch (e: RateLimitReachedException) { println("Rate Limit Exception: ${e.message}") } catch (e: Exception) { e.printStackTrace() } Thread.sleep(1) } Thread.sleep(1) repeat(10) { // restClient.orderClient.amendOrderBlocking( AmendOrderParams( Category.inverse, "BTCUSD", orderId = orderId, qty = random.nextInt(200, 400).toString(), price = 10_100.toString() ) ) } } } ) } assertEquals(nThreads, jobs.size) runBlocking { jobs.joinAll() } println("ALL JOINED!! Remaining sleep for 3 seconds") Thread.sleep(3_000) } }
1
Kotlin
2
1
ae1e96c815bc6f6bf5612f67e06b8bd5900f7a14
6,284
bybit-kotlin-api
MIT License
impl/misskey/src/main/kotlin/dev/usbharu/multim/misskey/v12/converter/misskey/v12/UsersConverter.kt
multim-dev
591,652,793
false
null
package dev.usbharu.multim.misskey.v12.converter.misskey.v12 import dev.usbharu.multim.misskey.v12.common.* import dev.usbharu.multim.misskey.v12.model.UsersRelationResponse import dev.usbharu.multim.misskey.v12.model.components.* object UsersConverter { fun UsersRelationResponse.toRelation( myself: MisskeyAccount, other: MisskeyAccount ): MisskeyRelation { return MisskeyRelation(myself, other, isFollowing, isFollowed, isMuted, isBlocked) } fun User.toProfile(): MisskeyProfile { return when (this) { is MeDetailed -> { MisskeyProfile( MisskeyAccount( this.id, this.name ?: "null", this.username, this.isBot, MisskeyAvatar(this.avatarUrl ?: "null") ), this.isBot, MisskeyContent(this.description ?: "null"), this.followingCount, this.followersCount, this.fields.map { it.toField() } ) } is UserDetailedNotMe -> { MisskeyProfile( MisskeyAccount( this.id, this.name ?: "null", this.username, this.isBot, MisskeyAvatar(this.avatarUrl ?: "null") ), this.isBot, MisskeyContent(this.description ?: "null"), this.followingCount, this.followersCount, this.fields.map { it.toField() } ) } is UserLite -> { MisskeyProfile( MisskeyAccount( this.id, this.name ?: "null", this.username, this.isBot, MisskeyAvatar(this.avatarUrl ?: "null") ), this.isBot ?: false, MisskeyContent("ERROR NO INFO") ) } } } fun Field.toField(): MisskeyField { return MisskeyField(this.name, this.value) } }
8
Kotlin
0
7
daad2d142ae6fa7414acdb6704832a4d477dc41f
2,308
multim
Apache License 2.0
app/src/main/java/com/jdagnogo/welovemarathon/wine/domain/WineUseCases.kt
jdagnogo
424,252,162
false
null
package com.jdagnogo.welovemarathon.wine.domain import androidx.annotation.Keep @Keep data class WineUseCases( val getWineSocialUseCase: GetWineSocialUseCase, val getWineTourUseCase: GetWineTourUseCase, val getWineInfoUseCase: GetWineInfoUseCase, )
0
Kotlin
0
0
1e54d39bd52996fe9f3c6e3668e21e4f415fa2a8
262
WeLoveMArathon
The Unlicense
app/src/main/java/shvyn22/flexingmarvel/presentation/characters/details/DetailsCharacterViewModel.kt
shvyn22
348,811,041
false
null
package shvyn22.flexingmarvel.presentation.characters.details import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import shvyn22.flexingmarvel.data.local.model.CharacterModel import shvyn22.flexingmarvel.data.local.model.EventModel import shvyn22.flexingmarvel.data.local.model.SeriesModel import shvyn22.flexingmarvel.domain.usecase.character.DeleteCharacterUseCase import shvyn22.flexingmarvel.domain.usecase.character.InsertCharacterUseCase import shvyn22.flexingmarvel.domain.usecase.character.IsCharacterFavoriteUseCase import shvyn22.flexingmarvel.domain.usecase.event.GetEventsByTypeUseCase import shvyn22.flexingmarvel.domain.usecase.series.GetSeriesByTypeUseCase import shvyn22.flexingmarvel.util.DetailsStateEvent import shvyn22.flexingmarvel.util.Resource class DetailsCharacterViewModel @AssistedInject constructor( getEventsByTypeUseCase: GetEventsByTypeUseCase, getSeriesByTypeUseCase: GetSeriesByTypeUseCase, isCharacterFavoriteUseCase: IsCharacterFavoriteUseCase, private val insertCharacterUseCase: InsertCharacterUseCase, private val deleteCharacterUseCase: DeleteCharacterUseCase, @Assisted private val character: CharacterModel ) : ViewModel() { private val detailsEventChannel = Channel<DetailsStateEvent>() val detailsEvent = detailsEventChannel.receiveAsFlow() val events: StateFlow<Resource<List<EventModel>>> = getEventsByTypeUseCase(character) .stateIn(viewModelScope, SharingStarted.Lazily, Resource.Idle()) val series: StateFlow<Resource<List<SeriesModel>>> = getSeriesByTypeUseCase(character) .stateIn(viewModelScope, SharingStarted.Lazily, Resource.Idle()) val isCharacterFavorite: StateFlow<Boolean> = isCharacterFavoriteUseCase(character.id) .stateIn(viewModelScope, SharingStarted.Lazily, false) fun onToggleFavorite() { if (isCharacterFavorite.value) deleteCharacter() else insertCharacter() } private fun insertCharacter() { viewModelScope.launch { insertCharacterUseCase(character) } } private fun deleteCharacter() { viewModelScope.launch { deleteCharacterUseCase(character) } } fun onEventClick(item: EventModel) { viewModelScope.launch { detailsEventChannel.send(DetailsStateEvent.NavigateToEventDetails(item)) } } fun onSeriesClick(item: SeriesModel) { viewModelScope.launch { detailsEventChannel.send(DetailsStateEvent.NavigateToSeriesDetails(item)) } } @AssistedFactory interface Factory { fun create(character: CharacterModel): DetailsCharacterViewModel } companion object { fun provideFactory( factory: Factory, character: CharacterModel ) = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return factory.create(character) as T } } } }
0
Kotlin
1
0
7483fb47b48fd3336e1c4253146237b3a64a8784
3,499
FlexingMarvel
MIT License
magic/core/src/main/java/link/magic/android/Magic.kt
magiclabs
589,703,550
false
null
package link.magic.android import android.content.Context import link.magic.android.core.relayer.urlBuilder.network.CustomNodeConfiguration import link.magic.android.modules.auth.AuthModule import link.magic.android.modules.user.UserModule import link.magic.android.core.relayer.urlBuilder.URLBuilder class Magic private constructor(context: Context, urlBuilder: URLBuilder): MagicCore( context, urlBuilder ) { /** * Contains methods for interacting with user data, checking login * status, generating cryptographically-secure ID tokens, and more. */ val user = UserModule(rpcProvider) /** * Contains methods for starting a Magic SDK authentication flow. */ val auth = AuthModule(rpcProvider) // default initializer constructor(ctx:Context, apiKey: String, locale: String = defaultLocale) : this(ctx, URLBuilder(apiKey, EthNetwork.Mainnet, locale, ctx.packageName, ProductType.MA)) // Eth Network initializer constructor(ctx:Context, apiKey: String, ethNetwork: EthNetwork, locale: String = defaultLocale) : this(ctx, URLBuilder(apiKey, ethNetwork, locale, ctx.packageName, ProductType.MA)) // Custom Node Initializer constructor(ctx:Context, apiKey: String, customNodeConfiguration: CustomNodeConfiguration, locale: String = defaultLocale) : this(ctx, URLBuilder(apiKey, customNodeConfiguration, locale, ctx.packageName, ProductType.MA)) }
0
Kotlin
0
2
676f89d138cbe76f72b289fdd164e72ffc796e32
1,453
magic-android
MIT License
android/uikit/src/main/java/com/opensource/xt/uikit/XTUIViewController.kt
PonyCui
99,914,246
false
{"TypeScript": 1029609, "Objective-C": 377108, "Kotlin": 370395, "JavaScript": 48139, "Java": 17663, "Ruby": 1475, "HTML": 1243}
package com.opensource.xt.uikit import android.app.Activity import android.app.Fragment import android.content.Intent import android.content.pm.ActivityInfo import android.graphics.Color import android.os.Bundle import android.os.Handler import android.view.View import android.view.ViewGroup import com.eclipsesource.v8.V8 import com.eclipsesource.v8.V8Array import com.eclipsesource.v8.V8Object import com.eclipsesource.v8.utils.V8ObjectUtils import com.opensource.xt.core.* import com.opensource.xt.uikit.libraries.keyboard.KeyboardHeightObserver import com.opensource.xt.uikit.libraries.keyboard.KeyboardHeightProvider import java.lang.ref.WeakReference /** * Created by cuiminghui on 2017/9/5. */ open class XTUIViewController: XTUIFragment(), XTComponentInstance, KeyboardHeightObserver { override var objectUUID: String? = null lateinit var xtrContext: XTUIContext override var view: XTUIView? = null set(value) { if (field != null) { return } if (value == null) { return } field = value value.viewDelegate = WeakReference(this) } internal var showBackButton = false var parentViewController: WeakReference<XTUIViewController>? = null internal set var childViewControllers: List<XTUIViewController> = listOf() internal set internal var supportOrientations: List<Int> = listOf(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) set(value) { field = value (activity as? XTUIActivity)?.resetOrientation() } open fun setContentView(activity: Activity) { XTUIScreen.resetScreenInfo(activity) this.requestFragment().let { val transaction = activity.fragmentManager.beginTransaction() transaction.replace(android.R.id.content, it) transaction.commit() it.setupKeyboardHeightProvider(activity) } } open fun attachFragment(activity: Activity, fragmentID: Int) { XTUIScreen.resetScreenInfo(activity) this.requestFragment().let { val transaction = activity.fragmentManager.beginTransaction() transaction.replace(fragmentID, it) transaction.commit() it.noStatusBar = true it.noSoftButtonBar = true it.resetContents() it.setupKeyboardHeightProvider(activity) } } fun scriptObject(): V8Object? { return xtrContext.evaluateScript("objectRefs['$objectUUID']") as? V8Object } open fun requestFragment(): XTUIViewController { return this } private var isViewLoaded = false open fun viewDidLoad() { isViewLoaded = true scriptObject()?.let { XTContext.invokeMethod(it, "viewDidLoad") XTContext.release(it) } this.viewWillLayoutSubviews() this.viewDidLayoutSubviews() } open fun viewWillAppear() { scriptObject()?.let { XTContext.invokeMethod(it, "viewWillAppear") XTContext.release(it) } } open fun viewDidAppear() { scriptObject()?.let { XTContext.invokeMethod(it, "viewDidAppear") XTContext.release(it) } } open fun viewWillDisappear() { scriptObject()?.let { XTContext.invokeMethod(it, "viewWillDisappear") XTContext.release(it) } } open fun viewDidDisappear() { scriptObject()?.let { XTContext.invokeMethod(it, "viewDidDisappear") XTContext.release(it) } } open fun viewWillLayoutSubviews() { if (!isViewLoaded) { return } scriptObject()?.let { XTContext.invokeMethod(it, "viewWillLayoutSubviews") XTContext.release(it) } } open fun viewDidLayoutSubviews() { if (!isViewLoaded) { return } scriptObject()?.let { XTContext.invokeMethod(it, "viewDidLayoutSubviews") XTContext.release(it) } } fun willMoveToParentViewController(parent: XTUIViewController?) { scriptObject()?.let { XTContext.invokeMethod(it, "_willMoveToParentViewController", listOf( parent?.objectUUID ?: V8.getUndefined() )) } } fun didMoveToParentViewController(parent: XTUIViewController?) { scriptObject()?.let { XTContext.invokeMethod(it, "_didMoveToParentViewController", listOf( parent?.objectUUID ?: V8.getUndefined() )) } } private var keyboardHeightProvider: KeyboardHeightProvider? = null private fun setupKeyboardHeightProvider(activity: Activity) { keyboardHeightProvider = KeyboardHeightProvider(activity) activity.findViewById<View>(android.R.id.content).rootView?.post { keyboardHeightProvider?.start() } } override fun onDestroy() { super.onDestroy() keyboardHeightProvider?.close() } override fun onPause() { super.onPause() keyboardHeightProvider?.setKeyboardHeightObserver(null) } override fun onResume() { super.onResume() keyboardHeightProvider?.setKeyboardHeightObserver(this) } override fun onKeyboardHeightChanged(height: Int, orientation: Int) { this.lastKeyboardHeight = height handleKeyboardHeightChanged(height) } var lastKeyboardHeight = 0 fun handleKeyboardHeightChanged(height: Int = this.lastKeyboardHeight) { scriptObject()?.let { if (height > 0) { XTContext.invokeMethod(it, "keyboardWillShow", listOf( XTUIUtils.fromRect(XTUIRect( 0.0, 0.0, this.view?.bounds?.width ?: 0.0, height.toDouble() / resources.displayMetrics.density), xtrContext.runtime), 0.25)) } else { XTContext.invokeMethod(it, "keyboardWillHide", listOf(0.25)) } XTContext.release(it) } } class JSExports(val context: XTUIContext): XTComponentExport() { override val name: String = "_XTUIViewController" override fun exports(): V8Object { val exports = V8Object(context.runtime) exports.registerJavaMethod(this, "create", "create", arrayOf()) exports.registerJavaMethod(this, "xtr_view", "xtr_view", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_setView", "xtr_setView", arrayOf(String::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_parentViewController", "xtr_parentViewController", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_childViewControllers", "xtr_childViewControllers", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_addChildViewController", "xtr_addChildViewController", arrayOf(String::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_removeFromParentViewController", "xtr_removeFromParentViewController", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_navigationController", "xtr_navigationController", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_navigationBar", "xtr_navigationBar", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_setNavigationBar", "xtr_setNavigationBar", arrayOf(String::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_showNavigationBar", "xtr_showNavigationBar", arrayOf(Boolean::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_hideNavigationBar", "xtr_hideNavigationBar", arrayOf(Boolean::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_showBackButton", "xtr_showBackButton", arrayOf(String::class.java)) exports.registerJavaMethod(this, "xtr_presentViewController", "xtr_presentViewController", arrayOf(String::class.java, Boolean::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_dismissViewController", "xtr_dismissViewController", arrayOf(Boolean::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_setSupportOrientations", "xtr_setSupportOrientations", arrayOf(V8Array::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_setLayoutOptions", "xtr_setLayoutOptions", arrayOf(V8Array::class.java, String::class.java)) exports.registerJavaMethod(this, "xtr_safeAreaInsets", "xtr_safeAreaInsets", arrayOf(String::class.java)) return exports } fun create(): String { val viewController = XTUIViewController() viewController.xtrContext = context val managedObject = XTManagedObject(viewController) viewController.objectUUID = managedObject.objectUUID XTMemoryManager.add(managedObject) return managedObject.objectUUID } fun xtr_view(objectRef: String): String? { return (XTMemoryManager.find(objectRef) as? XTUIViewController)?.view?.objectUUID } fun xtr_setView(viewRef: String, objectRef: String) { val view = XTMemoryManager.find(viewRef) as? XTUIView ?: return val viewController = XTMemoryManager.find(objectRef) as? XTUIViewController ?: return viewController.view = view view.post { viewController.viewDidLoad() } } fun xtr_parentViewController(objectRef: String): String? { return (XTMemoryManager.find(objectRef) as? XTUIViewController)?.parentViewController?.get()?.objectUUID } fun xtr_childViewControllers(objectRef: String): V8Array? { return (XTMemoryManager.find(objectRef) as? XTUIViewController)?.let { val v8Array = V8Array(context.runtime) it.childViewControllers.mapNotNull { it -> return@mapNotNull it.objectUUID }.forEach { v8Array.push(it) } return@let v8Array } } fun xtr_addChildViewController(childControllerRef: String, objectRef: String) { val childController = XTMemoryManager.find(childControllerRef) as? XTUIViewController ?: return (XTMemoryManager.find(objectRef) as? XTUIViewController)?.let { if (childController.parentViewController == null) { childController.willMoveToParentViewController(it) it.childViewControllers.toMutableList()?.let { mutable -> mutable.add(childController) childController.parentViewController = WeakReference(it) it.childViewControllers = mutable.toList() } childController.didMoveToParentViewController(it) } } } fun xtr_removeFromParentViewController(objectRef: String) { (XTMemoryManager.find(objectRef) as? XTUIViewController)?.let { it.parentViewController?.let { parentViewController -> it.willMoveToParentViewController(null) parentViewController.get()?.childViewControllers?.toMutableList()?.let { mutable -> mutable.remove(it) parentViewController.get()?.childViewControllers = mutable.toList() } it.didMoveToParentViewController(null) } it.parentViewController = null } } fun xtr_navigationController(objectRef: String): String? { (XTMemoryManager.find(objectRef) as? XTUIViewController)?.let { var currentParentViewController = it.parentViewController?.get() while (currentParentViewController != null) { if (currentParentViewController is XTUINavigationController) { return currentParentViewController.objectUUID } currentParentViewController = currentParentViewController.parentViewController?.get() } } return null } fun xtr_navigationBar(objectRef: String): String? { return (XTMemoryManager.find(objectRef) as? XTUIViewController)?.requestFragment()?.navigationBar?.objectUUID } fun xtr_setNavigationBar(navigationBarRef: String, objectRef: String) { val navigationBar = XTMemoryManager.find(navigationBarRef) as? XTUINavigationBar ?: return (XTMemoryManager.find(objectRef) as? XTUIViewController)?.requestFragment()?.navigationBar = navigationBar } fun xtr_showNavigationBar(value: Boolean, objectRef: String) { (XTMemoryManager.find(objectRef) as? XTUIViewController)?.requestFragment()?.navigationBarHidden = false } fun xtr_hideNavigationBar(value: Boolean, objectRef: String) { (XTMemoryManager.find(objectRef) as? XTUIViewController)?.requestFragment()?.navigationBarHidden = true } fun xtr_showBackButton(objectRef: String): Boolean { val viewController = (XTMemoryManager.find(objectRef) as? XTUIViewController) ?: return false return viewController?.activity?.intent?.getBooleanExtra("XTUIShowBackButton", viewController.showBackButton) ?: viewController.showBackButton } fun xtr_presentViewController(viewControllerRef: String, animated: Boolean, objectRef: String) { val targetViewController = (XTMemoryManager.find(viewControllerRef) as? XTUIViewController) ?: return val intent = Intent(context.appContext, NextActivity::class.java) if (!animated) { intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) } intent.putExtra("ViewControllerObjectUUID", targetViewController.objectUUID) context.appContext.startActivity(intent) } fun xtr_dismissViewController(animated: Boolean, objectRef: String) { val viewController = (XTMemoryManager.find(objectRef) as? XTUIViewController) ?: return viewController.requestFragment()?.let { (it.activity as? NextActivity)?.finishWithAnimation = !animated it.activity.finish() } } fun xtr_setSupportOrientations(value: V8Array, objectRef: String) { V8ObjectUtils.toList(value)?.let { var newValue = mutableListOf<Int>() if (it.contains(1)) { newValue.add(1) } if (it.contains(2)) { newValue.add(2) } if (it.contains(3)) { newValue.add(3) } if (it.contains(4)) { newValue.add(4) } (XTMemoryManager.find(objectRef) as? XTUIViewController)?.supportOrientations = newValue.toList() } } fun xtr_setLayoutOptions(value: V8Array, objectRef: String) { (XTMemoryManager.find(objectRef) as? XTUIViewController)?.layoutOptions = V8ObjectUtils.toList(value).mapNotNull { it as? Int } } fun xtr_safeAreaInsets(objectRef: String): V8Object { val v8Object = V8Object(context.runtime) v8Object.add("top", 0) v8Object.add("left", 0) v8Object.add("bottom", 0) v8Object.add("right", 0) (XTMemoryManager.find(objectRef) as? XTUIViewController)?.let { if (it.navigationBarHidden) { v8Object.add("top", it.getStatusBarHeight()) } } return v8Object } } class NextActivity: XTUIActivity() { var viewController: XTUIViewController? = null var finishWithAnimation = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) intent?.getStringExtra("ViewControllerObjectUUID")?.let { this.viewController = XTMemoryManager.find(it) as? XTUIViewController } this.viewController?.setContentView(this) } override fun onPause() { if (finishWithAnimation) { this.overridePendingTransition(0, 0) } super.onPause() } } }
2
TypeScript
0
5
27f6b6da501944997af5d87d6ac08067dcf8c3e6
16,755
XT
MIT License
core-network/src/main/java/com/bp/core_network/network/config/Configuration.kt
yvek
625,877,016
false
{"Kotlin": 16472}
package com.bp.core_network.network.config object Configuration { const val BASE_URL = "https://jsonplaceholder.typicode.com/" const val homeIconUrl = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRGqQ9h324N7QbTjXHDbiT6Suu-x9BReRtfWw&usqp=CAU" }
0
Kotlin
0
0
36d0e34cc60a3a6baa4e0d1608822d4daa26ef6e
263
BluePillow
Apache License 2.0
app/src/main/java/com/osy/intern/ui/detail/DetailActivity.kt
seung-yeol
199,826,935
false
null
package com.osy.intern.ui.detail import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.updateLayoutParams import com.bumptech.glide.Glide import com.osy.intern.R import com.osy.intern.data.vo.ImgVO import kotlinx.android.synthetic.main.activity_detail.* class DetailActivity : AppCompatActivity() { lateinit var document : ImgVO.Document var imgHeight : Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) with(intent.getBundleExtra("bundle")){ document = getParcelable("document") imgHeight = getInt("imgHeight") } initView() } private fun initView() { img.updateLayoutParams { height = imgHeight } Glide.with(this).load(document.imageUrl).thumbnail(0.3f).into(img) txtDocURL.text = document.docUrl txtSource.text = document.displaySitename txtDatetime.text = document.datetime } }
0
Kotlin
0
0
4f7c592bbdbc7611468b19ba754f5cc6f2cc34c0
1,047
intern
Apache License 2.0
app/src/main/kotlin/gj/meteoras/ui/place/compose/Weather.kt
gytisjakutonis
401,411,809
false
null
package gj.meteoras.ui.place.compose import androidx.compose.foundation.layout.size import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import gj.meteoras.R import gj.meteoras.data.Forecast import gj.meteoras.data.Place import org.shredzone.commons.suncalc.SunTimes import java.time.ZoneId @Composable fun Weather( coordinates: Place.Coordinates, timestamp: Forecast.Timestamp, ) { val sun = derivedStateOf { SunTimes.compute() .on(timestamp.time.atZone(utcZoneId).toLocalDate()) .at(coordinates.latitude, coordinates.longitude) .execute() .let { times -> times.isAlwaysUp || times.rise?.toInstant()?.isBefore(timestamp.time) == true && times.set?.toInstant()?.isAfter(timestamp.time) == true } } val image = derivedStateOf { when (timestamp.condition) { Forecast.Timestamp.Condition.Clear -> if (sun.value) R.drawable.ic_day else R.drawable.ic_night Forecast.Timestamp.Condition.IsolatedClound, Forecast.Timestamp.Condition.ScatteredClouds -> if (sun.value) R.drawable.ic_clouds_day else R.drawable.ic_clouds_night Forecast.Timestamp.Condition.Overcast -> R.drawable.ic_clouds Forecast.Timestamp.Condition.LightRain -> R.drawable.ic_light_rain Forecast.Timestamp.Condition.ModerateRain -> R.drawable.ic_moderate_rain Forecast.Timestamp.Condition.HeavyRain -> R.drawable.ic_heavy_rain Forecast.Timestamp.Condition.Sleet -> R.drawable.ic_sleet Forecast.Timestamp.Condition.LightSnow -> R.drawable.ic_light_snow Forecast.Timestamp.Condition.ModerateSnow -> R.drawable.ic_moderate_snow Forecast.Timestamp.Condition.HeavySnow -> R.drawable.ic_heavy_snow Forecast.Timestamp.Condition.Fog -> R.drawable.ic_fog Forecast.Timestamp.Condition.NA -> R.drawable.ic_na } } Icon( painter = painterResource(image.value), contentDescription = null, tint = MaterialTheme.colors.primaryVariant, modifier = Modifier.size(24.dp) ) } private val utcZoneId = ZoneId.of("UTC")
0
Kotlin
0
0
0465e6c33d8ea366b5cf6189faea4766e16b962c
2,500
MeteOras
MIT License
src/main/kotlin/org/mw/WordsGenerator.kt
zharkomi
615,667,353
false
null
package org.mw import org.mw.model.MarkovMultilevelModel import org.mw.model.Word import java.io.BufferedReader import java.io.InputStream import java.util.* object WordsGenerator { @JvmStatic fun main(args: Array<String>) { val parameters = GeneratorParameters.parseArguments(args) val (model, words) = createModel(parameters) generateWords(model, words, parameters) } private fun createModel(parameters: GeneratorParameters): Pair<MarkovMultilevelModel, Set<String>> { if (!parameters.modelExists()) { val words = readWordsFromFiles(parameters.getDictionaryStream()) val model = MarkovMultilevelModel(parameters.generate, parameters.getAlphabet()) model.loadDictionary(words) model.saveToFile(parameters.getOutputModelFile()) return Pair(model, words) } return Pair(MarkovMultilevelModel.readFromFile(parameters.getInputModelFile()), Collections.emptySet()) } private fun readWordsFromFiles(inputStream: InputStream): Set<String> { val reader = BufferedReader(inputStream.reader()) val result = HashSet<String>(); reader.use { reader -> var line = reader.readLine() while (line != null) { result.add(line.lowercase()) line = reader.readLine() } } return result; } private fun generateWords( model: MarkovMultilevelModel, dictionary: Set<String>, parameters: GeneratorParameters ) { if (parameters.run <= 0) { return } val wordsSet = TreeSet<Word>(); var exists = 0; for (i in 0 until parameters.wordCount) { val word = model.getNextWord(parameters.run) if (dictionary.contains(word.value)) { exists++ } wordsSet.add(word) } for (word in wordsSet) { println(word) } println("\n" + wordsSet.size + " unique items, $exists generated words were present in dictionary of size " + dictionary.size) val scores = wordsSet.groupBy { w -> w.score } println("Scores statistics: ") scores.entries.stream() .sorted(Comparator.comparing { (k, _) -> k }) .forEach { (k, v) -> println("$k: " + v.size) } } }
0
Kotlin
0
0
ce8c5f1439cde033b6d086b28fd1cfab2aba8faf
2,387
markov-words
MIT License
git-checkout-core/src/main/kotlin/com/tencent/bk/devops/git/core/service/handler/GitLfsHandler.kt
TencentBlueKing
382,218,435
false
{"Kotlin": 664573, "Java": 7574, "Shell": 732}
package com.tencent.bk.devops.git.core.service.handler import com.tencent.bk.devops.git.core.constant.ContextConstants import com.tencent.bk.devops.git.core.pojo.GitSourceSettings import com.tencent.bk.devops.git.core.service.GitCommandManager import com.tencent.bk.devops.git.core.util.EnvHelper import org.slf4j.LoggerFactory class GitLfsHandler( private val settings: GitSourceSettings, private val git: GitCommandManager ) : IGitHandler { companion object { private val logger = LoggerFactory.getLogger(GitLfsHandler::class.java) } override fun doHandle() { val startEpoch = System.currentTimeMillis() try { with(settings) { if (!lfs) { return } logger.groupStart("Fetching lfs") git.lfsVersion() if (lfsConcurrentTransfers != null && lfsConcurrentTransfers > 0) { git.config(configKey = "lfs.concurrenttransfers", configValue = lfsConcurrentTransfers.toString()) } if (settings.enableGitLfsClean == true) { git.tryCleanLfs() } git.lfsPull( fetchInclude = includeSubPath, fetchExclude = excludeSubPath ) logger.groupEnd("") } } finally { EnvHelper.putContext( key = ContextConstants.CONTEXT_LFS_COST_TIME, value = (System.currentTimeMillis() - startEpoch).toString() ) } } }
11
Kotlin
6
9
c6618833e663310354403c60e4a8f99a6e681931
1,603
ci-git-checkout
MIT License
forge/src/main/java/com/tkisor/upd8r/forge/event/ModEventSubscriber.kt
Tki-sor
638,110,305
false
null
package com.tkisor.upd8r.forge.event import com.tkisor.upd8r.config.Upd8rConfig import com.tkisor.upd8r.data.Upd8rData import net.minecraft.client.gui.screens.TitleScreen import net.minecraftforge.client.event.ScreenEvent import net.minecraftforge.common.MinecraftForge import net.minecraftforge.eventbus.api.SubscribeEvent import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent import net.minecraftforge.internal.BrandingControl import java.lang.reflect.Method object ModEventSubscriber { private var hasLoaded = false @SubscribeEvent fun onClientSetup(event: FMLClientSetupEvent?) { MinecraftForge.EVENT_BUS.register(ModEventSubscriber::class.java) } @SubscribeEvent fun openMainMenu(event: ScreenEvent.Init) { if (event.screen is TitleScreen) { this.init() } } fun init() { if (!hasLoaded) { try { val brandingControl = BrandingControl() val field = BrandingControl::class.java.getDeclaredField("brandings") field.isAccessible = true val computeBranding: Method = BrandingControl::class.java.getDeclaredMethod("computeBranding") computeBranding.isAccessible = true computeBranding.invoke(null) val brands: List<String> = ArrayList(field.get(brandingControl) as List<String>) val newBrands = mutableListOf<String>() field.set(brandingControl, newBrands) newBrands.addAll(brands) val upd8rInfo = mutableListOf<String>() upd8rInfo.add("当前版本:${Upd8rConfig().get().currentVersion.versionName} or ${Upd8rConfig().get().currentVersion.versionCode}") upd8rInfo.add("最新版本:${Upd8rData.versionName} or ${Upd8rData.versionCode}") newBrands.addAll(upd8rInfo) } catch (e: Exception) { e.printStackTrace() } hasLoaded = true } } }
2
Kotlin
0
0
9770f228f06d35bc1dec8161273c4bb0afac7272
2,014
Upd8r
MIT License
feature/movie-list/imp/src/main/kotlin/com/vpopov/movienow/feature/movie/list/imp/data/local/MovieDao.kt
Va1erii
461,271,627
false
null
package com.vpopov.movienow.feature.movie.list.imp.data.local import com.vpopov.movienow.feature.movie.list.api.model.Movie import kotlinx.coroutines.flow.Flow internal interface MovieDao { fun getMovies(): Flow<List<Movie>> }
4
Kotlin
0
0
ab03f4cc5484548b0d40486fac7b90c1c8e75470
233
movie-now
MIT License
domain/src/main/java/com/movingmaker/domain/usecase/SignOutUseCase.kt
dudwls901
458,682,004
false
{"Kotlin": 270966}
package com.movingmaker.domain.usecase import com.movingmaker.domain.model.UiState import javax.inject.Inject class SignOutUseCase @Inject constructor( ) { suspend operator fun invoke(): UiState<String> = UiState.Success("temp") }
9
Kotlin
0
1
32865202976a2586ec8aa3687467dcb40d93fdc9
236
CommentDiary-Android
MIT License
src/test/kotlin/no/nav/dagpenger/datadeling/ressurs/RessursDaoTest.kt
navikt
639,375,864
false
{"Kotlin": 61858, "Dockerfile": 106}
package no.nav.dagpenger.datadeling.ressurs import kotliquery.sessionOf import no.nav.dagpenger.datadeling.AbstractDatabaseTest import no.nav.dagpenger.datadeling.enDatadelingRequest import no.nav.dagpenger.datadeling.teknisk.asQuery import no.nav.dagpenger.datadeling.teknisk.objectMapper import no.nav.dagpenger.kontrakter.datadeling.DatadelingRequest import no.nav.dagpenger.kontrakter.datadeling.DatadelingResponse import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import java.time.LocalDate import java.time.LocalDateTime import java.util.* import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @TestInstance(TestInstance.Lifecycle.PER_CLASS) class RessursDaoTest : AbstractDatabaseTest() { private val ressursDao = RessursDao(database.dataSource) @Test fun `opprett ressurs`() { ressursDao.opprett(DatadelingRequest("123", LocalDate.now(), LocalDate.now())) ressursDao.opprett(DatadelingRequest("234", LocalDate.now(), LocalDate.now())) ressursDao.opprett(DatadelingRequest("345", LocalDate.now(), LocalDate.now())) alleRessurser().let { ressurser -> assertEquals(3, ressurser.size) assertTrue { ressurser.all { it.status == RessursStatus.OPPRETTET } } } } @Test fun `henter ressurs`() { val request = enDatadelingRequest() val response = DatadelingResponse( personIdent = "EN-IDENT", perioder = emptyList(), ) val id = insertRessurs(RessursStatus.FERDIG, request, response) ressursDao.hent(id!!).let { assertNotNull(it) assertEquals(it.status, RessursStatus.FERDIG) } } @Test fun `returnerer null om ressurs ikke finnes`() { assertNull(ressursDao.hent(UUID.randomUUID())) } @Test fun `ferdigstill ressurs`() { val opprettet = ressursDao.opprett(DatadelingRequest("123", LocalDate.now(), LocalDate.now())) assertNotNull(opprettet) assertEquals(RessursStatus.OPPRETTET, opprettet.status) val response = DatadelingResponse( personIdent = "EN-IDENT", perioder = emptyList(), ) ressursDao.ferdigstill(opprettet.uuid, response) val ferdigstilt = ressursDao.hent(opprettet.uuid) assertNotNull(ferdigstilt) assertEquals(RessursStatus.FERDIG, ferdigstilt.status) assertEquals(response.personIdent, ferdigstilt.response!!.personIdent) } @Test fun `marker ressurs som feilet`() { val ressurs = ressursDao.opprett(DatadelingRequest("123", LocalDate.now(), LocalDate.now())) assertNotNull(ressurs) assertEquals(RessursStatus.OPPRETTET, ressurs.status) ressursDao.markerSomFeilet(ressurs.uuid) assertEquals(RessursStatus.FEILET, ressursDao.hent(ressurs.uuid)!!.status) } @Test fun `marker gamle ressurser som feilet`() { val ressurs = ressursDao.opprett(DatadelingRequest("123", LocalDate.now(), LocalDate.now())) assertNotNull(ressurs) assertEquals(RessursStatus.OPPRETTET, ressurs.status) ressursDao.markerSomFeilet(LocalDateTime.now()) assertEquals(RessursStatus.FEILET, ressursDao.hent(ressurs.uuid)!!.status) } @Test fun `sletter ferdige ressurser`() { val now = LocalDateTime.now() insertRessurs(RessursStatus.OPPRETTET, opprettet = now.minusMinutes(10)) insertRessurs(RessursStatus.FERDIG, opprettet = now.minusMinutes(10)) insertRessurs(RessursStatus.FERDIG, opprettet = now) insertRessurs(RessursStatus.FEILET, opprettet = now) val antallSlettet = ressursDao.slettFerdigeRessurser(eldreEnn = now.minusMinutes(5)) assertEquals(1, antallSlettet) assertEquals(3, alleRessurser().size) } private fun alleRessurser() = sessionOf(database.dataSource).use { session -> session.run( asQuery("select * from ressurs").map { row -> Ressurs( uuid = row.uuid("uuid"), status = RessursStatus.valueOf(row.string("status").uppercase()), response = row.stringOrNull("response") ?.let { objectMapper.readValue(it, DatadelingResponse::class.java) } ) }.asList ) } private fun insertRessurs( status: RessursStatus = RessursStatus.OPPRETTET, request: DatadelingRequest = enDatadelingRequest(), response: DatadelingResponse? = null, opprettet: LocalDateTime = LocalDateTime.now() ) = sessionOf(database.dataSource).use { session -> session.run( asQuery( """ insert into ressurs(uuid, status, response, request, opprettet) values(?, CAST(? as ressurs_status), CAST(? as json), CAST(? as json), ?) returning uuid """.trimIndent(), UUID.randomUUID(), status.name.lowercase(), if (response != null) objectMapper.writeValueAsString(response) else null, objectMapper.writeValueAsString(request), opprettet ).map { it.uuid("uuid") }.asSingle ) } }
6
Kotlin
0
1
3dfcf67f1211cbd9c514debfd92e4248a17bdecc
5,467
dp-datadeling
MIT License
src/main/kotlin/com/github/zimablue/suits/internal/core/action/MythicAction.kt
Nerorrlex911
609,705,350
false
null
package com.github.zimablue.suits.internal.core.action import com.github.zimablue.suits.api.action.SuitAction import ink.ptms.um.Mythic import org.bukkit.entity.Player import taboolib.common5.cfloat class MythicAction(actionConfig: Map<String, Any?>): SuitAction(actionConfig) { override val key = "mythic" val skillId = actionConfig["skillId"].toString() override fun execute(context: MutableMap<String, Any>) { super.execute(context) Mythic.API.castSkill(caster=context["player"] as Player, skillName = skillId, power = context["suit_amount"].cfloat) } }
1
null
1
3
88bd20e9f953d8a62f0a30453a6adaea056b4fcc
593
PoemSuits
Creative Commons Zero v1.0 Universal
apps/kafka-streams-avro/main/ks/App.kt
rtc11
458,774,158
false
null
package ks import io.ktor.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* import kstream.Kafka import kstream.KafkaStreamsFactory import no.tordly.avro.aap.Vedtak import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.Topology import org.apache.kafka.streams.kstream.Materialized fun main() { embeddedServer(Netty, port = 8080, module = Application::app).start(wait = true) } internal fun createTopology(): Topology = StreamsBuilder().apply { val vedtakTable = table<String, Vedtak>("vedtak.avro", Materialized.`as`("vedtak-store")) createSøknadStream(vedtakTable) createMedlemStream(vedtakTable) }.build() fun Application.app( kafkaFactory: Kafka = KafkaStreamsFactory("http://localhost:8085"), topology: Topology = createTopology(), ) { val kStream = kafkaFactory.createKStream(topology = topology) environment.monitor.subscribe(ApplicationStarted) { kStream.start() } environment.monitor.subscribe(ApplicationStopping) { kStream.close() } }
0
Kotlin
2
0
0bcb54c4c523f1bc2ffb8eac6a6837cc8a20fd69
1,081
poc
MIT License
app/src/main/java/net/komunan/komunantw/ui/account/list/AccountListViewModel.kt
ofnhwx
127,734,456
false
{"Kotlin": 115360}
package net.komunan.komunantw.ui.account.list import androidx.lifecycle.LiveData import io.objectbox.android.ObjectBoxLiveData import net.komunan.komunantw.core.repository.entity.Account import net.komunan.komunantw.core.repository.entity.Account_ import net.komunan.komunantw.ui.common.base.TWBaseViewModel class AccountListViewModel : TWBaseViewModel() { val accounts: LiveData<List<Account>> get() = ObjectBoxLiveData(Account.query().apply { order(Account_.name) }.build()) }
8
Kotlin
0
0
80c366a0eeb67619761eb38a8a992074fd85aad7
513
KomunanTW
Apache License 2.0
kotlin-jira-client/kotlin-jira-client-test-base/src/main/kotlin/com/linkedplanet/kotlinjiraclient/JiraIssueLinkOperatorTest.kt
linked-planet
602,453,377
false
null
/*- * #%L * kotlin-jira-client-test-base * %% * Copyright (C) 2022 - 2023 linked-planet GmbH * %% * 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. * #L% */ package com.linkedplanet.kotlinjiraclient import com.linkedplanet.kotlinjiraclient.util.rightAssertedJiraClientError import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test interface JiraIssueLinkOperatorTest<JiraFieldType> : BaseTestConfigProvider<JiraFieldType> { @Test fun issueLinks_01CreateAndDeleteIssueLink() { println("### START issueLinks_01CreateAndDeleteIssueLink") val (inward, _) = jiraCommentTestHelper.createIssueWithComment("issueLinks_01CreateAndDeleteIssueLink Inward") val (outward, _) = jiraCommentTestHelper.createIssueWithComment("issueLinks_01CreateAndDeleteIssueLink Outward") // Create runBlocking { issueLinkOperator.createIssueLink( inward.key, outward.key, "Relates" ) }.rightAssertedJiraClientError() // Check val issueLinks = jiraIssueLinkTestHelper.getIssueLinks(inward.key) assertEquals(1, issueLinks.size()) val issueLink = issueLinks.first().asJsonObject val issueLinkId = issueLink.get("id").asString val outwardIssue = issueLink.getAsJsonObject("outwardIssue") assertEquals(outward.key, outwardIssue.get("key").asString) // Delete runBlocking { issueLinkOperator.deleteIssueLink(issueLinkId) }.rightAssertedJiraClientError() // Check val issueLinksAfterDeletion = jiraIssueLinkTestHelper.getIssueLinks(inward.key) assertEquals(0, issueLinksAfterDeletion.size()) println("### END issueLinks_01CreateAndDeleteIssueLink") } @Test fun issueLinks_02EpicLink() { println("### START issueLinks_02EpicLink") // Create epic val epic = jiraIssueTestHelper.createEpic( fieldFactory.jiraEpicNameField("Test17_EpicName"), // required property for Epics fieldFactory.jiraSummaryField("issueLinks_07_TheEpicItself") ) // Create issue with link to epic val issueWithEpicLink = jiraIssueTestHelper.createDefaultIssue( fieldFactory.jiraEpicLinkField(epic.key), // adds link to the epic fieldFactory.jiraSummaryField("issueLinks_07_IssueWithEpicLink") ) val issue = jiraIssueTestHelper.getIssueByKey(issueWithEpicLink.key) assertEquals(epic.key, issue.epicKey) println("### END issueLinks_02EpicLink") } }
1
Kotlin
0
0
773e685b3c23d366132e480b418f885961ddaf23
3,124
kotlin-atlassian-client
Apache License 2.0
app/src/main/java/com/example/fitfinder/ui/profile/AdditionalPicturesViewHolder.kt
OmriGawi
618,447,164
false
{"Kotlin": 235146}
package com.example.fitfinder.ui.profile import android.view.View import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import com.example.fitfinder.R class AdditionalPicturesViewHolder( itemView: View, private val listener: AdditionalPicturesAdapter.OnImageRemovedListener ) : RecyclerView.ViewHolder(itemView) { val image: ImageView = itemView.findViewById(R.id.iv_additional) private val ivRemove: ImageView = itemView.findViewById(R.id.iv_remove) fun bind(imageUrl: String) { ivRemove.setOnClickListener { listener.onImageRemoved(adapterPosition, imageUrl) } } fun setEditMode(isEditMode: Boolean) { ivRemove.visibility = if (isEditMode) View.VISIBLE else View.GONE } }
0
Kotlin
0
0
41a8135cf8d3242b62069c207da7679053233816
776
FitFinder
MIT License
src/main/kotlin/com/picimako/justkitting/reference/CallMatcherReferenceContributor.kt
picimako
422,496,981
false
{"Gradle Kotlin DSL": 2, "Markdown": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "TOML": 1, "INI": 4, "Java": 58, "Kotlin": 21, "XML": 18, "YAML": 2, "SVG": 2, "HTML": 7}
//Copyright 2023 Tamás Balog. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.picimako.justkitting.reference import com.intellij.json.psi.JsonPsiUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.search.ProjectScope import com.intellij.psi.util.PsiLiteralUtil.isUnsafeLiteral import com.intellij.psi.util.PsiTreeUtil.getParentOfType import com.intellij.util.ProcessingContext import com.intellij.util.SmartList import com.picimako.justkitting.CallMatcherUtil import java.util.function.Supplier /** * Adds references to the arguments of [com.siyeh.ig.callMatcher.CallMatcher] static factory methods: `staticCall`, `instanceCall`, `exactInstanceCall`. * The first one is the fully qualified name of the referenced class, while the rest are methods of said class. * * Upon resolving the references, the IDE navigates to the resolved class definition. * * In case of methods, if the call is [com.siyeh.ig.callMatcher.CallMatcher.exactInstanceCall], * then it provides references for methods exactly in the referenced class, * otherwise references are provided for methods in the super classes too. * * If the call is [com.siyeh.ig.callMatcher.CallMatcher.staticCall], it provides references only for static methods. * * @since 0.1.0 */ class CallMatcherReferenceContributor : PsiReferenceContributor() { override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { registrar.registerReferenceProvider( CallMatcherUtil.ARGUMENT_OF_CALL_MATCHER_PATTERN, object : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> { val parentCall = getParentOfType(element, PsiMethodCallExpression::class.java) ?: return PsiReference.EMPTY_ARRAY val callMatcherArguments = parentCall.argumentList val reference = SmartList<PsiReference>() //If the current literal is the first argument (the class FQN) of the CallMatcher call if (element.manager.areElementsEquivalent(element, callMatcherArguments.expressions[0])) { if (!isUnsafeLiteral(element as PsiLiteralExpression)) { findClass(element)?.let { reference.add(CallMatcherArgReference(element) { arrayOf(it) }) } } } else if (callMatcherArguments.expressionCount > 1 && !isUnsafeLiteral(element as PsiLiteralExpression)) { val className = parentCall.argumentList.expressions[0] //If the classname is a String we can simply find the class by it, otherwise first we have to evaluate the expression val referencedClass: PsiClass? = if (className is PsiLiteralExpression) findClass(className) else evaluate(className)?.let { findClass(it.toString(), element.getProject()) } //Mapping the PsiMethods to 'it', so that they are passed as PsiElements referencedClass?.let { reference.add(CallMatcherArgReference(element) { getMethodsByName(element, it, parentCall).map { it }.toTypedArray() }) } } return if (reference.isNotEmpty()) reference.toTypedArray() else PsiReference.EMPTY_ARRAY } }) } /** * Reference implementation to for class FQN and method name string literals in `CallMatcher` factory method arguments. */ private class CallMatcherArgReference(element: PsiElement, private val elementsToResolveTo: Supplier<Array<PsiElement>>) : PsiReferenceBase<PsiElement?>(element, TextRange.create(1, element.textRange.length - 1), true), PsiPolyVariantReference { override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { return if (!incompleteCode) elementsToResolveTo.get() .map { element: PsiElement -> PsiElementResolveResult(element) } .toTypedArray() else ResolveResult.EMPTY_ARRAY } override fun resolve(): PsiElement? { val resolveResults = multiResolve(false) return if (resolveResults.size == 1) resolveResults[0].element else null } } companion object { @JvmStatic fun findClass(expression: PsiExpression): PsiClass? { val evaluated = evaluate(expression) return if (evaluated != null) findClass(evaluated.toString(), expression.project) else null } private fun evaluate(expression: PsiExpression): Any? { return JavaPsiFacade.getInstance(expression.project).constantEvaluationHelper.computeConstantExpression(expression, true) } private fun findClass(text: String, project: Project): PsiClass? { return JavaPsiFacade.getInstance(project).findClass(text, ProjectScope.getAllScope(project)) } private fun getMethodsByName(element: PsiElement, referencedClass: PsiClass, parentCall: PsiMethodCallExpression?): Array<PsiMethod> { val methodsInClass = referencedClass.findMethodsByName( JsonPsiUtil.stripQuotes(element.text), !CallMatcherUtil.CALL_MATCHER_EXACT_INSTANCE_MATCHER.matches(parentCall)) return if (CallMatcherUtil.CALL_MATCHER_STATIC_MATCHER.matches(parentCall)) CallMatcherUtil.filterByStatic(methodsInClass) else CallMatcherUtil.filterByNonStatic(methodsInClass) } } }
3
Java
0
4
7c1f5c586c5b5ff428702cff5f50194d1c209d13
5,886
just-kitting
Apache License 2.0
feature-onboarding-impl/src/main/java/jp/co/soramitsu/onboarding/impl/welcome/WelcomeFragment.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.onboarding.impl.welcome import android.graphics.Color import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import jp.co.soramitsu.common.base.BaseFragment import jp.co.soramitsu.common.mixin.impl.observeBrowserEvents import jp.co.soramitsu.common.utils.createSpannable import jp.co.soramitsu.common.view.viewBinding import jp.co.soramitsu.feature_onboarding_impl.R import jp.co.soramitsu.feature_onboarding_impl.databinding.FragmentWelcomeBinding import jp.co.soramitsu.account.api.presentation.account.create.ChainAccountCreatePayload @AndroidEntryPoint class WelcomeFragment : BaseFragment<WelcomeViewModel>(R.layout.fragment_welcome) { companion object { const val KEY_PAYLOAD = "key_payload" fun getBundle( displayBack: Boolean, chainAccountData: ChainAccountCreatePayload? = null ): Bundle { return bundleOf( KEY_PAYLOAD to WelcomeFragmentPayload(displayBack, chainAccountData) ) } } override val viewModel: WelcomeViewModel by viewModels() private val binding by viewBinding(FragmentWelcomeBinding::bind) override fun initViews() { configureTermsAndPrivacy( getString(R.string.onboarding_terms_and_conditions_1), getString(R.string.onboarding_terms_and_conditions_2), getString(R.string.onboarding_privacy_policy) ) with(binding) { termsTv.movementMethod = LinkMovementMethod.getInstance() termsTv.highlightColor = Color.TRANSPARENT createAccountBtn.setOnClickListener { viewModel.createAccountClicked() } importAccountBtn.setOnClickListener { viewModel.importAccountClicked() } back.setOnClickListener { viewModel.backClicked() } } } private fun configureTermsAndPrivacy(sourceText: String, terms: String, privacy: String) { binding.termsTv.text = createSpannable(sourceText) { clickable(terms) { viewModel.termsClicked() } clickable(privacy) { viewModel.privacyClicked() } } } override fun subscribe(viewModel: WelcomeViewModel) { viewModel.shouldShowBackLiveData.observe { binding.back.visibility = if (it) View.VISIBLE else View.GONE } observeBrowserEvents(viewModel) } }
11
Kotlin
21
68
d5b83674645c90c029786a2954710209256f1e39
2,578
fearless-Android
Apache License 2.0
feature-staking-api/src/main/java/io/novafoundation/nova/feature_staking_api/domain/model/SlashingSpans.kt
novasamatech
415,834,480
false
{"Kotlin": 7662683, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_staking_api.domain.model import java.math.BigInteger class SlashingSpans( val lastNonZeroSlash: EraIndex, val prior: List<EraIndex> ) fun SlashingSpans?.numberOfSlashingSpans(): BigInteger { if (this == null) return BigInteger.ZERO // all from prior + one for lastNonZeroSlash val numberOfSlashingSpans = prior.size + 1 return numberOfSlashingSpans.toBigInteger() }
19
Kotlin
5
9
651db6927cdc6ff89448c83d451c84bda937e9fc
434
nova-wallet-android
Apache License 2.0
libBase/src/main/java/com/effective/android/base/util/AnimationUtils.kt
YummyLau
118,240,800
false
null
package com.effective.android.base.util import android.animation.ObjectAnimator import android.animation.PropertyValuesHolder import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AccelerateInterpolator import android.view.animation.AnticipateOvershootInterpolator import android.view.animation.DecelerateInterpolator import android.view.animation.Interpolator import android.view.animation.LinearInterpolator object AnimationUtils { val LINEAR_INTERPOLATOR: Interpolator = LinearInterpolator() val DECELERATE_INTERPOLATOR: Interpolator = DecelerateInterpolator() val ACCELERATE_INTERPOLATOR: Interpolator = AccelerateInterpolator() val ACCELERATE_DECELERATE_INTERPOLATOR: Interpolator = AccelerateDecelerateInterpolator() val ANTICIPATE_OVERSHOOT_INTERPOLATOR: Interpolator = AnticipateOvershootInterpolator() /** * 缩放且Y轴位移的组合属性动画 */ fun createAnimator(target: View, scaleFrom: Float, scaleTo: Float, translationYFrom: Float, translationYTo: Float, duration: Long): ObjectAnimator { val scaleX = PropertyValuesHolder.ofFloat("scaleX", scaleFrom, scaleTo) val scaleY = PropertyValuesHolder.ofFloat("scaleY", scaleFrom, scaleTo) val translationY = PropertyValuesHolder.ofFloat("translationY", translationYFrom, translationYTo) val objectAnimator = ObjectAnimator.ofPropertyValuesHolder(target, scaleX, scaleY, translationY) objectAnimator.duration = duration objectAnimator.interpolator = DECELERATE_INTERPOLATOR return objectAnimator } }
1
Kotlin
32
187
f9bad2216051e5b848b2d862cab7958f1bcdc5e8
1,650
AndroidModularArchiteture
MIT License
Frontend/app/src/main/java/com/upick/upick/network/DTOs.kt
a-2z
304,930,804
false
{"Python": 13451375, "Kotlin": 49003, "C": 38357, "CSS": 6613, "JavaScript": 6264, "HTML": 5475, "C++": 3856, "Shell": 3085, "PowerShell": 1755, "Batchfile": 1629}
package com.upick.upick.network import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Check a user's existence, username, and friends */ @JsonClass(generateAdapter = true) data class UsersGETResponse( val success: Boolean, val data: UsersGETData? ) { @JsonClass(generateAdapter = true) data class UsersGETData( val id: Int, val username: String, val friends: List<Int> ) } /** * Get list of friend requests sent and received */ @JsonClass(generateAdapter = true) data class PendingGETResponse( val success: Boolean, val data: PendingGETData? ) { @JsonClass(generateAdapter = true) data class PendingGETData( val sent: List<Int>, // userIds val received: List<Int> // userIds ) } /** * Get all relevant attributes of a group. */ @JsonClass(generateAdapter = true) data class GroupsGETResponse( val success: Boolean, val data: GroupsGETData? ) { @JsonClass(generateAdapter = true) data class GroupsGETData( @Json(name = "group_id") val groupId: Int, val date: String, val host: Int, val name: String, val members: List<Int>, @Json(name = "survey_complete") val surveyComplete: Boolean, @Json(name = "top_choices") val topChoices: List<Int>, // r1_id, r2_id, ... @Json(name = "voting_complete") val votingComplete: Boolean, @Json(name = "final_choice") val finalChoice: Int // r_id ) } /** * Get all invitations to groups */ @JsonClass(generateAdapter = true) data class InvitesGETResponse( val success: Boolean, val data: InvitesGETData? ) { @JsonClass(generateAdapter = true) data class InvitesGETData( val invitations: List<Int> // gr1, grp2 ) } /** * Get a restaurant's details */ @JsonClass(generateAdapter = true) data class RestaurantsGETResponse( val success: Boolean, val data: RestaurantsGETData? ) { @JsonClass(generateAdapter = true) data class RestaurantsGETData( val id: Int, val name: String, val price: Int, // backend will constrain to 1-4 inclusive val image: String, val rating: Int, // backend will constrain to 1-5 inclusive val description: String, @Json(name = "wait_time") val waitTime: Int, // backend will constrain to 1-3 inclusive val phone: String, @Json(name = "location_x") val locationX: Float, @Json(name = "location_y") val locationY: Float ) } /** * Create a new user */ @JsonClass(generateAdapter = true) data class UsersPOSTResponse( val success: Boolean, val data: Int? // usr_id ) /** * Sign in with existing username/pwd */ @JsonClass(generateAdapter = true) data class SignInPOSTResponse( val success: Boolean, val data: Int? // usr_id ) /** * Invite friend or accept if invited by that friend. * friend1 is always the user. */ @JsonClass(generateAdapter = true) data class InvitesPOSTResponse( val success: Boolean, val data: InvitesPOSTData? ) { @JsonClass(generateAdapter = true) data class InvitesPOSTData( val added: Int // friend2 ) } /** * Create a new group */ @JsonClass(generateAdapter = true) data class CreatePOSTResponse( val success: Boolean, val data: Int? // group_id ) /** * Invite a friend to join a group */ @JsonClass(generateAdapter = true) data class GroupsPOSTResponse( val success: Boolean, val data: Int? // user ) /** * Respond to survey questions. Options for price should be * 7.5, 18, 33, and 80, but the labels should be ($5-10), * ($10-$25), ($26-$40), and $41+. Please reference the * 'upick summary' doc for the actual values submitted vs * the labels the user sees. */ @JsonClass(generateAdapter = true) data class SurveyPOSTResponse( val success: Boolean, val data: String? // = "Responses submitted" ) /** * Place ranked votes */ @JsonClass(generateAdapter = true) data class VotePOSTResponse( val success: Boolean, val data: String? // = "Vote submitted." ) /** *Leave a group. If the host leaves, the group is deleted. */ @JsonClass(generateAdapter = true) data class GroupsDELETEResponse( val success: Boolean, val data: String? // = "You left the group." ) /** * Join a group. */ @JsonClass(generateAdapter = true) data class GroupsJoinPOSTResponse( val success: Boolean, val data: Int? // group ) /** * Delete a user from the database */ @JsonClass(generateAdapter = true) data class UsersDELETEResponse( val success: Boolean, val data: String? // user(name) )
0
Python
0
0
ba362cdafbb77b3ab67d3907b6c1f9037dde18db
4,633
upick
MIT License
app/src/main/java/io/lerk/lrkFM/adapter/BaseArrayAdapter.kt
lfuelling
122,087,128
false
{"Kotlin": 184967, "Java": 2298}
package io.lerk.lrkFM.adapter import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.annotation.IdRes import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.appcompat.content.res.AppCompatResources import io.lerk.lrkFM.R import io.lerk.lrkFM.activities.file.FileActivity import io.lerk.lrkFM.entities.FMFile /** * @author <NAME> (<EMAIL>) */ abstract class BaseArrayAdapter internal constructor( context: Context, resource: Int, items: List<FMFile?>? ) : ArrayAdapter<FMFile?>(context, resource, items!!) { var activity: FileActivity? = null init { if (context is FileActivity) { activity = context } else { Log.d(TAG, "Context is no FileActivity: " + context.javaClass.name) } } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return initUI(getItem(position)) } protected abstract fun initUI(f: FMFile?): View protected abstract fun openFile(f: FMFile) /** * Sets file name in the text field of a dialog. * * @param alertDialog the dialog * @param destinationName the id of the EditText * @param name the name */ fun presetNameForDialog(alertDialog: AlertDialog?, @IdRes destinationName: Int, name: String?) { val editText = alertDialog!!.findViewById<EditText>(destinationName) editText?.setText(name) ?: Log.w( TAG, "Unable to find view, can not set file title." ) } /** * Adds the path of a file to a dialog. * * @param f the file * @param alertDialog the dialog * @see .presetNameForDialog */ @Suppress("unused") fun presetPathForDialog(f: FMFile, alertDialog: AlertDialog?) { presetNameForDialog(alertDialog, R.id.destinationPath, f.file.absolutePath) } /** * Utility method to create an AlertDialog. * * @param positiveBtnText the text of the positive button * @param title the title * @param icon the icon * @param view the content view * @param positiveCallBack the positive callback * @param negativeCallBack the negative callback * @return the dialog */ fun getGenericFileOpDialog( @StringRes positiveBtnText: Int, @StringRes title: Int, @DrawableRes icon: Int, @LayoutRes view: Int, positiveCallBack: (AlertDialog?) -> Unit, negativeCallBack: (AlertDialog?) -> Unit ): AlertDialog { val dialog = AlertDialog.Builder(activity) .setView(view) .setTitle(title) .setCancelable(true).create() dialog.setButton( DialogInterface.BUTTON_POSITIVE, activity!!.getString(positiveBtnText) ) { _: DialogInterface?, _: Int -> positiveCallBack(dialog) } dialog.setButton( DialogInterface.BUTTON_NEGATIVE, activity!!.getString(R.string.cancel) ) { _: DialogInterface?, _: Int -> negativeCallBack(dialog) } dialog.setOnShowListener { _: DialogInterface? -> val dialogIcon = dialog.findViewById<ImageView>(R.id.dialogIcon) dialogIcon.setImageDrawable(AppCompatResources.getDrawable(context, icon)) val inputField: EditText? if (view == R.layout.layout_name_prompt) { inputField = dialog.findViewById(R.id.destinationName) if (inputField != null) { val name = activity!!.getTitleFromPath(activity!!.currentDirectory) inputField.setText(name) Log.d(TAG, "Destination set to: $name") } else { Log.w(TAG, "Unable to preset current name, text field is null!") } } else if (view == R.layout.layout_path_prompt) { inputField = dialog.findViewById(R.id.destinationPath) if (inputField != null) { val directory = activity?.currentDirectory inputField.setText(directory) Log.d(TAG, "Destination set to: $directory") } else { Log.w(TAG, "Unable to preset current path, text field is null!") } } } return dialog } companion object { val TAG = BaseArrayAdapter::class.java.canonicalName } }
9
Kotlin
10
56
04dd079ab8aa05206e8e9336b51aaf24145f3727
4,795
lrkFM
MIT License
app/src/main/java/io/lerk/lrkFM/adapter/BaseArrayAdapter.kt
lfuelling
122,087,128
false
{"Kotlin": 184967, "Java": 2298}
package io.lerk.lrkFM.adapter import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ImageView import androidx.annotation.DrawableRes import androidx.annotation.IdRes import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.appcompat.content.res.AppCompatResources import io.lerk.lrkFM.R import io.lerk.lrkFM.activities.file.FileActivity import io.lerk.lrkFM.entities.FMFile /** * @author <NAME> (<EMAIL>) */ abstract class BaseArrayAdapter internal constructor( context: Context, resource: Int, items: List<FMFile?>? ) : ArrayAdapter<FMFile?>(context, resource, items!!) { var activity: FileActivity? = null init { if (context is FileActivity) { activity = context } else { Log.d(TAG, "Context is no FileActivity: " + context.javaClass.name) } } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return initUI(getItem(position)) } protected abstract fun initUI(f: FMFile?): View protected abstract fun openFile(f: FMFile) /** * Sets file name in the text field of a dialog. * * @param alertDialog the dialog * @param destinationName the id of the EditText * @param name the name */ fun presetNameForDialog(alertDialog: AlertDialog?, @IdRes destinationName: Int, name: String?) { val editText = alertDialog!!.findViewById<EditText>(destinationName) editText?.setText(name) ?: Log.w( TAG, "Unable to find view, can not set file title." ) } /** * Adds the path of a file to a dialog. * * @param f the file * @param alertDialog the dialog * @see .presetNameForDialog */ @Suppress("unused") fun presetPathForDialog(f: FMFile, alertDialog: AlertDialog?) { presetNameForDialog(alertDialog, R.id.destinationPath, f.file.absolutePath) } /** * Utility method to create an AlertDialog. * * @param positiveBtnText the text of the positive button * @param title the title * @param icon the icon * @param view the content view * @param positiveCallBack the positive callback * @param negativeCallBack the negative callback * @return the dialog */ fun getGenericFileOpDialog( @StringRes positiveBtnText: Int, @StringRes title: Int, @DrawableRes icon: Int, @LayoutRes view: Int, positiveCallBack: (AlertDialog?) -> Unit, negativeCallBack: (AlertDialog?) -> Unit ): AlertDialog { val dialog = AlertDialog.Builder(activity) .setView(view) .setTitle(title) .setCancelable(true).create() dialog.setButton( DialogInterface.BUTTON_POSITIVE, activity!!.getString(positiveBtnText) ) { _: DialogInterface?, _: Int -> positiveCallBack(dialog) } dialog.setButton( DialogInterface.BUTTON_NEGATIVE, activity!!.getString(R.string.cancel) ) { _: DialogInterface?, _: Int -> negativeCallBack(dialog) } dialog.setOnShowListener { _: DialogInterface? -> val dialogIcon = dialog.findViewById<ImageView>(R.id.dialogIcon) dialogIcon.setImageDrawable(AppCompatResources.getDrawable(context, icon)) val inputField: EditText? if (view == R.layout.layout_name_prompt) { inputField = dialog.findViewById(R.id.destinationName) if (inputField != null) { val name = activity!!.getTitleFromPath(activity!!.currentDirectory) inputField.setText(name) Log.d(TAG, "Destination set to: $name") } else { Log.w(TAG, "Unable to preset current name, text field is null!") } } else if (view == R.layout.layout_path_prompt) { inputField = dialog.findViewById(R.id.destinationPath) if (inputField != null) { val directory = activity?.currentDirectory inputField.setText(directory) Log.d(TAG, "Destination set to: $directory") } else { Log.w(TAG, "Unable to preset current path, text field is null!") } } } return dialog } companion object { val TAG = BaseArrayAdapter::class.java.canonicalName } }
9
Kotlin
10
56
04dd079ab8aa05206e8e9336b51aaf24145f3727
4,795
lrkFM
MIT License
src/main/kotlin/com/between_freedom_and_space/mono_backend/posts/internal/reactions/service/InteractionPostReactionsService.kt
Between-Freedom-and-Space
453,797,438
false
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
package com.between_freedom_and_space.mono_backend.posts.internal.reactions.service import com.between_freedom_and_space.mono_backend.posts.internal.reactions.service.model.BasePostReactionModel import com.between_freedom_and_space.mono_backend.posts.internal.reactions.service.model.CreatePostReactionModel import com.between_freedom_and_space.mono_backend.posts.internal.reactions.service.model.UpdatePostReactionModel interface InteractionPostReactionsService { fun createReaction(model: CreatePostReactionModel): BasePostReactionModel fun updateReaction(reactionId: Long, model: UpdatePostReactionModel): BasePostReactionModel fun deleteReaction(reactionId: Long): BasePostReactionModel }
0
Kotlin
0
1
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
709
Mono-Backend
Apache License 2.0
zircon.core/common/src/main/kotlin/org/hexworks/zircon/api/uievent/UIEventHandler.kt
jmedinaJBM
178,613,075
true
{"Kotlin": 1311631, "Java": 128163}
package org.hexworks.zircon.api.uievent /** * Callback interface for handling [UIEvent]s. * @param T the type of the [UIEvent] which is handled. */ interface UIEventHandler<T: UIEvent> { /** * Handles the given [event] in a given [phase]. * See [UIEventResponse] and [UIEventPhase] for more info. */ fun handle(event: T, phase: UIEventPhase): UIEventResponse }
0
Kotlin
0
0
700f7542c1d59f5561f2aec084f9b6a1f50649b0
389
zircon
MIT License
app/src/main/java/com/wavky/wechatdemo/ui/common/BadgedDecorator.kt
wavky
403,655,617
false
{"Kotlin": 66671}
package com.wavky.wechatdemo.ui.common import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CornerSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.wavky.wechatdemo.R /** * Created on 2021/08/31 * @author Wavky.Huang */ @Composable fun BadgedDecorator( isBadgeVisible: Boolean = true, badgeSize: Dp = 12.dp, content: @Composable () -> Unit ) { Box(contentAlignment = Alignment.TopEnd) { content() if (isBadgeVisible) { Canvas( Modifier .size(badgeSize) .offset(badgeSize / 2, -(badgeSize / 2)) ) { drawCircle(Color.Red) } } } } @Preview @Composable fun BadgeViewPreview() { Box(Modifier.size(100.dp), contentAlignment = Alignment.Center) { BadgedDecorator() { Image( painter = painterResource(R.drawable.avatar_me), contentDescription = "profile image", Modifier .size(60.dp) .clip(RoundedCornerShape(CornerSize(4.dp))) ) } } }
0
Kotlin
0
0
c7fdff411e9197cb693d42178b29ed2101643bb8
1,580
Compose-WeChatDemo
Apache License 2.0
psclient/src/main/java/com/majeur/psclient/ui/BaseFragment.kt
MajeurAndroid
191,601,039
false
null
package com.majeur.psclient.ui import android.os.Bundle import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.majeur.psclient.service.ShowdownService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelChildren import kotlin.coroutines.CoroutineContext open class BaseFragment : Fragment(), MainActivity.Callbacks { private var _service: ShowdownService? = null protected val service get() = _service protected val fragmentScope = FragmentScope() protected val homeFragment get() = mainActivity.homeFragment protected val battleFragment get() = mainActivity.battleFragment protected val chatFragment get() = mainActivity.chatFragment protected val teamsFragment get() = mainActivity.teamsFragment val mainActivity: MainActivity get() = requireActivity() as MainActivity override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycle.addObserver(fragmentScope) } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(fragmentScope) } override fun onServiceBound(service: ShowdownService) { _service = service } override fun onServiceWillUnbound(service: ShowdownService) { _service = null } class FragmentScope : CoroutineScope, LifecycleObserver { private val supervisorJob = SupervisorJob() override val coroutineContext: CoroutineContext get() = supervisorJob + Dispatchers.Main @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun destroy() = coroutineContext.cancelChildren() } }
0
null
5
30
e940c15924db38ba38a71f12ae8e6d640b166609
1,834
Android-Unoffical-Showdown-Client
Apache License 2.0
example/src/commonMain/kotlin/com/jeantuffier/statemachine/ArticleScreenOrchestration.kt
jeantuffier
448,109,955
false
{"Kotlin": 110935}
package com.jeantuffier.statemachine import com.jeantuffier.statemachine.orchestrate.LoadingStrategy import com.jeantuffier.statemachine.orchestrate.Orchestrated import com.jeantuffier.statemachine.orchestrate.OrchestratedData import com.jeantuffier.statemachine.orchestrate.OrchestratedPage import com.jeantuffier.statemachine.orchestrate.Orchestration @Orchestration( baseName = "ArticleScreen", errorType = AppError::class, actions = [CloseMovieDetails::class], ) interface ArticleScreenOrchestration { @Orchestrated( trigger = LoadMovies::class, loadingStrategy = LoadingStrategy.SUSPEND, ) val movies: OrchestratedPage<Movie> @Orchestrated( trigger = SelectMovie::class, loadingStrategy = LoadingStrategy.SUSPEND, ) val movie: OrchestratedData<Movie> val someRandomValue: String }
0
Kotlin
0
3
4082d1b0b503822e2348de33191622bd0677c956
862
statemachine
MIT License
src/main/kotlin/de/darkatra/vrising/discord/commands/parameters/ServerStatusMonitorIdParameter.kt
DarkAtra
500,198,988
false
{"Kotlin": 102183, "Shell": 155}
package de.darkatra.vrising.discord.commands.parameters import dev.kord.core.entity.interaction.ChatInputCommandInteraction import dev.kord.rest.builder.interaction.GlobalChatInputCreateBuilder import dev.kord.rest.builder.interaction.string object ServerStatusMonitorIdParameter { const val NAME = "server-status-monitor-id" } fun GlobalChatInputCreateBuilder.addServerStatusMonitorIdParameter() { string( name = ServerStatusMonitorIdParameter.NAME, description = "The id of the server status monitor." ) { required = true } } fun ChatInputCommandInteraction.getServerStatusMonitorIdParameter(): String { return command.strings[ServerStatusMonitorIdParameter.NAME]!! }
7
Kotlin
2
9
0d8d897d75d2029ccaf63b6295f174655f1bcc92
718
v-rising-discord-bot
MIT License
app/src/main/java/app/quarkton/ton/extensions/Mnemonic.kt
Skydev0h
649,793,179
false
null
package app.quarkton.ton.extensions import cash.z.ecc.android.bip39.Mnemonics import io.ktor.utils.io.core.toByteArray import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import org.ton.api.pk.PrivateKeyEd25519 import org.ton.crypto.SecureRandom import org.ton.crypto.decodeHex import org.ton.crypto.digest.Digest import org.ton.crypto.kdf.PKCSS2ParametersGenerator import org.ton.crypto.mac.hmac.HMac import org.ton.mnemonic.Mnemonic import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.random.Random fun Mnemonic.toKeyTon(mnemonic: List<String>, password: String = ""): PrivateKeyEd25519 = PrivateKeyEd25519(toSeed(mnemonic, password)) fun Mnemonic.toKeyStd(mnemonic: List<String>, password: String = ""): PrivateKeyEd25519 = PrivateKeyEd25519(toSeed(mnemonic, password)) // TODO!!!~~~ fun Mnemonic.toKeyPriv(mnemonic: List<String>): PrivateKeyEd25519 = PrivateKeyEd25519(mnemonic[0].decodeHex()) fun Mnemonic.toKey(mnemonic: List<String>, password: String = ""): PrivateKeyEd25519 = when { mnemonic.size == 1 -> toKeyPriv(mnemonic) isValid(mnemonic, password) -> toKeyTon(mnemonic, password) isStdValid(mnemonic) -> toKeyStd(mnemonic, password) else -> throw IllegalArgumentException("Invalid mnemonic (Not TON or Standard)") } @Suppress("UnusedReceiverParameter") fun Mnemonic.isStdValid(mnemonic: List<String>): Boolean = try { if (mnemonic.size != 777) TODO("Implement correct seed and key derivation for standard phrases") Mnemonics.MnemonicCode(mnemonic.joinToString(" ")).validate() true } catch (e: Error) { false } // https://github.com/andreypfau/ton-kotlin/blob/main/ton-kotlin-mnemonic/src/commonMain/kotlin/org/ton/mnemonic/Mnemonic.kt // Monkey extracted and patched to create mnemonic with real 240 bits of entropy instead of choppy 64 bit PRNG private val MnemonicGeneratorCoroutineName = CoroutineName("mnemonic-generator-secure") private val DEFAULT_BASIC_SALT_BYTES = Mnemonic.DEFAULT_BASIC_SALT.encodeToByteArray() private val DEFAULT_PASSWORD_SALT_BYTES = Mnemonic.DEFAULT_PASSWORD_SALT.encodeToByteArray() private val DEFAULT_SALT_BYTES = Mnemonic.DEFAULT_SALT.encodeToByteArray() private val EMPTY_BYTES = ByteArray(0) @OptIn(DelicateCoroutinesApi::class) suspend fun Mnemonic.secureGenerate( password: String = "", wordCount: Int = DEFAULT_WORD_COUNT, wordlist: List<String> = mnemonicWords(), random: Random = SecureRandom ): List<String> = suspendCancellableCoroutine { continuation -> GlobalScope.launch( Dispatchers.Default + MnemonicGeneratorCoroutineName ) { try { val mnemonic = Array(wordCount) { "" } // Just 64 bits of entropy VS 240 from full mnemonic // val weakRandom = Random(random.nextLong()) // \-- nextLong seeds weakRandom with only 64 bits of entropy! val digest = Digest.sha512() val hMac = HMac(digest) val passwordEntropy = ByteArray(hMac.macSize) val nonPasswordEntropy = ByteArray(hMac.macSize) val passwordBytes = password.toByteArray() val generator = PKCSS2ParametersGenerator(hMac) // SD: Initialize with secure words ONCE repeat(wordCount) { mnemonic[it] = wordlist.random(random) } var iters = 0 while (continuation.isActive) { // Each iteration change one word to new random one with SecureRandom ("rolling") // Is PROVABLY not less secure than regenerating each time and is much faster! mnemonic[(iters++) % wordCount] = wordlist.random(random) val mnemonicBytes = mnemonic.joinToString(" ").toByteArray() if (password.isNotEmpty()) { entropy(hMac, mnemonicBytes, EMPTY_BYTES, nonPasswordEntropy) if (!(passwordValidation(generator, nonPasswordEntropy) && !basicValidation( generator, nonPasswordEntropy )) ) { continue } } entropy(hMac, mnemonicBytes, passwordBytes, passwordEntropy) if (!basicValidation(generator, passwordEntropy)) { continue } continuation.resume(mnemonic.toList()) break } } catch (e: Throwable) { continuation.resumeWithException(e) } } } private fun entropy(hMac: HMac, mnemonic: ByteArray, password: ByteArray, output: ByteArray) { hMac.init(mnemonic) hMac += password hMac.build(output) } private fun basicValidation(generator: PKCSS2ParametersGenerator, entropy: ByteArray): Boolean { generator.init( password = <PASSWORD>, salt = DEFAULT_BASIC_SALT_BYTES, iterationCount = Mnemonic.DEFAULT_BASIC_ITERATIONS ) return generator.generateDerivedParameters(512).first() == 0.toByte() } private fun passwordValidation(generator: PKCSS2ParametersGenerator, entropy: ByteArray): Boolean { generator.init( password = <PASSWORD>, salt = DEFAULT_PASSWORD_SALT_BYTES, iterationCount = Mnemonic.DEFAULT_PASSWORD_ITERATIONS ) return generator.generateDerivedParameters(512).first() == 1.toByte() }
0
Kotlin
0
0
9801d96548826fbe46b3f3fed35c4e7c7b7efb43
5,671
quarkton-dev
MIT License
src/test/kotlin/no/nav/hjelpemidler/soknad/mottak/test/Testdata.kt
navikt
326,995,575
false
{"Kotlin": 212092, "Dockerfile": 218}
package no.nav.hjelpemidler.soknad.mottak.test import com.fasterxml.jackson.databind.JsonNode import no.nav.hjelpemidler.soknad.mottak.jsonMapper object Testdata { val testmeldingerFraOebs = jsonMapper.readResource<List<JsonNode>>("/kafka_testmessages/testmeldingerFraOebs.json") }
0
Kotlin
0
0
93512cd1c929f1152c9ed348c2a321bb53f17d79
288
hm-soknadsbehandling
MIT License
app/src/main/java/chall/watchthis/database/entity/FavEntity.kt
marcinslowikowski123
697,265,391
false
{"Kotlin": 26708}
package chall.watchthis.database.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "Fav") data class FavEntity ( @PrimaryKey val id: Int?, @ColumnInfo(name = "favourite") var favourite: Boolean? )
0
Kotlin
0
0
8c4a87d4bd83690b786a613638f8a734b757ee5b
283
Watchthis
MIT License
core-frame/src/main/java/com/panyz/core_frame/http/HttpResponse.kt
panyz
333,628,190
false
null
package com.panyz.core_frame.http data class HttpResponse<T>( val data: T, val errorCode: Int, val errorMsg: String, val status:Int )
0
Kotlin
0
0
5f382b9e6b64d7533af88cce928b1eb4cac44a21
150
GankIO
Apache License 2.0
src/main/kotlin/org/jetbrains/research/testspark/settings/llm/SettingsLLMComponent.kt
JetBrains-Research
563,889,235
false
{"Kotlin": 531243, "Java": 5347, "Shell": 132}
package org.jetbrains.research.testspark.settings.llm import com.intellij.ide.ui.UINumericRange import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.service import com.intellij.openapi.ui.ComboBox import com.intellij.ui.EditorTextField import com.intellij.ui.JBColor import com.intellij.ui.JBIntSpinner import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBTabbedPane import com.intellij.util.ui.FormBuilder import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.Json import org.jdesktop.swingx.JXTitledSeparator import org.jetbrains.research.testspark.bundles.TestSparkLabelsBundle import org.jetbrains.research.testspark.bundles.TestSparkToolTipsBundle import org.jetbrains.research.testspark.display.TestSparkIcons import org.jetbrains.research.testspark.display.createButton import org.jetbrains.research.testspark.helpers.addLLMPanelListeners import org.jetbrains.research.testspark.helpers.getLLLMPlatforms import org.jetbrains.research.testspark.helpers.stylizeMainComponents import org.jetbrains.research.testspark.services.PromptParserService import org.jetbrains.research.testspark.services.SettingsApplicationService import org.jetbrains.research.testspark.settings.SettingsApplicationState import org.jetbrains.research.testspark.tools.llm.generation.LLMPlatform import java.awt.FlowLayout import java.awt.Font import javax.swing.BorderFactory import javax.swing.BoxLayout import javax.swing.JButton import javax.swing.JCheckBox import javax.swing.JPanel import javax.swing.JSeparator import javax.swing.JTextField class SettingsLLMComponent { private val settingsState: SettingsApplicationState get() = SettingsApplicationService.getInstance().state!! var panel: JPanel? = null // LLM Token private var llmUserTokenField = JTextField(30) // Models private var modelSelector = ComboBox(arrayOf("")) private var platformSelector = ComboBox(arrayOf(settingsState.openAIName)) // Default LLM Requests private var defaultLLMRequestsSeparator = JXTitledSeparator(TestSparkLabelsBundle.defaultValue("defaultLLMRequestsSeparator")) private var commonDefaultLLMRequestsPanel = JPanel() private val defaultLLMRequestPanels = mutableListOf<JPanel>() private val addDefaultLLMRequestsButtonPanel = JPanel(FlowLayout(FlowLayout.LEFT)) // Prompt Editor private var promptSeparator = JXTitledSeparator(TestSparkLabelsBundle.defaultValue("PromptSeparator")) private var promptEditorTabbedPane = createTabbedPane() // Maximum number of LLM requests private var maxLLMRequestsField = JBIntSpinner(UINumericRange(settingsState.maxLLMRequest, 1, 20)) // The depth of input parameters used in class under tests private var maxInputParamsDepthField = JBIntSpinner(UINumericRange(settingsState.maxInputParamsDepth, 1, 5)) // Maximum polymorphism depth private var maxPolyDepthField = JBIntSpinner(UINumericRange(settingsState.maxPolyDepth, 1, 5)) private val provideTestSamplesCheckBox: JCheckBox = JCheckBox(TestSparkLabelsBundle.defaultValue("provideTestSamplesCheckBox"), true) private val llmSetupCheckBox: JCheckBox = JCheckBox(TestSparkLabelsBundle.defaultValue("llmSetupCheckBox"), true) val llmPlatforms: List<LLMPlatform> = getLLLMPlatforms() var currentLLMPlatformName: String get() = platformSelector.item set(newAlg) { platformSelector.item = newAlg } var maxLLMRequest: Int get() = maxLLMRequestsField.number set(value) { maxLLMRequestsField.number = value } var maxInputParamsDepth: Int get() = maxInputParamsDepthField.number set(value) { maxInputParamsDepthField.number = value } var maxPolyDepth: Int get() = maxPolyDepthField.number set(value) { maxPolyDepthField.number = value } var classPrompt: String get() = getEditorTextField(PromptEditorType.CLASS).document.text set(value) { ApplicationManager.getApplication().runWriteAction { val editorTextField = getEditorTextField(PromptEditorType.CLASS) editorTextField.document.setText(value) } } var methodPrompt: String get() = getEditorTextField(PromptEditorType.METHOD).document.text set(value) { ApplicationManager.getApplication().runWriteAction { val editorTextField = getEditorTextField(PromptEditorType.METHOD) editorTextField.document.setText(value) } } var linePrompt: String get() = getEditorTextField(PromptEditorType.LINE).document.text set(value) { ApplicationManager.getApplication().runWriteAction { val editorTextField = getEditorTextField(PromptEditorType.LINE) editorTextField.document.setText(value) } } var defaultLLMRequests: String get() = Json.encodeToString( ListSerializer(String.serializer()), defaultLLMRequestPanels.filter { (it.getComponent(0) as JTextField).text.isNotBlank() }.map { (it.getComponent(0) as JTextField).text }, ) set(value) { fillDefaultLLMRequestsPanel(Json.decodeFromString(ListSerializer(String.serializer()), value)) } var llmSetupCheckBoxSelected: Boolean get() = llmSetupCheckBox.isSelected set(newStatus) { llmSetupCheckBox.isSelected = newStatus } var provideTestSamplesCheckBoxSelected: Boolean get() = provideTestSamplesCheckBox.isSelected set(newStatus) { provideTestSamplesCheckBox.isSelected = newStatus } init { // Adds additional style (width, tooltips) stylizeMainComponents(platformSelector, modelSelector, llmUserTokenField, llmPlatforms, settingsState) stylizePanel() fillDefaultLLMRequestsPanel(Json.decodeFromString(ListSerializer(String.serializer()), settingsState.defaultLLMRequests)) fillAddDefaultLLMRequestsButtonPanel() // Adds the panel components createSettingsPanel() // Adds listeners addListeners() } fun updateHighlighting(prompt: String, editorType: PromptEditorType) { val editorTextField = getEditorTextField(editorType) service<PromptParserService>().highlighter(editorTextField, prompt) if (!service<PromptParserService>().isPromptValid(prompt)) { val border = BorderFactory.createLineBorder(JBColor.RED) editorTextField.border = border } else { editorTextField.border = null } } private fun createTabbedPane(): JBTabbedPane { val tabbedPane = JBTabbedPane() // Add tabs for each testing level addPromptEditorTab(tabbedPane, PromptEditorType.CLASS) addPromptEditorTab(tabbedPane, PromptEditorType.METHOD) addPromptEditorTab(tabbedPane, PromptEditorType.LINE) return tabbedPane } private fun addPromptEditorTab(tabbedPane: JBTabbedPane, promptEditorType: PromptEditorType) { // initiate the panel val panel = JPanel() panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS) // Add editor text field (the prompt editor) to the panel val editorTextField = EditorTextField() editorTextField.setOneLineMode(false) panel.add(editorTextField) panel.add(JSeparator()) // add buttons for inserting keywords to the prompt editor addPromptButtons(panel) // add the panel as a new tab tabbedPane.addTab(promptEditorType.text, panel) } private fun addPromptButtons(panel: JPanel) { val keywords = service<PromptParserService>().getKeywords() val editorTextField = panel.getComponent(0) as EditorTextField keywords.forEach { val btnPanel = JPanel(FlowLayout(FlowLayout.LEFT)) val button = JButton("\$${it.text}") button.setForeground(JBColor.ORANGE) button.font = Font("Monochrome", Font.BOLD, 12) // add actionListener for button button.addActionListener { _ -> val editor = editorTextField.editor editor?.let { e -> val offset = e.caretModel.offset val document = editorTextField.document WriteCommandAction.runWriteCommandAction(e.project) { document.insertString(offset, "\$${it.text}") } } } // add button and it's description to buttons panel btnPanel.add(button) btnPanel.add(JBLabel("${it.description} - ${if (it.mandatory) "mandatory" else "optional"}")) panel.add(btnPanel) } } /** * Fills the addDefaultLLMRequestsButtonPanel with a button for adding default LLM requests. */ private fun fillAddDefaultLLMRequestsButtonPanel() { val addDefaultLLMRequestsButton = JButton(TestSparkLabelsBundle.defaultValue("addRequest"), TestSparkIcons.add) addDefaultLLMRequestsButton.isOpaque = false addDefaultLLMRequestsButton.isContentAreaFilled = false addDefaultLLMRequestsButton.addActionListener { addDefaultLLMRequestToPanel("") addDefaultLLMRequestsButtonPanel.revalidate() } addDefaultLLMRequestsButtonPanel.add(addDefaultLLMRequestsButton) } /** * Clears the default LLM request panels and fills the commonDefaultLLMRequestsPanel with the given list of default LLM requests. * * @param defaultLLMRequestsList The list of default LLM requests to fill the panel with. */ private fun fillDefaultLLMRequestsPanel(defaultLLMRequestsList: List<String>) { defaultLLMRequestPanels.clear() commonDefaultLLMRequestsPanel.removeAll() commonDefaultLLMRequestsPanel.layout = BoxLayout(commonDefaultLLMRequestsPanel, BoxLayout.Y_AXIS) for (defaultLLMRequest in defaultLLMRequestsList) { addDefaultLLMRequestToPanel(defaultLLMRequest) } commonDefaultLLMRequestsPanel.revalidate() } /** * Adds a default LLM request to the panel. * * @param defaultLLMRequest the default LLM request to be added */ private fun addDefaultLLMRequestToPanel(defaultLLMRequest: String) { val defaultLLMRequestPanel = JPanel(FlowLayout(FlowLayout.LEFT)) val textField = JTextField(defaultLLMRequest) textField.columns = 30 defaultLLMRequestPanel.add(textField) val removeButton = createButton(TestSparkIcons.remove, TestSparkLabelsBundle.defaultValue("removeRequest")) defaultLLMRequestPanel.add(removeButton) commonDefaultLLMRequestsPanel.add(defaultLLMRequestPanel) defaultLLMRequestPanels.add(defaultLLMRequestPanel) removeButton.addActionListener { textField.text = "" commonDefaultLLMRequestsPanel.remove(defaultLLMRequestPanel) commonDefaultLLMRequestsPanel.revalidate() } } /** * Adds listeners to the document of the user token field. * These listeners will update the model selector based on the text entered the user token field. */ private fun addListeners() { addLLMPanelListeners( platformSelector, modelSelector, llmUserTokenField, llmPlatforms, settingsState, ) addHighlighterListeners() } private fun addHighlighterListeners() { PromptEditorType.values().forEach { getEditorTextField(it).document.addDocumentListener( object : com.intellij.openapi.editor.event.DocumentListener { override fun documentChanged(event: com.intellij.openapi.editor.event.DocumentEvent) { updateHighlighting(event.document.text, it) } }, ) } } private fun stylizePanel() { maxLLMRequestsField.toolTipText = TestSparkToolTipsBundle.defaultValue("maximumNumberOfRequests") maxInputParamsDepthField.toolTipText = TestSparkToolTipsBundle.defaultValue("parametersDepth") maxPolyDepthField.toolTipText = TestSparkToolTipsBundle.defaultValue("maximumPolyDepth") promptSeparator.toolTipText = TestSparkToolTipsBundle.defaultValue("promptEditor") provideTestSamplesCheckBox.toolTipText = TestSparkToolTipsBundle.defaultValue("provideTestSamples") } /** * Create the main panel for LLM-related settings page */ private fun createSettingsPanel() { panel = FormBuilder.createFormBuilder() .addComponent(JXTitledSeparator(TestSparkLabelsBundle.defaultValue("LLMSettings"))) .addLabeledComponent( JBLabel(TestSparkLabelsBundle.defaultValue("llmPlatform")), platformSelector, 10, false, ) .addLabeledComponent( JBLabel(TestSparkLabelsBundle.defaultValue("llmToken")), llmUserTokenField, 10, false, ) .addLabeledComponent( JBLabel(TestSparkLabelsBundle.defaultValue("model")), modelSelector, 10, false, ) .addLabeledComponent( JBLabel(TestSparkLabelsBundle.defaultValue("parametersDepth")), maxInputParamsDepthField, 10, false, ) .addLabeledComponent( JBLabel(TestSparkLabelsBundle.defaultValue("maximumPolyDepth")), maxPolyDepthField, 10, false, ) .addLabeledComponent( JBLabel(TestSparkLabelsBundle.defaultValue("maximumNumberOfRequests")), maxLLMRequestsField, 10, false, ) .addComponent(llmSetupCheckBox, 10) .addComponent(provideTestSamplesCheckBox, 10) .addComponent(defaultLLMRequestsSeparator, 15) .addComponent(commonDefaultLLMRequestsPanel, 15) .addComponent(addDefaultLLMRequestsButtonPanel, 15) .addComponent(promptSeparator, 15) .addComponent(promptEditorTabbedPane, 15) .addComponentFillVertically(JPanel(), 0) .panel } private fun getEditorTextField(editorType: PromptEditorType): EditorTextField { return (promptEditorTabbedPane.getComponentAt(editorType.index) as JPanel).getComponent(0) as EditorTextField } fun updateTokenAndModel() { for (llmPlatform in llmPlatforms) { if (currentLLMPlatformName == llmPlatform.name) { llmUserTokenField.text = llmPlatform.token if (modelSelector.isEnabled) modelSelector.selectedItem = llmPlatform.model } } } }
9
Kotlin
3
17
3252e1f2eab05308390b1bfd809c81e3268e7e96
15,396
TestSpark
MIT License
app/src/main/java/radiant/nimbus/session/BlueskySession.kt
Radiant-Industries
677,522,730
false
{"Kotlin": 793750}
package radiant.nimbus.session import radiant.nimbus.api.Did; data class BlueskySession( val did: Did )
20
Kotlin
0
1
b2a6a419744b89c0184f44aacd74ee7a88afc23d
110
morpho-app
Apache License 2.0
sykepenger-mediators/src/main/kotlin/no/nav/helse/spleis/HendelseMediator.kt
androa
257,856,741
true
{"Kotlin": 1134624, "Dockerfile": 349}
package no.nav.helse.spleis import no.nav.helse.hendelser.* import no.nav.helse.person.ArbeidstakerHendelse import no.nav.helse.person.Person import no.nav.helse.person.PersonObserver import no.nav.helse.person.toMap import no.nav.helse.rapids_rivers.JsonMessage import no.nav.helse.rapids_rivers.RapidsConnection import no.nav.helse.spleis.db.LagrePersonDao import no.nav.helse.spleis.db.PersonRepository import no.nav.helse.spleis.meldinger.model.* import org.slf4j.LoggerFactory import java.time.LocalDateTime import java.util.* // Understands how to communicate messages to other objects // Acts like a GoF Mediator to forward messages to observers // Uses GoF Observer pattern to notify events internal class HendelseMediator( rapidsConnection: RapidsConnection, private val personRepository: PersonRepository, private val lagrePersonDao: LagrePersonDao ) : IHendelseMediator { private val log = LoggerFactory.getLogger(HendelseMediator::class.java) private val sikkerLogg = LoggerFactory.getLogger("tjenestekall") private val personMediator = PersonMediator(rapidsConnection) private val behovMediator = BehovMediator(rapidsConnection, sikkerLogg) override fun behandle(message: NySøknadMessage, sykmelding: Sykmelding) { håndter(message, sykmelding) { person -> HendelseProbe.onSykmelding() person.håndter(sykmelding) } } override fun behandle(message: SendtSøknadArbeidsgiverMessage, søknad: SøknadArbeidsgiver) { håndter(message, søknad) { person -> HendelseProbe.onSøknadArbeidsgiver() person.håndter(søknad) } } override fun behandle(message: SendtSøknadNavMessage, søknad: Søknad) { håndter(message, søknad) { person -> HendelseProbe.onSøknadNav() person.håndter(søknad) } } override fun behandle(message: InntektsmeldingMessage, inntektsmelding: Inntektsmelding) { håndter(message, inntektsmelding) { person -> HendelseProbe.onInntektsmelding() person.håndter(inntektsmelding) } } override fun behandle(message: YtelserMessage, ytelser: Ytelser) { håndter(message, ytelser) { person -> HendelseProbe.onYtelser() person.håndter(ytelser) } } override fun behandle(message: VilkårsgrunnlagMessage, vilkårsgrunnlag: Vilkårsgrunnlag) { håndter(message, vilkårsgrunnlag) { person -> HendelseProbe.onVilkårsgrunnlag() person.håndter(vilkårsgrunnlag) } } override fun behandle(message: SimuleringMessage, simulering: Simulering) { håndter(message, simulering) { person -> HendelseProbe.onSimulering() person.håndter(simulering) } } override fun behandle(message: ManuellSaksbehandlingMessage, manuellSaksbehandling: ManuellSaksbehandling) { håndter(message, manuellSaksbehandling) { person -> HendelseProbe.onManuellSaksbehandling() person.håndter(manuellSaksbehandling) } } override fun behandle(message: UtbetalingOverførtMessage, utbetaling: UtbetalingOverført) { håndter(message, utbetaling) { person -> person.håndter(utbetaling) } } override fun behandle(message: UtbetalingMessage, utbetaling: UtbetalingHendelse) { håndter(message, utbetaling) { person -> HendelseProbe.onUtbetaling() person.håndter(utbetaling) } } override fun behandle(message: PåminnelseMessage, påminnelse: Påminnelse) { håndter(message, påminnelse) { person -> HendelseProbe.onPåminnelse(påminnelse) person.håndter(påminnelse) } } override fun behandle(message: KansellerUtbetalingMessage, kansellerUtbetaling: KansellerUtbetaling) { håndter(message, kansellerUtbetaling) { person -> HendelseProbe.onKansellerUtbetaling() person.håndter(kansellerUtbetaling) } } private fun <Hendelse: ArbeidstakerHendelse> håndter(message: HendelseMessage, hendelse: Hendelse, handler: (Person) -> Unit) { person(message, hendelse).also { handler(it) finalize(it, message, hendelse) } } private fun person(message: HendelseMessage, hendelse: ArbeidstakerHendelse): Person { return (personRepository.hentPerson(hendelse.fødselsnummer()) ?: Person( aktørId = hendelse.aktørId(), fødselsnummer = hendelse.fødselsnummer() )).also { personMediator.observer(it, message, hendelse) it.addObserver(VedtaksperiodeProbe) } } private fun finalize(person: Person, message: HendelseMessage, hendelse: ArbeidstakerHendelse) { lagrePersonDao.lagrePerson(message, person, hendelse) if (!hendelse.hasMessages()) return if (hendelse.hasErrors()) sikkerLogg.info("aktivitetslogg inneholder errors:\n${hendelse.toLogString()}") else sikkerLogg.info("aktivitetslogg inneholder meldinger:\n${hendelse.toLogString()}") behovMediator.håndter(message, hendelse) } private class PersonMediator(private val rapidsConnection: RapidsConnection) { private val sikkerLogg = LoggerFactory.getLogger("tjenestekall") fun observer(person: Person, message: HendelseMessage, hendelse: ArbeidstakerHendelse) { person.addObserver(Observatør(message, hendelse)) } private fun publish(fødselsnummer: String, message: String) { rapidsConnection.publish(fødselsnummer, message.also { sikkerLogg.info("sender $it") }) } private inner class Observatør( private val message: HendelseMessage, private val hendelse: ArbeidstakerHendelse ): PersonObserver { override fun vedtaksperiodePåminnet(påminnelse: Påminnelse) { publish("vedtaksperiode_påminnet", JsonMessage.newMessage(mapOf( "vedtaksperiodeId" to påminnelse.vedtaksperiodeId, "tilstand" to påminnelse.tilstand(), "antallGangerPåminnet" to påminnelse.antallGangerPåminnet(), "tilstandsendringstidspunkt" to påminnelse.tilstandsendringstidspunkt(), "påminnelsestidspunkt" to påminnelse.påminnelsestidspunkt(), "nestePåminnelsestidspunkt" to påminnelse.nestePåminnelsestidspunkt() ))) } override fun vedtaksperiodeEndret(event: PersonObserver.VedtaksperiodeEndretTilstandEvent) { publish("vedtaksperiode_endret", JsonMessage.newMessage(mapOf( "vedtaksperiodeId" to event.vedtaksperiodeId, "gjeldendeTilstand" to event.gjeldendeTilstand, "forrigeTilstand" to event.forrigeTilstand, "aktivitetslogg" to event.aktivitetslogg.toMap(), "timeout" to event.timeout.toSeconds(), "hendelser" to event.hendelser ))) } override fun vedtaksperiodeUtbetalt(event: PersonObserver.UtbetaltEvent) { publish("utbetalt", JsonMessage.newMessage(mapOf( "førsteFraværsdag" to event.førsteFraværsdag, "vedtaksperiodeId" to event.vedtaksperiodeId.toString(), "utbetalingslinjer" to event.utbetalingslinjer.map { mapOf( "fom" to it.fom, "tom" to it.tom, "dagsats" to it.dagsats, "grad" to it.grad ) }, "forbrukteSykedager" to event.forbrukteSykedager, "opprettet" to event.opprettet ))) } override fun vedtaksperiodeIkkeFunnet(vedtaksperiodeEvent: PersonObserver.VedtaksperiodeIkkeFunnetEvent) { publish("vedtaksperiode_ikke_funnet", JsonMessage.newMessage(mapOf( "vedtaksperiodeId" to vedtaksperiodeEvent.vedtaksperiodeId ))) } override fun manglerInntektsmelding(event: PersonObserver.ManglendeInntektsmeldingEvent) { publish("trenger_inntektsmelding", JsonMessage.newMessage(mapOf( "vedtaksperiodeId" to event.vedtaksperiodeId, "fom" to event.fom, "tom" to event.tom ))) } private fun leggPåStandardfelter(event: String, outgoingMessage: JsonMessage) = outgoingMessage.apply { this["@event_name"] = event this["@id"] = UUID.randomUUID() this["@opprettet"] = LocalDateTime.now() this["@forårsaket_av"] = mapOf( "event_name" to message.navn, "id" to message.id, "opprettet" to message.opprettet ) this["aktørId"] = hendelse.aktørId() this["fødselsnummer"] = hendelse.fødselsnummer() this["organisasjonsnummer"] = hendelse.organisasjonsnummer() } private fun publish(event: String, outgoingMessage: JsonMessage) { publish(hendelse.fødselsnummer(), leggPåStandardfelter(event, outgoingMessage).toJson()) } } } } internal interface IHendelseMediator { fun behandle(message: NySøknadMessage, sykmelding: Sykmelding) fun behandle(message: SendtSøknadArbeidsgiverMessage, søknad: SøknadArbeidsgiver) fun behandle(message: SendtSøknadNavMessage, søknad: Søknad) fun behandle(message: InntektsmeldingMessage, inntektsmelding: Inntektsmelding) fun behandle(message: PåminnelseMessage, påminnelse: Påminnelse) fun behandle(message: YtelserMessage, ytelser: Ytelser) fun behandle(message: VilkårsgrunnlagMessage, vilkårsgrunnlag: Vilkårsgrunnlag) fun behandle(message: ManuellSaksbehandlingMessage, manuellSaksbehandling: ManuellSaksbehandling) fun behandle(message: UtbetalingOverførtMessage, utbetaling: UtbetalingOverført) fun behandle(message: UtbetalingMessage, utbetaling: UtbetalingHendelse) fun behandle(message: SimuleringMessage, simulering: Simulering) fun behandle(message: KansellerUtbetalingMessage, kansellerUtbetaling: KansellerUtbetaling) }
0
null
0
0
115ff38bac9f15ef49edd46e37cab4c67b925127
10,501
helse-spleis
MIT License
examples/welcome/login/src/main/java/com/motorro/statemachine/login/model/state/LoginStateFactory.kt
motorro
512,762,123
false
{"Kotlin": 102349}
/* * 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.motorro.statemachine.login.model.state import com.motorro.commonstatemachine.CommonMachineState import com.motorro.statemachine.commonapi.welcome.model.state.FlowStarter import com.motorro.statemachine.commonapi.welcome.model.state.WelcomeFeatureHost import com.motorro.statemachine.login.data.LoginDataState import com.motorro.statemachine.login.data.LoginGesture import com.motorro.statemachine.login.data.LoginUiState import com.motorro.statemachine.login.di.LoginScope import com.motorro.statemachine.login.model.LoginRenderer import timber.log.Timber import javax.inject.Inject /** * Login flow state factory */ internal interface LoginStateFactory : FlowStarter<LoginGesture, LoginUiState> { /** * Creates a starting state * @param email Common data state */ override fun start(email: String): CommonMachineState<LoginGesture, LoginUiState> = passwordEntry(LoginDataState(email)) /** * Enter existing user password * @param data Login data state */ fun passwordEntry(data: LoginDataState): LoginState /** * Checks email/password * @param data Data state */ fun checking(data: LoginDataState): LoginState /** * Password error screen */ fun error(data: LoginDataState, error: Throwable): LoginState /** * [LoginStateFactory] implementation */ @LoginScope class Impl @Inject constructor( host: WelcomeFeatureHost, renderer: LoginRenderer, private val createCredentialsCheck: CredentialsCheckState.Factory ) : LoginStateFactory { private val context: LoginContext = object : LoginContext { override val factory: LoginStateFactory = this@Impl override val host: WelcomeFeatureHost = host override val renderer: LoginRenderer = renderer } /** * Enter existing user password * @param data Common data state */ override fun passwordEntry(data: LoginDataState): LoginState { Timber.d("Creating 'Password entry'...") return PasswordEntryState(context, data) } /** * Checks email/password * @param data Data state */ override fun checking(data: LoginDataState): LoginState { Timber.d("Creating 'Credentials check'...") return createCredentialsCheck(context, data) } /** * Password error screen */ override fun error(data: LoginDataState, error: Throwable): LoginState { Timber.d("Creating 'Error'...") return ErrorState(context, data, error) } } }
1
Kotlin
5
42
5f6cbf2d867f027ce852fe90d38cc077d22308f7
3,257
CommonStateMachine
Apache License 2.0
app/src/main/java/com/example/bookworms/fragments/HomePageFragment.kt
JosephOri
804,031,334
false
{"Kotlin": 57005}
package com.example.bookworms.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.bookworms.models.entities.BookEntity import com.example.bookworms.R import com.example.bookworms.adapters.BookPostAdapter /** * A simple `Fragment` subclass. * Use the `HomePageFragment.newInstance` factory method to * create an instance of this fragment. */ class HomePageFragment : Fragment() { // TODO: firebase DB, storage reference, // initialize parameters of firestore instance private lateinit var recyclerView: RecyclerView private lateinit var bookList: ArrayList<BookEntity> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home_page, container, false) initializeParameters(view) return view } private fun initializeParameters(view : View) { bookList = arrayListOf( BookEntity("1", "The Alchemist", "Paulo Coelho", "https://images-na.ssl-images-amazon.com/images/I/71aFt4+OTOL.jpg", "Fiction", "4.5", "An allegorical novel, The Alchemist follows a young Andalusian shepherd in his journey to the pyramids of Egypt, after having a recurring dream of finding a treasure there."), ) recyclerView = view.findViewById(R.id.homePageBooksList) recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.setHasFixedSize(true) recyclerView.adapter = BookPostAdapter(bookList) } /* private fun fetchBooksFromDb(onSuccess: () -> Unit) { }*/ }
0
Kotlin
0
0
07bbdb145312800adf0be373c4580af600ef0de3
1,963
BookWorms
MIT License
mbcarkit/src/main/java/com/daimler/mbcarkit/socket/observable/VehicleObservableMessage.kt
Daimler
199,815,262
false
null
package com.daimler.mbcarkit.socket.observable import com.daimler.mbcarkit.business.model.vehicle.VehicleStatus import com.daimler.mbnetworkkit.socket.message.ObservableMessage abstract class VehicleObservableMessage<T>( data: T ) : ObservableMessage<T>(data) { internal abstract fun hasChanged(oldVehicleStatus: VehicleStatus?, updatedVehicleStatus: VehicleStatus): Boolean }
1
Kotlin
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
388
MBSDK-Mobile-Android
MIT License
rastersclient/src/main/java/com/nsimtech/rastersclient/data/Specificity.kt
nsimtechnologie
183,460,220
false
null
/** * Rasters API * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v2 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.nsimtech.rastersclient.data import kotlinx.serialization.Serializable /** * * @param name * @param value */ @Serializable data class HeaderType ( val name: kotlin.String? = null, val value: kotlin.String? = null ) { }
0
Kotlin
0
0
61b2c800871320034ebd1be7bed04c28cb43a5aa
572
android.rasters.client
MIT License
app/src/main/java/com/example/inventory/data/ItemsRepository.kt
josemanuelsanchezdelpalacio
759,797,695
false
{"Kotlin": 60020}
/* * Copyright (C) 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.example.inventory.data import kotlinx.coroutines.flow.Flow interface ItemsRepository { /**recupera todos los items de la base de datos*/ fun getAllItemsStream(): Flow<List<Item>> /**recupera un item de la base de datos a partir del ID.*/ fun getItemStream(id: Int): Flow<Item?> /**inserta un item en la base de datos*/ suspend fun insertItem(item: Item) /**elimina un item de la base de datos*/ suspend fun deleteItem(item: Item) /**actualiza un item de la base de datos*/ suspend fun updateItem(item: Item) }
0
Kotlin
0
0
603d7636c9211bff8dc6980fb2b946fa0dde9a44
1,189
InventoryRoom
Apache License 2.0
core/domain/src/main/kotlin/scene/events/SymbolPinnedToScene.kt
Soyle-Productions
239,407,827
false
null
package com.soyle.stories.domain.scene.events import com.soyle.stories.domain.scene.Scene data class SymbolPinnedToScene(override val sceneId: Scene.Id, val trackedSymbol: Scene.TrackedSymbol) : SceneEvent()
45
Kotlin
0
9
1a110536865250dcd8d29270d003315062f2b032
209
soyle-stories
Apache License 2.0
corgicore/src/main/java/com/shenjun/corgicore/tools/GestureHelper.kt
shenjunjkl
158,243,143
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 4, "XML": 20, "Kotlin": 69}
package com.shenjun.corgicore.tools import android.content.Context import android.view.GestureDetector import android.view.MotionEvent import kotlin.math.abs /** * Created by shenjun on 2020-02-13. */ class GestureHelper(ctx: Context, private val callback: GestureEventCallback) { private companion object { const val SCROLL_IDLE = 0 const val SCROLL_HORIZONTAL = 1 const val SCROLL_VERTICAL = 2 } private val mWrapper = VideoGestureWrapper() private val mGestureDetector: GestureDetector = GestureDetector(ctx, mWrapper) var verticalScrollEnabled = true var horizontalScrollEnabled = true var doubleTapEnabled = true var singleTapEnabled = true fun handleTouchEvent(ev: MotionEvent) { mGestureDetector.onTouchEvent(ev) mWrapper.handleUpEvent(ev) } interface GestureEventCallback { fun onSingleTap() fun onDoubleTap() fun onHorizontalScroll(ev: MotionEvent, delta: Float) fun onVerticalScroll(ev: MotionEvent, delta: Float) fun onScrollFinish(isVertical: Boolean) } private inner class VideoGestureWrapper : GestureDetector.SimpleOnGestureListener() { private var lastScrollAction = SCROLL_IDLE override fun onSingleTapConfirmed(e: MotionEvent?): Boolean { if (singleTapEnabled) { callback.onSingleTap() } return false } override fun onDoubleTap(e: MotionEvent?): Boolean { if (doubleTapEnabled) { callback.onDoubleTap() } return false } override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean { e1 ?: return false e2 ?: return false val deltaX = e2.x - e1.x val deltaY = e2.y - e1.y when (lastScrollAction) { SCROLL_HORIZONTAL -> callback.onHorizontalScroll(e2, deltaY) SCROLL_VERTICAL -> callback.onVerticalScroll(e2, deltaX) SCROLL_IDLE -> if (abs(deltaX) > abs(deltaY)) { if (verticalScrollEnabled) { lastScrollAction = SCROLL_VERTICAL callback.onVerticalScroll(e2, deltaX) } } else { if (horizontalScrollEnabled) { lastScrollAction = SCROLL_HORIZONTAL callback.onHorizontalScroll(e2, deltaY) } } } return false } fun handleUpEvent(ev: MotionEvent) { if (verticalScrollEnabled || horizontalScrollEnabled) { when (ev.action) { MotionEvent.ACTION_UP, MotionEvent.ACTION_OUTSIDE -> { if (lastScrollAction != SCROLL_IDLE) { callback.onScrollFinish(lastScrollAction == SCROLL_VERTICAL) lastScrollAction = SCROLL_IDLE } } } } } } }
1
null
1
1
b9c9ef274010d9a9c06dd0cb0647f9f2795049fe
3,144
CorgiVideoPlayer
MIT License
lib1/src/main/java/xe11/samples/android/lib1/Lib1Calculator.kt
xe11
641,114,110
false
null
package xe11.samples.android.lib1 class Lib1Calculator { fun sum(a: Int, b: Int): Int = a + b }
0
Kotlin
0
0
96c5db2027a405de0021d3c9520eb244e8d8cd77
102
sample-android-artifact-publishing-lib1
Apache License 2.0
app/src/main/java/org/stepik/android/exams/core/presenter/AuthPresenter.kt
StepicOrg
139,451,308
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Proguard": 2, "XML": 107, "Kotlin": 265, "Prolog": 1, "Java": 29, "CSS": 1}
package org.stepik.android.exams.core.presenter import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import org.stepik.android.exams.api.Api import org.stepik.android.exams.api.auth.AuthError import org.stepik.android.exams.api.auth.AuthRepository import org.stepik.android.exams.api.profile.ProfileRepository import org.stepik.android.exams.core.presenter.contracts.AuthView import org.stepik.android.exams.data.model.AccountCredentials import org.stepik.android.exams.data.preference.ProfilePreferences import org.stepik.android.exams.di.qualifiers.BackgroundScheduler import org.stepik.android.exams.di.qualifiers.MainScheduler import org.stepik.android.exams.util.RxOptional import org.stepik.android.exams.util.then import retrofit2.HttpException import javax.inject.Inject class AuthPresenter @Inject constructor( private val api: Api, private val authRepository: AuthRepository, private val profileRepository: ProfileRepository, private val profilePreferences: ProfilePreferences, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<AuthView>() { private val disposable = CompositeDisposable() private var isSuccess = false fun authFakeUser() { view?.onLoading() disposable.add(createFakeUserRx() .andThen(onLoginRx()) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribe( this::onSuccess ) { onError(AuthError.ConnectionProblem) }) } fun authWithLoginPassword(login: String, password: String) { view?.onLoading() disposable.add(loginRx(login, password) .andThen(onLoginRx()) .doOnComplete { profilePreferences.removeFakeUser() // we auth as normal user and can remove fake credentials } .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribe(this::onSuccess, this::handleLoginError)) } private fun handleLoginError(error: Throwable) { val authError = if (error is HttpException) { if (error.code() == 429) { AuthError.TooManyAttempts } else { AuthError.EmailPasswordInvalid } } else { AuthError.ConnectionProblem } onError(authError) } private fun createAccountRx(credentials: AccountCredentials): Completable = authRepository.createAccount(credentials.toRegistrationUser()) private fun loginRx(login: String, password: String): Completable = authRepository.authWithLoginPassword(login, password).toCompletable() private fun createFakeUserRx(): Completable = Single.fromCallable { RxOptional(profilePreferences.fakeUser) }.flatMapCompletable { optional -> val credentials = optional.value ?: api.createFakeAccount() if (optional.value == null) { profilePreferences.fakeUser = credentials createAccountRx(credentials) then loginRx(credentials.login, credentials.password) } else { loginRx(credentials.login, credentials.password).onErrorResumeNext { error -> if (error is HttpException && error.code() == 401) { // on some reason we cannot authorize user with old fake account credential profilePreferences.fakeUser = null // remove old fake user createFakeUserRx() // retry } else { Completable.error(error) } } } } private fun onLoginRx() = profileRepository.fetchProfileWithEmailAddresses() .doOnSuccess { profilePreferences.profile = it } .flatMapCompletable { it.subscribedForMail = false profileRepository.updateProfile(it) } private fun onError(authError: AuthError) { view?.onError(authError) } private fun onSuccess() { isSuccess = true view?.onSuccess() } override fun attachView(view: AuthView) { super.attachView(view) if (isSuccess) view.onSuccess() } override fun destroy() { disposable.dispose() } }
1
null
1
1
f2ed2cff758f5531f84e39ab939a8f7ee4146a41
4,748
stepik-android-exams
Apache License 2.0