path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/test/kotlin/com/uploader/DatabaseTool.kt
JanGorelova
354,213,739
false
null
package com.uploader import com.fasterxml.jackson.databind.ObjectMapper import com.uploader.TestingConstants.AWAIT_AT_MOST_SECONDS import com.uploader.TestingConstants.PYCHARM_2_CHANNEL import com.uploader.TestingConstants.PYCHARM_2_EXPECTED_INFO_JSON import com.uploader.TestingConstants.PYCHARM_2_FULL_NUMBER import com.uploader.TestingConstants.PYCHARM_2_VERSION import com.uploader.TestingConstants.PYCHARM_CHANNEL import com.uploader.TestingConstants.PYCHARM_FULL_NUMBER import com.uploader.TestingConstants.PYCHARM_VERSION import com.uploader.TestingConstants.WEBSTORM_CHANNEL import com.uploader.TestingConstants.WEBSTORM_EXPECTED_INFO_JSON import com.uploader.TestingConstants.WEBSTORM_FULL_NUMBER import com.uploader.TestingConstants.WEBSTORM_VERSION import com.uploader.TestingConstants.pycharm2Path import com.uploader.TestingConstants.pycharmPath import com.uploader.TestingConstants.webstormPath import com.uploader.TestingTool.downloadFromResource import com.uploader.dao.dto.BuildDto import com.uploader.dao.dto.BuildDto.State.DOWNLOADED import com.uploader.dao.entity.Build import com.uploader.dao.entity.BuildInfo import com.uploader.dao.repository.BuildInfoRepository import com.uploader.dao.repository.BuildRepository import com.uploader.db.DatabaseProvider import com.uploader.lifecycle.Constants.PYCHARM import com.uploader.lifecycle.Constants.WEBSTORM import java.util.concurrent.TimeUnit.SECONDS import kotlinx.coroutines.runBlocking import net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals import org.awaitility.Awaitility.await import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers import org.jetbrains.exposed.sql.selectAll import org.koin.core.component.KoinApiExtension import org.koin.core.component.inject import org.koin.test.KoinTest @KoinApiExtension object DatabaseTool : KoinTest { private val provider by inject<DatabaseProvider>() private val buildRepository by inject<BuildRepository>() private val buildInfoRepository by inject<BuildInfoRepository>() private val jsonMapper = ObjectMapper() fun getAllBuilds() = runBlocking { provider.dbQuery { Build.selectAll().toList() } } fun getAllBuildInfos() = runBlocking { provider.dbQuery { BuildInfo.selectAll().toList() } } fun doInitialSetup(): List<BuildDto> { await() .atMost(AWAIT_AT_MOST_SECONDS, SECONDS) .untilAsserted { val buildInfos = getAllBuildInfos() assertThat(buildInfos, Matchers.hasSize(3)) } val pyCharmBuild = runBlocking { buildRepository.getByFullNumberAndChannel(PYCHARM_FULL_NUMBER, PYCHARM_CHANNEL) } ?: error("Build with $PYCHARM_FULL_NUMBER and $PYCHARM_CHANNEL was not found") val pyCharmBuild2 = runBlocking { buildRepository.getByFullNumberAndChannel(PYCHARM_2_FULL_NUMBER, PYCHARM_2_CHANNEL) } ?: error("Build with $PYCHARM_2_FULL_NUMBER and $PYCHARM_2_CHANNEL was not found") val webstormBuild = runBlocking { buildRepository.getByFullNumberAndChannel(WEBSTORM_FULL_NUMBER, WEBSTORM_CHANNEL) } ?: error("Build with $WEBSTORM_FULL_NUMBER and $WEBSTORM_CHANNEL was not found") return listOf(pyCharmBuild, pyCharmBuild2, webstormBuild) } fun compareBuilds() { val pyCharmBuild = runBlocking { buildRepository.getByFullNumberAndChannel(PYCHARM_FULL_NUMBER, PYCHARM_CHANNEL) } val pyCharmBuild2 = runBlocking { buildRepository.getByFullNumberAndChannel( PYCHARM_2_FULL_NUMBER, PYCHARM_2_CHANNEL ) } val expectedPyCharmBuild = BuildDto( productName = PYCHARM, fullNumber = PYCHARM_FULL_NUMBER, channelId = PYCHARM_CHANNEL, version = PYCHARM_VERSION, state = DOWNLOADED, path = pycharmPath(), id = pyCharmBuild?.id, dateUpdated = pyCharmBuild?.dateUpdated, dateCreated = pyCharmBuild?.dateCreated ) val expectedPyCharmBuild2 = BuildDto( productName = PYCHARM, fullNumber = PYCHARM_2_FULL_NUMBER, channelId = PYCHARM_2_CHANNEL, version = PYCHARM_2_VERSION, state = DOWNLOADED, path = pycharm2Path(), id = pyCharmBuild2?.id, dateUpdated = pyCharmBuild2?.dateUpdated, dateCreated = pyCharmBuild2?.dateCreated ) val webStormBuild = runBlocking { buildRepository.getByFullNumberAndChannel(WEBSTORM_FULL_NUMBER, WEBSTORM_CHANNEL) } val expectedWebstormBuild = BuildDto( productName = WEBSTORM, fullNumber = WEBSTORM_FULL_NUMBER, channelId = WEBSTORM_CHANNEL, version = WEBSTORM_VERSION, state = DOWNLOADED, path = webstormPath(), id = webStormBuild?.id, dateUpdated = webStormBuild?.dateUpdated, dateCreated = webStormBuild?.dateCreated ) assertThat(pyCharmBuild, Matchers.equalTo(expectedPyCharmBuild)) assertThat(pyCharmBuild2, Matchers.equalTo(expectedPyCharmBuild2)) assertThat(webStormBuild, Matchers.equalTo(expectedWebstormBuild)) } fun compareBuildInfos() { comparePyCharmBuildInfos() val actualWebStormBuildInfo = runBlocking { buildInfoRepository.findAllByProductName(WEBSTORM).toList().first() } assertJsonEquals( actualWebStormBuildInfo.second, jsonMapper.readTree(downloadFromResource(WEBSTORM_EXPECTED_INFO_JSON)) ) } fun comparePyCharmBuildInfos() { val actualPyCharmBuildInfos = runBlocking { buildInfoRepository.findAllByProductName(PYCHARM).toList() } actualPyCharmBuildInfos.forEach { (fullNumber, info) -> val expected = when (fullNumber) { PYCHARM_FULL_NUMBER -> jsonMapper.readTree(downloadFromResource(TestingConstants.PYCHARM_EXPECTED_INFO_JSON)) else -> jsonMapper.readTree(downloadFromResource(PYCHARM_2_EXPECTED_INFO_JSON)) } assertJsonEquals(info, expected) } } }
0
Kotlin
0
0
64e940609b9c158a59bbf93c03ee23163c0d80cb
6,273
Build_Updater
Apache License 2.0
ktx/src/main/java/luyao/util/ktx/ext/StringExt.kt
xiangyutian
210,272,140
true
{"Kotlin": 144945, "Java": 3288}
package luyao.util.ktx.ext /** * Created by luyao * on 2019/7/23 9:25 */ fun <T> String?.notNull(f: () -> T, t: () -> T): T { return if (this != null) f() else t() }
0
null
0
0
91e21cb3178e32c629d7982b928c8e9f5b654186
174
AndroidUtilCodeKTX
Apache License 2.0
mosaic-runtime/src/commonTest/kotlin/com/jakewharton/mosaic/AnsiRenderingTest.kt
JakeWharton
292,637,686
false
{"Kotlin": 484366, "C++": 76018, "C": 22353, "Zig": 1779, "Shell": 1034}
package com.jakewharton.mosaic import assertk.assertThat import assertk.assertions.isEqualTo import com.jakewharton.mosaic.ui.Column import com.jakewharton.mosaic.ui.Row import com.jakewharton.mosaic.ui.Static import com.jakewharton.mosaic.ui.Text import kotlin.test.Test import kotlinx.coroutines.test.runTest class AnsiRenderingTest { private val rendering = AnsiRendering() @Test fun firstRender() { val rootNode = renderMosaicNode { Column { Text("Hello") Text("World!") } } // TODO We should not draw trailing whitespace. assertThat(rendering.render(rootNode).toString()).isEqualTo( """ |Hello$s |World! | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } @Test fun subsequentLongerRenderClearsRenderedLines() { val firstRootNode = renderMosaicNode { Column { Text("Hello") Text("World!") } } assertThat(rendering.render(firstRootNode).toString()).isEqualTo( """ |Hello$s |World! | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) val secondRootNode = renderMosaicNode { Column { Text("Hel") Text("lo") Text("Wor") Text("ld!") } } assertThat(rendering.render(secondRootNode).toString()).isEqualTo( """ |$cursorUp${cursorUp}Hel$clearLine |lo $clearLine |Wor |ld! | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } @Test fun subsequentShorterRenderClearsRenderedLines() { val firstRootNode = renderMosaicNode { Column { Text("Hel") Text("lo") Text("Wor") Text("ld!") } } assertThat(rendering.render(firstRootNode).toString()).isEqualTo( """ |Hel |lo$s |Wor |ld! | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) val secondRootNode = renderMosaicNode { Column { Text("Hello") Text("World!") } } assertThat(rendering.render(secondRootNode).toString()).isEqualTo( """ |$cursorUp$cursorUp$cursorUp${cursorUp}Hello $clearLine |World!$clearLine |$clearLine |$clearLine$cursorUp """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } @Test fun staticRendersFirst() { val rootNode = renderMosaicNode { Text("Hello") Static(snapshotStateListOf("World!")) { Text(it) } } assertThat(rendering.render(rootNode).toString()).isEqualTo( """ |World! |Hello | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } @Test fun staticLinesNotErased() = runTest { val firstRootNode = renderMosaicNode { Static(snapshotStateListOf("One")) { Text(it) } Text("Two") } assertThat(rendering.render(firstRootNode).toString()).isEqualTo( """ |One |Two | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) val secondRootNode = renderMosaicNode { Static(snapshotStateListOf("Three")) { Text(it) } Text("Four") } assertThat(rendering.render(secondRootNode).toString()).isEqualTo( """ |${cursorUp}Three$clearLine |Four | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } @Test fun staticOrderingIsDfs() { val rootNode = renderMosaicNode { Static(snapshotStateListOf("One")) { Text(it) } Column { Static(snapshotStateListOf("Two")) { Text(it) } Row { Static(snapshotStateListOf("Three")) { Text(it) } Text("Sup") } Static(snapshotStateListOf("Four")) { Text(it) } } Static(snapshotStateListOf("Five")) { Text(it) } } assertThat(rendering.render(rootNode).toString()).isEqualTo( """ |One |Two |Three |Four |Five |Sup | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } @Test fun staticInPositionedElement() { val firstRootNode = renderMosaicNode { Column { Text("TopTopTop") Row { Text("LeftLeft") Static(snapshotStateListOf("Static")) { Text(it) } } } } assertThat(rendering.render(firstRootNode).toString()).isEqualTo( """ |Static |TopTopTop |LeftLeft$s | """.trimMargin().wrapWithAnsiSynchronizedUpdate().replaceLineEndingsWithCRLF(), ) } }
27
Kotlin
57
1,912
3574b7b21bdee4f72c9f5b5eef0389cc8f9ddcfa
4,350
mosaic
Apache License 2.0
src/main/kotlin/kotlinFeedbackPlugin/ui/dialog/CancelDialogWindowTracker.kt
DmitryPogrebnoy
276,805,622
false
{"Kotlin": 119532}
package kotlinFeedbackPlugin.ui.dialog import com.intellij.openapi.components.service import com.intellij.openapi.ui.DialogWrapper import kotlinFeedbackPlugin.state.services.FeedbackDatesService import java.awt.event.ActionEvent import java.time.LocalDate import javax.swing.AbstractAction /** * Tracks the cancellation of the feedback dialog and stores the cancellation date in the storage. * * @see kotlinFeedbackPlugin.state.show.FeedbackDatesState */ class CancelDialogWindowTracker(private val dialogWrapper: DialogWrapper) : AbstractAction() { override fun actionPerformed(e: ActionEvent?) { val dateFeedbackState = service<FeedbackDatesService>().state ?: return dateFeedbackState.dateCloseFeedbackDialog = LocalDate.now() dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } }
0
Kotlin
1
0
4228ec23417c6cbb1844cd530883433443747655
821
Kotlin-feedback-plugin
Apache License 2.0
feature/webview-api/src/main/kotlin/org/bmsk/lifemash/feature/topic/api/WebViewNavGraph.kt
AndroidStudy-bmsk
632,254,827
false
{"Kotlin": 119717}
package org.bmsk.lifemash.feature.topic.api import org.bmsk.lifemash.feature.nav.LifeMashNavGraph interface WebViewNavGraph : LifeMashNavGraph<WebViewNavGraphInfo> data class WebViewNavGraphInfo( val onShowErrorSnackbar: (Throwable?) -> Unit, )
1
Kotlin
1
0
3e0d37ea57a8cb8877bd65130e249ceeea897d51
252
LifeMash-NewsApp
MIT License
app/src/main/java/com/github/alunicus/cinemalist/feature/movie/domain/model/dto/MovieDetailsDto.kt
alunicus
214,526,725
false
null
package com.github.alunicus.cinemalist.feature.movie.domain.model.dto import java.util.* data class MovieDetailsDto( val adult: Boolean, val backdropPath: String?, val belongsToCollection: BelongsToCollectionDto?, val budget: Int, val genres: List<GenreDto>, val homepage: String?, val id: Int, val imdbId: String?, val originalLanguage: String, val originalTitle: String, val overview: String?, val popularity: Double, val posterPath: String?, val productionCompanies: List<ProductionCompanyDto>, val productionCountries: List<ProductionCountryDto>, val releaseDate: Date, val revenue: Int, val runtime: Int?, val spokenLanguages: List<SpokenLanguageDto>, val status: String, val tagline: String?, val title: String, val video: Boolean, val voteAverage: Double, val voteCount: Int )
0
Kotlin
0
1
3a34743145018452af507ea6faeb95a52484649f
885
Cinemalist
Apache License 2.0
app/src/common/kotlin/com/brainasaservice/android/customviewtesting/DataSourceModule.kt
damian-burke
122,754,214
false
null
package com.brainasaservice.android.customviewtesting import com.brainasaservice.android.customviewtesting.data.AccountDataSource import com.brainasaservice.android.customviewtesting.model.Account import dagger.Module import dagger.Provides @Module class DataSourceModule { /** * For simplicity, our example simply returns Logged Out in our production state. */ @Provides fun providesMockAccountDataSource(): AccountDataSource = DumbAccountDataSource(Account.LoggedOut) }
0
Kotlin
1
17
49b0b744f8b02db87dd1f37d194ec6dd64d675cc
497
android-custom-view-testing
Apache License 2.0
app/src/main/java/com/fairybow/caloriediary/data/biometrics/BiometricsDao.kt
fairybow
785,890,629
false
{"Kotlin": 58702}
package com.fairybow.caloriediary.data.biometrics import androidx.room.Dao import androidx.room.Query import com.fairybow.caloriediary.data.BaseDao import com.fairybow.caloriediary.utilities.ActivityLevel import com.fairybow.caloriediary.utilities.Sex import com.fairybow.caloriediary.utilities.ZeroHourDate @Dao interface BiometricsDao : BaseDao<BiometricsTableRow> { @Query("SELECT * FROM BiometricsTableRow WHERE id = :id") fun get(id: Int): BiometricsTableRow? @Query("SELECT activityLevel FROM BiometricsTableRow WHERE id = :id") fun getActivityLevel(id: Int): ActivityLevel @Query("UPDATE BiometricsTableRow SET activityLevel = :activityLevel WHERE id = :id") suspend fun updateActivityLevel(activityLevel: ActivityLevel, id: Int) @Query("SELECT birthdate FROM BiometricsTableRow WHERE id = :id") fun getBirthdate(id: Int): ZeroHourDate @Query("UPDATE BiometricsTableRow SET birthdate = :birthdate WHERE id = :id") suspend fun updateBirthdate(birthdate: ZeroHourDate, id: Int) @Query("SELECT height FROM BiometricsTableRow WHERE id = :id") fun getHeight(id: Int): Double @Query("UPDATE BiometricsTableRow SET height = :height WHERE id = :id") suspend fun updateHeight(height: Double, id: Int) @Query("SELECT sex FROM BiometricsTableRow WHERE id = :id") fun getSex(id: Int): Sex @Query("UPDATE BiometricsTableRow SET sex = :sex WHERE id = :id") suspend fun updateSex(sex: Sex, id: Int) }
0
Kotlin
0
0
ec24a9d3fec4e621a02a57f7e7d4136c35c0fe6d
1,475
CalorieDiary
MIT License
shared/src/commonMain/kotlin/com/mr3y/ludi/shared/ui/presenter/DiscoverViewModel.kt
mr3y-the-programmer
606,875,717
false
{"Kotlin": 1275511, "HTML": 194}
package com.mr3y.ludi.shared.ui.presenter import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.snapshots.Snapshot import androidx.paging.cachedIn import cafe.adriel.voyager.core.model.ScreenModel import cafe.adriel.voyager.core.model.screenModelScope import com.mr3y.ludi.shared.ui.presenter.model.DiscoverFiltersState import com.mr3y.ludi.shared.ui.presenter.model.DiscoverState import com.mr3y.ludi.shared.ui.presenter.model.DiscoverStateGames import com.mr3y.ludi.shared.ui.presenter.model.Platform import com.mr3y.ludi.shared.ui.presenter.model.Store import com.mr3y.ludi.shared.ui.presenter.model.Tag import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import me.tatarka.inject.annotations.Inject @OptIn(FlowPreview::class) @Inject class DiscoverViewModel( private val pagingFactory: DiscoverPagingFactory ) : ScreenModel, DiscoverPagingFactory by pagingFactory { val searchQuery = mutableStateOf("") private val _filterState = MutableStateFlow(InitialFiltersState) private val trendingGames = trendingGamesPager.cachedIn(screenModelScope) private val topRatedGames = topRatedGamesPager.cachedIn(screenModelScope) private val favGenresBasedGames = favGenresBasedGamesPager?.cachedIn(screenModelScope) private val multiplayerGames = multiplayerGamesPager.cachedIn(screenModelScope) private val freeGames = freeGamesPager.cachedIn(screenModelScope) private val storyGames = storyGamesPager.cachedIn(screenModelScope) private val boardGames = boardGamesPager.cachedIn(screenModelScope) private val esportsGames = esportsGamesPager.cachedIn(screenModelScope) private val raceGames = raceGamesPager.cachedIn(screenModelScope) private val puzzleGames = puzzleGamesPager.cachedIn(screenModelScope) private val soundtrackGames = soundtrackGamesPager.cachedIn(screenModelScope) internal val Initial = DiscoverState( filtersState = InitialFiltersState, gamesState = DiscoverStateGames.SuggestedGames( trendingGames = trendingGames, topRatedGames = topRatedGames, favGenresBasedGames = favGenresBasedGames, multiplayerGames = multiplayerGames, freeGames = freeGames, storyGames = storyGames, boardGames = boardGames, eSportsGames = esportsGames, raceGames = raceGames, puzzleGames = puzzleGames, soundtrackGames = soundtrackGames ), isRefreshing = true ) private var _internalState by mutableStateOf(Initial) private val games = combine( snapshotFlow { searchQuery.value } .debounce(275) .distinctUntilChanged(), _filterState ) { searchText, filtersState -> if (searchText.isEmpty() && filtersState == InitialFiltersState) { Initial.gamesState } else { DiscoverStateGames.SearchQueryBasedGames( games = searchQueryBasedGamesPager(searchText, filtersState).cachedIn(screenModelScope) ) } }.map { Snapshot.withMutableSnapshot { _internalState = _internalState.copy(isRefreshing = false, gamesState = it) } }.launchIn(screenModelScope) val discoverState = snapshotFlow { _internalState } .stateIn( screenModelScope, SharingStarted.Lazily, _internalState ) fun updateSearchQuery(searchQueryText: String) { // Snapshot.withMutableSnapshot seems to be redundant in this class but, we are observing the snapshot state // using `snapshotFlow { }` which doesn't get notified of updates when we are in tests, and hence causing the assertions to fail. Snapshot.withMutableSnapshot { searchQuery.value = searchQueryText } } fun addToSelectedPlatforms(platform: Platform) { _filterState.update { it.copy(selectedPlatforms = it.selectedPlatforms + platform) } Snapshot.withMutableSnapshot { _internalState = _internalState.copy(filtersState = _filterState.value) } } fun removeFromSelectedPlatforms(platform: Platform) { _filterState.update { it.copy(selectedPlatforms = it.selectedPlatforms - platform) } Snapshot.withMutableSnapshot { _internalState = _internalState.copy(filtersState = _filterState.value) } } fun addToSelectedStores(store: Store) { _filterState.update { it.copy(selectedStores = it.selectedStores + store) } Snapshot.withMutableSnapshot { _internalState = _internalState.copy(filtersState = _filterState.value) } } fun removeFromSelectedStores(store: Store) { _filterState.update { it.copy(selectedStores = it.selectedStores - store) } Snapshot.withMutableSnapshot { _internalState = _internalState.copy(filtersState = _filterState.value) } } fun addToSelectedTags(tag: Tag) { _filterState.update { it.copy(selectedTags = it.selectedTags + tag) } Snapshot.withMutableSnapshot { _internalState = _internalState.copy(filtersState = _filterState.value) } } fun removeFromSelectedTags(tag: Tag) { _filterState.update { it.copy(selectedTags = it.selectedTags - tag) } Snapshot.withMutableSnapshot { _internalState = _internalState.copy(filtersState = _filterState.value) } } fun refresh() { Snapshot.withMutableSnapshot { _internalState = _internalState.copy(isRefreshing = true) } } fun refreshComplete() { Snapshot.withMutableSnapshot { _internalState = _internalState.copy(isRefreshing = false) } } companion object { val InitialFiltersState = DiscoverFiltersState( 0, allPlatforms = setOf( Platform(id = 21, label = "Android"), Platform(id = 3, label = "IOS"), Platform(id = 27, label = "Playstation 1"), Platform(id = 15, label = "Playstation 2"), Platform(id = 16, label = "Playstation 3"), Platform(id = 18, label = "Playstation 4"), Platform(id = 187, label = "Playstation 5"), Platform(id = 1, label = "Xbox One"), Platform(id = 186, label = "Xbox Series S/X"), Platform(id = 4, label = "PC") ), selectedPlatforms = emptySet(), allStores = setOf( Store(id = 1, label = "Steam"), Store(id = 4, label = "App store"), Store(id = 8, label = "Google play"), Store(id = 3, label = "Playstation store"), Store(id = 2, label = "Xbox store"), Store(id = 5, label = "GOG"), Store(id = 6, label = "Nintendo store"), Store(id = 9, label = "Itch.io"), Store(id = 11, label = "Epic games") ), selectedStores = emptySet(), allTags = setOf( Tag(id = 83, label = "Puzzle"), Tag(id = 42, label = "Soundtrack"), Tag(id = 1407, label = "Race"), Tag(id = 73, label = "ESports"), Tag(id = 162, label = "Board"), Tag(id = 406, label = "Story"), Tag(id = 79, label = "Free"), Tag(id = 31, label = "Single Player"), Tag(id = 7, label = "Multiplayer"), Tag(id = 397, label = "Online Multiplayer"), Tag(id = 468, label = "Role Playing"), Tag(id = 36, label = "Open World"), Tag(id = 32, label = "Sci-fi"), Tag(id = 45, label = "2D"), Tag(id = 123, label = "Comedy"), Tag(id = 134, label = "Anime") ).toSortedSet(compareBy { it.label }), selectedTags = emptySet(), sortingCriteria = null ) } }
5
Kotlin
0
9
c34f17c014f7ef050834a18b6854d67485b6bd83
8,416
Ludi
Apache License 2.0
app/src/main/java/com/inasweaterpoorlyknit/merlinsbag/viewmodel/OnboardingViewModel.kt
Lucodivo
762,597,375
false
{"Kotlin": 511621}
package com.inasweaterpoorlyknit.merlinsbag.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.inasweaterpoorlyknit.core.data.repository.UserPreferencesRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class OnboardingViewModel @Inject constructor( val userPreferencesRepository: UserPreferencesRepository ): ViewModel() { fun onGetStarted() = viewModelScope.launch(Dispatchers.IO){ userPreferencesRepository.setHasCompletedOnboarding(true) } }
0
Kotlin
0
1
d20a52635adcd42b48e609303f1a0d4673d73577
628
Merlinsbag
Apache License 2.0
binding-system-sqlite/src/main/java/ro/andob/outofroom/system_sqlite/Extensions.kt
andob
363,221,615
false
null
package ro.andob.outofroom.system_sqlite import android.database.sqlite.SQLiteOpenHelper import ro.andob.outofroom.EntityManager import ro.andob.outofroom.SystemSQLiteDBWrapper fun SQLiteOpenHelper.toEntityManager() = EntityManager(SystemSQLiteDBWrapper { writableDatabase })
0
Kotlin
0
1
1f8af1dc47e0a73e7d7b407299f1df395922ea2c
278
OutOfROOM
Apache License 2.0
app/src/main/java/com/aitgacem/budgeter/ui/viewmodels/OverviewViewModel.kt
naitgacem
722,472,421
false
{"Kotlin": 89949}
package com.aitgacem.budgeter.ui.viewmodels import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.aitgacem.budgeter.Budgeter import com.aitgacem.budgeter.data.TransactionsRepository import com.aitgacem.budgeter.data.model.Transaction import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class OverviewViewModel @Inject constructor( private val repository: TransactionsRepository, ) : ViewModel() { private var _recentTransactions = MutableStateFlow<List<Transaction>>(emptyList()) val recentTransactions = _recentTransactions private var _balance = MutableStateFlow(0.toFloat()) val balance = _balance init { refreshRecentTransactions() refreshBalance() } private fun refreshRecentTransactions() { viewModelScope.launch { repository.readRecentTransactionsFromDatabase().collect { transactions -> _recentTransactions.value = transactions } } } private fun refreshBalance() { viewModelScope.launch { repository.readBalance().collect { _balance.value = it ?: 0.toFloat() } } } }
0
Kotlin
0
0
00b1e93a33db799154d2b746ec562abfa9297ff0
1,572
Budgeter
Apache License 2.0
backend/src/main/kotlin/ntnu/idatt2105/user/service/UserDetailsServiceImpl.kt
olros
366,615,349
false
null
package ntnu.idatt2105.user.service import ntnu.idatt2105.core.exception.ApplicationException import ntnu.idatt2105.core.exception.EntityType import ntnu.idatt2105.core.exception.ExceptionType import ntnu.idatt2105.user.model.User import ntnu.idatt2105.user.repository.UserRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException class UserDetailsServiceImpl : UserDetailsService { @Autowired lateinit var userRepository: UserRepository @Throws(UsernameNotFoundException::class) override fun loadUserByUsername(email: String): UserDetails { val user: User = userRepository.findByEmail(email) ?: throw ApplicationException.throwException( EntityType.USER, ExceptionType.ENTITY_NOT_FOUND, "2", email) return UserDetailsImpl(user.id, user.email, user.password, getAuthorities(user)) } private fun getAuthorities(user: User) = user.roles.map { role -> SimpleGrantedAuthority("ROLE_".plus(role.name)) } .toCollection(mutableSetOf()) }
0
Kotlin
3
2
a2fa5bbca5a9db67f12733301b952807d66e673f
1,313
Rombestilling
MIT License
app/src/main/java/com/doubean/ford/model/PostItemGroupPartialEntity.kt
Bumblebee202111
453,416,432
false
null
package com.doubean.ford.model import java.time.LocalDateTime class PostItemGroup( val id: String, val name: String, val memberCount: Int? = null, val postCount: Int? = null, val dateCreated: LocalDateTime? = null, val shareUrl: String, val url: String, val uri: String, val avatarUrl: String? = null, val memberName: String? = null, val shortDescription: String? = null, val description: String? = null, val color: Int? = null, )
0
Kotlin
0
5
7f92e341028d187b351dadec6eccde2d7715b65e
495
doubean
Apache License 2.0
library/src/main/java/cloud/pace/sdk/api/poi/generated/model/MoveRequest.kt
pace
303,641,261
false
null
/* * PLEASE DO NOT EDIT! * * Generated by SwagGen with Kotlin template. * https://github.com/pace/SwagGen */ package cloud.pace.sdk.api.poi.generated.model import moe.banana.jsonapi2.JsonApi import moe.banana.jsonapi2.Resource /* Creates a new event object at lat/lng from this POI ID */ @JsonApi(type = "moveRequest") class MoveRequest : Resource() { /* Latitude in degrees */ var latitude: Float? = null /* Longitude in degrees */ var longitude: Float? = null }
0
Kotlin
1
5
c459c30690f3c2c480986312a3d837698ce028bc
490
cloud-sdk-android
MIT License
sample/src/main/kotlin/smartrecycleradapter/utils/AssetsUtils.kt
manneohlund
92,768,662
false
null
package smartrecycleradapter.utils import android.content.Context import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.io.InputStreamReader class AssetsUtils { companion object { @Throws(IOException::class) inline fun <reified T : Any> loadStyleFromAssets(context: Context, fileName: String): T { return loadStyle(context.assets.open(fileName)) } @Throws(IOException::class) inline fun <reified T : Any> loadStyleFromFile(file: File): T { return loadStyle(FileInputStream(file)) } @Throws(IOException::class) inline fun <reified T : Any> loadStyle(inputStream: InputStream): T { return Gson().fromJson(InputStreamReader(inputStream), object : TypeToken<T>() {}.type) } } }
12
Kotlin
51
407
aad30be7ed58deee39a8efaffac3207c486a28a2
925
smart-recycler-adapter
Apache License 2.0
app/src/main/java/space/rodionov/englishdriller/ui/CategoriesAdapter.kt
aleksej-rodionov
371,211,387
false
null
package space.rodionov.englishdriller.ui import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import space.rodionov.englishdriller.data.CategoryItem import space.rodionov.englishdriller.databinding.RecyclerSimpleItemBinding class CategoriesAdapter(private val listener: OnItemClickListener/*, var nativeLanguage: NativeLanguage*/) : ListAdapter<CategoryItem, CategoriesAdapter.CategoriesViewHolder>( DiffCallback() ) { inner class CategoriesViewHolder(private val binding: RecyclerSimpleItemBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.apply { btnVocabulary.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { val categoryItem = getItem(position) listener.onVocabularyClick(categoryItem) } } btnSwitch.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { val categoryItem = getItem(position) listener.onSwitchClick(categoryItem, btnSwitch.isChecked) } } } } fun bind(categoryItem: CategoryItem) { binding.apply { btnSwitch.isChecked = categoryItem.categoryShown btnSwitch.text = if (categoryItem.categoryShown) "On" else "Off" tvCategoryName.text = categoryItem.categoryNameRus // color of Checked category should be coded here } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoriesViewHolder { val binding = RecyclerSimpleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return CategoriesViewHolder(binding) } override fun onBindViewHolder(holder: CategoriesViewHolder, position: Int) { val currentItem = getItem(position) holder.bind(currentItem) } // override fun getItemCount(): Int = categoryList.size interface OnItemClickListener { fun onVocabularyClick(categoryItem: CategoryItem) fun onSwitchClick(categoryItem: CategoryItem, isChecked: Boolean) } class DiffCallback : DiffUtil.ItemCallback<CategoryItem>() { override fun areItemsTheSame(oldItem: CategoryItem, newItem: CategoryItem) = oldItem == newItem override fun areContentsTheSame(oldItem: CategoryItem, newItem: CategoryItem) = oldItem.categoryNameRus == newItem.categoryNameRus } }
0
Kotlin
0
0
984966cab7d0fd02a5fb5e23ef1a67808c0d8d7a
2,844
english-driller
Apache License 2.0
centurion-hive/src/test/kotlin/com/sksamuel/centurion/resolver/LenientWriteTest.kt
sksamuel
13,625,531
false
{"Kotlin": 212253, "Java": 19565, "Shell": 1586}
package com.sksamuel.centurion.resolver import arrow.core.Try import com.sksamuel.centurion.BooleanType import com.sksamuel.centurion.ConstantFileNamer import com.sksamuel.centurion.CreateTableConfig import com.sksamuel.centurion.DatabaseName import com.sksamuel.centurion.Float64Type import com.sksamuel.centurion.HiveTestConfig import com.sksamuel.centurion.HiveTestConfig.client import com.sksamuel.centurion.HiveTestConfig.fs import com.sksamuel.centurion.HiveUtils import com.sksamuel.centurion.HiveWriter import com.sksamuel.centurion.OptimisticFileManager import com.sksamuel.centurion.StringType import com.sksamuel.centurion.Struct import com.sksamuel.centurion.StructField import com.sksamuel.centurion.StructType import com.sksamuel.centurion.TableName import com.sksamuel.centurion.WriteMode import com.sksamuel.centurion.evolution.NoopSchemaEvolver import com.sksamuel.centurion.formats.ParquetFormat import com.sksamuel.centurion.parquet.parquetReader import com.sksamuel.centurion.parquet.readAll import com.sksamuel.centurion.partitioners.StaticPartitioner import io.kotlintest.matchers.collections.shouldBeEmpty import io.kotlintest.shouldBe import io.kotlintest.specs.FunSpec import org.apache.hadoop.fs.Path import org.apache.hadoop.hive.metastore.TableType import org.apache.hadoop.hive.metastore.api.Database import org.apache.hadoop.hive.metastore.api.FieldSchema class LenientWriteTest : FunSpec() { init { Try { HiveTestConfig.client.dropDatabase("tests") } Try { val db = Database("tests", "test database", "/user/hive/warehouse/tests", emptyMap()) HiveTestConfig.client.createDatabase(db) } test("writing data with lenient mode should align structs") { Try { HiveTestConfig.client.dropTable("tests", "lenientdata", true, true) } val metastoreSchema = StructType( StructField("name", StringType), StructField("title", StringType), StructField("salary", Float64Type), StructField("employed", BooleanType) ) val u1 = Struct( StructType( StructField("name", StringType), StructField("title", StringType), StructField("employed", BooleanType) ), listOf("sam", "mr", true) ) val u2 = Struct( StructType( StructField("name", StringType), StructField("salary", Float64Type), StructField("employed", BooleanType) ), listOf("bob", 3485.63, false) ) val writer = HiveWriter( DatabaseName("tests"), TableName("lenientdata"), WriteMode.Overwrite, fileManager = OptimisticFileManager(ConstantFileNamer("test.pq")), createConfig = CreateTableConfig(metastoreSchema, null, TableType.MANAGED_TABLE, ParquetFormat, null), evolver = NoopSchemaEvolver, partitioner = StaticPartitioner, resolver = LenientStructResolver, client = HiveTestConfig.client, fs = HiveTestConfig.fs ) writer.write(listOf(u1, u2)) writer.close() val table = HiveUtils(client, fs).table(DatabaseName("tests"), TableName("lenientdata")) table.sd.cols shouldBe listOf( FieldSchema("name", "string", null), FieldSchema("title", "string", null), FieldSchema("salary", "double", null), FieldSchema("employed", "boolean", null) ) HiveUtils(client, fs).table(DatabaseName("tests"), TableName("lenientdata")).partitionKeys.shouldBeEmpty() val file = Path(table.sd.location, "test.pq") val reader = parquetReader(file, HiveTestConfig.conf) val struct = reader.readAll().toList() struct.first().schema shouldBe StructType( StructField(name = "name", type = StringType, nullable = true), StructField(name = "title", type = StringType, nullable = true), StructField(name = "salary", type = Float64Type, nullable = true), StructField(name = "employed", type = BooleanType, nullable = true) ) struct.map { it.values }.toList() shouldBe listOf( listOf("sam", "mr", null, true), listOf("bob", null, 3485.63, false) ) } } }
0
Kotlin
46
325
72c8ac0290215e94ca02c2b23b2428f815576889
4,278
kotlin-big-data
Apache License 2.0
extension-api/src/main/kotlin/com/github/ottx96/ivy/data/IvyLeeTask.kt
ottx96
236,785,029
false
null
package com.github.ottx96.ivy.data import com.github.ottx96.ivy.data.enums.Priorities import com.github.ottx96.ivy.data.enums.TaskStatus import com.github.ottx96.ivy.serialization.LocalDateSerializer import kotlinx.serialization.Serializable import java.time.LocalDate /** * Container (data) classes * * Project: ivy-lee * Package: de.mait.ott * Created: 28.01.2020 16:58 * @author = manuel.ott * @since = 28. Januar 2020 * * UML: State diagram * @startuml * State Setup { * State "user input" as aui * aui: entry / open GUI screen * aui: do / wait for user input * aui: exit / save configuration data * [*] --> aui * } * State Initialization { * State "loading" as load * [*] --> load * load: entry / download task data * load: do / read task data * load: exit / open GUI screen * } * State "task overview (task status)" as tasks{ * [*] -> UNDONE * UNDONE: exit / refresh GUI * UNDONE -> IN_WORK: [user input] / do / refresh GUI * IN_WORK: exit / refresh GUI * IN_WORK --> DONE: [user input] / do / refresh GUI * DONE: exit / refresh GUI * DONE --> UNDONE: [user input] / do / refresh GUI * } * * [*] -> Setup : [first run] * [*] --> Initialization : [else] * Setup --> Initialization: [user input] / do / save data * Initialization --> tasks: [task data read] / do / open GUI * tasks ---> deletion : [user input] / do / delete task * deletion ---> tasks : [task deleted] / do / refresh GUI * deletion: exit / refresh GUI * tasks ---> creation : [user input] / do / show GUI screen * creation ---> tasks : [task created] / do / refresh GUI * creation: entry / show GUI screen * creation: do / wait for user input * creation: exit / save task data * creation: exit / refresh GUI * tasks -> [*]: [user input] / do / exit * @enduml */ @Serializable data class IvyLeeTask(var name: String = "", var descr: String = "", var estTimeSeconds: Int = 0, var status: TaskStatus = TaskStatus.EMPTY, var timeInvestedSeconds: Int = 0, var favorite: Boolean = false, @Serializable(with = LocalDateSerializer::class) var dueDate: LocalDate = LocalDate.now().plusDays(7), var priority: Priorities = Priorities.LOWEST) { companion object { const val REVISION = 3 } }
16
Kotlin
0
1
aa0dc0e6fd2853535945c0764bde33be1d92d7f1
2,329
ivy-lee
MIT License
frontend/android/src/main/java/com/mobilispect/android/MobilispectApp.kt
alandovskis
502,662,711
false
{"Kotlin": 358753, "Shell": 472, "Swift": 345}
package com.mobilispect.android import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MobilispectApp : Application()
1
Kotlin
0
1
60a1c33f6a8663d5528b38fc57b7236b5c3e0fd4
160
mobilispect
Apache License 2.0
ok-propertysale-mp-transport-ps/src/commonMain/kotlin/ru/otus/otuskotlin/propertysale/mp/transport/ps/models/flat/PsFlatDto.kt
otuskotlin
330,109,804
false
null
package ru.otus.otuskotlin.propertysale.mp.transport.ps.models.flat import kotlinx.serialization.Serializable import ru.otus.otuskotlin.propertysale.mp.transport.ps.models.common.models.PsActionDto @Serializable data class PsFlatDto( val id: String? = null, val name: String? = null, val description: String? = null, val floor: Int? = null, val numberOfRooms: Int? = null, val actions: Set<PsActionDto>? = null, )
0
Kotlin
0
1
ed9a38627e64ed36131280ca7449547ba1d06829
440
otuskotlin-202012-propertysale-ks
MIT License
app/src/main/kotlin/moe/linux/boilerplate/di/FragmentComponent.kt
ky0615
86,218,721
false
null
package moe.linux.boilerplate.di import dagger.Subcomponent import moe.linux.boilerplate.di.scope.FragmentScope import moe.linux.boilerplate.view.fragment.* @FragmentScope @Subcomponent(modules = arrayOf( FragmentModule::class )) interface FragmentComponent { fun injectTo(fragment: CardMenuDialogFragment) fun injectTo(fragment: FrontFragment) fun injectTo(fragment: MainFragment) fun injectTo(fragment: QiitaListFragment) fun injectTo(fragment: DetailFragment) }
0
Kotlin
0
0
67043a6d6946d199d929a681ff69d4d89e4d241a
491
ReadTDUStudentCard4Android
MIT License
src/main/kotlin/no/nav/aareg/teknisk_historikk/Sikkerhet.kt
navikt
567,189,411
false
{"Kotlin": 63220, "Dockerfile": 103}
package no.nav.aareg.teknisk_historikk import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.web.authentication.HttpStatusEntryPoint import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher @EnableWebSecurity @Configuration open class SecurityConfig { @Bean open fun filterChain(http: HttpSecurity) = http.csrf().disable() .authorizeHttpRequests { it.requestMatchers(antMatcher("/api/**")) .hasAnyAuthority("SCOPE_${SCOPE_KONTROLL_API}") .requestMatchers( antMatcher("/actuator/**"), antMatcher("/swagger-ui/**"), antMatcher("/api-docs/**"), antMatcher("/openapi-spec.yaml") ).permitAll() } .exceptionHandling { it.authenticationEntryPoint(HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)) } .oauth2ResourceServer { obj -> obj.jwt() } .build() } const val SCOPE_KONTROLL_API = "nav:aareg/v1/arbeidsforhold/tekniskhistorikk"
1
Kotlin
0
0
2cfd67d787fb5c7673c7c765f21f32b1a7472c24
1,346
aareg-teknisk-historikk
MIT License
compose/mpp/demo/src/uikitMain/kotlin/androidx/compose/mpp/demo/StatusBarState.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.mpp.demo import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.interop.LocalUIViewController import androidx.compose.ui.unit.dp import platform.UIKit.UIStatusBarAnimation import platform.UIKit.UIStatusBarStyleDarkContent import platform.UIKit.UIStatusBarStyleDefault import platform.UIKit.UIStatusBarStyleLightContent import platform.UIKit.UIView private var statusBarStyleIndex by mutableStateOf(0) val preferredStatusBarStyleValue by derivedStateOf { styleValues[statusBarStyleIndex].second } private var statusBarHiddenIndex by mutableStateOf(0) val prefersStatusBarHiddenValue by derivedStateOf { hiddenValues[statusBarHiddenIndex].second } private var statusBarAnimationIndex by mutableStateOf(0) val preferredStatysBarAnimationValue by derivedStateOf { animationValues[statusBarAnimationIndex].second } private val hiddenValues = listOf( "null" to null, "True" to true, "False" to false ) private val animationValues = listOf( "null" to null, "UIStatusBarAnimationFade" to UIStatusBarAnimation.UIStatusBarAnimationFade, "UIStatusBarAnimationSlide" to UIStatusBarAnimation.UIStatusBarAnimationSlide ) private val styleValues = listOf( "null" to null, "UIStatusBarStyleDefault" to UIStatusBarStyleDefault, "UIStatusBarStyleLightContent" to UIStatusBarStyleLightContent, "UIStatusBarStyleDarkContent" to UIStatusBarStyleDarkContent ) val StatusBarStateExample = Screen.Example("StatusBarState") { Column(modifier = Modifier.fillMaxSize()) { Dropdown("preferredStatusBarStyle", styleValues[statusBarStyleIndex].first, styleValues.map { it.first }) { statusBarStyleIndex = it } Dropdown("prefersStatusBarHidden", hiddenValues[statusBarHiddenIndex].first, hiddenValues.map { it.first }) { statusBarHiddenIndex = it } Dropdown("preferredStatysBarAnimation", animationValues[statusBarAnimationIndex].first, animationValues.map { it.first }) { statusBarAnimationIndex = it } } val viewController = LocalUIViewController.current LaunchedEffect(statusBarStyleIndex, statusBarHiddenIndex, statusBarAnimationIndex) { UIView.animateWithDuration(0.3) { viewController.setNeedsStatusBarAppearanceUpdate() } } } @Composable private fun Dropdown( name: String, current: String, all: List<String>, onSelected: (Int) -> Unit ) { var expanded by remember { mutableStateOf(false) } Box(modifier = Modifier .padding(16.dp) .fillMaxWidth() .clickable { expanded = true }) { Text("$name: $current") DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }) { all.forEachIndexed { index, item -> DropdownMenuItem( onClick = { onSelected(index) expanded = false }) { Text(item) } } } } }
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
4,425
compose
Apache License 2.0
src/main/kotlin/com/github/nikitavbv/servicemonitor/alert/AlertController.kt
nikitavbv
151,761,891
false
null
package com.github.nikitavbv.servicemonitor.alert import com.github.nikitavbv.servicemonitor.ALERT_API import com.github.nikitavbv.servicemonitor.agent.Agent import com.github.nikitavbv.servicemonitor.agent.AgentNotFoundException import com.github.nikitavbv.servicemonitor.agent.AgentRepository import com.github.nikitavbv.servicemonitor.api.StatusOKResponse import com.github.nikitavbv.servicemonitor.exceptions.AccessDeniedException import com.github.nikitavbv.servicemonitor.exceptions.AuthRequiredException import com.github.nikitavbv.servicemonitor.exceptions.MissingParameterException import com.github.nikitavbv.servicemonitor.metric.Metric import com.github.nikitavbv.servicemonitor.metric.MetricNotFoundException import com.github.nikitavbv.servicemonitor.metric.MetricRepository import com.github.nikitavbv.servicemonitor.project.Project import com.github.nikitavbv.servicemonitor.user.ApplicationUser import com.github.nikitavbv.servicemonitor.user.ApplicationUserRepository import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import javax.servlet.http.HttpServletRequest @RestController @RequestMapping(ALERT_API) class AlertController( val alertRepository: AlertRepository, val applicationUserRepository: ApplicationUserRepository, val agentRepository: AgentRepository, val metricRepository: MetricRepository ) { @GetMapping fun getAllAlerts(req: HttpServletRequest): Map<String, Any?> { return mapOf( "alerts" to getAlertsForUser(getApplicationUserByHttpRequest(req)) ) } @PostMapping fun createAlert(req: HttpServletRequest, @RequestBody body: Map<String, Any?>): Map<String, Any?> { val user = getApplicationUserByHttpRequest(req) val agentID = getRequiredBodyParameter(body, "agentID").toString().toLong() val agent = agentRepository.findById(agentID).orElseThrow { AgentNotFoundException() } val project = agent.project ?: throw AssertionError("No project set for agent") if (!project.users.contains(user)) throw AccessDeniedException() val metricID = getRequiredBodyParameter(body, "metricID").toString().toLong() val metric = metricRepository.findById(metricID).orElseThrow { MetricNotFoundException() } val paramName = getRequiredBodyParameter(body, "paramName").toString() val condition = getRequiredBodyParameter(body, "condition").toString() val conditionLevel = getRequiredBodyParameter(body, "conditionLevel").toString() val action = getRequiredBodyParameter(body, "alertAction").toString() val alert = Alert( metric = metric, paramName = paramName, alertCondition = condition, level = conditionLevel, action = action ) alertRepository.save(alert) metric.alerts.add(alert) metricRepository.save(metric) return mapOf( "status" to "ok", "id" to alert.id ) } @DeleteMapping("/{alertID}") fun deleteAlert(req: HttpServletRequest, @PathVariable alertID: Long): StatusOKResponse { val user = getApplicationUserByHttpRequest(req) val alert = alertRepository.findById(alertID).orElseThrow { AlertNotFoundException() } val agent = alert.metric.getAgentStrictly() val project = agent.project ?: throw AssertionError("Agent has no project set") if (!project.users.contains(user)) throw AccessDeniedException() alert.metric.alerts.remove(alert) alertRepository.delete(alert) metricRepository.save(alert.metric) return StatusOKResponse() } fun getAlertsForUser(user: ApplicationUser): List<Map<String, Any?>> { val alerts = mutableListOf<Map<String, Any?>>() user.projects.forEach { alerts.addAll(getAlertsForProject(it)) } return alerts } fun getAlertsForProject(project: Project): List<Map<String, Any?>> { val alerts = mutableListOf<Map<String, Any?>>() project.agents.forEach { alerts.addAll(getAlertsForAgent(it)) } return alerts } fun getAlertsForAgent(agent: Agent): List<Map<String, Any?>> { val alerts = mutableListOf<Map<String, Any?>>() agent.metrics.forEach { alerts.addAll(getAlertsForMetric(it)) } return alerts } fun getAlertsForMetric(metric: Metric): List<Map<String, Any?>> { return metric.alerts.map { mapOf( "alert" to it, "metric" to it.metric ) }.toList() } fun getRequiredBodyParameter(body: Map<String, Any?>, key: String): Any { return body[key] ?: throw MissingParameterException(key) } fun getApplicationUserByHttpRequest(req: HttpServletRequest): ApplicationUser { return applicationUserRepository.findByUsername(req.remoteUser ?: throw AuthRequiredException()) } }
0
Kotlin
0
0
d26cbb6e99cb420590e5f47f58f282612aa89997
5,340
ServiceMonitor
MIT License
src/main/kotlin/com/advanon/bus/MessageBusConverter.kt
Advanon
132,481,097
false
{"Kotlin": 8923}
package com.advanon.bus /** * A class implementing [MessageBusConverter] is responsible for the conversion between a message payload and the * corresponding instance. * * @author <NAME> */ interface MessageBusConverter { /** * Convert a String containing a message payload to the corresponding instance. * * @param payload The message payload * @return The corresponding instance */ fun convertMessagePayload(payload: String): Any? }
0
Kotlin
1
5
e5b53c723e7d2c96f2831293a19f6aa94f4270fc
474
AdvaBus
Apache License 2.0
xnet/src/main/java/com/gfms/xnet/discovery/payload/PongPayload.kt
r3tr056
875,356,073
false
{"Kotlin": 382790, "C++": 177456, "C": 140193, "CMake": 3494}
package com.gfms.xnet.discovery.payload import com.gfms.xnet.serialization.Deserializable import com.gfms.xnet.serialization.Serializable import com.gfms.xnet.serialization.SERIALIZED_USHORT_SIZE import com.gfms.xnet.serialization.deserializeUShort import com.gfms.xnet.serialization.serializeUShort data class PongPayload( val identifier: Int ): Serializable { override fun serialize(): ByteArray { return serializeUShort(identifier % UShort.MAX_VALUE.toInt()) } companion object Deserializer: Deserializable<PongPayload> { override fun deserialize(buffer: ByteArray, offset: Int): Pair<PongPayload, Int> { val identifier = deserializeUShort(buffer, offset) return Pair(PongPayload(identifier), offset + SERIALIZED_USHORT_SIZE) } } }
0
Kotlin
0
0
d76c8c1f2c9a426354d88065f37c15e1c6a51b02
806
koinoor
MIT License
app-analyses/src/test/kotlin/com/usvision/analyses/detector/SharedPersistenceTest.kt
the-sortinghat
419,233,583
false
{"Kotlin": 185733, "Dockerfile": 1834, "JavaScript": 293}
package com.usvision.analyses.detector import com.usvision.analyses.analyzer.Count import com.usvision.analyses.analyzer.DatabaseUsage import com.usvision.analyses.analyzer.NumberOfClients import com.usvision.analyses.analyzer.Relationship import com.usvision.model.domain.Microservice import com.usvision.model.domain.databases.PostgreSQL import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs class SharedPersistenceTest { private lateinit var underTest: SharedPersistence @MockK private lateinit var mockNclients: NumberOfClients @MockK private lateinit var mockDbUsages: DatabaseUsage @BeforeTest fun `create clean, new instance of SharedPersistence`() { MockKAnnotations.init(this) underTest = SharedPersistence( nClients = mockNclients, dbUsage = mockDbUsages ) } @Test fun `it identifies one when given a shared database by two services`() { // given val msOne = Microservice(name = "one") val msTwo = Microservice(name = "two") val sharedDb = PostgreSQL(id = "id") every { mockNclients.getResults() } returns mapOf( sharedDb to Count(value = 2, type = "Int", unit = "clients") ) every { mockDbUsages.getResults() } returns mapOf( sharedDb to setOf( Relationship(with = msOne), Relationship(with = msTwo) ) ) // when underTest.run() val results = underTest.getInstances() // then assertEquals(results.size, 1) assertIs<SharedPersistenceInstance>(results.first()) } @Test fun `it doesnt identify any when given an exclusive database`() { // given val ms = Microservice(name = "one") val db = PostgreSQL(id = "id") every { mockNclients.getResults() } returns mapOf( db to Count(value = 1, type = "Int", unit = "clients") ) every { mockDbUsages.getResults() } returns mapOf( db to setOf(Relationship(with = ms)) ) // when underTest.run() val results = underTest.getInstances() // then assertEquals(results.size, 0) } }
3
Kotlin
0
3
d5143ab39da2efe586cf185808d387ce902be64f
2,393
pattern-detector
MIT License
src/main/kotlin/tokyo/aieuo/mineflow/flowItem/action/variable/JoinListVariableToString.kt
aieuo
364,472,156
false
null
package tokyo.aieuo.mineflow.flowItem.action.variable import tokyo.aieuo.mineflow.Main import tokyo.aieuo.mineflow.exception.InvalidFlowValueException import tokyo.aieuo.mineflow.flowItem.FlowItem import tokyo.aieuo.mineflow.flowItem.FlowItemExecutor import tokyo.aieuo.mineflow.flowItem.FlowItemIds import tokyo.aieuo.mineflow.formAPI.element.Element import tokyo.aieuo.mineflow.formAPI.element.mineflow.ExampleInput import tokyo.aieuo.mineflow.formAPI.response.CustomFormResponseList import tokyo.aieuo.mineflow.utils.Category import tokyo.aieuo.mineflow.utils.DummyVariableMap import tokyo.aieuo.mineflow.utils.Language import tokyo.aieuo.mineflow.variable.DummyVariable import tokyo.aieuo.mineflow.variable.ListVariable import tokyo.aieuo.mineflow.variable.StringVariable class JoinListVariableToString( var variableName: String = "", var separator: String = "", var resultName: String = "result" ) : FlowItem() { override val id = FlowItemIds.JOIN_LIST_VARIABLE_TO_STRING override val nameTranslationKey = "action.joinToString.name" override val detailTranslationKey = "action.joinToString.detail" override val detailDefaultReplaces = listOf("name", "separator", "result") override val category = Category.VARIABLE override fun isDataValid(): Boolean { return separator != "" } override fun getDetail(): String { if (!isDataValid()) return getName() return Language.get(detailTranslationKey, listOf(variableName, separator, resultName)) } override fun execute(source: FlowItemExecutor) = sequence { throwIfCannotExecute() val helper = Main.variableHelper val name = source.replaceVariables(variableName) val separator = source.replaceVariables(separator) val result = source.replaceVariables(resultName) val variable = source.getVariable(name) ?: helper.getNested(name) if (variable === null) { throw InvalidFlowValueException(Language.get("variable.notFound", listOf(name))) } if (variable !is ListVariable) { throw InvalidFlowValueException( Language.get( "action.addListVariable.error.existsOtherType", listOf(name, variable.toString()) ) ) } val strings = mutableListOf<String>() variable.value.forEach { strings.add(it.toString()) } source.addVariable(result, StringVariable(strings.joinToString(separator))) yield(FlowItemExecutor.Result.CONTINUE) } override fun getEditFormElements(variables: DummyVariableMap): List<Element> { return listOf( ExampleInput("@action.variable.form.name", "aieuo", variableName, true), ExampleInput("@action.joinToString.form.separator", ", ", separator, false), ExampleInput("@action.form.resultVariableName", "string", resultName, true), ) } override fun loadSaveData(contents: CustomFormResponseList) = apply { variableName = contents.getString(0) separator = contents.getString(1) resultName = contents.getString(2) } override fun serializeContents(): List<Any> { return listOf(variableName, separator, resultName) } override fun getAddingVariables(): DummyVariableMap { return mapOf( resultName to DummyVariable(DummyVariable.Type.STRING) ) } }
0
Kotlin
0
0
9c2ef7133d84c5d9b6f4336463d9e1d56442924a
3,470
Mineflow-Kotlin
MIT License
zeta-components/zeta-quartz-starter/src/main/kotlin/org/zetaframework/quartz/module/QuartzJobDetailDTO.kt
xia5800
510,203,856
false
{"Kotlin": 617877, "Lua": 347}
package org.zetaframework.quartz.module import com.fasterxml.jackson.annotation.JsonFormat import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import java.util.* /** * 任务 详情 * * @author gcc */ @ApiModel(description = "任务详情") class QuartzJobDetailDTO { /** 任务名称 */ @ApiModelProperty(value = "任务名称") var jobName: String? = null /** 任务描述 */ @ApiModelProperty(value = "任务描述") var jobDescription: String? = null /** 任务执行类 */ @ApiModelProperty(value = "任务执行类") var jobClassName: String? = null /** 任务参数 */ @ApiModelProperty(value = "任务参数") var jobParam: String? = null /** 下次触发时间 */ @ApiModelProperty(value = "下次触发时间") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") var nextFireTime: Date? = null /** 上次触发时间 */ @ApiModelProperty(value = "上次触发时间") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") var prevFireTime: Date? = null /** 触发器优先级 */ @ApiModelProperty(value = "触发器优先级") var priority: Int? = null /** 开始时间 */ @ApiModelProperty(value = "开始时间") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") var startTime: Date? = null /** 结束时间 */ @ApiModelProperty(value = "结束时间") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") var endTime: Date? = null /** * 触发器状态 * * 状态值说明: * null: 获取状态失败 * NONE: 触发器不存在或被删除 * NORMAL: 正常 * PAUSED: 暂停 * COMPLETE: 完成 * ERROR: 错误 * BLOCKED: 阻塞 */ @ApiModelProperty(value = "触发器状态", allowableValues = "null,NONE,NORMAL,PAUSED,COMPLETE,ERROR,BLOCKED") var triggerState: String? = null /** 触发器类型 */ @ApiModelProperty(value = "触发器类型", allowableValues = "CRON,CAL_INT,SIMPLE,DAILY_I") var triggerType: String? = null /** cron表达式,仅当triggerType=CRON的时候才有值 */ @ApiModelProperty(value = "cron表达式,仅当triggerType=CAL_INT,DAILY_I的时候才有值") var cron: String? = null /** 间隔的时间单位,仅当triggerType=CAL_INT,DAILY_I的时候才有值 */ @ApiModelProperty(value = "间隔的时间单位,仅当triggerType=CAL_INT,DAILY_I的时候才有值") var strProp1: String? = null /** 星期几,仅当triggerType=DAILY_I的时候才有值 */ @ApiModelProperty(value = "星期几,仅当triggerType=DAILY_I的时候才有值") var strProp2: String? = null /** 开始结束时间,仅当triggerType=DAILY_I的时候才有值 */ @ApiModelProperty(value = "开始结束时间,仅当triggerType=DAILY_I的时候才有值") var strProp3: String? = null /** 重复次数,仅当triggerType=CAL_INT,DAILY_I的时候才有值 */ @ApiModelProperty(value = "重复次数,仅当triggerType=CAL_INT,DAILY_I的时候才有值") var intProp1: Int? = null /** 重复次数,-1代表重复执行。仅当triggerType=SIMPLE的时候才有值 */ @ApiModelProperty(value = "重复次数,-1代表重复执行。仅当triggerType=SIMPLE的时候才有值") var simpleRepeatCount: Int? = null /** 重复间隔,单位毫秒。仅当triggerType=SIMPLE的时候才有值 */ @ApiModelProperty(value = "重复间隔,单位毫秒。仅当triggerType=SIMPLE的时候才有值") var simpleRepeatInterval: Long? = null }
0
Kotlin
0
4
cf4d02af6310ac6134f9e24c0bf1139656441e36
2,951
springboot-kotlin-module
MIT License
module-user/src/main/java/com/example/fragment/module/user/fragment/LoginFragment.kt
miaowmiaow
364,865,870
false
null
package com.example.fragment.module.user.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import com.example.fragment.library.common.constant.Router import com.example.fragment.library.common.fragment.RouterFragment import com.example.fragment.library.common.utils.WanHelper import com.example.fragment.module.user.databinding.FragmentLoginBinding import com.example.fragment.module.user.model.UserViewModel class LoginFragment : RouterFragment() { private val viewModel: UserViewModel by viewModels() private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLoginBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun initView() { binding.black.setOnClickListener { activity.onBackPressed() } binding.username.addKeyboardListener(binding.root) binding.password.addKeyboardListener(binding.root) binding.login.setOnClickListener { val username = binding.username.text.toString() val password = binding.password.text.toString() if (checkParameter(username, password)) { viewModel.login(username, password) } } binding.register.setOnClickListener { activity.navigation(Router.LOGIN_TO_REGISTER) } } override fun initViewModel() { viewModel.loginResult.observe(viewLifecycleOwner) { result -> when { result.errorCode == "0" -> { result.data?.apply { WanHelper.setUser(this) } activity.onBackPressed() } result.errorCode.isNotBlank() && result.errorMsg.isNotBlank() -> { activity.showTips(result.errorMsg) } } } } override fun onLoad() { } private fun checkParameter(username: String, password: String): Boolean { if (username.isBlank()) { activity.showTips("用户名不能为空") return false } if (password.isBlank()) { activity.showTips("密码不能为空") return false } return true } }
0
Kotlin
33
204
cbd04c277155083a1c2d5a2b943ff6b3b42f091a
2,598
FragmentProject
Apache License 2.0
module-user/src/main/java/com/example/fragment/module/user/fragment/LoginFragment.kt
miaowmiaow
364,865,870
false
null
package com.example.fragment.module.user.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import com.example.fragment.library.common.constant.Router import com.example.fragment.library.common.fragment.RouterFragment import com.example.fragment.library.common.utils.WanHelper import com.example.fragment.module.user.databinding.FragmentLoginBinding import com.example.fragment.module.user.model.UserViewModel class LoginFragment : RouterFragment() { private val viewModel: UserViewModel by viewModels() private var _binding: FragmentLoginBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentLoginBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun initView() { binding.black.setOnClickListener { activity.onBackPressed() } binding.username.addKeyboardListener(binding.root) binding.password.addKeyboardListener(binding.root) binding.login.setOnClickListener { val username = binding.username.text.toString() val password = binding.password.text.toString() if (checkParameter(username, password)) { viewModel.login(username, password) } } binding.register.setOnClickListener { activity.navigation(Router.LOGIN_TO_REGISTER) } } override fun initViewModel() { viewModel.loginResult.observe(viewLifecycleOwner) { result -> when { result.errorCode == "0" -> { result.data?.apply { WanHelper.setUser(this) } activity.onBackPressed() } result.errorCode.isNotBlank() && result.errorMsg.isNotBlank() -> { activity.showTips(result.errorMsg) } } } } override fun onLoad() { } private fun checkParameter(username: String, password: String): Boolean { if (username.isBlank()) { activity.showTips("用户名不能为空") return false } if (password.isBlank()) { activity.showTips("密码不能为空") return false } return true } }
0
Kotlin
33
204
cbd04c277155083a1c2d5a2b943ff6b3b42f091a
2,598
FragmentProject
Apache License 2.0
automation/espresso/src/main/kotlin/com/instructure/canvas/espresso/TestAppManager.kt
instructure
179,290,947
false
{"Kotlin": 16085132, "Dart": 4413539, "HTML": 185120, "Ruby": 32390, "Shell": 19157, "Java": 13488, "Groovy": 11717, "JavaScript": 9505, "CSS": 1356, "Swift": 404, "Dockerfile": 112, "Objective-C": 37}
/* * Copyright (C) 2024 - present Instructure, Inc. * * 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.instructure.canvas.espresso import androidx.work.WorkerFactory import com.instructure.canvasapi2.AppManager import com.instructure.canvasapi2.utils.RemoteConfigUtils open class TestAppManager: AppManager() { override fun onCreate() { super.onCreate() RemoteConfigUtils.initialize() } var workerFactory: WorkerFactory? = null override fun getWorkManagerFactory(): WorkerFactory { return workerFactory ?: WorkerFactory.getDefaultWorkerFactory() } override fun performLogoutOnAuthError() = Unit }
7
Kotlin
102
127
f82ec380673be5812c88bbc6b15c3d960515c6d8
1,205
canvas-android
Apache License 2.0
wallet-connect/src/main/java/com/paytomat/walletconnect/android/WCEncryptor.kt
paytomat
192,522,428
false
null
package com.paytomat.walletconnect.android import com.paytomat.walletconnect.android.model.WCEncryptionPayload import org.bouncycastle.crypto.digests.SHA256Digest import org.bouncycastle.crypto.macs.HMac import org.bouncycastle.crypto.params.KeyParameter import org.bouncycastle.jce.provider.BouncyCastleProvider import org.bouncycastle.util.encoders.Hex import java.security.SecureRandom import java.security.Security import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec /** * created by Alex Ivanov on 2019-06-12. */ object WCEncryptor { private fun randomBytes(n: Int): ByteArray = ByteArray(n).apply { SecureRandom().nextBytes(this) } private fun computeHMAC(payload: String, iv: String, key: ByteArray): String { val data: ByteArray = Hex.decode(payload) + Hex.decode(iv) return HMac(SHA256Digest()).apply { init(KeyParameter(key)) update(data, 0, data.size) }.let { hmac -> ByteArray(hmac.macSize).apply { hmac.doFinal(this, 0) } }.let { Hex.toHexString(it) } } fun encrypt(data: ByteArray, key: ByteArray): WCEncryptionPayload { val ivBytes: ByteArray = randomBytes(16) Security.addProvider(BouncyCastleProvider()) val encryptedBytes: ByteArray = Cipher.getInstance("AES/CBC/PKCS7PADDING").apply { init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(ivBytes)) }.run { doFinal(data) } val encryptedData: String = Hex.toHexString(encryptedBytes) val iv: String = Hex.toHexString(ivBytes) val hmac: String = computeHMAC(encryptedData, iv, key) return WCEncryptionPayload(encryptedData, hmac, iv) } fun decrypt(payload: WCEncryptionPayload, key: ByteArray): ByteArray { val computedHmac: String = computeHMAC(payload.data, payload.iv, key) if (computedHmac != payload.hmac) { throw WCError.BadServerResponse } Security.addProvider(BouncyCastleProvider()) return Cipher.getInstance("AES/CBC/PKCS7PADDING").apply { init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(Hex.decode(payload.iv))) }.run { doFinal(Hex.decode(payload.data)) } } }
1
Kotlin
3
7
a79d08abf42777d450116fa9e577c292d9d98730
2,315
wallet-connect-android
Apache License 2.0
common/src/main/kotlin/de/sean/splugin/bukkit/tasks/AfkPlayerManager.kt
spnda
356,426,258
false
{"Kotlin": 42971}
package de.sean.splugin.bukkit.tasks import de.sean.splugin.util.Messages.getRandomMessage import org.bukkit.Bukkit import org.bukkit.configuration.file.FileConfiguration import org.bukkit.entity.Player import java.util.* import kotlin.collections.HashMap object AfkPlayerManager { private var initialized: Boolean = false private var markAfkMessages: MutableList<*>? = null private var unmarkAfkMessages: MutableList<*>? = null private val playerLastActivity = HashMap<UUID, Long>() private val afkPlayers = HashMap<UUID, Boolean>() fun init(config: FileConfiguration) { initialized = true markAfkMessages = config.getList("messages.afk", ArrayList<Any>()) unmarkAfkMessages = config.getList("messages.not_afk", ArrayList<Any>()) } fun getLastActivity(player: UUID): Long = playerLastActivity[player] ?: System.currentTimeMillis() fun setLastActivity(player: UUID, time: Long) { playerLastActivity[player] = time } fun isAfk(player: UUID): Boolean = afkPlayers[player] ?: false fun setAfk(player: UUID, value: Boolean) { afkPlayers[player] = value } fun markPlayerAfk(player: Player) { Bukkit.broadcastMessage(getRandomMessage(markAfkMessages).replace("[player]", player.displayName)) player.setDisplayName(player.displayName + " (AFK)") player.setPlayerListName(player.playerListName + " (AFK)") } fun unmarkPlayerAfk(player: Player) { player.setPlayerListName(player.playerListName.replace(" (AFK)", "")) player.setDisplayName(player.displayName.replace(" (AFK)", "")) Bukkit.broadcastMessage(getRandomMessage(unmarkAfkMessages).replace("[player]", player.displayName)) } fun remove(player: Player) { playerLastActivity.remove(player.uniqueId) afkPlayers.remove(player.uniqueId) } }
5
Kotlin
0
2
9843341b0151db22b38284c1b39f97ee0d702105
1,877
SPlugin
MIT License
app/src/main/java/com/rangganf/storyappearly/MyApplication.kt
RanggaNf
820,492,762
false
{"Kotlin": 84236}
package com.rangganf.storyappearly import android.app.Application import coil.ImageLoader import coil.ImageLoaderFactory class MyApplication : Application(), ImageLoaderFactory { // Metode untuk membuat instance baru dari ImageLoader override fun newImageLoader(): ImageLoader { return ImageLoader.Builder(this) .crossfade(true) // Mengaktifkan efek crossfade pada gambar .build() } }
0
Kotlin
0
1
2d25b89fe8cc3f335d6078e3c6c7735a2fda05b0
433
StoryApp
MIT License
firebase-appcheck-library/src/main/java/com/vulcanlabs/appcheck/domain/entity/AppCheckPayload.kt
devswl
779,167,697
false
{"Kotlin": 27108}
package com.vulcanlabs.appcheck.domain.entity data class AppCheckPayload( var sha1: String, var exp: Long, var iat: Long )
0
Kotlin
0
0
db97040072d73b285a1e4a0a65fb404b4376deed
135
Local-AppCheck
MIT License
routing-coroutines/src/main/kotlin/io/javalin/community/routing/coroutines/DefaultContextCoroutinesServlet.kt
javalin
394,095,380
false
null
package io.javalin.community.routing.coroutines import io.javalin.http.Context import java.util.concurrent.ExecutorService import java.util.concurrent.Executors class DefaultContextCoroutinesServlet<CONTEXT>( executorService: ExecutorService = Executors.newCachedThreadPool(), private val contextFactory: (Context) -> CONTEXT ) : CoroutinesServlet<CONTEXT, Unit>( dispatcher = ExclusiveDispatcherWithShutdown(executorService), syncHandler = { ctx, route -> route.handler(contextFactory(ctx)) }, asyncHandler = { ctx, route, _ -> route.handler(contextFactory(ctx)) }, errorConsumer = { _, throwable -> throwable.printStackTrace() } ), GracefullyShutdownableDispatcher { override fun prepareShutdown() { (dispatcher as GracefullyShutdownableDispatcher).prepareShutdown() } override fun completeShutdown() { (dispatcher as GracefullyShutdownableDispatcher).completeShutdown() } }
4
Kotlin
1
6
016eba8cd00ea9baa828e60efaf567ab74c77a17
937
javalin-routing-extensions
MIT License
app/src/main/java/com/xeniac/warrantyroster_manager/warranty_management/presentation/add_warranty/AddWarrantyViewModel.kt
WilliamGates99
397,662,276
false
null
package com.xeniac.warrantyroster_manager.warranty_management.presentation.add_warranty import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.xeniac.warrantyroster_manager.core.domain.repository.PreferencesRepository import com.xeniac.warrantyroster_manager.core.domain.repository.UserRepository import com.xeniac.warrantyroster_manager.util.Constants.ERROR_INPUT_BLANK_EXPIRY_DATE import com.xeniac.warrantyroster_manager.util.Constants.ERROR_INPUT_BLANK_STARTING_DATE import com.xeniac.warrantyroster_manager.util.Constants.ERROR_INPUT_BLANK_TITLE import com.xeniac.warrantyroster_manager.util.Constants.ERROR_INPUT_INVALID_STARTING_DATE import com.xeniac.warrantyroster_manager.util.DateHelper import com.xeniac.warrantyroster_manager.util.Event import com.xeniac.warrantyroster_manager.util.Resource import com.xeniac.warrantyroster_manager.util.UiText import com.xeniac.warrantyroster_manager.warranty_management.domain.model.Category import com.xeniac.warrantyroster_manager.warranty_management.domain.model.WarrantyInput import com.xeniac.warrantyroster_manager.warranty_management.domain.repository.CategoryRepository import com.xeniac.warrantyroster_manager.warranty_management.domain.repository.WarrantyRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @HiltViewModel class AddWarrantyViewModel @Inject constructor( private val userRepository: UserRepository, private val categoryRepository: CategoryRepository, private val warrantyRepository: WarrantyRepository, private val preferencesRepository: PreferencesRepository ) : ViewModel() { private val _addWarrantyLiveData: MutableLiveData<Event<Resource<Nothing>>> = MutableLiveData() val addWarrantyLiveData: LiveData<Event<Resource<Nothing>>> = _addWarrantyLiveData fun getCategoryTitleMapKey(): String { val categoryTitleMapKey = preferencesRepository.getCategoryTitleMapKey() Timber.i("Category title map key is $categoryTitleMapKey") return categoryTitleMapKey } fun getAllCategoryTitles(titleMapKey: String): List<String> { val allCategoryTitlesList = categoryRepository.getAllCategoryTitlesList(titleMapKey) Timber.i("All category titles are $allCategoryTitlesList") return allCategoryTitlesList } fun getCategoryById(categoryId: String): Category { val category = categoryRepository.getCategoryById(categoryId) Timber.i("Category found by id is $category") return category } fun getCategoryByTitle(categoryTitle: String): Category { val category = categoryRepository.getCategoryByTitle(categoryTitle) Timber.i("Category found by title is $category") return category } fun validateAddWarrantyInputs( title: String, brand: String?, model: String?, serialNumber: String?, isLifetime: Boolean, startingDateInput: String?, expiryDateInput: String?, description: String?, categoryId: String, selectedStartingDateInMillis: Long, selectedExpiryDateInMillis: Long ) = viewModelScope.launch { safeValidateAddWarrantyInputs( title, brand, model, serialNumber, isLifetime, startingDateInput, expiryDateInput, description, categoryId, selectedStartingDateInMillis, selectedExpiryDateInMillis ) } private fun safeValidateAddWarrantyInputs( title: String, brand: String?, model: String?, serialNumber: String?, isLifetime: Boolean, startingDateInput: String?, expiryDateInput: String?, description: String?, categoryId: String, selectedStartingDateInMillis: Long, selectedExpiryDateInMillis: Long ) { if (title.isBlank()) { _addWarrantyLiveData.postValue( Event(Resource.Error(UiText.DynamicString(ERROR_INPUT_BLANK_TITLE))) ) return } if (startingDateInput.isNullOrBlank()) { _addWarrantyLiveData.postValue( Event(Resource.Error(UiText.DynamicString(ERROR_INPUT_BLANK_STARTING_DATE))) ) return } val isExpiryDateInputBlank = !isLifetime && expiryDateInput.isNullOrBlank() if (isExpiryDateInputBlank) { _addWarrantyLiveData.postValue( Event(Resource.Error(UiText.DynamicString(ERROR_INPUT_BLANK_EXPIRY_DATE))) ) return } val isStartingDateInvalid = !isLifetime && !DateHelper.isStartingDateValid( selectedStartingDateInMillis, selectedExpiryDateInMillis ) if (isStartingDateInvalid) { _addWarrantyLiveData.postValue( Event(Resource.Error(UiText.DynamicString(ERROR_INPUT_INVALID_STARTING_DATE))) ) return } val warrantyInput = WarrantyInput( title, brand, model, serialNumber, isLifetime, startingDateInput, expiryDateInput, description, categoryId, userRepository.getCurrentUserUid() ) addWarrantyToFirestore(warrantyInput) } fun addWarrantyToFirestore(warrantyInput: WarrantyInput) = viewModelScope.launch { safeAddWarrantyToFirestore(warrantyInput) } private suspend fun safeAddWarrantyToFirestore(warrantyInput: WarrantyInput) { _addWarrantyLiveData.postValue(Event(Resource.Loading())) try { warrantyRepository.addWarrantyToFirestore(warrantyInput) _addWarrantyLiveData.postValue(Event(Resource.Success())) Timber.i("Warranty successfully added.") } catch (e: Exception) { Timber.e("safeAddWarrantyToFirestore Exception: ${e.message}") _addWarrantyLiveData.postValue(Event(Resource.Error(UiText.DynamicString(e.message.toString())))) } } }
1
Kotlin
2
6
286000e0e7702c1afc8cc78b75270310c6fc5b2c
6,081
WarrantyRoster
Apache License 2.0
app/src/main/java/com/thuatnguyen/tindersample/ui/UserViewModel.kt
nthuat
291,731,207
false
null
package com.thuatnguyen.tindersample.ui import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.thuatnguyen.tindersample.model.Result import com.thuatnguyen.tindersample.model.User import com.thuatnguyen.tindersample.model.data import com.thuatnguyen.tindersample.model.isSucceeded import com.thuatnguyen.tindersample.repository.UserRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class UserViewModel @ViewModelInject constructor( private val userRepository: UserRepository ) : ViewModel() { private val _userLiveData = MutableLiveData<Result<List<User>>>() val userLiveData: LiveData<Result<List<User>>> = _userLiveData fun getUsers(isFavoriteUserMode: Boolean) { if (isFavoriteUserMode) { getFavoriteUsers() } else { getUsersFromNetwork() } } fun getUsersFromNetwork() { viewModelScope.launch { userRepository.getUsersFromNetwork().collect { _userLiveData.value = it } } } private fun getFavoriteUsers() { viewModelScope.launch { userRepository.getFavoriteUsersFromLocal().collect { _userLiveData.value = it } } } fun saveFavoriteUser(position: Int) { viewModelScope.launch { userLiveData.value?.let { if (it.isSucceeded) { val userList = it.data!! if (position in userList.indices) { userRepository.saveFavoriteUser(userList[position]) } } } } } fun resetUserData() { _userLiveData.value = null } }
0
Kotlin
1
3
5a8d5dbf0d4851c66794ec72dc4a3879ea58357c
1,922
tinder-sample
Apache License 2.0
thunder-stomp/src/main/java/com/jeremy/thunder/stomp/internal/StompStateManager.kt
jaeyunn15
671,450,093
false
{"Kotlin": 101963}
package com.jeremy.thunder.stomp.internal import com.jeremy.thunder.stomp.compiler.MessageCompiler.compileMessage import com.jeremy.thunder.stomp.compiler.thunderStompRequest import com.jeremy.thunder.stomp.model.ACK import com.jeremy.thunder.stomp.model.Command import com.jeremy.thunder.stomp.model.DEFAULT_ACK import com.jeremy.thunder.stomp.model.DESTINATION import com.jeremy.thunder.stomp.model.ID import com.jeremy.thunder.stomp.model.SUPPORTED_VERSIONS import com.jeremy.thunder.stomp.model.VERSION import com.jeremy.thunder.thunder_internal.AppConnectionListener import com.jeremy.thunder.thunder_internal.NetworkConnectivityService import com.jeremy.thunder.thunder_internal.StateManager import com.jeremy.thunder.thunder_internal.WebSocket import com.jeremy.thunder.thunder_internal.cache.BaseRecovery import com.jeremy.thunder.thunder_internal.cache.BaseValve import com.jeremy.thunder.thunder_internal.cache.ICacheController import com.jeremy.thunder.thunder_internal.event.StompRequest import com.jeremy.thunder.thunder_internal.event.ThunderRequest import com.jeremy.thunder.thunder_state.WebSocketEvent import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.plus import kotlinx.coroutines.withContext import java.util.UUID class StompStateManager private constructor( private val connectionListener: AppConnectionListener, private val networkState: NetworkConnectivityService, private val recoveryCache: BaseRecovery<ThunderRequest>, private val valveCache: BaseValve<ThunderRequest>, private val webSocketCore: WebSocket.Factory, private val scope: CoroutineScope ): StateManager { private val innerScope = scope + CoroutineExceptionHandler { _, throwable -> } private var socket: WebSocket? = null private val _connectState = MutableStateFlow<com.jeremy.thunder.thunder_state.ConnectState>(com.jeremy.thunder.thunder_state.ConnectState.Initialize) private val _events = MutableSharedFlow<WebSocketEvent>(replay = 1) private val headerIdStore by lazy { HeaderIdStore() } override fun getStateOfType(): com.jeremy.thunder.thunder_state.ManagerState { return com.jeremy.thunder.thunder_state.StompManager } override fun collectWebSocketEvent() = _events.asSharedFlow() init { _connectState.map(valveCache::onUpdateValve).launchIn(innerScope) connectionListener.collectAppState() .mapLatest { appState -> when (appState) { com.jeremy.thunder.thunder_state.Inactive -> { recoveryProcess() false } com.jeremy.thunder.thunder_state.Active -> { true } } }.combine(networkState.networkStatus) { upStreamState, networkState -> if (upStreamState) { when (networkState) { com.jeremy.thunder.thunder_state.NetworkState.Unavailable -> { recoveryProcess() false } com.jeremy.thunder.thunder_state.NetworkState.Available -> { true } } } else false }.combine(_events) { upStreamState, webSocketEvent -> if (upStreamState) { when (webSocketEvent) { is WebSocketEvent.OnMessageReceived -> Unit is WebSocketEvent.OnConnectionOpen -> { _connectState.update { com.jeremy.thunder.thunder_state.ConnectState.Establish } } WebSocketEvent.OnConnectionClosed -> { _connectState.update { com.jeremy.thunder.thunder_state.ConnectState.ConnectClose() } } is WebSocketEvent.OnConnectionError -> { _connectState.update { com.jeremy.thunder.thunder_state.ConnectState.ConnectError( com.jeremy.thunder.thunder_state.ThunderError.SocketLoss(webSocketEvent.error) ) } recoveryProcess() } } } }.onStart { openConnection {} }.launchIn(innerScope) combine( _connectState, valveCache.emissionOfValveFlow(), ) { connectState, valve -> if (connectState is com.jeremy.thunder.thunder_state.ConnectState.Establish) { valve.forEach(::requestExecute) } }.launchIn(innerScope) } private suspend fun recoveryProcess() { connectionRecoveryProcess { requestRecoveryProcess() } } private suspend fun checkOnValidState(): Boolean = withContext(Dispatchers.Default) { val appState = connectionListener.collectAppState().firstOrNull() val networkState = networkState.networkStatus.firstOrNull() appState == com.jeremy.thunder.thunder_state.Active && networkState == com.jeremy.thunder.thunder_state.NetworkState.Available } private suspend fun connectionRecoveryProcess(onConnect: () -> Unit) { if (checkOnValidState()) { retryConnection( onConnect = onConnect, ) } } private fun requestRecoveryProcess() { if (recoveryCache.hasCache()) { val request = recoveryCache.get() val webSocketRequest = (request as StompRequest) valveCache.requestToValve(webSocketRequest) recoveryCache.clear() } } override fun retryConnection(onConnect: () -> Unit) { closeConnection { openConnection(onConnect) } } private fun requestExecute(message: ThunderRequest) = innerScope.launch(Dispatchers.IO) { val request = message as StompRequest when (request.command) { Command.SUBSCRIBE.name.lowercase() -> { subscribe( topic = request.destination, payload = request.payload.orEmpty() ) } Command.UNSUBSCRIBE.name.lowercase() -> { unsubscribe( topic = request.destination ) } Command.SEND.name.lowercase() -> { sendMessage( topic = request.destination, payload = request.payload.orEmpty() ) } else -> { // not implement yet } } } /** * After sending data using the socket, we store it in the recovery cache only after receiving a completion for the event. * */ private fun sendMessage(topic: String, payload: String) { socket?.let { runCatching { val uuid = UUID.randomUUID().toString() headerIdStore.put(topic, uuid) it.send( compileMessage( thunderStompRequest { this.command = Command.SEND header { ID to uuid DESTINATION to topic ACK to DEFAULT_ACK } this.payload = payload } ) ) } } } override fun openConnection(onConnect: () -> Unit) = synchronized(this) { if (socket == null) { socket = webSocketCore.create() socket?.let { webSocket -> webSocket.open().onEach { if (it is WebSocketEvent.OnConnectionOpen) { onConnect.invoke() webSocket.send( compileMessage( thunderStompRequest { command = Command.CONNECT header { VERSION to SUPPORTED_VERSIONS } } ) ) } _events.tryEmit(it) }.launchIn(innerScope) } } } override fun closeConnection(onDisconnect: () -> Unit): Unit = synchronized(this) { socket?.let { websocket -> websocket.close(1000, "shutdown") socket = null headerIdStore.clear() onDisconnect.invoke() } } override fun send(message: ThunderRequest) { val request = message as StompRequest valveCache.requestToValve(request) recoveryCache.set(request) } private fun subscribe(topic: String, payload: String) { socket?.let { websocket -> runCatching { val uuid = UUID.randomUUID().toString() headerIdStore.put(topic, uuid) websocket.send( compileMessage( thunderStompRequest { command = Command.SUBSCRIBE header { ID to uuid DESTINATION to topic ACK to DEFAULT_ACK } this.payload = payload } ) ) } } } private fun unsubscribe(topic: String) { socket?.let { websocket -> runCatching { websocket.send( compileMessage( thunderStompRequest { this.command = Command.UNSUBSCRIBE header { ID to headerIdStore[topic] DESTINATION to topic ACK to DEFAULT_ACK } } ) ) } } } class Factory: StateManager.Factory { override fun create( connectionListener: AppConnectionListener, networkStatus: NetworkConnectivityService, cacheController: ICacheController<ThunderRequest>, webSocketCore: WebSocket.Factory ): StateManager { return StompStateManager( connectionListener = connectionListener, networkState = networkStatus, recoveryCache = cacheController.getRecovery(), valveCache = cacheController.getValve(), webSocketCore = webSocketCore, scope = CoroutineScope(SupervisorJob()) ) } } companion object { private const val RETRY_CONNECTION_GAP = 1_000L } }
0
Kotlin
1
10
35d2241cdaf742b4cd052cb38f2ba5964144aa95
11,879
Thunder
MIT License
core/domain/src/main/java/com/example/domain/model/Text.kt
olex-st
648,748,909
false
null
package com.example.domain.model sealed interface Text
0
Kotlin
0
0
7aa43826809330ce4a3aaf7063239023193c547e
56
DeutscheBankChallenge
Apache License 2.0
churros/src/main/java/com/asapp/churros/rx/RegulatedBuffer.kt
asappinc
224,284,112
false
null
package com.asapp.churros.rx import io.reactivex.Observable import io.reactivex.Observer import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.disposables.Disposable import io.reactivex.subjects.PublishSubject import java.util.concurrent.TimeUnit fun <T, S> Observable<T>.regulatedBuffer( initialBatchSize: Int, initialTimeSpan: Long, timeUnit: TimeUnit, scheduler: Scheduler, getNewBatchSize: (S) -> Int, getNewTimeSpan: (S) -> Long, callBack: (List<T>) -> Single<S> ): Observable<S> = lift { RegulatedBufferObserver( it, initialBatchSize, initialTimeSpan, timeUnit, scheduler, getNewBatchSize, getNewTimeSpan, callBack ) } class RegulatedBufferObserver<T, S>( private val child: Observer<in S>, initialBatchSize: Int, initialTimeSpan: Long, private val timeUnit: TimeUnit, private val scheduler: Scheduler, private val getNewBatchSize: (S) -> Int, private val getNewTimeSpan: (S) -> Long, private val callBack: (List<T>) -> Single<S> ) : Observer<T>, Disposable { private val internalSubject = PublishSubject.create<T>() private var batchSize = initialBatchSize private var timeSpan = initialTimeSpan private var internalDisposable: Disposable? = null private var mainDisposable: Disposable? = null override fun onComplete() { if (mainDisposable?.isDisposed == true) { return } child.onComplete() } override fun onSubscribe(disposable: Disposable) { mainDisposable = disposable child.onSubscribe(this) } override fun onNext(t: T) { if (mainDisposable?.isDisposed == true) { return } if (internalDisposable == null) { internalDisposable = internalSubject.buffer(timeSpan, timeUnit, scheduler, batchSize) .flatMapSingle { callBack(it) } .subscribe ({ val newBatchSize = getNewBatchSize(it) val newTimeSpan = getNewTimeSpan(it) if (batchSize != newBatchSize || timeSpan != newTimeSpan) { batchSize = newBatchSize timeSpan = newTimeSpan internalDisposable!!.dispose() internalDisposable = null } child.onNext(it) }) { child.onError(it) } } internalSubject.onNext(t) } override fun onError(throwable: Throwable) { if (mainDisposable?.isDisposed == true) { return } child.onError(throwable) } override fun isDisposed(): Boolean = mainDisposable?.isDisposed ?: false override fun dispose() { internalDisposable?.dispose() } }
2
Kotlin
1
6
6688ab4f93a8ecfb5a47acca62c7c037a1eb97ca
2,963
churros
MIT License
app/src/main/java/com/ahmetroid/popularmovies/network/Api.kt
ahmetturk
239,481,816
false
null
package com.ahmetroid.popularmovies.network import com.ahmetroid.popularmovies.BuildConfig.TMDB_API_KEY import com.squareup.moshi.Moshi import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory private const val BASE_URL = "https://api.themoviedb.org/3/" private const val QUERY_PARAMETER_API = "api_key" private val moshi = Moshi.Builder().build() private val okHttpClient = OkHttpClient.Builder() .addInterceptor { chain -> val httpUrl = chain.request().url().newBuilder() .addQueryParameter(QUERY_PARAMETER_API, TMDB_API_KEY) .build() val request = chain.request().newBuilder() .url(httpUrl) .build() return@addInterceptor chain.proceed(request) } .build() private val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .client(okHttpClient) .baseUrl(BASE_URL) .build() object Api { lateinit var language: String val service: ApiService by lazy { retrofit.create(ApiService::class.java) } }
0
Kotlin
0
1
a3d5dd777af78bf67117aa47041d5cca34938c9a
1,097
Sinemate
Apache License 2.0
app/src/main/java/com/jamesm10101/astraeus/data/Epic.kt
JamesM10101
665,791,630
false
{"Kotlin": 182016}
package com.jamesm10101.astraeus.data import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverter import androidx.room.TypeConverters import com.squareup.moshi.Json import kotlinx.parcelize.Parcelize /** * This class provides type converters for Room database. * * @see [com.jamesm10101.astraeus.data.Epic] */ class EpicConverters { /** * Converts coordinates to a string. * * @param coordinates The coordinates to convert. * @return A string representation of the coordinates. */ @TypeConverter fun fromCoordinates(coordinates: Coordinates): String { return "${coordinates.lat},${coordinates.lon}" } /** * Converts a string to coordinates. * * @param coordinatesString The string to convert. * @return A Coordinates object. */ @TypeConverter fun toCoordinates(coordinatesString: String): Coordinates { val (lat, lon) = coordinatesString.split(",") return Coordinates(lat.toFloat(), lon.toFloat()) } /** * Converts satellite position to a string. * * @param position The satellite position to convert. * @return A string representation of the satellite position. */ @TypeConverter fun fromSatPosition(position: SatellitePosition): String { return "${position.x},${position.y},${position.z}" } /** * Converts a string to satellite position. * * @param position The string to convert. * @return A SatellitePosition object. */ @TypeConverter fun toSatPosition(position: String): SatellitePosition { val (x, y, z) = position.split(",") return SatellitePosition(x.toFloat(), y.toFloat(), z.toFloat()) } /** * Converts attitude quaternions to a string. * * @param quaternions The attitude quaternions to convert. * @return A string representation of the attitude quaternions. */ @TypeConverter fun fromAttQuaternions(quaternions: AttitudeQuaternions): String { return "${quaternions.q0},${quaternions.q1},${quaternions.q2},${quaternions.q3}" } /** * Converts a string to attitude quaternions. * * @param quaternions The string to convert. * @return An AttitudeQuaternions object. */ @TypeConverter fun toAttQuaternions(quaternions: String): AttitudeQuaternions { val (q0, q1, q2, q3) = quaternions.split(",") return AttitudeQuaternions(q0.toFloat(), q1.toFloat(), q2.toFloat(), q3.toFloat()) } } @Parcelize @Entity(tableName = "epics") @TypeConverters(EpicConverters::class) data class Epic( @PrimaryKey @Json(name = "identifier") val id: String, @Json(name = "caption") val caption: String, @Json(name = "image") val image: String, var imgSrcUrl: String?, @Json(name = "version") val version: String, @Json(name = "date") val date: String, @Json(name = "centroid_coordinates") val centroidCoords: Coordinates, @Json(name = "dscovr_j2000_position") val dscovrPos: SatellitePosition, @Json(name = "lunar_j2000_position") val lunarPos: SatellitePosition, @Json(name = "sun_j2000_position") val sunPos: SatellitePosition, @Json(name = "attitude_quaternions") val attQuaternions: AttitudeQuaternions, ) : Parcelable
0
Kotlin
0
0
f81f4400e5fedd31acd5b24858a6cf5cbfba3c66
3,344
Astraeus
MIT License
src/main/kotlin/com/fernandosini/storeapikotlin/data/models/OrderStatus.kt
FernandoSini
766,205,667
false
{"Kotlin": 26904}
package com.fernandosini.storeapikotlin.data.models enum class OrderStatus { Processing, WaitingPayment, Rejected, Finished, Dispatched, Delivered,Closed }
0
Kotlin
0
0
6e8e907d7fa6cbc410a230950637c14929d8ebbb
168
store-kotlin
MIT License
library/src/main/java/com/github/lcdsmao/springx/ViewPropertySpringAnimator.kt
yongju-jin
212,013,196
true
{"Kotlin": 14220, "Java": 1115}
package com.github.lcdsmao.springx import android.view.View import androidx.annotation.MainThread import androidx.core.view.ViewCompat import androidx.dynamicanimation.animation.DynamicAnimation import androidx.dynamicanimation.animation.SpringAnimation import androidx.dynamicanimation.animation.SpringForce class ViewPropertySpringAnimator( private val view: View ) { interface AnimatorListener { fun onAnimationStart(animator: ViewPropertySpringAnimator) {} fun onAnimationCancel(animator: ViewPropertySpringAnimator) {} fun onAnimationEnd(animator: ViewPropertySpringAnimator) {} } private val pendingAnimations = mutableListOf<SpringAnimationHolder>() private val runningAnimations = mutableMapOf<DynamicAnimation.ViewProperty, SpringAnimation>() val isRunning: Boolean get() = runningAnimations.isNotEmpty() private var defaultDampingRatio: Float = SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY private var defaultStiffness: Float = SpringForce.STIFFNESS_MEDIUM private var animatorListener: AnimatorListener? = null fun defaultDampingRatio(value: Float) = apply { defaultDampingRatio = value } fun defaultStiffness(value: Float) = apply { defaultStiffness = value } fun x( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.X, finalValue, config) } fun xBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.X, finalValue, config) } fun y( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.Y, finalValue, config) } fun yBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.Y, finalValue, config) } fun z( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.Z, finalValue, config) } fun zBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.Z, finalValue, config) } fun rotation( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.ROTATION, finalValue, config) } fun rotationBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.ROTATION, finalValue, config) } fun rotationX( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.ROTATION_X, finalValue, config) } fun rotationXBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.ROTATION_X, finalValue, config) } fun rotationY( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.ROTATION_Y, finalValue, config) } fun rotationYBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.ROTATION_Y, finalValue, config) } fun translationX( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.TRANSLATION_X, finalValue, config) } fun translationXBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.TRANSLATION_X, finalValue, config) } fun translationY( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.TRANSLATION_Y, finalValue, config) } fun translationYBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.TRANSLATION_Y, finalValue, config) } fun translationZ( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.TRANSLATION_Z, finalValue, config) } fun translationZBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.TRANSLATION_Z, finalValue, config) } fun scaleX( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.SCALE_X, finalValue, config) } fun scaleXBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.SCALE_X, finalValue, config) } fun scaleY( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.SCALE_Y, finalValue, config) } fun scaleYBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.SCALE_Y, finalValue, config) } fun alpha( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animateProperty(DynamicAnimation.ALPHA, finalValue, config) } fun alphaBy( finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ): ViewPropertySpringAnimator = apply { animatePropertyBy(DynamicAnimation.ALPHA, finalValue, config) } private fun animateProperty( property: DynamicAnimation.ViewProperty, finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ) { animateProperty(property, finalValue, 0f, config) } private fun animatePropertyBy( property: DynamicAnimation.ViewProperty, finalValue: Float, config: SpringAnimationConfig.() -> Unit = {} ) { animateProperty(property, finalValue, getViewValue(property), config) } private fun animateProperty( property: DynamicAnimation.ViewProperty, finalValue: Float, finalValueBias: Float, configBuilder: SpringAnimationConfig.() -> Unit = {} ) { var anim = runningAnimations[property] if (anim == null) { anim = SpringAnimation(view, property) anim.createEndListener(property) runningAnimations[property] = anim } val config = SpringAnimationConfig(finalValue).apply(configBuilder) config.defaultDampingRatio = defaultDampingRatio config.defaultStiffness = defaultStiffness config.finalValueBias = finalValueBias pendingAnimations += SpringAnimationHolder(anim, config) } private fun getViewValue(property: DynamicAnimation.ViewProperty): Float { return when (property) { DynamicAnimation.TRANSLATION_X -> view.translationX DynamicAnimation.TRANSLATION_Y -> view.translationY DynamicAnimation.TRANSLATION_Z -> ViewCompat.getTranslationZ(view) DynamicAnimation.ROTATION -> view.rotation DynamicAnimation.ROTATION_X -> view.rotationX DynamicAnimation.ROTATION_Y -> view.rotationY DynamicAnimation.SCALE_X -> view.scaleX DynamicAnimation.SCALE_Y -> view.scaleY DynamicAnimation.X -> view.x DynamicAnimation.Y -> view.y DynamicAnimation.Z -> ViewCompat.getZ(view) DynamicAnimation.ALPHA -> view.alpha else -> 0f } } private fun SpringAnimation.createEndListener( property: DynamicAnimation.ViewProperty ) { val listener = object : DynamicAnimation.OnAnimationEndListener { override fun onAnimationEnd( animation: DynamicAnimation<out DynamicAnimation<*>>?, canceled: Boolean, value: Float, velocity: Float ) { runningAnimations.remove(property) animation?.removeEndListener(this) if (runningAnimations.isEmpty() && !canceled) { animatorListener?.onAnimationEnd(this@ViewPropertySpringAnimator) } } } addEndListener(listener) } @MainThread fun start(): ViewPropertySpringAnimator = apply { val animations = pendingAnimations.toList() pendingAnimations.clear() animatorListener?.onAnimationStart(this) animations.forEach { it.start() } } @MainThread fun cancel() { pendingAnimations.clear() val animations = runningAnimations.values.toList() runningAnimations.clear() animations.forEach { it.cancel() } animatorListener?.onAnimationCancel(this) } @MainThread fun skipToEnd() { pendingAnimations.clear() val animations = runningAnimations.values.toList() animations.filter { it.canSkipToEnd() } .forEach { it.skipToEnd() } } fun setListener( onStart: (animator: ViewPropertySpringAnimator) -> Unit = {}, onCancel: (animator: ViewPropertySpringAnimator) -> Unit = {}, onEnd: (animator: ViewPropertySpringAnimator) -> Unit = {} ) = setListener(object : AnimatorListener { override fun onAnimationStart(animator: ViewPropertySpringAnimator) { onStart(animator) } override fun onAnimationCancel(animator: ViewPropertySpringAnimator) { onCancel(animator) } override fun onAnimationEnd(animator: ViewPropertySpringAnimator) { onEnd(animator) } }) fun setListener(listener: AnimatorListener?) = apply { this.animatorListener = listener } fun removeUpdateListener(listener: DynamicAnimation.OnAnimationUpdateListener) { runningAnimations.forEach { (_, animation) -> animation.removeUpdateListener(listener) } } fun removeEndListener(listener: DynamicAnimation.OnAnimationEndListener) { runningAnimations.forEach { (_, animation) -> animation.removeEndListener(listener) } } }
0
null
0
0
170204ef34a196bc9cd86676f46da9415ea926de
10,307
SpringX
Apache License 2.0
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/experimental/internal/KotlinNativeUsage.kt
qwwdfsad
139,408,015
true
{"Kotlin": 3888671, "C++": 813655, "Groovy": 137514, "C": 120803, "Objective-C++": 66761, "Swift": 29084, "JavaScript": 19264, "Python": 8631, "Shell": 8167, "Batchfile": 6974, "Objective-C": 3532, "Pascal": 1698, "Java": 782, "HTML": 185}
package org.jetbrains.kotlin.gradle.plugin.experimental.internal object KotlinNativeUsage { const val KLIB = "kotlin-native-klib" }
0
Kotlin
0
0
6d561bd45cac508cddcc89589fb53a89323f5416
137
kotlin-native
Apache License 2.0
src/commonMain/kotlin/Loader.kt
AtriKawaii
531,817,304
false
null
import kotlinx.cinterop.* import kotlinx.cinterop.internal.CStruct import platform.posix.size_t import platform.posix.uint16_t import platform.posix.uint8_t import values.RustStr import atri_manager.AtriManager as CAtriManager @CStruct("AtriVTable") data class AtriVTable( val log: CPointer<CFunction<(handle: size_t, manager: COpaquePointer, level: uint8_t, log: CValue<RustStr>) -> Unit>> ) data class AtriManager( val handle: size_t, val managerPtr: COpaquePointer, val getFun: CPointer<CFunction<(uint16_t) -> COpaquePointer>> ) lateinit var ATRI_MANAGER: AtriManager private set lateinit var ATRI_VTABLE: AtriVTable private set @CName("kotlin_atri_manager_init") @Suppress("unused") fun atriManagerInit(m: CAtriManager) { ATRI_MANAGER = AtriManager( m.handle, m.manager_ptr!!, m.get_fun!!.reinterpret() ) val getFun = ATRI_MANAGER.getFun val vtable = AtriVTable( log = getFun(20000u).reinterpret() ) ATRI_VTABLE = vtable }
0
Kotlin
0
1
c946d75bf463cd65b1c2f07e32732942fd2cbfe5
1,014
atri_kotlin
MIT License
app/src/main/java/com/itl/kg/androidlabkt/nevigationLab/mvvm/NavLabRegisterViewModel.kt
KenGuerrilla
364,918,808
false
null
package com.itl.kg.androidlabkt.nevigationLab.mvvm import android.content.Context import androidx.lifecycle.ViewModel import com.itl.kg.androidlabkt.nevigationLab.repository.NavLabDatabase import com.itl.kg.androidlabkt.nevigationLab.repository.NavLabAccountPreferencesHelper /** * RegisterViewModel - 管理註冊流程資料操作 */ class NavRegisterViewModel : ViewModel() { companion object { const val TAG = "NavRegisterViewModel" } private var registerUnit: NavRegisterUnit? = null fun setRegisterAccount(account: String, password: String) { registerUnit = NavRegisterUnit(account, password) } // 儲存註冊資訊 fun saveAccountInfo(context: Context) { registerUnit?.run { registerAccount(this) saveToPreferences(this, context) } } private fun saveToPreferences(unit: NavRegisterUnit, context: Context) { NavLabAccountPreferencesHelper.also { sp -> sp.setAccount(unit.account, context) } } private fun registerAccount(unit: NavRegisterUnit) { NavLabDatabase.register(unit.account, unit.password) } } data class NavRegisterUnit ( val account: String, val password: String )
0
Kotlin
0
0
4cd76444bb1a0f9f123444c2042ba1d953dc9831
1,212
AndroidLabKT
Apache License 2.0
app/src/main/java/com/fitmate/fitmate/data/source/CertificationConverters.kt
Workout-Study
770,138,955
false
{"Kotlin": 355008, "Java": 2038}
package com.fitmate.fitmate.data.source import android.net.Uri import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.GsonBuilder import java.net.URI import java.time.Instant class CertificationConverters { @TypeConverter fun listToJson(list: MutableList<Uri>): String { if (list.isEmpty()) { return "" } val value = StringBuilder() for ((index, uri) in list.withIndex()) { value.append(uri.toString()) if (index < list.size - 1) { value.append(",") } } return value.toString() } @TypeConverter fun jsonToList(value: String): MutableList<Uri> { val listType = mutableListOf<Uri>() val array = value.split(",").toTypedArray() for (item in array) { listType.add(Uri.parse(item)) } return listType } @TypeConverter fun fromInstantToString(instant: Instant?): String? { return instant?.toString() } @TypeConverter fun fromStringToInstant(string: String?): Instant? { return string?.let { Instant.parse(it) } } @TypeConverter fun fromStringList(list: List<String>?): String? { return list?.joinToString(separator = ",") } @TypeConverter fun toStringList(string: String?): List<String>? { return string?.split(",")?.map { it.trim() } } }
23
Kotlin
0
0
053aadeefededd934be756804b10650fb2449c12
1,437
WorkoutStudy_Android
The Unlicense
app/src/main/java/com/shhatrat/loggerek/activities/ConfigActivity.kt
Shhatrat
94,308,787
false
null
package com.shhatrat.loggerek.activities import android.app.getKoin import android.content.Intent import android.graphics.Color import android.support.v4.app.Fragment import android.view.View.GONE import android.view.View.VISIBLE import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.AccountHeaderBuilder import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.DrawerBuilder import com.mikepenz.materialdrawer.holder.BadgeStyle import com.mikepenz.materialdrawer.holder.StringHolder import com.mikepenz.materialdrawer.model.DividerDrawerItem import com.mikepenz.materialdrawer.model.PrimaryDrawerItem import com.mikepenz.materialdrawer.model.ProfileDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import com.shhatrat.loggerek.R import com.shhatrat.loggerek.fragments.LogFragment import com.shhatrat.loggerek.fragments.SettingsFragment import com.shhatrat.loggerek.fragments.StatusFragment import com.shhatrat.loggerek.fragments.UnsendFragment import com.shhatrat.loggerek.models.Data import com.shhatrat.loggerek.models.Unsend import com.shhatrat.loggerek.models.User import io.realm.Realm import kotlinx.android.synthetic.main.activity_config.* import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt import java.net.URLEncoder class ConfigActivity : android.support.v7.app.AppCompatActivity() { var autorization = false var o : com.shhatrat.loggerek.api.OAuth? = null val parameters = "username|caches_found|caches_notfound|caches_hidden|profile_url|home_location" val ret by lazy {getKoin().get<com.shhatrat.loggerek.api.Api>()} val realm by lazy{getKoin().get<Realm>()} lateinit var header : AccountHeader lateinit var drawer : Drawer var STATUS = "Status" var UNSEND = "Unsend" var GOOD = "Good" var BAD = "Bad" var DEFAULT = "Default" var SETTINGS = "Settings" var LOGOUT = "Logout" var HELP = "Help" override fun onCreate(savedInstanceState: android.os.Bundle?) { super.onCreate(savedInstanceState) setContentView(com.shhatrat.loggerek.R.layout.activity_config) STATUS = getString(R.string.status) UNSEND = getString(R.string.unsend) GOOD = getString(R.string.good) BAD = getString(R.string.bad) DEFAULT = getString(R.string.defaultL) SETTINGS = getString(R.string.settings) LOGOUT = getString(R.string.logout) HELP = getString(R.string.help) val toolbar = findViewById(com.shhatrat.loggerek.R.id.toolbar) as android.support.v7.widget.Toolbar setSupportActionBar(toolbar) if(!isViewed()) startActivity(Intent(this, IntroActivity::class.java)) o = com.shhatrat.loggerek.api.OAuth(getString(R.string.consumer_key), getString(R.string.consumer_secret)) preapreFab() preapreDrawer() if(isUserLogged()) { replaceFragment(StatusFragment.getInstance()) preapreHeader() } } fun updateBadge(){ drawer.updateBadge(1, StringHolder(realm.where(Unsend::class.java).findAll().count().toString())) } fun getUnsendNumber() = realm.where(Unsend::class.java).findAll().count().toString() fun isViewed(): Boolean = Data.introViewed fun isUserLogged(): Boolean = Data.consumerkey !=null fun preapreFab(){ if(isUserLogged()) fab.visibility = GONE else fab.visibility = VISIBLE fab.setOnClickListener { logUser() autorization = true } } fun logUser() { android.os.AsyncTask.execute { o!!.prepareOAuth(this) } } override fun onResume() { super.onResume() updateBadge() if(autorization) { autorization = false com.afollestad.materialdialogs.MaterialDialog.Builder(this) .title(getString(R.string.set_code)) .positiveText(getString(R.string.ok)) .inputType(android.text.InputType.TYPE_CLASS_TEXT) .input("", " ", com.afollestad.materialdialogs.MaterialDialog.InputCallback { _, input -> finishOAuth(input.toString()) }) .show() } } fun preapreHeader(){ header.addProfile(ProfileDrawerItem().withName(realm.where(User::class.java).findFirst().username).withIcon(R.drawable.logo_oc), 0) } fun preapreDrawer(){ header = AccountHeaderBuilder() .withActivity(this@ConfigActivity) .build() drawer = DrawerBuilder() .withActivity(this@ConfigActivity) .withToolbar(this@ConfigActivity.toolbar) .withAccountHeader(header) .addDrawerItems( PrimaryDrawerItem().withName(STATUS).withTag(STATUS).withIcon(R.drawable.ic_sentiment_very_satisfied_white_24dp), PrimaryDrawerItem().withName(UNSEND).withTag(UNSEND).withIcon(R.drawable.ic_clear_white_24dp).withIdentifier(1).withBadge(getUnsendNumber()).withBadgeStyle(BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_red_700)), DividerDrawerItem(), PrimaryDrawerItem().withName(GOOD).withTag(GOOD).withIcon(R.drawable.ic_sentiment_very_satisfied_white_24dp), PrimaryDrawerItem().withName(BAD).withTag(BAD).withIcon(R.drawable.ic_sentiment_very_dissatisfied_white_24dp), PrimaryDrawerItem().withName(DEFAULT).withTag(DEFAULT).withIcon(R.drawable.ic_tab_white_24dp) ) .withOnDrawerItemClickListener { _, _, drawerItem -> changeFragment(drawerItem) } .addStickyDrawerItems( PrimaryDrawerItem().withName(SETTINGS).withTag(SETTINGS).withIcon(R.drawable.ic_settings_white_24dp), PrimaryDrawerItem().withName(HELP).withTag(HELP).withIcon(R.drawable.abc_ic_menu_selectall_mtrl_alpha), PrimaryDrawerItem().withName(LOGOUT).withTag(LOGOUT).withIcon(R.drawable.ic_exit_to_app_white_24dp)) .build() } fun changeFragment(drawerItem: IDrawerItem<*, *>?): Boolean{ if(drawerItem!!.tag == HELP) startActivity(Intent(this, IntroActivity::class.java)) if(!isUserLogged()) showTip() else { toolbar.title = "${getString(R.string.app_name)} - ${drawerItem.tag}" if(drawerItem.tag == GOOD) replaceFragment(LogFragment.getInstance(LogFragment.Type.GOOD)) if(drawerItem.tag == BAD) replaceFragment(LogFragment.getInstance(LogFragment.Type.BAD)) if(drawerItem.tag == DEFAULT) replaceFragment(LogFragment.getInstance(LogFragment.Type.DEFAULT)) if(drawerItem.tag == STATUS) replaceFragment(StatusFragment.getInstance()) if(drawerItem.tag == UNSEND) replaceFragment(UnsendFragment.getInstance()) if(drawerItem.tag == SETTINGS) replaceFragment(SettingsFragment.getInstance()) if(drawerItem.tag == LOGOUT) logout() } return false } fun replaceFragment(fragemnt : Fragment){ val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.frame, fragemnt) transaction.commit() } fun showTip(){ MaterialTapTargetPrompt.Builder(this) .setTarget(findViewById(R.id.fab)) .setPrimaryText(getString(R.string.add_account)) .setCaptureTouchEventOnFocal(true) .setCaptureTouchEventOutsidePrompt(true) .setSecondaryText("") .show() } fun finishOAuth(dat : String) { android.os.AsyncTask.execute { o!!.okHttpPin(dat, this) ret.getUsername(parameters.getUTF8String()) .subscribeOn(io.reactivex.schedulers.Schedulers.newThread()) .observeOn(io.reactivex.android.schedulers.AndroidSchedulers.mainThread()) .subscribe({ u -> run { realm.addUser(u) preapreFab() preapreHeader() replaceFragment(StatusFragment.getInstance()) } }, { e -> android.util.Log.d("apiLog", e.message) }) } } fun logout(){ realm.deteleAllWithoutMagic() Data.clear() preapreFab() val transaction = supportFragmentManager.beginTransaction() transaction.remove(supportFragmentManager.fragments.get(0)) transaction.commit() header.removeProfile(0) updateBadge() } } fun String.getUTF8String() :String = URLEncoder.encode(this, "UTF-8") private fun Realm.addUser(u: User) { this.beginTransaction() this.copyToRealmOrUpdate(u) this.commitTransaction() } private fun Realm.deteleAllWithoutMagic() { this.beginTransaction() this.deleteAll() this.commitTransaction() }
0
Kotlin
0
0
cf9c633915faa5e622c4d2b9bc9fbace520bfc07
9,436
Loggerek-old
Apache License 2.0
src/main/kotlin/org/cdb/homunculus/logic/StorageLogic.kt
CodeDrillBrigade
714,769,385
false
{"Kotlin": 190419, "Dockerfile": 336}
package org.cdb.homunculus.logic import kotlinx.coroutines.flow.Flow import org.cdb.homunculus.exceptions.NotFoundException import org.cdb.homunculus.models.StorageRoom import org.cdb.homunculus.models.embed.storage.Cabinet import org.cdb.homunculus.models.embed.storage.Shelf import org.cdb.homunculus.models.identifiers.EntityId import org.cdb.homunculus.models.identifiers.Identifier import org.cdb.homunculus.models.identifiers.ShortId interface StorageLogic { /** * Updates an existing [StorageRoom] adding a [Cabinet] to it. If [cabinet] contains no shelves, then a default shelf is added * automatically. * * @param storageRoomId the id of the [StorageRoom] to update. * @param cabinet the [Cabinet] to add. * @return the updated [StorageRoom]. * @throws NotFoundException if the [StorageRoom] does not exist. */ suspend fun addCabinet( storageRoomId: ShortId, cabinet: Cabinet, ): StorageRoom /** * Updates an existing [StorageRoom]'s [Cabinet] adding a [Shelf] to it. * * @param storageRoomId the id of the [StorageRoom] to update. * @param cabinetId the id of the [Cabinet] to update. * @param shelf the [Shelf] to add. * @return the updated [StorageRoom]. * @throws NotFoundException if the [StorageRoom] or the [Cabinet] do not exist. */ suspend fun addShelf( storageRoomId: ShortId, cabinetId: ShortId, shelf: Shelf, ): StorageRoom /** * Creates a new [StorageRoom]. * * @param storage the [StorageRoom] to create. * @return the [EntityId] of the newly created entity. */ suspend fun create(storage: StorageRoom): Identifier /** * Replaces a [StorageRoom] with the one passed as parameter. * * @param storage the [StorageRoom] to update. * @throws NotFoundException if there is no existing room with the id of [storage]. */ suspend fun update(storage: StorageRoom) /** * Replaces a [Cabinet] in the room which [storageRoomId] is passed as parameter. * * @param storageRoomId the id of the [StorageRoom] where the cabinet is. * @param cabinet the [Cabinet] to replace. * @throws NotFoundException if there is no existing room with [storageRoomId] as id or no cabinet with the specified id in * the room. */ suspend fun update( storageRoomId: ShortId, cabinet: Cabinet, ) /** * Replaces a [Shelf] in the cabinet of the room which ids are passed as parameters. * * @param storageRoomId the id of the [StorageRoom] where the cabinet is. * @param cabinetId the is of the [Cabinet] where the shelf is. * @param shelf the [Shelf] to replace. * @throws NotFoundException if there is no existing room with [storageRoomId] as id or no cabinet with the specified id in * the room or no such shelf in the cabinet. */ suspend fun update( storageRoomId: ShortId, cabinetId: ShortId, shelf: Shelf, ) /** * Retrieves all the [StorageRoom]s in the database. * * @return a [Flow] of [StorageRoom]s. */ fun getAll(): Flow<StorageRoom> /** * Deletes a [StorageRoom] by its [entityId]. * * @throws NotFoundException if there is no existing room with [entityId] as id. */ suspend fun delete(entityId: ShortId) /** * Deletes a [Cabinet] in a room. * * @param storageRoomId the id of the [StorageRoom] to delete. * @param cabinetId the id of the [Cabinet] to delete. * @throws NotFoundException if there is no existing room with [storageRoomId] as id or no cabinet with the specified [cabinetId] in * the room. */ suspend fun delete( storageRoomId: ShortId, cabinetId: ShortId, ) /** * Deletes a [Shelf] in a cabinet. * * @param storageRoomId the id of the [StorageRoom] to delete. * @param cabinetId the id of the [Cabinet] to delete. * @param shelfId the id of the [Shelf] to delete. * @throws NotFoundException if there is no existing room with [storageRoomId] as id or no cabinet with the specified [cabinetId] in * the room or no shelf with the specified [shelfId] in the room. */ suspend fun delete( storageRoomId: ShortId, cabinetId: ShortId, shelfId: ShortId, ) }
0
Kotlin
0
0
9830788175ad4ecf8e0a8d8a08b8c1f1c075f4cf
4,056
Homunculus
MIT License
src/jvmTest/kotlin/choliver/nespot/apu/TimerTest.kt
oliver-charlesworth
251,006,755
false
null
package choliver.nespot.apu import choliver.nespot.apu.Timer.Companion.MIN_PERIOD import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow class TimerTest { private val timer = Timer().apply { periodCycles = 4 } @Test fun `generates periodic ticks`() { assertEquals( listOf(0, 0, 0, 1).repeat(3).adjustForStartup(), timer.take(12) ) } @Test fun `generates multi-ticks`() { timer.advance(1) // Ignore startup zero assertEquals(3, timer.advance(12)) } @Test fun `doesn't immediately restart on new period`() { timer.take(1) // Make some progress timer.periodCycles = 3 assertEquals( listOf(0, 0, 1, 0, 0, 1), // If the period immediately reset, then we would expect more leading zeros timer.take(6) ) } @Test fun `disabled if below minimum period`() { timer.periodCycles = MIN_PERIOD - 1 assertEquals( listOf(0).repeat(20).adjustForStartup(), timer.take(20) ) } @Test fun `doesn't divide by zero`() { timer.periodCycles = 0 assertDoesNotThrow { timer.take(20) } } private fun Timer.take(num: Int) = List(num) { advance(1) } // Always an initial tick because pos starts at zero private fun List<Int>.adjustForStartup() = listOf(first() + 1) + drop(1) }
14
Kotlin
0
1
e5d251b82e11f2986e8a732d55298c2ab0de3191
1,385
nespot
MIT License
app/src/main/java/com/gjf/life_demo/utils/SpacingItemDecoration.kt
blacknickwield
405,325,287
false
{"Kotlin": 105340}
package com.gjf.life_demo.utils import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView /*** * 设置RecyclerView中item间距 */ class SpacingItemDecoration(private val padding: Int) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { super.getItemOffsets(outRect, view, parent, state) outRect.top = padding outRect.right = padding outRect.left = padding } }
0
Kotlin
0
0
62479c516374d6d0d77f9dc68f298eaec8bf012f
566
BITMap
MIT License
src/commonTest/kotlin/fr/acinq/lightning/db/PaymentsDbTestsCommon.kt
ACINQ
243,326,972
false
null
package fr.acinq.lightning.db import fr.acinq.bitcoin.Block import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Crypto import fr.acinq.bitcoin.Satoshi import fr.acinq.lightning.* import fr.acinq.lightning.Lightning.randomBytes32 import fr.acinq.lightning.Lightning.randomKey import fr.acinq.lightning.channel.TooManyAcceptedHtlcs import fr.acinq.lightning.payment.FinalFailure import fr.acinq.lightning.payment.PaymentRequest import fr.acinq.lightning.tests.utils.LightningTestSuite import fr.acinq.lightning.tests.utils.runSuspendTest import fr.acinq.lightning.utils.* import fr.acinq.lightning.wire.TemporaryNodeFailure import kotlin.test.* @OptIn(kotlin.time.ExperimentalTime::class) class PaymentsDbTestsCommon : LightningTestSuite() { @Test fun `receive incoming payment with 1 htlc`() = runSuspendTest { val (db, preimage, pr) = createFixture() assertNull(db.getIncomingPayment(pr.paymentHash)) val channelId = randomBytes32() val incoming = IncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr), null, 100) db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr), 100) val pending = db.getIncomingPayment(pr.paymentHash) assertNotNull(pending) assertEquals(incoming, pending) db.receivePayment(pr.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment( amount = 200_000.msat, channelId = channelId, htlcId = 1L )), 110) val received = db.getIncomingPayment(pr.paymentHash) assertNotNull(received) assertEquals(pending.copy(received = IncomingPayment.Received(setOf(IncomingPayment.ReceivedWith.LightningPayment( amount = 200_000.msat, channelId = channelId, htlcId = 1L )), 110)), received) } @Test fun `receive incoming payment with several parts`() = runSuspendTest { val (db, preimage, pr) = createFixture() assertNull(db.getIncomingPayment(pr.paymentHash)) val (channelId1, channelId2, channelId3) = listOf(randomBytes32(), randomBytes32(), randomBytes32()) val incoming = IncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr), null, 200) db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr), 200) val pending = db.getIncomingPayment(pr.paymentHash) assertNotNull(pending) assertEquals(incoming, pending) db.receivePayment(pr.paymentHash, setOf( IncomingPayment.ReceivedWith.LightningPayment(amount = 57_000.msat, channelId = channelId1, htlcId = 1L), IncomingPayment.ReceivedWith.LightningPayment(amount = 43_000.msat, channelId = channelId2, htlcId = 54L), IncomingPayment.ReceivedWith.NewChannel(amount = 99_000.msat, channelId = channelId3, fees = 1_000.msat, id = UUID.randomUUID()) ), 110) val received = db.getIncomingPayment(pr.paymentHash) assertNotNull(received) assertEquals(199_000.msat, received.amount) assertEquals(1_000.msat, received.fees) assertEquals(3, received.received!!.receivedWith.size) assertEquals(57_000.msat, received.received!!.receivedWith.elementAt(0).amount) assertEquals(0.msat, received.received!!.receivedWith.elementAt(0).fees) assertEquals(channelId1, (received.received!!.receivedWith.elementAt(0) as IncomingPayment.ReceivedWith.LightningPayment).channelId) assertEquals(54L, (received.received!!.receivedWith.elementAt(1) as IncomingPayment.ReceivedWith.LightningPayment).htlcId) assertEquals(channelId3, (received.received!!.receivedWith.elementAt(2) as IncomingPayment.ReceivedWith.NewChannel).channelId) } @Test fun `receiving several payments on the same payment hash is additive`() = runSuspendTest { val (db, preimage, pr) = createFixture() val channelId = randomBytes32() db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr), 200) db.receivePayment(pr.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment( amount = 200_000.msat, channelId = channelId, htlcId = 1L )), 110) val received1 = db.getIncomingPayment(pr.paymentHash) assertNotNull(received1) assertNotNull(received1.received) assertEquals(200_000.msat, received1.amount) db.receivePayment(pr.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment( amount = 100_000.msat, channelId = channelId, htlcId = 2L )), 150) val received2 = db.getIncomingPayment(pr.paymentHash) assertNotNull(received2) assertNotNull(received2.received) assertEquals(300_000.msat, received2.amount) assertEquals(150, received2.received!!.receivedAt) assertEquals(setOf( IncomingPayment.ReceivedWith.LightningPayment( amount = 200_000.msat, channelId = channelId, htlcId = 1L ), IncomingPayment.ReceivedWith.LightningPayment( amount = 100_000.msat, channelId = channelId, htlcId = 2L ) ), received2.received!!.receivedWith) } @Test fun `received total amount accounts for the fee`() = runSuspendTest { val (db, preimage, pr) = createFixture() db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr), 200) db.receivePayment(pr.paymentHash, setOf(IncomingPayment.ReceivedWith.NewChannel( id = UUID.randomUUID(), amount = 500_000.msat, fees = 15_000.msat, channelId = randomBytes32() )), 110) val received1 = db.getIncomingPayment(pr.paymentHash) assertNotNull(received1?.received) assertEquals(500_000.msat, received1!!.amount) assertEquals(15_000.msat, received1.fees) } @Test fun `simultaneously add and receive incoming payment`() = runSuspendTest { val db = InMemoryPaymentsDb() val preimage = randomBytes32() val channelId = randomBytes32() val origin = IncomingPayment.Origin.SwapIn("1PwLgmRdDjy5GAKWyp8eyAC4SFzWuboLLb") val receivedWith = setOf(IncomingPayment.ReceivedWith.NewChannel(amount = 50_000_000.msat, fees = MilliSatoshi(1234), channelId = channelId, id = UUID.randomUUID())) assertNull(db.getIncomingPayment(randomBytes32())) db.addAndReceivePayment(preimage = preimage, origin = origin, receivedWith = receivedWith) val payment = db.getIncomingPayment(Crypto.sha256(preimage).toByteVector32()) assertNotNull(payment) assertEquals(origin, payment.origin) assertNotNull(payment.received) assertEquals(receivedWith, payment.received?.receivedWith) assertEquals(50_000_000.msat, payment.amount) assertEquals(1234.msat, payment.fees) } @Test fun `reject duplicate payment hash`() = runSuspendTest { val (db, preimage, pr) = createFixture() db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr)) assertFails { db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr)) } } @Test fun `set expired invoices`() = runSuspendTest { val (db, preimage, _) = createFixture() val pr = createExpiredInvoice(preimage) db.addIncomingPayment(preimage, IncomingPayment.Origin.Invoice(pr)) val expired = db.getIncomingPayment(pr.paymentHash) assertNotNull(expired) assertTrue(expired.isExpired()) assertEquals(IncomingPayment.Origin.Invoice(pr), expired.origin) assertEquals(preimage, expired.preimage) } @Test fun `list received payments`() = runSuspendTest { val (db, pendingPreimage, pending) = createFixture() db.addIncomingPayment(pendingPreimage, IncomingPayment.Origin.Invoice(pending)) assertNull(db.getIncomingPayment(pending.paymentHash)?.received) val expiredPreimage = randomBytes32() val expired = createExpiredInvoice(expiredPreimage) db.addIncomingPayment(expiredPreimage, IncomingPayment.Origin.Invoice(expired)) assertNull(db.getIncomingPayment(expired.paymentHash)?.received) val preimage1 = randomBytes32() val received1 = createInvoice(preimage1) db.addIncomingPayment(preimage1, IncomingPayment.Origin.Invoice(received1)) db.receivePayment(received1.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment(amount = 180_000.msat, channelId = randomBytes32(), 1)), 50) val payment1 = db.getIncomingPayment(received1.paymentHash)!! val preimage2 = randomBytes32() val received2 = createInvoice(preimage2) db.addIncomingPayment(preimage2, IncomingPayment.Origin.SwapIn("1PwLgmRdDjy5GAKWyp8eyAC4SFzWuboLLb")) db.receivePayment(received2.paymentHash, setOf(IncomingPayment.ReceivedWith.NewChannel(UUID.randomUUID(), 180_000.msat, 10_000.msat, channelId = null, )), 60) val payment2 = db.getIncomingPayment(received2.paymentHash)!! val preimage3 = randomBytes32() val received3 = createInvoice(preimage3) db.addIncomingPayment(preimage3, IncomingPayment.Origin.Invoice(received3)) db.receivePayment(received3.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment(amount = 180_000.msat, channelId = randomBytes32(), 1)), 70) val payment3 = db.getIncomingPayment(received3.paymentHash)!! val all = db.listReceivedPayments(count = 10, skip = 0) assertEquals(listOf(payment3, payment2, payment1), all) assertTrue(all.all { it.received != null }) val skipped = db.listReceivedPayments(count = 5, skip = 2) assertEquals(listOf(payment1), skipped) val count = db.listReceivedPayments(count = 1, skip = 1) assertEquals(listOf(payment2), count) val filtered = db.listReceivedPayments(count = 5, skip = 0, filters = setOf(PaymentTypeFilter.Normal)) assertEquals(listOf(payment3, payment1), filtered) val filteredAndSkipped = db.listReceivedPayments(count = 5, skip = 1, filters = setOf(PaymentTypeFilter.Normal)) assertEquals(listOf(payment1), filteredAndSkipped) } @Test fun `send outgoing payment`() = runSuspendTest { val (db, _, pr) = createFixture() val (a, b, c) = listOf(randomKey().publicKey(), randomKey().publicKey(), randomKey().publicKey()) val initialParts = listOf( OutgoingPayment.LightningPart(UUID.randomUUID(), 20_000.msat, listOf(HopDesc(a, c, ShortChannelId(42))), OutgoingPayment.LightningPart.Status.Pending, 100), OutgoingPayment.LightningPart(UUID.randomUUID(), 30_000.msat, listOf(HopDesc(a, b), HopDesc(b, c)), OutgoingPayment.LightningPart.Status.Pending, 105) ) val initialPayment = OutgoingPayment( id = UUID.randomUUID(), recipientAmount = 50_000.msat, recipient = pr.nodeId, details = OutgoingPayment.Details.Normal(pr), parts = initialParts, status = OutgoingPayment.Status.Pending ) db.addOutgoingPayment(initialPayment) // We should never re-use ids. assertFails { db.addOutgoingPayment(initialPayment.copy(recipientAmount = 60_000.msat)) } assertFails { db.addOutgoingPayment(initialPayment.copy(id = UUID.randomUUID(), parts = initialParts.map { it.copy(id = initialPayment.parts[0].id) })) } assertEquals(initialPayment, db.getOutgoingPayment(initialPayment.id)) assertNull(db.getOutgoingPayment(UUID.randomUUID())) initialPayment.parts.forEach { assertEquals(initialPayment, db.getOutgoingPaymentFromPartId(it.id)) } assertNull(db.getOutgoingPaymentFromPartId(UUID.randomUUID())) // One of the parts fails. val onePartFailed = initialPayment.copy( parts = listOf( initialParts[0].copy(status = OutgoingPayment.LightningPart.Status.Failed(TemporaryNodeFailure.code, TemporaryNodeFailure.message, 110)), initialParts[1] ) ) db.completeOutgoingLightningPart(initialPayment.parts[0].id, Either.Right(TemporaryNodeFailure), 110) assertEquals(onePartFailed, db.getOutgoingPayment(initialPayment.id)) initialPayment.parts.forEach { assertEquals(onePartFailed, db.getOutgoingPaymentFromPartId(it.id)) } // We should never update non-existing parts. assertFails { db.completeOutgoingLightningPart(UUID.randomUUID(), Either.Right(TemporaryNodeFailure)) } assertFails { db.completeOutgoingLightningPart(UUID.randomUUID(), randomBytes32()) } // Other payment parts are added. val newParts = listOf( OutgoingPayment.LightningPart(UUID.randomUUID(), 5_000.msat, listOf(HopDesc(a, c)), OutgoingPayment.LightningPart.Status.Pending, 115), OutgoingPayment.LightningPart(UUID.randomUUID(), 10_000.msat, listOf(HopDesc(a, b)), OutgoingPayment.LightningPart.Status.Pending, 120), ) assertFails { db.addOutgoingLightningParts(UUID.randomUUID(), newParts) } assertFails { db.addOutgoingLightningParts(onePartFailed.id, newParts.map { it.copy(id = initialPayment.parts[0].id) }) } val withMoreParts = onePartFailed.copy(parts = onePartFailed.parts + newParts) db.addOutgoingLightningParts(onePartFailed.id, newParts) assertEquals(withMoreParts, db.getOutgoingPayment(initialPayment.id)) withMoreParts.parts.forEach { assertEquals(withMoreParts, db.getOutgoingPaymentFromPartId(it.id)) } // Payment parts succeed. val preimage = randomBytes32() val partsSettled = withMoreParts.copy( parts = listOf( withMoreParts.parts[0], // this one was failed (withMoreParts.parts[1] as OutgoingPayment.LightningPart).copy(status = OutgoingPayment.LightningPart.Status.Succeeded(preimage, 125)), (withMoreParts.parts[2] as OutgoingPayment.LightningPart).copy(status = OutgoingPayment.LightningPart.Status.Succeeded(preimage, 126)), (withMoreParts.parts[3] as OutgoingPayment.LightningPart).copy(status = OutgoingPayment.LightningPart.Status.Succeeded(preimage, 127)), ) ) assertEquals(OutgoingPayment.Status.Pending, partsSettled.status) db.completeOutgoingLightningPart(withMoreParts.parts[1].id, preimage, 125) db.completeOutgoingLightningPart(withMoreParts.parts[2].id, preimage, 126) db.completeOutgoingLightningPart(withMoreParts.parts[3].id, preimage, 127) assertEquals(partsSettled, db.getOutgoingPayment(initialPayment.id)) partsSettled.parts.forEach { assertEquals(partsSettled, db.getOutgoingPaymentFromPartId(it.id)) } // Payment succeeds: failed parts will be ignored. val paymentSucceeded = partsSettled.copy( status = OutgoingPayment.Status.Completed.Succeeded.OffChain(preimage, 130), parts = partsSettled.parts.drop(1) ) db.completeOutgoingPaymentOffchain(initialPayment.id, preimage, 130) assertFails { db.completeOutgoingPaymentOffchain(UUID.randomUUID(), preimage, 130) } assertEquals(paymentSucceeded, db.getOutgoingPayment(initialPayment.id)) partsSettled.parts.forEach { assertEquals(paymentSucceeded, db.getOutgoingPaymentFromPartId(it.id)) } } @Test fun `outgoing payment from closed channel`() = runSuspendTest { // When a channel is closed, a corresponding OutgoingPayment is // automatically injected into the database (the user's ledger). // The payment.recipientAmount is set to the channel's local balance // at the time the channel is closed. val (db, _, pr) = createFixture() val paymentId = UUID.randomUUID() val channelBalance = 100_000_000.msat val pendingPayment = OutgoingPayment( id = paymentId, recipientAmount = channelBalance, recipient = pr.nodeId, details = OutgoingPayment.Details.ChannelClosing( channelId = randomBytes32(), closingAddress = "", isSentToDefaultAddress = true ), parts = listOf(), status = OutgoingPayment.Status.Pending ) db.addOutgoingPayment(pendingPayment) // Fees should be zero at this point, since the payment is still Pending. // It's not completed until the transactions are confirmed on the blockchain. assertEquals(pendingPayment.fees, MilliSatoshi(0)) val fundsLost = Satoshi(100) val closingTx = OutgoingPayment.ClosingTxPart( id = UUID.randomUUID(), txId = randomBytes32(), claimed = channelBalance.truncateToSatoshi() - fundsLost, closingType = ChannelClosingType.Mutual, createdAt = currentTimestampMillis() ) db.completeOutgoingPaymentForClosing(id = paymentId, parts = listOf(closingTx), completedAt = currentTimestampMillis()) val completedPayment = db.getOutgoingPayment(paymentId) assertNotNull(completedPayment) assertEquals(listOf(closingTx), completedPayment.parts) // Now that the payment has been settled on-chain, the fees can be calculated. // If we failed to claim any amount of the channel balance, // we can consider these as fees (in a generic sense). // The UI is expected to provide a more detailed explanation. assertEquals(fundsLost.toMilliSatoshi(), completedPayment.fees) assertEquals(channelBalance, completedPayment.amount) } @Test fun `outgoing payment from closed channel without parts`() = runSuspendTest { val (db, _, pr) = createFixture() val paymentId = UUID.randomUUID() val channelBalance = 100_000_000.msat val pendingPayment = OutgoingPayment( id = paymentId, recipientAmount = channelBalance, recipient = pr.nodeId, details = OutgoingPayment.Details.ChannelClosing( channelId = randomBytes32(), closingAddress = "", isSentToDefaultAddress = true ), parts = listOf(), status = OutgoingPayment.Status.Pending ) db.addOutgoingPayment(pendingPayment) db.completeOutgoingPaymentForClosing(id = paymentId, parts = listOf(), completedAt = currentTimestampMillis()) val completedPayment = db.getOutgoingPayment(paymentId) assertNotNull(completedPayment) assertEquals(channelBalance, completedPayment.amount) } @Test fun `outgoing normal payment fee & amount computation`() = runSuspendTest { val (db, preimage, pr) = createFixture() val (a, b, c) = listOf(randomKey().publicKey(), randomKey().publicKey(), randomKey().publicKey()) // test normal payment fee computation val hops1 = listOf(HopDesc(a, c, ShortChannelId(42)), HopDesc(b, c)) val hops2 = listOf(HopDesc(a, b)) val normalPayment = OutgoingPayment( id = UUID.randomUUID(), recipientAmount = 180_000.msat, recipient = pr.nodeId, details = OutgoingPayment.Details.Normal(pr), parts = listOf(), status = OutgoingPayment.Status.Pending ) db.addOutgoingPayment(normalPayment) val normalParts = listOf( OutgoingPayment.LightningPart(UUID.randomUUID(), amount = 115_000.msat, route = hops1, status = OutgoingPayment.LightningPart.Status.Pending, createdAt = 100), OutgoingPayment.LightningPart(UUID.randomUUID(), amount = 75_000.msat, route = hops2, status = OutgoingPayment.LightningPart.Status.Pending, createdAt = 105) ) db.addOutgoingLightningParts(parentId = normalPayment.id, parts = normalParts) db.completeOutgoingLightningPart(normalParts[0].id, preimage, 110) db.completeOutgoingLightningPart(normalParts[1].id, preimage, 115) db.completeOutgoingPaymentOffchain(normalPayment.id, preimage, 120) val normalPaymentInDb = db.getOutgoingPayment(normalPayment.id) assertNotNull(normalPaymentInDb) assertEquals(10_000.msat, normalPaymentInDb.fees) assertEquals(190_000.msat, normalPaymentInDb.amount) } @Test fun `outgoing swap-out payment fee & amount computation`() = runSuspendTest { val (db, preimage, pr) = createFixture() val (a, b, c) = listOf(randomKey().publicKey(), randomKey().publicKey(), randomKey().publicKey()) val hops = listOf(HopDesc(a, c, ShortChannelId(42)), HopDesc(b, c)) // test swap-out payment fee computation val swapOutPayment = OutgoingPayment( id = UUID.randomUUID(), recipientAmount = 150_000.msat, recipient = pr.nodeId, details = OutgoingPayment.Details.SwapOut("2NCnVWgTuCptq1y7Cie4KwSBADcBqXKTNCR", pr, 15.sat), parts = listOf(), status = OutgoingPayment.Status.Pending ) db.addOutgoingPayment(swapOutPayment) val swapOutParts = listOf( OutgoingPayment.LightningPart(UUID.randomUUID(), amount = 157_000.msat, route = hops, status = OutgoingPayment.LightningPart.Status.Pending, createdAt = 100), ) db.addOutgoingLightningParts(parentId = swapOutPayment.id, parts = swapOutParts) db.completeOutgoingLightningPart(swapOutParts[0].id, preimage, 110) db.completeOutgoingPaymentOffchain(swapOutPayment.id, preimage, 120) val swapOutPaymentInDb = db.getOutgoingPayment(swapOutPayment.id) assertNotNull(swapOutPaymentInDb) // the service receives 150 000 msat // the swap amount received by the on-chain address is 135 000 msat // the mining fee are contained in the swap-out service fee // total fees is 7 000 msat for routing with trampoline + 15 000 msat for the swap-out service assertEquals(22_000.msat, swapOutPaymentInDb.fees) assertEquals(157_000.msat, swapOutPaymentInDb.amount) } @Test fun `fail outgoing payment`() = runSuspendTest { val (db, _, pr) = createFixture() val initialParts = listOf( OutgoingPayment.LightningPart(UUID.randomUUID(), 20_000.msat, listOf(HopDesc(randomKey().publicKey(), randomKey().publicKey())), OutgoingPayment.LightningPart.Status.Pending, 100), OutgoingPayment.LightningPart(UUID.randomUUID(), 30_000.msat, listOf(HopDesc(randomKey().publicKey(), randomKey().publicKey())), OutgoingPayment.LightningPart.Status.Pending, 105) ) val initialPayment = OutgoingPayment( id = UUID.randomUUID(), recipientAmount = 50_000.msat, recipient = pr.nodeId, details = OutgoingPayment.Details.Normal(pr), parts = initialParts, status = OutgoingPayment.Status.Pending ) db.addOutgoingPayment(initialPayment) assertEquals(initialPayment, db.getOutgoingPayment(initialPayment.id)) val channelId = randomBytes32() val partsFailed = initialPayment.copy( parts = listOf( initialParts[0].copy(status = OutgoingPayment.LightningPart.Status.Failed(TemporaryNodeFailure.code, TemporaryNodeFailure.message, 110)), initialParts[1].copy(status = OutgoingPayment.LightningPart.Status.Failed(null, TooManyAcceptedHtlcs(channelId, 10).details(), 111)), ) ) db.completeOutgoingLightningPart(initialPayment.parts[0].id, Either.Right(TemporaryNodeFailure), 110) db.completeOutgoingLightningPart(initialPayment.parts[1].id, Either.Left(TooManyAcceptedHtlcs(channelId, 10)), 111) assertEquals(partsFailed, db.getOutgoingPayment(initialPayment.id)) initialPayment.parts.forEach { assertEquals(partsFailed, db.getOutgoingPaymentFromPartId(it.id)) } val paymentFailed = partsFailed.copy(status = OutgoingPayment.Status.Completed.Failed(FinalFailure.NoRouteToRecipient, 120)) db.completeOutgoingPaymentOffchain(initialPayment.id, FinalFailure.NoRouteToRecipient, 120) assertFails { db.completeOutgoingPaymentOffchain(UUID.randomUUID(), FinalFailure.NoRouteToRecipient, 120) } assertEquals(paymentFailed, db.getOutgoingPayment(initialPayment.id)) initialPayment.parts.forEach { assertEquals(paymentFailed, db.getOutgoingPaymentFromPartId(it.id)) } } @Test fun `list outgoing payments by payment hash`() = runSuspendTest { val (db, _, pr) = createFixture() assertTrue(db.listOutgoingPayments(pr.paymentHash).isEmpty()) val payment1 = OutgoingPayment(UUID.randomUUID(), 50_000.msat, pr.nodeId, OutgoingPayment.Details.Normal(pr)) db.addOutgoingPayment(payment1) assertEquals(listOf(payment1), db.listOutgoingPayments(pr.paymentHash)) val payment2 = payment1.copy( id = UUID.randomUUID(), parts = listOf(OutgoingPayment.LightningPart(UUID.randomUUID(), 50_000.msat, listOf(), OutgoingPayment.LightningPart.Status.Pending, 100)) ) db.addOutgoingPayment(payment2) assertEquals(setOf(payment1, payment2), db.listOutgoingPayments(pr.paymentHash).toSet()) } @Test fun `list outgoing payments`() = runSuspendTest { val (db, _, _) = createFixture() assertTrue(db.listOutgoingPayments(count = 10, skip = 0).isEmpty()) assertTrue(db.listOutgoingPayments(count = 5, skip = 5).isEmpty()) val pending1 = OutgoingPayment(UUID.randomUUID(), 50_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) val pending2 = OutgoingPayment(UUID.randomUUID(), 55_000.msat, randomKey().publicKey(), OutgoingPayment.Details.KeySend(randomBytes32())) val pending3 = OutgoingPayment(UUID.randomUUID(), 30_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) val pending4 = OutgoingPayment(UUID.randomUUID(), 60_000.msat, randomKey().publicKey(), OutgoingPayment.Details.SwapOut("1PwLgmRdDjy5GAKWyp8eyAC4SFzWuboLLb", createInvoice(randomBytes32()), 14.sat)) val pending5 = OutgoingPayment(UUID.randomUUID(), 55_000.msat, randomKey().publicKey(), OutgoingPayment.Details.KeySend(randomBytes32())) val pending6 = OutgoingPayment(UUID.randomUUID(), 45_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) val pending7 = OutgoingPayment(UUID.randomUUID(), 35_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) listOf(pending1, pending2, pending3, pending4, pending5, pending6, pending7).forEach { db.addOutgoingPayment(it) } // Pending payments should not be listed. assertTrue(db.listOutgoingPayments(count = 10, skip = 0).isEmpty()) db.completeOutgoingPaymentOffchain(pending1.id, randomBytes32(), completedAt = 100) val payment1 = db.getOutgoingPayment(pending1.id)!! db.completeOutgoingPaymentOffchain(pending2.id, FinalFailure.NoRouteToRecipient, completedAt = 101) val payment2 = db.getOutgoingPayment(pending2.id)!! // payment3 is still pending db.completeOutgoingPaymentOffchain(pending4.id, FinalFailure.InsufficientBalance, completedAt = 102) val payment4 = db.getOutgoingPayment(pending4.id)!! db.completeOutgoingPaymentOffchain(pending5.id, randomBytes32(), completedAt = 103) val payment5 = db.getOutgoingPayment(pending5.id)!! db.completeOutgoingPaymentOffchain(pending6.id, randomBytes32(), completedAt = 104) val payment6 = db.getOutgoingPayment(pending6.id)!! db.completeOutgoingPaymentOffchain(pending7.id, randomBytes32(), completedAt = 105) val payment7 = db.getOutgoingPayment(pending7.id)!! assertEquals(listOf(payment7, payment6, payment5, payment4, payment2, payment1), db.listOutgoingPayments(count = 10, skip = 0)) assertEquals(listOf(payment7, payment6), db.listOutgoingPayments(count = 2, skip = 0)) assertEquals(listOf(payment5, payment4), db.listOutgoingPayments(count = 2, skip = 2)) assertEquals(listOf(payment5, payment4, payment2), db.listOutgoingPayments(count = 10, skip = 0, setOf(PaymentTypeFilter.KeySend, PaymentTypeFilter.SwapOut))) assertEquals(listOf(payment5), db.listOutgoingPayments(count = 1, skip = 0, setOf(PaymentTypeFilter.KeySend, PaymentTypeFilter.SwapOut))) assertEquals(listOf(payment4, payment2), db.listOutgoingPayments(count = 5, skip = 1, setOf(PaymentTypeFilter.KeySend, PaymentTypeFilter.SwapOut))) } @Test fun `list payments`() = runSuspendTest { val (db, _, _) = createFixture() val (preimage1, preimage2, preimage3, preimage4) = listOf(randomBytes32(), randomBytes32(), randomBytes32(), randomBytes32()) val incoming1 = IncomingPayment(preimage1, IncomingPayment.Origin.Invoice(createInvoice(preimage1)), null, createdAt = 20) val incoming2 = IncomingPayment(preimage2, IncomingPayment.Origin.SwapIn("1PwLgmRdDjy5GAKWyp8eyAC4SFzWuboLLb"), null, createdAt = 21) val incoming3 = IncomingPayment(preimage3, IncomingPayment.Origin.Invoice(createInvoice(preimage3)), null, createdAt = 22) val incoming4 = IncomingPayment(preimage4, IncomingPayment.Origin.Invoice(createInvoice(preimage4)), null, createdAt = 23) listOf(incoming1, incoming2, incoming3, incoming4).forEach { db.addIncomingPayment(it.preimage, it.origin, it.createdAt) } val outgoing1 = OutgoingPayment(UUID.randomUUID(), 50_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) val outgoing2 = OutgoingPayment(UUID.randomUUID(), 55_000.msat, randomKey().publicKey(), OutgoingPayment.Details.KeySend(randomBytes32())) val outgoing3 = OutgoingPayment(UUID.randomUUID(), 60_000.msat, randomKey().publicKey(), OutgoingPayment.Details.SwapOut("1PwLgmRdDjy5GAKWyp8eyAC4SFzWuboLLb", createInvoice(randomBytes32()), 14.sat)) val outgoing4 = OutgoingPayment(UUID.randomUUID(), 45_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) val outgoing5 = OutgoingPayment(UUID.randomUUID(), 35_000.msat, randomKey().publicKey(), OutgoingPayment.Details.Normal(createInvoice(randomBytes32()))) listOf(outgoing1, outgoing2, outgoing3, outgoing4, outgoing5).forEach { db.addOutgoingPayment(it) } // Pending payments should not be listed. assertTrue(db.listPayments(count = 10, skip = 0).isEmpty()) val channelId1 = randomBytes32() db.receivePayment(incoming1.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment(amount = 20_000.msat, channelId = channelId1, 1)), receivedAt = 100) val inFinal1 = incoming1.copy(received = IncomingPayment.Received(setOf(IncomingPayment.ReceivedWith.LightningPayment(amount = 20_000.msat, channelId = channelId1, 1)), 100)) db.completeOutgoingPaymentOffchain(outgoing1.id, randomBytes32(), completedAt = 102) val outFinal1 = db.getOutgoingPayment(outgoing1.id)!! db.completeOutgoingPaymentOffchain(outgoing2.id, FinalFailure.UnknownError, completedAt = 103) val outFinal2 = db.getOutgoingPayment(outgoing2.id)!! val newChannelUUID = UUID.randomUUID() db.receivePayment(incoming2.paymentHash, setOf(IncomingPayment.ReceivedWith.NewChannel(id = newChannelUUID, amount = 25_000.msat, fees = 2_500.msat, channelId = null)), receivedAt = 105) val inFinal2 = incoming2.copy(received = IncomingPayment.Received(setOf(IncomingPayment.ReceivedWith.NewChannel(id = newChannelUUID, amount = 25_000.msat, fees = 2_500.msat, channelId = null)), 105)) db.completeOutgoingPaymentOffchain(outgoing3.id, randomBytes32(), completedAt = 106) val outFinal3 = db.getOutgoingPayment(outgoing3.id)!! val channelId4 = randomBytes32() db.receivePayment(incoming4.paymentHash, setOf(IncomingPayment.ReceivedWith.LightningPayment(amount = 10_000.msat, channelId = channelId4, 1)), receivedAt = 110) val inFinal4 = incoming4.copy(received = IncomingPayment.Received(setOf(IncomingPayment.ReceivedWith.LightningPayment(amount = 10_000.msat, channelId = channelId4, 1)), 110)) db.completeOutgoingPaymentOffchain(outgoing5.id, randomBytes32(), completedAt = 112) val outFinal5 = db.getOutgoingPayment(outgoing5.id)!! // outgoing4 and incoming3 are still pending. assertEquals(listOf(outFinal5, inFinal4, outFinal3, inFinal2, outFinal2, outFinal1, inFinal1), db.listPayments(count = 10, skip = 0)) assertEquals(listOf(outFinal1, inFinal1), db.listPayments(count = 5, skip = 5)) assertEquals(listOf(outFinal5, inFinal4, outFinal1, inFinal1), db.listPayments(count = 10, skip = 0, setOf(PaymentTypeFilter.Normal))) assertEquals(listOf(outFinal5, inFinal4, outFinal2, outFinal1, inFinal1), db.listPayments(count = 10, skip = 0, setOf(PaymentTypeFilter.Normal, PaymentTypeFilter.KeySend))) assertEquals(listOf(outFinal1, inFinal1), db.listPayments(count = 5, skip = 3, setOf(PaymentTypeFilter.Normal, PaymentTypeFilter.KeySend))) assertEquals(listOf(), db.listPayments(count = 5, skip = 5, setOf(PaymentTypeFilter.Normal, PaymentTypeFilter.KeySend))) } companion object { private val defaultFeatures = Features( Feature.VariableLengthOnion to FeatureSupport.Optional, Feature.PaymentSecret to FeatureSupport.Optional, Feature.BasicMultiPartPayment to FeatureSupport.Optional ) private fun createFixture(): Triple<PaymentsDb, ByteVector32, PaymentRequest> { val db = InMemoryPaymentsDb() val preimage = randomBytes32() val pr = createInvoice(preimage) return Triple(db, preimage, pr) } private fun createInvoice(preimage: ByteVector32): PaymentRequest { return PaymentRequest.create(Block.LivenetGenesisBlock.hash, 150_000.msat, Crypto.sha256(preimage).toByteVector32(), randomKey(), "invoice", CltvExpiryDelta(16), defaultFeatures) } private fun createExpiredInvoice(preimage: ByteVector32 = randomBytes32()): PaymentRequest { val now = currentTimestampSeconds() return PaymentRequest.create(Block.LivenetGenesisBlock.hash, 150_000.msat, Crypto.sha256(preimage).toByteVector32(), randomKey(), "invoice", CltvExpiryDelta(16), defaultFeatures, expirySeconds = 60, timestampSeconds = now - 120) } } }
23
null
8
48
d36d723fe9644f8ff0ca31703e23903367943d1e
34,903
lightning-kmp
Apache License 2.0
plugins/atomicfu/atomicfu-compiler/testData/box/atomics_basic/LoopTest.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// TODO(KT-65977): reenable these tests with caches //IGNORE_NATIVE: cacheMode=STATIC_EVERYWHERE //IGNORE_NATIVE: cacheMode=STATIC_PER_FILE_EVERYWHERE import kotlinx.atomicfu.* import kotlin.test.* class LoopTest { private val a = atomic(0) private val a1 = atomic(1) private val b = atomic(true) private val l = atomic(5000000000) private val r = atomic<A>(A("aaaa")) private val rs = atomic<String>("bbbb") class A(val s: String) // loop tests fun atomicfuIntLoopTest(newValue: Int): Int { a.value = 0 a.loop { cur -> if (cur == 10) { a.compareAndSet(10, newValue) assertEquals(newValue, a.value) return a.value } else { a.incrementAndGet() } } } fun atomicfuBooleanLoopTest(newValue: Boolean): Boolean { b.value = true b.loop { cur -> if (cur == false) { if (b.compareAndSet(false, newValue)) { assertEquals(newValue, b.value) return b.value } } else { b.value = false } } } fun atomicfuLongLoopTest(newValue: Long): Long { l.value = 5000000000 l.loop { cur -> if (cur == 5000000010) { if (l.compareAndSet(5000000010, newValue)) { assertEquals(newValue, l.value) return l.value } } else { l.incrementAndGet() } } } fun atomicfuRefLoopTest(newValue: A): A { r.value = A("aaa") r.loop { cur -> if (cur.s == "bbb") { r.compareAndSet(cur, newValue) assertEquals(newValue.s, r.value.s) return r.value } else { r.value = A("bbb") } } } fun atomicfuLoopTest() { assertEquals(777, atomicfuIntLoopTest(777)) assertFalse(atomicfuBooleanLoopTest(false)) assertEquals(9000000000, atomicfuLongLoopTest(9000000000)) assertEquals("bbbb", atomicfuRefLoopTest(A("bbbb")).s) } // update tests fun atomicfuIntUpdateTest() { a.value = 0 a.update { value -> if (value < 10) { a.incrementAndGet() } else { Int.MAX_VALUE } } assertEquals(Int.MAX_VALUE, a.value) } fun atomicfuBooleanUpdateTest() { b.value = false b.update { value -> if (!value) { b.compareAndSet(false, true) } else { true } } assertEquals(true, b.value) assertTrue(b.value) } fun atomicfuLongUpdateTest() { l.value = 0L l.update { value -> if (value < 10) { l.incrementAndGet() } else { Long.MAX_VALUE } } assertEquals(Long.MAX_VALUE, l.value) } fun atomicfuRefUpdateTest() { r.lazySet(A("aaaa")) r.update { value -> if (value.s == "aaaa") { r.value = A("bbbb") r.value } else { A("cccc${value.s}") } } assertEquals("ccccbbbb", r.value.s) } fun atomicfuUpdateTest() { atomicfuIntUpdateTest() atomicfuBooleanUpdateTest() atomicfuLongUpdateTest() atomicfuRefUpdateTest() } // updateAndGet tests fun atomicfuIntUpdateAndGetTest() { a.value = 0 val resInt = a.updateAndGet { value -> if (value < 10) { a.incrementAndGet() } else { Int.MAX_VALUE } } assertEquals(Int.MAX_VALUE, resInt) assertEquals(Int.MAX_VALUE, a.value) } fun atomicfuBooleanUpdateAndGetTest() { b.value = false val resBool = b.updateAndGet { value -> if (!value) { b.compareAndSet(false, true) } else { true } } assertTrue(resBool) assertTrue(b.value) } fun atomicfuLongUpdateAndGetTest() { l.value = 0L val resLong = l.updateAndGet { value -> if (value < 10) { l.incrementAndGet() } else { Long.MAX_VALUE } } assertEquals(Long.MAX_VALUE, l.value) assertEquals(Long.MAX_VALUE, resLong) } fun atomicfuRefUpdateAndGetTest() { r.lazySet(A("aaaa")) val resRef = r.updateAndGet { value -> if (value.s == "aaaa") { r.value = A("bbbb") r.value } else { A("cccc${value.s}") } } assertEquals("ccccbbbb", resRef.s) assertEquals("ccccbbbb", r.value.s) } fun atomicfuUpdateAndGetTest() { atomicfuIntUpdateAndGetTest() atomicfuBooleanUpdateAndGetTest() atomicfuLongUpdateAndGetTest() atomicfuRefUpdateAndGetTest() } // getAndUpdate tests fun atomicfuIntGetAndUpdateTest() { a.value = 0 val resInt = a.getAndUpdate { value -> if (value < 10) { a.incrementAndGet() } else { Int.MAX_VALUE } } assertEquals(10, resInt) assertEquals(Int.MAX_VALUE, a.value) } fun atomicfuBooleanGetAndUpdateTest() { b.value = false val resBool = b.getAndUpdate { value -> if (!value) { b.compareAndSet(false, true) } else { true } } assertTrue(resBool) assertTrue(b.value) } fun atomicfuLongGetAndUpdateTest() { l.value = 0L val resLong = l.getAndUpdate { value -> if (value < 10) { l.incrementAndGet() } else { Long.MAX_VALUE } } assertEquals(Long.MAX_VALUE, l.value) assertEquals(10, resLong) } fun atomicfuRefGetAndUpdateTest() { r.lazySet(A("aaaa")) val resRef = r.getAndUpdate { value -> if (value.s == "aaaa") { r.value = A("bbbb") r.value } else { A("cccc${value.s}") } } assertEquals("bbbb", resRef.s) assertEquals("ccccbbbb", r.value.s) } fun atomicfuGetAndUpdateTest() { atomicfuIntGetAndUpdateTest() atomicfuBooleanGetAndUpdateTest() atomicfuLongGetAndUpdateTest() atomicfuRefGetAndUpdateTest() } } fun box(): String { val testClass = LoopTest() testClass.atomicfuLoopTest() testClass.atomicfuUpdateTest() testClass.atomicfuUpdateAndGetTest() testClass.atomicfuGetAndUpdateTest() return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
7,023
kotlin
Apache License 2.0
arcade-visuals/src/main/kotlin/net/casual/arcade/visuals/countdown/Countdown.kt
CasualChampionships
621,955,934
false
{"Kotlin": 981165, "Java": 176720, "GLSL": 4396}
package net.casual.arcade.visuals.countdown import net.casual.arcade.scheduler.GlobalTickedScheduler import net.casual.arcade.scheduler.MinecraftScheduler import net.casual.arcade.scheduler.task.Completable import net.casual.arcade.utils.TimeUtils.Seconds import net.casual.arcade.utils.time.MinecraftTimeDuration import net.minecraft.server.level.ServerPlayer import org.jetbrains.annotations.ApiStatus.NonExtendable import org.jetbrains.annotations.ApiStatus.OverrideOnly import kotlin.math.roundToInt public interface Countdown { @OverrideOnly public fun beforeCountdown(players: Collection<ServerPlayer>, interval: MinecraftTimeDuration) { } @OverrideOnly public fun sendCountdown(players: Collection<ServerPlayer>, current: Int, remaining: MinecraftTimeDuration) @OverrideOnly public fun afterCountdown(players: Collection<ServerPlayer>) { } @NonExtendable public fun countdown( duration: MinecraftTimeDuration = 10.Seconds, interval: MinecraftTimeDuration = 1.Seconds, scheduler: MinecraftScheduler = GlobalTickedScheduler.get(), players: () -> Collection<ServerPlayer> ): Completable { val post = Completable.Impl() var remaining = duration var current = (remaining / interval).roundToInt() this.beforeCountdown(players(), interval) scheduler.scheduleInLoop(MinecraftTimeDuration.ZERO, interval, remaining) { this.sendCountdown(players(), current--, remaining) remaining -= interval } scheduler.schedule(remaining) { this.afterCountdown(players()) post.complete() } return post } }
1
Kotlin
1
2
b78dd42472d500120dbb3e2670cb67652da4449b
1,695
arcade
MIT License
distribution-test/src/test/kotlin/app/simplecloud/distribution/test/DistributionMessageTest.kt
theSimpleCloud
527,154,329
false
{"Kotlin": 168178}
/* * MIT License * * Copyright (c) 2022 Frederick Baier & Philipp Eistrach * * 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 app.simplecloud.distribution.test import app.simplecloud.simplecloud.distribution.api.Address import app.simplecloud.simplecloud.distribution.api.DistributionComponent import app.simplecloud.simplecloud.distribution.api.DistributionFactory import app.simplecloud.simplecloud.distribution.api.MessageListener import app.simplecloud.simplecloud.distribution.test.TestDistributionFactoryImpl import app.simplecloud.simplecloud.distribution.test.VirtualNetwork import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * Date: 08.04.22 * Time: 17:56 * @author Frederick Baier * */ class DistributionMessageTest { private lateinit var factory: DistributionFactory @BeforeEach fun setUp() { this.factory = TestDistributionFactoryImpl() } @AfterEach fun tearDown() { VirtualNetwork.reset() } @Test fun newServer_receiveSelfMessages() { val server = this.factory.createServer(1630, emptyList()) val messageManager = server.getMessageManager() var messageReceived = false messageManager.setMessageListener(object : MessageListener { override fun messageReceived(message: Any, sender: DistributionComponent) { messageReceived = true } }) messageManager.sendMessage("test") assertTrue(messageReceived) } @Test fun serverAndClient_ClientReceiveMessage() { val server = this.factory.createServer(1630, emptyList()) val client = this.factory.createClient(Address("127.0.0.1", 1630)) val clientMessageManager = client.getMessageManager() var received = 0 clientMessageManager.setMessageListener(object : MessageListener { override fun messageReceived(message: Any, sender: DistributionComponent) { received++ } }) val serverMessageManager = server.getMessageManager() serverMessageManager.setMessageListener(object : MessageListener { override fun messageReceived(message: Any, sender: DistributionComponent) { received++ } }) serverMessageManager.sendMessage("test") assertEquals(2, received) } @Test fun singleReceiverMessage() { val server = this.factory.createServer(1630, emptyList()) val client = this.factory.createClient(Address("127.0.0.1", 1630)) val clientMessageManager = client.getMessageManager() var received = 0 clientMessageManager.setMessageListener(object : MessageListener { override fun messageReceived(message: Any, sender: DistributionComponent) { received++ } }) val serverMessageManager = server.getMessageManager() serverMessageManager.setMessageListener(object : MessageListener { override fun messageReceived(message: Any, sender: DistributionComponent) { received++ } }) serverMessageManager.sendMessage("test", client.getSelfComponent()) assertEquals(1, received) } }
0
Kotlin
0
0
f83e41ae0bd6b618b7566b9d3d1ca24d3201b92d
4,450
distribution
MIT License
app/src/main/kotlin/by/ntnk/msluschedule/data/StudyGroup.kt
antkir
119,114,156
false
null
package by.ntnk.msluschedule.data data class StudyGroup constructor( val key: Int, val name: String, val faculty: Int, val course: Int, val year: Int )
0
Kotlin
0
1
89a560333ebd1eac020ae91ad1899d2669c6da18
193
MsluSchedule
Apache License 2.0
data/src/main/java/com/example/data/mappers/base/LocalDataMapper.kt
meghdadya
776,918,286
false
{"Kotlin": 85745}
package com.example.data.mappers.base import com.example.data.models.base.LocalDataModel import com.example.domain.models.DomainModel abstract class LocalDataMapper<L : LocalDataModel, D : DomainModel> { abstract fun mapTo(local: L): D abstract fun mapFrom(domain: D): L }
0
Kotlin
0
0
a0b7cd489ee3e85e1197b90d8b08eb94a9c7901c
284
OryAuthentication
Apache License 2.0
feature-b/src/main/java/uk/co/applylogic/modularization/feature_b/ui/feature_b/FeatureBFragment.kt
golanshy
234,530,215
false
null
package uk.co.applylogic.modularization.feature_b.ui.feature_b import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import uk.co.applylogic.modularization.feature_b.FeatureBActivity import uk.co.applylogic.modularization.feature_b.R import uk.co.applylogic.modularization.feature_b.databinding.FeatureBFragmentBinding class FeatureBFragment : Fragment() { private lateinit var viewModel: FeatureBViewModel private lateinit var binding: FeatureBFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate( inflater, R.layout.feature_b_fragment, container, false ) return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(FeatureBViewModel::class.java) binding.lifecycleOwner = this binding.activity = activity as FeatureBActivity binding.fragment = this binding.viewModel = viewModel } }
0
Kotlin
0
0
ed2b5f501d47d70ecf260d71a02c6d256cd556a5
1,333
modularization-demo
Apache License 2.0
mvvm/src/main/java/cn/carveknife/mvvm/http/exception/NetworkErrorException.kt
Carveknife
312,512,449
false
null
package cn.carveknife.mvvm.http.exception import java.lang.RuntimeException /** * description : * created time: 2020/11/13 17:15 * created by: cuibenguang */ class NetworkErrorException(message: String?) : RuntimeException(message) { }
0
Kotlin
0
2
019f4512bc1b38f68286901c00c4b56e590ffe3b
241
AndroidMVVM
Apache License 2.0
data-network-connectivity/src/main/kotlin/com/soberg/netinfo/android/data/netconnectivity/AndroidNetworkConnectionModule.kt
jsoberg
575,643,501
false
null
package com.soberg.netinfo.android.data.netconnectivity import android.content.Context import android.net.ConnectivityManager import androidx.core.content.ContextCompat.getSystemService import com.soberg.netinfo.domain.lan.NetworkConnectionRepository import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module internal abstract class AndroidNetworkConnectionModule { companion object { @Provides @Singleton internal fun provideConnectivityManager(@ApplicationContext appContext: Context): ConnectivityManager = getSystemService(appContext, ConnectivityManager::class.java) as ConnectivityManager } @Binds internal abstract fun provideConnectionRepository(repository: AndroidNetworkConnectionRepository): NetworkConnectionRepository }
0
Kotlin
0
3
c3a72bc3eab3fb392a827d77b20a16d1f7f81116
1,004
Android-Net-Info
MIT License
app/src/main/java/com/moonfoxy/rickandmortyencyclopedia/local/converter/CharacterEntityConverter.kt
MoonFoxy
661,396,047
false
null
package com.moonfoxy.rickandmortyencyclopedia.local.converter import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken class CharacterEntityConverter { @TypeConverter fun fromListToJson(value: List<String>): String = Gson().toJson(value) @TypeConverter fun fromJsonToList(value: String): List<String> { val listType = object : TypeToken<List<String>>() {}.type return Gson().fromJson(value, listType) } }
0
Kotlin
0
0
a66ec40f912d4e835206c590ce865beaa211cd26
490
Rick_and_Morty_Encyclopedia
MIT License
app/src/main/java/com/moonfoxy/rickandmortyencyclopedia/local/converter/CharacterEntityConverter.kt
MoonFoxy
661,396,047
false
null
package com.moonfoxy.rickandmortyencyclopedia.local.converter import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken class CharacterEntityConverter { @TypeConverter fun fromListToJson(value: List<String>): String = Gson().toJson(value) @TypeConverter fun fromJsonToList(value: String): List<String> { val listType = object : TypeToken<List<String>>() {}.type return Gson().fromJson(value, listType) } }
0
Kotlin
0
0
a66ec40f912d4e835206c590ce865beaa211cd26
490
Rick_and_Morty_Encyclopedia
MIT License
android/app/src/main/java/com/sicariusnoctis/collaborativeintelligence/Statistics.kt
YodaEmbedding
208,207,262
false
null
package com.sicariusnoctis.collaborativeintelligence import com.google.common.collect.EvictingQueue import kotlinx.serialization.Serializable import java.time.Duration import java.time.Instant import java.util.* import kotlin.collections.HashMap class Statistics { private val modelStats = HashMap<ModelConfig, ModelStatistics>() operator fun get(modelConfig: ModelConfig): ModelStatistics = modelStats.getOrPut(modelConfig, { ModelStatistics() }) operator fun get(frameNumber: Int): ModelStatistics = modelStats .filterValues { v -> v.containsKey(frameNumber) } .values .first() operator fun set(modelConfig: ModelConfig, modelStatistics: ModelStatistics) { modelStats[modelConfig] = modelStatistics } } class ModelStatistics { val isEmpty @Synchronized get() = lastNValidSamples.isEmpty() val isFirstExist: Boolean @Synchronized get() = allSamples.size != 0 var framesDropped = 0 @Synchronized get private set val framesProcessed @Synchronized get() = validSamples.size val fps @Synchronized get() = fps() val totalAverage @Synchronized get() = if (lastNValidSamples.isEmpty()) 0 else lastNValidSamples.map { it.total!!.toMillis() }.sum() / lastNValidSamples.size val uploadAverage @Synchronized get() = if (lastNValidSamples.isEmpty()) 0 else lastNValidSamples.map { it.uploadBytes!! }.sum() / lastNValidSamples.size val sample: Sample @Synchronized get() = lastNValidSamples.last() val samples: Map<Int, Sample> @Synchronized get() = validSamples var currentSample: Sample? = null @Synchronized get private set private val allSamples = LinkedHashMap<Int, Sample>() private val validSamples = LinkedHashMap<Int, Sample>() private val lastNValidSamples = EvictingQueue.create<Sample>(10) @Synchronized operator fun get(frameNumber: Int) = allSamples[frameNumber]!! @Synchronized fun containsKey(frameNumber: Int) = allSamples.containsKey(frameNumber) @Synchronized fun frameDropped() { framesDropped++ } @Synchronized fun makeSample(frameNumber: Int) { val sample = Sample() currentSample = sample allSamples[frameNumber] = sample } @Synchronized fun setPreprocess(frameNumber: Int, start: Instant, end: Instant) { allSamples[frameNumber]!!.preprocessStart = start allSamples[frameNumber]!!.preprocessEnd = end } @Synchronized fun setInference(frameNumber: Int, start: Instant, end: Instant) { allSamples[frameNumber]!!.inferenceStart = start allSamples[frameNumber]!!.inferenceEnd = end } @Synchronized fun setPostencode(frameNumber: Int, start: Instant, end: Instant) { allSamples[frameNumber]!!.postencodeStart = start allSamples[frameNumber]!!.postencodeEnd = end } @Synchronized fun setNetworkWrite(frameNumber: Int, start: Instant, end: Instant) { allSamples[frameNumber]!!.networkWriteStart = start allSamples[frameNumber]!!.networkWriteEnd = end } @Synchronized fun setNetworkRead(frameNumber: Int, start: Instant, end: Instant) { allSamples[frameNumber]!!.networkReadStart = start allSamples[frameNumber]!!.networkReadEnd = end } @Synchronized fun setUpload(frameNumber: Int, uploadBytes: Int) { allSamples[frameNumber]!!.uploadBytes = uploadBytes } @Synchronized fun setResultResponse(frameNumber: Int, resultResponse: ResultResponse) { val sample = allSamples[frameNumber]!! sample.resultResponse = resultResponse validSamples[frameNumber] = sample lastNValidSamples.add(sample) } private fun fps() = 1000.0 * lastNValidSamples.size / Duration.between( lastNValidSamples.first().preprocessStart, lastNValidSamples.last().networkReadEnd ).toMillis().toDouble() } @Serializable data class SerializableSample( val frameNumber: Int, val preprocess: Long, val clientInference: Long, val postencode: Long, val networkWrite: Long, val serverInference: Long, val networkRead: Long, val networkWait: Long, val total: Long ) { companion object { fun fromSample(frameNumber: Int, sample: Sample) = SerializableSample( frameNumber, sample.preprocess!!.toMillis(), sample.clientInference!!.toMillis(), sample.postencode!!.toMillis(), sample.networkWrite!!.toMillis(), sample.serverInference!!.toMillis(), sample.networkRead!!.toMillis(), sample.networkWait!!.toMillis(), sample.total!!.toMillis() ) } } data class Sample( var preprocessStart: Instant? = null, var preprocessEnd: Instant? = null, var inferenceStart: Instant? = null, var inferenceEnd: Instant? = null, var postencodeStart: Instant? = null, var postencodeEnd: Instant? = null, var networkWriteStart: Instant? = null, var networkWriteEnd: Instant? = null, var networkReadStart: Instant? = null, var networkReadEnd: Instant? = null, var uploadBytes: Int? = null, var resultResponse: ResultResponse? = null ) { val preprocess get() = durationBetween(preprocessStart, preprocessEnd) val clientInference get() = durationBetween(inferenceStart, inferenceEnd) val postencode get() = durationBetween(postencodeStart, postencodeEnd) val networkWrite get() = durationBetween(networkWriteStart, networkWriteEnd) val serverInference get() = resultResponse?.let { Duration.ofMillis(it.inferenceTime) } val networkRead get() = durationBetween(networkReadStart, networkReadEnd) val networkWait get() = durationBetween(networkWriteStart, networkReadEnd) val total get() = durationBetween(preprocessStart, networkReadEnd) val frameNumber get() = resultResponse!!.frameNumber override fun toString() = durations() .zip(durationDescriptions) .joinToString(separator = "\n") { (duration, description) -> "%.3fs %s".format(duration?.toMillis()?.div(1000.0), description) } val isValid get() = uploadBytes != null && instants().all { it != null } private fun durations() = listOf( Pair(preprocessStart, preprocessEnd), Pair(inferenceStart, inferenceEnd), Pair(postencodeStart, postencodeEnd), Pair(networkWriteStart, networkWriteEnd), Pair(networkWriteEnd, networkReadEnd) ) .map { durationBetween(it.first, it.second) } private fun instants() = listOf( preprocessStart, preprocessEnd, inferenceStart, inferenceEnd, postencodeStart, postencodeEnd, networkWriteStart, networkWriteEnd, networkReadStart, networkReadEnd ) companion object { private val durationDescriptions = listOf( "Preprocess", "Inference", "Postencode", "Network Send", "Network Wait" ) private fun durationBetween(start: Instant?, end: Instant?): Duration? { return if (start == null || end == null) null else Duration.between(start, end) } } }
4
Kotlin
0
6
53d3ea010861e1fc539cf38f14fca50476dee196
7,353
collaborative-intelligence
MIT License
app/src/main/java/eu/ways4/trackex/data/model/Tag.kt
smartDevel
559,468,195
false
null
package eu.ways4.trackex.data.model import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Tag(val id: String, val name: String): Parcelable
0
Kotlin
0
0
43ee648a05b23eaf1f3d2b1bc55a7a0139c28256
178
trackex
Apache License 2.0
example-app/src/androidTest/java/com/adyen/checkout/test/rule/MockServerRule.kt
Adyen
91,104,663
false
{"Kotlin": 4787892, "Shell": 4706}
/* * Copyright (c) 2024 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by oscars on 6/6/2024. */ package com.adyen.checkout.test.rule import com.adyen.checkout.test.server.CheckoutMockWebServer import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class MockServerRule : TestRule { override fun apply(base: Statement, description: Description?): Statement = object : Statement() { override fun evaluate() { try { CheckoutMockWebServer.start() base.evaluate() } finally { CheckoutMockWebServer.stop() } } } }
22
Kotlin
66
126
c45a6ee4d2039163ae075436a9d1231ffcb16f5c
756
adyen-android
MIT License
app/src/main/java/com/alexvas/rtsp/demo/live/LiveFragment.kt
jpetrocik
549,106,174
false
{"INI": 2, "YAML": 1, "Gradle": 7, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 2, "Ignore List": 5, "Proguard": 2, "Java": 586, "XML": 26, "Kotlin": 14}
package com.alexvas.rtsp.demo.live import android.annotation.SuppressLint import android.content.ContentValues import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.os.Environment import android.os.Handler import android.os.HandlerThread import android.provider.MediaStore import android.util.Log import android.view.* import android.widget.Button import android.widget.ImageButton import android.widget.TextView import android.widget.Toast import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.alexvas.rtsp.demo.R import com.alexvas.rtsp.demo.SettingsActivity import com.alexvas.rtsp.demo.databinding.FragmentLiveBinding import com.alexvas.rtsp.widget.RtspSurfaceView import net.petrocik.onvif.* import java.io.File import java.io.File.separator import java.io.FileOutputStream import java.io.OutputStream import java.util.concurrent.atomic.AtomicBoolean @SuppressLint("LogNotTimber") class LiveFragment : Fragment() { private var profileToken = "MainStreamProfileToken" private lateinit var defaultPTZSpeed: PTZSpeed private var presets = mutableListOf<String>() private var connected = false private lateinit var binding: FragmentLiveBinding private val rtspStatusListener = object: RtspSurfaceView.RtspStatusListener { override fun onRtspStatusConnecting() { connected = false binding.pbLoading.visibility = View.VISIBLE binding.vShutter.visibility = View.VISIBLE enableActions(false) enablePresets(false) } override fun onRtspStatusConnected() { } override fun onRtspStatusDisconnected() { connected = false binding.pbLoading.visibility = View.GONE binding.vShutter.visibility = View.VISIBLE enableActions(false) enablePresets(false) } override fun onRtspStatusFailedUnauthorized() { if (context == null) return binding.pbLoading.visibility = View.GONE Toast.makeText(context, "Authentication Failure" , Toast.LENGTH_LONG).show() } override fun onRtspStatusFailed(message: String?) { if (context == null) return binding.pbLoading.visibility = View.GONE Toast.makeText(context, message , Toast.LENGTH_LONG).show() } override fun onRtspFirstFrameRendered() { connected = true binding.vShutter.visibility = View.GONE binding.pbLoading.visibility = View.GONE enableActions(true) enablePresets(true) resize(1080, 1980) } } private fun enablePresets(enabled: Boolean){ if (!enabled || connected && !presets.isNullOrEmpty()) { enable(binding.preset1, enabled) enable(binding.preset2, enabled) enable(binding.preset3, enabled) enable(binding.preset4, enabled) enable(binding.preset5, enabled) } } private fun enableActions(enabled: Boolean) { enable(binding.snapShotButton, enabled) enable(binding.tvStatus, enabled) } private fun enable(imageButton: ImageButton, enabled: Boolean) { if (context == null) return imageButton.isEnabled = enabled val statusColor = if (imageButton.isEnabled) R.color.colorPrimary else R.color.colorPrimaryDisabled imageButton.imageTintList = ResourcesCompat.getColorStateList(resources, statusColor, null) } private fun enable(textButton: Button, enabled: Boolean) { if (context == null) return textButton.isEnabled = enabled val statusColor = if (textButton.isEnabled) R.color.colorPrimary else R.color.colorPrimaryDisabled textButton.backgroundTintList = ResourcesCompat.getColorStateList(resources, statusColor, null) } private fun enable(textView: TextView, enabled: Boolean) { if (context == null) return textView.isEnabled = enabled val statusColor = if (textView.isEnabled) R.color.colorPrimary else R.color.colorPrimaryDisabled textView.setTextColor(ResourcesCompat.getColor(resources, statusColor, null)) } private fun getSnapshot(): Bitmap? { if (DEBUG) Log.v(TAG, "getSnapshot()") val surfaceBitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888) val lock = Object() val success = AtomicBoolean(false) val thread = HandlerThread("PixelCopyHelper") thread.start() val sHandler = Handler(thread.looper) val listener = PixelCopy.OnPixelCopyFinishedListener { copyResult -> success.set(copyResult == PixelCopy.SUCCESS) synchronized (lock) { lock.notify() } } synchronized (lock) { PixelCopy.request(binding.svVideo.holder.surface, surfaceBitmap, listener, sHandler) lock.wait() } thread.quitSafely() return if (success.get()) surfaceBitmap else null } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { if (DEBUG) Log.v(TAG, "onCreateView()") binding = FragmentLiveBinding.inflate(inflater, container, false) binding.svVideo.setStatusListener(rtspStatusListener) binding.settingsButton.setOnClickListener { val myIntent = Intent(context, SettingsActivity::class.java) startActivity(myIntent) } binding.snapShotButton.setOnClickListener { val bitmap = getSnapshot() if (bitmap != null) { saveImage(bitmap, context!!) Toast.makeText(requireContext(), "Snapshot succeeded", Toast.LENGTH_LONG).show() } else { Toast.makeText(requireContext(), "Snapshot failed", Toast.LENGTH_LONG).show() } } binding.preset1.setOnClickListener { gotoPreset(1) } binding.preset2.setOnClickListener { gotoPreset(2) } binding.preset3.setOnClickListener { gotoPreset(3) } binding.preset4.setOnClickListener { gotoPreset(4) } binding.preset5.setOnClickListener { gotoPreset(5) } return binding.root } override fun onResume() { if (DEBUG) Log.v(TAG, "onResume()") super.onResume() val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val onvif = sharedPreferences.getString("onvif", "") if (onvif == null || onvif.equals("")) { binding.presetPanel.visibility = View.GONE } else { binding.presetPanel.visibility = View.VISIBLE // getConfiguration(onvif) getPtzConfiguration(onvif) } val url = sharedPreferences.getString("url", "") val username = sharedPreferences.getString("username", "") val password = sharedPreferences.getString("password", "") if (url.equals("")) { val myIntent = Intent(context, SettingsActivity::class.java) startActivity(myIntent) return } var uri = Uri.parse(url) binding.svVideo.init(uri, username, password, "rtsp-client-android") binding.svVideo.start(true, true) } override fun onPause() { val started = binding.svVideo.isStarted() if (DEBUG) Log.v(TAG, "onPause(), started:$started") super.onPause() binding.presetPanel.visibility = View.GONE enablePresets(false) enableActions(false) if (started) { binding.svVideo.stop() } } companion object { private val TAG: String = LiveFragment::class.java.simpleName private const val DEBUG = true private const val SNAPSHOT_FOLDER_NAME = "IPCamera" } private fun getPtzConfiguration(onvif: String) { var ptzBinding = PTZBinding( object: IServiceEvents { override fun Starting() {} override fun Completed(result: OperationResult<*>?) { var res = result!!.Result when (res) { is GetConfigurationsResponse -> { defaultPTZSpeed = res[0].DefaultPTZSpeed this@LiveFragment.getPresets(onvif) } } }}, onvif ) ptzBinding.GetConfigurationsAsync() } // private fun getConfiguration(onvif: String) { // // var mediaBinding = MediaBinding( object: IServiceEvents { // override fun Starting() {} // override fun Completed(result: OperationResult<*>?) { // var res = result!!.Result // when (res) { // is Profile -> { // var videoResolution = res.VideoEncoderConfiguration.Resolution // } // } // }}, onvif ) // // mediaBinding.GetProfileAsync(profileToken) // // } private fun resize(height: Int, width: Int) { var decorView = this@LiveFragment.activity?.window?.decorView val resource = context!!.resources.getIdentifier( "status_bar_height", "dimen", "android" ) var statusBarHeight = 0; if (resource > 0) { statusBarHeight = context!!.resources.getDimensionPixelSize(resource) } var videoRatio = height.toDouble() / width.toDouble() if (decorView?.height == null || decorView.width == null) return var layoutParams = binding.svVideo.layoutParams; var viewRatio = Math.min(decorView.height.toDouble() - statusBarHeight, decorView.width.toDouble()) / Math.max(decorView.height.toDouble() - statusBarHeight, decorView.width.toDouble()) layoutParams.height = if (videoRatio > viewRatio) (decorView.width * viewRatio).toInt() else (decorView.width * videoRatio).toInt() binding.svVideo.layoutParams = layoutParams; } private fun getPresets(onvif: String) { var ptzBinding = PTZBinding( object: IServiceEvents { override fun Starting() {} override fun Completed(result: OperationResult<*>?) { var res = result!!.Result when (res) { is GetPresetsResponse -> { presets.clear() for (i in 0..4) { presets.add(res[i].token) } enablePresets(true) } } }}, onvif ) ptzBinding.GetPresetsAsync(profileToken) } private fun gotoPreset(preset: Int) { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val onvif = sharedPreferences.getString("onvif", ""); if (onvif.equals("")) return; var ptzBinding = PTZBinding(object: IServiceEvents { override fun Starting() {} override fun Completed(result: OperationResult<*>?) {}}, onvif ) ptzBinding.GotoPresetAsync(profileToken, presets[preset-1], defaultPTZSpeed) } /// @param folderName can be your app's name private fun saveImage(bitmap: Bitmap, context: Context) { if (android.os.Build.VERSION.SDK_INT >= 29) { val values = contentValues() values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + SNAPSHOT_FOLDER_NAME) values.put(MediaStore.Images.Media.IS_PENDING, true) // RELATIVE_PATH and IS_PENDING are introduced in API 29. val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) if (uri != null) { saveImageToStream(bitmap, context.contentResolver.openOutputStream(uri)) values.put(MediaStore.Images.Media.IS_PENDING, false) context.contentResolver.update(uri, values, null, null) } } else { val directory = File(Environment.getExternalStorageDirectory().toString() + separator + SNAPSHOT_FOLDER_NAME) // getExternalStorageDirectory is deprecated in API 29 if (!directory.exists()) { directory.mkdirs() } val fileName = System.currentTimeMillis().toString() + ".png" val file = File(directory, fileName) saveImageToStream(bitmap, FileOutputStream(file)) if (file.absolutePath != null) { val values = contentValues() values.put(MediaStore.Images.Media.DATA, file.absolutePath) // .DATA is deprecated in API 29 context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } } } private fun contentValues() : ContentValues { val values = ContentValues() values.put(MediaStore.Images.Media.MIME_TYPE, "image/png") values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000); values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); return values } private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) { if (outputStream != null) { try { bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) outputStream.close() } catch (e: Exception) { e.printStackTrace() } } } }
1
null
1
1
6104aa91beb6330f8aad3793add3f94e02448392
13,946
rtsp-client-android
Apache License 2.0
database/database-vertx/src/main/kotlin/ru/tinkoff/kora/database/vertx/VertxQueryExecutorExtension.kt
Squiry
772,475,645
true
{"Java Properties": 1, "Gradle": 98, "Shell": 1, "EditorConfig": 1, "Markdown": 3, "Batchfile": 1, "Text": 2, "Ignore List": 1, "Java": 1446, "Kotlin": 467, "XML": 8, "JSON": 17, "INI": 10, "YAML": 5, "SQL": 3, "OASv3-yaml": 11, "HTML": 2, "OASv2-yaml": 1, "Mustache": 32, "Protocol Buffer": 3}
package ru.tinkoff.kora.database.vertx import io.vertx.sqlclient.SqlClient import io.vertx.sqlclient.SqlConnection import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.future.await import kotlinx.coroutines.future.future import kotlin.coroutines.coroutineContext suspend inline fun <T> VertxConnectionFactory.withConnection(noinline callback: suspend (SqlClient) -> T): T { val ctx = coroutineContext val future = withConnection { CoroutineScope(ctx).future { callback.invoke(it) } } return future.await() } suspend inline fun <T> VertxConnectionFactory.inTx(noinline callback: suspend (SqlConnection) -> T): T { val ctx = coroutineContext val future = inTx { CoroutineScope(ctx).future<T>(ctx) { callback.invoke(it) } } return future.await() }
0
null
0
0
c26f794e60e903a358b0c1ffac9a865507415ff6
830
kora
Apache License 2.0
webApp/src/jsMain/kotlin/orguser/OrgUserHeader.kt
mutualmobile
495,292,087
false
null
package orguser import components.AppThemeContext import csstype.Display import csstype.number import kotlinx.js.jso import mui.icons.material.Logout import mui.icons.material.Menu import mui.material.* import mui.material.styles.TypographyVariant import mui.system.Breakpoint import mui.system.responsive import mui.system.sx import react.FC import react.Props import react.dom.aria.AriaHasPopup import react.dom.aria.ariaHasPopup import react.dom.aria.ariaLabel import react.dom.html.ReactHTML import react.key import react.router.useNavigate import react.useContext external interface HeaderProps : Props { var navDrawerToggle: () -> Unit var logout: () -> Unit var isLoggingOut: Boolean var showOptionsInHeader: Boolean var drawerItems: DrawerItems? } val Header = FC<HeaderProps> { props -> val drawerItems = props.drawerItems val navigate = useNavigate() AppBar { position = AppBarPosition.static Container { maxWidth = "xl" Toolbar { disableGutters = true if (!props.showOptionsInHeader) { IconButton { Menu() onClick = { props.navDrawerToggle() } } } Stack { sx { flexGrow = number(1.0) } spacing = responsive(2) direction = responsive(StackDirection.row) Typography { variant = TypographyVariant.h5 component = ReactHTML.div +"Dashboard" } if (props.showOptionsInHeader) { drawerItems?.forEach { item -> MenuItem { key = item.key onClick = { navigate(item.key) } Typography { align = TypographyAlign.center +item.name } } } } } if (props.isLoggingOut) { CircularProgress() } else { IconButton { Logout() onClick = { props.logout() } } } } } } }
0
Kotlin
4
41
763dd7f45f8271cebe9107c63f3532e1b14c666f
2,670
HarvestTimeKMP
Apache License 2.0
app/src/main/java/com/meksconway/areyouexpert/util/Util.kt
meksconways
251,727,106
false
null
package com.meksconway.areyouexpert.util import android.content.res.Resources import android.util.DisplayMetrics import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.schedulers.Schedulers //Transformers fun <T> Observable<T>.remote(): Observable<Res<T>> = map { Res.success(it) } .networkErrorHandler() .subscribeOn(Schedulers.io()) .compose(concatWithLoading()) fun <T> Observable<T>.local(): Observable<Res<T>> = map { Res.success(it) } .localErrorHandler() .subscribeOn(Schedulers.io()) .compose(concatWithLoading()) fun <T> concatWithLoading(): ObservableTransformer<Res<T>, Res<T>> = ObservableTransformer { Observable.just(Res.loading<T>()).concatWith(it) } fun <T> Observable<Res<T>>.networkErrorHandler(): Observable<Res<T>> { val transformer: ObservableTransformer<Res<T>, Res<T>> = ObservableTransformer { upstream -> upstream.onErrorReturn { // val handleInfo = when(throwable) { // is HttpException -> RetrofitErrorHandlerFactory.getHttpErrorHandler() // else -> throwable // // } Res.error(it) } } return compose(transformer) } fun <T> Observable<Res<T>>.localErrorHandler(): Observable<Res<T>> { val transformer: ObservableTransformer<Res<T>, Res<T>> = ObservableTransformer { upstream -> upstream.onErrorReturn { // val handleInfo = when(throwable) { // is HttpException -> RetrofitErrorHandlerFactory.getHttpErrorHandler() // else -> throwable // // } Res.error(it) } } return compose(transformer) } data class Res<T> constructor( val status: Status, var data: T?, val error: Throwable? = null ) { companion object { @JvmStatic fun <T> error(throwable: Throwable): Res<T> { return Res(Status.ERROR, null, throwable) } @JvmStatic fun <T> success(data: T): Res<T> { return Res(Status.SUCCESS, data, null) } @JvmStatic fun <T> loading(): Res<T> { return Res(Status.LOADING, null, null) } } } enum class Status { LOADING, ERROR, SUCCESS } object RetrofitErrorHandlerFactory { fun getHttpErrorHandler() { } } val Float.dp: Float get() = (this / Resources.getSystem().displayMetrics.density) val Float.px: Float get() = (this * Resources.getSystem().displayMetrics.density) fun convertPixelsToDp(px: Float): Float { return px / (Resources.getSystem().displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT) } //sealed class Resource<T>( // val data: T? = null, // val message: String? = null //) { // class Success<T>(data: T) : Resource<T>(data) // class Loading<T>(data: T? = null) : Resource<T>(data) // class Error<T>(message: String, data: T? = null) : Resource<T>(data, message) //}
0
Kotlin
0
0
d00b6d9d4e95d1527006140ad9257c7094aeb871
3,106
AreYouExpert-Android
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/cloud_assembly_schema/SSMParameterContextQueryDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5467235}
package com.faendir.awscdkkt.generated.cloud_assembly_schema import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.cloud_assembly_schema.SSMParameterContextQuery @Generated public fun buildSSMParameterContextQuery(initializer: @AwsCdkDsl SSMParameterContextQuery.Builder.() -> Unit = {}): SSMParameterContextQuery = SSMParameterContextQuery.Builder().apply(initializer).build()
1
Kotlin
0
4
a73787ba1e6f0a616b074f42fe6eedd9775f3e2a
457
aws-cdk-kt
Apache License 2.0
features/fixtures/mazeracer/app/src/main/java/com/bugsnag/mazeracer/scenarios/BatchTimeoutScenario.kt
bugsnag
539,491,063
false
{"Kotlin": 399825, "Gherkin": 44549, "Ruby": 5497, "Shell": 1946, "Makefile": 617, "Java": 489}
package com.bugsnag.mazeracer.scenarios import com.bugsnag.android.performance.BugsnagPerformance import com.bugsnag.android.performance.PerformanceConfiguration import com.bugsnag.android.performance.internal.InternalDebug import com.bugsnag.android.performance.measureSpan import com.bugsnag.mazeracer.Scenario class BatchTimeoutScenario( config: PerformanceConfiguration, scenarioMetadata: String ) : Scenario(config, scenarioMetadata) { init { InternalDebug.spanBatchSizeSendTriggerPoint = 100 InternalDebug.workerSleepMs = 250 } override fun startScenario() { BugsnagPerformance.start(config) // a short sleep to allow the worker to finish a single pass before continuing Thread.sleep(50) measureSpan("Span 1") { Thread.sleep(30) } measureSpan("Span 2") { Thread.sleep(30) } Thread.sleep(InternalDebug.workerSleepMs) measureSpan("Span 3") { Thread.sleep(30) } Thread.sleep(30) } }
2
Kotlin
1
4
0c23eb8b5f56a480eb2d02ae399967558be69463
1,059
bugsnag-android-performance
MIT License
compass/src/main/kotlin/dev/arunkumar/compass/thread/RealmDispatcher.kt
arunkumar9t2
405,335,855
false
null
/* * Copyright 2021 Arunkumar * * 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 dev.arunkumar.compass.thread import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Runnable import kotlinx.coroutines.asCoroutineDispatcher import kotlin.coroutines.CoroutineContext public class RealmDispatcher( private val tag: String? = null, ) : CoroutineDispatcher(), AutoCloseable { private val realmExecutor by lazy { RealmExecutor(tag) } private val delegateDispatcher by lazy { realmExecutor.asCoroutineDispatcher() } override fun dispatch( context: CoroutineContext, block: Runnable ): Unit = delegateDispatcher.dispatch(context, block) override fun isDispatchNeeded( context: CoroutineContext ): Boolean = delegateDispatcher.isDispatchNeeded(context) override fun close(): Unit = realmExecutor.close() }
1
Kotlin
1
17
d62d90c554c89b1b39ab2e69211a5f480725d00a
1,367
compass
Apache License 2.0
app/src/androidTest/java/com/ricdip/tictactoegame/ni/NativeGameTest.kt
ricdip
616,663,823
false
null
package com.ricdip.tictactoegame.ni import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth import com.ricdip.tictactoegame.utils.Game import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NativeGameTest { @Test fun getBoardStatus() { val boardInputInit = BoardInput(".........", Game.WHITE) val boardOutputInit = NativeGame.getBoardStatus(boardInputInit) val boardInputWinX = BoardInput("X.OOX...X", Game.BLACK) val boardOutputWinX = NativeGame.getBoardStatus(boardInputWinX) val boardInputWinO = BoardInput("OXXO.XO..", Game.WHITE) val boardOutputWinO = NativeGame.getBoardStatus(boardInputWinO) val boardInputDraw = BoardInput("XOXXOOOXX", Game.BLACK) val boardOutputDraw = NativeGame.getBoardStatus(boardInputDraw) Truth.assertThat(boardOutputInit.gameOver).isEqualTo(false) Truth.assertThat(boardOutputInit.winner).isEqualTo(Game.NONE) Truth.assertThat(boardOutputInit.draw).isEqualTo(false) Truth.assertThat(boardOutputWinX.gameOver).isEqualTo(true) Truth.assertThat(boardOutputWinX.winner).isEqualTo(Game.WHITE) Truth.assertThat(boardOutputWinX.draw).isEqualTo(false) Truth.assertThat(boardOutputWinO.gameOver).isEqualTo(true) Truth.assertThat(boardOutputWinO.winner).isEqualTo(Game.BLACK) Truth.assertThat(boardOutputWinO.draw).isEqualTo(false) Truth.assertThat(boardOutputDraw.gameOver).isEqualTo(true) Truth.assertThat(boardOutputDraw.winner).isEqualTo(Game.NONE) Truth.assertThat(boardOutputDraw.draw).isEqualTo(true) } @Test fun getNextAiMove() { val boardInputInit = BoardInput(".........", Game.WHITE) val boardOutputInit = NativeGame.getBoardStatus(boardInputInit) val boardInputInGame = BoardInput(".X.......", Game.BLACK) val boardOutputInGame = NativeGame.getBoardStatus(boardInputInGame) val boardInputWinX = BoardInput("X.OOX...X", Game.BLACK) val boardOutputWinX = NativeGame.getBoardStatus(boardInputWinX) val boardInputWinO = BoardInput("OXXO.XO..", Game.WHITE) val boardOutputWinO = NativeGame.getBoardStatus(boardInputWinO) val boardInputDraw = BoardInput("XOXXOOOXX", Game.BLACK) val boardOutputDraw = NativeGame.getBoardStatus(boardInputDraw) Truth.assertThat(boardOutputInit.gameOver).isEqualTo(false) Truth.assertThat(boardOutputInit.winner).isEqualTo(Game.NONE) Truth.assertThat(boardOutputInit.draw).isEqualTo(false) Truth.assertThat(boardOutputInGame.gameOver).isEqualTo(false) Truth.assertThat(boardOutputInGame.winner).isEqualTo(Game.NONE) Truth.assertThat(boardOutputInGame.draw).isEqualTo(false) Truth.assertThat(boardOutputWinX.gameOver).isEqualTo(true) Truth.assertThat(boardOutputWinX.winner).isEqualTo(Game.WHITE) Truth.assertThat(boardOutputWinX.draw).isEqualTo(false) Truth.assertThat(boardOutputWinO.gameOver).isEqualTo(true) Truth.assertThat(boardOutputWinO.winner).isEqualTo(Game.BLACK) Truth.assertThat(boardOutputWinO.draw).isEqualTo(false) Truth.assertThat(boardOutputDraw.gameOver).isEqualTo(true) Truth.assertThat(boardOutputDraw.winner).isEqualTo(Game.NONE) Truth.assertThat(boardOutputDraw.draw).isEqualTo(true) } }
0
Kotlin
0
0
b30df60668209eed25c951b4c43f798406711e21
3,469
android-tic-tac-toe
MIT License
app/src/main/java/name/lmj0011/courierlocker/viewmodels/TripViewModel.kt
ashishkharcheiuforks
274,859,542
true
{"Kotlin": 253294}
package name.lmj0011.courierlocker.viewmodels import android.app.Application import android.content.SharedPreferences import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.preference.PreferenceManager import com.github.kittinunf.fuel.httpGet import com.github.kittinunf.fuel.json.responseJson import com.github.kittinunf.result.Result import com.mooveit.library.Fakeit import kotlinx.coroutines.* import name.lmj0011.courierlocker.database.Stop import name.lmj0011.courierlocker.database.Trip import name.lmj0011.courierlocker.database.TripDao import name.lmj0011.courierlocker.helpers.Util import name.lmj0011.courierlocker.helpers.isTripOfMonth import name.lmj0011.courierlocker.helpers.isTripOfToday import name.lmj0011.courierlocker.helpers.setTripTimestamp import org.json.JSONException import timber.log.Timber import java.net.URLEncoder class TripViewModel( val database: TripDao, application: Application ) : AndroidViewModel(application) { private var viewModelJob = Job() private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob) private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplication()) private val googleApiKey = preferences.getString("advancedDirectionsApiKey", "")!! var trips = database.getAllTrips() val trip = MutableLiveData<Trip?>() var payAmountValidated = MutableLiveData<Boolean?>() val totalMoney: String get() { val result = trips.value?.fold(0.0) { sum, trip -> val toAdd = trip.payAmount.toDoubleOrNull() if (toAdd == null){ sum } else { sum + toAdd } } result?.let{ return Util.numberFormatInstance.format(it) } return Util.numberFormatInstance.format(0.0) } val todayTotalMoney: String get() { val result = trips.value?.fold(0.0) { sum, trip -> val toAdd = trip.payAmount.toDoubleOrNull() if (toAdd == null || !isTripOfToday(trip)){ sum } else { sum + toAdd } } result?.let{ return Util.numberFormatInstance.format(it) } return Util.numberFormatInstance.format(0.0) } val todayCompletedTrips: String get() { val result = trips.value?.fold(0) { sum, trip -> if (isTripOfToday(trip) && trip.pickupAddress.isNotEmpty() && trip.dropOffAddress.isNotEmpty() ){ sum + 1 } else { sum } } result?.let{ return it.toString() } return "0" } val monthTotalMoney: String get() { val result = trips.value?.fold(0.0) { sum, trip -> val toAdd = trip.payAmount.toDoubleOrNull() if (toAdd == null || !isTripOfMonth(trip)){ sum } else { sum + toAdd } } result?.let{ return Util.numberFormatInstance.format(it) } return Util.numberFormatInstance.format(0.0) } override fun onCleared() { super.onCleared() viewModelJob.cancel() } fun setTrip(idx: Int) { uiScope.launch { val trip = withContext(Dispatchers.IO){ this@TripViewModel.database.get(idx.toLong()) } /// backwards compatibility for database v3 and lower trip?.let { when { it.stops != null && it.stops.size > 0 -> { // all good, this Trip was created "after" database v3 } else -> { // add pickup and dropOff address to empty Stops List for backwards compatibility val pickup = Stop(it.pickupAddress, it.pickupAddressLatitude, it.pickupAddressLongitude) val dropOff = Stop(it.dropOffAddress, it.dropOffAddressLatitude, it.dropOffAddressLongitude) it.stops.addAll(arrayOf(pickup, dropOff)) } } } /// this@TripViewModel.trip.postValue(trip) } } fun insertTrip( pickupAddress: String, pickupAddressLatitude: Double, pickupAddressLongitude: Double, dropOffAddress: String?, dropOffAddressLatitude: Double?, dropOffAddressLongitude: Double?, payAmount: String?, gigName: String, stops: Array<Stop> ) { uiScope.launch { val trip = Trip().apply { setTripTimestamp(this) this.pickupAddress = pickupAddress this.pickupAddressLatitude = pickupAddressLatitude this.pickupAddressLongitude = pickupAddressLongitude dropOffAddress?.let { this.dropOffAddress = it } dropOffAddressLatitude?.let { this.dropOffAddressLatitude = it } dropOffAddressLongitude?.let { this.dropOffAddressLongitude = it } payAmount?.let { this.payAmount = payAmount } this.gigName = gigName this.stops.addAll(stops) } withContext(Dispatchers.IO){ trip.distance = this@TripViewModel.setTripDistance(trip) this@TripViewModel.database.insert(trip) } } } fun updateTrip(trip: Trip?) { trip?.let { val stop = it.stops.last() it.dropOffAddress = stop.address it.dropOffAddressLatitude = stop.latitude it.dropOffAddressLongitude = stop.longitude } uiScope.launch { withContext(Dispatchers.IO){ trip?.let { it.distance = this@TripViewModel.setTripDistance(it) this@TripViewModel.database.update(it) } } } } fun deleteTrip(idx: Long) { uiScope.launch { withContext(Dispatchers.IO){ this@TripViewModel.database.deleteByTripId(idx) } } } fun insertNewRandomTripRow() { uiScope.launch { val trip = Trip( pickupAddress= "${Fakeit.address().streetAddress()}", dropOffAddress= "${Fakeit.address().streetAddress()}", payAmount = (1..40).random().toString(), gigName = "Doordash" ).apply { setTripTimestamp(this) } withContext(Dispatchers.IO){ this@TripViewModel.database.insert(trip) } } } /** * Deletes all Trips permanently */ fun clearAllTrips() { uiScope.launch { withContext(Dispatchers.IO){ this@TripViewModel.database.clear() } } } fun setTripDistance(trip: Trip?): Double { val defaultValue = 0.0 if (trip == null || googleApiKey.isNullOrBlank()) return defaultValue val sb = StringBuilder() // TODO will need to add waypoints for "Stops" https://developers.google.com/maps/documentation/directions/intro#Waypoints sb.append("https://maps.googleapis.com/maps/api/directions/json") sb.append("?mode=driving") sb.append("&origin=${trip.pickupAddressLatitude},${trip.pickupAddressLongitude}") sb.append("&destination=${trip.dropOffAddressLatitude},${trip.dropOffAddressLongitude}") sb.append("&waypoints=${generateWaypointsQueryStr(trip.stops)}") sb.append("&key=$googleApiKey") val (request, response, result) = sb.toString() .httpGet() .responseJson() return when (result) { is Result.Failure -> { val ex = result.getException() Timber.e("Result.Failure: ${ex.message}") return defaultValue } is Result.Success -> { try { var totalDistance = 0.toDouble() val data = result.value.obj() val route = data.getJSONArray("routes").getJSONObject(0) val legs = route.getJSONArray("legs") for (i in 0 until legs.length()) { val leg = legs.getJSONObject(i) totalDistance += leg.getJSONObject("distance").getDouble("value") } return totalDistance } catch (ex: JSONException) { Timber.e("JSONException: ${ex.message}") } return defaultValue } } } fun validatePayAmount(amount: String?): Boolean { return try { amount!!.toDouble() payAmountValidated.value = true true } catch (ex: Exception) { payAmountValidated.value = false false } } private fun generateWaypointsQueryStr(stops: MutableList<Stop>): String { // drop the first and last Stops, since those are already used for "origin" and "destination" val stops2 = stops.drop(1).dropLast(1) val str = stops2.fold(StringBuilder()) { sb, ele -> sb.append("${ele.latitude},${ele.longitude}|") }.toString() return URLEncoder.encode(str, "utf-8") } }
0
null
0
0
91de985cdcf7becff02d48747a09eb2ddd03d176
9,831
courier-locker
Apache License 2.0
src/main/kotlin/io/github/ydwk/yde/impl/entities/message/embed/FieldImpl.kt
YDWK
609,956,533
false
null
/* * Copyright 2022 YDWK inc. * * * 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 io.github.ydwk.yde.impl.entities.message.embed import com.fasterxml.jackson.databind.JsonNode import io.github.ydwk.yde.YDE import io.github.ydwk.yde.entities.message.embed.Field import io.github.ydwk.yde.util.EntityToStringBuilder class FieldImpl(override val yde: YDE, override val json: JsonNode) : Field { override val name: String get() = json["name"].asText() override val value: String get() = json["value"].asText() override val inline: Boolean? get() = if (json.has("inline")) json["inline"].asBoolean() else null override fun toString(): String { return EntityToStringBuilder(yde, this).name(this.name).toString() } }
5
Kotlin
0
0
00909dea196121e944b8b3e794337b407395ccc9
1,294
YDE
Apache License 2.0
android/app/src/main/java/com/psinder/myapplication/ui/profile/UserProfileViewModel.kt
Peltorator
402,524,109
false
null
package com.psinder.myapplication.ui.profile import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.psinder.myapplication.repository.AuthRepository import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.launch class UserProfileViewModel : ViewModel()
0
Kotlin
0
3
f929b307dee68c177c0bdd7dc163920a5e315354
308
psynder
Apache License 2.0
buildSrc/src/main/kotlin/com/elouyi/buildutils/LocalProperties.kt
Kazusa1412
399,684,507
false
null
package com.elouyi.buildutils import org.gradle.api.Project import java.io.FileInputStream import java.util.* import kotlin.reflect.KProperty class LocalProperties private constructor(delegate: Project) { // 简单单例 companion object { var localProperties: LocalProperties? = null fun getLocalProperties(project: Project): LocalProperties { return localProperties ?: LocalProperties(project) } } private val localProperties = Properties() init { localProperties.load(FileInputStream(delegate.rootProject.file("local.properties"))) } operator fun getValue(clazz: Any?,prop: KProperty<*>): String? { val propName = prop.name return localProperties[propName].run { if (this !== null) toString() else null } } operator fun get(key: String): Any? = localProperties[key] }
0
Kotlin
0
0
f15c9eb4f88eb282cf175370c4e77bf7269c50d7
901
lely
MIT License
app/src/main/java/dev/pimentel/rickandmorty/presentation/locations/LocationsAdapter.kt
bfpimentel
273,356,184
false
null
package dev.pimentel.rickandmorty.presentation.locations import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import dev.pimentel.rickandmorty.R import dev.pimentel.rickandmorty.databinding.LocationsItemBinding import dev.pimentel.rickandmorty.presentation.locations.dto.LocationsItem class LocationsAdapter : ListAdapter<LocationsItem, LocationsAdapter.ViewHolder>( DIFF_CALLBACK ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = ViewHolder( LocationsItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position), position) } inner class ViewHolder( private val binding: LocationsItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(location: LocationsItem, position: Int) { binding.apply { type.text = location.type name.text = location.name val layoutParams = root.layoutParams as ViewGroup.MarginLayoutParams val biggerMargin = root.resources.getDimensionPixelSize( R.dimen.common_item_bigger_margin ) val smallerMargin = root.resources.getDimensionPixelSize( R.dimen.common_item_smaller_margin ) if (position % 2 == 0) { layoutParams.marginStart = biggerMargin layoutParams.marginEnd = smallerMargin } else { layoutParams.marginStart = smallerMargin layoutParams.marginEnd = biggerMargin } layoutParams.topMargin = biggerMargin if (position >= itemCount - 2) { layoutParams.bottomMargin = biggerMargin } else { layoutParams.bottomMargin = 0 } } } } private companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<LocationsItem>() { override fun areItemsTheSame( oldItem: LocationsItem, newItem: LocationsItem ) = oldItem.id == newItem.id override fun areContentsTheSame( oldItem: LocationsItem, newItem: LocationsItem ) = oldItem.id == newItem.id } } }
0
Kotlin
1
1
0de46077173eeeef0d2e737e4618280d02075a31
2,688
rick-and-morty-app
MIT License
shared/src/commonMain/kotlin/com/kyle/quera/model/Response.kt
knmueller
874,508,841
false
{"Kotlin": 84558, "Dockerfile": 568}
package com.kyle.quera.model import kotlinx.serialization.Serializable @Serializable data class PagedResponse<T>( val elements: List<T>, val page: Int, val size: Int = elements.size, // keep this order to preserve response order of json keys val total: Long, )
0
Kotlin
0
0
4300d4253e7d56cb9fd4b5b3db3ca71fe0358ab6
278
QueraRoadService
MIT License
buildSrc/src/main/kotlin/AppInfo.kt
jakepurple13
353,155,453
false
{"Kotlin": 1921729}
object AppInfo { const val otakuVersionName = "31.0.2" const val compileVersion = 34 const val minimumSdk = 26 const val targetSdk = 34 }
13
Kotlin
21
397
8af30910a5c76c3a8eabbc57bacd92d11b7c0624
153
OtakuWorld
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/items/food/eating.kts
Cleako
177,039,011
true
{"Kotlin": 2535600, "CSS": 2003}
package gg.rsmod.plugins.content.items.food Food.values.forEach { food -> on_item_option(item = food.item, option = "eat") { val p = player if (!Foods.canEat(p, food)) { return@on_item_option } val inventorySlot = player.getInteractingItemSlot() if (p.inventory.remove(item = food.item, beginSlot = inventorySlot).hasSucceeded()) { Foods.eat(p, food) if (food.replacement != -1) { p.inventory.add(item = food.replacement, beginSlot = inventorySlot) } } } }
0
Kotlin
0
0
21d5fa429c5f231f09ed8ca0c537e18e31460fec
579
rsmod
Apache License 2.0
app_root/src/test/java/com/trian/di/DatabaseModuleTest.kt
triandamai
495,370,273
false
null
package com.trian.di import android.content.Context import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Named @Module @InstallIn(SingletonComponent::class) object DatabaseModuleTest { @Provides @Named("test_db") fun provideInMemoryDb(@ApplicationContext context: Context) = Room.inMemoryDatabaseBuilder(context, CexupDatabase::class.java).allowMainThreadQueries().build() }
0
Kotlin
0
0
66b41b294ca7347cc41b42b99f8203991964afed
560
starter-pack
Apache License 2.0
app/src/main/java/com/bengcare/bengcare/data/remote/response/DeleteReviewResponse.kt
BengCare
796,771,725
false
{"Kotlin": 239121}
package com.bengcare.bengcare.data.remote.response data class DeleteReviewResponse( val status: Boolean, val message: String )
0
Kotlin
0
0
ab6a63c29a225f107f1c7d4283fcdb1e6d4ae968
136
BengCare-Android
MIT License
app/src/main/java/com/example/myyelp/RestaurantsAdapter.kt
nicolelee1012
427,992,836
false
{"Kotlin": 8379}
package com.example.myyelp import android.content.Context import android.text.Layout import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RatingBar import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.CenterCrop import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestOptions private const val TAG = "RestaurantsAdapter" class RestaurantsAdapter(val context:Context, val restaurants: List<YelpRestaurant>, val onClickListener: OnClickListener) : RecyclerView.Adapter<RestaurantsAdapter.ViewHolder>() { interface OnClickListener { fun onItemClick(position: Int) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_restaurant, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val restaurant = restaurants[position] holder.bind(restaurant) holder.itemView.setOnClickListener{ Log.i(TAG, "$position was clicked") onClickListener.onItemClick(position) } } override fun getItemCount() = restaurants.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val tvName = itemView.findViewById<TextView>(R.id.tvName) private val tvNumReview = itemView.findViewById<TextView>(R.id.tvNumReview) private val tvAddress = itemView.findViewById<TextView>(R.id.tvAddress) private val tvCategory = itemView.findViewById<TextView>(R.id.tvCategory) private val tvDistance = itemView.findViewById<TextView>(R.id.tvDistance) private val tvPrice = itemView.findViewById<TextView>(R.id.tvPrice) private val ratingBar = itemView.findViewById<RatingBar>(R.id.ratingBar) private val imageView = itemView.findViewById<ImageView>(R.id.imageView) fun bind(restaurant: YelpRestaurant) { tvName.text = restaurant.name ratingBar.rating = restaurant.rating.toFloat() tvNumReview.text = "${restaurant.numReviews} Reviews" tvAddress.text = restaurant.location.address tvCategory.text = restaurant.categories[0].title tvDistance.text = restaurant.displayDistance() tvPrice.text = restaurant.price Glide.with(context).load(restaurant.imageUrl).transform(CenterCrop(), RoundedCorners(20)).into(imageView) } } }
0
Kotlin
0
0
b9658918f0038097a5a9b7437d138c64940995c2
2,707
MyYelp
Apache License 2.0
app/src/main/java/com/yusuforhan/booksapp/android/presentation/main/BookStoreApp.kt
Yusuf-Orhan
735,695,566
false
{"Kotlin": 161551}
package com.yusuforhan.booksapp.android.presentation.main import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class BookStoreApp : Application()
0
Kotlin
0
3
85c292a7284e52d709d5b22c598606793f7f6572
183
BooksApp
The Unlicense
oglHelper/src/main/java/com/dima6120/oglHelper/enums/TextureTarget.kt
dima6120
298,513,503
false
null
package com.dima6120.oglHelper.enums import android.opengl.GLES11Ext import android.opengl.GLES20 import android.opengl.GLES30 import com.dima6120.oglHelper.interfaces.GLConstEnumInterface enum class TextureTarget(val glesValue: Int) : GLConstEnumInterface { TEXTURE_EXTERNAL_OES(GLES11Ext.GL_TEXTURE_EXTERNAL_OES), TEXTURE_2D(GLES20.GL_TEXTURE_2D), TEXTURE_3D(GLES30.GL_TEXTURE_3D), TEXTURE_2D_ARRAY(GLES30.GL_TEXTURE_2D_ARRAY), TEXTURE_CUBE_MAP (GLES20.GL_TEXTURE_CUBE_MAP); override fun getGLESValue(): Int = glesValue }
0
Kotlin
0
0
d997580dd751d6ba82a6ad5ffbb56a7099aa63ba
550
OGLHelper
Apache License 2.0
oglHelper/src/main/java/com/dima6120/oglHelper/enums/TextureTarget.kt
dima6120
298,513,503
false
null
package com.dima6120.oglHelper.enums import android.opengl.GLES11Ext import android.opengl.GLES20 import android.opengl.GLES30 import com.dima6120.oglHelper.interfaces.GLConstEnumInterface enum class TextureTarget(val glesValue: Int) : GLConstEnumInterface { TEXTURE_EXTERNAL_OES(GLES11Ext.GL_TEXTURE_EXTERNAL_OES), TEXTURE_2D(GLES20.GL_TEXTURE_2D), TEXTURE_3D(GLES30.GL_TEXTURE_3D), TEXTURE_2D_ARRAY(GLES30.GL_TEXTURE_2D_ARRAY), TEXTURE_CUBE_MAP (GLES20.GL_TEXTURE_CUBE_MAP); override fun getGLESValue(): Int = glesValue }
0
Kotlin
0
0
d997580dd751d6ba82a6ad5ffbb56a7099aa63ba
550
OGLHelper
Apache License 2.0
src/main/java/com/cplusedition/bot/dsl/css/impl/Medium.kt
cplusedition
412,142,025
false
{"TypeScript": 3121002, "Java": 3005697, "JavaScript": 2745438, "HTML": 2273206, "Kotlin": 2011043, "CSS": 236922, "PureBasic": 147886, "LLVM": 117819, "Shell": 4832, "C": 4368, "M4": 603, "Makefile": 321}
/*! C+edition for Desktop, Community Edition. Copyright (C) 2021 Cplusedition Limited. All rights reserved. The author licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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.cplusedition.bot.dsl.css.impl import com.cplusedition.bot.dsl.css.api.IMedium class Medium(private val medium: String) : IMedium { fun medium(): String { return medium } override fun toString(): String { return medium } companion object { var all = "all," var braille = "braille," var embossed = "embossed," var handheld = "handheld," var print = "print," var projection = "projection," var screen = "screen," var speech = "speech," var tty = "tty," var tv = "tv;" } }
0
TypeScript
0
0
801e52da05ab50b56df4a1a7fbeacb09f6b4fa2e
1,339
cplusedition-desktop-ce
Apache License 2.0
src/main/kotlin/CEffectSound.kt
argcc
777,572,651
false
{"Kotlin": 451601}
package org.example class CEffectSound:CEffect() { override fun GetTypeId(): UInt { return 0x48u } }
0
Kotlin
0
0
7e58b1b74515577b14423443009bc2d04594184a
118
ei_reverse_consp
MIT License
src/main/kotlin/_2020/Day10.kt
thebrightspark
227,161,060
false
null
package _2020 import aocRun import splitToInts import kotlin.math.pow fun main() { aocRun(testInput1) { input -> val adapters = createSortedAdapterList(input) val differenceMap = (0 until adapters.size - 1) .map { adapters[it + 1] - adapters[it] } .groupBy { it } .mapValues { it.value.size } println(differenceMap) return@aocRun differenceMap[1]!! * differenceMap[3]!! } aocRun(testInput1) { input -> val adapters = createSortedAdapterList(input) val differences = (0 until adapters.size - 1).map { adapters[it + 1] - adapters[it] } println(differences) var count = 1 var i = 0 while (i < differences.size) { val curI = i i++ val diff = differences[curI] // We're only paying attention to differences of 1 if (diff != 1) continue // Count the size of this group of 1s var last = curI + 1 while (differences[last] == 1) last++ var range = last - curI // If group is only a single 1, then ignore if (range <= 1) continue if (range == 2) { // If group of 2, then only 2 permutations available println("$curI-$last = 2") count *= 2 } else { // Remove 1 from the range, as we need to always keep the last adapter before the next 3 jolt gap range -= 1 // Calculate number of permutations for range val permutations = 2F.pow(range).toInt() - 2F.pow(range - 2).toInt() println("$curI-$last = 2^$range - 2^${range - 2} = $permutations") count *= permutations } // Skip forward to i = last + 1 } return@aocRun count } } private fun createSortedAdapterList(input: String): List<Int> = input.splitToInts().toMutableList().apply { add(0) add(maxOrNull()!! + 3) sort() println(this) } private val testInput1 = """ 16 10 15 5 1 11 7 19 6 12 4 """.trimIndent() private val testInput2 = """ 28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3 """.trimIndent() private val puzzleInput = """ 99 128 154 160 61 107 75 38 15 11 129 94 157 84 121 14 119 48 30 10 55 108 74 104 91 45 134 109 164 66 146 44 116 89 79 32 149 1 136 58 96 7 60 23 31 3 65 110 90 37 43 115 122 52 113 123 161 50 95 150 120 101 126 151 114 127 73 82 162 140 51 144 36 4 163 85 42 59 67 64 86 49 2 145 135 22 24 33 137 16 27 70 133 130 20 21 83 143 100 41 76 17 """.trimIndent()
0
Kotlin
0
0
ee6031d155d0fce816b3bf70279bbc4f7ffef024
2,310
AdventOfCode
Creative Commons Zero v1.0 Universal
feature/connection/src/main/kotlin/flow/connection/Endpoint.kt
andrikeev
503,060,387
false
{"Kotlin": 877303, "HTML": 10376, "Shell": 177, "Dockerfile": 160}
package flow.connection import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import flow.models.settings.Endpoint internal val Endpoint.title: String @Composable get() = stringResource( when (this) { is Endpoint.Proxy -> R.string.connection_endpoint_proxy is Endpoint.Rutracker -> R.string.connection_endpoint_rutracker is Endpoint.Mirror -> R.string.connection_endpoint_mirror }, )
1
Kotlin
4
24
e7fc2c0c8b9a3606c4ace46e88063c75fe220700
485
Flow
MIT License
src/Day01.kt
carotkut94
572,816,808
false
null
fun main() { fun prepare(input:String): List<Long> { return input.split("\n\n").map { it.split("\n") }.map { it.sumOf { item -> item.toLong() } } } fun part1(input: List<Long>): Triple<Long, Long, Long> { var (first, second, third) = arrayOf(Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE) for(e in input){ if(e>first){ third = second second = first first = e }else if (e > second) { third = second second = e }else if (e > third) { third = e } } return Triple(first, second, third) } fun part2(triple: Triple<Long, Long, Long>): Long { return triple.first+triple.second+triple.third } val input = readAsString("Day01") val processedInput = prepare(input) val triple = part1(processedInput) println(triple.first) println(part2(triple)) }
0
Kotlin
0
0
ef3dee8be98abbe7e305e62bfe8c7d2eeff808ad
1,000
aoc-2022
Apache License 2.0
src/main/kotlin/no/nav/omsorgspenger/soknad/Søknad.kt
navikt
220,962,483
false
null
package no.nav.omsorgspenger.soknad import com.fasterxml.jackson.annotation.JsonAlias import io.ktor.http.* import no.nav.helse.dusseldorf.ktor.client.buildURL import no.nav.k9.søknad.Søknad import no.nav.omsorgspenger.barn.BarnOppslag import no.nav.omsorgspenger.soker.Søker import java.net.URI import java.net.URL import java.time.ZoneOffset import java.time.ZonedDateTime import java.util.* data class Søknad( val nyVersjon: Boolean, val søknadId: String = UUID.randomUUID().toString(), val mottatt: ZonedDateTime = ZonedDateTime.now(ZoneOffset.UTC), val språk: String, val kroniskEllerFunksjonshemming: Boolean, var barn: Barn, val sammeAdresse: Boolean?, val relasjonTilBarnet: SøkerBarnRelasjon? = null, val legeerklæring: List<URL>, val samværsavtale: List<URL>? = null, val harForståttRettigheterOgPlikter: Boolean, val harBekreftetOpplysninger: Boolean ) { infix fun oppdaterBarnsNorskIdentifikatorFra(listeOverBarnOppslag: List<BarnOppslag>) { if(this.barn.manglerNorskIdentifikator()){ barn oppdaterNorskIdentifikatorMed listeOverBarnOppslag.hentNorskIdentifikatorForBarn(barn.aktørId) } } fun tilKomplettSøknad( søker: Søker, k9Format: Søknad, k9MellomlagringIngress: URI, ) = KomplettSøknad( nyVersjon = nyVersjon, språk = språk, søknadId = søknadId, mottatt = mottatt, kroniskEllerFunksjonshemming = kroniskEllerFunksjonshemming, søker = søker, barn = barn, relasjonTilBarnet = relasjonTilBarnet, sammeAdresse = sammeAdresse, legeerklæring = legeerklæring.tilK9MellomLagringUrl(k9MellomlagringIngress), samværsavtale = samværsavtale?.tilK9MellomLagringUrl(k9MellomlagringIngress), harForståttRettigheterOgPlikter = harForståttRettigheterOgPlikter, harBekreftetOpplysninger = harBekreftetOpplysninger, k9FormatSøknad = k9Format ) } enum class SøkerBarnRelasjon() { @JsonAlias("mor") MOR(), @JsonAlias("far") FAR(), @JsonAlias("adoptivforelder") ADOPTIVFORELDER(), @JsonAlias("fosterforelder") FOSTERFORELDER() } fun List<URL>.tilK9MellomLagringUrl(baseUrl: URI): List<URL> = map { val idFraUrl = it.path.substringAfterLast("/") Url.buildURL( baseUrl = baseUrl, pathParts = listOf(idFraUrl) ).toURL() } private fun List<BarnOppslag>.hentNorskIdentifikatorForBarn(aktørId: String?) = find { it.aktørId == aktørId }?.identitetsnummer
0
Kotlin
0
0
5f91315bdfadd0c200a1e5bb65ff718626f4dec8
2,542
omsorgspenger-api
MIT License
wot-server/src/main/kotlin/dev/d1s/wot/server/service/WebhookService.kt
d1snin
513,986,150
false
{"Kotlin": 109906, "Shell": 846, "Dockerfile": 92}
/* * Copyright 2022 <NAME> and other Webhooks over Telegram project contributors * * 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 dev.d1s.wot.server.service import cc.popkorn.annotations.Injectable import cc.popkorn.injecting import com.soywiz.krypto.encoding.hex import dev.d1s.teabag.dto.DtoConverter import dev.d1s.teabag.dto.EntityWithDto import dev.d1s.teabag.dto.convertToDtoIf import dev.d1s.teabag.dto.ktorm.ExportedSequenceWithDto import dev.d1s.teabag.dto.ktorm.convertElementsToDtoIf import dev.d1s.teabag.ktorm.DEFAULT_LIMIT import dev.d1s.teabag.ktorm.DEFAULT_OFFSET import dev.d1s.teabag.postgresql.handlePsqlUniqueViolationOrThrow import dev.d1s.teabag.stdlib.exception.EntityNotFoundException import dev.d1s.wot.commons.dto.webhook.WebhookDto import dev.d1s.wot.commons.entity.webhook.WebhookNonce import dev.d1s.wot.commons.entity.webhook.WebhookState import dev.d1s.wot.server.bot.factory.TelegramBotFactory import dev.d1s.wot.server.entity.Target import dev.d1s.wot.server.entity.Webhook import dev.d1s.wot.server.entity.WebhookTarget import dev.d1s.wot.server.exception.UnavailableWebhookException import dev.d1s.wot.server.repository.WebhookRepository import dev.d1s.wot.server.repository.WebhookTargetRepository import dev.d1s.wot.server.util.idString import dev.inmo.tgbotapi.types.chat.Chat import org.lighthousegames.logging.logging import java.util.concurrent.ThreadLocalRandom interface WebhookService { suspend fun createWebhook(webhook: Webhook): EntityWithDto<Webhook, WebhookDto> suspend fun getWebhook(id: String, requireDto: Boolean = false): EntityWithDto<Webhook, WebhookDto> suspend fun getWebhookTargetsByTarget(target: Target): List<Webhook> suspend fun getWebhookByNonce(nonce: String, requireDto: Boolean = false): EntityWithDto<Webhook, WebhookDto> suspend fun getWebhooks( limit: Int?, offset: Int?, requireDto: Boolean = false ): ExportedSequenceWithDto<Webhook, WebhookDto> suspend fun updateWebhook(id: String, webhook: Webhook): EntityWithDto<Webhook, WebhookDto> suspend fun deleteWebhook(id: String) suspend fun isAvailable(nonce: String): Boolean suspend fun checkWebhookAvailability(webhook: Webhook) suspend fun subscribe(webhook: Webhook, chat: Chat) suspend fun unsubscribe(webhook: Webhook, chat: Chat) suspend fun isSubscribed(webhook: Webhook, chat: Chat): Boolean suspend fun hasAccess(chat: Chat, to: Webhook): Boolean suspend fun regenerateNonce(id: String): WebhookNonce } @Injectable class WebhookServiceImpl : WebhookService { private val log = logging() private val webhookRepository by injecting<WebhookRepository>() private val webhookTargetRepository by injecting<WebhookTargetRepository>() private val webhookDtoConverter by injecting<DtoConverter<WebhookDto, Webhook>>() private val targetService by injecting<TargetService>() private val telegramBotFactory by injecting<TelegramBotFactory>() override suspend fun createWebhook(webhook: Webhook): EntityWithDto<Webhook, WebhookDto> { log.d { "Creating webhook $webhook" } webhook.nonce = createNonce().nonce telegramBotFactory.getTelegramBot(webhook) handlePsqlUniqueViolationOrThrow { webhookRepository.add(webhook) } val dto = webhookDtoConverter.convertToDto(webhook) return webhook to dto } override suspend fun getWebhook(id: String, requireDto: Boolean): EntityWithDto<Webhook, WebhookDto> { val webhook = webhookRepository.findWebhookByIdOrNameOrBotTokenOrNonce(id) ?: throw EntityNotFoundException() return webhook to webhookDtoConverter.convertToDtoIf(webhook, requireDto) } override suspend fun getWebhookTargetsByTarget(target: Target) = webhookTargetRepository.findWebhookTargetsByTargetId(target.id).map(WebhookTarget::webhook) override suspend fun getWebhookByNonce(nonce: String, requireDto: Boolean): EntityWithDto<Webhook, WebhookDto> { val webhook = webhookRepository.findWebhookByNonce(nonce) ?: throw EntityNotFoundException() return webhook to webhookDtoConverter.convertToDtoIf(webhook, requireDto) } override suspend fun getWebhooks( limit: Int?, offset: Int?, requireDto: Boolean ): ExportedSequenceWithDto<Webhook, WebhookDto> { val webhooks = webhookRepository.findAllWebhooks(limit ?: DEFAULT_LIMIT, offset ?: DEFAULT_OFFSET) return webhooks to webhookDtoConverter.convertElementsToDtoIf(webhooks, requireDto) } override suspend fun updateWebhook(id: String, webhook: Webhook): EntityWithDto<Webhook, WebhookDto> { log.d { "Updating webhook $id with data $webhook" } val (existingWebhook, _) = this.getWebhook(id) existingWebhook.apply { this.name = webhook.name this.botToken = webhook.botToken this.private = webhook.private this.state = webhook.state this.targetType = webhook.targetType } handlePsqlUniqueViolationOrThrow { existingWebhook.flushChanges() } return existingWebhook to webhookDtoConverter.convertToDto(existingWebhook) } override suspend fun deleteWebhook(id: String) { log.d { "Deleting webhook $id" } val (webhook, _) = this.getWebhook(id) telegramBotFactory.stopTelegramBot(webhook) webhook.delete() } override suspend fun isAvailable(nonce: String): Boolean { val (webhook, _) = this.getWebhookByNonce(nonce) return webhook.isAvailable } override suspend fun checkWebhookAvailability(webhook: Webhook) { if (!webhook.isAvailable) { throw UnavailableWebhookException() } } override suspend fun subscribe(webhook: Webhook, chat: Chat) { log.d { "Subscribing ${chat.id} to webhook $webhook." } this.checkWebhookAvailability(webhook) if (webhook.isTargetAcquired) { error("No more targets allowed for webhook $webhook with CHANNEL target type. Only one target can be registered.") } webhookTargetRepository.add( WebhookTarget { this.webhook = webhook this.target = targetService.createOrGetTargetForChat(chat) } ) if (webhook.isAwaitingTarget) { webhook.state = WebhookState.AVAILABLE webhook.flushChanges() } log.d { "Successfully subscribed the chat to webhook $webhook." } } override suspend fun unsubscribe(webhook: Webhook, chat: Chat) { log.d { "Unsubscribing $chat from webhook $webhook." } val (target, _) = targetService.getTarget(chat.idString) webhookTargetRepository.deleteWebhookTarget(webhook, target) ?: throw EntityNotFoundException() log.d { "Successfully unsubscribed the chat from webhook $webhook." } } override suspend fun isSubscribed(webhook: Webhook, chat: Chat): Boolean = webhookTargetRepository.findWebhookTargetsByWebhookId(webhook.id).find { it.target.chatId == chat.idString } != null override suspend fun hasAccess(chat: Chat, to: Webhook): Boolean = !to.private || this.isSubscribed(to, chat) override suspend fun regenerateNonce(id: String): WebhookNonce { log.d { "Regenerating nonce for webhook $id" } val (webhook, _) = this.getWebhook(id) val generatedNonce = this.createNonce() webhook.nonce = generatedNonce.nonce webhook.flushChanges() return generatedNonce } private fun createNonce(): WebhookNonce { val buffer = ByteArray(BUFFER_SIZE) ThreadLocalRandom.current().nextBytes(buffer) return WebhookNonce(buffer.hex) } private companion object { private const val BUFFER_SIZE = 16 } }
5
Kotlin
0
2
1cb12aeffe5a7e395dc36742a58d9e3ea545e239
8,634
webhooks-over-tgm
Apache License 2.0
app/src/main/java/demo/movie/app/ui/recycler/callbacks/TvDiffUtilCallback.kt
MikrasovP
286,046,038
false
null
package demo.movie.app.ui.recycler.callbacks import androidx.recyclerview.widget.DiffUtil import demo.movie.app.model.dto.tv.TvPreviewDto class TvDiffUtilCallback( private val oldList: List<TvPreviewDto>, private val newList: List<TvPreviewDto> ) : DiffUtil.Callback() { override fun areItemsTheSame(oldPos: Int, newPos: Int): Boolean = oldList[oldPos].id == newList[newPos].id override fun areContentsTheSame(oldPos: Int, newPos: Int): Boolean = oldList[oldPos] == newList[newPos] override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size }
1
Kotlin
0
0
c8e1900fcc3803e145d7cac0c3de88aebeda316d
628
MovieGeek
MIT License
src/main/kotlin/com/mrkirby153/botcore/ConfirmationHandler.kt
mrkirby153
137,817,672
false
{"Kotlin": 149231}
package com.mrkirby153.botcore import com.mrkirby153.botcore.builder.ButtonBuilder import com.mrkirby153.botcore.builder.MessageBuilder import com.mrkirby153.botcore.command.slashcommand.dsl.SlashContext import com.mrkirby153.botcore.coroutine.await import com.mrkirby153.botcore.utils.SLF4J import kotlinx.coroutines.suspendCancellableCoroutine import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import net.dv8tion.jda.api.interactions.InteractionHook import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle import java.util.concurrent.atomic.AtomicLong import kotlin.coroutines.resume object ConfirmationHandler : ListenerAdapter() { private val log by SLF4J private var nextId = AtomicLong(1) private val interactions = mutableMapOf<Long, QueuedConfirmation>() private val componentsToInteractions = mutableMapOf<String, Long>() override fun onButtonInteraction(event: ButtonInteractionEvent) { val id = event.componentId val interactionId = componentsToInteractions[id] ?: return log.debug("Processing interaction $interactionId") val interaction = interactions.remove(interactionId) ?: return try { if (id == interaction.yes) { log.debug("$interactionId confirmed") event.deferReply().queue() interaction.callback.onSuccess(event.hook) } else if (id == interaction.no) { log.debug("$interactionId rejected") event.deferReply().queue() interaction.callback.onFail(event.hook) } } finally { componentsToInteractions.remove(interaction.yes) componentsToInteractions.remove(interaction.no) } } internal fun enqueue( callback: Callback, yes: String, no: String, allowedUsers: List<User> ): Long { val id = nextId.getAndIncrement() log.debug("Enqueueing a callback with Y:$yes, N:$no as ID $id") interactions[id] = QueuedConfirmation(callback, yes, no, allowedUsers.map { it.idLong }) componentsToInteractions[yes] = id componentsToInteractions[no] = id return id } internal fun dequeue(id: Long) { log.debug("De-queueing a callback with id $id") val queued = interactions.remove(id) if (queued != null) { componentsToInteractions.remove(queued.yes) componentsToInteractions.remove(queued.no) } } } /** * Confirms an interaction with two buttons, a "yes" button and a "no" button. Specify [yesButton] or * [noButton] to determine what the respective buttons look like. Specify [allowedUsers] to dictate * who can interact with the button. */ suspend fun SlashContext.confirm( ephemeral: Boolean = false, yesButton: (ButtonBuilder.() -> Unit)? = null, noButton: (ButtonBuilder.() -> Unit)? = null, allowedUsers: List<User> = listOf(user), builder: MessageBuilder.() -> Unit, ): Pair<InteractionHook, Boolean> { if (!ephemeral) check(allowedUsers.isNotEmpty()) { "At least one allowedUser must be specified with a non-ephemeral message" } val message = MessageBuilder().apply(builder) var buttons: Pair<String, String> message.apply { buttons = buildRow(yesButton, noButton) } reply(message.create()).setEphemeral(ephemeral).await() return suspendCancellableCoroutine { continuation -> val callback = object : Callback { override fun onSuccess(hook: InteractionHook) { continuation.resume(Pair(hook, true)) } override fun onFail(hook: InteractionHook) { continuation.resume(Pair(hook, false)) } } val id = ConfirmationHandler.enqueue(callback, buttons.first, buttons.second, allowedUsers) continuation.invokeOnCancellation { ConfirmationHandler.dequeue(id) } } } /** * Confirms an interaction with two buttons, a "yes" button and a "no" button. Specify [yesButton] or * [noButton] to determine what the respective buttons look like. Specify [allowedUser] to dictate * who can interact with the button. */ suspend fun InteractionHook.confirm( allowedUser: User, yesButton: (ButtonBuilder.() -> Unit)? = null, noButton: (ButtonBuilder.() -> Unit)? = null, builder: MessageBuilder.() -> Unit ) = confirm(listOf(allowedUser), yesButton, noButton, builder) /** * Confirms an interaction with two buttons, a "yes" button and a "no" button. Specify [yesButton] or * [noButton] to determine what the respective buttons look like. Specify [allowedUsers] to dictate * who can interact with the button. */ suspend fun InteractionHook.confirm( allowedUsers: List<User>, yesButton: (ButtonBuilder.() -> Unit)? = null, noButton: (ButtonBuilder.() -> Unit)? = null, builder: MessageBuilder.() -> Unit ): Pair<InteractionHook, Boolean> { val message = MessageBuilder().apply(builder) var buttons: Pair<String, String> message.apply { buttons = buildRow(yesButton, noButton) } editOriginal(message.edit()).await() return suspendCancellableCoroutine { continuation -> val callback = object : Callback { override fun onSuccess(hook: InteractionHook) { continuation.resume(Pair(hook, false)) } override fun onFail(hook: InteractionHook) { continuation.resume(Pair(hook, false)) } } val id = ConfirmationHandler.enqueue(callback, buttons.first, buttons.second, allowedUsers) continuation.invokeOnCancellation { ConfirmationHandler.dequeue(id) } } } private fun MessageBuilder.buildRow( yesButton: (ButtonBuilder.() -> Unit)?, noButton: (ButtonBuilder.() -> Unit)? ): Pair<String, String> { var yesId: String? = null var noId: String? = null actionRow { yesId = button { if (yesButton != null) { yesButton.invoke(this) } else { text = "Yes" style = ButtonStyle.SUCCESS } } noId = button { if (noButton != null) { noButton.invoke(this) } else { text = "No" style = ButtonStyle.DANGER } } } checkNotNull(yesId) { "Yes button was not invoked" } checkNotNull(noId) { "No button was not invoked" } return Pair(yesId!!, noId!!) } internal interface Callback { fun onSuccess(hook: InteractionHook) fun onFail(hook: InteractionHook) } private data class QueuedConfirmation( val callback: Callback, val yes: String, val no: String, val allowedUsers: List<Long> )
0
Kotlin
1
0
5d63c4c608d6d95a2044c0aa98a8c07606b7eeb4
6,904
bot-core
MIT License