path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/minhdtm/example/weapose/domain/usecase/GetSevenDaysWeatherUseCase.kt | hide-your-code | 497,644,916 | false | null | package com.minhdtm.example.weapose.domain.usecase
import android.content.Context
import com.google.android.gms.maps.model.LatLng
import com.minhdtm.example.weapose.R
import com.minhdtm.example.weapose.data.model.OneCallResponse
import com.minhdtm.example.weapose.domain.exception.WeatherException
import com.minhdtm.example.weapose.domain.repositories.WeatherRepository
import com.minhdtm.example.weapose.domain.usecase.base.FlowUseCase
import com.minhdtm.example.weapose.presentation.di.IoDispatcher
import com.minhdtm.example.weapose.presentation.utils.asFlow
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GetSevenDaysWeatherUseCase @Inject constructor(
@ApplicationContext private val context: Context,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher,
private val weatherRepository: WeatherRepository,
) : FlowUseCase<GetSevenDaysWeatherUseCase.Params, OneCallResponse>(ioDispatcher) {
override fun execute(params: Params?): Flow<OneCallResponse> = if (params == null) {
WeatherException.SnackBarException(message = context.getString(R.string.error_message_lat_lng_are_invalid))
.asFlow()
} else {
weatherRepository.getSevenDaysWeather(params.latLng)
}
data class Params(
val latLng: LatLng,
)
}
| 23 | Kotlin | 33 | 93 | 05e50205aac5e429f088fe56cf7b20a13766ee96 | 1,450 | weather_compose_clean_architecture | Apache License 2.0 |
provider/src/main/kotlin/de/qhun/declaration_provider/provider/gamepedia/GamepediaDeclarationProvider.kt | wartoshika | 319,145,505 | false | null | package de.qhun.declaration_provider.provider.gamepedia
import de.qhun.declaration_provider.domain.Declaration
import de.qhun.declaration_provider.domain.WowVersion
import de.qhun.declaration_provider.provider.DeclarationProvider
import de.qhun.declaration_provider.provider.gamepedia.GamepediaDetailDownloader.downloadDetails
import kotlinx.coroutines.coroutineScope
object GamepediaDeclarationProvider : DeclarationProvider {
override suspend fun provide(version: WowVersion): List<Declaration> = coroutineScope {
GamepediaOverviewDownloader
.downloadOverview(version)
.downloadDetails()
}
}
| 0 | Kotlin | 0 | 0 | bc26206f36ae06bdc9cb3e206b4baa22e8bcaf82 | 638 | wow-declaration-provider | MIT License |
compiler/util/src/org/jetbrains/kotlin/utils/fileUtils.kt | staltz | 49,639,828 | true | {"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831} | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.utils.fileUtils
import java.io.File
// TODO: move to stdlib as:
// public fun File?.readTextOrEmpty(encoding: String = Charset.defaultCharset().name()): String = this?.readText(encoding) ?: ""
public fun File?.readTextOrEmpty(): String = this?.readText() ?: ""
public fun File.withReplacedExtensionOrNull(oldExt: String, newExt: String): File? {
if (getName().endsWith(oldExt)) {
val path = getPath()
val pathWithoutExt = path.substring(0, path.length() - oldExt.length())
val pathWithNewExt = pathWithoutExt + newExt
return File(pathWithNewExt)
}
return null
} | 0 | Java | 1 | 1 | 80074c71fa925a1c7173e3fffeea4cdc5872460f | 1,240 | kotlin | Apache License 2.0 |
Entendendo-algoritmos/src/main/kotlin/Main.kt | antonio195 | 705,611,092 | false | {"Kotlin": 531} | fun main() {
val lista = ArrayList<Int>()
for (i in 0..9){
lista.add(i)
}
println(buscaBinaria(lista, 2))
}
| 0 | Kotlin | 0 | 0 | 4d586bfc1aa3833d2508abc2b3121fb4c10d1b49 | 133 | entendendo-algoritmos | Apache License 2.0 |
app/src/main/java/com/example/newstrending/data/model/NewSourceResponse.kt | pavanmankar | 716,406,389 | false | {"Kotlin": 67346} | package com.example.newstrending.data.model
data class NewSourceResponse(
val sources: List<NewSource>,
val status: String
) | 0 | Kotlin | 2 | 5 | 965c4dd0681807bbc62e9ff2a87fb5efbb92ac9f | 133 | newsAppDaggerHilt | Apache License 2.0 |
src/commonMain/kotlin/epicarchitect/breakbadhabits/resources/strings/habits/dashboard/HabitDashboardStrings.kt | epicarchitect | 502,453,185 | false | {"Kotlin": 260243, "Swift": 548} | package epicarchitect.breakbadhabits.resources.strings.habits.dashboard
interface HabitDashboardStrings {
fun habitHasNoEvents(): String
fun showAllTracks(): String
fun addHabitEventRecord(): String
fun abstinenceChartTitle(): String
fun statisticsTitle(): String
fun statisticsAverageAbstinenceTime(): String
fun statisticsMaxAbstinenceTime(): String
fun statisticsMinAbstinenceTime(): String
fun statisticsDurationSinceFirstTrack(): String
fun statisticsCountEventsInCurrentMonth(): String
fun statisticsCountEventsInPreviousMonth(): String
fun statisticsTotalCountEvents(): String
} | 2 | Kotlin | 1 | 31 | 2745c8e4ef0cb7a24fef2efd0e4d368e1c345fd1 | 634 | breakbadhabits | MIT License |
dataprovider/src/main/java/co/com/lafemmeapp/dataprovider/network/entities/DeviceRegisterParams.kt | Informatica-Empresarial | 106,600,201 | false | null | package co.com.lafemmeapp.dataprovider.network.entities
/**
* Created by oscargallon on 5/29/17.
*/
data class DeviceRegisterParams(val userUuid: String,
val platform: String? = "Android",
val deviceUuid: String,
val appIdentifier: String,
val deviceData: String? = null)
| 1 | null | 1 | 1 | 486ab3eab99e9a06e70e32d1cbe34a9fa5a7fd81 | 403 | AppAndroid | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/uievents/DragEvent.factory.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6891970} | // Automatically generated - do not modify!
@file:Suppress(
"NOTHING_TO_INLINE",
)
package web.uievents
import web.events.EventTarget
import web.events.EventType
inline fun DragEvent(
type: EventType<DragEvent<EventTarget>>,
): DragEvent<*> =
DragEvent<EventTarget?>(
type = type,
)
inline fun DragEvent(
type: EventType<DragEvent<EventTarget>>,
init: DragEventInit,
): DragEvent<*> =
DragEvent<EventTarget?>(
type = type,
init = init,
)
| 0 | Kotlin | 7 | 28 | 8b3f4024ebb4f67e752274e75265afba423a8c38 | 499 | types-kotlin | Apache License 2.0 |
app/src/main/java/gr/pchasapis/moviedb/mvvm/viewModel/home/HomeViewModel.kt | pandelisgreen13 | 210,415,019 | false | null | package gr.pchasapis.moviedb.mvvm.viewModel.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import gr.pchasapis.moviedb.common.SingleLiveEvent
import gr.pchasapis.moviedb.model.data.HomeDataModel
import gr.pchasapis.moviedb.model.data.MovieDataModel
import gr.pchasapis.moviedb.mvvm.interactor.home.HomeInteractorImpl
import gr.pchasapis.moviedb.mvvm.viewModel.base.BaseViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.*
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(private val homeInteractor: HomeInteractorImpl) : BaseViewModel() {
private lateinit var searchMutableLiveData: MutableLiveData<MutableList<HomeDataModel>>
private var theatreMutableLiveData: SingleLiveEvent<MutableList<MovieDataModel>> = SingleLiveEvent()
private var finishPaginationLiveData: MutableLiveData<Boolean> = MutableLiveData()
private var toolbarTitleLiveData: MutableLiveData<Boolean> = MutableLiveData()
private var paginationLoaderLiveData: MutableLiveData<Boolean> = MutableLiveData()
private var searchList = mutableListOf<HomeDataModel>()
private var databaseList = mutableListOf<HomeDataModel>()
private var page = 0
private var isFetching = false
private var queryText = ""
fun getSearchList(): LiveData<MutableList<HomeDataModel>> {
if (!::searchMutableLiveData.isInitialized) {
searchMutableLiveData = MutableLiveData()
fetchSearchResult()
}
return searchMutableLiveData
}
fun getMovieInTheatre(): SingleLiveEvent<MutableList<MovieDataModel>> {
return theatreMutableLiveData
}
fun getPaginationStatus(): LiveData<Boolean> {
return finishPaginationLiveData
}
fun getPaginationLoader(): LiveData<Boolean> {
return paginationLoaderLiveData
}
fun fetchSearchResult() {
if (isFetching() || queryText.isEmpty()) {
return
}
setFetching(true)
uiScope.launch {
if (page == 0) {
loadingLiveData.value = true
}
page++
homeInteractor.onRetrieveSearchResult(queryText, page).collect { response ->
response.data?.let {
emptyLiveData.value = false
finishPaginationLiveData.value = isPaginationFinished(it.firstOrNull()?.page
?: 0, it.firstOrNull()?.totalPage ?: 0)
searchList.addAll(it)
searchMutableLiveData.value = searchList
} ?: run {
Timber.e(response.throwable.toString())
onErrorThrowable(response.throwable)
finishPaginationLiveData.value = true
}
paginationLoaderLiveData.value = false
loadingLiveData.value = false
setFetching(false)
}
}
}
@Synchronized
private fun isFetching(): Boolean {
return this.isFetching
}
@Synchronized
private fun setFetching(isFetching: Boolean) {
this.isFetching = isFetching
}
private fun resetPagination() {
if (queryText.isEmpty()) {
return
}
page = 0
searchList.clear()
}
fun setQueryText(queryText: String) {
this.queryText = queryText
}
private fun isPaginationFinished(page: Int, totalPages: Int): Boolean {
return page >= totalPages
}
fun updateModel(updatedHomeDataModel: HomeDataModel?) {
if (updatedHomeDataModel?.id == null) {
return
}
searchList.map {
return@map when (it.id) {
updatedHomeDataModel.id -> it.isFavorite = updatedHomeDataModel.isFavorite
else -> it
}
}
}
fun searchForResults() {
fetchSearchResult()
resetPagination()
}
private fun filterListByQuery() {
if (queryText.isEmpty()) {
searchMutableLiveData.value = databaseList
return
}
val queryList = databaseList.filter {
it.title?.lowercase(Locale.getDefault())?.contains(queryText.toLowerCase(Locale.getDefault()), true)
?: false
}
searchMutableLiveData.value = queryList.toMutableList()
}
fun fetchMovieInTheatre() {
loadingLiveData.value = true
uiScope.launch {
val response = homeInteractor.getMoviesInTheatres()
loadingLiveData.value = false
response.data?.let {
theatreMutableLiveData.value = it.toMutableList()
} ?: response.throwable?.let {
Timber.e(it.toString())
searchMutableLiveData.value = searchList
} ?: run {
searchMutableLiveData.value = searchList
}
}
}
}
| 0 | Kotlin | 0 | 4 | e4d1ff7cf4417db4ecfa9a4bad083fe7955613eb | 5,054 | movieDB | MIT License |
enro-processor/src/main/java/dev/enro/processor/extensions/Element.implements.kt | isaac-udy | 256,179,010 | false | {"Kotlin": 1447007} | package dev.enro.processor.extensions
import com.squareup.javapoet.ClassName
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Element
import javax.lang.model.element.TypeElement
internal fun Element.implements(
processingEnv: ProcessingEnvironment,
className: ClassName
): Boolean {
if (this !is TypeElement) return false
val typeMirror = processingEnv.typeUtils.erasure(
processingEnv.elementUtils.getTypeElement(
className.canonicalName()
).asType()
)
return processingEnv.typeUtils.isAssignable(asType(), typeMirror)
}
| 1 | Kotlin | 13 | 246 | fab4af27fd1d0c066f1ad99ded202e1c6b16c575 | 616 | Enro | Apache License 2.0 |
data-android/network/src/main/java/dev/shuanghua/weather/data/android/network/NetworkDataSource.kt | shuanghua | 479,336,029 | false | null | package dev.shuanghua.weather.data.android.network
import dev.shuanghua.weather.data.android.model.params.CityListParams
import dev.shuanghua.weather.data.android.model.params.DistrictParams
import dev.shuanghua.weather.data.android.model.params.FavoriteCityParams
import dev.shuanghua.weather.data.android.model.params.SearchCityByKeywordsParams
import dev.shuanghua.weather.data.android.model.params.WeatherParams
import dev.shuanghua.weather.data.android.network.api.ShenZhenApi
import dev.shuanghua.weather.data.android.network.model.ShenZhenCity
import dev.shuanghua.weather.data.android.network.model.ShenZhenDistrict
import dev.shuanghua.weather.data.android.network.model.ShenZhenFavoriteCityWeather
import dev.shuanghua.weather.data.android.network.model.ShenZhenProvince
import dev.shuanghua.weather.data.android.network.model.ShenZhenWeather
import dev.shuanghua.weather.data.android.serializer.NetworkParamsSerialization
import javax.inject.Inject
interface NetworkDataSource {
suspend fun getMainWeather(
params: WeatherParams,
): ShenZhenWeather
suspend fun getDistrictWithStationList(
params: DistrictParams,
): List<ShenZhenDistrict>?
suspend fun getFavoriteCityWeatherList(
params: FavoriteCityParams,
): List<ShenZhenFavoriteCityWeather>
suspend fun getProvinceList(): List<ShenZhenProvince>
suspend fun getCityList(
params: CityListParams,
): List<ShenZhenCity>
suspend fun searchCityByKeyword(
params: SearchCityByKeywordsParams,
): List<ShenZhenCity>
}
class RetrofitNetworkDataSource @Inject constructor(
private val szApi: ShenZhenApi,
private val serializer: NetworkParamsSerialization,
) : NetworkDataSource {
/**
* 首页天气 + 收藏页-站点天气
*/
override suspend fun getMainWeather(
params: WeatherParams,
): ShenZhenWeather {
return szApi.getMainWeather(
serializer.weatherParamsToJson(params)
).data
}
/**
* 观测区县 + 每个区下对应的站点列表
* 服务器上,非广东城市的站点列表数据为 null
*/
override suspend fun getDistrictWithStationList(
params: DistrictParams,
): List<ShenZhenDistrict>? = szApi.getDistrictWithStationList(
serializer.districtListParamsToJson(params)
).data.list
/**
* 收藏-城市天气
* 收藏页面有两个请求接口
* 站点天气请求和首页是公用的 getMainWeather(params: WeatherParams)
*/
override suspend fun getFavoriteCityWeatherList(
params: FavoriteCityParams,
): List<ShenZhenFavoriteCityWeather> = szApi.getFavoriteCityWeather(
serializer.favoriteCityParamsToJson(params)
).data.list
/**
* 省份页面不需要额外参数
* 它只有一个 Url
*/
override suspend fun getProvinceList(
): List<ShenZhenProvince> = szApi.getProvinces().data.list
override suspend fun getCityList(
params: CityListParams,
): List<ShenZhenCity> = szApi.getCityList(
serializer.cityListParamsToJson(params)
).data.cityList
override suspend fun searchCityByKeyword(
params: SearchCityByKeywordsParams,
): List<ShenZhenCity> = emptyList()
}
| 0 | Kotlin | 0 | 0 | 4b69fe4f435363faa6367cf0e955b733e86dc649 | 3,099 | jianmoweather | Apache License 2.0 |
L7/TaskMaster/app/src/main/java/com/example/taskmaster/Task.kt | Spiryd | 609,987,379 | false | {"Kotlin": 71319, "Java": 2655} | package com.example.taskmaster
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import taskdb.TaskEntity
@Parcelize
class Task( var id: Long = 0, var description: String): Parcelable {
} | 0 | Kotlin | 0 | 0 | 68e31374c5e9f2c737bb970025affc017d7174ee | 204 | MobileApplications | The Unlicense |
app/src/main/java/com/qm/cleanmodule/data/remote/ErrorResponse.kt | Qenawi | 415,690,721 | false | null | package com.qm.cleanmodule.data.remote
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
//MARK:- ErrorResponse @Docs
@Parcelize
data class ErrorResponse(
@field:SerializedName("code")
val code: Int? = null,
@field:SerializedName("message")
val message: String? = null,
@field:SerializedName("validation")
val validation: List<String?>? = null,
) : Parcelable
| 0 | Kotlin | 0 | 0 | 77ab5bba0e4c5a09da778a187dabe34aa062b451 | 435 | youtube | MIT License |
backend/src/main/kotlin/top/kanetah/planhv2/backend/entity/Subject.kt | kanetah | 118,541,878 | false | {"JavaScript": 104696, "Kotlin": 96766, "HTML": 5613, "CSS": 1941, "Dockerfile": 207} | package top.kanetah.planhv2.backend.entity
import top.kanetah.planhv2.backend.annotation.Entity
import java.util.*
/**
* created by kane on 2018/1/23
*/
@Entity
data class Subject(
val subjectId: Int = Int.MIN_VALUE,
val subjectName: String,
val teacherName: String,
val emailAddress: String,
val teamLimit: IntArray? = null,
val recommendProcessorId: Int
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Subject
if (subjectId != other.subjectId) return false
if (subjectName != other.subjectName) return false
if (teacherName != other.teacherName) return false
if (emailAddress != other.emailAddress) return false
if (!Arrays.equals(teamLimit, other.teamLimit)) return false
if (recommendProcessorId != other.recommendProcessorId) return false
return true
}
override fun hashCode(): Int {
var result = subjectId
result = 31 * result + subjectName.hashCode()
result = 31 * result + teacherName.hashCode()
result = 31 * result + emailAddress.hashCode()
result = 31 * result + Arrays.hashCode(teamLimit)
result = 31 * result + recommendProcessorId
return result
}
}
| 44 | JavaScript | 0 | 2 | f386b724d08a6fe9afdc8119ddccf7f57a717301 | 1,360 | planhv2 | MIT License |
app/src/main/java/com/mr3y/poodle/presentation/SearchScreenViewModel.kt | mr3y-the-programmer | 510,513,007 | false | {"Kotlin": 126309} | package com.mr3y.poodle.presentation
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.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mr3y.poodle.domain.SearchForArtifactsUseCase
import com.mr3y.poodle.domain.SearchUiState
import com.mr3y.poodle.repository.SearchQuery
import com.mr3y.poodle.repository.SearchResult
import com.mr3y.poodle.repository.Source
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
private const val SEARCH_QUERY_DEBOUNCE_THRESHOLD = 600L
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class SearchScreenViewModel @Inject constructor(
private val searchForArtifactsUseCase: SearchForArtifactsUseCase
) : ViewModel() {
var searchQuery = mutableStateOf(SearchQuery.EMPTY)
private set
var isSearchOnMavenEnabled = mutableStateOf(true)
private set
var isSearchOnJitPackEnabled = mutableStateOf(true)
private set
private var internalState by mutableStateOf(SearchUiState.Initial)
val homeState: StateFlow<SearchUiState> = combine(
snapshotFlow { searchQuery.value }.debounce(SEARCH_QUERY_DEBOUNCE_THRESHOLD),
snapshotFlow { isSearchOnMavenEnabled.value },
snapshotFlow { isSearchOnJitPackEnabled.value }
) { query, enableSearchingOnMaven, enableSearchingOnJitPack ->
searchForArtifactsUseCase(
query,
enableSearchingOnMaven,
enableSearchingOnJitPack
).map { searchResult ->
Snapshot.withMutableSnapshot {
internalState = reduce(
internalState,
searchResult,
enableSearchingOnMaven,
enableSearchingOnJitPack
)
}
internalState
}
}
.flatMapLatest { it }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 5000),
initialValue = internalState
)
fun toggleSearchOnMaven(enabled: Boolean) {
Snapshot.withMutableSnapshot {
isSearchOnMavenEnabled.value = enabled
}
}
fun toggleSearchOnJitPack(enabled: Boolean) {
Snapshot.withMutableSnapshot {
isSearchOnJitPackEnabled.value = enabled
}
}
fun updateSearchQuery(
searchText: String? = null,
groupId: String? = null,
limit: Int? = null,
packaging: String? = null,
tags: Set<String>? = null,
containsClassSimpleName: String? = null,
containsClassFQN: String? = null
) {
Snapshot.withMutableSnapshot {
searchQuery.value = searchQuery.value.copy(
text = searchText ?: searchQuery.value.text,
groupId = groupId ?: searchQuery.value.groupId,
limit = limit ?: searchQuery.value.limit,
packaging = packaging ?: searchQuery.value.packaging,
tags = tags ?: searchQuery.value.tags,
containsClassSimpleName = containsClassSimpleName ?: searchQuery.value.containsClassSimpleName,
containsClassFullyQualifiedName = containsClassFQN ?: searchQuery.value.containsClassFullyQualifiedName
)
}
}
internal fun reduce(
previousState: SearchUiState,
searchResult: SearchResult?,
isSearchingOnMavenEnabled: Boolean = true,
isSearchingOnJitPackEnabled: Boolean = true
): SearchUiState {
if (searchResult == null) return SearchUiState.Initial
val (artifacts, source) = searchResult
val mavenCentralArtifacts = when {
isSearchingOnMavenEnabled && source == Source.MavenCentral -> artifacts
isSearchingOnMavenEnabled -> previousState.mavenCentralArtifacts
else -> null
}
val jitPackArtifacts = when {
isSearchingOnJitPackEnabled && source == Source.JitPack -> artifacts
isSearchingOnJitPackEnabled -> previousState.jitPackArtifacts
else -> null
}
return SearchUiState(
mavenCentralArtifacts = mavenCentralArtifacts,
jitPackArtifacts = jitPackArtifacts,
metadata = searchForArtifactsUseCase.getAdditionalMetadata()
)
}
}
| 0 | Kotlin | 0 | 0 | 6d8e1723b385243e0dfff06fab7dbd47ab1a7f80 | 4,914 | Poodle | Apache License 2.0 |
platforms/android/library-compose/src/main/java/io/element/android/wysiwyg/compose/EditorStyledText.kt | matrix-org | 508,730,706 | false | {"Rust": 977569, "Kotlin": 346077, "Swift": 321966, "TypeScript": 247731, "Shell": 7329, "HTML": 5880, "JavaScript": 4482, "Objective-C": 3675, "Makefile": 1835, "CSS": 1782, "Ruby": 80} | package io.element.android.wysiwyg.compose
import android.text.Spanned
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import io.element.android.wysiwyg.EditorStyledTextView
import io.element.android.wysiwyg.compose.internal.applyStyle
import io.element.android.wysiwyg.compose.internal.rememberTypeface
import io.element.android.wysiwyg.compose.internal.toStyleConfig
import io.element.android.wysiwyg.display.MentionDisplayHandler
/**
* A composable EditorStyledText.
* This composable is a wrapper around the [EditorStyledTextView] view.
*
* @param text The text to render.
* If it's spanned it will be rendered as is, otherwise it will go first to HtmlConverter.
* Your might want to use HtmlConverter before the rendering to avoid the conversion at each recomposition.
* @param modifier The modifier for the layout.
* @param style The styles to use for any customisable elements.
*/
@Composable
fun EditorStyledText(
text: CharSequence,
modifier: Modifier = Modifier,
mentionDisplayHandler: MentionDisplayHandler? = null,
style: RichTextEditorStyle = RichTextEditorDefaults.style(),
) {
val typeface = style.text.rememberTypeface()
AndroidView(modifier = modifier, factory = { context ->
EditorStyledTextView(context)
}, update = { view ->
view.setStyleConfig(style.toStyleConfig(view.context))
view.applyStyle(style)
view.typeface = typeface
view.mentionDisplayHandler = mentionDisplayHandler
if (text is Spanned) {
view.text = text
} else {
view.setHtml(text.toString())
}
})
} | 40 | Rust | 15 | 65 | cb9644b6d26d68e24863abc72452a1d96e91cec0 | 1,697 | matrix-rich-text-editor | Apache License 2.0 |
app/src/main/java/com/upai/commonnetworkdemo/util/CommonData.kt | sya233 | 281,869,563 | false | null | package com.upai.commonnetworkdemo.util
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.upai.commonnetworkdemo.R
import kotlinx.android.synthetic.main.rv_item_ok_http.view.*
const val version = "1.0"
const val key = "<KEY>"
const val address = "http://api.juheapi.com/japi"
// bean
data class History(
val result: List<Result>,
val reason: String,
val error_code: String
)
data class Result(
val _id: String,
val title: String,
val pic: String,
val year: String,
val month: String,
val day: String,
val des: String,
val lunar: String
)
// RecyclerView
class HistoryAdapter : RecyclerView.Adapter<HistoryAdapter.Holder>() {
var historyList: List<Result> = arrayListOf()
fun updateList(list: List<Result>) {
historyList = list
}
override fun onBindViewHolder(holder: Holder, position: Int) {
Glide.with(holder.itemView.civPic.context).load(historyList[position].pic)
.into(holder.itemView.civPic)
holder.itemView.tvTitle.text = historyList[position].title
val time: String =
"${historyList[position].year}-${historyList[position].month}-${historyList[position].day}"
holder.itemView.tvTime.text = time
holder.itemView.tvDes.text = historyList[position].des
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(
R.layout.rv_item_ok_http,
parent, false
)
return Holder(view)
}
override fun getItemCount(): Int {
return historyList.size
}
class Holder(itemView: View) : RecyclerView.ViewHolder(itemView)
} | 0 | Kotlin | 0 | 0 | 688696726032ac0a6f5bb2f72c5594302455792e | 1,839 | common-network-demo | Apache License 2.0 |
app/src/main/java/com/kssidll/arru/ui/screen/modify/item/edititem/EditItemRoute.kt | KSSidll | 655,360,420 | false | {"Kotlin": 1021398} | package com.kssidll.arru.ui.screen.modify.item.edititem
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.res.stringResource
import com.kssidll.arru.R
import com.kssidll.arru.domain.data.Data
import com.kssidll.arru.ui.screen.modify.item.ModifyItemScreenImpl
import dev.olshevski.navigation.reimagined.hilt.hiltViewModel
import kotlinx.coroutines.launch
@Composable
fun EditItemRoute(
itemId: Long,
navigateBack: () -> Unit,
navigateBackDelete: () -> Unit,
navigateProductAdd: (query: String?) -> Unit,
navigateVariantAdd: (productId: Long, query: String?) -> Unit,
navigateProductEdit: (productId: Long) -> Unit,
navigateVariantEdit: (variantId: Long) -> Unit,
providedProductId: Long?,
providedVariantId: Long?,
) {
val scope = rememberCoroutineScope()
val viewModel: EditItemViewModel = hiltViewModel()
LaunchedEffect(itemId) {
if (!viewModel.updateState(itemId)) {
navigateBack()
}
}
LaunchedEffect(
providedProductId,
providedVariantId
) {
viewModel.setSelectedProductToProvided(
providedProductId,
providedVariantId
)
}
ModifyItemScreenImpl(
onBack = navigateBack,
state = viewModel.screenState,
products = viewModel.allProducts()
.collectAsState(initial = Data.Loading()).value,
variants = viewModel.productVariants.collectAsState(initial = Data.Loading()).value,
onNewProductSelected = {
scope.launch {
viewModel.onNewProductSelected(it)
}
},
onNewVariantSelected = {
viewModel.onNewVariantSelected(it)
},
onSubmit = {
scope.launch {
if (viewModel.updateItem(itemId)
.isNotError()
) {
navigateBack()
}
}
},
onDelete = {
scope.launch {
if (viewModel.deleteItem(itemId)
.isNotError()
) {
navigateBackDelete()
}
}
},
submitButtonText = stringResource(id = R.string.item_edit),
onProductAddButtonClick = navigateProductAdd,
onVariantAddButtonClick = navigateVariantAdd,
onItemLongClick = navigateProductEdit,
onItemVariantLongClick = navigateVariantEdit,
)
}
| 3 | Kotlin | 1 | 38 | 19906cc3e517ec30849f6ab33be83315cd45918b | 2,627 | Arru | BSD 3-Clause Clear License |
feature_add_curation/src/main/java/com/phicdy/mycuration/feature/addcuration/AddCurationTextFieldType.kt | phicdy | 24,188,186 | false | {"Kotlin": 688608, "HTML": 1307, "Shell": 1127} | package com.phicdy.mycuration.feature.addcuration
enum class AddCurationTextFieldType {
TITLE, WORD
} | 38 | Kotlin | 9 | 30 | c270cb9f819dfcb6a2ac4b9ee5ddc459c698497f | 106 | MyCuration | The Unlicense |
build-tools/conventions/src/main/kotlin/PendantMetadataPlugin.kt | Morfly | 699,622,261 | false | {"Kotlin": 490264} | import io.morfly.pendant.buildtools.PendantConventionPlugin
class PendantMetadataPlugin : PendantConventionPlugin({})
object PendantMetadata {
const val JVM_TOOLCHAIN_VERSION = 8
const val KOTLIN_LANGUAGE_VERSION = "1.7"
const val ARTIFACT_GROUP = "io.morfly.pendant"
} | 0 | Kotlin | 0 | 3 | 1d9e226088ecdb5fc1b32eecfc9fa16dde99dec8 | 284 | pendant | Apache License 2.0 |
tcn-client-android/tcn-client-android/src/main/java/org/tcncoalition/tcnclient/bluetooth/BeaconData.kt | generalmotors | 279,946,799 | true | {"Kotlin": 257493, "Java": 5776} | package org.tcncoalition.tcnclient.bluetooth
import java.nio.ByteBuffer
import java.util.*
class BeaconData {
public var deviceName: String? = null
public var uuid: String? = null
public var rssi: Int? = 0
public var txPower: Int? = 0
} | 1 | Kotlin | 2 | 1 | 41c9eefcc48f584a5544f7c92b6fc95e89e11f9c | 259 | covidwatch-android-tcn | Apache License 2.0 |
src/main/kotlin/me/rafaelldi/aspire/sessionHost/AspireSessionHostRunner.kt | rafaelldi | 723,084,178 | false | {"Kotlin": 90965, "C#": 40585} | package me.rafaelldi.aspire.sessionHost
import com.intellij.execution.CantRunException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.KillableColoredProcessHandler
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.process.ProcessOutputType
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.createNestedDisposable
import com.intellij.openapi.rd.util.launchOnUi
import com.intellij.openapi.rd.util.withUiContext
import com.intellij.openapi.util.Key
import com.jetbrains.rd.framework.*
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
import com.jetbrains.rd.util.lifetime.isNotAlive
import com.jetbrains.rdclient.protocol.RdDispatcher
import com.jetbrains.rider.runtime.RiderDotNetActiveRuntimeHost
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow
import me.rafaelldi.aspire.generated.*
import me.rafaelldi.aspire.util.decodeAnsiCommandsToString
import java.nio.charset.StandardCharsets
import java.nio.file.Path
import kotlin.io.path.div
@Service
class AspireSessionHostRunner {
companion object {
fun getInstance() = service<AspireSessionHostRunner>()
private val LOG = logger<AspireSessionHostRunner>()
private const val ASPNETCORE_URLS = "ASPNETCORE_URLS"
private const val RIDER_OTEL_PORT = "RIDER_OTEL_PORT"
private const val RIDER_PARENT_PROCESS_PID = "RIDER_PARENT_PROCESS_PID"
private const val RIDER_RD_PORT = "RIDER_RD_PORT"
private const val DOTNET_OTLP_ENDPOINT_URL = "DOTNET_OTLP_ENDPOINT_URL"
}
private val pluginId = PluginId.getId("me.rafaelldi.aspire")
private val hostAssemblyPath: Path = run {
val plugin = PluginManagerCore.getPlugin(pluginId) ?: error("Plugin $pluginId could not be found.")
val basePath = plugin.pluginPath ?: error("Could not detect path of plugin $plugin on disk.")
basePath / "aspire-session-host" / "aspire-session-host.dll"
}
suspend fun runSessionHost(
project: Project,
sessionHostConfig: AspireSessionHostConfig,
sessionHostLifetime: LifetimeDefinition
) {
LOG.info("Starting Aspire session host: $sessionHostConfig")
if (sessionHostLifetime.isNotAlive) {
LOG.warn("Unable to start Aspire host because lifetime is not alive")
return
}
val dotnet = RiderDotNetActiveRuntimeHost.getInstance(project).dotNetCoreRuntime.value
?: throw CantRunException("Cannot find active .NET runtime")
val protocol = startProtocol(sessionHostLifetime)
subscribe(sessionHostConfig, protocol.aspireSessionHostModel, sessionHostLifetime, project)
val commandLine = GeneralCommandLine()
.withExePath(dotnet.cliExePath)
.withCharset(StandardCharsets.UTF_8)
.withParameters(hostAssemblyPath.toString())
.withEnvironment(
buildMap {
put(ASPNETCORE_URLS, "http://localhost:${sessionHostConfig.debugSessionPort}/")
put(RIDER_OTEL_PORT, sessionHostConfig.openTelemetryPort.toString())
put(RIDER_RD_PORT, "${protocol.wire.serverPort}")
put(RIDER_PARENT_PROCESS_PID, ProcessHandle.current().pid().toString())
if (sessionHostConfig.openTelemetryProtocolUrl != null)
put(DOTNET_OTLP_ENDPOINT_URL, sessionHostConfig.openTelemetryProtocolUrl)
}
)
LOG.trace("Host command line: ${commandLine.commandLineString}")
val processHandler = KillableColoredProcessHandler.Silent(commandLine)
sessionHostLifetime.onTermination {
if (!processHandler.isProcessTerminating && !processHandler.isProcessTerminated) {
LOG.trace("Killing Aspire host process")
processHandler.killProcess()
}
}
processHandler.addProcessListener(object : ProcessListener {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
val text = decodeAnsiCommandsToString(event.text, outputType)
if (outputType == ProcessOutputType.STDERR) {
LOG.error(text)
} else {
LOG.debug(text)
}
}
override fun processTerminated(event: ProcessEvent) {
sessionHostLifetime.executeIfAlive {
LOG.trace("Terminating Aspire host lifetime")
sessionHostLifetime.terminate(true)
}
}
}, sessionHostLifetime.createNestedDisposable())
processHandler.startNotify()
LOG.trace("Aspire session host started")
project.messageBus.syncPublisher(AspireSessionHostLifecycleListener.TOPIC)
.sessionHostStarted(sessionHostConfig, protocol.aspireSessionHostModel, sessionHostLifetime)
}
private suspend fun startProtocol(lifetime: Lifetime) = withUiContext {
val dispatcher = RdDispatcher(lifetime)
val wire = SocketWire.Server(lifetime, dispatcher, null)
val protocol = Protocol(
"AspireSessionHost::protocol",
Serializers(),
Identities(IdKind.Server),
dispatcher,
wire,
lifetime
)
return@withUiContext protocol
}
private suspend fun subscribe(
hostConfig: AspireSessionHostConfig,
hostModel: AspireSessionHostModel,
hostLifetime: Lifetime,
project: Project
) {
val sessionEvents = Channel<AspireSessionEvent>(Channel.UNLIMITED)
hostLifetime.launchOnUi {
sessionEvents.consumeAsFlow().collect {
when (it) {
is AspireSessionStarted -> {
LOG.trace("Aspire session started (${it.id}, ${it.pid})")
hostModel.processStarted.fire(ProcessStarted(it.id, it.pid))
}
is AspireSessionTerminated -> {
LOG.trace("Aspire session terminated (${it.id}, ${it.exitCode})")
hostModel.processTerminated.fire(ProcessTerminated(it.id, it.exitCode))
}
is AspireSessionLogReceived -> {
LOG.trace("Aspire session log received (${it.id}, ${it.isStdErr}, ${it.message})")
hostModel.logReceived.fire(LogReceived(it.id, it.isStdErr, it.message))
}
}
}
}
withUiContext {
hostModel.sessions.view(hostLifetime) { sessionLifetime, sessionId, sessionModel ->
LOG.info("New session added $sessionId, $sessionModel")
val runner = AspireSessionRunner.getInstance(project)
runner.runSession(
AspireSessionRunner.RunSessionCommand(
sessionId,
sessionModel,
sessionLifetime,
sessionEvents,
hostConfig.hostName,
hostConfig.isDebug,
hostConfig.openTelemetryPort
)
)
}
}
}
} | 0 | Kotlin | 0 | 15 | ddcaa13e13d3eed22a73460ffb4af07040985003 | 7,728 | aspire-plugin | MIT License |
src/main/kotlin/moe/hanatomizu/minecraftbackrooms/objects/ModBlockItems.kt | Hanatomizu | 765,698,906 | false | {"Kotlin": 15970} | /*
* Copyright 2024 Hanatomizu
*
* 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 moe.hanatomizu.minecraftbackrooms.objects
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
object ModBlockItems {
val ENTRANCE_FLOOR_ITEM: BlockItem = BlockItem(ModBlocks.ENTRANCE_FLOOR, Item.Settings())
val ENTRANCE_WALL_ITEM: BlockItem = BlockItem(ModBlocks.ENTRANCE_WALL, Item.Settings())
} | 1 | Kotlin | 0 | 1 | 17fd9bc3484164d58cd5d3f5773b1f59286d6790 | 906 | minecraft-backrooms | Apache License 2.0 |
src/main/kotlin/moe/hanatomizu/minecraftbackrooms/objects/ModBlockItems.kt | Hanatomizu | 765,698,906 | false | {"Kotlin": 15970} | /*
* Copyright 2024 Hanatomizu
*
* 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 moe.hanatomizu.minecraftbackrooms.objects
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
object ModBlockItems {
val ENTRANCE_FLOOR_ITEM: BlockItem = BlockItem(ModBlocks.ENTRANCE_FLOOR, Item.Settings())
val ENTRANCE_WALL_ITEM: BlockItem = BlockItem(ModBlocks.ENTRANCE_WALL, Item.Settings())
} | 1 | Kotlin | 0 | 1 | 17fd9bc3484164d58cd5d3f5773b1f59286d6790 | 906 | minecraft-backrooms | Apache License 2.0 |
frontend/app/src/main/java/com/harissabil/anidex/data/remote/anime/dto/Studio.kt | harissabil | 718,008,784 | false | {"Kotlin": 279663, "PHP": 35922} | package com.harissabil.anidex.data.remote.anime.dto
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Genre(
val mal_id: Int,
val name: String,
val type: String,
val url: String
) : Parcelable | 0 | Kotlin | 0 | 0 | 4d90767118de195fcda1c209208bdbc3292e7a86 | 246 | TemanWibu | MIT License |
src/main/kotlin/gq/genprog/dumbdog/game/User.kt | general-programming | 135,825,878 | false | {"Kotlin": 24708, "JavaScript": 16582, "CSS": 4207, "HTML": 718} | package gq.genprog.dumbdog.game
import java.util.*
/**
* Written by @offbeatwitch.
* Licensed under MIT.
*/
open class User(val id: UUID) {
var username = "Guest"
override fun equals(other: Any?): Boolean {
if (other is User) {
return this.id == other.id
}
return super.equals(other)
}
class Builder {
var id: UUID? = null
var username: String? = null
fun build(): User {
val player = User(id!!)
if (username != null)
player.username = username!!
return player
}
}
} | 0 | Kotlin | 0 | 1 | db945665706404b084c561f434a5911c319c470c | 616 | dumb-dog | MIT License |
app/src/main/java/com/codepath/apps/restclienttemplate/models/TweetsAdapter.kt | Volan360 | 450,938,530 | false | {"Kotlin": 19135, "Java": 2939} | package com.codepath.apps.restclienttemplate.models
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterInside
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.codepath.apps.restclienttemplate.R
class TweetsAdapter(val tweets: ArrayList<Tweet>): RecyclerView.Adapter<TweetsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TweetsAdapter.ViewHolder {
val context = parent.context
val inflater = LayoutInflater.from(context)
//Inflate Layout
val view = inflater.inflate(R.layout.item_tweet, parent, false)
return ViewHolder(view)
}
//Populates data into the item through the holder
override fun onBindViewHolder(holder: TweetsAdapter.ViewHolder, position: Int) {
//Get the data model based on the position
val tweet : Tweet = tweets.get(position)
//Set item values based on data model
holder.tvUserName.text = tweet.user?.name
holder.tvTweetBody.text = tweet.body
holder.tvTimeStamp.text = tweet.timeStamp
Glide.with(holder.itemView)
.load(tweet.user?.publicImageUrl)
.transform(CenterInside(), RoundedCorners(24))
.into(holder.ivProfileImage)
holder.itemView.animation = AnimationUtils.loadAnimation(holder.itemView.context, R.anim.tweetscroll)
}
override fun getItemCount(): Int {
return tweets.size
}
// Clean all elements of the recycler
fun clear() {
tweets.clear()
notifyDataSetChanged()
}
// Add a list of items -- change to type used
fun addAll(tweetList: List<Tweet>) {
tweets.addAll(tweetList)
notifyDataSetChanged()
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView)
{
val ivProfileImage = itemView.findViewById<ImageView>(R.id.ivProfileImage)
val tvUserName = itemView.findViewById<TextView>(R.id.tvUsername)
val tvTweetBody = itemView.findViewById<TextView>(R.id.tvTweetBody)
val tvTimeStamp = itemView.findViewById<TextView>(R.id.tvTimeStamp)
}
} | 2 | Kotlin | 0 | 0 | f33a330ee2b549a0425a2a6b9c72a9fe14e9918f | 2,411 | SimpleTweet | Apache License 2.0 |
src/main/java/uk/ac/cam/cl/bravo/dataset/BoneCondition.kt | jjurm | 166,785,284 | false | null | package uk.ac.cam.cl.bravo.dataset
enum class BoneCondition(val label: String) {
NORMAL("negative"), ABNORMAL("positive");
companion object {
private val map: Map<String, BoneCondition> = values().map { it.label to it }.toMap()
fun fromLabel(label: String) = map[label]
}
}
| 0 | null | 2 | 2 | f08b2a7f57062f14301ae12c9e5295ffa4016aab | 305 | bonedoctor | MIT License |
src/main/kotlin/de/havemann/transformer/domain/entries/NavigationEntriesTransformer.kt | LukasHavemann | 362,340,388 | false | null | package de.havemann.transformer.domain.entries
import java.util.*
class NavigationEntriesTransformer(
private val entries: List<Entry>,
private val parentLabel: String? = null,
private var result: MutableList<Link> = mutableListOf()
) {
fun transform(): List<Link> {
if (entries.isEmpty()) return Collections.emptyList()
entries.forEach { innerTransform(it.label, it.children) }
return result
}
private fun innerTransform(parentLabel: String, children: List<Entry>?) {
children?.forEach {
val nodeLabel = it.label
if (it.type == Type.LINK && isInclude(parentLabel)) {
val label = if (isInclude(parentLabel)) nodeLabel else "$parentLabel - $nodeLabel"
result.add(Link(label, it.url ?: throw InvalidLinkException(it)))
}
if (it.type == Type.NODE) {
innerTransform("$parentLabel - $nodeLabel", it.children)
}
}
}
private fun isInclude(parentLabel: String): Boolean {
return if (this.parentLabel != null) parentLabel.contains(this.parentLabel) else true
}
}
class InvalidLinkException(entry: Entry) : IllegalArgumentException(entry.toString())
| 0 | Kotlin | 0 | 0 | 8638fe7c4037c93708cdaf05b9a8c23954e7d866 | 1,241 | microservice-transformer | MIT License |
app/src/androidTest/java/fr/boitakub/tuxedo/tests/OkHttp3IdlingResource.kt | jforatier | 388,597,382 | false | null | package fr.boitakub.tuxedo.tests
import androidx.annotation.CheckResult
import androidx.test.espresso.IdlingResource
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import java.lang.NullPointerException
class OkHttp3IdlingResource private constructor(
private val name: String,
private val dispatcher: Dispatcher
) :
IdlingResource {
@Volatile
var callback: IdlingResource.ResourceCallback? = null
override fun getName(): String {
return name
}
override fun isIdleNow(): Boolean {
return dispatcher.runningCallsCount() == 0
}
override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback) {
this.callback = callback
}
companion object {
/**
* Create a new [IdlingResource] from `client` as `name`. You must register
* this instance using `Espresso.registerIdlingResources`.
*/
@CheckResult // Extra guards as a library.
fun create(name: String, client: OkHttpClient): OkHttp3IdlingResource {
if (name == null) throw NullPointerException("name == null")
if (client == null) throw NullPointerException("client == null")
return OkHttp3IdlingResource(name, client.dispatcher)
}
}
init {
dispatcher.idleCallback = Runnable {
val callback = callback
callback?.onTransitionToIdle()
}
}
}
| 1 | Kotlin | 2 | 2 | 7c15e1844a53601648bd46eac282d8be1b6e25ce | 1,436 | Tuxedo | MIT License |
palette/src/main/java/com/elixer/palette/models/ColorArc.kt | Shivamdhuria | 440,952,471 | false | {"Kotlin": 31225} | package com.elixer.palette.models
import androidx.compose.ui.graphics.Color
/**
* Color Arc holding exact data to instruct where and how to draw a an arc
* @param radius radius if the arc
* @param strokeWidth stroke width directed radially outwards
* @param startingAngle the angle to start the arc from 0 - 360
* @param sweep arc drawn from starting -> starting + sweep
* @param color the color that will be used to paint the arc
*/
data class ColorArc(
val radius: Float,
val strokeWidth: Float,
val startingAngle: Float,
val sweep: Float,
val color: Color,
) {
fun contains(angle: Float, distance: Float, rotation: Float): Boolean {
if (angle in ((startingAngle + rotation) % 360).rangeTo((startingAngle + sweep + rotation) % 360f)) {
return distance in (radius - strokeWidth)..(radius + strokeWidth)
} else return false
}
} | 1 | Kotlin | 1 | 64 | 8207270e5008b7c69b3b1f9ab57df237c1b78eda | 893 | palette | Apache License 2.0 |
src/main/kotlin/ast/cc/interfaces/CCVisitor.kt | chorlang | 83,657,539 | false | null | package ast.cc.interfaces
import ast.cc.nodes.*
/**
* Created by fmontesi on 03/04/17.
*/
interface CCVisitor<T> {
fun visit(n: Condition): T
fun visit(n: Termination): T
fun visit(n: ProcedureDefinition): T
fun visit(n: ProcedureInvocation): T
fun visit(n: Choreography): T
fun visit(n: Program): T
fun visit(n: Multicom): T
fun visit(n: CommunicationSelection): T
}
| 1 | Kotlin | 0 | 0 | d607ed6aebafa42531b12e71760c1515113bfaa5 | 411 | core-choreographies | Apache License 2.0 |
postgresql/src/main/kotlin/io/github/clasicrando/kdbc/postgresql/pool/PgBlockingConnectionProvider.kt | ClasicRando | 722,364,579 | false | {"Kotlin": 1024058, "Dockerfile": 1005, "Shell": 913} | package io.github.clasicrando.kdbc.postgresql.pool
import io.github.clasicrando.kdbc.core.pool.BlockingConnectionPool
import io.github.clasicrando.kdbc.core.pool.BlockingConnectionProvider
import io.github.clasicrando.kdbc.core.stream.SocketBlockingStream
import io.github.clasicrando.kdbc.postgresql.connection.PgBlockingConnection
import io.github.clasicrando.kdbc.postgresql.connection.PgConnectOptions
import io.github.clasicrando.kdbc.postgresql.stream.PgBlockingStream
import io.ktor.network.sockets.InetSocketAddress
/**
* Postgresql specific implementation for [BlockingConnectionProvider] that provides the means to
* create new [BlockingConnectionPool] instances holding [PgBlockingConnection]s as well as
* validating that as [PgBlockingConnection] is valid for reuse.
*/
internal class PgBlockingConnectionProvider(
private val connectOptions: PgConnectOptions,
) : BlockingConnectionProvider<PgBlockingConnection> {
override fun create(pool: BlockingConnectionPool<PgBlockingConnection>): PgBlockingConnection {
val address = InetSocketAddress(connectOptions.host, connectOptions.port.toInt())
val blockingStream = SocketBlockingStream(address)
var stream: PgBlockingStream? = null
try {
stream = PgBlockingStream.connect(
blockingStream = blockingStream,
connectOptions = connectOptions,
)
return PgBlockingConnection.connect(
connectOptions = connectOptions,
stream = stream,
pool = pool as PgBlockingConnectionPool,
)
} catch (ex: Throwable) {
stream?.close()
throw ex
}
}
override fun validate(connection: PgBlockingConnection): Boolean {
if (connection.isConnected && connection.inTransaction) {
connection.rollback()
}
return connection.isConnected && !connection.inTransaction
}
}
| 4 | Kotlin | 0 | 9 | 08679d4d012e1a1eea1564bd290129a7dc3f0c0b | 1,964 | kdbc | Apache License 2.0 |
zowe-imperative/src/jsMain/kotlin/zowe/imperative/config/doc/IConfigUpdateSchemaOptionsLayer.kt | lppedd | 761,812,661 | false | {"Kotlin": 1836694} | @file:JsModule("@zowe/imperative")
package zowe.imperative.config.doc
@seskar.js.JsVirtual
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
sealed external interface IConfigUpdateSchemaOptionsLayer {
companion object {
@seskar.js.JsValue("active")
val active: IConfigUpdateSchemaOptionsLayer
@seskar.js.JsValue("global")
val global: IConfigUpdateSchemaOptionsLayer
@seskar.js.JsValue("all")
val all: IConfigUpdateSchemaOptionsLayer
}
}
| 0 | Kotlin | 0 | 2 | 484545aa795ad8fd8e44eae3c14f5086b8e7f208 | 467 | kotlin-externals | MIT License |
app/src/main/java/nz/co/warehouseandroidtest/ui/search/SearchResultAdapter.kt | softpian | 375,844,881 | false | {"Gradle": 4, "Text": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "Kotlin": 43, "XML": 49} | package nz.co.warehouseandroidtest.ui.search
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import nz.co.warehouseandroidtest.R
import nz.co.warehouseandroidtest.models.SearchResultItem
import java.util.*
class SearchResultAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val searchResultItem: MutableList<SearchResultItem> = ArrayList()
private val TYPE_ITEM = 1
private val TYPE_FOOTER = 2
private var currentLoadState = 2
val LOADING = 1
val LOADING_COMPLETE = 2
val LOADING_END = 3
fun setSearchResultItem(searchResultItem: List<SearchResultItem>?) {
searchResultItem?.let {
this.searchResultItem.clear()
this.searchResultItem.addAll(it)
notifyDataSetChanged()
}
}
override fun getItemViewType(position: Int): Int {
return if (position + 1 == itemCount) {
TYPE_FOOTER
} else {
TYPE_ITEM
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == TYPE_ITEM) {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_row_layout, parent, false)
SearchResultViewHolder(view)
} else {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.layout_refresh_footer, parent, false)
FooterViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is SearchResultViewHolder) {
holder.bind(searchResultItem[position])
} else if (holder is FooterViewHolder) {
val footerViewHolder = holder
when (currentLoadState) {
LOADING -> {
footerViewHolder.pbLoading.visibility = View.VISIBLE
footerViewHolder.tvLoading.visibility = View.VISIBLE
footerViewHolder.llEnd.visibility = View.GONE
}
LOADING_COMPLETE -> {
footerViewHolder.pbLoading.visibility = View.INVISIBLE
footerViewHolder.tvLoading.visibility = View.INVISIBLE
footerViewHolder.llEnd.visibility = View.GONE
}
LOADING_END -> {
footerViewHolder.pbLoading.visibility = View.GONE
footerViewHolder.tvLoading.visibility = View.GONE
footerViewHolder.llEnd.visibility = View.VISIBLE
}
else -> {
}
}
}
}
override fun getItemCount(): Int {
return searchResultItem.size + 1
}
fun setLoadState(loadState: Int) {
currentLoadState = loadState
notifyDataSetChanged()
}
} | 1 | null | 1 | 1 | 991f2a72e6a43cfbe9c1451143a6901f75e52f06 | 2,946 | twg-project | Apache License 2.0 |
widgets/widgets-style/src/main/kotlin/com/paligot/confily/widgets/style/Conferences4HallGlanceColorScheme.kt | GerardPaligot | 444,230,272 | false | {"Kotlin": 887764, "Swift": 125581, "Shell": 1148, "Dockerfile": 542, "HTML": 338, "CSS": 102} | package com.paligot.confily.widgets.style
import androidx.glance.material3.ColorProviders
import com.paligot.confily.style.theme.DarkColors
import com.paligot.confily.style.theme.LightColors
object Conferences4HallGlanceColorScheme {
val colors = ColorProviders(
light = LightColors,
dark = DarkColors
)
}
| 9 | Kotlin | 5 | 141 | 465cf6c21bf28010a01af8095ad9dcca068c5035 | 332 | Confily | Apache License 2.0 |
transport/src/main/kotlin/by/mylnikov/transport/repository/sqlite/SQLiteScheduleRepository.kt | amylnikau | 78,213,783 | false | {"Kotlin": 78626} | package by.mylnikov.transport.repository.sqlite
import android.content.ContentValues
import android.database.sqlite.SQLiteOpenHelper
import by.mylnikov.transport.model.RouteRecord
import by.mylnikov.transport.model.Schedule
import by.mylnikov.transport.model.ScheduleID
import by.mylnikov.transport.repository.ScheduleRepository
import by.mylnikov.transport.repository.ScheduleSpecification
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.reactivex.Observable
import java.util.*
class SQLiteScheduleRepository(private val mDBHelper: SQLiteOpenHelper) : ScheduleRepository {
companion object {
const val SQL_GET_SCHEDULE_BY_ID = "SELECT * FROM ${DBContract.ScheduleTable.TABLE_NAME} WHERE ${DBContract.ScheduleTable.FROM_ID} = '%s' AND ${DBContract.ScheduleTable.TO_ID} = '%s' AND ${DBContract.ScheduleTable.DATE} = '%s'"
const val SQL_GET_FAVORITE_BY_ID = "SELECT ${DBContract.ScheduleTable.IS_FAVORITE} FROM ${DBContract.ScheduleTable.TABLE_NAME} WHERE ${DBContract.ScheduleTable.FROM_ID} = '%s' AND ${DBContract.ScheduleTable.TO_ID} = '%s'"
}
override fun modify(specification: ScheduleSpecification) {
specification as SqlSpecification
val db = mDBHelper.writableDatabase
db.execSQL(specification.toSqlClauses())
db.close()
}
override fun addSchedule(schedule: Schedule) {
val db = mDBHelper.writableDatabase
val values = ContentValues()
val id = schedule.id
val cursor = db.rawQuery(SQL_GET_FAVORITE_BY_ID.format(id.from, id.to), null)
if (cursor.moveToFirst() && cursor.getInt(cursor.getColumnIndex(DBContract.ScheduleTable.IS_FAVORITE)) == 1) {
schedule.isFavorite = true
}
cursor.close()
values.put(DBContract.ScheduleTable.FROM_ID, id.from)
values.put(DBContract.ScheduleTable.TO_ID, id.to)
values.put(DBContract.ScheduleTable.DATE, id.date)
values.put(DBContract.ScheduleTable.FROM_NAME, schedule.departureName)
values.put(DBContract.ScheduleTable.TO_NAME, schedule.destinationName)
values.put(DBContract.ScheduleTable.IS_FAVORITE, schedule.isFavorite)
values.put(DBContract.ScheduleTable.UPDATED_TIME, schedule.updatedTime)
values.put(DBContract.ScheduleTable.SCHEDULE, Gson().toJson(schedule.records).toByteArray())
db.insert(DBContract.ScheduleTable.TABLE_NAME, null, values)
db.close()
}
override fun updateSchedule(schedule: Schedule) {
val db = mDBHelper.writableDatabase
val values = ContentValues()
val id = schedule.id
val whereClause = "${DBContract.ScheduleTable.FROM_ID}=? AND ${DBContract.ScheduleTable.TO_ID}=? AND ${DBContract.ScheduleTable.DATE}=?"
val whereArgs = arrayOf(id.from, id.to, id.date)
values.put(DBContract.ScheduleTable.FROM_NAME, schedule.departureName)
values.put(DBContract.ScheduleTable.TO_NAME, schedule.destinationName)
values.put(DBContract.ScheduleTable.IS_FAVORITE, schedule.isFavorite)
values.put(DBContract.ScheduleTable.UPDATED_TIME, schedule.updatedTime)
values.put(DBContract.ScheduleTable.SCHEDULE, Gson().toJson(schedule.records).toByteArray())
db.update(DBContract.ScheduleTable.TABLE_NAME, values, whereClause, whereArgs)
db.close()
}
override fun getSchedule(scheduleId: ScheduleID): Observable<Schedule> {
return Observable.create {
val db = mDBHelper.readableDatabase
val cursor = db.rawQuery(SQL_GET_SCHEDULE_BY_ID.format(scheduleId.from, scheduleId.to, scheduleId.date), null)
if (cursor.moveToFirst()) {
val blob = cursor.getBlob(cursor.getColumnIndex(DBContract.ScheduleTable.SCHEDULE))
val json = String(blob)
val records: ArrayList<RouteRecord> = Gson().fromJson(json, object : TypeToken<ArrayList<RouteRecord>>() {}.type)
val isFavorite = cursor.getInt(cursor.getColumnIndex(DBContract.ScheduleTable.IS_FAVORITE)) == 1
val departureName = cursor.getString(cursor.getColumnIndex(DBContract.ScheduleTable.FROM_NAME))
val destinationName = cursor.getString(cursor.getColumnIndex(DBContract.ScheduleTable.TO_NAME))
val updatedTime = cursor.getString(cursor.getColumnIndex(DBContract.ScheduleTable.UPDATED_TIME))
it.onNext(Schedule(scheduleId, departureName, destinationName, isFavorite, updatedTime, records))
}
cursor.close()
db.close()
it.onComplete()
}
}
}
| 0 | Kotlin | 0 | 4 | 76a88cc1b1659d2be1f40a03be2a1062061708be | 4,621 | transport | MIT License |
app/src/test/kotlin/io/orangebuffalo/simpleaccounting/services/integration/thirdparty/DropboxApiClientTest.kt | orange-buffalo | 154,902,725 | false | {"Kotlin": 1102242, "TypeScript": 575198, "Vue": 277186, "SCSS": 30742, "JavaScript": 6817, "HTML": 633, "CSS": 10} | package io.orangebuffalo.simpleaccounting.infra.thirdparty.dropbox
import com.github.tomakehurst.wiremock.client.WireMock.*
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo
import com.github.tomakehurst.wiremock.junit5.WireMockTest
import io.kotest.matchers.collections.shouldContainExactly
import io.orangebuffalo.simpleaccounting.tests.infra.api.stubPostRequestTo
import io.orangebuffalo.simpleaccounting.tests.infra.api.willReturnOkJson
import io.orangebuffalo.simpleaccounting.tests.infra.api.willReturnResponse
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.toInstant
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Files
import java.nio.file.Path
@WireMockTest
internal class DropboxApiClientTest {
private lateinit var apiClient: DropboxApiClient
@TempDir
private lateinit var tempDir: Path
@BeforeEach
fun setup(wmRuntimeInfo: WireMockRuntimeInfo) {
val port = wmRuntimeInfo.httpPort
apiClient = DropboxApiClient(
accessToken = "TestAccessToken",
refreshToken = "TestRefreshToken",
clientId = "TestClientId",
clientSecret = "TestClientSecret",
apiBaseUrl = "http://localhost:$port",
contentBaseUrl = "http://localhost:$port",
)
}
@Test
fun `should upload file`(): Unit = runBlocking {
// Create a temp file and write some content to it
val tempFile = Files.createFile(tempDir.resolve("tempFile.txt"))
Files.writeString(tempFile, "This is a temp file")
stubPostRequestTo("/2/files/upload") {
withRequestBody(equalTo("This is a temp file"))
withHeader("Authorization", equalTo("Bearer TestAccessToken"))
withHeader("Content-Type", equalTo("application/octet-stream"))
withHeader(
"Dropbox-API-Arg", equalToJson(
"""{
"path": "/your/destination/path",
"mode": "add",
"autorename": false,
"mute": true,
"strict_conflict": false
}"""
)
)
willReturnOkJson(/*language=json*/
"""{
"name": "uploaded.txt",
"path_lower": "/uploaded.txt",
"path_display": "/Uploaded.txt",
"id": "id_upload",
"client_modified": "2023-09-02T00:00:00Z",
"server_modified": "2023-09-02T00:00:00Z",
"rev": "345",
"size": 19,
"content_hash": "hash_upload"
}"""
)
}
apiClient.uploadFile(tempFile, "/your/destination/path")
verify(exactly(1), postRequestedFor(urlEqualTo("/2/files/upload")))
}
@Test
fun `should refresh token on upload file`(): Unit = runBlocking {
// Create a temp file and write some content to it
val tempFile = Files.createFile(tempDir.resolve("tempFile.txt"))
Files.writeString(tempFile, "This is a temp file")
stubExpiredTokenForRequestTo("/2/files/upload")
stubNewTokenRequest()
stubPostRequestTo("/2/files/upload") {
withRequestBody(equalTo("This is a temp file"))
withHeader("Authorization", equalTo("Bearer NewToken"))
withHeader("Content-Type", equalTo("application/octet-stream"))
withHeader(
"Dropbox-API-Arg", equalToJson(
"""{
"path": "/your/destination/path",
"mode": "add",
"autorename": false,
"mute": true,
"strict_conflict": false
}"""
)
)
willReturnOkJson(/*language=json*/
"""{
"name": "uploaded.txt",
"path_lower": "/uploaded.txt",
"path_display": "/Uploaded.txt",
"id": "id_upload",
"client_modified": "2023-09-02T00:00:00Z",
"server_modified": "2023-09-02T00:00:00Z",
"rev": "345",
"size": 19,
"content_hash": "hash_upload"
}"""
)
}
apiClient.uploadFile(tempFile, "/your/destination/path")
verify(exactly(2), postRequestedFor(urlEqualTo("/2/files/upload")))
verify(exactly(1), postRequestedFor(urlEqualTo("/oauth2/token")))
}
@Test
fun `should list folder`(): Unit = runBlocking {
stubPostRequestTo("/2/files/list_folder") {
withHeader("Authorization", equalTo("Bearer TestAccessToken"))
withHeader("Content-Type", equalTo("application/json"))
willReturnOkJson(/*language=json*/
"""{
"entries": [
{
".tag": "file",
"name": "file1.txt",
"path_lower": "/file1",
"path_display": "/File1",
"id": "id_1",
"client_modified": "2021-09-01T00:00:00Z",
"server_modified": "2021-09-01T00:00:00Z",
"rev": "123",
"size": 1024,
"content_hash": "hash1"
},
{
".tag": "file",
"name": "file2.txt",
"path_lower": "/file2",
"path_display": "/File2",
"id": "id_2",
"client_modified": "2021-09-02T00:00:00Z",
"server_modified": "2021-09-02T00:00:00Z",
"rev": "124",
"size": 2048,
"content_hash": "hash2"
}
],
"cursor": "some_cursor",
"has_more": false
}"""
)
}
val listFolderResult = apiClient.listFolder("/some_folder")
listFolderResult.shouldContainExactly(
FileListFolderEntry(
tag = "file",
name = "file1.txt",
path = "/file1",
pathDisplay = "/File1",
id = "id_1",
clientModified = "2021-09-01T00:00:00Z".toInstant(),
serverModified = "2021-09-01T00:00:00Z".toInstant(),
revision = "123",
size = 1024,
contentHash = "hash1"
),
FileListFolderEntry(
tag = "file",
name = "file2.txt",
path = "/file2",
pathDisplay = "/File2",
id = "id_2",
clientModified = "2021-09-02T00:00:00Z".toInstant(),
serverModified = "2021-09-02T00:00:00Z".toInstant(),
revision = "124",
size = 2048,
contentHash = "hash2"
)
)
verify(exactly(1), postRequestedFor(urlEqualTo("/2/files/list_folder")))
}
@Test
fun `should refresh token on list folder`(): Unit = runBlocking {
stubExpiredTokenForRequestTo("/2/files/list_folder")
stubNewTokenRequest()
stubPostRequestTo("/2/files/list_folder") {
withHeader("Authorization", equalTo("Bearer NewToken"))
withHeader("Content-Type", equalTo("application/json"))
willReturnOkJson(/*language=json*/
"""{
"entries": [
{
".tag": "file",
"name": "file1.txt",
"path_lower": "/file1",
"path_display": "/File1",
"id": "id_1",
"client_modified": "2021-09-01T00:00:00Z",
"server_modified": "2021-09-01T00:00:00Z",
"rev": "123",
"size": 1024,
"content_hash": "hash1"
}
],
"cursor": "some_cursor",
"has_more": false
}"""
)
}
val listFolderResult = apiClient.listFolder("/some_folder")
listFolderResult.shouldContainExactly(
FileListFolderEntry(
tag = "file",
name = "file1.txt",
path = "/file1",
pathDisplay = "/File1",
id = "id_1",
clientModified = "2021-09-01T00:00:00Z".toInstant(),
serverModified = "2021-09-01T00:00:00Z".toInstant(),
revision = "123",
size = 1024,
contentHash = "hash1"
)
)
verify(exactly(2), postRequestedFor(urlEqualTo("/2/files/list_folder")))
verify(postRequestedFor(urlEqualTo("/oauth2/token")))
}
private fun stubNewTokenRequest() {
stubPostRequestTo("/oauth2/token") {
withHeader("Content-Type", containing("application/x-www-form-urlencoded"))
withRequestBody(
equalTo(
"grant_type=refresh_token&client_id=TestClientId&client_secret=TestClientSecret&refresh_token=TestRefreshToken"
)
)
willReturnOkJson(
"""{
"access_token": "NewToken",
"expires_in": 3600 }
"""
)
}
}
private fun stubExpiredTokenForRequestTo(url: String) {
stubPostRequestTo(url) {
withHeader("Authorization", equalTo("Bearer TestAccessToken"))
willReturnResponse {
withStatus(401)
withHeader("Content-Type", "application/json")
withBody(
"""{
"error_summary": "expired_access_token/...",
"error": {
".tag": "expired_access_token"
}
}"""
)
}
}
}
@Test
fun `should list folder with pagination`(): Unit = runBlocking {
// First page
stubPostRequestTo("/2/files/list_folder") {
withHeader("Authorization", equalTo("Bearer TestAccessToken"))
withHeader("Content-Type", equalTo("application/json"))
willReturnOkJson(/*language=json*/
"""{
"entries": [
{
".tag": "file",
"name": "file1.txt",
"path_lower": "/file1",
"path_display": "/File1",
"id": "id_1",
"client_modified": "2022-09-02T00:00:00Z",
"server_modified": "2022-09-02T00:00:01Z",
"rev": "1",
"size": 100,
"content_hash": "hash_1"
},
{
".tag": "file",
"name": "file2.txt",
"path_lower": "/file2",
"path_display": "/File2",
"id": "id_2",
"client_modified": "2022-09-02T00:00:02Z",
"server_modified": "2022-09-02T00:00:03Z",
"rev": "2",
"size": 200,
"content_hash": "hash_2"
}
],
"cursor": "cursor_1",
"has_more": true
}"""
)
}
// Second page
stubPostRequestTo("/2/files/list_folder/continue") {
withHeader("Authorization", equalTo("Bearer TestAccessToken"))
withHeader("Content-Type", equalTo("application/json"))
willReturnOkJson(/*language=json*/
"""{
"entries": [
{
".tag": "file",
"name": "file3.txt",
"path_lower": "/file3",
"path_display": "/File3",
"id": "id_3",
"client_modified": "2022-09-02T00:00:04Z",
"server_modified": "2022-09-02T00:00:05Z",
"rev": "3",
"size": 300,
"content_hash": "hash_3"
}
],
"cursor": "cursor_2",
"has_more": false
}"""
)
}
val files = apiClient.listFolder("/")
files.shouldContainExactly(
FileListFolderEntry(
tag = "file",
name = "file1.txt",
path = "/file1",
pathDisplay = "/File1",
id = "id_1",
clientModified = "2022-09-02T00:00:00Z".toInstant(),
serverModified = "2022-09-02T00:00:01Z".toInstant(),
revision = "1",
size = 100,
contentHash = "hash_1"
),
FileListFolderEntry(
tag = "file",
name = "file2.txt",
path = "/file2",
pathDisplay = "/File2",
id = "id_2",
clientModified = "2022-09-02T00:00:02Z".toInstant(),
serverModified = "2022-09-02T00:00:03Z".toInstant(),
revision = "2",
size = 200,
contentHash = "hash_2"
),
FileListFolderEntry(
tag = "file",
name = "file3.txt",
path = "/file3",
pathDisplay = "/File3",
id = "id_3",
clientModified = "2022-09-02T00:00:04Z".toInstant(),
serverModified = "2022-09-02T00:00:05Z".toInstant(),
revision = "3",
size = 300,
contentHash = "hash_3"
)
)
verify(exactly(1), postRequestedFor(urlEqualTo("/2/files/list_folder")))
verify(exactly(1), postRequestedFor(urlEqualTo("/2/files/list_folder/continue")))
}
@Test
fun `should delete files`(): Unit = runBlocking {
stubPostRequestTo("/2/files/delete_batch") {
withHeader("Authorization", equalTo("Bearer TestAccessToken"))
withHeader("Content-Type", equalTo("application/json"))
willReturnOkJson("{}")
}
apiClient.deleteFiles(listOf("/file1", "/file2"))
verify(exactly(1), postRequestedFor(urlEqualTo("/2/files/delete_batch")))
}
@Test
fun `should refresh token on delete files`(): Unit = runBlocking {
stubExpiredTokenForRequestTo("/2/files/delete_batch")
stubNewTokenRequest()
stubPostRequestTo("/2/files/delete_batch") {
withHeader("Authorization", equalTo("Bearer NewToken"))
withHeader("Content-Type", equalTo("application/json"))
withRequestBody(
equalToJson(
"""{
"entries":[
{ "path": "/file1" },
{ "path": "/file2" }
]
}"""
)
)
willReturnOkJson("{}")
}
apiClient.deleteFiles(listOf("/file1", "/file2"))
verify(exactly(2), postRequestedFor(urlEqualTo("/2/files/delete_batch")))
verify(exactly(1), postRequestedFor(urlEqualTo("/oauth2/token")))
}
}
| 70 | Kotlin | 0 | 1 | dec521702827283d9c1e9273830d061bada1cd5d | 16,437 | simple-accounting | Creative Commons Attribution 3.0 Unported |
src/main/kotlin/csense/idea/base/csense/compareTo.kt | csense-oss | 226,373,994 | false | {"Kotlin": 148126} | @file:Suppress("RedundantVisibilityModifier", "NOTHING_TO_INLINE")
package csense.idea.base.csense
public inline operator fun Number.compareTo(other: Number): Int = when (this) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
else -> toDouble().compareTo(other)
}
public inline operator fun Byte.compareTo(other: Number): Int = when (other) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
//TODO bad fallback? hmm
else -> this.compareTo(other.toDouble())
}
public inline operator fun Short.compareTo(other: Number): Int = when (other) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
//TODO bad fallback? hmm
else -> this.compareTo(other.toDouble())
}
public inline operator fun Int.compareTo(other: Number): Int = when (other) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
//TODO bad fallback? hmm
else -> this.compareTo(other.toDouble())
}
public inline operator fun Long.compareTo(other: Number): Int = when (other) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
//TODO bad fallback? hmm
else -> this.compareTo(other.toDouble())
}
public inline operator fun Float.compareTo(other: Number): Int = when (other) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
//TODO bad fallback? hmm
else -> this.compareTo(other.toDouble())
}
public inline operator fun Double.compareTo(other: Number): Int = when (other) {
is Byte -> this.compareTo(other)
is Short -> this.compareTo(other)
is Int -> this.compareTo(other)
is Long -> this.compareTo(other)
is Float -> this.compareTo(other)
is Double -> this.compareTo(other)
//TODO bad fallback? hmm
else -> this.compareTo(other.toDouble())
}
| 0 | Kotlin | 0 | 0 | 064ccdffc00fb0ee4b382339271321a7f4e2e185 | 2,737 | idea-kotlin-shared-base | MIT License |
themes/new-ui/new-ui-standalone/src/main/kotlin/org/jetbrains/jewel/themes/expui/standalone/control/CustomWindowDecorationSupport.kt | JetBrains | 440,164,967 | false | null | package org.jetbrains.jewel.themes.expui.standalone.control
import java.awt.Shape
import java.awt.Window
interface CustomWindowDecorationSupport {
fun setCustomDecorationEnabled(window: Window, enabled: Boolean)
fun setCustomDecorationTitleBarHeight(window: Window, height: Int)
fun setCustomDecorationHitTestSpotsMethod(window: Window, spots: Map<Shape, Int>)
/**
* Default idle implementation for CustomWindowDecorationSupport, it do nothing.
*/
companion object : CustomWindowDecorationSupport {
override fun setCustomDecorationEnabled(window: Window, enabled: Boolean) {
}
override fun setCustomDecorationTitleBarHeight(window: Window, height: Int) {
}
override fun setCustomDecorationHitTestSpotsMethod(window: Window, spots: Map<Shape, Int>) {
}
}
}
| 17 | Kotlin | 11 | 318 | 817adc042a029698983c9686d0f1497204bfdf14 | 845 | jewel | Apache License 2.0 |
app/src/main/java/com/android/sampleporject/view/MainActivity.kt | Ganganaidu | 331,563,460 | false | null | package com.android.sampleporject.view
import android.os.Bundle
import com.android.sampleporject.R
import com.android.sampleporject.base.view.BaseActivity
class MainActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow()
}
}
} | 0 | Kotlin | 1 | 0 | 4ee3a1b33a7967496af11f331d6b8aed27d03aec | 562 | sampleMVVM | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/PeopleArrowsLeftRight.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.PeopleArrowsLeftRight: ImageVector
get() {
if (_peopleArrowsLeftRight != null) {
return _peopleArrowsLeftRight!!
}
_peopleArrowsLeftRight = Builder(name = "PeopleArrowsLeftRight", defaultWidth = 512.0.dp,
defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.42f, 13.41f)
lineToRelative(-2.91f, 2.91f)
lineToRelative(-1.41f, -1.41f)
lineToRelative(1.9f, -1.9f)
horizontalLineToRelative(-6.0f)
lineToRelative(1.91f, 1.9f)
lineToRelative(-1.41f, 1.41f)
lineToRelative(-2.91f, -2.91f)
curveToRelative(-0.77f, -0.78f, -0.77f, -2.04f, 0.0f, -2.81f)
lineToRelative(2.92f, -2.92f)
lineToRelative(1.41f, 1.41f)
lineToRelative(-1.91f, 1.91f)
horizontalLineToRelative(6.0f)
lineToRelative(-1.92f, -1.91f)
lineToRelative(1.41f, -1.41f)
lineToRelative(2.92f, 2.92f)
curveToRelative(0.77f, 0.78f, 0.77f, 2.04f, 0.0f, 2.81f)
close()
moveTo(5.0f, 5.0f)
curveToRelative(1.38f, 0.0f, 2.5f, -1.12f, 2.5f, -2.5f)
reflectiveCurveTo(6.38f, 0.0f, 5.0f, 0.0f)
reflectiveCurveTo(2.5f, 1.12f, 2.5f, 2.5f)
reflectiveCurveToRelative(1.12f, 2.5f, 2.5f, 2.5f)
close()
moveTo(5.17f, 9.17f)
lineToRelative(2.95f, -2.95f)
curveToRelative(-0.35f, -0.14f, -0.73f, -0.22f, -1.13f, -0.22f)
lineTo(3.0f, 6.0f)
curveToRelative(-1.66f, 0.0f, -3.0f, 1.34f, -3.0f, 3.0f)
verticalLineToRelative(8.0f)
lineTo(2.0f, 17.0f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-7.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-6.35f)
lineToRelative(-2.83f, -2.83f)
curveToRelative(-1.56f, -1.56f, -1.56f, -4.09f, 0.0f, -5.65f)
close()
moveTo(19.0f, 5.0f)
curveToRelative(1.38f, 0.0f, 2.5f, -1.12f, 2.5f, -2.5f)
reflectiveCurveToRelative(-1.12f, -2.5f, -2.5f, -2.5f)
reflectiveCurveToRelative(-2.5f, 1.12f, -2.5f, 2.5f)
reflectiveCurveToRelative(1.12f, 2.5f, 2.5f, 2.5f)
close()
moveTo(21.0f, 6.0f)
horizontalLineToRelative(-4.0f)
curveToRelative(-0.4f, 0.0f, -0.78f, 0.08f, -1.13f, 0.22f)
lineToRelative(2.95f, 2.95f)
curveToRelative(1.56f, 1.56f, 1.56f, 4.09f, 0.0f, 5.65f)
lineToRelative(-2.83f, 2.83f)
verticalLineToRelative(6.35f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-7.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-7.0f)
horizontalLineToRelative(2.0f)
lineTo(23.99f, 9.0f)
curveToRelative(0.0f, -1.66f, -1.34f, -3.0f, -3.0f, -3.0f)
close()
}
}
.build()
return _peopleArrowsLeftRight!!
}
private var _peopleArrowsLeftRight: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,469 | icons | MIT License |
utilities/src/main/kotlin/freem/utilities/collections/trie/Trie.kt | freemlang | 658,320,863 | false | {"Kotlin": 48583} | package freem.utilities.collections.trie
interface Trie<out Type>: TrieNode<Type>, Collection<List<Type>> {
override val children: Map<@UnsafeVariance Type, TrieNode<Type>>?
override operator fun get(key: @UnsafeVariance Type) = children?.get(key)
} | 0 | Kotlin | 0 | 0 | aa2cec5321b53c00925320a246c8e9271a427d5c | 258 | Freem | Apache License 2.0 |
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/types/message/ChatEvents/voice/VoiceChatEnded.kt | InsanusMokrassar | 163,152,024 | false | null | package dev.inmo.tgbotapi.types.message.ChatEvents.voice
import com.soywiz.klock.TimeSpan
import com.soywiz.klock.seconds
import dev.inmo.tgbotapi.types.Seconds
import dev.inmo.tgbotapi.types.durationField
import dev.inmo.tgbotapi.types.message.ChatEvents.abstracts.VoiceChatEvent
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class VoiceChatEnded(
@SerialName(durationField)
val duration: Seconds
) : VoiceChatEvent {
val timeSpan: TimeSpan
get() = TimeSpan(duration.seconds.milliseconds)
}
| 9 | Kotlin | 10 | 99 | 8206aefbb661db936d4078a8ef7cc9cecb5384e4 | 569 | TelegramBotAPI | Apache License 2.0 |
android/app/src/main/kotlin/io/github/longlinht/password_manager/MainActivity.kt | longlinht | 304,243,117 | false | {"Dart": 56290, "Ruby": 1354, "Swift": 404, "Kotlin": 141, "Objective-C": 38} | package io.github.longlinht.password_manager
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 6bcfeb5d9e8e54dbe214e1b4702527cab4af27a1 | 141 | password_manager | MIT License |
pulsar-tools/pulsar-browser/src/test/kotlin/ai/platon/pulsar/browser/driver/examples/TracingExample.kt | platonai | 124,882,400 | false | null | package ai.platon.pulsar.browser.driver.examples
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.kklisura.cdt.protocol.events.tracing.DataCollected
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
class TracingExample: BrowserExampleBase() {
override fun run() {
val page = devTools.page
val tracing = devTools.tracing
val dataCollectedList = mutableListOf<Any>()
// Add tracing data to dataCollectedList
tracing.onDataCollected { event: DataCollected ->
if (event.value != null) {
dataCollectedList.addAll(event.value)
}
}
// When tracing is complete, dump dataCollectedList to JSON file.
tracing.onTracingComplete {
// Dump tracing to file.
val path = Paths.get("/tmp/tracing.json")
println("Tracing completed! Dumping to $path")
dump(path, dataCollectedList)
devTools.close()
}
page.onLoadEventFired { tracing.end() }
page.enable()
tracing.start()
page.navigate(testUrl)
}
private fun dump(path: Path, data: List<Any>) {
val om = ObjectMapper()
try {
om.writeValue(path.toFile(), data)
} catch (e: IOException) {
e.printStackTrace()
}
}
}
fun main() {
TracingExample().use { it.run() }
}
| 1 | null | 32 | 110 | f93bccf5075009dc7766442d3a23b5268c721f54 | 1,452 | pulsar | Apache License 2.0 |
src/main/kotlin/com/unscrambler/controllers/IndexController.kt | blrB | 93,422,946 | false | null | package com.unscrambler.controllers
import com.unscrambler.models.Language
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.RequestMapping
@Controller
class IndexController {
@RequestMapping("/")
fun index(model: Model): String {
val lang = Language.values()
model.addAttribute("lang", lang)
return "index"
}
}
| 0 | Kotlin | 0 | 0 | 225fa64c1b4da63db237ebce81b250cf39996304 | 433 | UnscramblerWord | The Unlicense |
src/es/manhwasnet/src/eu/kanade/tachiyomi/extension/es/manhwasnet/ManhwasNet.kt | beucismis | 406,427,239 | true | {"Kotlin": 4744965} | package eu.kanade.tachiyomi.extension.es.manhwasnet
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Element
class ManhwasNet : HttpSource() {
override val baseUrl: String = "https://manhwas.net"
override val lang: String = "es"
override val name: String = "Manhwas.net"
override val supportsLatest: Boolean = true
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
return document.select(".listing-chapters_wrap .chapter-link a").map { chapterAnchor ->
val chapterUrl = getUrlWithoutDomain(chapterAnchor.attr("href"))
val chapterName = chapterUrl.substringAfterLast("-")
val chapter = SChapter.create()
chapter.chapter_number = chapterName.toFloat()
chapter.name = chapterName
chapter.url = chapterUrl
chapter
}
}
override fun imageUrlParse(response: Response): String {
throw UnsupportedOperationException("Not used.")
}
override fun latestUpdatesParse(response: Response): MangasPage {
val document = response.asJsoup()
val content = document.selectFirst(".d-flex[style=\"flex-wrap:wrap;\"]")
val manhwas = parseManhwas(content)
return MangasPage(manhwas, false)
}
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/es")
}
override fun mangaDetailsParse(response: Response): SManga {
val document = response.asJsoup()
val profileManga = document.selectFirst(".profile-manga")
val manhwa = SManga.create()
manhwa.title = profileManga.selectFirst(".post-title h1").text()
manhwa.thumbnail_url = profileManga.selectFirst(".summary_image img").attr("src")
manhwa.description = profileManga.selectFirst(".description-summary p").text()
val status = profileManga.selectFirst(".post-status .post-content_item:nth-child(2)").text()
manhwa.status = SManga.ONGOING
if (!status.contains("publishing")) manhwa.status = SManga.COMPLETED
return manhwa
}
override fun pageListParse(response: Response): List<Page> {
val document = response.asJsoup()
return document.select("#chapter_imgs img").mapIndexed { i, img ->
val url = img.attr("src")
Page(i, imageUrl = url)
}
}
override fun popularMangaParse(response: Response): MangasPage {
return parseLibraryMangas(response)
}
override fun popularMangaRequest(page: Int): Request {
val url = "$baseUrl/biblioteca".toHttpUrlOrNull()!!.newBuilder()
if (page > 1) {
url.addQueryParameter("page", page.toString())
}
return GET(url.build().toString())
}
override fun searchMangaParse(response: Response): MangasPage {
return parseLibraryMangas(response)
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/biblioteca".toHttpUrlOrNull()!!.newBuilder()
url.addQueryParameter("buscar", query)
if (page > 1) {
url.addQueryParameter("page", page.toString())
}
return GET(url.build().toString())
}
private fun parseLibraryMangas(response: Response): MangasPage {
val document = response.asJsoup()
val content = document.selectFirst(".d-flex[style=\"flex-wrap:wrap;\"]")
val manhwas = parseManhwas(content)
val hasNextPage = document.selectFirst(".pagination .page-link[rel=\"next\"]") != null
return MangasPage(manhwas, hasNextPage)
}
private fun parseManhwas(element: Element): List<SManga> {
return element.select(".series-card").map { seriesCard ->
val seriesCol = seriesCard.parent()
val manhwa = SManga.create()
manhwa.title = seriesCol.selectFirst(".series-title").text().trim()
manhwa.thumbnail_url = seriesCard.selectFirst(".thumb-img").attr("src")
manhwa.url = getUrlWithoutDomain(
transformUrl(seriesCard.selectFirst("a").attr("href"))
)
manhwa
}
}
private fun transformUrl(url: String): String {
if (!url.contains("/leer/")) return url
val name = url.substringAfter("/leer/").substringBeforeLast("-")
return "$baseUrl/manga/$name"
}
private fun getUrlWithoutDomain(url: String) = url.substringAfter(baseUrl)
}
| 0 | Kotlin | 0 | 0 | a439d59b4202511fd14238375558a92052f755c8 | 4,945 | tachiyomi-extensions | Apache License 2.0 |
kotlin-reference-server/src/main/kotlin/org/stellar/reference/callbacks/customer/CustomerService.kt | stellar | 452,893,461 | false | {"Kotlin": 2035247, "Java": 1283931, "Smarty": 1224, "Shell": 513, "Dockerfile": 453} | package org.stellar.reference.callbacks.customer
import java.util.*
import org.stellar.anchor.api.callback.GetCustomerRequest
import org.stellar.anchor.api.callback.GetCustomerResponse
import org.stellar.anchor.api.callback.PutCustomerRequest
import org.stellar.anchor.api.callback.PutCustomerResponse
import org.stellar.anchor.api.shared.CustomerField
import org.stellar.anchor.api.shared.ProvidedCustomerField
import org.stellar.reference.callbacks.BadRequestException
import org.stellar.reference.callbacks.NotFoundException
import org.stellar.reference.dao.CustomerRepository
import org.stellar.reference.log
import org.stellar.reference.model.Customer
import org.stellar.reference.model.Status
class CustomerService(private val customerRepository: CustomerRepository) {
fun getCustomer(request: GetCustomerRequest): GetCustomerResponse {
val customer =
when {
request.id != null -> {
customerRepository.get(request.id)
?: throw NotFoundException("customer for 'id' '${request.id}' not found", request.id)
}
request.account != null -> {
customerRepository.get(request.account, request.memo, request.memoType)
?: Customer(
stellarAccount = request.account,
memo = request.memo,
memoType = request.memoType
)
}
else -> {
throw BadRequestException("Either id or account must be provided")
}
}
return convertCustomerToResponse(customer, request.type)
}
fun upsertCustomer(request: PutCustomerRequest): PutCustomerResponse {
log.info("Upserting customer: $request")
val customer =
when {
request.id != null -> customerRepository.get(request.id)
request.account != null ->
customerRepository.get(request.account, request.memo, request.memoType)
else -> {
throw BadRequestException("Either id or account must be provided")
}
}
// Update the customer if it exists, otherwise create a new one.
if (customer != null) {
customerRepository.update(
customer.copy(
firstName = request.firstName ?: customer.firstName,
lastName = request.lastName ?: customer.lastName,
address = request.address ?: customer.address,
emailAddress = request.emailAddress ?: customer.emailAddress,
bankAccountNumber = request.bankAccountNumber ?: customer.bankAccountNumber,
bankAccountType = request.bankAccountType ?: customer.bankAccountType,
bankNumber = request.bankNumber ?: customer.bankNumber,
bankBranchNumber = request.bankBranchNumber ?: customer.bankBranchNumber,
clabeNumber = request.clabeNumber ?: customer.clabeNumber,
idType = request.idType ?: customer.idType,
idCountryCode = request.idCountryCode ?: customer.idCountryCode,
idIssueDate = request.idIssueDate ?: customer.idIssueDate,
idExpirationDate = request.idExpirationDate ?: customer.idExpirationDate,
idNumber = request.idNumber ?: customer.idNumber,
)
)
return PutCustomerResponse(customer.id)
} else {
val id = UUID.randomUUID().toString()
customerRepository.create(
Customer(
id = id,
stellarAccount = request.account,
memo = request.memo,
memoType = request.memoType,
firstName = request.firstName,
lastName = request.lastName,
address = request.address,
emailAddress = request.emailAddress,
bankAccountNumber = request.bankAccountNumber,
bankAccountType = request.bankAccountType,
bankNumber = request.bankNumber,
bankBranchNumber = request.bankBranchNumber,
clabeNumber = request.clabeNumber,
idType = request.idType,
idCountryCode = request.idCountryCode,
idIssueDate = request.idIssueDate,
idExpirationDate = request.idExpirationDate,
idNumber = request.idNumber,
)
)
return PutCustomerResponse(id)
}
}
fun deleteCustomer(id: String) {
customerRepository.delete(id)
}
fun invalidateClabe(id: String) {
try {
customerRepository.update(customerRepository.get(id)!!.copy(clabeNumber = null))
} catch (e: Exception) {
throw NotFoundException("customer for 'id' '$id' not found", id)
}
}
private fun convertCustomerToResponse(customer: Customer, type: String?): GetCustomerResponse {
val providedFields = mutableMapOf<String, ProvidedCustomerField>()
val missingFields = mutableMapOf<String, CustomerField>()
val fields =
mapOf(
"first_name" to createField(customer.firstName, "string", "The customer's first name"),
"last_name" to createField(customer.lastName, "string", "The customer's last name"),
"address" to
createField(customer.address, "string", "The customer's address", optional = true),
"email_address" to
createField(customer.emailAddress, "string", "The customer's email address"),
"bank_account_number" to
createField(
customer.bankAccountNumber,
"string",
"The customer's bank account number",
optional = type != "sep31-receiver"
),
"bank_account_type" to
createField(
customer.bankAccountType,
"string",
"The customer's bank account type",
choices = listOf("checking", "savings"),
optional = type != "sep31-receiver"
),
"bank_number" to
createField(
customer.bankNumber,
"string",
"The customer's bank routing number",
optional = type != "sep31-receiver"
),
"bank_branch_number" to
createField(
customer.bankBranchNumber,
"string",
"The customer's bank branch number",
optional = true
),
"clabe_number" to
createField(
customer.clabeNumber,
"string",
"The customer's CLABE number",
optional = type != "sep31-receiver"
),
"id_type" to
createField(
customer.idType,
"string",
"The customer's ID type",
optional = true,
choices = listOf("drivers_license", "passport", "national_id")
),
"id_country_code" to
createField(
customer.idCountryCode,
"string",
"The customer's ID country code",
optional = true
),
"id_issue_date" to
createField(
customer.idIssueDate,
"string",
"The customer's ID issue date",
optional = true
),
"id_expiration_date" to
createField(
customer.idExpirationDate,
"string",
"The customer's ID expiration date",
optional = true
),
"id_number" to
createField(customer.idNumber, "string", "The customer's ID number", optional = true)
)
// Extract fields from customer
fields.forEach(
fun(entry: Map.Entry<String, Field>) {
when (entry.value) {
is Field.Provided -> providedFields[entry.key] = (entry.value as Field.Provided).field
is Field.Missing -> missingFields[entry.key] = (entry.value as Field.Missing).field
}
}
)
val status =
when {
missingFields.filter { !it.value.optional }.isNotEmpty() -> Status.NEEDS_INFO
else -> Status.ACCEPTED
}.toString()
return GetCustomerResponse.builder()
.id(customer.id)
.status(status)
.providedFields(providedFields)
.fields(missingFields)
.build()
}
sealed class Field {
class Provided(val field: ProvidedCustomerField) : Field()
class Missing(val field: CustomerField) : Field()
}
private fun createField(
value: Any?,
type: String,
description: String,
optional: Boolean? = false,
choices: List<String>? = listOf()
): Field {
return when (value != null) {
true -> {
var builder =
ProvidedCustomerField.builder()
.type(type)
.description(description)
.status(Status.ACCEPTED.toString())
.optional(optional)
if (choices != null) {
builder = builder.choices(choices)
}
Field.Provided(builder.build())
}
false -> {
var builder = CustomerField.builder().type(type).description(description).optional(optional)
if (choices != null) {
builder = builder.choices(choices)
}
Field.Missing(builder.build())
}
}
}
}
| 18 | Kotlin | 33 | 32 | 56c793bbc06e0448bd53380c6d7f1ce45ab877ef | 8,888 | java-stellar-anchor-sdk | Apache License 2.0 |
app/src/main/java/com/wisnu/kurniawan/composetodolist/features/todo/scheduled/di/ScheduledModule.kt | wisnukurniawan | 409,054,048 | false | null | package com.wisnu.kurniawan.composetodolist.features.todo.scheduled.di
import com.wisnu.kurniawan.composetodolist.features.todo.scheduled.data.IScheduledEnvironment
import com.wisnu.kurniawan.composetodolist.features.todo.scheduled.data.ScheduledEnvironment
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
@Module
@InstallIn(ViewModelComponent::class)
abstract class ScheduledModule {
@Binds
abstract fun provideEnvironment(
environment: ScheduledEnvironment
): IScheduledEnvironment
}
| 0 | Kotlin | 4 | 73 | 784a7b86014f4d0b3ee0d2055aaa64f731bcbfd6 | 589 | Compose-ToDo | Apache License 2.0 |
app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailFragment.kt | jasper55 | 192,397,303 | false | null | package com.example.android.architecture.blueprints.todoapp.taskdetail
import android.Manifest
import android.app.Activity.RESULT_OK
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.DatePicker
import android.widget.TimePicker
import androidx.fragment.app.Fragment
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import com.example.android.architecture.blueprints.todoapp.EventObserver
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.contacts.*
import com.example.android.architecture.blueprints.todoapp.databinding.TaskdetailFragBinding
import com.example.android.architecture.blueprints.todoapp.util.*
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import timber.log.Timber
/**
* Main UI for the task detail screen.
*/
class TaskDetailFragment : Fragment(), TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
private lateinit var viewDataBinding: TaskdetailFragBinding // is been generated because taskdetail_frag.xml
private lateinit var viewModel: TaskDetailViewModel
private lateinit var timePicker: TimePickerFragment
private lateinit var datePicker: DatePickerFragment
private var taskId: Int? = null
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setupFab()
requestPermission(PermissionChecker.REQUEST_CONTACTS_CODE)
viewDataBinding.viewmodel?.let {
view?.setupSnackbar(this, it.snackbarMessage, Snackbar.LENGTH_SHORT)
}
taskId = TaskDetailFragmentArgs.fromBundle(arguments!!).TASKID
setupNavigation()
setupDataPickers()
}
private fun setupDataPickers() {
timePicker = TimePickerFragment(this)
datePicker = DatePickerFragment(this)
}
private fun setupNavigation() {
viewModel.deleteTaskCommand.observe(this, EventObserver {
val action = TaskDetailFragmentDirections
.actionTaskDetailFragmentToTasksFragment(DELETE_RESULT_OK)
findNavController().navigate(action)
})
viewModel.editTaskCommand.observe(this, EventObserver {
val taskId = TaskDetailFragmentArgs.fromBundle(arguments!!).TASKID
val action = TaskDetailFragmentDirections
.actionTaskDetailFragmentToAddEditTaskFragment(taskId,
resources.getString(R.string.edit_task))
findNavController().navigate(action)
})
}
private fun setupFab() {
activity?.findViewById<View>(R.id.fab_edit_task)?.setOnClickListener {
viewDataBinding.viewmodel?.editTask()
}
}
override fun onResume() {
super.onResume()
taskId = arguments?.let {
TaskDetailFragmentArgs.fromBundle(it).TASKID
}
loadData(taskId)
}
private fun loadData(taskId: Int?) {
context?.let {
viewDataBinding.viewmodel?.loadData(taskId, it)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val baseView = inflater.inflate(R.layout.taskdetail_frag, container, false)
viewModel = obtainViewModel(TaskDetailViewModel::class.java)
viewDataBinding = TaskdetailFragBinding.bind(baseView).apply {
viewmodel = viewModel
}
taskId = TaskDetailFragmentArgs.fromBundle(arguments!!).TASKID
addContactsFragmentToView(taskId!!)
viewDataBinding.lifecycleOwner = this.viewLifecycleOwner
viewDataBinding.userActionlistener = object : TaskDetailUserActionsListener {
override fun onAddContactClicked(v: View) {
if (viewModel.contactPermissionGranted.value!!) {
startPickContactIntent()
} else requestPermission(PermissionChecker.REQUEST_ADD_CONTACT)
}
override fun onTimeChanged(v: View) {
timePicker.showDialog(context)
}
override fun onDueDateChanged(v: View) {
datePicker.showDialog(context)
}
override fun onFavoriteChanged(v: View) {
viewModel.setFavored((v as CheckBox).isChecked)
}
override fun onCompleteChanged(v: View) {
viewModel.setCompleted((v as CheckBox).isChecked)
}
}
setHasOptionsMenu(true)
return baseView // only this view is return as the other view is declared inside the xml
}
private fun addContactsFragmentToView(taskId: Int) {
val fm = childFragmentManager
val ft = fm!!.beginTransaction()
fm.beginTransaction()
val fragTwo = ContactsFragment()
val bundle = Bundle()
bundle.putInt("taskId", taskId)
fragTwo.arguments = bundle
ft.add(R.id.contact_list, fragTwo)
ft.commit()
}
private fun requestPermission(code: Int) {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS),
code)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == RESULT_OK)
when (requestCode) {
ContactBookService.CALL_PICK_CONTACT -> {
viewDataBinding.viewmodel?.let {
view?.setupSnackbar(this, it.snackbarMessage, Snackbar.LENGTH_SHORT)
it.viewModelScope.launch {
val contactIdString = it.getContactIdString()
val newContactId = data?.let { ContactBookService.getContactID(it, context) }
val contactString = ContactBookService.addContactToString(contactIdString!!, newContactId)
// initiate List which needs to be displayed by adapter
// ContactBookService.getContactListFromString(contactString)
viewModel.setContactString(contactString)
}
}
loadData(taskId)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
when (requestCode) {
PermissionChecker.REQUEST_ADD_CONTACT -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Timber.i("READ_CONTACTS permission granted")
viewDataBinding.viewmodel?.setPermissionGranted(true)
startPickContactIntent()
} else {
//else do nothing - will be call back on next launch
Timber.w("READ_CONTACTS permission refused")
}
}
PermissionChecker.REQUEST_CONTACTS_CODE -> {
return
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_delete_db_task -> {
viewDataBinding.viewmodel?.showDeleteDialog(context!!)
true
}
else -> false
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.taskdetail_fragment_menu, menu)
}
fun startPickContactIntent() {
Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")).also { pickContactIntent ->
pickContactIntent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, ContactBookService.CALL_PICK_CONTACT)
}
}
override fun onTimeSet(p0: TimePicker?, hour: Int, min: Int) {
val time = "$hour:$min"
val long = DateUtil.parseTimeToLong(time)
viewModel.saveTime(long, time)
}
override fun onDateSet(p0: DatePicker?, dYear: Int, dMonth: Int, dDay: Int) {
val date = "$dDay.${dMonth + 1}.$dYear"
val long = DateUtil.parseToLong(date)
viewModel.saveDueDate(long,date)
}
} | 0 | Kotlin | 0 | 0 | adbb376fc080449128162c4ae7ac8dad93f193d6 | 8,784 | Todo_MVVM_Kotlin | Apache License 2.0 |
app/src/main/kotlin/org/andstatus/app/context/MyContextEmpty.kt | andstatus | 3,040,264 | false | {"Kotlin": 3385973, "XSLT": 14655, "HTML": 14046, "CSS": 4427, "Shell": 707} | /*
* Copyright (C) 2021 yvolk (<NAME>), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.context
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import org.andstatus.app.account.MyAccounts
import org.andstatus.app.notification.NotificationData
import org.andstatus.app.notification.Notifier
import org.andstatus.app.origin.PersistentOrigins
import org.andstatus.app.service.CommandQueue
import org.andstatus.app.service.ConnectionState
import org.andstatus.app.timeline.meta.PersistentTimelines
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.user.CachedUsersAndActors
import java.util.function.Supplier
class MyContextEmpty: MyContext {
override fun newInitialized(initializer: Any): MyContext = throwException()
override val initialized: Boolean = false
override val isReady: Boolean = false
override val state: MyContextState = MyContextState.EMPTY
override val context: Context
get() = throwException()
override val baseContext: Context get() = throwException()
override val preferencesChangeTime: Long = 0
override val lastDatabaseError: String = ""
override val database: SQLiteDatabase? = null
override val users: CachedUsersAndActors get() = throwException()
override val accounts: MyAccounts get() = throwException()
override val origins: PersistentOrigins get() = throwException()
override val timelines: PersistentTimelines get() = throwException()
override val queues: CommandQueue get() = throwException()
override fun save(reason: Supplier<String>) {}
override fun release(reason: Supplier<String>) {}
override val isExpired: Boolean get() = false
override fun setExpired(reason: Supplier<String>) {}
override val connectionState: ConnectionState = ConnectionState.UNKNOWN
override var isInForeground: Boolean
get() = false
set(_) {}
override val notifier: Notifier get() = throwException()
private fun throwException(): Nothing {
throw IllegalStateException("This is empty implementation")
}
override fun notify(data: NotificationData) {}
override fun clearNotifications(timeline: Timeline) {}
override val instanceId: Long = 0L
companion object {
val EMPTY: MyContext = MyContextEmpty()
}
}
| 86 | Kotlin | 69 | 306 | 6166aded1f115e6e6a7e66ca3756f39f0434663e | 2,903 | andstatus | Apache License 2.0 |
lib/accounts/src/commonMain/kotlin/zakadabar/lib/accounts/data/RolesByAccount.kt | wiltonlazary | 378,492,647 | true | {"Kotlin": 1162402, "JavaScript": 2042, "HTML": 1390, "Shell": 506} | /*
* Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.lib.accounts.data
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import zakadabar.stack.data.entity.EntityId
import zakadabar.stack.data.query.QueryBo
import zakadabar.stack.data.query.QueryBoCompanion
@Serializable
class RolesByAccount(
val accountId: EntityId<AccountPrivateBo>
) : QueryBo<RoleGrantBo> {
override suspend fun execute() = comm.query(this, serializer(), ListSerializer(RoleGrantBo.serializer()))
companion object : QueryBoCompanion<RoleGrantBo>(RoleBo.boNamespace)
} | 0 | null | 0 | 0 | 1eabec93db32f09cf715048c6cffd0a7948f4d9c | 687 | zakadabar-stack | Apache License 2.0 |
spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt | Baeldung | 260,481,121 | false | null | package com.baeldung.bootmicroservice.model
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table
import java.time.LocalDateTime
@Table
data class Profile(@Id var id:Long?, var firstName : String, var lastName : String, var birthDate: LocalDateTime) | 17 | null | 294 | 460 | 7b73245fbe5d49e8ae45a1aa95a62eb2326989bb | 305 | kotlin-tutorials | MIT License |
src/main/kotlin/sparta/nbcamp/wachu/domain/review/model/v1/ReviewMultiMedia.kt | spartaKotlinTeamSober | 828,133,738 | false | {"Kotlin": 150539} | package sparta.nbcamp.wachu.domain.review.model.v1
import jakarta.persistence.*
@Entity
@Table(name = "review_media")
class ReviewMultiMedia(
@Column(name = "review_id")
var reviewId: Long,
@Column
var mediaUrl: String,
@Enumerated(EnumType.STRING)
@Column
var mediaType: ReviewMediaType
) {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
companion object {
fun toEntity(reviewId: Long, mediaUrl: String, mediaType: ReviewMediaType): ReviewMultiMedia {
return ReviewMultiMedia(
reviewId = reviewId,
mediaUrl = mediaUrl,
mediaType = mediaType
)
}
}
} | 9 | Kotlin | 0 | 0 | 014497d3cf1dc6656b0e9cf1b750d92f6a85add1 | 720 | wachu_server | MIT License |
app/src/main/java/com/udacity/notepad/recycler/NotesAdapter.kt | Alfser | 371,545,061 | false | null | package com.udacity.notepad.recycler
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.udacity.notepad.R
import com.udacity.notepad.data.Note
import com.udacity.notepad.recycler.NotesAdapter.NotesViewHolder
class NotesAdapter(private val context: Context, private val notes:List<Note>) : RecyclerView.Adapter<NotesViewHolder>() {
private var isRefreshing = false
override fun getItemId(position: Int): Long {
return notes[position].id.toLong()
}
override fun getItemCount(): Int {
return notes.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_note, parent, false)
return NotesViewHolder(view)
}
override fun onBindViewHolder(holder: NotesViewHolder, position: Int) {
val note = notes[position]
holder.text.text = note.text
}
class NotesViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
val text: TextView get() = itemView.findViewById(R.id.text)
}
} | 0 | Kotlin | 0 | 0 | 877affcc3aceadb32316a2d1cc9a33a7bc19ec25 | 1,261 | SimpleNotePad | Apache License 2.0 |
app/src/main/java/com/prof18/secureqrreader/Utils.kt | Gozirin | 586,401,887 | false | null |
package com.prof18.secureqrreader
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Patterns
import android.widget.Toast
fun Context.getActivity(): Activity? {
var currentContext = this
while (currentContext is ContextWrapper) {
if (currentContext is Activity) {
return currentContext
}
currentContext = currentContext.baseContext
}
return null
}
fun hasFlash(context: Context): Boolean =
context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
fun goToAppSettings(context: Context) {
val intent = Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", context.packageName, null)
)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
fun isUrl(qrResult: String?): Boolean {
val url = qrResult ?: return false
return Patterns.WEB_URL.matcher(url).matches()
}
fun openUrl(qrResult: String?, context: Context) {
val url = qrResult ?: return
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(browserIntent)
}
fun copyToClipboard(qrResult: String?, context: Context) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
as ClipboardManager
val clip: ClipData = ClipData.newPlainText("QR Result", qrResult)
clipboard.setPrimaryClip(clip)
}
fun shareResult(qrResult: String?, context: Context) {
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, qrResult)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
context.startActivity(shareIntent)
} | 0 | Kotlin | 0 | 0 | 128226f89775652cce210b842046bc1f6ab2e8c0 | 1,981 | QrScanner | Apache License 2.0 |
screen/ui/src/main/kotlin/dev/teogor/ceres/screen/ui/lookandfeel/LookAndFeelNavigation.kt | teogor | 555,090,893 | false | {"Kotlin": 1324729} | /*
* Copyright 2023 teogor (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.teogor.ceres.screen.ui.lookandfeel
import androidx.compose.runtime.Composable
import androidx.navigation.NavGraphBuilder
import dev.teogor.ceres.navigation.core.ScreenRoute
import dev.teogor.ceres.navigation.core.screenNav
const val lookAndFeelNavigationRoute = "settings_look_and_feel_route"
object LookAndFeelScreenRoute : ScreenRoute {
override val route: String = lookAndFeelNavigationRoute
}
inline fun NavGraphBuilder.lookAndFeelScreenNav(
crossinline block: @Composable () -> Unit,
) = screenNav(
route = lookAndFeelNavigationRoute,
) {
block()
}
| 2 | Kotlin | 4 | 62 | 48576bbf21c28c200d18167d0178125c2d5c239a | 1,179 | ceres | Apache License 2.0 |
src/main/kotlin/icu/windea/pls/dev/cwt/CwtLocalisationConfigGenerator.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.dev.cwt
import icu.windea.pls.core.*
import icu.windea.pls.model.*
import java.io.*
/**
* 用于从`localisations.log`生成
*/
class CwtLocalisationConfigGenerator(
val gameType: ParadoxGameType,
val logPath: String,
val cwtPath: String,
) {
data class LocalisationInfo(
var name: String = "",
val promotions: MutableSet<String> = mutableSetOf(),
val properties: MutableSet<String> = mutableSetOf(),
)
enum class Position {
ScopeName, Promotions, Properties
}
fun generate() {
val logFile = File(logPath)
val infos = mutableListOf<LocalisationInfo>()
var info = LocalisationInfo()
var position = Position.ScopeName
val allLines = logFile.bufferedReader().readLines()
for(line in allLines) {
val l = line.trim()
if(l.surroundsWith("--", "--")) {
if(info.name.isNotEmpty()) {
infos.add(info)
info = LocalisationInfo()
}
info.name = l.removeSurrounding("--", "--")
position = Position.ScopeName
continue
}
if(l == "Promotions:") {
position = Position.Promotions
continue
}
if(l == "Properties") {
position = Position.Properties
continue
}
when(position) {
Position.Promotions -> {
val v = l.takeIf { it.isNotEmpty() && it.all { c -> c != '=' } }
if(v != null) info.promotions.add(v)
}
Position.Properties -> {
val v = l.takeIf { it.isNotEmpty() && it.all { c -> c != '=' } }
if(v != null) info.properties.add(v)
}
else -> {}
}
}
if(info.name.isNotEmpty()) {
infos.add(info)
}
val newLocLines = getLocLines(infos)
val cwtFile = File(cwtPath)
val allCwtLines = cwtFile.bufferedReader().readLines()
val newLines = mutableListOf<String>()
var flag = false
for(line in allCwtLines) {
if(line == "localisation_commands = {") {
flag = true
newLines.addAll(newLocLines)
continue
}
if(flag && line == "}") {
flag = false
continue
}
if(flag) continue
newLines.add(line)
}
cwtFile.writeText(newLines.joinToString("\n"))
}
private fun getLocLines(infos: List<LocalisationInfo>): List<String> {
val map = mutableMapOf<String, MutableSet<String>>()
infos.forEach { info ->
info.properties.forEach { prop ->
val set = map.getOrPut(prop) { mutableSetOf() }
val scope = info.name
when {
scope == "Base Scope" -> {
set.add("any")
}
scope == "Ship (and Starbase)" -> {
set.add("ship")
set.add("starbase")
}
else -> {
set.add(scope.lowercase())
}
}
}
}
val result = mutableListOf<String>()
result.add("localisation_commands = {")
map.forEach { (k, v) ->
val vs = when {
v.isEmpty() -> "{}"
v.contains("any") -> "{ any }"
else -> v.joinToString(" ", "{ ", " }")
}
result.add(" $k = $vs")
}
result.add("}")
return result
}
} | 9 | null | 4 | 37 | 4b3531109f2428f6f7e6be5abc9b5b27547950e8 | 3,823 | Paradox-Language-Support | MIT License |
app/src/main/java/com/example/css545application/data/PreferencesRepository.kt | sarahmarie23 | 780,148,390 | false | {"Kotlin": 35271} | package com.example.css545application.data
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
import com.example.css545application.ui.SoupUiState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class PreferencesRepository(
private val dataStore: DataStore<Preferences>
) {
val storedImageURI: Flow<String?> = dataStore.data.map {
it[IMAGE_URI_KEY]
}.distinctUntilChanged()
val storedUserName: Flow<String?> = dataStore.data.map {
it[USER_NAME_KEY]
}.distinctUntilChanged()
val storedSoupCount: Flow<Int> = dataStore.data.map { preferences ->
preferences[SOUP_COUNT_KEY] ?: 0
}
val storedMaxSoupCount: Flow<Int?> = dataStore.data.map {
it[MAX_SOUP_COUNT_KEY] ?.toInt()
}.distinctUntilChanged()
val storedRecentDate: Flow<Date?> = dataStore.data.map {
val dateString = it[RECENT_DATE_KEY]
dateString?.let {
try {
SimpleDateFormat("MM-dd-yyyy", Locale.getDefault()).parse(dateString)
} catch (e: Exception) {
null
}
}
}.distinctUntilChanged()
suspend fun setStoredImageURI(uri: String) {
dataStore.edit { preferences ->
preferences[IMAGE_URI_KEY] = uri
}
}
suspend fun setStoredUserName(userName: String) {
dataStore.edit { preferences ->
preferences[USER_NAME_KEY] = userName
}
}
suspend fun setStoredSoupCount(storedSoupCount: Int) {
dataStore.edit { preferences ->
preferences[SOUP_COUNT_KEY] = storedSoupCount
}
}
suspend fun setStoredMaxSoupCount(count: Int) {
dataStore.edit { preferences ->
preferences[MAX_SOUP_COUNT_KEY] = count
}
}
suspend fun setStoredRecentDate(date: Date) {
val dateString = SimpleDateFormat("MM-dd-yyyy", Locale.getDefault()).format(date)
dataStore.edit { preferences ->
preferences[RECENT_DATE_KEY] = dateString
}
}
companion object {
val IMAGE_URI_KEY = stringPreferencesKey("image_uri")
val USER_NAME_KEY = stringPreferencesKey("user_name")
val SOUP_COUNT_KEY = intPreferencesKey("soup_count")
val MAX_SOUP_COUNT_KEY = intPreferencesKey("max_soup_count")
val RECENT_DATE_KEY = stringPreferencesKey("recent_date")
//private var INSTANCE: PreferencesRepository? = null
/*
fun getInstance(dataStore: DataStore<Preferences>): PreferencesRepository {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: create(dataStore).also { INSTANCE = it }
}
}
private fun create(dataStore: DataStore<Preferences>): PreferencesRepository {
return PreferencesRepository(dataStore)
}
fun initialize(context: Context) {
if (INSTANCE == null) {
val dataStore = PreferenceDataStoreFactory.create {
context.preferencesDataStoreFile("user_preferences")
}
INSTANCE = PreferencesRepository(dataStore)
}
}
fun get(): PreferencesRepository {
return INSTANCE ?: throw IllegalStateException(
"PreferencesRepository must be initialized"
)
}
}
suspend fun getSoupUiState(): Flow<SoupUiState> {
return dataStore.data.map { dataStore ->
SoupUiState(
countState = dataStore[SOUP_COUNT_KEY] ?: 0,
maxCountState = dataStore[MAX_SOUP_COUNT_KEY] ?: 0,
recentDateState = dataStore[RECENT_DATE_KEY]?.let { dateString ->
parseDate(dateString)
}
)
}
*/
}
} | 0 | Kotlin | 0 | 0 | 1f0e02d5b03940888105b2ea8b5bb8f1f3e34ed6 | 4,308 | Spring-2024-App-Project | MIT License |
src/main/kotlin/com/antwerkz/bottlerocket/configuration/types/ServiceExecutor.kt | evanchooly | 36,263,772 | false | {"Maven POM": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "XML": 3, "Java": 1, "Kotlin": 81, "YAML": 3} | package com.antwerkz.bottlerocket.configuration.types
enum class ServiceExecutor {
SYNCHRONOUS,
ADAPTIVE
}
| 4 | Kotlin | 1 | 2 | dceb89cb720716a3fe13b3d64f53af1e4426108f | 116 | bottlerocket | Apache License 2.0 |
util/src/main/kotlin/rs/emulate/util/compression/Bzip.kt | apollo-rsps | 50,723,825 | false | null | package rs.emulate.util.compression
import com.google.common.io.ByteStreams
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.ByteBufOutputStream
import io.netty.buffer.Unpooled
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream
object Bzip {
val HEADER = charArrayOf('B', 'Z', 'h', '1').map(Char::toByte).toByteArray()
}
fun ByteBuf.bunzip2(uncompressedLength: Int): ByteBuf {
val header = Unpooled.wrappedBuffer(Bzip.HEADER)
val input = Unpooled.wrappedBuffer(header, this)
val output = Unpooled.buffer(uncompressedLength)
BZip2CompressorInputStream(ByteBufInputStream(input)).use { inputStream ->
ByteBufOutputStream(output).use { outputStream ->
ByteStreams.copy(inputStream, outputStream)
}
}
return output.asReadOnly()
}
fun ByteBuf.bzip2(): ByteBuf {
val output = Unpooled.buffer()
ByteBufInputStream(this).use { inputStream ->
BZip2CompressorOutputStream(ByteBufOutputStream(output), 1).use { outputStream ->
ByteStreams.copy(inputStream, outputStream)
}
}
val length = output.readableBytes() - Bzip.HEADER.size
return output.slice(Bzip.HEADER.size, length).asReadOnly()
}
| 6 | null | 5 | 12 | fba5069744a04835c23373c1d11f90b201cdc604 | 1,350 | Vicis | ISC License |
app/src/main/java/com/jslee/moobeside/util/CustomTimberDebugTree.kt | JaesungLeee | 675,525,103 | false | {"Kotlin": 248136} | package com.jslee.moobeside.util
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
/**
* MooBeside
* @author jaesung
* @created 2023/08/07
*/
@Singleton
class CustomTimberDebugTree @Inject constructor() : Timber.DebugTree() {
override fun createStackElementTag(element: StackTraceElement): String {
return "${element.className}:${element.lineNumber}#${element.methodName}"
}
} | 10 | Kotlin | 0 | 2 | 7f015aa2d14907b5a179a3c26392258ced682200 | 431 | MooBeside | MIT License |
fabric/src/main/kotlin/org/valkyrienskies/mod/fabric/common/FabricHooksImpl.kt | Dayr11 | 586,629,745 | true | {"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 12, "EditorConfig": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Git Config": 1, "XML": 6, "Kotlin": 61, "Java": 146, "JSON": 44, "TOML": 1, "YAML": 3, "INI": 2} | package org.valkyrienskies.mod.fabric.common
import io.netty.buffer.ByteBuf
import net.fabricmc.api.EnvType.CLIENT
import net.fabricmc.loader.api.FabricLoader
import org.valkyrienskies.core.apigame.world.IPlayer
import org.valkyrienskies.mod.common.ValkyrienSkiesMod
import org.valkyrienskies.mod.common.hooks.CommonHooksImpl
import java.nio.file.Path
class FabricHooksImpl(private val networking: VSFabricNetworking) : CommonHooksImpl() {
override val isPhysicalClient: Boolean
get() = FabricLoader.getInstance().environmentType == CLIENT
override val configDir: Path
get() = FabricLoader.getInstance().configDir.resolve(ValkyrienSkiesMod.MOD_ID)
override fun sendToServer(buf: ByteBuf) {
networking.sendToServer(buf)
}
override fun sendToClient(buf: ByteBuf, player: IPlayer) {
networking.sendToClient(buf, player)
}
}
| 0 | null | 0 | 0 | 26720096406bfd2f71642eb5ec5e3c315b895f50 | 883 | Valkyrien-Skies-2 | Apache License 2.0 |
app/src/main/kotlin/com/foreverht/workplus/receiver/MzPushReceiver.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreverht.workplus.receiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.foreveross.atwork.R
import com.foreveross.atwork.infrastructure.shared.CommonShareInfo
import com.foreveross.atwork.modules.chat.activity.ChatDetailActivity
import com.foreveross.atwork.modules.main.activity.MainActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.meizu.cloud.pushsdk.MzPushMessageReceiver
import com.meizu.cloud.pushsdk.handler.MzPushMessage
import com.meizu.cloud.pushsdk.notification.PushNotificationBuilder
import com.meizu.cloud.pushsdk.platform.message.*
class MzPushReceiver: MzPushMessageReceiver() {
override fun onRegister(contex: Context?, pushToken: String?) {
}
override fun onSubTagsStatus(contex: Context?, status: SubTagsStatus?) {
}
override fun onRegisterStatus(contex: Context?, status: RegisterStatus?) {
Log.e("MZPush", "mz push token = " + status?.pushId);
CommonShareInfo.setMeiZuPushToken(contex, status?.pushId)
}
override fun onUnRegisterStatus(contex: Context?, status: UnRegisterStatus?) {
}
override fun onSubAliasStatus(contex: Context?, alias: SubAliasStatus?) {
}
override fun onUnRegister(contex: Context?, isUnRegister: Boolean) {
}
override fun onPushStatus(contex: Context?, status: PushSwitchStatus?) {
}
override fun onUpdateNotificationBuilder(pushNotificationBuilder: PushNotificationBuilder?) {
pushNotificationBuilder?.setmStatusbarIcon(R.mipmap.icon_notice_small)
}
override fun onNotificationClicked(context: Context?, mzMessage: MzPushMessage?) {
Log.e("MZPush", "content = " + mzMessage?.content + " selfDefineContentString = " + mzMessage?.selfDefineContentString)
val extras: HashMap<String, String> = Gson().fromJson(mzMessage?.selfDefineContentString, object: TypeToken<HashMap<String, String>>(){}.type)
var intent = Intent()
var bundles = Bundle()
var from = extras?.get("from")
var type = extras?.get("type")
bundles.putString("type", type)
if ("MEETING".equals(type)) {
intent = Intent(context, MainActivity::class.java)
} else {
intent = Intent(context, ChatDetailActivity::class.java)
}
bundles.putString("from", from)
bundles.putString("to", extras?.get("to"))
bundles.putString("display_name", extras?.get("display_name"))
bundles.putString("display", extras?.get("display_avatar"))
Log.e("MZPush", "display_name = " + extras?.get("display_name"))
intent.putExtras(bundles)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(intent);
}
} | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 2,808 | w6s_lite_android | MIT License |
app/src/main/java/com/fingerprintjs/android/aev/demo/demo_screen/api/VerifyRequest.kt | fingerprintjs | 335,972,296 | false | null | package com.fingerprintjs.android.aev.demo.demo_screen.api
import com.fingerprintjs.android.aev.transport.Request
import com.fingerprintjs.android.aev.transport.RequestResultType
import com.fingerprintjs.android.aev.transport.RequestType
import com.fingerprintjs.android.aev.transport.TypedRequestResult
import org.json.JSONObject
import java.util.*
class Verdict(
val name: String,
val value: Boolean
)
class VerificationResult(
val deviceId: String,
val verdicts: List<Verdict>
)
class VerificationResultResponse(
type: RequestResultType,
rawResponse: ByteArray?
) : TypedRequestResult<VerificationResult>(type, rawResponse) {
override fun typedResult(): VerificationResult? {
val errorResponse = VerificationResult("", emptyList())
val body = rawResponse?.toString(Charsets.UTF_8) ?: return errorResponse
return try {
val jsonBody = JSONObject(body)
val deviceId = jsonBody.getString(DEVICE_ID_KEY)
val results = jsonBody.getJSONObject(RESULTS_KEY)
val verdictList = LinkedList<Verdict>()
results.keys().forEach {
val value = results.getBoolean(it)
verdictList.add(Verdict(splitCamelCaseString(it), value))
}
VerificationResult(deviceId, verdictList)
} catch (exception: Exception) {
errorResponse
}
}
private fun splitCamelCaseString(camelCaseString: String): String {
return camelCaseString.map {
if (it.isUpperCase()) {
" ${it.toLowerCase()}"
} else it
}.joinToString("").capitalize()
}
}
class VerifyRequest(
endpointUrl: String,
private val autorizationToken: String,
private val requestId: String
) : Request {
override val url = "$endpointUrl/api/v1/verify"
override val type = RequestType.POST
override val headers = mapOf(
"Content-Type" to "application/json"
)
override fun bodyAsMap(): Map<String, Any> {
val resultMap = HashMap<String, Any>()
resultMap[PRIVATE_API_KEY] = autorizationToken
resultMap[REQUEST_ID_KEY] = requestId
return resultMap
}
}
| 1 | null | 3 | 71 | 5769d4ef97dda4751765f3fa81bb917c09b9d4fc | 2,215 | aev | MIT License |
app/src/main/java/com/emenjivar/pomodoro/utils/model/Phase.kt | emenjivar | 439,725,046 | false | null | package com.emenjivar.pomodoro.utils.model
enum class Phase {
WORK, REST
}
| 5 | Kotlin | 0 | 9 | 1eb12225916300a065400116148026ffe2a1867e | 80 | pomodoro-timer | MIT License |
zebra/feature/vault/src/main/java/com/maksimowiczm/zebra/feature/vault/opened/OpenedVaultScreen.kt | maksimowiczm | 854,647,759 | false | {"Kotlin": 244293} | package com.maksimowiczm.zebra.feature.vault.opened
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TooltipBox
import androidx.compose.material3.TooltipDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberTooltipState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.PreviewLightDark
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maksimowiczm.zebra.core.common_ui.SomethingWentWrongScreen
import com.maksimowiczm.zebra.core.common_ui.theme.ZebraTheme
import com.maksimowiczm.zebra.core.data.model.Vault
import com.maksimowiczm.zebra.core.data.model.VaultEntry
import com.maksimowiczm.zebra.core.data.model.VaultEntryIdentifier
import com.maksimowiczm.zebra.core.data.model.VaultIdentifier
import com.maksimowiczm.zebra.core.network.NetworkStatus
import com.maksimowiczm.zebra.feature_vault.R
@Composable
internal fun OpenedVaultScreen(
onNavigateUp: () -> Unit,
onClose: () -> Unit,
onShare: (VaultIdentifier, VaultEntryIdentifier) -> Unit,
viewModel: OpenedVaultViewModel = hiltViewModel(),
) {
val uiState by viewModel.state.collectAsStateWithLifecycle()
val featureShare by viewModel.featureShare.collectAsStateWithLifecycle()
val context = LocalContext.current
BackHandler {
onNavigateUp()
}
LaunchedEffect(uiState) {
if (uiState is OpenVaultUiState.Closed) {
Toast.makeText(context, context.getString(R.string.locked), Toast.LENGTH_SHORT).show()
onClose()
}
if (uiState is OpenVaultUiState.Lost) {
onNavigateUp()
}
}
when (uiState) {
OpenVaultUiState.Loading,
OpenVaultUiState.Closed,
-> LoadingScreen()
OpenVaultUiState.Lost -> SomethingWentWrongScreen(onNavigateUp)
is OpenVaultUiState.Unlocked -> {
val state = uiState as OpenVaultUiState.Unlocked
val shareHandler = if (featureShare) {
if (state.networkStatus == NetworkStatus.Online) {
ShareHandler.Enabled { entryIdentifier ->
onShare(state.vault.identifier, entryIdentifier)
}
} else {
ShareHandler.NotAvailable
}
} else {
ShareHandler.Disabled
}
OpenedVaultScreen(
vault = state.vault,
onNavigateUp = onNavigateUp,
entries = state.entries,
onLock = { viewModel.onLock() },
onCopy = { text, hide -> viewModel.onCopy(text, hide) },
shareHandler = shareHandler
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun OpenedVaultScreen(
onNavigateUp: () -> Unit,
onLock: () -> Unit,
onCopy: (String, Boolean) -> Unit,
shareHandler: ShareHandler,
vault: Vault,
entries: List<VaultEntry>,
) {
Column {
TopAppBar(
title = {
Text(
text = vault.name,
style = MaterialTheme.typography.headlineLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
actions = {
TooltipBox(
positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
state = rememberTooltipState(),
tooltip = {
Text(stringResource(R.string.lock))
}
) {
IconButton(
onClick = onLock
) {
Icon(
imageVector = Icons.Default.Lock,
contentDescription = stringResource(R.string.lock)
)
}
}
IconButton(
onClick = onNavigateUp
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = stringResource(R.string.close)
)
}
}
)
Column(
modifier = Modifier.fillMaxSize()
) {
LazyColumn {
items(entries) {
VaultEntryListItem(
entry = it,
onCopy = onCopy,
shareHandler = shareHandler,
)
HorizontalDivider()
}
}
}
}
}
@Composable
private fun LoadingScreen() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator()
}
}
@PreviewLightDark
@Composable
private fun OpenedVaultScreenPreview(
@PreviewParameter(VaultEntryListProvider::class) entries: List<VaultEntry>,
) {
ZebraTheme {
Surface {
OpenedVaultScreen(
onNavigateUp = {},
onLock = {},
onCopy = { _, _ -> },
vault = Vault(
identifier = 0,
name = "My vault",
path = "".toUri()
),
entries = entries,
shareHandler = ShareHandler.Disabled
)
}
}
} | 0 | Kotlin | 0 | 0 | 21f20c7f83a542b704928171371d10e6a14c6ce5 | 6,860 | zebra-android | Apache License 2.0 |
android-logging/src/main/java/com/cren90/android/logging/strategies/LogStrategy.kt | cren90 | 527,753,310 | false | {"Kotlin": 17078} | package com.cren90.android.logging.strategies
import com.cren90.android.logging.splitter.LogSplitter
/**
* Wrapper interface around logging various messages to different locations (Logcat, Splunk, Crashlytics, Datadog, etc)
*/
interface LogStrategy {
val logSplitter: LogSplitter
/**
* Logs a fatal [message] with a given [tag] and any associated [data]
*/
fun fatal(message: String?, tag: String, data: Map<String, Any?>? = null)
/**
* Logs a error [message] with a given [tag] and any associated [data]
*/
fun error(message: String?, tag: String, data: Map<String, Any?>? = null)
/**
* Logs a warning [message] with a given [tag] and any associated [data]
*/
fun warning(message: String?, tag: String, data: Map<String, Any?>? = null)
/**
* Logs a info( [message] with a given [tag] and any associated [data]
*/
fun info(message: String?, tag: String, data: Map<String, Any?>? = null)
/**
* Logs a debug [message] with a given [tag] and any associated [data] will only occur in debug builds
*/
fun debug(message: String?, tag: String, data: Map<String, Any?>? = null)
/**
* Logs a verbose [message] with a given [tag] and any associated [data] will only occur in debug builds
*/
fun verbose(message: String?, tag: String, data: Map<String, Any?>? = null)
} | 0 | Kotlin | 0 | 0 | 8b7728358a423da1ac356d08518993e2c7b2bd73 | 1,380 | android-logging | Apache License 2.0 |
app/src/main/java/com/uinjkt/mobilepqi/ui/mahasiswa/menutugas/MahasiswaTugasViewModel.kt | acalapatih | 708,105,917 | false | {"Kotlin": 524790} | package com.uinjkt.mobilepqi.ui.mahasiswa.menutugas
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mobilepqi.core.data.Resource
import com.mobilepqi.core.domain.model.tugas.GetListTugasModel
import com.mobilepqi.core.domain.usecase.tugas.MenuTugasUseCase
import kotlinx.coroutines.launch
class MahasiswaTugasViewModel(private val useCase: MenuTugasUseCase) : ViewModel() {
private val _getListTugas = MutableLiveData<Resource<GetListTugasModel>>()
val getListTugas: LiveData<Resource<GetListTugasModel>> get() = _getListTugas
fun getListTugas(idKelas: Int) {
viewModelScope.launch {
useCase.getListTugas(idKelas).collect {
_getListTugas.value = it
}
}
}
} | 0 | Kotlin | 0 | 0 | e4c7c4a93d1c2b1632a45c827b9df76652b0d0f7 | 849 | MobilePQI_mobileApps | MIT License |
modulecheck-parsing/java/src/main/kotlin/modulecheck/parsing/java/JavaEverythingPrinter.kt | RBusarow | 316,627,145 | false | null | /*
* Copyright (C) 2021-2022 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package modulecheck.parsing.java
import com.github.javaparser.ast.Node
import modulecheck.utils.remove
internal class JavaEverythingPrinter {
private val parentNameMap = mutableMapOf<Node, String>()
fun visit(node: Node) {
val thisName = node::class.java.simpleName
val parentName = node.parentName()
println(
""" ******************************** -- $thisName -- parent: $parentName
|$node
|_________________________________________________________________________________
""".trimMargin()
)
node.childNodes.forEach { child ->
visit(child)
}
}
private fun Node.parentName() = parentNode.getOrNull()
?.let { parent ->
parentNameMap.getOrPut(parent) {
val typeCount = parentNameMap.keys.count { it::class == parent::class }
val simpleName = parent::class.java.simpleName
val start = if (typeCount == 0) {
simpleName
} else {
"$simpleName (${typeCount + 1})"
}
start // + parent.extendedTypes()
}
}
@Suppress("UnusedPrivateMember")
private fun Node.extendedTypes(): String {
return this::class.supertypes
.ifEmpty { return "" }
.joinToString(prefix = " [ ", postfix = " ] ") { kType ->
kType.toString()
.remove("com.github.javaparser.ast.body.")
}
}
}
internal fun Node.printEverything() {
JavaEverythingPrinter().visit(this)
}
| 8 | Kotlin | 7 | 95 | 24e7c7667490630d30cf8b59cd504cd863cd1fba | 2,034 | ModuleCheck | Apache License 2.0 |
project/core/src/main/kotlin/io/github/liangcha385/clayillustratedhandbook/ClayIllustratedHandbook.kt | liangcha385 | 835,576,475 | false | {"Kotlin": 1365} | package io.github.liangcha385.clayillustratedhandbook
import taboolib.module.configuration.Config
import taboolib.module.configuration.Configuration
object ClayIllustratedHandbook {
@Config
lateinit var conf: Configuration
private set
} | 0 | Kotlin | 0 | 0 | b4787d6a1f2df63b903e8b56cce3c7b0a23b4186 | 254 | ClayIllustratedHandbook-plugins | Creative Commons Zero v1.0 Universal |
core_view/src/main/java/com/turtleteam/core_view/theme/Shapes.kt | Egor-Liadsky | 711,194,733 | false | {"Kotlin": 240067} | package com.turtleteam.core_view.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.unit.dp
val LocalShapes = staticCompositionLocalOf<Shapes> { error("shapes wasnt provided") }
val turtleShapes = Shapes(
small = RoundedCornerShape(5.dp),
medium = RoundedCornerShape(12.dp),
large = RoundedCornerShape(0.dp)
)
| 0 | Kotlin | 0 | 0 | b2b124b5306a4c07567ecffbc0a244e65683ff1d | 464 | TurtleAppAndroid | Apache License 2.0 |
app/src/main/java/com/sample/neuroid/us/fragments/NIDSecondFragment.kt | Neuro-ID | 433,158,128 | false | {"Kotlin": 339612, "JavaScript": 1588, "Shell": 831, "HTML": 755} | package com.sample.neuroid.us.fragments
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.sample.neuroid.us.constants.NID_GO_TO_THIRD_FRAG
import com.sample.neuroid.us.databinding.NidFragmentTwoBinding
import com.sample.neuroid.us.interfaces.NIDNavigateFragsListener
class NIDSecondFragment: Fragment() {
private lateinit var binding : NidFragmentTwoBinding
private var listener: NIDNavigateFragsListener? = null
override fun onAttach(context: Context) {
super.onAttach(context)
listener = context as? NIDNavigateFragsListener
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = NidFragmentTwoBinding.inflate(inflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
buttonContinueFragTwo.setOnClickListener {
listener?.goToNextScreen(NID_GO_TO_THIRD_FRAG)
}
}
}
} | 2 | Kotlin | 3 | 2 | f0e6d5328dae8a3c45832cd9328604b93c4df3e8 | 1,220 | neuroid-android-sdk | MIT License |
src/jvmMain/kotlin/acidicoala/koalageddon/home/model/HomeTab.kt | acidicoala | 584,899,259 | false | null | package acidicoala.koalageddon.home.model
import acidicoala.koalageddon.core.model.Store
import acidicoala.koalageddon.core.ui.composition.LocalStrings
import acidicoala.koalageddon.core.values.Bitmaps
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import kotlinx.serialization.Serializable
@Serializable
enum class HomeTab(
val priority: Int,
val store: Store?,
val label: @Composable () -> String,
val painter: @Composable () -> Painter,
) {
Start(
priority = 0,
store = null,
label = { LocalStrings.current.startPage },
painter = { painterResource(Bitmaps.Icon) },
),
Settings(
priority = 1,
store = null,
label = { LocalStrings.current.settings },
painter = { painterResource(Bitmaps.Settings) },
),
Epic(
priority = 100,
store = Store.Epic,
label = { LocalStrings.current.storeEpic },
painter = { painterResource(Bitmaps.Epic) },
),
Ubisoft(
priority = 101,
store = Store.Ubisoft,
label = { LocalStrings.current.storeUbisoft },
painter = { painterResource(Bitmaps.Ubisoft) },
),
Steam(
priority = 102,
store = Store.Steam,
label = { LocalStrings.current.storeSteam },
painter = { painterResource(Bitmaps.Steam) },
),
} | 1 | Kotlin | 4 | 50 | 9ec09a7ba5cabc7b1be173a9c8e8794c93984a24 | 1,437 | Koalageddon2 | The Unlicense |
app/src/androidTest/java/com/github/spacepilothannah/spongiform/support/SpongiformServiceTestHelper.kt | spacepilothannah | 175,169,331 | false | null | package com.github.spacepilothannah.spongiform.support
class SpongiformServiceTestHelper {
} | 0 | Kotlin | 0 | 0 | 3e0b4bf1d1966024cf1a2a410f215d5e78ba5447 | 94 | spongiform-app | MIT License |
rtron-transformer/src/main/kotlin/io/rtron/transformer/opendrive2roadspaces/roadspaces/RoadBuilder.kt | tum-gis | 258,142,903 | false | null | /*
* Copyright 2019-2020 Chair of Geoinformatics, Technical University of Munich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rtron.transformer.opendrive2roadspaces.roadspaces
import arrow.core.Option
import arrow.core.Some
import arrow.core.getOrElse
import arrow.core.none
import com.github.kittinunf.result.Result
import com.github.kittinunf.result.map
import io.rtron.io.logging.LogManager
import io.rtron.math.geometry.curved.threed.surface.CurveRelativeParametricSurface3D
import io.rtron.math.range.Range
import io.rtron.math.range.shiftLowerEndpointTo
import io.rtron.model.opendrive.common.EContactPoint
import io.rtron.model.opendrive.road.lanes.RoadLanesLaneSection
import io.rtron.model.roadspaces.junction.JunctionIdentifier
import io.rtron.model.roadspaces.roadspace.ContactPoint
import io.rtron.model.roadspaces.roadspace.RoadspaceContactPointIdentifier
import io.rtron.model.roadspaces.roadspace.RoadspaceIdentifier
import io.rtron.model.roadspaces.roadspace.attribute.AttributeList
import io.rtron.model.roadspaces.roadspace.attribute.attributes
import io.rtron.model.roadspaces.roadspace.road.LaneIdentifier
import io.rtron.model.roadspaces.roadspace.road.LaneSection
import io.rtron.model.roadspaces.roadspace.road.LaneSectionIdentifier
import io.rtron.model.roadspaces.roadspace.road.Road
import io.rtron.model.roadspaces.roadspace.road.RoadLinkage
import io.rtron.std.handleFailure
import io.rtron.transformer.opendrive2roadspaces.analysis.FunctionBuilder
import io.rtron.transformer.opendrive2roadspaces.configuration.Opendrive2RoadspacesConfiguration
import io.rtron.model.opendrive.road.Road as OpendriveRoad
/**
* Builder for [Road] objects of the RoadSpaces data model.
*/
class RoadBuilder(
val configuration: Opendrive2RoadspacesConfiguration
) {
// Properties and Initializers
private val _reportLogger = LogManager.getReportLogger(configuration.projectId)
private val _functionBuilder = FunctionBuilder(_reportLogger, configuration)
private val _laneBuilder = LaneBuilder(configuration)
// Methods
/**
* Builds a single road from the OpenDRIVE data model.
*
* @param id identifier of the road space
* @param road source road model of OpenDRIVE
* @param roadSurface road surface with torsion applied
* @param roadSurfaceWithoutTorsion road surface without torsion applied (needed for lanes with true level entry)
* @param baseAttributes attributes attached to each element of the road (e.g. lanes)
*/
fun buildRoad(
id: RoadspaceIdentifier,
road: OpendriveRoad,
roadSurface: CurveRelativeParametricSurface3D,
roadSurfaceWithoutTorsion: CurveRelativeParametricSurface3D,
baseAttributes: AttributeList
):
Result<Road, Exception> {
// check whether source model is processable
road.lanes.isProcessable(configuration.tolerance)
.map { _reportLogger.log(it, id.toString()) }
.handleFailure { return it }
val laneOffset = _functionBuilder.buildLaneOffset(id, road.lanes)
val laneSections = road.lanes.getLaneSectionsWithRanges(road.length)
.mapIndexed { currentId, currentLaneSection ->
buildLaneSection(
LaneSectionIdentifier(currentId, id),
currentLaneSection.first,
currentLaneSection.second,
baseAttributes
)
}
.handleFailure { return it }
if (laneSections.isEmpty())
return Result.error(IllegalArgumentException("Road element contains no valid lane sections."))
val roadLinkage = buildRoadLinkage(id, road)
val roadspaceRoad = Road(id, roadSurface, roadSurfaceWithoutTorsion, laneOffset, laneSections, roadLinkage)
return Result.success(roadspaceRoad)
}
/**
* Builds a [LaneSection] which corresponds to OpenDRIVE's concept of lane sections.
*/
private fun buildLaneSection(
laneSectionIdentifier: LaneSectionIdentifier,
curvePositionDomain: Range<Double>,
laneSection: RoadLanesLaneSection,
baseAttributes: AttributeList
):
Result<LaneSection, Exception> {
// check whether source model is processable
laneSection.isProcessable()
.map { _reportLogger.log(it, laneSectionIdentifier.toString()) }
.handleFailure { return it }
val localCurvePositionDomain = curvePositionDomain.shiftLowerEndpointTo(0.0)
val laneSectionAttributes = buildAttributes(laneSection)
val lanes = laneSection.getLeftRightLanes()
.map { (currentLaneId, currentSrcLane) ->
val laneIdentifier = LaneIdentifier(currentLaneId, laneSectionIdentifier)
val attributes = baseAttributes + laneSectionAttributes
_laneBuilder.buildLane(laneIdentifier, localCurvePositionDomain, currentSrcLane, attributes)
}
val centerLane = _laneBuilder.buildCenterLane(
laneSectionIdentifier,
localCurvePositionDomain,
laneSection.center.lane,
baseAttributes
)
val roadspaceLaneSection = LaneSection(laneSectionIdentifier, curvePositionDomain, lanes, centerLane)
return Result.success(roadspaceLaneSection)
}
private fun buildRoadLinkage(id: RoadspaceIdentifier, road: OpendriveRoad): RoadLinkage {
val belongsToJunctionId = road.getJunction()
.map { JunctionIdentifier(it, id.modelIdentifier) }
val predecessorRoadspaceContactPointId = road.link.predecessor.getRoadPredecessorSuccessor()
.map { RoadspaceContactPointIdentifier(it.second.toContactPoint().getOrElse { ContactPoint.START }, RoadspaceIdentifier(it.first, id.modelIdentifier)) }
val predecessorJunctionId = road.link.predecessor.getJunctionPredecessorSuccessor()
.map { JunctionIdentifier(it, id.modelIdentifier) }
val successorRoadspaceContactPointId = road.link.successor.getRoadPredecessorSuccessor()
.map { RoadspaceContactPointIdentifier(it.second.toContactPoint().getOrElse { ContactPoint.START }, RoadspaceIdentifier(it.first, id.modelIdentifier)) }
val successorJunctionId = road.link.successor.getJunctionPredecessorSuccessor()
.map { JunctionIdentifier(it, id.modelIdentifier) }
return RoadLinkage(
belongsToJunctionId,
predecessorRoadspaceContactPointId,
predecessorJunctionId,
successorRoadspaceContactPointId,
successorJunctionId,
)
}
private fun buildAttributes(laneSection: RoadLanesLaneSection) =
attributes("${configuration.attributesPrefix}laneSection_") {
attribute("curvePositionStart", laneSection.laneSectionStart.curvePosition)
}
}
fun EContactPoint.toContactPoint(default: Option<ContactPoint> = none()) =
when (this) {
EContactPoint.START -> Some(ContactPoint.START)
EContactPoint.END -> Some(ContactPoint.END)
EContactPoint.UNKNOWN -> default
}
| 4 | Kotlin | 8 | 26 | 5d7013f8d0e0b65418c0256211d39dc28b71d019 | 7,839 | rtron | Apache License 2.0 |
kafkistry-events/src/main/kotlin/com/infobip/kafkistry/kafkastate/ClusterEventListener.kt | infobip | 456,885,171 | false | {"Kotlin": 2590613, "FreeMarker": 803040, "JavaScript": 297269, "CSS": 6804} | package com.infobip.kafkistry.kafkastate
import com.infobip.kafkistry.events.ClusterEvent
import com.infobip.kafkistry.events.EventListener
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
/**
* Use case for this ClusterEventListener is to refresh latest seen configuration state of a cluster.
* This refresh is done after some ClusterEvent is fired, which means that some operation on cluster is performed
* on kafka.
*/
@Component
class ClusterEventListener(
private val kafkaStateProvider: KafkaClustersStateProvider
) : EventListener<ClusterEvent> {
override val log = LoggerFactory.getLogger(ClusterEventListener::class.java)!!
override val eventType = ClusterEvent::class
override fun handleEvent(event: ClusterEvent) {
kafkaStateProvider.refreshClusterState(event.clusterIdentifier)
}
} | 2 | Kotlin | 6 | 42 | 4c8101069c813270d2f3c986b5b9f04dacda4a10 | 863 | kafkistry | Apache License 2.0 |
app/src/main/java/com/arcadone/pokestorie/composables/ModalBottomSheetDialog.kt | ArcaDone | 804,002,329 | false | {"Kotlin": 88352} | package com.arcadone.pokestorie.composables
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SheetState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.arcadone.pokestorie.domain.model.PokemonInfo
import com.arcadone.pokestorie.ui.theme.PokeStorieAppTheme
import com.arcadone.pokestorie.ui.theme.ThemeDS
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ModalBottomSheetDialog(
modifier: Modifier = Modifier,
pokemonInfo: PokemonInfo,
bottomSheetState: SheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false),
onDismissRequest: (Boolean) -> Unit
) {
ModalBottomSheet(
modifier = Modifier.then(modifier),
containerColor = ThemeDS.colors.white,
onDismissRequest = {
onDismissRequest(false)
},
sheetState = bottomSheetState,
content = {
PokemonDetailScreen(pokemonInfo)
}
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun BottomSheetPreview() {
val samplePokemonInfo = PokemonInfo(
name = "Pikachu",
imageUrl = "",
imageSVG = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/25.svg",
types = listOf("Electric"),
description = "Pikachu that can generate powerful electricity have cheek sacs that are extra soft and super stretchy.",
abilities = listOf("Static", "Lightning Rod"),
moves = listOf("Quick Attack", "Thunderbolt"),
baseStats = listOf(),
evolutionChain = listOf(
PokemonInfo.EvolutionInfo("Pichu", null, "Friendship"),
PokemonInfo.EvolutionInfo("Pikachu", null, "Thunder Stone"),
PokemonInfo.EvolutionInfo("Raichu", null, "Thunder Stone")
)
)
PokeStorieAppTheme {
ModalBottomSheetDialog(pokemonInfo = samplePokemonInfo, onDismissRequest = {})
}
} | 0 | Kotlin | 0 | 0 | 37338a5df2deba70ab9a7b9e8bcd39bb797a9086 | 2,139 | pokeStorie | MIT License |
app/src/main/java/com/example/foodapp/ItemActivity.kt | AnkurTambe | 371,776,129 | false | null | package com.example.foodapp
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_item.*
class ItemActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var cat: String? = intent.getStringExtra("cat")
title = "$cat Menu"
setContentView(R.layout.activity_item)
var url = "http://" + UserInfo.ip + "/FoodAppPhp/get_items.php?category=$cat"
var list1 = ArrayList<Item>()
var rq: RequestQueue = Volley.newRequestQueue(this)
var jar = JsonArrayRequest(Request.Method.GET, url, null, { response ->
for (x in 0 until response.length())
list1.add(
Item(
response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getDouble("price"),
response.getJSONObject(x).getString("photo")
)
)
var adp = ItemAdapter(this, list1)
item_rv.layoutManager = LinearLayoutManager(this)
item_rv.adapter = adp
}, { error ->
Toast.makeText(this, error.message, Toast.LENGTH_SHORT).show()
})
rq.add(jar)
}
override fun onBackPressed() {
startActivity(Intent(this, HomeActivity::class.java))
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.tools, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.userinfo) {
Toast.makeText(this, "Your Profile", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, ProfileActivity::class.java))
}
if (item.itemId == R.id.cart) {
Toast.makeText(this, "Your Cart", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, OrderActivity::class.java))
}
return super.onOptionsItemSelected(item)
}
}
| 0 | Kotlin | 0 | 2 | 5354591995605972c441e8ec0ac5b1bc992156cb | 2,511 | FoodApp | MIT License |
app/src/main/java/com/example/jetpack_compose_all_in_one/ui/views/tmdbapi/MovieViewModel.kt | myofficework000 | 626,474,700 | false | {"Kotlin": 1392414} | package com.example.jetpack_compose_all_in_one.ui.views.tmdbapi
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.jetpack_compose_all_in_one.di.TMDBAPI
import com.example.jetpack_compose_all_in_one.features.tmdb_using_flows_paging3.tmdbapi.TmdbResponse
import com.example.jetpack_compose_all_in_one.features.tmdb_using_flows_paging3.tmdbapi.repository.IMovieRepository
import com.example.jetpack_compose_all_in_one.utils.ResultState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MovieViewModel @Inject constructor(
@TMDBAPI val movieRepository: IMovieRepository,
private val ioDispatcher: CoroutineDispatcher
): ViewModel() {
private val _popularMovies: MutableStateFlow<ResultState<TmdbResponse>> = MutableStateFlow(
ResultState.Loading()
)
val popularMovies = _popularMovies.asStateFlow()
var totalPages: Int = 1
private set
var page: Int = 1
private set
fun getPopularMovies(page: Int) {
viewModelScope.launch(ioDispatcher){
_popularMovies.value = ResultState.Loading()
movieRepository.getPopularMovies(page).collect{
_popularMovies.value = it
when (it) {
is ResultState.Success -> {
[email protected] = page
[email protected] = it.body?.totalPages?:1
}
else -> {
[email protected] = 1
[email protected] = 1
}
}
}
}
}
fun getPopularMoviesNext() {
if (page >= totalPages) return
getPopularMovies(page+1)
}
fun getPopularMoviesPrev() {
if (page < 2) return
getPopularMovies(page-1)
}
} | 21 | Kotlin | 22 | 222 | 4de5418608d6917b5c97fac7d868454c424daa26 | 2,083 | Jetpack-Compose-All-in-one-Guide | MIT License |
roots/src/test/java/org/ranapat/roots/api/BaseTest.kt | ranapat | 793,092,228 | false | {"Kotlin": 42563, "Shell": 619} | package org.ranapat.roots.api
import com.fasterxml.jackson.annotation.JsonProperty
import okhttp3.HttpUrl
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.json.JSONObject
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
@RunWith(MockitoJUnitRunner::class)
class BaseTest {
private class ApiResponse(
@JsonProperty("status") val status: String,
@JsonProperty("response") val response: String
)
@Test
fun `shall set headers`() {
val builder: Request.Builder = mock()
Base.setHeaders(builder, mapOf(
"key1" to "value1"
))
verify(builder, times(1)).addHeader(any<String>(), any<String>())
verify(builder, times(1)).addHeader("key1", "value1")
}
@Test
fun `shall not set headers`() {
val builder: Request.Builder = mock()
Base.setHeaders(builder, null)
verify(builder, times(0)).addHeader(any<String>(), any<String>())
}
@Test
fun `shall ensure successful`() {
val response: Response = mock {
on { isSuccessful } doReturn true
}
val result = Base.ensureSuccessful(response)
assertThat(result, `is`(equalTo(response)))
}
@Test(expected = RequestNotSuccessfulException::class)
fun `shall not ensure successful`() {
val responseRequestUrl: HttpUrl = mock {
on { toString() } doReturn "http://localhost"
}
val responseRequest: Request = mock {
on { url } doReturn responseRequestUrl
}
val response: Response = mock {
on { isSuccessful } doReturn false
on { request } doReturn responseRequest
}
Base.ensureSuccessful(response)
}
@Test
fun `shall get from json - case 1`() {
val responseBody: ResponseBody = mock {
on { string() } doAnswer { _ ->
"{\"status\": \"ok\",\"response\": \"good\"}"
}
}
val response: Response = mock {
on { body } doReturn responseBody
}
val result = Base.toTyped(response, ApiResponse::class.java, null)
assertThat(result.status, `is`(equalTo("ok")))
assertThat(result.response, `is`(equalTo("good")))
}
@Test
fun `shall get from json - case 2`() {
val responseBody: ResponseBody = mock {
on { string() } doAnswer { _ ->
"{\"status\": \"ok\",\"response\": \"good\"}"
}
}
val response: Response = mock {
on { body } doReturn responseBody
}
val result = Base.toTyped(
response, ApiResponse::class.java,
object : NormaliseResponse<ApiResponse> {
override fun invoke(response: Response): ApiResponse {
val json = JSONObject(response.body?.string() ?: "")
return ApiResponse(
"wow-" + json.getString("status"),
"wow-" + json.getString("response")
)
}
}
)
assertThat(result.status, `is`(equalTo("wow-ok")))
assertThat(result.response, `is`(equalTo("wow-good")))
}
@Test(expected = RequestMissingBodyException::class)
fun `shall not get from json - case 1`() {
val responseRequestUrl: HttpUrl = mock {
on { toString() } doReturn "http://localhost"
}
val responseRequest: Request = mock {
on { url } doReturn responseRequestUrl
}
val response: Response = mock {
on { body } doReturn null
on { request } doReturn responseRequest
}
Base.toTyped(
response, ApiResponse::class.java,
object : NormaliseResponse<ApiResponse> {
override fun invoke(response: Response): ApiResponse {
val json = JSONObject(response.body?.string() ?: "")
return ApiResponse(
"wow-" + json.getString("status"),
"wow-" + json.getString("response")
)
}
}
)
}
} | 0 | Kotlin | 0 | 0 | 1ee67b15e8220a390333d1806f7eb075066805d5 | 4,588 | roots | The Unlicense |
layout/src/main/java/br/com/zup/nimbus/compose/layout/style/model/Border.kt | ZupIT | 495,447,304 | false | {"Kotlin": 183596, "Shell": 1211} | /*
* Copyright 2023 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.nimbus.compose.layout.style.model
import androidx.compose.ui.graphics.Color
internal data class Border(
val borderWidth: Double?, // default: 0
val borderDashLength: Double?, // default: 1
val borderDashSpacing: Double?, // default: 0
val cornerRadius: Double?, // default: 0
val borderColor: Color?, // default: black
) {
companion object {
val empty = Border(null, null, null, null, null)
}
}
| 2 | Kotlin | 4 | 7 | 59078f425b4e4e806f8c5d883df53a633432f61a | 1,080 | nimbus-layout-compose | Apache License 2.0 |
app/src/test/java/com/example/zeldacountdown/ExampleUnitTest.kt | mathieucans | 577,268,943 | false | null | package com.example.zeldacountdown
import org.junit.Test
import org.junit.Assert.*
import java.time.LocalDate
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun zero_day_left_the_day_of_release() {
val today = LocalDate.parse("2023-05-12")
val daysLeft = ZeldaCountDown(today).daysLeft()
assertEquals(0, daysLeft)
}
@Test
fun one_day_left_the_day_before_of_release() {
val today = LocalDate.parse("2023-05-11")
val daysLeft = ZeldaCountDown(today).daysLeft()
assertEquals(1, daysLeft)
}
@Test
fun `151 days left from 2022 - 12 - 12`() {
val today = LocalDate.parse("2022-12-12")
val daysLeft = ZeldaCountDown(today).daysLeft()
assertEquals(151, daysLeft)
}
} | 0 | Kotlin | 0 | 0 | 73b1af9f04b8617ffb301ebf93c24838d0eed06e | 916 | zelda-count-down | MIT License |
app/src/main/java/ac/id/unikom/codelabs/navigasee/mvvm/login/LoginActivity.kt | mnkadafi | 621,252,553 | false | null | package ac.id.unikom.codelabs.navigasee.mvvm.login
import ac.id.unikom.codelabs.navigasee.R
import ac.id.unikom.codelabs.navigasee.data.source.LoginRepository
import ac.id.unikom.codelabs.navigasee.databinding.ActivityLoginBinding
import ac.id.unikom.codelabs.navigasee.mvvm.dashboard_supir_sobat.DashboardSupirSobatActivity
import ac.id.unikom.codelabs.navigasee.mvvm.my_location.MyLocationActivity
import ac.id.unikom.codelabs.navigasee.utilities.base.BaseActivity
import ac.id.unikom.codelabs.navigasee.utilities.helper.EventObserver
import ac.id.unikom.codelabs.navigasee.utilities.helper.Preferences
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import pub.devrel.easypermissions.EasyPermissions
class LoginActivity : BaseActivity<LoginViewModel, ActivityLoginBinding>(R.layout.activity_login), LoginUserActionListener {
private val TAG by lazy { LoginActivity::class.java.simpleName }
private lateinit var role: String
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
GOOGLE_SIGN_IN_RESULT_CODE -> {
try {
// The Task returned from this call is always completed, no need to attach
// a listener.
val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
val account = task.getResult(ApiException::class.java)
//dari account harus nge post email, nama, role, foto, api_token
if (account != null) {
viewModel.login(account, role)
}
} catch (e: ApiException) {
Log.wtf(TAG, "signInResult:failed code=${e.statusCode}")
}
}
}
}
}
override fun login(role: String) {
this.role = role
val i = viewModel.googleSignInClient.signInIntent
startActivityForResult(i, GOOGLE_SIGN_IN_RESULT_CODE)
}
private val viewModel: LoginViewModel by viewModels {
LoginViewModelFactory(LoginRepository.getInstance())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding.mListener = this
mBinding.mViewModel = viewModel
mParentVM = viewModel
viewModel.preferences = Preferences.getInstance()
if (!EasyPermissions.hasPermissions(this, *BegPermissionModal.PERMISSIONS_MANDATORY)) {
val beg_permission_intent = Intent(this, BegPermissionModal::class.java)
startActivity(beg_permission_intent)
}
}
override fun onCreateObserver(viewModel: LoginViewModel) {
viewModel.apply {
loginSuccess.observe(this@LoginActivity, EventObserver {
if (it) {
if (role.equals("Tunanetra")) {
val i = Intent(this@LoginActivity, MyLocationActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
} else if (role.equals("Supir") || role.equals("Sahabat")) {
val i = Intent(this@LoginActivity, DashboardSupirSobatActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
}
}
})
}
}
override fun setContentData() {
viewModel.googleSignInClient = GoogleSignIn.getClient(this, viewModel.gso)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
override fun setMessageType(): String = MESSAGE_TYPE_TOAST
companion object {
private const val GOOGLE_SIGN_IN_RESULT_CODE = 101
}
}
| 0 | Kotlin | 0 | 0 | 10407007495982148ffbabfb06535926aaf8c32a | 4,579 | Voiye | Apache License 2.0 |
src/main/kotlin/com/robotutor/iot/UtilsConfiguration.kt | IOT-echo-system | 731,163,902 | false | {"Kotlin": 15185, "Shell": 545} | package com.robotutor.iot
import com.mongodb.ConnectionString
import com.robotutor.iot.filters.WebApiFilter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.env.Environment
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory
import org.springframework.web.server.WebFilter
@Configuration
class UtilsConfiguration(private val environment: Environment) {
@Bean
@Primary
fun reactiveMongoTemplate(): ReactiveMongoTemplate {
val uri = environment.getRequiredProperty("spring.data.mongodb.uri")
return ReactiveMongoTemplate(SimpleReactiveMongoDatabaseFactory(ConnectionString(uri)))
}
@Bean
fun customApiFilter(): WebFilter {
return WebApiFilter()
}
}
| 0 | Kotlin | 0 | 0 | 12172c859039913c9844f3ebc6d5fb210fd59ec9 | 946 | web-client-starter | MIT License |
app/src/main/java/org/fossasia/susi/ai/chat/adapters/viewholders/YoutubeVideoViewHolder.kt | ShubhamAvasthi | 161,621,071 | true | {"Kotlin": 465937, "Java": 42275, "Shell": 2946} | package org.fossasia.susi.ai.chat.adapters.viewholders
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.ImageView
import com.squareup.picasso.Picasso
import org.fossasia.susi.ai.R
import org.fossasia.susi.ai.chat.IYoutubeVid
import org.fossasia.susi.ai.chat.YoutubeVid
import org.fossasia.susi.ai.data.model.ChatMessage
import kotterknife.bindView
import timber.log.Timber
class YoutubeVideoViewHolder(view: View, clickListener: MessageViewHolder.ClickListener) : MessageViewHolder(view, clickListener) {
private val playerView: ImageView by bindView(R.id.youtube_view)
private val playBtn: ImageView by bindView(R.id.play_video)
private var model: ChatMessage? = null
private var videoId: String? = null
private var youtubeVid: IYoutubeVid? = null
fun setPlayerView(model: ChatMessage?) {
this.model = model
if (model != null) {
try {
videoId = model.identifier
val imgUrl = "http://img.youtube.com/vi/$videoId/0.jpg"
Picasso.get()
.load(imgUrl)
.placeholder(ContextCompat.getDrawable(itemView.context, R.drawable.ic_susi)!!)
.into(playerView)
} catch (e: Exception) {
Timber.e(e)
}
}
youtubeVid = YoutubeVid(itemView.context)
playBtn.setOnClickListener { youtubeVid!!.playYoutubeVid(videoId!!) }
}
}
| 0 | Kotlin | 0 | 0 | 01d362e1832d928287b02adb165b4b95fa1632d7 | 1,499 | susi_android | Apache License 2.0 |
wow-query/src/main/kotlin/me/ahoo/wow/query/ConditionDsl.kt | Ahoo-Wang | 628,167,080 | false | {"Kotlin": 2115096, "TypeScript": 43338, "Java": 35717, "HTML": 12915, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 413} | /*
* Copyright [2021-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)].
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.ahoo.wow.query
import me.ahoo.wow.api.query.Condition
/**
* ``` kotlin
* condition {
* "field1" eq "value1"
* "field2" ne "value2"
* "filed3" gt 1
* "field4" lt 1
* "field5" gte 1
* "field6" lte 1
* "field7" like "value7"
* "field8" isIn listOf("value8")
* "field9" notIn listOf("value9")
* "field10" between (1 to 2)
* "field11" all listOf("value11")
* "field12" startsWith "value12"
* "field13" elemMatch {
* "field14" eq "value14"
* }
* "field15".isNull()
* "field16".notNull()
* and {
* "field3" eq "value3"
* "field4" eq "value4"
* }
* or {
* "field3" eq "value3"
* "field4" eq "value4"
* }
* }
* ```
*/
class ConditionDsl {
private var conditions: MutableList<Condition> = mutableListOf()
fun condition(condition: Condition) {
conditions.add(condition)
}
fun and(block: ConditionDsl.() -> Unit) {
val nestedDsl = ConditionDsl()
nestedDsl.block()
if (nestedDsl.conditions.isEmpty()) {
return
}
val nestedCondition = Condition.and(nestedDsl.conditions)
condition(nestedCondition)
}
fun or(block: ConditionDsl.() -> Unit) {
val nestedDsl = ConditionDsl()
nestedDsl.block()
if (nestedDsl.conditions.isEmpty()) {
return
}
val nestedCondition = Condition.or(nestedDsl.conditions)
condition(nestedCondition)
}
fun empty() {
condition(Condition.empty())
}
infix fun String.eq(value: Any) {
condition(Condition.eq(this, value))
}
infix fun String.ne(value: Any) {
condition(Condition.ne(this, value))
}
infix fun String.gt(value: Any) {
condition(Condition.gt(this, value))
}
infix fun String.lt(value: Any) {
condition(Condition.lt(this, value))
}
infix fun String.gte(value: Any) {
condition(Condition.gte(this, value))
}
infix fun String.lte(value: Any) {
condition(Condition.lte(this, value))
}
infix fun String.like(value: Any) {
condition(Condition.like(this, value))
}
infix fun String.isIn(value: List<Any>) {
condition(Condition.isIn(this, value))
}
infix fun String.notIn(value: List<Any>) {
condition(Condition.notIn(this, value))
}
infix fun String.between(value: Pair<Any, Any>) {
condition(Condition.between(this, value.first, value.second))
}
infix fun String.all(value: List<Any>) {
condition(Condition.all(this, value))
}
infix fun String.startsWith(value: Any) {
condition(Condition.startsWith(this, value))
}
infix fun String.elemMatch(block: ConditionDsl.() -> Unit) {
val nestedDsl = ConditionDsl()
nestedDsl.block()
condition(Condition.elemMatch(this, nestedDsl.build()))
}
fun String.isNull() {
condition(Condition.isNull(this))
}
fun String.notNull() {
condition(Condition.notNull(this))
}
fun build(): Condition {
if (conditions.isEmpty()) {
return Condition.empty()
}
if (conditions.size == 1) {
return conditions.first()
}
return Condition.and(conditions)
}
}
| 6 | Kotlin | 12 | 119 | bd26ead36aed8be4ab9e5381e15d9a71a968c9fa | 4,016 | Wow | Apache License 2.0 |
app/src/main/java/com/testtube/gstreporter/views/adapters/SalesListAdapter.kt | devinbits | 259,389,063 | false | null | package com.testtube.gstreporter.views.adapters
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.testtube.gstreporter.R
import com.testtube.gstreporter.model.SaleItem
import com.testtube.gstreporter.utils.Common
import com.testtube.gstreporter.utils.Constant
import com.testtube.gstreporter.views.vInterface.RecyclerViewInterface
import com.testtube.gstreporter.views.vInterface.RecyclerViewInterface.Actions
import kotlinx.android.synthetic.main.sale_item.view.*
import java.util.*
class SalesListAdapter(
private var salesList: List<SaleItem>, private var listener: RecyclerViewInterface
) : RecyclerView.Adapter<SalesListAdapter.MyViewHolder>() {
private val rawItems: List<SaleItem> = salesList
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val invoiceNumber: TextView = itemView.invoice_number
private val date: TextView = itemView.date_text
private val partyName: TextView = itemView.party_name
private val invoiceAmount: TextView = itemView.invoiceAmount
private val deleteSaleItem: View = itemView.deleteButton
@SuppressLint("SetTextI18n")
fun bindValues(
saleItem: SaleItem,
listener: RecyclerViewInterface
) {
invoiceNumber.text = saleItem.Bill
date.text = Common.getFormattedDate(Constant.dateFormat, saleItem.Date)
partyName.text = saleItem.Party_Name
invoiceAmount.text = "₹ ${saleItem.Total_Invoice_Value}"
deleteSaleItem.setOnClickListener {
listener.onAction(
adapterPosition,
Actions.Delete,
saleItem.InvoiceId
)
}
itemView.setOnClickListener {
listener.onAction(adapterPosition, Actions.Edit, saleItem)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.sale_item, parent, false)
)
}
override fun getItemCount(): Int {
return salesList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindValues(salesList[position], listener)
}
fun filter(query: String?) {
salesList = if (query?.length!! > 0)
rawItems.filter { saleItem ->
saleItem.Bill.contains(query)
|| Common.getFormattedDate(Constant.dateFormat, saleItem.Date)
.toLowerCase(Locale.getDefault())
.contains(query)
|| saleItem.Party_GSTN.toLowerCase(Locale.getDefault()).contains(query)
|| saleItem.Party_Name.toLowerCase(Locale.getDefault()).contains(query)
|| saleItem.Total_Invoice_Value.toString().contains(query)
}
else rawItems
notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 1 | 8cb6da7114a6f38329c947a905b51912b3bb3d4e | 3,186 | GST-Reporter | MIT License |
kotlin-extensions/src/main/kotlin/kotlinext/js/Function.kt | JetBrains | 93,250,841 | false | null | package kotlinext.js
external interface JsFunction<in C, out O> {
fun call(ctx: C, vararg args: Any?): O
fun apply(ctx: C, args: Array<out Any?>): O
fun bind(ctx: C, vararg args: Any?): JsFunction<Nothing?, O>
val length: Int
}
external interface JsFunction0<out O> : JsFunction<Nothing?, O>
operator fun <O> JsFunction0<O>.invoke() = asDynamic()()
external interface JsFunction1<in I, out O> : JsFunction<Nothing?, O>
operator fun <I, O> JsFunction1<I, O>.invoke(arg: I) =
asDynamic()(arg)
external interface JsFunction2<in I1, in I2, out O> : JsFunction<Nothing?, O>
operator fun <I1, I2, O> JsFunction2<I1, I2, O>.invoke(arg1: I1, arg2: I2) =
asDynamic()(arg1, arg2)
external interface JsFunction3<in I1, in I2, in I3, out O> : JsFunction<Nothing?, O>
operator fun <I1, I2, I3, O> JsFunction3<I1, I2, I3, O>.invoke(arg1: I1, arg2: I2, arg3: I3) =
asDynamic()(arg1, arg2, arg3)
| 2 | Kotlin | 4 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 931 | kotlin-wrappers | Apache License 2.0 |
library/src/main/kotlin/chat/tamtam/botsdk/model/prepared/ChatMember.kt | Namazed | 167,152,441 | false | null | package chat.tamtam.botsdk.model.prepared
import chat.tamtam.botsdk.model.response.Permissions
class ChatMembersList(
val members: List<ChatMember>,
val marker: Long?
)
data class ChatMember(
val userInfo: User,
val lastAccessTime: Long,
val isOwner: Boolean,
val isAdmin: Boolean?,
val joinTime: Long?,
val permissions: List<Permissions>?
) | 2 | Kotlin | 1 | 11 | a3784296550bb96b199f1a466e7bb75fad79dd0f | 376 | TamTamBotApiClientDsl | Apache License 2.0 |
rx-usecases/src/test/java/app/futured/arkitekt/rxusecases/disposables/MaybeDisposablesOwnerTest.kt | futuredapp | 124,508,581 | false | {"Kotlin": 357272, "Java": 1724, "Ruby": 1104} | package app.futured.arkitekt.rxusecases.disposables
import app.futured.arkitekt.rxusecases.usecases.MaybeUseCase
import app.futured.arkitekt.rxusecases.usecases.RxMockitoJUnitRunner
import io.reactivex.Maybe
import io.reactivex.disposables.Disposable
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class MaybeDisposablesOwnerTest : RxMockitoJUnitRunner() {
@Test
fun `test interface can be called properly`() {
val tempMayber = object : MaybeUseCase<String, String>() {
override fun prepare(args: String) = Maybe.just(args)
}
withDisposablesOwner {
tempMayber.execute("Hello") { }
}
withDisposablesOwner {
tempMayber.execute("Hello") {
onSuccess { }
onComplete { }
onError { }
}
}
withDisposablesOwner {
tempMayber.create("").subscribe()
}
}
@Test
fun `success handled properly`() {
val tempMayber = object : MaybeUseCase<String, String>() {
override fun prepare(args: String) = Maybe.just(args)
}
var capturedString = ""
withDisposablesOwner {
tempMayber.execute("Hello") {
onSuccess { capturedString = it }
}
}
assertEquals(capturedString, "Hello")
}
@Test
fun `error handled properly`() {
val tempException = RuntimeException("test exc")
val tempMayber = object : MaybeUseCase<Unit, Unit>() {
override fun prepare(args: Unit) = Maybe.error<Unit>(tempException)
}
var capturedException = Throwable()
withDisposablesOwner {
tempMayber.execute(Unit) {
onError { capturedException = it }
}
}
assertEquals(capturedException, tempException)
}
@Test
fun `previous run disposable should be disposed`() {
val tempMayber = object : MaybeUseCase<String, String>() {
override fun prepare(args: String) = Maybe.never<String>()
}
val disposablesList = mutableListOf<Disposable>()
val runExecute: (MaybeDisposablesOwner.() -> Unit) = {
disposablesList.add(tempMayber.execute("Hello") {})
}
withDisposablesOwner {
runExecute()
runExecute()
}
assertTrue(disposablesList.size == 2)
assertTrue(disposablesList[0].isDisposed)
assertTrue(!disposablesList[1].isDisposed)
}
@Test
fun `previous run disposable not disposed when requested`() {
val tempMayber = object : MaybeUseCase<String, String>() {
override fun prepare(args: String) = Maybe.never<String>()
}
val disposablesList = mutableListOf<Disposable>()
val runExecute: (MaybeDisposablesOwner.() -> Unit) = {
val singler = tempMayber.execute("Hello") {
disposePrevious(false)
}
disposablesList.add(singler)
}
withDisposablesOwner {
runExecute()
runExecute()
}
assertTrue(disposablesList.size == 2)
assertTrue(!disposablesList[0].isDisposed)
assertTrue(!disposablesList[1].isDisposed)
}
@Test
fun `onStart should be called before subscription for execute method`() {
val testMayber = object : MaybeUseCase<Unit, String>() {
override fun prepare(args: Unit) = Maybe.fromCallable { "result" }
}
val events = mutableListOf<String>()
withDisposablesOwner {
testMayber.execute(Unit) {
onStart { events.add("start") }
onSuccess { events.add(it) }
}
}
assertEquals(2, events.size)
assertEquals("start", events[0])
assertEquals("result", events[1])
}
@Test
fun `onStart should be called before subscription for executeStream method`() {
val testMaybe = Maybe.fromCallable { "result" }
val events = mutableListOf<String>()
withDisposablesOwner {
testMaybe.executeStream {
onStart { events.add("start") }
onSuccess { events.add(it) }
}
}
assertEquals(2, events.size)
assertEquals("start", events[0])
assertEquals("result", events[1])
}
@Test
fun `run execute without params`() {
val tempMayber = object : MaybeUseCase<Unit, String>() {
override fun prepare(args: Unit) = Maybe.just("Hello")
}
var capturedString = ""
withDisposablesOwner {
tempMayber.execute {
onSuccess {
capturedString = it
}
}
}
assertEquals(capturedString, "Hello")
}
}
| 10 | Kotlin | 9 | 120 | 2a3d089342a53f4a09e6055a9076275974dc3f04 | 4,897 | arkitekt | MIT License |
helper/src/main/java/digital/klik/helper/network/liveData/ConnectionLiveData.kt | dikawardani24 | 301,948,418 | false | null | package digital.klik.helper.network.liveData
import android.content.Context
import android.content.IntentFilter
import android.net.ConnectivityManager
import androidx.lifecycle.MutableLiveData
import digital.klik.helper.network.broadcast.NetworkBroadcastReceiver
import digital.klik.helper.network.model.ConnectionInfo
class ConnectionLiveData(private val context: Context): MutableLiveData<ConnectionInfo>() {
private val networkReceiver = NetworkBroadcastReceiver(this)
@Suppress("DEPRECATION")
override fun onActive() {
super.onActive()
val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(networkReceiver, filter)
}
override fun onInactive() {
super.onInactive()
context.unregisterReceiver(networkReceiver)
}
} | 0 | Kotlin | 0 | 0 | 0c2f848d649afd18faba125c669d89a50ccb1fe9 | 821 | android-helper | MIT License |
app/src/main/java/pl/dowiez/dowiezplchat/helpers/api/IMyAccountCallback.kt | Kay-Eth | 421,208,413 | false | {"Kotlin": 85776} | package pl.dowiez.dowiezplchat.helpers.api
interface IMyAccountCallback : IApiCallback {
fun onSuccess()
} | 0 | Kotlin | 0 | 0 | 1fe4d323cb7a0b45adc738a5bb2dea64ae2c4010 | 111 | DowiezPlChat | Apache License 2.0 |
app/src/main/java/com/example/appdenunciacliente/framework/di/HiltModule.kt | rubens23 | 488,318,729 | false | {"Kotlin": 112881, "Java": 1165} | package com.example.appdenunciacliente.framework.di
import com.example.appdenunciacliente.framework.data.repositories.FIrebaseStorageRepositoryImpl
import com.example.appdenunciacliente.framework.data.repositories.FirebaseRepository
import com.example.appdenunciacliente.framework.data.repositories.FirebaseRepositoryImpl
import com.example.appdenunciacliente.framework.data.repositories.FirebaseStorageRepository
import com.example.appdenunciacliente.framework.managers.LoginManager
import com.example.appdenunciacliente.framework.managers.LoginManagerImpl
import com.example.appdenunciacliente.framework.utils.CalendarTimeDateUtilitary
import com.example.appdenunciacliente.framework.utils.CalendarTimeDateUtilitaryImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
class HiltModule {
@Provides
fun providesLoginManager(): LoginManager {
return LoginManagerImpl()
}
@Provides
fun providesCalendarTimeDateUtilitary(): CalendarTimeDateUtilitary{
return CalendarTimeDateUtilitaryImpl()
}
@Provides
fun providesRealTimeDatabaseRepository(calendarTimeDateUtilitary: CalendarTimeDateUtilitary): FirebaseRepository {
return FirebaseRepositoryImpl(calendarTimeDateUtilitary)
}
@Provides
fun providesFirebaseStorageRepository(): FirebaseStorageRepository {
return FIrebaseStorageRepositoryImpl()
}
} | 0 | Kotlin | 0 | 0 | c7cfe7e0fe0bf9d5d010442addf8e772414b47af | 1,502 | appDenuncia | Apache License 2.0 |
vscode/src/jsMain/kotlin/vscode/StatusBarAlignment.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | @file:JsModule("vscode")
package vscode
import seskar.js.JsIntValue
import seskar.js.JsVirtual
/**
* Represents the alignment of status bar items.
*/
@JsVirtual
@Suppress("NESTED_CLASS_IN_EXTERNAL_INTERFACE")
sealed external interface StatusBarAlignment {
companion object {
/**
* Aligned to the left side.
*/
@JsIntValue(1)
val Left: StatusBarAlignment
/**
* Aligned to the right side.
*/
@JsIntValue(2)
val Right: StatusBarAlignment
}
}
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 493 | kotlin-externals | MIT License |
mokkery-plugin/src/main/kotlin/dev/mokkery/plugin/MokkeryCompilerPluginRegistrar.kt | lupuuss | 652,785,006 | false | {"Kotlin": 366649} | package dev.mokkery.plugin
import com.google.auto.service.AutoService
import dev.mokkery.plugin.diagnostics.MokkeryDiagnosticRendererFactory
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.diagnostics.rendering.RootDiagnosticRendererFactory
import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrarAdapter
@AutoService(CompilerPluginRegistrar::class)
class MokkeryCompilerPluginRegistrar : CompilerPluginRegistrar() {
override val supportsK2: Boolean = true
override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
IrGenerationExtension.registerExtension(MokkeryIrGenerationExtension(configuration))
FirExtensionRegistrarAdapter.registerExtension(MokkeryFirRegistrar())
RootDiagnosticRendererFactory.registerFactory(MokkeryDiagnosticRendererFactory())
}
}
| 0 | Kotlin | 2 | 61 | e1a965dc38aaa10c369abf1a6e60f5acf2ab339f | 1,016 | Mokkery | Apache License 2.0 |
applications/stream-account-generator-source/src/main/kotlin/com/vmware/financial/open/banking/account/domain/Balance.kt | Tanzu-Solutions-Engineering | 400,235,533 | false | null | package com.vmware.financial.open.banking.account.domain
import java.math.BigDecimal
import java.util.*
data class Balance (
var currency : String = "",
var amount : BigDecimal = BigDecimal.ZERO
)
| 3 | Kotlin | 2 | 2 | 736e3dc0d6d52b908a7c75b0a9a17077d5a6773b | 207 | tanzu-rabbitmq-event-streaming-showcase | Apache License 2.0 |
app/src/main/java/com/artemchep/config/store/util/StoreWriteMapKey.kt | AChep | 139,670,954 | false | {"Kotlin": 36627} | package com.artemchep.config.store.util
import com.artemchep.config.store.StoreWrite
/**
* @author <NAME> */
class StoreWriteMapKey<K>(
private val storeWrite: StoreWrite<K>,
/**
* Map function of the
* keys.
*/
private val map: (K) -> K
) : StoreWrite<K> {
override fun putBoolean(key: K, value: Boolean) = storeWrite.putBoolean(map(key), value)
override fun putString(key: K, value: String) = storeWrite.putString(map(key), value)
override fun putLong(key: K, value: Long) = storeWrite.putLong(map(key), value)
override fun putInt(key: K, value: Int) = storeWrite.putInt(map(key), value)
} | 0 | Kotlin | 1 | 4 | 0dfb2771e0c64f18e17d7f830dac02b90974ce9d | 640 | config | Apache License 2.0 |
src/medium/_24SwapNodesInPairs.kt | ilinqh | 390,190,883 | false | null | package medium
import ListNode
class _24SwapNodesInPairs {
class Solution {
fun swapPairs(head: ListNode?): ListNode? {
if (head?.next == null) {
return head
}
val dummyHead = ListNode(0)
dummyHead.next = head
var temp = dummyHead
while (temp.next != null && temp.next?.next != null) {
val node1 = temp.next!!
val node2 = temp.next!!.next!!
node1.next = node2.next
node2.next = node1
temp.next = node2
temp = node1
}
return dummyHead.next
}
}
// Best
class BestSolution {
fun swapPairs(head: ListNode?): ListNode? {
//终止条件
if (head?.next == null) {
return head
}
val next = head.next
//单次要执行 1head指向交换后的节点 2next指向head
head.next = swapPairs(next?.next)
next?.next = head
return next
}
}
} | 0 | Kotlin | 0 | 0 | 0459c09408f35843bd347ff6d80e3e0e3f2ac15b | 1,067 | AlgorithmsProject | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.