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
platform/new-ui-onboarding/src/com/intellij/platform/ide/newUiOnboarding/NewUiOnboardingStartupActivity.kt
mallowigi
201,728,124
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.platform.ide.newUiOnboarding import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.EDT import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectActivity import com.intellij.platform.ide.newUiOnboarding.NewUiOnboardingUtil.ONBOARDING_PROPOSED_VERSION import com.intellij.ui.ExperimentalUI import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class NewUiOnboardingStartupActivity : ProjectActivity { override suspend fun execute(project: Project) { val propertiesComponent = PropertiesComponent.getInstance() if (NewUiOnboardingUtil.isOnboardingEnabled && propertiesComponent.getBoolean(ExperimentalUI.NEW_UI_SWITCH) && propertiesComponent.getValue(ONBOARDING_PROPOSED_VERSION) == null) { propertiesComponent.unsetValue(ExperimentalUI.NEW_UI_SWITCH) val version = ApplicationInfo.getInstance().build.asStringWithoutProductCodeAndSnapshot() propertiesComponent.setValue(ONBOARDING_PROPOSED_VERSION, version) withContext(Dispatchers.EDT) { NewUiOnboardingService.getInstance(project).showOnboardingDialog() } } } }
1
null
1
1
fc993c389f66042dad1e71451b6c6eb0bc03e4c2
1,368
intellij-community
Apache License 2.0
app/src/main/java/com/carolmusyoka/movieapp/util/extension/RetrofitExt.kt
Breens-Mbaka
438,067,613
false
{"Kotlin": 81005}
package com.carolmusyoka.movieapp.util.extension import com.carolmusyoka.movieapp.data.model.network.APIResponse import retrofit2.Call import retrofit2.Response inline fun <T> Call<T>.request(crossinline onResult: (response: APIResponse<T>) -> Unit) { enqueue(object : retrofit2.Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) { onResult(APIResponse.Success(response)) } else { onResult(APIResponse.Failure(response)) } } override fun onFailure(call: Call<T>, throwable: Throwable) { onResult(APIResponse.Exception(throwable)) } }) }
0
null
2
2
3e752c60ec329025f49c94aae259d80e9a0312a9
715
MovieApp
MIT License
presentation/src/main/java/com/hamza/clean/ui/favorites/FavoritesViewModel.kt
hmz9
612,902,426
false
null
package com.hamza.clean.ui.favorites import androidx.lifecycle.viewModelScope import androidx.paging.* import com.hamza.clean.entities.MovieListItem import com.hamza.clean.mapper.toPresentation import com.hamza.clean.ui.base.BaseViewModel import com.hamza.clean.util.singleSharedFlow import com.hamza.data.util.DispatchersProvider import com.hamza.domain.usecase.AddMovieToFavorite import com.hamza.domain.usecase.CheckFavoriteStatus import com.hamza.domain.usecase.GetFavoriteMovies import com.hamza.domain.usecase.RemoveMovieFromFavorite import com.hamza.domain.util.onSuccess import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.* import javax.inject.Inject /** * @author by <NAME> on 03/09/2023 */ @HiltViewModel class FavoritesViewModel @Inject constructor( private val checkFavoriteStatus: CheckFavoriteStatus, private val addMovieToFavorite: AddMovieToFavorite, private val removeMovieFromFavorite: RemoveMovieFromFavorite, getFavoriteMovies: GetFavoriteMovies, dispatchers: DispatchersProvider ) : BaseViewModel(dispatchers) { data class FavoriteUiState( val isLoading: Boolean = true, val noDataAvailable: Boolean = false, val isFavorite: Boolean = false ) sealed class NavigationState { data class MovieDetails(val movieId: Int) : NavigationState() } val movies: Flow<PagingData<MovieListItem>> = getFavoriteMovies(30).map { it.map { it.toPresentation() as MovieListItem } }.cachedIn(viewModelScope) private val _uiState: MutableStateFlow<FavoriteUiState> = MutableStateFlow(FavoriteUiState()) val uiState = _uiState.asStateFlow() private val _navigationState: MutableSharedFlow<NavigationState> = singleSharedFlow() val navigationState = _navigationState.asSharedFlow() fun onMovieClicked(movieId: Int) = _navigationState.tryEmit(NavigationState.MovieDetails(movieId)) fun onLoadStateUpdate(loadState: CombinedLoadStates, itemCount: Int) { val showLoading = loadState.refresh is LoadState.Loading val showNoData = loadState.append.endOfPaginationReached && itemCount < 1 _uiState.update { it.copy( isLoading = showLoading, noDataAvailable = showNoData ) } } }
0
Kotlin
0
0
a6b10845b07b3bc5a651c77503ab0e50b79ba7ba
2,320
movie-android-clean-mvvm
Apache License 2.0
server/src/main/kotlin/com/darkrockstudios/apps/hammer/projects/ProjectsDatasource.kt
Wavesonics
499,367,913
false
{"Kotlin": 1630287, "Swift": 32452, "CSS": 2064, "Ruby": 1578, "Shell": 361}
package com.darkrockstudios.apps.hammer.projects import com.darkrockstudios.apps.hammer.base.ProjectId import com.darkrockstudios.apps.hammer.project.ProjectDefinition import kotlinx.datetime.Instant interface ProjectsDatasource { suspend fun saveSyncData(userId: Long, data: ProjectsSyncData) suspend fun getProjects(userId: Long): Set<ProjectDefinition> suspend fun findProjectByName(userId: Long, projectName: String): ProjectDefinition? suspend fun getProject(userId: Long, projectId: ProjectId): ProjectDefinition? suspend fun loadSyncData(userId: Long): ProjectsSyncData suspend fun createUserData(userId: Long) suspend fun updateSyncData( userId: Long, action: (ProjectsSyncData) -> ProjectsSyncData ): ProjectsSyncData { val syncData = loadSyncData(userId) val updated = action(syncData) saveSyncData(userId, updated) return updated } companion object { fun defaultUserData(userId: Long): ProjectsSyncData { return ProjectsSyncData( lastSync = Instant.DISTANT_PAST, deletedProjects = emptySet() ) } } }
19
Kotlin
6
128
5eb281596110fe9c315f9c53d5412a93078f870d
1,055
hammer-editor
MIT License
app/src/main/kotlin/com/vsouhrada/kotlin/android/anko/fibo/function/signin/user/presenter/CreateUserPresenter.kt
vsouhrada
77,144,360
false
null
package com.vsouhrada.kotlin.android.anko.fibo.function.signin.user.presenter /** * @author vsouhrada * @since 0.1.0 */ class CreateUserPresenter { }
1
null
6
29
f13d80e93f3075708fc5e3bfd92799b51f12ada2
154
kotlin-anko-demo
Apache License 2.0
src/main/kotlin/com/panther/dboms/utils/SimpleHttpClient.kt
githenry2212
112,705,686
false
null
/** * * @author yangfan * @since 2017/12/29 15:31 * */ package com.panther.dboms.utils import java.net.HttpURLConnection import java.net.URL class SimpleHttpClient { private var reqUrl: String? = null private var connectTimeout: Int = 5000 private var reqMethod: Method = Method.GET private var dataType: ContentType? = null private var reqData: String? = null private val headers = hashMapOf<String, String>() fun url(url: String) { reqUrl = url } fun connectTimeout(timeout: Int) { connectTimeout = timeout } fun method(method: Method) { reqMethod = method } fun data(type: ContentType, data: String) { dataType = type reqData = data } fun header(name: String, value: String) { headers[name] = value } fun execute(): Response { if (reqUrl == null) error("request url must be not null") val conn: HttpURLConnection = URL(reqUrl).openConnection() as HttpURLConnection conn.connectTimeout = connectTimeout conn.requestMethod = reqMethod.name headers.forEach { name, value -> conn.addRequestProperty(name, value) } if (reqData != null) { conn.setRequestProperty("Content-Type", dataType?.value) conn.doOutput = true conn.outputStream.use { it.write(reqData?.toByteArray()) } } val respText = conn.inputStream.use { it.bufferedReader().readLines().joinToString(separator = "\n") } return Response(conn.responseCode, conn.responseMessage, respText) } } enum class ContentType(val value: String) { APPLICATION_FORM_URLENCODED("application/x-www-form-urlencoded"), MULTIPART_FORM_DATA("multipart/form-data"), APPLICATION_JSON("application/json;charset=utf-8"), APPLICATION_OCTET_STREAM("application/octet-stream"), TEXT_HTML("text/html"), TEXT_XML("text/xml") } enum class Method { GET, POST, PUT, DELETE } data class Response(val code: Int, val status: String?, val respText: String?) fun http(init: SimpleHttpClient.() -> Unit): Response { val httpClient = SimpleHttpClient() httpClient.init() return httpClient.execute() }
0
Kotlin
0
0
ab080e089e2d4d3f51e136a1356c3943326fd792
2,206
DBOMS
Apache License 2.0
appengine/ktor/src/main/kotlin/HelloApplication.kt
GoogleCloudPlatform
138,930,896
false
null
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.demo /* ktlint-disable no-wildcard-imports */ import io.ktor.application.* import io.ktor.features.* import io.ktor.html.* import io.ktor.routing.* import kotlinx.html.* // Entry Point of the application as defined in resources/application.conf. // @see https://ktor.io/servers/configuration.html#hocon-file fun Application.main() { // This adds Date and Server headers to each response, and allows custom additional headers install(DefaultHeaders) // This uses use the logger to log every call (request/response) install(CallLogging) routing { // Here we use a DSL for building HTML on the route "/" // @see https://github.com/Kotlin/kotlinx.html get("/") { call.respondHtml { head { title { +"Ktor on Google App Engine Standard" } } body { p { +"Hello there! This is Ktor running on Google Appengine Standard" } } } } get("/demo") { call.respondHtml { head { title { +"Ktor on Google App Engine Standard" } } body { p { +"It's another route!" } } } } } }
35
Kotlin
82
229
b7184e6ddd991eb4ac3a91f76dde0b007646cf62
1,988
kotlin-samples
Apache License 2.0
app/src/main/java/at/shockbytes/dante/storage/reader/CsvReader.kt
shockbytes
92,944,830
false
{"Kotlin": 790848}
package at.shockbytes.dante.storage.reader import io.reactivex.Single import java.io.File class CsvReader : FileReader { private val csvRegex = (",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)".toRegex()) override fun readFile(file: File): Sequence<String> { return file.useLines { it } } override fun readWholeFile(file: File): Single<String> { return Single.fromCallable { file.readLines().joinToString("\n") } } fun readCsvContent(content: String): Single<Sequence<List<String>>> { return Single.fromCallable { content .split("\n") .asSequence() .map { line -> line .split(csvRegex) .map { it.trim() } } } } }
21
Kotlin
7
73
626fd7c12691be646fcd7b55a9c46539073af675
840
Dante
Apache License 2.0
src/main/kotlin/ComparatorExample.kt
raghunandankavi2010
352,541,625
false
null
fun main() { val list = ArrayList<Medicine>() list.add(Medicine("BloodPressure", 10)) list.add(Medicine("BloodPressure", 1200)) list.add(Medicine("Diabetes", 20)) list.add(Medicine("Diabetes", 100)) list.add(Medicine("Sugar", 105)) list.add(Medicine("Sugar", 120)) list.add(Medicine("Sugar", 100)) val sortedList = list.sortedWith(compareBy<Medicine> { it.category }).filter { it.price == 100} for (obj in sortedList) { println(obj) } } data class Medicine(val category: String, val price: Int) { override fun toString(): String { return "$category $price" } }
0
Kotlin
0
0
e6221981e76a24570534b5e877ed756348fa712e
634
KotlinLearning
Apache License 2.0
app/src/main/java/dev/notoriouscoder4/newstimes/ui/components/FilterItem.kt
notoriouscoder4
744,951,028
false
{"Kotlin": 97046}
package dev.notoriouscoder4.newstimes.ui.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import dev.notoriouscoder4.newstimes.R import dev.notoriouscoder4.newstimes.data.database.entity.Source import dev.notoriouscoder4.newstimes.data.model.Country import dev.notoriouscoder4.newstimes.data.model.Language @Composable fun CountryItem( country: Country, onItemClick: (Country) -> Unit ) { Card(modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(4.dp) .clickable { onItemClick(country) } ) { Box( modifier = Modifier .fillMaxWidth() .height(40.dp), contentAlignment = Alignment.Center ) { Text(text = country.name) } } } @Composable fun LanguageItem( language: Language, onItemClick: (Language) -> Unit ) { Card(modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(4.dp) .clickable { onItemClick(language) }) { Box( modifier = Modifier .fillMaxWidth() .height(40.dp), contentAlignment = Alignment.Center ) { Text(text = language.name) } } } @Composable fun SourceItem( source: Source, onItemClick: (Source) -> Unit ) { Card(modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(4.dp) .clickable { onItemClick(source) }) { Box( modifier = Modifier .fillMaxWidth() .height(40.dp), contentAlignment = Alignment.Center ) { Text(text = source.name ?: stringResource(R.string.unknown)) } } }
0
Kotlin
0
0
e3cc4cf05d31ea9154a093d6a4c302ae75001bc2
2,354
NewsTimes
MIT License
app/src/main/java/com/ssimagepicker/app/ui/MainActivity.kt
SimformSolutionsPvtLtd
346,382,920
false
{"Kotlin": 103454}
package com.ssimagepicker.app.ui import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import com.app.imagepickerlibrary.ImagePicker import com.app.imagepickerlibrary.ImagePicker.Companion.registerImagePicker import com.app.imagepickerlibrary.listener.ImagePickerResultListener import com.app.imagepickerlibrary.model.ImageProvider import com.app.imagepickerlibrary.model.PickerType import com.app.imagepickerlibrary.ui.bottomsheet.SSPickerOptionsBottomSheet import com.ssimagepicker.app.PickerOptions import com.ssimagepicker.app.R import com.ssimagepicker.app.databinding.FragmentDemoBinding import com.ssimagepicker.app.isAtLeast11 class DemoFragment : Fragment(), View.OnClickListener, SSPickerOptionsBottomSheet.ImagePickerClickListener, ImagePickerResultListener, PickerOptionsBottomSheet.PickerOptionsListener { private lateinit var binding: FragmentDemoBinding companion object { private const val IMAGE_LIST = "IMAGE_LIST" } private val imagePicker: ImagePicker by lazy { registerImagePicker(this) } private val imageList = mutableListOf<Uri>() private val imageDataAdapter = ImageDataAdapter(imageList) private var pickerOptions = PickerOptions.default() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_demo, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.clickHandler = this setUI(savedInstanceState) } private fun setUI(savedInstanceState: Bundle?) { binding.imageRecyclerView.adapter = imageDataAdapter if (savedInstanceState != null && savedInstanceState.containsKey(IMAGE_LIST)) { val uriList: List<Uri> = savedInstanceState.getParcelableArrayList(IMAGE_LIST) ?: listOf() updateImageList(uriList) } } override fun onClick(v: View) { when (v.id) { R.id.options_button -> { openPickerOptions() } R.id.open_picker_button -> { openImagePicker() } R.id.open_sheet_button -> { val fragment = SSPickerOptionsBottomSheet.newInstance(R.style.CustomPickerBottomSheet) fragment.show(childFragmentManager, SSPickerOptionsBottomSheet.BOTTOM_SHEET_TAG) } } } /** * This method receives the selected picker type option from the bottom sheet. */ override fun onImageProvider(provider: ImageProvider) { when (provider) { ImageProvider.GALLERY -> { pickerOptions = pickerOptions.copy(pickerType = PickerType.GALLERY) openImagePicker() } ImageProvider.CAMERA -> { pickerOptions = pickerOptions.copy(pickerType = PickerType.CAMERA) openImagePicker() } ImageProvider.NONE -> { //User has pressed cancel show anything or just leave it blank. } } } /** * Opens the options for picker. The picker option is bottom sheet with many input parameters. */ private fun openPickerOptions() { val fragment = PickerOptionsBottomSheet.newInstance(pickerOptions) fragment.setClickListener(this) fragment.show(childFragmentManager, PickerOptionsBottomSheet.BOTTOM_SHEET_TAG) } /** * Once the picker options are selected in bottom sheet * we will receive the latest picker options in this method */ override fun onPickerOptions(pickerOptions: PickerOptions) { this.pickerOptions = pickerOptions openImagePicker() } /** * Open the image picker according to picker type and the ui options. * The new system picker is only available for Android 13+. */ private fun openImagePicker() { imagePicker .title("My Picker") .multipleSelection(pickerOptions.allowMultipleSelection, pickerOptions.maxPickCount) .showCountInToolBar(pickerOptions.showCountInToolBar) .showFolder(pickerOptions.showFolders) .cameraIcon(pickerOptions.showCameraIconInGallery) .doneIcon(pickerOptions.isDoneIcon) .allowCropping(pickerOptions.openCropOptions) .compressImage(pickerOptions.compressImage) .maxImageSize(pickerOptions.maxPickSizeMB) .extension(pickerOptions.pickExtension) if (isAtLeast11()) { imagePicker.systemPicker(pickerOptions.openSystemPicker) } imagePicker.open(pickerOptions.pickerType) } /** * Single Selection and the image captured from camera will be received in this method. */ override fun onImagePick(uri: Uri?) { uri?.let { updateImageList(listOf(it)) } } /** * Multiple Selection uris will be received in this method */ override fun onMultiImagePick(uris: List<Uri>?) { if (!uris.isNullOrEmpty()) { updateImageList(uris) } } private fun updateImageList(list: List<Uri>) { imageList.clear() imageList.addAll(list) imageDataAdapter.notifyDataSetChanged() } override fun onSaveInstanceState(outState: Bundle) { outState.putParcelableArrayList(IMAGE_LIST, ArrayList(imageList)) super.onSaveInstanceState(outState) } }
3
Kotlin
35
279
58308d1a9cda7e8880883992df28bc6cfb11f000
5,807
SSImagePicker
Apache License 2.0
app/src/main/java/com/miniai/facematch/FrameInferface.kt
MiniAiLive
734,916,598
false
{"Kotlin": 24354, "Java": 22135}
package com.miniai.facematch; import android.graphics.Bitmap interface FrameInferface { fun onRegister() }
0
Kotlin
69
36
84bfb7a1a7fd9081ec7b105eefb75fd0537d77e7
113
FaceMatching-Android
Open LDAP Public License v2.3
core/network/src/main/kotlin/org/michaelbel/movies/network/model/Keyword.kt
michaelbel
115,437,864
false
null
package org.michaelbel.movies.network.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Keyword( @SerialName("id") val id: Long, @SerialName("name") val name: String? )
4
Kotlin
21
81
00b1cd807a4e7c894b0792ebb668e4cbcedc5605
241
movies
Apache License 2.0
app/src/main/java/com/nora/devbyte/ui/details/VideoDetailsFragment.kt
NoraHeithur
499,880,188
false
{"Kotlin": 33554}
package com.nora.devbyte.ui.details import android.content.ActivityNotFoundException import android.content.Intent import android.content.Intent.* import android.graphics.Color import android.os.Build import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.navArgs import com.google.android.material.transition.MaterialContainerTransform import com.nora.devbyte.R import com.nora.devbyte.databinding.FragmentVideoDetailsBinding import com.nora.devbyte.ui.utils.themeColor import org.koin.androidx.viewmodel.ext.android.viewModel class VideoDetailsFragment : Fragment(), VideoListener { private val viewModel: VideoDetailsViewModel by viewModel() private val args: VideoDetailsFragmentArgs by navArgs() private val binding: FragmentVideoDetailsBinding by lazy { FragmentVideoDetailsBinding.inflate(layoutInflater) } private fun bindingView() { binding.lifecycleOwner = viewLifecycleOwner binding.viewmodel = viewModel binding.listener = this } private fun bindingData() { viewModel.getVideo(args.video) } private fun bindingIntentAction(url: String) { var intent = Intent() try { val packageManager = requireContext().packageManager ?: return if (intent.resolveActivity(packageManager) != null) { intent = Intent( ACTION_VIEW, viewModel.video.value!!.getYoutubeSchemeUri(url) ).apply { addCategory(CATEGORY_BROWSABLE) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER } } } startActivity(intent) } catch (e: ActivityNotFoundException) { intent = Intent(ACTION_VIEW, viewModel.video.value!!.getUri(url)) startActivity(intent) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { sharedElementEnterTransition = MaterialContainerTransform().apply { drawingViewId = R.id.main_nav_host duration = resources.getInteger(R.integer.motion_duration_normal).toLong() scrimColor = Color.TRANSPARENT setAllContainerColors(requireContext().themeColor(com.google.android.material.R.attr.colorSurface)) } bindingView() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bindingData() } override fun onButtonWatchOnYoutubeClicked(url: String) { bindingIntentAction(url) } }
0
Kotlin
0
0
c5d036ab6589be5f9cd2de24e23ea293d2ed3c79
2,934
DevByte-with-Paging
MIT License
app-macrosoft/src/main/kotlin/dev/bogdanzurac/marp/app/macrosoft/MacrosoftAppNavigator.kt
bogdanzurac
606,411,511
false
null
package dev.bogdanzurac.marp.app.macrosoft import dev.bogdanzurac.marp.core.logger import dev.bogdanzurac.marp.core.navigation.AppNavigator import dev.bogdanzurac.marp.core.navigation.FeatureNavigator import dev.bogdanzurac.marp.feature.crypto.ui.Crypto import dev.bogdanzurac.marp.feature.crypto.ui.CryptoNavigator import dev.bogdanzurac.marp.feature.news.ui.News import dev.bogdanzurac.marp.feature.news.ui.NewsNavigator import dev.bogdanzurac.marp.feature.weather.ui.Weather import dev.bogdanzurac.marp.feature.weather.ui.WeatherNavigator import org.koin.core.annotation.Single @Single class MacrosoftAppNavigator( private val cryptoNavigator: CryptoNavigator, private val newsNavigator: NewsNavigator, private val weatherNavigator: WeatherNavigator, ) : AppNavigator() { override fun getFeatureNavigatorForRoute(route: String): FeatureNavigator { logger.d("Getting FeatureNavigator for route: $route") return when (route) { Crypto.path -> cryptoNavigator News.path -> newsNavigator Weather.path -> weatherNavigator else -> throw IllegalStateException("Current route '$route' is not associated with a FeatureNavigator") } } }
0
Kotlin
0
2
1b8859f92a7c20837817b0abf897530bb691caba
1,223
marp-app-client-android
Apache License 2.0
src/main/kotlin/lmr/rcd/util/Valued.kt
halgorithm
256,116,377
false
null
package lmr.rcd.util interface Valued<T> { val value: T }
0
Kotlin
0
0
195af71e8794a0867598675dbacb39eae7f20bc5
63
lmr-rcd-kt
Boost Software License 1.0
shared/src/commonMain/kotlin/data/api/GifApiRetriever.kt
ntietje1
672,375,249
false
{"Kotlin": 482135, "Swift": 839}
package data.api import io.ktor.client.HttpClient import io.ktor.client.plugins.ClientRequestException import io.ktor.client.request.get import io.ktor.client.request.headers import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.bodyAsText import io.ktor.http.HttpStatusCode import kotlinx.coroutines.runBlocking import kotlinx.io.IOException import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject class ListResultOrError<T>(val result: List<T>? = listOf(), val error: Exception? = null) enum class GifError { SEARCH_FAILED, NEXT_SEARCH_FAILED } class GifApiRetriever( private val client: HttpClient = HttpClient() ) { private val json = Json { ignoreUnknownKeys = true } private var next: String? = null private var lastQuery: String? = null private fun clearNext() { next = null lastQuery = null } suspend fun searchGifs(query: String, limit: Int): ListResultOrError<MediaFormat> { clearNext() val gifResponse = getSearchResults(query, limit) if (gifResponse == null) { println("Error getting gifs. returning empty list") return ListResultOrError(error = Exception(GifError.SEARCH_FAILED.name)) } next = gifResponse.next lastQuery = query return ListResultOrError(gifResponse.results.map { it.formats }) } suspend fun getNextGifs(limit: Int): ListResultOrError<MediaFormat> { if (next == null || lastQuery == null) { throw Exception("Attempted to get next gifs without a previous search") } val gifResponse = getSearchResults(lastQuery!!, limit) if (gifResponse == null) { println("Error getting gifs. returning empty list") return ListResultOrError(error = Exception(GifError.NEXT_SEARCH_FAILED.name)) } next = gifResponse.next return ListResultOrError(gifResponse.results.map { it.formats }) } /** * Get Search Result GIFs */ private suspend fun getSearchResults(query: String, limit: Int): GifResponse? { try { val url = "https://tenor.googleapis.com/v2/search?q=${query}&key=${API_KEY}&limit=${limit}" + if (next != null) "&pos=$next" else "" println("URL: $url") val response = get(url) if (response == null) { println("Error getting gifs. returning null") return null } val gifResponse = json.decodeFromString<GifResponse>(response.toString()) return gifResponse } catch (err: Exception) { err.printStackTrace() return null } } /** * Construct and run a GET request */ private suspend fun get(url: String): JsonObject? { try { val response: HttpResponse = client.get(url) { headers { append("Content-Type", "application/json; charSet=UTF-8") append("Accept", "application/json") } } // Handle failure val statusCode = response.status.value if (statusCode != HttpStatusCode.OK.value && statusCode != HttpStatusCode.Created.value) { val responseText = response.bodyAsText() throw ClientRequestException(response, responseText) } // Parse response val content = response.bodyAsText() if (content.isBlank()) { throw IOException("Empty response") } val jsonElement: JsonElement = json.parseToJsonElement(content) return jsonElement.jsonObject } catch (err: Exception) { err.printStackTrace() return null } } companion object { private val API_KEY by lazy { runBlocking { CredentialManager().fetchTenorApiKey() } } } } @Serializable data class GifResponse( val next: String, val results: List<GifObject> ) @Serializable data class GifObject( // val created: Float, // val hasaudio: Boolean, // val id: String, @SerialName("media_formats") val formats: MediaFormat, // val tags: List<String>, // val title: String, val itemurl: String, // val hascaption: Boolean? = null, val url: String ) @Serializable data class MediaFormat( val gif: MediaObject? = null, val mediumGif: MediaObject? = null, val tinyGif: MediaObject? = null, val nanoGif: MediaObject? = null, val mp4: MediaObject? = null, val loopedMp4: MediaObject? = null, val tinyMp4: MediaObject? = null, val nanoMp4: MediaObject? = null, val webm: MediaObject? = null, val tinyWebm: MediaObject? = null, val nanoWebm: MediaObject? = null ) { fun getNormalGif(): MediaObject { return gif ?: mediumGif ?: tinyGif ?: nanoGif ?: throw Exception("No gif found") } fun getPreviewGif(): MediaObject { return nanoGif ?: tinyGif ?: mediumGif ?: gif ?: throw Exception("No preview found") } } @Serializable data class MediaObject( val preview: String, val url: String, val dims: List<Int>, val size: Int, )
7
Kotlin
0
1
9ad81c871b39e1ef8ded47edc50ae0fddbc4c85e
5,462
MTG_Life_Total_App
Apache License 2.0
shared/src/androidMain/kotlin/com/rvcoding/imhere/data/local/DataStoreFactory.android.kt
revs87
842,125,970
false
{"Kotlin": 137015, "Swift": 621, "HTML": 332, "CSS": 102}
package com.rvcoding.imhere.data.local import com.rvcoding.imhere.applicationContext import com.rvcoding.imhere.domain.data.local.dataStoreFileName actual fun getDataStoreFilePath(): String = applicationContext.filesDir.resolve(dataStoreFileName).absolutePath
0
Kotlin
0
0
3276a4a97d5da205251e2bc4c4bb3f37d27ae773
262
imhere-cmp
Apache License 2.0
app/src/main/kotlin/com/akinci/chatter/data/repository/MessageRepository.kt
AttilaAKINCI
353,730,900
false
{"Kotlin": 193030}
package com.akinci.chatter.data.repository import com.akinci.chatter.core.utils.DateTimeFormat import com.akinci.chatter.data.mapper.toDomain import com.akinci.chatter.data.room.message.MessageDao import com.akinci.chatter.data.room.message.MessageEntity import kotlinx.coroutines.flow.map import timber.log.Timber import java.time.ZonedDateTime import javax.inject.Inject class MessageRepository @Inject constructor( private val messageDao: MessageDao, ) { fun get(chatSessionId: Long) = messageDao.get(chatSessionId) .map { messages -> messages.map { it.toDomain() } } suspend fun save( chatSessionId: Long, primaryUserId: Long, text: String, ) = runCatching { messageDao.save( MessageEntity( chatSessionId = chatSessionId, senderUserId = primaryUserId, text = text, date = DateTimeFormat.STORE.format(ZonedDateTime.now()).orEmpty(), ) ) }.onFailure { Timber.e(it, "Message couldn't be send. Text: $text - Owner: $primaryUserId") } }
0
Kotlin
0
0
22fcbbc4b5ec2f98094ea89d52d2e9baa05ca7e6
1,107
ChatterAI
Apache License 2.0
app/src/main/java/com/ranhaveshush/mdb/ui/fragment/HomeFragment.kt
ranhaveshush
185,007,146
false
null
package com.ranhaveshush.mdb.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.ranhaveshush.mdb.R import com.ranhaveshush.mdb.databinding.FragmentHomeBinding import com.ranhaveshush.mdb.ui.adapter.MoviesAdapter import com.ranhaveshush.mdb.ui.recyclerview.MarginLinearItemDecoration import com.ranhaveshush.mdb.viewmodel.HomeViewModel class HomeFragment : Fragment(R.layout.fragment_home) { private val viewModel: HomeViewModel by viewModels { appComponent.homeViewModelFactory() } private lateinit var binding: FragmentHomeBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeBinding.inflate(layoutInflater) binding.lifecycleOwner = viewLifecycleOwner binding.viewmodel = viewModel binding.popularMoviesDirections = HomeFragmentDirections.actionHomeFragmentToPopularMoviesFragment() binding.topRatedMoviesDirections = HomeFragmentDirections.actionHomeFragmentToTopRatedMoviesFragment() binding.upcomingMoviesDirections = HomeFragmentDirections.actionHomeFragmentToUpcomingMoviesFragment() return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val movieItemMargin = resources.getDimension(R.dimen.item_movie_margin).toInt() binding.popularMovies.recyclerViewMovies.adapter = MoviesAdapter() binding.popularMovies.recyclerViewMovies.addItemDecoration( MarginLinearItemDecoration( movieItemMargin ) ) binding.topRatedMovies.recyclerViewMovies.adapter = MoviesAdapter() binding.topRatedMovies.recyclerViewMovies.addItemDecoration( MarginLinearItemDecoration( movieItemMargin ) ) binding.upcomingMovies.recyclerViewMovies.adapter = MoviesAdapter() binding.upcomingMovies.recyclerViewMovies.addItemDecoration( MarginLinearItemDecoration( movieItemMargin ) ) } }
0
Kotlin
0
0
bb6941ea83aa2ee629defece08771cb94c96d779
2,374
mdb
Apache License 2.0
glata/src/main/java/com/yalantis/glata/shader/FloatingAlphaColorShader.kt
Yalantis
165,843,008
false
null
package com.yalantis.glata.shader import android.opengl.GLES20 import com.yalantis.glata.core.RendererParams import com.yalantis.glata.core.model.ModelParams import com.yalantis.glata.core.scene.SceneParams import com.yalantis.glata.core.shader.BaseShader import com.yalantis.glata.util.Utils class FloatingAlphaColorShader( val sourceAlpha: SourceAlpha = SourceAlpha.SRC_ALPHA, val destination: Destination = Destination.ONLY_ALPHA) : BaseShader() { private var uAlphaHandle: Int = 0 override fun initShaders() { attributes = arrayOf("a_Position", "a_TexCoordinate") vertexShader = "uniform mat4 u_MVPMatrix; \n" + // A constant representing the combined model/view/projection matrix. "attribute vec4 a_Position; \n" + // Per-vertex position information we will pass in. "attribute vec4 a_Color; \n" + // Per-vertex color information we will pass in. "varying vec4 v_Color; \n" + // This will be passed into the fragment shader. "void main() { \n" + " v_Color = a_Color; \n" + // Pass through the texture coordinate. " gl_Position = u_MVPMatrix * a_Position; \n" + "} \n" fragmentShader = "precision mediump float; \n" + "uniform float u_Alpha; \n" + // new alpha value "varying vec4 v_Color; \n" + // This is the color from the vertex shader interpolated across the triangle per fragment "void main() { \n" + " gl_FragColor = v_Color; \n" + " ${destination.value} *= ${sourceAlpha.value}; \n" + "}" } override fun setShaderParams(rp: RendererParams, mp: ModelParams, sp: SceneParams) { setMvpMatrixHandle(mp, sp) mp.shaderVars?.let { setAlpha(it.alpha) } } fun setAlpha(alpha: Float) { GLES20.glUniform1f(uAlphaHandle, Utils.clamp(0f, 1f, alpha)) } override fun setVariableHandles() { uMvpMatrixHandle = GLES20.glGetUniformLocation(programHandle, "u_MVPMatrix") uAlphaHandle = GLES20.glGetUniformLocation(programHandle, "u_Alpha") aPositionHandle = GLES20.glGetAttribLocation(programHandle, "a_Position") aColorHandle = GLES20.glGetAttribLocation(programHandle, "a_Color") } enum class SourceAlpha(val value: String) { SRC_ALPHA("u_Alpha"), ONE_MINUS_SRC_ALPHA("1.0 - u_Alpha") } enum class Destination(val value: String) { ONLY_ALPHA("gl_FragColor.a"), FULL_COLOR("gl_FragColor") } }
1
Kotlin
13
83
f022e7348afb381ac567ff6954164ef47438edf1
2,632
GLata
The Unlicense
base/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/NamespaceDetector.kt
qiangxu1996
301,210,525
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint.checks import com.android.SdkConstants.ANDROID_URI import com.android.SdkConstants.APP_PREFIX import com.android.SdkConstants.AUTO_URI import com.android.SdkConstants.TOOLS_PREFIX import com.android.SdkConstants.TOOLS_URI import com.android.SdkConstants.URI_PREFIX import com.android.SdkConstants.XMLNS_PREFIX import com.android.ide.common.rendering.api.ResourceNamespace import com.android.resources.ResourceFolderType import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.LintFix import com.android.tools.lint.detector.api.ResourceXmlDetector import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.XmlContext import com.android.tools.lint.detector.api.isEditableTo import com.android.utils.XmlUtils.getFirstSubTag import com.android.utils.XmlUtils.getNextTag import org.w3c.dom.Attr import org.w3c.dom.Document import org.w3c.dom.Element import java.util.HashMap /** Checks for various issues related to XML namespaces */ /** Constructs a new [NamespaceDetector] */ class NamespaceDetector : ResourceXmlDetector() { private var unusedNamespaces: MutableMap<String, Attr>? = null override fun visitDocument(context: XmlContext, document: Document) { var haveCustomNamespace = false val root = document.documentElement val attributes = root.attributes val n = attributes.length for (i in 0 until n) { val item = attributes.item(i) val prefix = item.nodeName if (prefix.startsWith(XMLNS_PREFIX)) { val value = item.nodeValue if (value != ANDROID_URI) { val attribute = item as Attr if (value.startsWith(URI_PREFIX)) { haveCustomNamespace = true val namespaces = unusedNamespaces ?: run { val new = HashMap<String, Attr>() unusedNamespaces = new new } namespaces[prefix.substring(XMLNS_PREFIX.length)] = attribute } else if (value.startsWith("urn:")) { continue } else if (!value.startsWith("http://")) { if (context.isEnabled(TYPO) && // In XML there can be random XML documents from users // with arbitrary schemas; let them use https if they want context.resourceFolderType != ResourceFolderType.XML ) { var fix: LintFix? = null if (value.startsWith("https://")) { fix = LintFix.create() .replace() .text("https") .with("http") .name("Replace with http://${value.substring(8)}") .build() } context.report( TYPO, attribute, context.getValueLocation(attribute), "Suspicious namespace: should start with `http://`", fix ) } continue } else if (value != AUTO_URI && value.contains("auto") && value.startsWith("http://schemas.android.com/") ) { context.report( RES_AUTO, attribute, context.getValueLocation(attribute), "Suspicious namespace: Did you mean `$AUTO_URI`?" ) } else if (value == TOOLS_URI && (prefix == XMLNS_ANDROID || prefix.endsWith( APP_PREFIX ) && prefix == XMLNS_PREFIX + APP_PREFIX) ) { context.report( TYPO, attribute, context.getValueLocation(attribute), "Suspicious namespace and prefix combination" ) } if (!context.isEnabled(TYPO)) { continue } val name = attribute.name if (name != XMLNS_ANDROID && name != XMLNS_A) { // See if it looks like a typo val resIndex = value.indexOf("/res/") if (resIndex != -1 && value.length + 5 > URI_PREFIX.length) { val urlPrefix = value.substring(0, resIndex + 5) if (urlPrefix != URI_PREFIX && isEditableTo(URI_PREFIX, urlPrefix, 3)) { val correctUri = URI_PREFIX + value.substring(resIndex + 5) context.report( TYPO, attribute, context.getValueLocation(attribute), "Possible typo in URL: was `\"$value\"`, should " + "probably be `\"$correctUri\"`" ) } } continue } if (name == XMLNS_A) { // For the "android" prefix we always assume that the namespace prefix // should be our expected prefix, but for the "a" prefix we make sure // that it's at least "close"; if you're bound it to something completely // different, don't complain. if (!isEditableTo(ANDROID_URI, value, 4)) { continue } } if (value.equals(ANDROID_URI, ignoreCase = true)) { context.report( TYPO, attribute, context.getValueLocation(attribute), "URI is case sensitive: was `\"$value\"`, expected `\"$ANDROID_URI\"`" ) } else { context.report( TYPO, attribute, context.getValueLocation(attribute), "Unexpected namespace URI bound to the `\"android\"` " + "prefix, was `$value`, expected `$ANDROID_URI`" ) } } else if (prefix != XMLNS_ANDROID && (prefix.endsWith(TOOLS_PREFIX) && prefix == XMLNS_PREFIX + TOOLS_PREFIX || prefix.endsWith( APP_PREFIX ) && prefix == XMLNS_PREFIX + APP_PREFIX) ) { val attribute = item as Attr context.report( TYPO, attribute, context.getValueLocation(attribute), "Suspicious namespace and prefix combination" ) } } } if (haveCustomNamespace) { val project = context.project val checkCustomAttrs = project.resourceNamespace == ResourceNamespace.RES_AUTO && (context.isEnabled( CUSTOM_VIEW ) && project.isLibrary || context.isEnabled(RES_AUTO) && project.isGradleProject) if (checkCustomAttrs) { checkCustomNamespace(context, root) } val checkUnused = context.isEnabled(UNUSED) if (checkUnused) { checkUnused(root) val namespaces = unusedNamespaces if (namespaces != null && !namespaces.isEmpty()) { for ((prefix, attribute) in namespaces) { context.report( UNUSED, attribute, context.getLocation(attribute), "Unused namespace `$prefix`" ) } } } } if (context.isEnabled(REDUNDANT)) { var child = getFirstSubTag(root) while (child != null) { checkRedundant(context, child) child = getNextTag(child) } } } private fun checkUnused(element: Element) { val attributes = element.attributes val n = attributes.length for (i in 0 until n) { val attribute = attributes.item(i) as Attr val prefix = attribute.prefix if (prefix != null) { unusedNamespaces?.remove(prefix) } } var child = getFirstSubTag(element) while (child != null) { checkUnused(child) child = getNextTag(child) } } private fun checkRedundant(context: XmlContext, element: Element) { // This method will not be called on the document element val attributes = element.attributes val n = attributes.length for (i in 0 until n) { val attribute = attributes.item(i) as Attr val name = attribute.name if (name.startsWith(XMLNS_PREFIX)) { // See if this attribute is already set on the document element val root = element.ownerDocument.documentElement val redundant = root.getAttribute(name) == attribute.value if (redundant) { val fix = fix().name("Delete namespace").set().remove(name).build() context.report( REDUNDANT, attribute, context.getLocation(attribute), "This namespace declaration is redundant", fix ) } } } var child = getFirstSubTag(element) while (child != null) { checkRedundant(context, child) child = getNextTag(child) } } private fun checkCustomNamespace(context: XmlContext, element: Element) { val attributes = element.attributes val n = attributes.length for (i in 0 until n) { val attribute = attributes.item(i) as Attr if (attribute.name.startsWith(XMLNS_PREFIX)) { val uri = attribute.value if (uri != null && !uri.isEmpty() && uri.startsWith(URI_PREFIX) && uri != ANDROID_URI ) { if (context.project.isGradleProject) { context.report( RES_AUTO, attribute, context.getValueLocation(attribute), "In Gradle projects, always use `$AUTO_URI` for custom " + "attributes" ) } else { context.report( CUSTOM_VIEW, attribute, context.getValueLocation(attribute), "When using a custom namespace attribute in a library " + "project, use the namespace `\"$AUTO_URI\"` instead." ) } } } } } companion object { private val IMPLEMENTATION = Implementation( NamespaceDetector::class.java, Scope.MANIFEST_AND_RESOURCE_SCOPE, Scope.RESOURCE_FILE_SCOPE, Scope.MANIFEST_SCOPE ) /** Typos in the namespace */ @JvmField val TYPO = Issue.create( id = "NamespaceTypo", briefDescription = "Misspelled namespace declaration", explanation = """ Accidental misspellings in namespace declarations can lead to some very obscure \ error messages. This check looks for potential misspellings to help track these \ down.""", category = Category.CORRECTNESS, priority = 8, severity = Severity.FATAL, implementation = IMPLEMENTATION ) /** Unused namespace declarations */ @JvmField val UNUSED = Issue.create( id = "UnusedNamespace", briefDescription = "Unused namespace", explanation = """ Unused namespace declarations take up space and require processing that is \ not necessary""", category = Category.PERFORMANCE, priority = 1, severity = Severity.WARNING, implementation = IMPLEMENTATION ) /** Unused namespace declarations */ @JvmField val REDUNDANT = Issue.create( id = "RedundantNamespace", briefDescription = "Redundant namespace", explanation = """ In Android XML documents, only specify the namespace on the root/document \ element. Namespace declarations elsewhere in the document are typically \ accidental leftovers from copy/pasting XML from other files or documentation.""", category = Category.PERFORMANCE, priority = 1, severity = Severity.WARNING, implementation = IMPLEMENTATION ) /** Using custom namespace attributes in a library project */ @JvmField val CUSTOM_VIEW = Issue.create( id = "LibraryCustomView", briefDescription = "Custom views in libraries should use res-auto-namespace", explanation = """ When using a custom view with custom attributes in a library project, the \ layout must use the special namespace $AUTO_URI instead of a URI which includes \ the library project's own package. This will be used to automatically adjust \ the namespace of the attributes when the library resources are merged into \ the application project.""", category = Category.CORRECTNESS, priority = 6, severity = Severity.FATAL, implementation = IMPLEMENTATION ) /** Unused namespace declarations */ @JvmField val RES_AUTO = Issue.create( id = "ResAuto", briefDescription = "Hardcoded Package in Namespace", explanation = """ In Gradle projects, the actual package used in the final APK can vary; for \ example,you can add a `.debug` package suffix in one version and not the other. \ Therefore, you should **not** hardcode the application package in the resource; \ instead, use the special namespace `http://schemas.android.com/apk/res-auto` \ which will cause the tools to figure out the right namespace for the resource \ regardless of the actual package used during the build.""", category = Category.CORRECTNESS, priority = 9, severity = Severity.FATAL, implementation = IMPLEMENTATION ) /** Prefix relevant for custom namespaces */ private const val XMLNS_ANDROID = "xmlns:android" private const val XMLNS_A = "xmlns:a" } }
1
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
16,942
vmtrace
Apache License 2.0
franky-intellij/src/main/kotlin/me/serce/franky/ui/jvmsListPanel.kt
SerCeMan
60,903,397
false
{"C++": 377719, "Kotlin": 41546, "Protocol Buffer": 1303, "CMake": 1208, "Java": 935, "C": 82}
package me.serce.franky.ui import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import me.serce.franky.jvm.AttachableJVM import me.serce.franky.jvm.JVMAttachService import me.serce.franky.util.Lifetime import me.serce.franky.util.subscribeUI import rx.Observable import rx.Subscription import rx.lang.kotlin.PublishSubject import rx.schedulers.Schedulers import java.awt.Component import java.awt.Dimension import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.concurrent.TimeUnit import javax.swing.DefaultListCellRenderer import javax.swing.DefaultListModel import javax.swing.JLabel import javax.swing.JList interface JvmsListViewModel : HasComponent { val connectJvmPublisher: Observable<AttachableJVM> } class JvmsListViewModelImpl(val lifetime: Lifetime) : JvmsListViewModel { private class JvmsListState { val jvms = PublishSubject<List<AttachableJVM>>() val jvmPublisher = PublishSubject<AttachableJVM>() } private val state = JvmsListState() private val view = JvmsListView(state) private val model = JvmsController(lifetime, state) override val connectJvmPublisher = state.jvmPublisher override fun createComponent() = view.createComponent() private class JvmsController(val lifetime: Lifetime, val state: JvmsListState) { val attachService = JVMAttachService.getInstance() init { Observable.interval(0, 5, TimeUnit.SECONDS, Schedulers.io()) .map { attachService.attachableJVMs() } .subscribe { state.jvms.onNext(it) } .unsubscibeOn(lifetime) } } private class JvmsListView(val state: JvmsListState) : View { val listModel = DefaultListModel<AttachableJVM>() val jvmsList = JList<AttachableJVM>().apply { model = listModel background = UIUtil.getListBackground() addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { state.jvmPublisher.onNext(selectedValue) } } }) } val mainPanel = BorderLayoutPanel() var loadingLabel: BorderLayoutPanel? = borderLayoutPanel { addToTop(JLabel("Loading...")) } init { state.jvms.subscribeUI { jvms -> if (loadingLabel != null) { mainPanel.remove(loadingLabel) mainPanel.addToCenter(jvmsList) loadingLabel = null } if (jvms != listModel.elements().toList()) { listModel.removeAllElements() jvms?.forEach { listModel.addElement(it) } } } jvmsList.cellRenderer = object : DefaultListCellRenderer() { override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component? { return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply { value as AttachableJVM? if (value != null) { text = "[${value.id}] ${value.name}" toolTipText = text } } } } } override fun createComponent() = mainPanel.apply { preferredSize = Dimension(200, 0) addToTop(jbLabel { text = "Running JVMs" }) addToCenter(loadingLabel) } } } fun Subscription.unsubscibeOn(lifetime: Lifetime): Subscription = apply { lifetime += { unsubscribe() } }
0
C++
1
9
bbe330ef84476ac9d9315bc17f97c3849b040584
3,983
franky
Apache License 2.0
rrouter-strategy/src/main/java/org/sheedon/rrouter/strategy/handler/BaseStrategyHandler.kt
Sheedon
387,140,116
false
{"Java": 217489, "Kotlin": 90601}
/* * Copyright (C) 2022 Sheedon. * * 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.sheedon.rrouter.strategy.handler import android.util.SparseArray import org.sheedon.rrouter.core.DataSource import org.sheedon.rrouter.core.StrategyHandle import org.sheedon.rrouter.core.ProcessChain import org.sheedon.rrouter.core.Request /** * 基础策略执行者 * * @Author: sheedon * @Email: [email protected] * @Date: 2021/7/19 4:33 下午 */ abstract class BaseStrategyHandler : StrategyHandle { /** * 处理请求代理 * * @param requestStrategies 请求策略集合 * @param card 请求卡片 * @param <RequestCard> 请求卡片 * @return 是否处理成功 </RequestCard> */ override fun <RequestCard> handleRequestStrategy( processChain: ProcessChain, requestStrategies: SparseArray<Request<RequestCard>>, card: RequestCard? ): Boolean { return handleRealRequestStrategy(processChain, requestStrategies, card) } /** * 真实处理请求代理 * * @param processChain 请求进度 * @param requestStrategies 请求策略集合 * @param card 请求卡片 * @param <RequestCard> 请求卡片类型 * @return 是否调用成功 </RequestCard> */ protected open fun <RequestCard> handleRealRequestStrategy( processChain: ProcessChain, requestStrategies: SparseArray<Request<RequestCard>>, card: RequestCard? ): Boolean { // 拿到当前进度对应的请求 val request = requestStrategies[processChain.getProcess()] // 请求不存在,则请求失败 if (request == null) { processChain.updateCurrentStatus(ProcessChain.STATUS_COMPLETED) return false } // 状态并非「未发送」,则请求失败 if (processChain.getCurrentStatus() != ProcessChain.STATUS_NORMAL) { processChain.updateCurrentStatus(ProcessChain.STATUS_COMPLETED) return false } // 请求任务 processChain.updateCurrentStatus(ProcessChain.STATUS_REQUESTING) request.request(card) return true } /** * 处理反馈代理 * * @param callback 反馈监听 * @param message 描述信息 * @param isSuccess 是否请求成功 * @param <ResponseModel> 结果model类型 * @return 是否处理成功 </ResponseModel> */ override fun <ResponseModel> handleCallbackStrategy( processChain: ProcessChain, callback: DataSource.Callback<ResponseModel>?, model: ResponseModel?, message: String?, isSuccess: Boolean ): Boolean { // 当前状态已完成,不做额外反馈处理 if (processChain.getCurrentStatus() == ProcessChain.STATUS_COMPLETED) { return false } // 当前状态是默认,意味着流程错误,不往下执行 return if (processChain.getCurrentStatus() == ProcessChain.STATUS_NORMAL) { false } else handleRealCallbackStrategy( processChain, callback, model, message, isSuccess ) // 真实执行 } /** * 真实处理反馈代理 * * @param processChain 流程链 * @param callback 反馈监听 * @param model 数据 * @param message 描述信息 * @param isSuccess 是否请求成功 * @param <ResponseModel> 反馈model类型 * @return 是否处理成功 </ResponseModel> */ protected open fun <ResponseModel> handleRealCallbackStrategy( processChain: ProcessChain, callback: DataSource.Callback<ResponseModel>?, model: ResponseModel?, message: String?, isSuccess: Boolean ): Boolean { // 状态并非「发送中」,则反馈执行失败 if (processChain.getCurrentStatus() != ProcessChain.STATUS_REQUESTING) { processChain.updateCurrentStatus(ProcessChain.STATUS_COMPLETED) return false } processChain.updateCurrentStatus(ProcessChain.STATUS_COMPLETED) handleCallback(callback, model, message, isSuccess) return true } /** * 处理反馈结果 * * @param callback 反馈监听器 * @param model 反馈Model * @param message 描述信息 * @param isSuccess 是否为成功数据反馈 * @param <ResponseModel> 反馈数据类型 </ResponseModel> */ protected open fun <ResponseModel> handleCallback( callback: DataSource.Callback<ResponseModel>?, model: ResponseModel?, message: String?, isSuccess: Boolean ) { if (isSuccess) { callback?.onDataLoaded(model) return } callback?.onDataNotAvailable(message) } }
1
null
1
1
67b4323eddf2485dfbdeaef0c499b93df440bbea
4,934
RequestRouter
Apache License 2.0
src/main/kotlin/snyk/common/annotator/SnykCodeAnnotator.kt
snyk
117,852,067
false
{"Kotlin": 839906, "JavaScript": 9475, "SCSS": 2354, "HCL": 562, "Java": 187}
package snyk.code.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiFile import io.snyk.plugin.isSnykCodeRunning import io.snyk.plugin.ui.toolwindow.SnykPluginDisposable import snyk.common.ProductType class SnykCodeAnnotator : SnykAnnotator(product = ProductType.CODE_SECURITY) { init { Disposer.register(SnykPluginDisposable.getInstance(), this) } override fun apply( psiFile: PsiFile, annotationResult: List<SnykAnnotation>, holder: AnnotationHolder, ) { if (disposed) return if (isSnykCodeRunning(psiFile.project)) return super.apply(psiFile, annotationResult, holder) } }
8
Kotlin
34
54
7ee680baff7ccf3b4440e7414b021efda8c58416
737
snyk-intellij-plugin
Apache License 2.0
mobileChatExamples/androidChatExample/app/src/main/java/com/blitz/androidchatexample/ChatApplication.kt
amazon-connect
214,268,077
false
{"JavaScript": 219107, "Kotlin": 91877, "Swift": 90939, "HTML": 68770, "CSS": 32218, "Shell": 58}
package com.blitz.androidchatexample import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class ChatApplication: Application() { override fun onCreate() { super.onCreate() } }
17
JavaScript
214
146
a3fa1d42af209ff42f5db6dee78c0a33b3cb34c4
229
amazon-connect-chat-ui-examples
MIT No Attribution
app/src/main/java/com/adyen/sampleapp/MyAuthenticationService.kt
Adyen
636,746,031
false
null
package com.adyen.sampleapp import com.adyen.ipp.authentication.AuthenticationProvider import com.adyen.ipp.authentication.AuthenticationResponse import com.adyen.ipp.authentication.AuthenticationService import org.json.JSONObject import java.io.IOException import kotlin.coroutines.resume import kotlinx.coroutines.suspendCancellableCoroutine import okhttp3.Call import okhttp3.Callback import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response class MyAuthenticationService : AuthenticationService() { val apiKey = BuildConfig.EnvironmentApiKey val merchantAccount = BuildConfig.EnvironmentMerchantAccount val apiUrl = BuildConfig.EnvironmentUrl override val authenticationProvider: AuthenticationProvider get() = object : AuthenticationProvider { override suspend fun authenticate(setupToken: String): Result<AuthenticationResponse> { val client = OkHttpClient() val jsonObject = JSONObject() // Please put below your merchant account jsonObject.put("merchantAccount", merchantAccount) jsonObject.put("setupToken", setupToken) val mediaType = "application/json".toMediaType() val body = jsonObject.toString().toRequestBody(mediaType) val request = Request.Builder() // Please add your URL to receive session token .url(apiUrl) .addHeader( "x-api-key", // Please add api key apiKey ) .post(body) .build() return suspendCancellableCoroutine { continuation -> client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { continuation.resume(Result.failure(Throwable(e))) } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful && response.body != null) { val json = JSONObject(response.body!!.string()) continuation.resume( Result.success( AuthenticationResponse( json.optString( "sdkData" ) ) ) ) } else { continuation.resume(Result.failure(Throwable("error"))) } } }) } } } }
0
Kotlin
0
0
e83f817bafd70ac5ca872af9d5ce699fac27592e
3,048
adyen-pos-mobile-android
MIT License
door-runtime/src/commonMain/kotlin/com/ustadmobile/door/paging/DoorLoadResultExt.kt
UstadMobile
344,538,858
false
null
package com.ustadmobile.door.paging /** * Convert the given DoorLoadResult to the platform specific type. */ expect fun <Key: Any, Value: Any> DoorLoadResult<Key, Value>.toLoadResult(): LoadResult<Key, Value> expect fun <Key: Any, Value: Any> LoadResult<Key, Value>.toDoorLoadResult(): DoorLoadResult<Key, Value>
0
Kotlin
0
89
58f93d9057ece78cc3f8be3d4d235c0204a15f11
317
door
Apache License 2.0
kgraphql-ktor/src/main/kotlin/com/apurebase/kgraphql/KtorGraphQLConfiguration.kt
stuebingerb
872,399,797
false
null
package com.apurebase.kgraphql import com.apurebase.kgraphql.configuration.PluginConfiguration class KtorGraphQLConfiguration( val playground: Boolean, val endpoint: String ): PluginConfiguration
49
null
41
3
f15b4e5327aff0bf3e011211405aa4b6dc8f36f1
206
KGraphQL
MIT License
core/src/main/java/be/appwise/core/validation/rules/edittext/NumericRule.kt
wisemen-digital
349,150,482
false
{"Kotlin": 255860}
package be.appwise.core.validation.rules.edittext import android.widget.EditText class NumericRule<T: EditText>( val message: String = "This field must be a number" ) : EditTextRule<T>(message) { override val textValidationRule = { text: String -> text.matches(Regex("[0-9]+")) } }
7
Kotlin
5
5
c7a8a31aea0b61923af987ab5410f19897d52820
304
AndroidCore
MIT License
cordapp-contracts-states/src/test/kotlin/com/hmlr/contracts/LandTitleAssignBuyerConveyancerTests.kt
LandRegistry
158,533,826
false
null
package com.hmlr.contracts import com.hmlr.AbstractContractsStatesTestUtils import com.hmlr.model.DTCConsentStatus import com.hmlr.model.LandTitleStatus import net.corda.core.contracts.TypeOnlyCommandData import net.corda.core.utilities.seconds import net.corda.testing.node.MockServices import net.corda.testing.node.ledger import org.junit.Test class LandTitleAssignBuyerConveyancerTests : AbstractContractsStatesTestUtils() { private var ledgerServices = MockServices(listOf("com.hmlr.contracts")) class DummyCommand : TypeOnlyCommandData() @Test fun `must Include Assign Buyer Conveyancer Command`() { val outputProposedChargeAndRestrictionState = proposedChargeOrRestrictionState.copy(buyerConveyancer = CHARLIE.party, status = DTCConsentStatus.ASSIGN_BUYER_CONVEYANCER, participants = proposedChargeOrRestrictionState.participants + CHARLIE.party) ledgerServices.ledger { transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), AssignBuyerConveyancerToPropsedChargeAndRestrictionStateTests.DummyCommand()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.verifies() } } } @Test fun `must Include Exactly Two Input States`() { val outputProposedChargeAndRestrictionState = proposedChargeOrRestrictionState.copy(buyerConveyancer = CHARLIE.party, status = DTCConsentStatus.ASSIGN_BUYER_CONVEYANCER, participants = proposedChargeOrRestrictionState.participants + CHARLIE.party) ledgerServices.ledger { transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.verifies() } } } @Test fun `must Include Four Output States`() { val outputProposedChargeAndRestrictionState = proposedChargeOrRestrictionState.copy(buyerConveyancer = CHARLIE.party, status = DTCConsentStatus.ASSIGN_BUYER_CONVEYANCER, participants = proposedChargeOrRestrictionState.participants + CHARLIE.party) ledgerServices.ledger { transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.verifies() } } } @Test fun `buyer Conveyancer Must Be Participant`() { val outputProposedChargeAndRestrictionState = proposedChargeOrRestrictionState.copy(buyerConveyancer = CHARLIE.party, status = DTCConsentStatus.ASSIGN_BUYER_CONVEYANCER, participants = proposedChargeOrRestrictionState.participants + CHARLIE.party) val invalidOutputLandTitleState = landTitleState.copy(participants = landTitleState.participants + ALICE.party) ledgerServices.ledger { transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, invalidOutputLandTitleState) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.verifies() } } } @Test fun `must Be Signed By Owners Conveyancer`() { val outputProposedChargeAndRestrictionState = proposedChargeOrRestrictionState.copy(buyerConveyancer = CHARLIE.party, status = DTCConsentStatus.ASSIGN_BUYER_CONVEYANCER, participants = proposedChargeOrRestrictionState.participants + CHARLIE.party) ledgerServices.ledger { transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(CHARLIE.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(CHARLIE.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.fails() } transaction { input(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleState) input(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, proposedChargeOrRestrictionState) output(ProposedChargeAndRestrictionContract.PROPOSED_CHARGE_RESTRICTION_CONTRACT_ID, outputProposedChargeAndRestrictionState) output(LandAgreementContract.LAND_AGREEMENT_CONTRACT_ID, agreementState.copy(paymentConfirmationStateLinearId = paymentConfirmationState.linearId.toString())) output(LandTitleContract.LAND_TITLE_CONTRACT_ID, landTitleStateWithBuyerConveyancer) output(PaymentConfirmationContract.PAYMENT_CONFIRMATION_CONTRACT_ID, paymentConfirmationState) command(listOf(BOB.publicKey), ProposedChargeAndRestrictionContract.Commands.AssignBuyerConveyancer()) command(listOf(BOB.publicKey), LandAgreementContract.Commands.CreateDraftAgreement()) command(listOf(BOB.publicKey), PaymentConfirmationContract.Commands.IssuePaymentConfirmation()) command(listOf(BOB.publicKey), LandTitleContract.Commands.AssignBuyerConveyancer()) timeWindow(ledgerServices.clock.instant(), 60.seconds) this.verifies() } } } }
0
Kotlin
6
7
3c3b8f0c3bbd5927766d9df3113ecd951afd91b1
18,414
digital-street-cordapp
MIT License
emojipicker/src/main/java/com/kazumaproject/emojipicker/model/Emoji.kt
KazumaProject
599,677,394
false
{"Kotlin": 257606, "Java": 153764}
package com.kazumaproject.emojipicker.model data class Emoji( val id: Int, val emoji_short_name: String, val unicode: Int )
0
Kotlin
0
0
17ac7b5bfa58223eb87c9c360a1e6ec335683fcf
137
MarkdownNote
MIT License
app/src/main/java/com/example/roomdb/AddEditActivity.kt
Diana-Kieru
813,278,638
false
{"Kotlin": 43024}
package com.example.roomdb import HubAdapter import RestClient import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.RecyclerView import com.example.roomdb.models.Hub import com.example.roomdb.models.ParcelableHub import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.gson.Gson import kotlinx.coroutines.launch class AddEditActivity : AppCompatActivity(), HubAdapter.OnEditClickListener { private lateinit var fabAddHub: FloatingActionButton private lateinit var hubAdapter: HubAdapter private lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_add_edit) // Initialize the adapter with an empty list hubAdapter = HubAdapter(emptyList(), ::deleteHub, this) // Get the reference to the RecyclerView recyclerView = findViewById(R.id.rvHubs) recyclerView.adapter = hubAdapter fetchHubs() fabAddHub = findViewById(R.id.fabAddHub) fabAddHub.setOnClickListener { // Launch the RegistrationActivity val intent = Intent(this, Registration::class.java) startActivity(intent) } } override fun onEditClick(hub: Hub) { val gson = Gson() val keyContactsJson = gson.toJson(hub.keyContacts) val parcelableHub = ParcelableHub( hub.id, hub.hubName, hub.hubCode, hub.address, hub.yearEstablished, hub.ownership, hub.floorSize, hub.facilities, hub.inputCenter, hub.typeOfBuilding, hub.longitude, hub.latitude, hub.region, keyContactsJson, hub.userId ) // Rest of your code... val intent = Intent(this, EditHubActivity::class.java) intent.putExtra("hubData", parcelableHub) startActivity(intent) } private fun fetchHubs() { val sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE) val token = sharedPreferences.getString("accessToken", "") ?: "" val apiService = RestClient.getApiService(applicationContext) lifecycleScope.launch { try { val response = apiService.getHubs("Bearer $token") if (response.isSuccessful) { val hubList = response.body()?.forms if (hubList != null) { // Sort the hubList in descending order based on the ID val sortedHubList = hubList.sortedByDescending { it.id } setupRecyclerView(sortedHubList) // Update the adapter with the sorted list hubAdapter.updateList(sortedHubList) } } else { // Handle API error } } catch (e: Exception) { // Handle network error } } } private fun deleteHub(hub: Hub) { val id = hub.id val sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE) val token = sharedPreferences.getString("accessToken", "") ?: "" val apiService = RestClient.getApiService(applicationContext) lifecycleScope.launch { try { val response = apiService.deleteHub("Bearer $token", id) if (response.isSuccessful) { // Hub deleted successfully showToastMessage("Hub deleted successfully") // Refresh the list of hubs fetchHubs() } else { // Handle API error showToastMessage("Failed to delete hub: ${response.message()}") } } catch (e: Exception) { // Handle network error showToastMessage("Network error: ${e.message}") } } } private fun showToastMessage(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } private fun setupRecyclerView(hubList: List<Hub>) { hubAdapter.updateList(hubList) } }
0
Kotlin
0
0
ede5dd9413d188ebbb2811a5a0fe8b9b421f43a1
4,636
Room-DB
MIT License
app/src/main/java/com/zmj/androidfirstline/broadcast/MyBroadCastReceiver.kt
ZmjDns
284,897,580
false
null
package com.zmj.androidfirstline.broadcast import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import android.widget.Toast /** * Author : Zmj * Blog : https://blog.csdn.net/Zmj_Dns * GitHub : https://github.com/ZmjDns * Time : 2020/8/6 * Description : */ class MyBroadCastReceiver: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Toast.makeText(context,"Received my broadcast",Toast.LENGTH_SHORT).show() Log.d("MyBroadCastReceiver","Received my broadcast") //阻止广播往下传 abortBroadcast() } }
0
Kotlin
0
0
eed31dc990ff5043134ca84fcc379193da1c2d0b
644
AndroidFirstLine
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/util/episode/EpisodeFilterDownloaded.kt
aniyomiorg
358,887,741
false
{"Kotlin": 4957619}
package eu.kanade.tachiyomi.util.episode import eu.kanade.tachiyomi.data.download.anime.AnimeDownloadCache import tachiyomi.domain.entries.anime.model.Anime import tachiyomi.domain.items.episode.model.Episode import tachiyomi.source.local.entries.anime.isLocal import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Returns a copy of the list with not downloaded chapters removed. */ fun List<Episode>.filterDownloadedEpisodes(anime: Anime): List<Episode> { if (anime.isLocal()) return this val downloadCache: AnimeDownloadCache = Injekt.get() return filter { downloadCache.isEpisodeDownloaded( it.name, it.scanlator, anime.ogTitle, anime.source, false, ) } }
24
Kotlin
8
4,992
823099f775ef608b7c11f096da1f50762dab82df
776
aniyomi
Apache License 2.0
src/main/kotlin/top/lanscarlos/vulpecula/kether/action/ActionMemory.kt
Lanscarlos
517,897,387
false
null
package top.lanscarlos.vulpecula.kether.action import net.luckperms.api.LuckPerms import net.luckperms.api.node.NodeType import net.luckperms.api.node.types.MetaNode import org.bukkit.Bukkit import org.bukkit.entity.Entity import org.bukkit.entity.Player import taboolib.common.platform.ProxyPlayer import taboolib.library.kether.ParsedAction import taboolib.module.kether.ScriptAction import taboolib.module.kether.ScriptFrame import taboolib.module.kether.run import taboolib.module.kether.scriptParser import top.lanscarlos.vulpecula.kether.VulKetherParser import top.lanscarlos.vulpecula.kether.live.LiveData import top.lanscarlos.vulpecula.kether.live.readString import top.lanscarlos.vulpecula.utils.* import top.maplex.abolethcore.AbolethUtils import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap /** * Vulpecula * top.lanscarlos.vulpecula.kether.action * * @author Lanscarlos * @since 2022-11-12 00:23 */ class ActionMemory( val key: LiveData<String>, val value: ParsedAction<*>?, val unique: ParsedAction<*>?, val storage: String? ) : ScriptAction<Any?>() { override fun run(frame: ScriptFrame): CompletableFuture<Any?> { return listOf( key.getOrNull(frame), value?.let { frame.run(it) }, unique?.let { frame.run(it) } ).thenTake().thenApply { args -> val key = args[0]?.toString() ?: error("No key selected.") val value = args[1] val unique = args[2] if (this.value != null) { // 设置变量 setMemory(frame, key, value, unique, storage) } else { // 获取变量 getMemory(frame, key, unique, storage) } } } companion object { val luckPermsAPI by lazy { try { Bukkit.getServicesManager().getRegistration(LuckPerms::class.java)?.provider } catch (e: Exception) { null } } private val cache = ConcurrentHashMap<Entity, ConcurrentHashMap<String, Any>>() private val globalCache = ConcurrentHashMap<String, Any>() /** * 获取变量 * * @param unique 对应实体,若为 null 则为全局变量 * @param storage 存储容器,默认使用 cache 存储 * */ fun getMemory(frame: ScriptFrame, key: String, unique: Any?, storage: String? = null): Any? { when (storage?.lowercase()) { "luckperms", "lp" -> { val api = luckPermsAPI ?: error("No LuckPerms plugin service found.") val user = when (unique) { is Player -> api.getPlayerAdapter(Player::class.java).getUser(unique) else -> { val player = Bukkit.getPlayerExact(unique.toString()) ?: frame.playerOrNull()?.toBukkit() api.getPlayerAdapter(Player::class.java).getUser(player ?: error("No LuckPerms player selected.")) } } return user.cachedData.metaData.getMetaValue(key) } "aboleth", "abo" -> { val uuid = when (unique) { is Player -> unique.uniqueId is ProxyPlayer -> unique.uniqueId is String -> Bukkit.getPlayerExact(unique)?.uniqueId else -> null } return AbolethUtils.get(uuid ?: AbolethUtils.getServerUUID(), key) } else -> { val map = if (unique is Entity) { cache.computeIfAbsent(unique) { ConcurrentHashMap() } } else { globalCache } return map[key] } } } /** * 获取变量 * * @param value 若为空则删除对应键值 * @param unique 对应实体,若为 null 则为全局变量 * @param storage 存储容器,默认使用 cache 存储 * * @return value 的值 * */ fun setMemory(frame: ScriptFrame, key: String, value: Any?, unique: Any?, storage: String? = null): Any? { when (storage?.lowercase()) { "luckperms", "lp" -> { val api = luckPermsAPI ?: error("No LuckPerms plugin service found.") val user = when (unique) { is Player -> api.getPlayerAdapter(Player::class.java).getUser(unique) else -> { val player = Bukkit.getPlayerExact(unique.toString()) ?: frame.playerOrNull()?.toBukkit() api.getPlayerAdapter(Player::class.java).getUser(player ?: error("No LuckPerms player selected.")) } } user.data().clear(NodeType.META.predicate { it.metaKey.equals(key, true) }) if (value != null) { val node = MetaNode.builder(key, value.toString()).build() user.data().add(node) api.userManager.saveUser(user) } } "aboleth", "abo" -> { val uuid = when (unique) { is Player -> unique.uniqueId is ProxyPlayer -> unique.uniqueId is String -> Bukkit.getPlayerExact(unique)?.uniqueId else -> null } if (value != null) { AbolethUtils.set(uuid ?: AbolethUtils.getServerUUID(), key, value) } else { AbolethUtils.remove(uuid ?: AbolethUtils.getServerUUID(), key) } } else -> { val map = if (unique is Entity) { cache.computeIfAbsent(unique) { ConcurrentHashMap() } } else { globalCache } if (value != null) { map[key] = value } else { map.remove(key) } } } return value } /** * * 变量是默认相对于实体独立的 * * 获取变量 * memory {key} * memory {key} by &entity * memory {key} by &entity using lp * memory {key} -global(g) * * 设置变量 * memory {key} to {value} * memory {key} to {value} by &entity * memory {key} to {value} by &entity using lp * memory {key} to {value} -global(g) * */ @VulKetherParser( id = "memory", name = ["memory"] ) fun parser() = scriptParser { reader -> val key = reader.readString() val value = if (reader.hasNextToken("to")) { reader.nextBlock() } else null val unique = if (reader.hasNextToken("by", "with")) { reader.nextParsedAction() } else null val storage = reader.tryNextToken("using") // 全局变量不以 ActionMemory(key, value, unique, storage) } } }
0
Kotlin
1
17
bdb9a71f2e1b52f259c95a58b864d885a8ac779b
7,380
Vulpecula
Creative Commons Zero v1.0 Universal
src/test/kotlin/io/github/caijiang/common/test/TemplateTest.kt
caijiang
734,162,676
false
{"Kotlin": 118037, "Java": 64}
package io.github.caijiang.common.test import io.github.caijiang.common.test.mvc_demo.MvcDemoApp import org.assertj.core.api.Assertions.assertThat import org.springframework.boot.test.context.SpringBootTest import org.springframework.core.io.ClassPathResource import org.springframework.http.HttpMethod import org.springframework.test.context.ActiveProfiles import org.springframework.web.client.exchange import org.springframework.web.client.getForEntity import org.springframework.web.client.getForObject import kotlin.test.Test /** * @author CJ */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = [MvcDemoApp::class]) @ActiveProfiles("test") class TemplateTest : AbstractSpringTest() { @Test fun assertion() { val template = createTestTemplate() assertThat(template, "/echoUrlEncoded?p1=1&p2=2") .isLegalResponse() .isSuccessResponse() assertThat(template.getForEntity("/echoUrlEncoded?p1=1&p2=2")) .isLegalResponse() assertThat(template, "/echoUrlEncoded22?p1=1&p2=2") .isFailedResponse() .isErrorCodeMatch("404") } @Test fun well() { val template = createTestTemplate() val r1 = template.exchange<String>( "/echoUrlEncoded", HttpMethod.POST, ClassPathResource("/echoUrlEncode.properties").createUrlEncodeHttpEntityFromProperties() ) assertThat(r1.statusCode.is2xxSuccessful) .isTrue() assertThat(r1.body) .isEqualTo("foo+bar") val r2 = template.exchange<String>( "/echoUrlEncoded", HttpMethod.POST, ClassPathResource("/echoUrlEncode.properties").inputStream.createUrlEncodeHttpEntityFromProperties() ) assertThat(r2.statusCode.is2xxSuccessful) .isTrue() assertThat(r2.body) .isEqualTo("foo+bar") assertThat(template.getForObject<String?>("/readCookie")) .isNull() template.getForObject<String>("/setCookie") assertThat(template.getForObject<String>("/readCookie")) .isEqualTo("foo") } }
0
Kotlin
0
0
53c820d300dbdfd34360fc7c5494b49fbe6d30dd
2,199
common-ext
MIT License
app/src/main/java/com/newgamesoftware/moviesappdemo/base/layout/BaseCoordinatorLayout.kt
nejatboy
426,532,203
false
null
package com.newgamesoftware.moviesappdemo.base.layout import android.content.Context import androidx.coordinatorlayout.widget.CoordinatorLayout abstract class BaseCoordinatorLayout(context: Context): CoordinatorLayout(context) { init { id = generateViewId() } }
0
Kotlin
0
2
f1f4a0f21834b1f32d914cd4a0e089d0a587a46e
280
MoviesDemo-Android
MIT License
app/src/main/java/com/example/whats_eat/data/di/dispatcherQualifier/DispatcherQualifier.kt
KanuKim97
428,755,782
false
null
package com.example.whats_eat.data.di.dispatcherQualifier import javax.inject.Qualifier @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class IoDispatcher @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class MainDispatcher @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class DefaultDispatcher
1
Kotlin
0
2
d01a732ec329b6d32ba7b1d87855e3ecf6e1a6bb
341
whats_eat
Apache License 2.0
src/main/org/lrs/kmodernlrs/services/AgentsService.kt
dtarnawczyk
73,920,384
false
null
package org.lrs.kmodernlrs.services import org.lrs.kmodernlrs.domain.Actor interface AgentsService { fun getAgentDetails(actor: Actor) : Actor? fun getAll() : List<Actor>? fun get10Agents(from: Int) : List<Actor>? fun get20Agents(from: Int) : List<Actor>? fun get50Agents(from: Int) : List<Actor>? fun getAgentsLimitFrom(limit: Int, from: Int) : List<Actor>? fun getCount() : Long fun exists(actor: Actor) : Boolean }
0
Kotlin
1
4
e534a527635660fe330980411bc8116200af355b
453
modernlrs
Apache License 2.0
core/src/main/kotlin/com/hexagontk/core/I18n.kt
hexagontk
56,139,239
false
null
package com.hexagonkt.helpers import java.util.* import kotlin.reflect.KClass /** Set of allowed country codes in this JVM. */ val countryCodes: Set<String> by lazy { Locale.getISOCountries().toSet() } /** Set of allowed language codes in this JVM. */ val languageCodes: Set<String> by lazy { Locale.getISOLanguages().toSet() } /** Set of allowed currency codes in this JVM. */ val currencyCodes: Set<String> by lazy { Currency.getAvailableCurrencies().map { it.currencyCode }.toSet() } /** * [TODO](https://github.com/hexagonkt/hexagon/issues/271). * * @param locale . * @return . */ inline fun <reified T : ResourceBundle> resourceBundle( locale: Locale = Locale.getDefault()): ResourceBundle = resourceBundle(T::class, locale) /** * [TODO](https://github.com/hexagonkt/hexagon/issues/271). * * @param type . * @param locale . * @return . */ fun <T : ResourceBundle> resourceBundle( type: KClass<T>, locale: Locale = Locale.getDefault()): ResourceBundle = ResourceBundle.getBundle(type.java.name, locale) /** * [TODO](https://github.com/hexagonkt/hexagon/issues/271). * * @param language . * @param country . * @return . */ fun localeOf(language: String = "", country: String = ""): Locale { require(language.isNotEmpty() || country.isNotEmpty()) { "A non-blank language or country is required" } require(language.isEmpty() || language in languageCodes) { "Language: '$language' not allowed" } require(country.isEmpty() || country in countryCodes) { "Country: '$country' not allowed" } return Locale.Builder().setLanguage(language).setRegion(country).build() } /** * [TODO](https://github.com/hexagonkt/hexagon/issues/271). * * @param language . * @param country . * @return . */ fun localeOfOrNull(language: String = "", country: String = ""): Locale? = try { localeOf(language, country) } catch (_: IllegalArgumentException) { null } fun languageOf(language: String): Locale = localeOf(language = language) fun languageOfOrNull(language: String): Locale? = try { languageOf(language) } catch (_: IllegalArgumentException) { null } fun countryOf(country: String): Locale = localeOf(country = country) fun countryOfOrNull(country: String): Locale? = try { countryOf(country) } catch (_: IllegalArgumentException) { null } fun parseLocale(languageCountry: String): Locale = languageCountry .split("_") .let { when { it.size == 1 && it[0].all { c -> c.isUpperCase() } -> countryOf(it[0]) it.size == 1 -> languageOf(it[0]) it.size == 2 -> localeOf(it[0], it[1]) else -> throw IllegalArgumentException("Invalid locale format: $languageCountry") } } fun parseLocaleOrNull(languageCountry: String): Locale? = try { parseLocale(languageCountry) } catch (_: IllegalArgumentException) { null }
3
null
99
578
7436f1985832d21696fe7c08a0f454add6520284
3,032
hexagon
Apache License 2.0
Client/app/src/main/java/com/t3ddyss/clother/presentation/chat/ChatsListViewModel.kt
t3ddyss
337,083,750
false
{"Kotlin": 343905, "Python": 38739, "Jupyter Notebook": 22857, "HTML": 11031, "Dockerfile": 439, "Shell": 405}
package com.t3ddyss.clother.presentation.chat import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.t3ddyss.clother.domain.chat.ChatInteractor import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.shareIn import javax.inject.Inject @HiltViewModel class ChatsListViewModel @Inject constructor( chatInteractor: ChatInteractor ) : ViewModel() { val chats = chatInteractor .observeChats() .shareIn(viewModelScope, SharingStarted.Eagerly) }
0
Kotlin
1
23
cf8036e576d4b01896c09321aef5644f4e716316
570
Clother
MIT License
src/main/kotlin/net/rebux/jumpandrun/utils/MessageBuilder.kt
7rebux
402,599,961
false
{"Kotlin": 109944}
package net.rebux.jumpandrun.utils import net.rebux.jumpandrun.config.MessagesConfig import org.bukkit.Bukkit import org.bukkit.command.CommandSender /** * A builder class for messages. * * This class is used to create any type of message in the plugin. It also supports multiline * messages by default. The prefix is also included by default. * * @param[template] The template to use as the message basis. This may include <code>\n</code> for * multiple lines. */ data class MessageBuilder(private var template: String) { private var values: Map<String, Any>? = null private var prefix: Boolean = true private var error: Boolean = false /** * Specifies the values to be set in the message. * * @param[values] A map of key value pairs which replaces each key in the template with its * value. */ fun values(values: Map<String, Any>) = apply { this.values = values } /** * Specifies whether the message should start with the default prefix. This is true by default. * * @param[prefix] Whether the message should start with the prefix. */ fun prefix(prefix: Boolean = true) = apply { this.prefix = prefix } /** * Specifies whether the message should be formatted as an error. * * @param[error] Whether the message should be formatted as an error. */ fun error(error: Boolean = true) = apply { this.error = error } /** Builds the message and returns all lines in a [Collection]. */ fun build(): Collection<String> { return template.split("\n").map(::replaceValues).map(::appendOptions) } /** Builds the message and only returns the first line. */ fun buildSingle(): String { return build().first() } /** * Builds and sends all lines of the message to the provided [receiver]. * * @param[receiver] The receiver of the message. */ fun buildAndSend(receiver: CommandSender) { build().forEach(receiver::sendMessage) } /** Builds the message and sends all lines as a broadcast message to the server. */ fun buildAndSendGlobally() { build().forEach(Bukkit::broadcastMessage) } private fun replaceValues(line: String): String { return values?.entries?.fold(line) { acc, (key, value) -> acc.replace("{$key}", value.toString()) } ?: line } private fun appendOptions(line: String): String { return buildString { if (prefix) append(MessagesConfig.prefix) if (error) append("§4") append(line) } } }
0
Kotlin
0
1
9353f5d6087704b40583aad93df0f406784ea331
2,605
jump-and-run
MIT License
app/src/main/java/com/example/androiddevchallenge/Navigation.kt
janbina
347,207,502
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import androidx.navigation.NavController import androidx.navigation.compose.navigate interface Navigation { fun navigateUp() fun navigate(route: String) } class NavControllerNavigation( private val controller: NavController ) : Navigation { override fun navigateUp() { controller.navigateUp() } override fun navigate(route: String) { controller.navigate(route) } } class Dummy : Navigation { override fun navigateUp() {} override fun navigate(route: String) {} }
0
Kotlin
0
0
c5063a9d481198da1fafd52d04e9f80995939786
1,177
android-dev-challenge-compose-week3
Apache License 2.0
app/src/main/java/gr/exm/agroxm/util/DateTimeHelper.kt
LedgerProject
321,964,554
false
null
package gr.exm.agroxm.util import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.util.concurrent.TimeUnit fun LocalDateTime.startOfHour(): LocalDateTime { return this.withMinute(0).withSecond(0).withNano(0) } fun LocalDateTime.endOfHour(): LocalDateTime { return this.plusHours(1).startOfHour() } fun LocalDateTime.endOfDay(): LocalDateTime { return this.apply { plusDays(1) withHour(0) withMinute(0) withSecond(0) withNano(0) } } fun LocalDateTime.millis(): Long { return TimeUnit.SECONDS.toMillis(this.atZone(ZoneOffset.systemDefault()).toEpochSecond()) } fun fromMillis(millis: Long): LocalDateTime { return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()) } fun LocalDateTime.formatDefault(): String { return format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)) }
0
Kotlin
2
2
381a02f1d0d891b7d1c08a03b5fd5b26063402d0
1,028
disemin-android
Apache License 2.0
adapter/src/main/kotlin/io/goooler/demoapp/adapter/rv/core/IVhModelWrapper.kt
Goooler
188,988,687
false
{"Kotlin": 151079, "Java": 152}
package io.goooler.demoapp.adapter.rv.core /** * Created on 2020/10/23. * * Model wrapper. M type need same as constrained [IVhModelType]. * * @author feling * @version 1.0.0 * @since 1.0.0 */ interface IVhModelWrapper<M : IVhModelType> : IVhModelType { /** * If [viewType] return value is not -1, this [IVhModelWrapper] self will be as a node. */ override val viewType: Int get() = -1 /** * As sub model list. */ val subList: Iterable<M> }
6
Kotlin
11
70
7f47125cc66743aac154671a4e18699acec77fd2
472
DemoApp
Apache License 2.0
src/main/kotlin/problems/Fibonacci.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
package problems object Fibonacci { fun fibIterative(limit: Int): Long { var prePrev = 0L var prev = 1L if (limit < 0) { throw Exception("Not a valid input") } if (limit == 0) { return 0 } if (limit == 1) { return prev } for (i in 2..limit) { val sum = prePrev + prev prePrev = prev prev = sum } return prev } fun fibRecursive(limit: Int): Int { if (limit == 0) { return 0 } if (limit == 1) { return 1 } if (limit < 0) { throw Exception("Not a valid input") } return fibRecursive(limit - 1) + fibRecursive(limit - 2) } fun fibMemoized(limit: Int): Int { if (limit < 0) { throw Exception("Not a valid input") } if (limit <= 1) { return limit } val memo = IntArray(limit + 1) { -1 } memo[0] = 0 memo[1] = 1 fun doFib(limit: Int): Int { if (memo[limit] != -1) { return memo[limit] } memo[limit] = doFib(limit - 2) + doFib(limit - 1) return memo[limit] } return doFib(limit) } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,322
data-structures
MIT License
archive/src/main/kotlin/org/openrs2/archive/cache/CacheExporter.kt
openrs2
315,027,372
false
null
package org.openrs2.archive.cache import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonUnwrapped import io.netty.buffer.ByteBufAllocator import io.netty.buffer.Unpooled import org.openrs2.buffer.use import org.openrs2.cache.ChecksumTable import org.openrs2.cache.DiskStore import org.openrs2.cache.Js5Archive import org.openrs2.cache.Js5Compression import org.openrs2.cache.Js5MasterIndex import org.openrs2.cache.MasterIndexFormat import org.openrs2.cache.Store import org.openrs2.crypto.XteaKey import org.openrs2.db.Database import org.postgresql.util.PGobject import java.sql.Connection import java.time.Instant import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.SortedSet import javax.inject.Inject import javax.inject.Singleton @Singleton public class CacheExporter @Inject constructor( private val database: Database, private val alloc: ByteBufAllocator ) { public data class Stats( val validIndexes: Long, val indexes: Long, val validGroups: Long, val groups: Long, val validKeys: Long, val keys: Long, val size: Long, val blocks: Long ) { @JsonIgnore public val allIndexesValid: Boolean = indexes == validIndexes && indexes != 0L @JsonIgnore public val validIndexesFraction: Double = if (indexes == 0L) { 1.0 } else { validIndexes.toDouble() / indexes } @JsonIgnore public val allGroupsValid: Boolean = groups == validGroups @JsonIgnore public val validGroupsFraction: Double = if (groups == 0L) { 1.0 } else { validGroups.toDouble() / groups } @JsonIgnore public val allKeysValid: Boolean = keys == validKeys @JsonIgnore public val validKeysFraction: Double = if (keys == 0L) { 1.0 } else { validKeys.toDouble() / keys } /* * The max block ID is conveniently also the max number of blocks, as * zero is reserved. */ public val diskStoreValid: Boolean = blocks <= DiskStore.MAX_BLOCK } public data class Build(val major: Int, val minor: Int?) : Comparable<Build> { override fun compareTo(other: Build): Int { return compareValuesBy(this, other, Build::major, Build::minor) } override fun toString(): String { return if (minor != null) { "$major.$minor" } else { major.toString() } } internal companion object { internal fun fromPgObject(o: PGobject): Build? { val value = o.value!! require(value.length >= 2) val parts = value.substring(1, value.length - 1).split(",") require(parts.size == 2) val major = parts[0] val minor = parts[1] if (major.isEmpty()) { return null } return Build(major.toInt(), if (minor.isEmpty()) null else minor.toInt()) } } } public data class CacheSummary( val id: Int, val game: String, val environment: String, val language: String, val builds: SortedSet<Build>, val timestamp: Instant?, val sources: SortedSet<String>, @JsonUnwrapped val stats: Stats? ) public data class Cache( val id: Int, val sources: List<Source>, val updates: List<String>, val stats: Stats?, val masterIndex: Js5MasterIndex?, val checksumTable: ChecksumTable? ) public data class Source( val game: String, val environment: String, val language: String, val build: Build?, val timestamp: Instant?, val name: String?, val description: String?, val url: String? ) public data class Key( val archive: Int, val group: Int, val nameHash: Int?, val name: String?, @JsonProperty("mapsquare") val mapSquare: Int?, val key: XteaKey ) public suspend fun list(): List<CacheSummary> { return database.execute { connection -> connection.prepareStatement( """ SELECT * FROM ( SELECT c.id, g.name AS game, e.name AS environment, l.iso_code AS language, array_remove(array_agg(DISTINCT ROW(s.build_major, s.build_minor)::build ORDER BY ROW(s.build_major, s.build_minor)::build ASC), NULL) builds, MIN(s.timestamp) AS timestamp, array_remove(array_agg(DISTINCT s.name ORDER BY s.name ASC), NULL) sources, cs.valid_indexes, cs.indexes, cs.valid_groups, cs.groups, cs.valid_keys, cs.keys, cs.size, cs.blocks FROM caches c JOIN sources s ON s.cache_id = c.id JOIN game_variants v ON v.id = s.game_id JOIN games g ON g.id = v.game_id JOIN environments e ON e.id = v.environment_id JOIN languages l ON l.id = v.language_id LEFT JOIN cache_stats cs ON cs.cache_id = c.id GROUP BY c.id, g.name, e.name, l.iso_code, cs.valid_indexes, cs.indexes, cs.valid_groups, cs.groups, cs.valid_keys, cs.keys, cs.size, cs.blocks ) t ORDER BY t.game ASC, t.environment ASC, t.language ASC, t.builds[1] ASC, t.timestamp ASC """.trimIndent() ).use { stmt -> stmt.executeQuery().use { rows -> val caches = mutableListOf<CacheSummary>() while (rows.next()) { val id = rows.getInt(1) val game = rows.getString(2) val environment = rows.getString(3) val language = rows.getString(4) val builds = rows.getArray(5).array as Array<*> val timestamp = rows.getTimestamp(6)?.toInstant() @Suppress("UNCHECKED_CAST") val sources = rows.getArray(7).array as Array<String> val validIndexes = rows.getLong(8) val stats = if (!rows.wasNull()) { val indexes = rows.getLong(9) val validGroups = rows.getLong(10) val groups = rows.getLong(11) val validKeys = rows.getLong(12) val keys = rows.getLong(13) val size = rows.getLong(14) val blocks = rows.getLong(15) Stats(validIndexes, indexes, validGroups, groups, validKeys, keys, size, blocks) } else { null } caches += CacheSummary( id, game, environment, language, builds.mapNotNull { o -> Build.fromPgObject(o as PGobject) }.toSortedSet(), timestamp, sources.toSortedSet(), stats ) } caches } } } } public suspend fun get(id: Int): Cache? { return database.execute { connection -> val masterIndex: Js5MasterIndex? val checksumTable: ChecksumTable? val stats: Stats? connection.prepareStatement( """ SELECT m.format, mc.data, b.data, cs.valid_indexes, cs.indexes, cs.valid_groups, cs.groups, cs.valid_keys, cs.keys, cs.size, cs.blocks FROM caches c LEFT JOIN master_indexes m ON m.id = c.id LEFT JOIN containers mc ON mc.id = m.container_id LEFT JOIN crc_tables t ON t.id = c.id LEFT JOIN blobs b ON b.id = t.blob_id LEFT JOIN cache_stats cs ON cs.cache_id = c.id WHERE c.id = ? """.trimIndent() ).use { stmt -> stmt.setInt(1, id) stmt.executeQuery().use { rows -> if (!rows.next()) { return@execute null } val formatString = rows.getString(1) masterIndex = if (formatString != null) { Unpooled.wrappedBuffer(rows.getBytes(2)).use { compressed -> Js5Compression.uncompress(compressed).use { uncompressed -> val format = MasterIndexFormat.valueOf(formatString.uppercase()) Js5MasterIndex.readUnverified(uncompressed, format) } } } else { null } val blob = rows.getBytes(3) checksumTable = if (blob != null) { Unpooled.wrappedBuffer(blob).use { buf -> ChecksumTable.read(buf) } } else { null } val validIndexes = rows.getLong(4) stats = if (rows.wasNull()) { null } else { val indexes = rows.getLong(5) val validGroups = rows.getLong(6) val groups = rows.getLong(7) val validKeys = rows.getLong(8) val keys = rows.getLong(9) val size = rows.getLong(10) val blocks = rows.getLong(11) Stats(validIndexes, indexes, validGroups, groups, validKeys, keys, size, blocks) } } } val sources = mutableListOf<Source>() connection.prepareStatement( """ SELECT g.name, e.name, l.iso_code, s.build_major, s.build_minor, s.timestamp, s.name, s.description, s.url FROM sources s JOIN game_variants v ON v.id = s.game_id JOIN games g ON g.id = v.game_id JOIN environments e ON e.id = v.environment_id JOIN languages l ON l.id = v.language_id WHERE s.cache_id = ? ORDER BY s.name ASC """.trimIndent() ).use { stmt -> stmt.setInt(1, id) stmt.executeQuery().use { rows -> while (rows.next()) { val game = rows.getString(1) val environment = rows.getString(2) val language = rows.getString(3) var buildMajor: Int? = rows.getInt(4) if (rows.wasNull()) { buildMajor = null } var buildMinor: Int? = rows.getInt(5) if (rows.wasNull()) { buildMinor = null } val build = if (buildMajor != null) { Build(buildMajor, buildMinor) } else { null } val timestamp = rows.getTimestamp(6)?.toInstant() val name = rows.getString(7) val description = rows.getString(8) val url = rows.getString(9) sources += Source(game, environment, language, build, timestamp, name, description, url) } } } val updates = mutableListOf<String>() connection.prepareStatement( """ SELECT url FROM updates WHERE cache_id = ? """.trimIndent() ).use { stmt -> stmt.setInt(1, id) stmt.executeQuery().use { rows -> while (rows.next()) { updates += rows.getString(1) } } } Cache(id, sources, updates, stats, masterIndex, checksumTable) } } public suspend fun getFileName(id: Int): String? { return database.execute { connection -> // TODO(gpe): what if a cache is from multiple games? connection.prepareStatement( """ SELECT g.name AS game, e.name AS environment, l.iso_code AS language, array_remove(array_agg(DISTINCT ROW(s.build_major, s.build_minor)::build ORDER BY ROW(s.build_major, s.build_minor)::build ASC), NULL) builds, MIN(s.timestamp) AS timestamp FROM sources s JOIN game_variants v ON v.id = s.game_id JOIN games g ON g.id = v.game_id JOIN environments e ON e.id = v.environment_id JOIN languages l ON l.id = v.language_id WHERE s.cache_id = ? GROUP BY g.name, e.name, l.iso_code LIMIT 1 """.trimIndent() ).use { stmt -> stmt.setInt(1, id) stmt.executeQuery().use { rows -> if (!rows.next()) { return@execute null } val game = rows.getString(1) val environment = rows.getString(2) val language = rows.getString(3) val name = StringBuilder("$game-$environment-$language") val builds = rows.getArray(4).array as Array<*> for (build in builds.mapNotNull { o -> Build.fromPgObject(o as PGobject) }.toSortedSet()) { name.append("-b") name.append(build) } val timestamp = rows.getTimestamp(5) if (!rows.wasNull()) { name.append('-') name.append( timestamp.toInstant() .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")) ) } name.append("-openrs2#") name.append(id) name.toString() } } } } public fun export(id: Int, storeFactory: (Boolean) -> Store) { database.executeOnce { connection -> val legacy = connection.prepareStatement( """ SELECT id FROM crc_tables WHERE id = ? """.trimIndent() ).use { stmt -> stmt.setInt(1, id) stmt.executeQuery().use { rows -> rows.next() } } storeFactory(legacy).use { store -> if (legacy) { exportLegacy(connection, id, store) } else { export(connection, id, store) } } } } private fun export(connection: Connection, id: Int, store: Store) { connection.prepareStatement( """ SELECT archive_id, group_id, data, version FROM resolved_groups WHERE master_index_id = ? """.trimIndent() ).use { stmt -> stmt.fetchSize = BATCH_SIZE stmt.setInt(1, id) stmt.executeQuery().use { rows -> alloc.buffer(2, 2).use { versionBuf -> store.create(Js5Archive.ARCHIVESET) while (rows.next()) { val archive = rows.getInt(1) val group = rows.getInt(2) val bytes = rows.getBytes(3) val version = rows.getInt(4) val versionNull = rows.wasNull() versionBuf.clear() if (!versionNull) { versionBuf.writeShort(version) } Unpooled.wrappedBuffer(Unpooled.wrappedBuffer(bytes), versionBuf.retain()).use { buf -> store.write(archive, group, buf) // ensure the .idx file exists even if it is empty if (archive == Js5Archive.ARCHIVESET) { store.create(group) } } } } } } } private fun exportLegacy(connection: Connection, id: Int, store: Store) { connection.prepareStatement( """ SELECT index_id, file_id, data, version FROM resolved_files WHERE crc_table_id = ? """.trimIndent() ).use { stmt -> stmt.fetchSize = BATCH_SIZE stmt.setInt(1, id) stmt.executeQuery().use { rows -> alloc.buffer(2, 2).use { versionBuf -> store.create(0) while (rows.next()) { val index = rows.getInt(1) val file = rows.getInt(2) val bytes = rows.getBytes(3) val version = rows.getInt(4) val versionNull = rows.wasNull() versionBuf.clear() if (!versionNull) { versionBuf.writeShort(version) } Unpooled.wrappedBuffer(Unpooled.wrappedBuffer(bytes), versionBuf.retain()).use { buf -> store.write(index, file, buf) } } } } } } public suspend fun exportKeys(id: Int): List<Key> { return database.execute { connection -> connection.prepareStatement( """ SELECT g.archive_id, g.group_id, g.name_hash, n.name, (k.key).k0, (k.key).k1, (k.key).k2, (k.key).k3 FROM resolved_groups g JOIN keys k ON k.id = g.key_id LEFT JOIN names n ON n.hash = g.name_hash AND n.name ~ '^l(?:[0-9]|[1-9][0-9])_(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$' WHERE g.master_index_id = ? """.trimIndent() ).use { stmt -> stmt.setInt(1, id) stmt.executeQuery().use { rows -> val keys = mutableListOf<Key>() while (rows.next()) { val archive = rows.getInt(1) val group = rows.getInt(2) var nameHash: Int? = rows.getInt(3) if (rows.wasNull()) { nameHash = null } val name = rows.getString(4) val k0 = rows.getInt(5) val k1 = rows.getInt(6) val k2 = rows.getInt(7) val k3 = rows.getInt(8) val mapSquare = getMapSquare(name) keys += Key(archive, group, nameHash, name, mapSquare, XteaKey(k0, k1, k2, k3)) } keys } } } } private companion object { private const val BATCH_SIZE = 256 private val LOC_NAME_REGEX = Regex("l(\\d+)_(\\d+)") private fun getMapSquare(name: String?): Int? { if (name == null) { return null } val match = LOC_NAME_REGEX.matchEntire(name) ?: return null val x = match.groupValues[1].toInt() val z = match.groupValues[2].toInt() return (x shl 8) or z } } }
0
Kotlin
1
3
88ef8aec9270fc7aef29d7c83d1499f479ca0be1
21,303
openrs2
ISC License
app/src/main/java/com/tinaciousdesign/covidtoday/utils/SortingUtils.kt
tinacious
325,900,779
false
null
package com.tinaciousdesign.covidtoday.utils import com.tinaciousdesign.covidtoday.data.Country import com.tinaciousdesign.covidtoday.data.TabIndex fun sortCountriesForTab(countries: List<Country>, position: Int): List<Country> = when (position) { TabIndex.CASES_TODAY.ordinal -> countries.sortedByDescending { it.todayCases } TabIndex.DEATHS_TODAY.ordinal -> countries.sortedByDescending { it.todayDeaths } TabIndex.ALL_CASES.ordinal -> countries.sortedByDescending { it.cases } TabIndex.ALL_DEATHS.ordinal -> countries.sortedByDescending { it.deaths } TabIndex.RECOVERED.ordinal -> countries.sortedByDescending { it.recovered } TabIndex.ACTIVE.ordinal -> countries.sortedByDescending { it.active } TabIndex.CRITICAL.ordinal -> countries.sortedByDescending { it.critical } TabIndex.CASES_PER_MILLION.ordinal -> countries.sortedByDescending { it.casesPerOneMillion } TabIndex.DEATHS_PER_MILLION.ordinal -> countries.sortedByDescending { it.deathsPerOneMillion } else -> countries }
2
Kotlin
0
1
1e9207999e91272fe2ce919c1812f438955bbe08
1,073
CovidToday-Android
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/NavigationUnread.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.NavigationUnread: ImageVector get() { if (_navigationUnread != null) { return _navigationUnread!! } _navigationUnread = fluentIcon(name = "Regular.NavigationUnread") { fluentPath { moveTo(19.25f, 8.5f) arcToRelative(2.75f, 2.75f, 0.0f, true, false, 0.0f, -5.5f) arcToRelative(2.75f, 2.75f, 0.0f, false, false, 0.0f, 5.5f) close() moveTo(15.58f, 6.5f) arcToRelative(3.77f, 3.77f, 0.0f, false, true, 0.0f, -1.5f) lineTo(2.74f, 5.0f) lineToRelative(-0.1f, 0.01f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f) horizontalLineToRelative(12.83f) close() moveTo(21.25f, 18.0f) lineTo(2.65f, 18.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.1f, 1.5f) horizontalLineToRelative(18.6f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.1f, -1.5f) close() moveTo(2.75f, 11.5f) horizontalLineToRelative(18.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(2.75f, 13.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.49f) horizontalLineToRelative(0.1f) close() } } return _navigationUnread!! } private var _navigationUnread: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
1,802
compose-fluent-ui
Apache License 2.0
core/src/main/java/id/shaderboi/anilist/core/domain/model/anime/Anime.kt
andraantariksa
471,877,514
false
{"Kotlin": 95740}
package id.shaderboi.anilist.core.domain.model.anime data class Anime( val aired: Aired, val airing: Boolean, val background: String?, val broadcast: Broadcast?, val demographics: List<Demographic>, val duration: String, val episodes: Int?, val explicitGenres: List<ExplicitGenre>, val favorites: Int, val genres: List<Genre>, val images: Images, val licensors: List<Licensor>, val malId: Int, val members: Int, val popularity: Int, val producers: List<Producer>, val rank: Int?, val rating: String, val score: Float?, val scoredBy: Int?, val season: String?, val source: String, val status: String, val studios: List<Studio>, val synopsis: String?, val themes: List<Theme>, val title: String, val titleEnglish: String?, val titleJapanese: String?, val titleSynonyms: List<String>, val trailer: Trailer?, val type: String?, val url: String, val year: Int? )
0
Kotlin
0
2
b9ac622737b9eccab0918b0e952316f96ada5825
994
anilist
MIT License
camera/camera-video/src/androidTest/java/androidx/camera/video/VideoTestingUtil.kt
androidx
256,589,781
false
{"Kotlin": 102020198, "Java": 64486929, "C++": 9138822, "AIDL": 618356, "Python": 308339, "Shell": 184292, "TypeScript": 40586, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20307, "CMake": 18033, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.video import android.content.Context import android.media.MediaMetadataRetriever import android.net.Uri import android.os.Build import android.util.Log import android.util.Size import androidx.camera.camera2.internal.compat.quirk.DeviceQuirks as Camera2DeviceQuirks import androidx.camera.camera2.internal.compat.quirk.ExtraCroppingQuirk as Camera2ExtraCroppingQuirk import androidx.camera.camera2.pipe.integration.CameraPipeConfig import androidx.camera.camera2.pipe.integration.compat.quirk.DeviceQuirks as PipeDeviceQuirks import androidx.camera.camera2.pipe.integration.compat.quirk.ExtraCroppingQuirk as PipeExtraCroppingQuirk import androidx.camera.core.CameraInfo import androidx.camera.core.UseCase import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.video.VideoRecordEvent.Finalize import androidx.camera.video.internal.compat.quirk.DeviceQuirks import androidx.camera.video.internal.compat.quirk.StopCodecAfterSurfaceRemovalCrashMediaServerQuirk import androidx.core.util.Consumer import com.google.common.truth.Truth.assertThat import java.io.File import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.last import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.flow.transformWhile import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import org.junit.Assume.assumeFalse import org.junit.Assume.assumeTrue private const val TAG = "VideoTestingUtil" fun assumeExtraCroppingQuirk(implName: String) { assumeFalse( "Devices in ExtraCroppingQuirk will get a fixed resolution regardless of any settings", hasExtraCroppingQuirk(implName) ) } fun hasExtraCroppingQuirk(implName: String): Boolean { return (implName.contains(CameraPipeConfig::class.simpleName!!) && PipeDeviceQuirks[PipeExtraCroppingQuirk::class.java] != null) || Camera2DeviceQuirks.get(Camera2ExtraCroppingQuirk::class.java) != null } fun assumeStopCodecAfterSurfaceRemovalCrashMediaServerQuirk() { // Skip for b/293978082. For tests that will unbind the VideoCapture before stop the recording, // they should be skipped since media server will crash if the codec surface has been removed // before MediaCodec.stop() is called. assumeTrue( DeviceQuirks.get(StopCodecAfterSurfaceRemovalCrashMediaServerQuirk::class.java) == null ) } fun assumeSuccessfulSurfaceProcessing() { // Skip for b/253211491 assumeFalse( "Skip tests for Cuttlefish API 30 eglCreateWindowSurface issue", Build.MODEL.contains("Cuttlefish") && Build.VERSION.SDK_INT == 30 ) } fun assumeNotBrokenEmulator() { assumeFalse( "Skip tests for Emulator API 30 crashing issue", Build.MODEL.contains("gphone") && Build.VERSION.SDK_INT == 30 ) } fun getRotationNeeded(videoCapture: VideoCapture<Recorder>, cameraInfo: CameraInfo) = cameraInfo.getSensorRotationDegrees(videoCapture.targetRotation) fun verifyVideoResolution(context: Context, file: File, expectedResolution: Size) { MediaMetadataRetriever().useAndRelease { it.setDataSource(context, Uri.fromFile(file)) assertThat(it.getRotatedResolution()).isEqualTo(expectedResolution) } } fun isStreamSharingEnabled(useCase: UseCase) = !useCase.camera!!.hasTransform fun isSurfaceProcessingEnabled(videoCapture: VideoCapture<*>) = videoCapture.node != null || isStreamSharingEnabled(videoCapture) /** * Executes the given block in the scope of a recording [Recording] with a [SharedFlow] containing * the [VideoRecordEvent]s for that recording. */ @OptIn(ExperimentalCoroutinesApi::class) suspend inline fun PendingRecording.startWithRecording( crossinline block: suspend Recording.(SharedFlow<VideoRecordEvent>) -> Unit ) { val eventFlow = MutableSharedFlow<VideoRecordEvent>(replay = 1) val eventListener = Consumer<VideoRecordEvent> { event -> when (event) { is VideoRecordEvent.Pause, is VideoRecordEvent.Resume, is Finalize -> { // For all of these events, we need to reset the replay cache since we want // them to be the first event received by new subscribers. The same is true for // Start, but since no events should exist before start, we don't need to reset // in that case. eventFlow.resetReplayCache() } } // We still try to emit every event. This should cause the replay cache to contain one // of Start, Pause, Resume or Finalize. Status events will always only be sent after // Start or Resume, so they will only be sent to subscribers that have received one of // those events already. eventFlow.tryEmit(event) } val recording = start(CameraXExecutors.directExecutor(), eventListener) recording.use { it.apply { block(eventFlow) } } } suspend inline fun <reified T : VideoRecordEvent> SharedFlow<VideoRecordEvent>.waitForEvent( timeoutMs: Long ) = withTimeout(timeoutMs) { transformWhile { emit(it) it !is T } } suspend fun doTempRecording( context: Context, videoCapture: VideoCapture<Recorder>, minDurationMillis: Long, pauseDurationMillis: Long = 1000, withAudio: Boolean = true ): File { val tmpFile = createTempFileForRecording().apply { deleteOnExit() } videoCapture.output .prepareRecording(context, FileOutputOptions.Builder(tmpFile).build()) .apply { if (withAudio) { withAudioEnabled() } val segmentDuration = if (pauseDurationMillis > 0) { minDurationMillis / 2 } else { minDurationMillis } startWithRecording { eventFlow -> // Record until the duration matches the first segment duration withTimeout(timeMillis = 5 * minDurationMillis) { eventFlow .takeWhile { event -> event.recordingStats.recordedDurationNanos <= TimeUnit.MILLISECONDS.toNanos(segmentDuration) } .collect {} } if (pauseDurationMillis > 0) { // Pause in the middle of the recording pause() // Wait for the pause event eventFlow.waitForEvent<VideoRecordEvent.Pause>( timeoutMs = 5 * minDurationMillis ) // Stay paused for pauseDurationMillis delay(pauseDurationMillis) // Resume the recording resume() // Wait for the resume event eventFlow.waitForEvent<VideoRecordEvent.Resume>( timeoutMs = 5 * minDurationMillis ) // Record for the remaining half of the min duration time withTimeout(timeMillis = 5 * minDurationMillis) { eventFlow .takeWhile { event -> event.recordingStats.recordedDurationNanos <= TimeUnit.MILLISECONDS.toNanos(minDurationMillis) } .collect {} } } // Stop the recording stop() // Wait for the recording to finalize val finalize = eventFlow.waitForEvent<Finalize>(timeoutMs = 5 * minDurationMillis).last() as Finalize Log.i( TAG, "Recording finalized " + if (!finalize.hasError()) "successfully" else "with error ${finalize.error}" ) } } return tmpFile } // See b/177458751 suspend fun createTempFileForRecording(): File = withContext(Dispatchers.IO) { File.createTempFile("CameraX", ".tmp") }
28
Kotlin
946
5,135
3669da61ebe3541ddfab37143d5067aa19789300
9,139
androidx
Apache License 2.0
SNOWBALL/android/app/src/main/kotlin/com/projectsnowball/MainActivity.kt
icodeyou
538,717,508
false
{"Dart": 12532, "Shell": 6007, "Swift": 689, "Kotlin": 140, "Objective-C": 38}
package com.projectsnowball.projectsnowball import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
Dart
0
14
d77d2e00457979ca9e58221fa6f3cadf0e44ce87
140
hello_riverpod
MIT License
app/src/main/java/com/shema102/spacextracker/SpacexApplication.kt
shema102
294,646,424
false
null
package com.shema102.spacextracker import android.app.Application import androidx.preference.PreferenceManager import com.jakewharton.threetenabp.AndroidThreeTen import com.shema102.spacextracker.di.component.DaggerAppComponent import com.shema102.spacextracker.di.module.* import dagger.android.DispatchingAndroidInjector import dagger.android.HasAndroidInjector import javax.inject.Inject class SpacexApplication : Application(), HasAndroidInjector { @Inject lateinit var _androidInjector: DispatchingAndroidInjector<Any> override fun androidInjector() = _androidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.builder() .unitProviderModule(UnitProviderModule(this)) .themeProviderModule(ThemeProviderModule(this)) .dataSourceModule(DataSourceModule(this)) .databaseModule(DatabaseModule(this)) .launchesModule(LaunchesModule()).build().inject(this) AndroidThreeTen.init(this@SpacexApplication) PreferenceManager.setDefaultValues(this, R.xml.preferences, false) } }
0
Kotlin
0
0
129b7be95c10382cef3d3cbd3d59fbd02ae6149d
1,110
SpacexTracker
Apache License 2.0
app/src/main/java/com/chintansoni/android/architecturecomponentsblueprint/base/BaseToolbarActivity.kt
iChintanSoni
123,463,076
false
{"Kotlin": 46446}
package com.chintansoni.android.architecturecomponentsblueprint.base import android.os.Bundle import android.view.Menu import kotlinx.android.synthetic.main.layout_appbar_toolbar.* /** * Created by chint on 11/22/2017. */ abstract class BaseToolbarActivity : BaseActivity() { companion object { const val RES_NO_MENU = 0 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(toolbar) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. if (getMenuResource() != RES_NO_MENU) menuInflater.inflate(getMenuResource(), menu) return true } open fun getMenuResource(): Int { return RES_NO_MENU } }
0
Kotlin
1
4
8523b0b5a13c6bbf60f802fa8e760b29ce7f7253
834
ArchitectureComponentsBluePrint
Apache License 2.0
solution/GeoBreadcrumbs/app/src/main/java/ns/fajnet/android/geobreadcrumbs/dtos/TrackDto.kt
udragan
301,786,489
false
null
package ns.fajnet.android.geobreadcrumbs.dtos import ns.fajnet.android.geobreadcrumbs.database.Track data class TrackDto( val id: Long = 0L, val name: String = "", val startTimeMillis: Long = 0L, val duration: Long = 0L, val distance: Float = 0F, val currentSpeed: Float = 0F, val averageSpeed: Float = 0F, val maxSpeed: Float = 0F, val currentBearing: Float = 0F, val overallBearing: Float = 0F, val noOfPlaces: Int = 0, val noOfPoints: Int = 0 ) { // companion object ---------------------------------------------------------------------------- companion object { fun fromDb(track: Track) = TrackDto( track.id, track.name, track.startTimeMillis, track.endTimeMillis - track.startTimeMillis, track.distance, 0F, track.averageSpeed, track.maxSpeed, 0F, track.bearing, track.numberOfPlaces, track.numberOfPoints ) } }
0
Kotlin
0
0
10e84db78a29709d70019cd49007531ed1110070
1,093
android_geoBreadcrumbs
Apache License 2.0
ast/src/main/kotlin/gay/pizza/pork/ast/gen/NativeFunctionDescriptor.kt
GayPizzaSpecifications
680,636,847
false
{"Kotlin": 279655}
// GENERATED CODE FROM PORK AST CODEGEN package gay.pizza.pork.ast.gen import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable @SerialName("nativeFunctionDescriptor") class NativeFunctionDescriptor(val form: Symbol, val definitions: List<StringLiteral>) : Node() { override val type: NodeType = NodeType.NativeFunctionDescriptor override fun <T> visitChildren(visitor: NodeVisitor<T>): List<T> = visitor.visitAll(listOf(form), definitions) override fun <T> visit(visitor: NodeVisitor<T>): T = visitor.visitNativeFunctionDescriptor(this) override fun equals(other: Any?): Boolean { if (other !is NativeFunctionDescriptor) return false return other.form == form && other.definitions == definitions } override fun hashCode(): Int { var result = form.hashCode() result = 31 * result + definitions.hashCode() result = 31 * result + type.hashCode() return result } }
0
Kotlin
1
0
8c48c93663ef4749e793f7785d2637d67dd84e0e
953
pork
MIT License
app/src/main/java/com/wristkey/ExportActivity.kt
4f77616973
367,811,056
false
null
package com.wristkey import android.app.KeyguardManager import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.res.ColorStateList import android.graphics.Color import android.net.Uri import android.os.Bundle import android.os.Environment import android.os.Vibrator import android.provider.Settings import android.support.wearable.activity.WearableActivity import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKeys import androidx.wear.widget.BoxInsetLayout import java.io.File import java.io.FileWriter import java.io.IOException import java.text.SimpleDateFormat import java.util.* class ExportActivity : WearableActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_export) val boxinsetlayout = findViewById<BoxInsetLayout>(R.id.BoxInsetLayout) val jsonFileExportLabel = findViewById<TextView>(R.id.BitwardenImportLabel) val jsonFileExportButton = findViewById<ImageView>(R.id.BitwardenImportButton) val fileExport = findViewById<LinearLayout>(R.id.BitwardenImport) val jsonQrCodeExportLabel = findViewById<TextView>(R.id.AuthenticatorImportLabel) val qrCodeExport = findViewById<LinearLayout>(R.id.AuthenticatorImport) val jsonQrCodeExportButton = findViewById<ImageView>(R.id.AuthenticatorImportButton) val backButton = findViewById<ImageView>(R.id.BackButton) var currentAccent = appData.getString("accent", "4285F4") var currentTheme = appData.getString("theme", "000000") boxinsetlayout.setBackgroundColor(Color.parseColor("#"+currentTheme)) jsonFileExportButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#"+currentAccent)) jsonQrCodeExportButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#"+currentAccent)) backButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#"+currentAccent)) if (currentTheme == "F7F7F7") { jsonFileExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#000000"))) jsonQrCodeExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#000000"))) } else { jsonFileExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#FFFFFF"))) jsonQrCodeExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#FFFFFF"))) } if (appData.getBoolean("screen_lock", true)) { val lockscreen = getSystemService(KEYGUARD_SERVICE) as KeyguardManager if (lockscreen.isKeyguardSecure) { val i = lockscreen.createConfirmDeviceCredentialIntent("Wristkey", "App locked") startActivityForResult(i, CODE_AUTHENTICATION_VERIFICATION) } } // Begin unpacking data val exportData: String = accounts.all.values.toString() fileExport.setOnClickListener { val sdf = SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss") val currentDateandTime: String = sdf.format(Date()) val fileName = "$currentDateandTime.backup" try { val root = File(Environment.getExternalStorageDirectory(), "wristkey") if (!root.exists()) { root.mkdirs() } val file = File(root, fileName) val writer = FileWriter(file) writer.append(exportData) writer.flush() writer.close() Toast.makeText(this, "Exported successfully. Make sure to delete after use.", Toast.LENGTH_SHORT).show() } catch (e: IOException) { e.printStackTrace() val toast = Toast.makeText(this, "Couldn't write to file. Disable and re-enable storage permission.", Toast.LENGTH_LONG) toast.show() val settingsIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri: Uri = Uri.fromParts("package", packageName, null) settingsIntent.data = uri startActivity(settingsIntent) val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) finish() } val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) finish() } qrCodeExport.setOnClickListener { val intent = Intent(applicationContext, QRCodeActivity::class.java) intent.putExtra("qr_data", exportData) startActivity(intent) val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) finish() } backButton.setOnClickListener { val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) val intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (!(resultCode == RESULT_OK && requestCode == CODE_AUTHENTICATION_VERIFICATION)) { finish() } } }
3
Kotlin
2
64
e82f3ba40b5f2281a4a2afe28536d98fa789f7f3
5,689
Wristkey
MIT License
app/src/main/java/com/wristkey/ExportActivity.kt
4f77616973
367,811,056
false
null
package com.wristkey import android.app.KeyguardManager import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.res.ColorStateList import android.graphics.Color import android.net.Uri import android.os.Bundle import android.os.Environment import android.os.Vibrator import android.provider.Settings import android.support.wearable.activity.WearableActivity import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKeys import androidx.wear.widget.BoxInsetLayout import java.io.File import java.io.FileWriter import java.io.IOException import java.text.SimpleDateFormat import java.util.* class ExportActivity : WearableActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_export) val boxinsetlayout = findViewById<BoxInsetLayout>(R.id.BoxInsetLayout) val jsonFileExportLabel = findViewById<TextView>(R.id.BitwardenImportLabel) val jsonFileExportButton = findViewById<ImageView>(R.id.BitwardenImportButton) val fileExport = findViewById<LinearLayout>(R.id.BitwardenImport) val jsonQrCodeExportLabel = findViewById<TextView>(R.id.AuthenticatorImportLabel) val qrCodeExport = findViewById<LinearLayout>(R.id.AuthenticatorImport) val jsonQrCodeExportButton = findViewById<ImageView>(R.id.AuthenticatorImportButton) val backButton = findViewById<ImageView>(R.id.BackButton) var currentAccent = appData.getString("accent", "4285F4") var currentTheme = appData.getString("theme", "000000") boxinsetlayout.setBackgroundColor(Color.parseColor("#"+currentTheme)) jsonFileExportButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#"+currentAccent)) jsonQrCodeExportButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#"+currentAccent)) backButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#"+currentAccent)) if (currentTheme == "F7F7F7") { jsonFileExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#000000"))) jsonQrCodeExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#000000"))) } else { jsonFileExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#FFFFFF"))) jsonQrCodeExportLabel.setTextColor(ColorStateList.valueOf(Color.parseColor("#FFFFFF"))) } if (appData.getBoolean("screen_lock", true)) { val lockscreen = getSystemService(KEYGUARD_SERVICE) as KeyguardManager if (lockscreen.isKeyguardSecure) { val i = lockscreen.createConfirmDeviceCredentialIntent("Wristkey", "App locked") startActivityForResult(i, CODE_AUTHENTICATION_VERIFICATION) } } // Begin unpacking data val exportData: String = accounts.all.values.toString() fileExport.setOnClickListener { val sdf = SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss") val currentDateandTime: String = sdf.format(Date()) val fileName = "$currentDateandTime.backup" try { val root = File(Environment.getExternalStorageDirectory(), "wristkey") if (!root.exists()) { root.mkdirs() } val file = File(root, fileName) val writer = FileWriter(file) writer.append(exportData) writer.flush() writer.close() Toast.makeText(this, "Exported successfully. Make sure to delete after use.", Toast.LENGTH_SHORT).show() } catch (e: IOException) { e.printStackTrace() val toast = Toast.makeText(this, "Couldn't write to file. Disable and re-enable storage permission.", Toast.LENGTH_LONG) toast.show() val settingsIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri: Uri = Uri.fromParts("package", packageName, null) settingsIntent.data = uri startActivity(settingsIntent) val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) finish() } val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) finish() } qrCodeExport.setOnClickListener { val intent = Intent(applicationContext, QRCodeActivity::class.java) intent.putExtra("qr_data", exportData) startActivity(intent) val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) finish() } backButton.setOnClickListener { val vibratorService = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibratorService.vibrate(50) val intent = Intent(applicationContext, MainActivity::class.java) startActivity(intent) finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (!(resultCode == RESULT_OK && requestCode == CODE_AUTHENTICATION_VERIFICATION)) { finish() } } }
3
Kotlin
2
64
e82f3ba40b5f2281a4a2afe28536d98fa789f7f3
5,689
Wristkey
MIT License
cinescout/rating/domain/src/commonMain/kotlin/cinescout/rating/domain/model/ScreenplayIdWithPersonalRating.kt
fardavide
280,630,732
false
{"Kotlin": 2374797, "Shell": 11599}
package cinescout.rating.domain.model import cinescout.screenplay.domain.model.Rating import cinescout.screenplay.domain.model.ids.MovieIds import cinescout.screenplay.domain.model.ids.ScreenplayIds import cinescout.screenplay.domain.model.ids.TmdbScreenplayId import cinescout.screenplay.domain.model.ids.TvShowIds sealed interface ScreenplayIdWithPersonalRating { val personalRating: Rating val screenplayIds: ScreenplayIds } fun ScreenplayIdWithPersonalRating( screenplayIds: ScreenplayIds, personalRating: Rating ): ScreenplayIdWithPersonalRating = when (screenplayIds) { is MovieIds -> MovieIdWithPersonalRating(screenplayIds, personalRating) is TvShowIds -> TvShowIdWithPersonalRating(screenplayIds, personalRating) } class MovieIdWithPersonalRating( override val screenplayIds: MovieIds, override val personalRating: Rating ) : ScreenplayIdWithPersonalRating class TvShowIdWithPersonalRating( override val screenplayIds: TvShowIds, override val personalRating: Rating ) : ScreenplayIdWithPersonalRating fun List<ScreenplayIdWithPersonalRating>.ids(): List<ScreenplayIds> = map { it.screenplayIds } fun List<ScreenplayIdWithPersonalRating>.tmdbIds(): List<TmdbScreenplayId> = map { it.screenplayIds.tmdb }
18
Kotlin
2
6
f04a22b832397f22065a85af038dd15d90225cde
1,260
CineScout
Apache License 2.0
src/main/kotlin/com/bridgecrew/settings/CheckovSettingsState.kt
bridgecrewio
363,621,839
false
{"Kotlin": 72702}
package com.bridgecrew.settings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project import com.intellij.util.xmlb.XmlSerializerUtil @State( name = "com.bridgecrew.settings.CheckovSettingsState", storages = arrayOf(Storage("CheckovSettingsState.xml")) ) class CheckovSettingsState() : PersistentStateComponent<CheckovSettingsState> { var apiToken: String = "" var certificate: String = "" var prismaURL: String = "" fun getInstance(): CheckovSettingsState? { return ApplicationManager.getApplication().getService(CheckovSettingsState::class.java) } override fun getState(): CheckovSettingsState = this override fun loadState(state: CheckovSettingsState) { XmlSerializerUtil.copyBean(state, this) } }
18
Kotlin
0
3
6568176b755bcfe74d9d805d638466093b64c66b
970
checkov-jetbrains-ide
Apache License 2.0
src/serverMain/kotlin/mce/pass/frontend/Diagnostic.kt
mcenv
435,848,712
false
null
package mce.pass.frontend import mce.Id import mce.ast.surface.Eff import mce.ast.surface.Term sealed class Diagnostic { abstract val id: Id data class TermExpected(val type: Term, override val id: Id) : Diagnostic() data class VarNotFound(val name: String, override val id: Id) : Diagnostic() data class DefNotFound(val name: String, override val id: Id) : Diagnostic() data class ModNotFound(val name: String, override val id: Id) : Diagnostic() data class NotExhausted(override val id: Id) : Diagnostic() data class SizeMismatch(val expected: Int, val actual: Int, override val id: Id) : Diagnostic() data class TermMismatch(val expected: Term, val actual: Term, override val id: Id) : Diagnostic() data class ModMismatch(override val id: Id) : Diagnostic() data class SigMismatch(override val id: Id) : Diagnostic() data class EffMismatch(val expected: List<Eff>, val actual: List<Eff>, override val id: Id) : Diagnostic() data class PhaseMismatch(val expected: Elab.Phase, val actual: Elab.Phase, override val id: Id) : Diagnostic() data class RelevanceMismatch(override val id: Id) : Diagnostic() data class PolyRepr(override val id: Id) : Diagnostic() data class UnsolvedMeta(override val id: Id) : Diagnostic() }
79
Kotlin
0
15
f63905729320733d3cae95c3b51b492e94339fca
1,284
mce
MIT License
plugin/src/main/kotlin/ru/cian/huawei/publish/models/response/AccessTokenResponse.kt
cianru
234,567,962
false
null
package ru.cian.huawei.publish.models.response import com.google.gson.annotations.SerializedName internal data class AccessTokenResponse( @SerializedName("access_token") val accessToken: String?, @SerializedName("expires_in") val expiresIn: Long?, @SerializedName("ret") val ret: Ret? )
0
Kotlin
21
91
ef2f517b139e3522abde88b64f4c7cf06594cf64
313
huawei-appgallery-publish-gradle-plugin
Apache License 2.0
framework/src/main/kotlin/pt/isel/SHORT/html/element/Hr.kt
48276AntonioMarques
762,862,793
false
{"Kotlin": 290899, "CSS": 6361, "JavaScript": 2091, "HTML": 587}
package pt.isel.SHORT.html.element import pt.isel.SHORT.html.base.attribute.Attribute import pt.isel.SHORT.html.base.element.HtmlReceiver import pt.isel.SHORT.html.base.element.Tag import pt.isel.SHORT.html.base.element.VoidTag /** * Represents the HTML <hr> tag. * Description: Represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section. */ fun Tag.Hr(attributes: List<Attribute> = emptyList(), content: HtmlReceiver? = null): Tag = apply { appendChild(VoidTag("hr", attributes, scope)) }
0
Kotlin
0
1
0457515ab97855e4f42f7eeacec53f2919908918
582
short
Apache License 2.0
app/src/main/java/com/yuriy/openradio/mobile/dependencies/DependencyRegistry.kt
ChernyshovYuriy
679,720,363
false
{"Kotlin": 877885, "Java": 3552}
/* * Copyright 2022 The "Open Radio" Project. Author: Chernyshov Yuriy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yuriy.openradio.mobile.dependencies import com.yuriy.openradio.shared.dependencies.DependencyRegistryCommon import com.yuriy.openradio.shared.dependencies.FavoritesStorageDependency import com.yuriy.openradio.shared.dependencies.LatestRadioStationStorageDependency import com.yuriy.openradio.shared.model.storage.FavoritesStorage import com.yuriy.openradio.shared.model.storage.LatestRadioStationStorage import java.util.concurrent.atomic.AtomicBoolean object DependencyRegistry : FavoritesStorageDependency, LatestRadioStationStorageDependency { private lateinit var sFavoritesStorage: FavoritesStorage private lateinit var sLatestRadioStationStorage: LatestRadioStationStorage @Volatile private var sInit = AtomicBoolean(false) fun init() { if (sInit.get()) { return } DependencyRegistryCommon.injectFavoritesStorage(this) DependencyRegistryCommon.injectLatestRadioStationStorage(this) sInit.set(true) } override fun configureWith(favoritesStorage: FavoritesStorage) { sFavoritesStorage = favoritesStorage } override fun configureWith(latestRadioStationStorage: LatestRadioStationStorage) { sLatestRadioStationStorage = latestRadioStationStorage } }
13
Kotlin
0
8
7cfe3b7e55228f14df5f85b8d993db32df771d42
1,917
OpenRadio
Apache License 2.0
app/src/main/java/com/jc/antfundchart/fund/FundLabelDrawable.kt
JereChen11
647,205,981
false
null
package com.jc.antfundchart.fund import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.Typeface import android.graphics.drawable.Drawable import com.jc.antfundchart.utils.px import com.jc.antfundchart.utils.sp2px /** * @author JereChen */ class FundLabelDrawable : Drawable() { private val labelTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.LEFT typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) textSize = 16f.sp2px color = Color.parseColor("#D3D3D3") } private val paddingBottom = 10f.px private fun drawLabelTag(canvas: Canvas) { canvas.drawText( "JC基金复刻", bounds.left.toFloat(), bounds.bottom - paddingBottom, labelTextPaint ) } override fun draw(canvas: Canvas) { drawLabelTag(canvas) } override fun setAlpha(alpha: Int) { labelTextPaint.alpha = alpha } override fun setColorFilter(colorFilter: ColorFilter?) { labelTextPaint.colorFilter = colorFilter } override fun getOpacity(): Int { return when (labelTextPaint.alpha) { 0xff -> { PixelFormat.OPAQUE } 0x00 -> { PixelFormat.TRANSPARENT } else -> { PixelFormat.TRANSLUCENT } } } }
0
Kotlin
1
6
c333c0646cea6038cb269f6cacbc328b0e65cb80
1,527
AntFundChart
Apache License 2.0
kotlin-project/rekindle-book-store-aqa/domain/core/src/main/kotlin/com/rekindle/book/store/domain/configuration/endpoint/OrdersEndpoint.kt
amfibolos
845,646,691
false
{"Kotlin": 69165, "C#": 51552, "TypeScript": 47535, "JavaScript": 574}
package com.rekindle.book.store.domain.configuration.endpoint import org.aeonbits.owner.Config import org.aeonbits.owner.Config.Key import org.aeonbits.owner.Config.Sources @Sources(value = ["classpath:endpoints/orders-endpoints.properties"]) interface OrdersEndpoint : Config { @Key("orders") fun bookstores(): String @Key("order.by.tracking.id") fun orderByTrackingId(): String }
0
Kotlin
0
0
d33eada0e214304ae083bb840b3877ca41a171c9
402
rekindle-aqa
Apache License 2.0
src/main/kotlin/com/openmeteo/api/common/CellSelection.kt
open-meteo
524,706,191
false
{"Kotlin": 145141}
package com.openmeteo.api.common import kotlinx.serialization.SerialName /** * Preference how grid-cells are selected */ enum class CellSelection { @SerialName("land") Land, @SerialName("sea") Sea, @SerialName("nearest") Nearest, }
6
Kotlin
1
20
c342acd53559fe92b54821d6603709fee645e2d0
260
open-meteo-api-kotlin
MIT License
src/main/kotlin/managers/user/IUserManager.kt
msvetkov
223,715,227
true
{"Kotlin": 80517}
package managers.user import controllers.auth.models.AuthData import managers.database.dao.models.HibUser import managers.user.models.User interface IUserManager { /** * Method creates [user] to database and sends its id(that also set in [user]) or -1(error case, id not set in [user]) * * @return id of user in db or -1 (error) */ fun createUser(user: HibUser): Int /** * Method tries to find user by [id] in database * * @return founded user or null */ fun getUser(id: Int): User? /** * Method tries to find user by [AuthData] in database * * @return founded user or null */ fun getUser(authData: AuthData): User? /** * Method tries to find user by [token] in database * * @return founded user or null */ fun getUserByToken(token: String): User? /** * Method tries to find user by [email] in database * * @return founded user or null */ fun getUserByEmail(email: String): User? /** * Method saves [user] of User to database and sends its updated model or null * * @return updated user or null(error) */ fun saveUser(user: HibUser): User? /** * Method delete [user] of User in database */ fun removeUser(user: HibUser) /** * Method get not confirmed users * * @return list of [User] */ fun getListOfNotConfirmed(): List<User> }
0
Kotlin
0
0
54d88c531a7ae6f3a92932bf3edfbe7cb9028d72
1,452
PhysicsLeti-Backend
MIT License
src/main/kotlin/lirand/api/dsl/command/types/PrefixedType.kt
dyam0
453,766,342
false
null
package lirand.api.dsl.command.types import com.mojang.brigadier.StringReader import com.mojang.brigadier.arguments.ArgumentType import com.mojang.brigadier.builder.ArgumentBuilder import com.mojang.brigadier.context.CommandContext import com.mojang.brigadier.suggestion.Suggestions import com.mojang.brigadier.suggestion.SuggestionsBuilder import lirand.api.dsl.command.builders.ContinuableNodeDSLBuilder import lirand.api.dsl.command.types.exceptions.ChatCommandExceptionType import lirand.api.dsl.command.types.exceptions.ChatCommandSyntaxException import lirand.api.dsl.command.types.extensions.until import lirand.api.extensions.server.nmsNumberVersion import lirand.api.extensions.server.nmsVersion import net.md_5.bungee.api.chat.TranslatableComponent import org.bukkit.command.CommandSender import java.util.concurrent.CompletableFuture fun <T> ContinuableNodeDSLBuilder<*>.prefixed( prefixedType: Pair<String, ArgumentType<T>>, unknownPrefixExceptionType: ChatCommandExceptionType = PrefixedType.defaultExceptionType ) = PrefixedType(prefixedType.first, prefixedType.second, unknownPrefixExceptionType) open class PrefixedType<T>( val prefix: String, open val type: ArgumentType<T>, open val unknownPrefixExceptionType: ChatCommandExceptionType = defaultExceptionType ) : Type<T> { val prefixForm = "${prefix.lowercase()}:" /** * Returns the result of parsing argument of the provided [type] if it has [prefix]. * * @param reader the reader * @return a [T] parsed by [type]. * @throws ChatCommandSyntaxException if argument hasn't been parsed by [type] or doesn't have [prefix]. */ override fun parse(reader: StringReader): T { val prefix = reader.until(':').lowercase() if (reader.canRead()) reader.skip() else throw unknownPrefixExceptionType.createWithContext(reader, prefix) if (prefix == this.prefix.lowercase()) return type.parse(reader) else throw unknownPrefixExceptionType.createWithContext(reader, prefix) } /** * Returns the result of type's [ArgumentType.listSuggestions] if [prefix] was provided. * If not returns [prefix]. * * @param S the type of the source * @param context the context * @param builder the builder * @return the result of type's [ArgumentType.listSuggestions] if [prefix] was provided */ override fun <S> listSuggestions( context: CommandContext<S>, builder: SuggestionsBuilder ): CompletableFuture<Suggestions> { if (builder.remaining.startsWith(prefixForm)) { return type.listSuggestions(context, SuggestionsBuilder(builder.input, builder.start + prefixForm.length)) } if (prefixForm.startsWith(builder.remaining)) { builder.suggest(prefixForm) } return builder.buildFuture() } override fun getExamples(): List<String> = type.examples.map { "$prefix:$it" } override fun map(): ArgumentType<*> { return argumentTag } companion object { val argumentTag = run { val nmsPackage = if (nmsNumberVersion < 17) "net.minecraft.server.v$nmsVersion" else "net.minecraft.commands.arguments.item" val clazz = Class.forName("$nmsPackage.ArgumentTag") clazz.getConstructor() .newInstance() as ArgumentType<*> } internal val defaultExceptionType = ChatCommandExceptionType { TranslatableComponent("argument.id.unknown", it[0]) } } }
0
Kotlin
1
12
96cc59d4fbf0db90863499db798907a915e90237
3,300
LirandAPI
MIT License
src/me/anno/config/VersionFeatures.kt
AntonioNoack
456,513,348
false
null
package me.anno.config import me.anno.io.utils.StringMap @Suppress("unused") abstract class VersionFeatures(val oldVersion: Int) { abstract fun addNewPackages(config: StringMap) fun addVersion(introductionVersion: Int, modify: () -> Unit) { if (oldVersion < introductionVersion) { modify() } } }
0
null
3
9
566e183d43bff96ee3006fecf0142e6d20828857
338
RemsEngine
Apache License 2.0
app/src/main/java/io/agora/flat/ui/activity/base/BaseActivity.kt
zhujiaqing
432,065,747
true
{"Kotlin": 513623, "Shell": 495}
package io.agora.flat.ui.activity.base import android.content.Context import androidx.appcompat.app.AppCompatActivity import io.agora.flat.common.android.LanguageManager open class BaseActivity : AppCompatActivity() { override fun attachBaseContext(newBase: Context) { super.attachBaseContext(LanguageManager.onAttach(newBase)) } }
0
null
0
0
33a98c11d04d85dcdcb290eb29e2809cad5d0622
349
flat-android
MIT License
app/src/main/java/com/example/bottomsheetsample/bottomsheet/count/CountBottomSheet.kt
taehee28
724,967,666
false
{"Kotlin": 14866}
package com.example.bottomsheetsample.bottomsheet.count import android.util.Log import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import com.example.bottomsheetsample.R import com.example.bottomsheetsample.bottomsheet.BaseBottomSheetDialog import com.example.bottomsheetsample.bottomsheet.SheetScreenEvent import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch /** * 예제로 만든 바텀 시트 다이얼로그. * 바텀 시트 위에 얹어지는 Fragment들과 ViewModel을 통해서 데이터를 주고받음. */ class CountBottomSheet : BaseBottomSheetDialog() { private val viewModel: CountSheetViewModel by viewModels() // private val viewModel: CountSheetViewModel by activityViewModels() override val navGraphId: Int get() = R.navigation.count_bottom_sheet_nav_graph override fun initView() { observeScreenFlow() } private fun observeScreenFlow() { lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel .screenFlow .distinctUntilChanged() .collectLatest { Log.d("CountBottomSheet", ">> screen : ${it.name}") if (it == SheetScreenEvent.CLOSE) { [email protected]() } else { changeScreen(screen = it) } } } } } private fun changeScreen(screen: SheetScreenEvent) { when (screen) { SheetScreenEvent.NEXT -> { // 스텝이 여러개인 경우 화면마다 다음으로 넘어가는 action의 아이디를 통일시켜서 // 어떤 화면이라도 같은 action 아이디를 사용하도록 하기 navController.navigate(R.id.action_firstCountSheetFragment_to_secondCountSheetFragment) } SheetScreenEvent.PREV -> { navController.popBackStack() } else -> throw IllegalArgumentException("없는 화면") } } }
0
Kotlin
0
0
08ac44b8b08d2871f1a962e4c456a37222e0cbbb
2,281
BottomSheetSample
MIT License
app/src/main/java/com/example/kfeedreader/ItemAdapter.kt
RubensZaes
252,579,030
false
null
package com.example.kfeedreader import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList class ItemAdapter(val list: ArrayList<MainActivity.Item>, val context: Context) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() { class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { val tituloTextView: TextView = view.findViewById(R.id.tituloTextView) val autorTextView: TextView = view.findViewById(R.id.autorTextView) val dataTextView: TextView = view.findViewById(R.id.dataTextView) val imagemTextView: ImageView = view.findViewById(R.id.imagemImageView) val verMaisButton: Button = view.findViewById(R.id.verMaisButton) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val v = LayoutInflater.from(parent?.context).inflate(R.layout.item_list, parent, false) val ivh = ItemViewHolder(v) return ivh } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { holder?.tituloTextView?.text = list[position].titulo holder?.autorTextView?.text = list[position].autor holder?.dataTextView?.text = SimpleDateFormat("dd/MM/yyyy", Locale("pt", "BR")).format(Date(list[position].data)) holder?.verMaisButton?.setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, list[position].link) context.startActivity(intent) } DownloadImageTask(holder?.imagemTextView!!).execute(list[position].imagem) } override fun getItemCount(): Int = list.size }
0
Kotlin
0
0
d7d03297f3eca387824a79f1004fdafa20ec37fc
1,893
KFeedReader-AndroidPro-
MIT License
app/src/main/kotlin/com/gmail/yaroslavlancelot/technarium/core/presentation/MainActivity.kt
YaroslavHavrylovych
228,385,485
false
null
package com.gmail.yaroslavlancelot.technarium.core.presentation import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.compose.material.MaterialTheme import com.gmail.yaroslavlancelot.technarium.core.presentation.composables.MainScreen import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private val mainViewModel: MainViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { MainScreen(mainViewModel) } } } }
0
Kotlin
0
1
6fffd4bede6927009760bbca82810695e1203926
743
technical_news
Apache License 2.0
core/src/main/kotlin/cohort/CohortDescription.kt
amplitude
519,022,661
false
null
package com.amplitude.cohort import kotlinx.serialization.Serializable @Serializable data class CohortDescription( val id: String, val lastComputed: Long, val size: Int )
0
Kotlin
1
0
5fc1b86922ad2f381b39ce89d094bd25051db62a
185
evaluation-proxy
MIT License
src/main/kotlin/dev/crashteam/repricer/client/ke/KazanExpressLkClient.kt
crashteamdev
513,840,113
false
{"Kotlin": 371717, "Java": 188503, "Dockerfile": 613, "PLpgSQL": 483}
package dev.crashteam.repricer.client.ke import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import dev.crashteam.repricer.client.ke.model.ProxyRequestBody import dev.crashteam.repricer.client.ke.model.ProxyRequestContext import dev.crashteam.repricer.client.ke.model.StyxResponse import dev.crashteam.repricer.client.ke.model.lk.* import dev.crashteam.repricer.config.properties.ServiceProperties import dev.crashteam.repricer.service.util.RandomUserAgent import mu.KotlinLogging import org.springframework.core.ParameterizedTypeReference import org.springframework.http.* import org.springframework.stereotype.Component import org.springframework.util.LinkedMultiValueMap import org.springframework.web.client.RestTemplate import org.springframework.web.client.exchange import java.net.URLEncoder import java.util.* import kotlin.collections.HashMap private val log = KotlinLogging.logger {} @Component class KazanExpressLkClient( private val lkRestTemplate: RestTemplate, private val restTemplate: RestTemplate, private val serviceProperties: ServiceProperties, ) : KazanExpressClient { override fun getAccountShops(userId: String, userToken: String): List<AccountShop> { val headers = HttpHeaders().apply { set("Authorization", "Bearer $userToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<List<AccountShop>>( "https://api.business.kazanexpress.ru/api/seller/shop/", HttpMethod.GET, HttpEntity<Void>(headers) ) return handleResponse(responseEntity) } override fun getAccountShopItems( userId: String, userToken: String, shopId: Long, page: Int ): List<AccountShopItem> { val headers = HttpHeaders().apply { set("Authorization", "Bearer $userToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<AccountShopItemWrapper>( "https://api.business.kazanexpress.ru/api/seller/shop/$shopId/product/getProducts?" + "searchQuery=&filter=active&sortBy=id&order=descending&size=99&page=$page", HttpMethod.GET, HttpEntity<Void>(headers) ) return handleResponse(responseEntity).productList } override fun changeAccountShopItemPrice( userId: String, userToken: String, shopId: Long, payload: ShopItemPriceChangePayload ): Boolean { val headers = HttpHeaders().apply { set("Authorization", "Bearer $userToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set("Content-Type", MediaType.APPLICATION_JSON_VALUE) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<Any>( "https://api.business.kazanexpress.ru/api/seller/shop/$shopId/product/sendSkuData", HttpMethod.POST, HttpEntity<ShopItemPriceChangePayload>(payload, headers) ) if (!responseEntity.statusCode.is2xxSuccessful) { log.warn { "Bad response while trying to change item price." + " statusCode=${responseEntity.statusCode};responseBody=${responseEntity.body};" + "requestBody=${jacksonObjectMapper().writeValueAsString(payload)}" } } return responseEntity.statusCode.is2xxSuccessful } override fun getProductInfo(userId: String, userToken: String, shopId: Long, productId: Long): AccountProductInfo { val headers = HttpHeaders().apply { set("Authorization", "Bearer $userToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<AccountProductInfo>( "https://api.business.kazanexpress.ru/api/seller/shop/$shopId/product?productId=$productId", HttpMethod.GET, HttpEntity<Void>(headers) ) return handleResponse(responseEntity) } override fun getProductDescription( userId: String, userToken: String, shopId: Long, productId: Long ): AccountProductDescription { val headers = HttpHeaders().apply { set("Authorization", "Bearer $userToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<AccountProductDescription>( "https://api.business.kazanexpress.ru/api/seller/shop/$shopId/product/$productId/description-response", HttpMethod.GET, HttpEntity<Void>(headers) ) return handleResponse(responseEntity) } override fun auth(userId: String, username: String, password: String): AuthResponse { val map = HashMap<String, String>().apply { set("grant_type", "password") set("username", username) set("password", password) } val urlEncodedString = getUrlEncodedString(map) val proxyRequestBody = ProxyRequestBody( url = "https://api.business.kazanexpress.ru/api/oauth/token", httpMethod = "POST", context = listOf( ProxyRequestContext( key = "headers", value = mapOf( "User-Agent" to RandomUserAgent.getRandomUserAgent(), "Authorization" to "Basic $basicAuthToken", "Content-Type" to MediaType.APPLICATION_FORM_URLENCODED_VALUE, USER_ID_HEADER to userId ) ), ProxyRequestContext("content", Base64.getEncoder().encodeToString(urlEncodedString.encodeToByteArray())) ) ) val responseType: ParameterizedTypeReference<StyxResponse<AuthResponse>> = object : ParameterizedTypeReference<StyxResponse<AuthResponse>>() {} val styxResponse = restTemplate.exchange( "${serviceProperties.proxy!!.url}/v2/proxy", HttpMethod.POST, HttpEntity<ProxyRequestBody>(proxyRequestBody), responseType ).body return handleProxyResponse(styxResponse!!)!! } override fun refreshAuth(userId: String, refreshToken: String): ResponseEntity<AuthResponse> { val map = LinkedMultiValueMap<Any, Any>().apply { set("grant_type", "refresh_token") set("refresh_token", refreshToken) } val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_FORM_URLENCODED set("Authorization", "Basic $basicAuthToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<AuthResponse>( "https://api.business.kazanexpress.ru/api/oauth/token", HttpMethod.POST, HttpEntity(map, headers) ) return responseEntity } override fun checkToken(userId: String, token: String): ResponseEntity<CheckTokenResponse> { val map = LinkedMultiValueMap<Any, Any>().apply { set("token", token) } val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_FORM_URLENCODED set("Authorization", "Basic $basicAuthToken") set("User-Agent", RandomUserAgent.getRandomUserAgent()) set(USER_ID_HEADER, userId) } val responseEntity = lkRestTemplate.exchange<CheckTokenResponse>( "https://api.business.kazanexpress.ru/api/auth/seller/check_token", HttpMethod.POST, HttpEntity(map, headers) ) return responseEntity } private fun <T> handleResponse(responseEntity: ResponseEntity<T>): T { val statusCode = responseEntity.statusCode val isError = statusCode.series() == HttpStatus.Series.CLIENT_ERROR || statusCode.series() == HttpStatus.Series.SERVER_ERROR if (isError) { throw KazanExpressClientException(statusCode.value()) } return responseEntity.body!! } private fun <T> handleProxyResponse(styxResponse: StyxResponse<T>): T? { val originalStatus = styxResponse.originalStatus val statusCode = HttpStatus.resolve(originalStatus) val isError = statusCode == null || statusCode.series() == HttpStatus.Series.CLIENT_ERROR || statusCode.series() == HttpStatus.Series.SERVER_ERROR if (isError) { throw KazanExpressProxyClientException( originalStatus, styxResponse.body.toString(), "Bad response. StyxStatus=${styxResponse.code}; Status=$originalStatus; Body=${styxResponse.body.toString()}" ) } if (styxResponse.code != 0) { log.warn { "Bad proxy status - ${styxResponse.code}" } } return styxResponse.body } private fun getUrlEncodedString(params: HashMap<String, String>): String { val result = StringBuilder() var first = true for ((key, value) in params) { if (first) first = false else result.append("&") result.append(URLEncoder.encode(key, "UTF-8")) result.append("=") result.append(URLEncoder.encode(value, "UTF-8")) } return result.toString() } companion object { const val basicAuthToken = "a2F6YW5leHByZXNzOnNlY3JldEtleQ==" const val USER_ID_HEADER = "X-USER-ID" const val USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36" } }
11
Kotlin
0
0
93bb127260ac9a9ed1f2cc295865a358dd989c50
10,309
ke-space
Apache License 2.0
instrumented/nightly-tests/src/main/kotlin/com/datadog/android/nightly/activities/Constants.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.nightly.activities internal const val HUNDRED_PERCENT = 100f internal const val FAKE_RESOURCE_DOWNLOADED_BYTES = 200L internal const val CRASH_DELAY_MS = 1000L
33
Kotlin
39
86
bcf0d12fd978df4e28848b007d5fcce9cb97df1c
440
dd-sdk-android
Apache License 2.0
core/src/main/kotlin/net/corda/core/Utils.kt
arnabmitra
97,902,540
true
{"Kotlin": 3302152, "Java": 182903, "Groovy": 27918, "Shell": 320, "Batchfile": 106}
// TODO Move out the Kotlin specific stuff into a separate file @file:JvmName("Utils") package net.corda.core import com.google.common.base.Throwables import com.google.common.io.ByteStreams import com.google.common.util.concurrent.* import net.corda.core.crypto.SecureHash import net.corda.core.crypto.sha256 import net.corda.core.internal.createDirectories import net.corda.core.internal.div import net.corda.core.internal.write import org.slf4j.Logger import rx.Observable import rx.Observer import rx.subjects.PublishSubject import rx.subjects.UnicastSubject import java.io.* import java.math.BigDecimal import java.nio.file.Files import java.nio.file.Path import java.time.Duration import java.util.concurrent.CompletableFuture import java.util.concurrent.ExecutionException import java.util.concurrent.Future import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import java.util.zip.Deflater import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream import kotlin.concurrent.withLock // TODO: Review by EOY2016 if we ever found these utilities helpful. val Int.bd: BigDecimal get() = BigDecimal(this) val Double.bd: BigDecimal get() = BigDecimal(this) val String.bd: BigDecimal get() = BigDecimal(this) val Long.bd: BigDecimal get() = BigDecimal(this) fun String.abbreviate(maxWidth: Int): String = if (length <= maxWidth) this else take(maxWidth - 1) + "…" /** Like the + operator but throws an exception in case of integer overflow. */ infix fun Int.checkedAdd(b: Int) = Math.addExact(this, b) /** Like the + operator but throws an exception in case of integer overflow. */ @Suppress("unused") infix fun Long.checkedAdd(b: Long) = Math.addExact(this, b) /** Same as [Future.get] but with a more descriptive name, and doesn't throw [ExecutionException], instead throwing its cause */ fun <T> Future<T>.getOrThrow(timeout: Duration? = null): T { return try { if (timeout == null) get() else get(timeout.toNanos(), TimeUnit.NANOSECONDS) } catch (e: ExecutionException) { throw e.cause!! } } fun <V> future(block: () -> V): Future<V> = CompletableFuture.supplyAsync(block) fun <F : ListenableFuture<*>, V> F.then(block: (F) -> V) = addListener(Runnable { block(this) }, MoreExecutors.directExecutor()) fun <U, V> Future<U>.match(success: (U) -> V, failure: (Throwable) -> V): V { return success(try { getOrThrow() } catch (t: Throwable) { return failure(t) }) } fun <U, V, W> ListenableFuture<U>.thenMatch(success: (U) -> V, failure: (Throwable) -> W) = then { it.match(success, failure) } fun ListenableFuture<*>.andForget(log: Logger) = then { it.match({}, { log.error("Background task failed:", it) }) } @Suppress("UNCHECKED_CAST") // We need the awkward cast because otherwise F cannot be nullable, even though it's safe. infix fun <F, T> ListenableFuture<F>.map(mapper: (F) -> T): ListenableFuture<T> = Futures.transform(this, { (mapper as (F?) -> T)(it) }) infix fun <F, T> ListenableFuture<F>.flatMap(mapper: (F) -> ListenableFuture<T>): ListenableFuture<T> = Futures.transformAsync(this) { mapper(it!!) } /** Executes the given block and sets the future to either the result, or any exception that was thrown. */ inline fun <T> SettableFuture<T>.catch(block: () -> T) { try { set(block()) } catch (t: Throwable) { setException(t) } } fun <A> ListenableFuture<out A>.toObservable(): Observable<A> { return Observable.create { subscriber -> thenMatch({ subscriber.onNext(it) subscriber.onCompleted() }, { subscriber.onError(it) }) } } /** Returns the index of the given item or throws [IllegalArgumentException] if not found. */ fun <T> List<T>.indexOfOrThrow(item: T): Int { val i = indexOf(item) require(i != -1) return i } /** * Returns the single element matching the given [predicate], or `null` if element was not found, * or throws if more than one element was found. */ fun <T> Iterable<T>.noneOrSingle(predicate: (T) -> Boolean): T? { var single: T? = null for (element in this) { if (predicate(element)) { if (single == null) { single = element } else throw IllegalArgumentException("Collection contains more than one matching element.") } } return single } /** Returns single element, or `null` if element was not found, or throws if more than one element was found. */ fun <T> Iterable<T>.noneOrSingle(): T? { var single: T? = null for (element in this) { if (single == null) { single = element } else throw IllegalArgumentException("Collection contains more than one matching element.") } return single } /** Returns a random element in the list, or null if empty */ fun <T> List<T>.randomOrNull(): T? { if (size <= 1) return firstOrNull() val randomIndex = (Math.random() * size).toInt() return get(randomIndex) } /** Returns a random element in the list matching the given predicate, or null if none found */ fun <T> List<T>.randomOrNull(predicate: (T) -> Boolean) = filter(predicate).randomOrNull() inline fun elapsedTime(block: () -> Unit): Duration { val start = System.nanoTime() block() val end = System.nanoTime() return Duration.ofNanos(end - start) } // TODO: Add inline back when a new Kotlin version is released and check if the java.lang.VerifyError // returns in the IRSSimulationTest. If not, commit the inline back. fun <T> logElapsedTime(label: String, logger: Logger? = null, body: () -> T): T { // Use nanoTime as it's monotonic. val now = System.nanoTime() try { return body() } finally { val elapsed = Duration.ofNanos(System.nanoTime() - now).toMillis() if (logger != null) logger.info("$label took $elapsed msec") else println("$label took $elapsed msec") } } fun <T> Logger.logElapsedTime(label: String, body: () -> T): T = logElapsedTime(label, this, body) /** * A threadbox is a simple utility that makes it harder to forget to take a lock before accessing some shared state. * Simply define a private class to hold the data that must be grouped under the same lock, and then pass the only * instance to the ThreadBox constructor. You can now use the [locked] method with a lambda to take the lock in a * way that ensures it'll be released if there's an exception. * * Note that this technique is not infallible: if you capture a reference to the fields in another lambda which then * gets stored and invoked later, there may still be unsafe multi-threaded access going on, so watch out for that. * This is just a simple guard rail that makes it harder to slip up. * * Example: * * private class MutableState { var i = 5 } * private val state = ThreadBox(MutableState()) * * val ii = state.locked { i } */ class ThreadBox<out T>(val content: T, val lock: ReentrantLock = ReentrantLock()) { inline fun <R> locked(body: T.() -> R): R = lock.withLock { body(content) } inline fun <R> alreadyLocked(body: T.() -> R): R { check(lock.isHeldByCurrentThread, { "Expected $lock to already be locked." }) return body(content) } fun checkNotLocked() = check(!lock.isHeldByCurrentThread) } /** * Given a path to a zip file, extracts it to the given directory. */ fun extractZipFile(zipFile: Path, toDirectory: Path) = extractZipFile(Files.newInputStream(zipFile), toDirectory) /** * Given a zip file input stream, extracts it to the given directory. */ fun extractZipFile(inputStream: InputStream, toDirectory: Path) { val normalisedDirectory = toDirectory.normalize().createDirectories() ZipInputStream(BufferedInputStream(inputStream)).use { while (true) { val e = it.nextEntry ?: break val outPath = (normalisedDirectory / e.name).normalize() // Security checks: we should reject a zip that contains tricksy paths that try to escape toDirectory. check(outPath.startsWith(normalisedDirectory)) { "ZIP contained a path that resolved incorrectly: ${e.name}" } if (e.isDirectory) { outPath.createDirectories() continue } outPath.write { out -> ByteStreams.copy(it, out) } it.closeEntry() } } } /** Convert a [ByteArrayOutputStream] to [InputStreamAndHash]. */ fun ByteArrayOutputStream.getInputStreamAndHash(baos: ByteArrayOutputStream): InputStreamAndHash { val bytes = baos.toByteArray() return InputStreamAndHash(ByteArrayInputStream(bytes), bytes.sha256()) } data class InputStreamAndHash(val inputStream: InputStream, val sha256: SecureHash.SHA256) { companion object { /** * Get a valid InputStream from an in-memory zip as required for some tests. The zip consists of a single file * called "z" that contains the given content byte repeated the given number of times. * Note that a slightly bigger than numOfExpectedBytes size is expected. */ @Throws(IllegalArgumentException::class) @JvmStatic fun createInMemoryTestZip(numOfExpectedBytes: Int, content: Byte): InputStreamAndHash { require(numOfExpectedBytes > 0) val baos = ByteArrayOutputStream() ZipOutputStream(baos).use { zos -> val arraySize = 1024 val bytes = ByteArray(arraySize) { content } val n = (numOfExpectedBytes - 1) / arraySize + 1 // same as Math.ceil(numOfExpectedBytes/arraySize). zos.setLevel(Deflater.NO_COMPRESSION) zos.putNextEntry(ZipEntry("z")) for (i in 0 until n) { zos.write(bytes, 0, arraySize) } zos.closeEntry() } return baos.getInputStreamAndHash(baos) } } } // TODO: Generic csv printing utility for clases. val Throwable.rootCause: Throwable get() = Throwables.getRootCause(this) /** * Returns an Observable that buffers events until subscribed. * @see UnicastSubject */ fun <T> Observable<T>.bufferUntilSubscribed(): Observable<T> { val subject = UnicastSubject.create<T>() val subscription = subscribe(subject) return subject.doOnUnsubscribe { subscription.unsubscribe() } } /** * Copy an [Observer] to multiple other [Observer]s. */ fun <T> Observer<T>.tee(vararg teeTo: Observer<T>): Observer<T> { val subject = PublishSubject.create<T>() subject.subscribe(this) teeTo.forEach { subject.subscribe(it) } return subject } /** * Returns a [ListenableFuture] bound to the *first* item emitted by this Observable. The future will complete with a * NoSuchElementException if no items are emitted or any other error thrown by the Observable. If it's cancelled then * it will unsubscribe from the observable. */ fun <T> Observable<T>.toFuture(): ListenableFuture<T> = ObservableToFuture(this) private class ObservableToFuture<T>(observable: Observable<T>) : AbstractFuture<T>(), Observer<T> { private val subscription = observable.first().subscribe(this) override fun onNext(value: T) { set(value) } override fun onError(e: Throwable) { setException(e) } override fun cancel(mayInterruptIfRunning: Boolean): Boolean { subscription.unsubscribe() return super.cancel(mayInterruptIfRunning) } override fun onCompleted() {} } /** Return the sum of an Iterable of [BigDecimal]s. */ fun Iterable<BigDecimal>.sum(): BigDecimal = fold(BigDecimal.ZERO) { a, b -> a + b } fun <T> Class<T>.checkNotUnorderedHashMap() { if (HashMap::class.java.isAssignableFrom(this) && !LinkedHashMap::class.java.isAssignableFrom(this)) { throw NotSerializableException("Map type $this is unstable under iteration. Suggested fix: use LinkedHashMap instead.") } } fun Class<*>.requireExternal(msg: String = "Internal class") = require(!name.startsWith("net.corda.node.") && !name.contains(".internal.")) { "$msg: $name" }
0
Kotlin
0
0
b6902aada698404de7b83192fe2b5af35294238b
12,184
corda
Apache License 2.0
intellij-plugin/src/main/kotlin/com/apollographql/ijplugin/inspection/ApolloOneOfGraphQLViolationInspection.kt
apollographql
69,469,299
false
{"Kotlin": 3463807, "Java": 198208, "CSS": 34435, "HTML": 5844, "JavaScript": 1191}
package com.apollographql.ijplugin.inspection import com.apollographql.ijplugin.ApolloBundle import com.apollographql.ijplugin.navigation.findFragmentSpreads import com.apollographql.ijplugin.util.rawType import com.apollographql.ijplugin.util.resolve import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemsHolder import com.intellij.lang.jsgraphql.psi.GraphQLArgument import com.intellij.lang.jsgraphql.psi.GraphQLArrayValue import com.intellij.lang.jsgraphql.psi.GraphQLFragmentDefinition import com.intellij.lang.jsgraphql.psi.GraphQLInputObjectTypeDefinition import com.intellij.lang.jsgraphql.psi.GraphQLInputValueDefinition import com.intellij.lang.jsgraphql.psi.GraphQLNonNullType import com.intellij.lang.jsgraphql.psi.GraphQLNullValue import com.intellij.lang.jsgraphql.psi.GraphQLObjectField import com.intellij.lang.jsgraphql.psi.GraphQLObjectValue import com.intellij.lang.jsgraphql.psi.GraphQLTypedOperationDefinition import com.intellij.lang.jsgraphql.psi.GraphQLVariable import com.intellij.lang.jsgraphql.psi.GraphQLVariableDefinition import com.intellij.lang.jsgraphql.psi.GraphQLVisitor import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.parentOfType class ApolloOneOfGraphQLViolationInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : GraphQLVisitor() { override fun visitObjectValue(o: GraphQLObjectValue) { super.visitObjectValue(o) val parent = if (o.parent is GraphQLArrayValue) o.parent.parent else o.parent val inputValueDefinition: GraphQLInputValueDefinition = (parent as? GraphQLArgument ?: parent as? GraphQLObjectField) ?.resolve() ?: return val graphQLTypeName = inputValueDefinition.type?.rawType ?: return val graphQLInputObjectTypeDefinition: GraphQLInputObjectTypeDefinition = graphQLTypeName.resolve() ?: return val isOneOf = graphQLInputObjectTypeDefinition.directives.any { it.name == "oneOf" } if (!isOneOf) return if (o.objectFieldList.size != 1) { holder.registerProblem(o, ApolloBundle.message("inspection.oneOfGraphQLViolation.reportText.oneFieldMustBeSupplied", graphQLTypeName.name!!)) } else { val field = o.objectFieldList.first() when (val value = field.value) { is GraphQLNullValue -> { holder.registerProblem(o, ApolloBundle.message("inspection.oneOfGraphQLViolation.reportText.fieldMustNotBeNull", field.name!!, graphQLTypeName.name!!)) } is GraphQLVariable -> { // Look for the parent operation - if there isn't one, we're in a fragment: search for an operation using this fragment val operationDefinition = field.parentOfType<GraphQLTypedOperationDefinition>() ?: field.parentOfType<GraphQLFragmentDefinition>()?.let { fragmentParent -> findFragmentSpreads(fragmentParent.project) { it.nameIdentifier.reference?.resolve() == fragmentParent.nameIdentifier }.firstOrNull() ?.parentOfType<GraphQLTypedOperationDefinition>() } ?: return val variableDefinition: GraphQLVariableDefinition = operationDefinition.variableDefinitions ?.variableDefinitions?.firstOrNull { it.variable.name == value.name } ?: return if (variableDefinition.type !is GraphQLNonNullType) { holder.registerProblem( o, ApolloBundle.message( "inspection.oneOfGraphQLViolation.reportText.variableMustBeNonNullType", value.name!!, variableDefinition.type?.text ?: "Unknown" ) ) } } } } } } } }
135
Kotlin
651
3,750
174cb227efe76672cf2beac1affc7054f6bb2892
3,969
apollo-kotlin
MIT License
common/src/main/kotlin/nullversionnova/musicscript/script/Songs.kt
null-version-nova
719,239,793
false
{"Kotlin": 23203, "Java": 16254}
package nullversionnova.musicscript.script import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonArray import com.google.gson.JsonObject import nullversionnova.musicscript.MusicScript import java.io.File object Songs { val songs = mutableListOf<Song>() fun init() { val file = File("${ MusicScript.DATA_PATH}/songs.json").readText() val gson = Gson() val builder = GsonBuilder() builder.registerTypeAdapter(Song::class.java,Song.SongDeserializer()) val obj = gson.fromJson(file,JsonArray::class.java) for (i in obj) { songs.add(gson.fromJson(i,Song::class.java)) } } fun hasSong(name: String) : Boolean { for (i in songs) { if (i.name == name) { return true } } return false } fun getSong(name: String) : Song? { for (i in songs) { if (i.name == name) { return i } } return null } }
0
Kotlin
0
1
7ffbee1006fb0c20027190bbfdf69179a665638f
1,044
musicscript
MIT License
libs/rest/rest-server-impl/src/main/kotlin/net/corda/rest/server/impl/websocket/WebSocketCloserService.kt
corda
346,070,752
false
null
package net.corda.rest.server.impl.websocket import io.javalin.websocket.WsContext import org.eclipse.jetty.websocket.api.CloseStatus /** * Close a WebSocket connection. */ interface WebSocketCloserService { fun close(webSocketContext: WsContext, closeStatus: CloseStatus) }
14
null
27
69
0766222eb6284c01ba321633e12b70f1a93ca04e
283
corda-runtime-os
Apache License 2.0
app/src/main/java/com/thanasis/e_thessbike/backend/login/LoginUIState.kt
ThanasisGeorg
778,332,485
false
{"Kotlin": 201630}
package com.thanasis.e_thessbike.backend.login data class LoginUIState ( var email: String = "", var password: String = "", var emailError: Boolean = false, var passwordError: Boolean = false )
0
Kotlin
0
0
98cac3c5f9df96eee4f0dcbe622e26b3b8c38ae4
211
e-ThessBike
MIT License
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/events/Extensions.kt
chag6720
401,943,815
true
{"Kotlin": 3103126, "CSS": 352, "Java": 145}
package io.kotest.engine.events import io.kotest.core.config.Configuration import io.kotest.core.extensions.AfterSpecExtension import io.kotest.core.extensions.BeforeSpecExtension import io.kotest.core.extensions.Extension import io.kotest.core.extensions.SpecFinalizeExtension import io.kotest.core.extensions.SpecInitializeExtension import io.kotest.core.spec.Spec import io.kotest.fp.Try /** * Used to send invoke extension points on specs. */ class Extensions(private val configuration: Configuration) { /** * Returns all [Extension]s applicable to the [Spec]. This includes extensions via the * function override, those registered explicitly in the spec, and project wide extensions * from configuration. */ private fun resolvedExtensions(spec: Spec): List<Extension> { return spec.extensions() + // overriding in the spec spec.registeredExtensions() + // registered on the spec configuration.extensions() // globals } fun specInitialize(spec: Spec): Try<Unit> = Try { resolvedExtensions(spec).filterIsInstance<SpecInitializeExtension>().forEach { it.initialize(spec) } } fun specFinalize(spec: Spec): Try<Unit> = Try { resolvedExtensions(spec).filterIsInstance<SpecFinalizeExtension>().forEach { it.finalize(spec) } } fun beforeSpec(spec: Spec): Try<Unit> = Try { resolvedExtensions(spec).filterIsInstance<BeforeSpecExtension>().forEach { it.beforeSpec(spec) } } fun afterSpec(spec: Spec): Try<Unit> = Try { resolvedExtensions(spec).filterIsInstance<AfterSpecExtension>().forEach { it.afterSpec(spec) } } }
0
null
0
0
07ded8ab26a99da872b058f6747dcbc5527d1f71
1,619
kotest
Apache License 2.0
tiltak/src/main/kotlin/no/nav/amt/tiltak/deltaker/repositories/NavAnsattRepository.kt
navikt
393,356,849
false
null
package no.nav.amt.tiltak.deltaker.repositories import no.nav.amt.tiltak.deltaker.commands.UpsertNavAnsattCommand import no.nav.amt.tiltak.deltaker.dbo.NavAnsattDbo import org.springframework.jdbc.core.RowMapper import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Component import java.util.* @Component open class NavAnsattRepository( private val template: NamedParameterJdbcTemplate ) { private val rowMapper = RowMapper { rs, _ -> NavAnsattDbo( id = UUID.fromString(rs.getString("id")), navIdent = rs.getString("nav_ident"), navn = rs.getString("navn"), telefonnummer = rs.getString("telefonnummer"), epost = rs.getString("epost") ) } fun upsert(upsertCmd: UpsertNavAnsattCommand) { val sql = """ INSERT INTO nav_ansatt(id, nav_ident, navn, telefonnummer, epost) VALUES (:id, :navIdent, :navn, :telefonnummer, :epost) ON CONFLICT (nav_ident) DO UPDATE SET navn = :navn, telefonnummer = :telefonnummer, epost = :epost """.trimIndent() val parameterSource = MapSqlParameterSource().addValues( mapOf( "id" to UUID.randomUUID(), "navIdent" to upsertCmd.navIdent, "navn" to upsertCmd.navn, "telefonnummer" to upsertCmd.telefonnummer, "epost" to upsertCmd.epost ) ) template.update(sql, parameterSource) } fun getNavAnsattWithIdent(navIdent: String): NavAnsattDbo? { return template.query( "SELECT * FROM nav_ansatt WHERE nav_ident = :navIdent", MapSqlParameterSource().addValues(mapOf("navIdent" to navIdent)), rowMapper ).firstOrNull() } }
3
Kotlin
1
1
1d5e0b292fc624c4653caf0b7e21cab4e8691b13
1,727
amt-tiltak
MIT License
shared/src/commonMain/kotlin/me/saket/press/shared/syncer/git/DeviceInfo.kt
saket
201,701,386
false
null
package me.saket.press.shared.syncer.git interface DeviceInfo { /** * Dedicated location for storing files that other apps can't access. * Press currently uses this for syncing notes to a git repository. */ val appStorage: File /** * Currently used by [GitSyncer] for identifying * this device when setting up syncing. */ fun deviceName(): String fun supportsSplitScreen(): Boolean }
13
Kotlin
110
1,849
5f64350ec51402f3e6aeff145cbc35438780a03c
415
press
Apache License 2.0
dodam-design-system/src/main/java/com/b1nd/dodam/designsystem/previews/DodamBadgePreview.kt
Team-B1ND
772,621,822
false
{"Kotlin": 222293, "Swift": 640}
package com.b1nd.dodam.designsystem.previews import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.b1nd.dodam.designsystem.DodamTheme import com.b1nd.dodam.designsystem.component.DodamBadge @Composable @Preview fun DodamBadgePreview( ){ DodamTheme { Column( modifier = Modifier .fillMaxSize() .background(DodamTheme.colors.backgroundNormal) ) { Row { DodamBadge() Spacer(modifier = Modifier.width(30.dp)) DodamBadge( count = "1" ) Spacer(modifier = Modifier.width(30.dp)) DodamBadge( count = "999+" ) } } } }
0
Kotlin
1
7
9ff73f68ca535c3b2c09f72781edd65bc97225b2
1,177
dds-compose
MIT License
src/commonMain/kotlin/baaahs/sm/server/PinkyArgs.kt
baaahs
174,897,412
false
{"Kotlin": 3355751, "C": 1529197, "C++": 661364, "GLSL": 412680, "JavaScript": 62186, "HTML": 55088, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.sm.server import kotlinx.cli.ArgParser import kotlinx.cli.ArgType import kotlinx.cli.default class PinkyArgs(parser: ArgParser) { // TODO: Use this. val sceneName by parser.option(ArgType.String, shortName = "m") // TODO: Use this. val showName by parser.option(ArgType.String, "show", "s") // TODO: Use this. val switchShowAfter by parser.option(ArgType.Int, description = "Switch show after no input for x seconds") .default(600) // TODO: Use this. val adjustShowAfter by parser.option( ArgType.Int, description = "Start adjusting show inputs after no input for x seconds" ) val simulateBrains by parser.option(ArgType.Boolean, description = "Simulate connected brains") .default(false) companion object { val defaults: PinkyArgs = PinkyArgs(ArgParser("void")) } }
82
Kotlin
4
40
4dd92e5859d743ed7186caa55409f676d6408c95
876
sparklemotion
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CornerDownLeft.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline 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.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.CornerDownLeft: ImageVector get() { if (_cornerDownLeft != null) { return _cornerDownLeft!! } _cornerDownLeft = Builder(name = "CornerDownLeft", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(18.0f, 6.0f) verticalLineToRelative(6.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, 3.0f) horizontalLineToRelative(-10.0f) lineToRelative(4.0f, -4.0f) moveToRelative(0.0f, 8.0f) lineToRelative(-4.0f, -4.0f) } } .build() return _cornerDownLeft!! } private var _cornerDownLeft: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
1,727
compose-icon-collections
MIT License
app/src/main/java/xyz/teamgravity/sqldelight/presentation/screen/PersonListScreen.kt
raheemadamboev
466,060,722
false
null
package xyz.teamgravity.sqldelight.presentation.screen import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Done import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.hilt.navigation.compose.hiltViewModel import xyz.teamgravity.sqldelight.data.model.PersonModel import xyz.teamgravity.sqldelight.presentation.viewmodel.PersonListViewModel @Composable fun PersonListScreen() { val viewmodel = hiltViewModel<PersonListViewModel>() val persons by remember(viewmodel) { viewmodel.persons }.collectAsState(initial = emptyList()) Box( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Column( modifier = Modifier.fillMaxSize() ) { LazyColumn( modifier = Modifier .fillMaxWidth() .weight(1F) ) { items(persons) { person -> PersonCard( person = person, onPersonClick = viewmodel::onGetPerson, onDeleteClick = viewmodel::onDeletePerson, modifier = Modifier.fillMaxWidth() ) } } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { TextField( value = viewmodel.firstName, onValueChange = viewmodel::onFirstNameChange, placeholder = { Text(text = "First name") }, modifier = Modifier.weight(1F) ) Spacer(modifier = Modifier.width(8.dp)) TextField( value = viewmodel.lastName, onValueChange = viewmodel::onLastNameChange, placeholder = { Text(text = "Last name") }, modifier = Modifier.weight(1F) ) Spacer(modifier = Modifier.width(8.dp)) IconButton(onClick = viewmodel::onInsertPerson) { Icon( imageVector = Icons.Outlined.Done, contentDescription = "Insert person", tint = Color.Black ) } } } viewmodel.person?.let { person -> Dialog(onDismissRequest = viewmodel::onPersonDialogDismiss) { Box( modifier = Modifier .fillMaxWidth() .background(Color.White) .padding(16.dp), contentAlignment = Alignment.Center ) { Text(text = "${person.firstName} ${person.lastName}") } } } } } @Composable fun PersonCard( person: PersonModel, onPersonClick: (id: Long) -> Unit, onDeleteClick: (id: Long) -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier .clickable { onPersonClick(person.id!!) }, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = person.firstName, fontSize = 22.sp, fontWeight = FontWeight.Bold ) IconButton(onClick = { onDeleteClick(person.id!!) }) { Icon( imageVector = Icons.Outlined.Delete, contentDescription = "Delete person", tint = Color.Gray ) } } }
0
Kotlin
0
1
647b28a10ddf7b5f75a814b9fb4d1353f8ecba55
4,632
sql-delight
Apache License 2.0
domain/src/test/java/prieto/fernando/domain/mapper/RandomJokeLocalToDomainModelMapperTest.kt
ferPrieto
216,438,304
false
null
package prieto.fernando.domain.mapper import junit.framework.Assert.assertEquals import org.junit.Before import org.junit.Test import prieto.fernando.data.CategoryDomainModel import prieto.fernando.data.RandomJokeDomainModel import prieto.fernando.mapper.RandomJokeLocalToDomainModelMapper import prieto.fernando.model.CategoryLocalModel import prieto.fernando.model.RandomJokeLocalModel class RandomJokeLocalToDomainModelMapperTest { private lateinit var cut: RandomJokeLocalToDomainModelMapper @Before fun setUp() { cut = RandomJokeLocalToDomainModelMapper() } @Test fun `Given RandomJokeLocalModel when toDomain then return expected RandomJokeDomainModel`() { // Given val type = "some Type" val id = "some Id" val joke = "nice joke" val categoryLocalModels = listOf(CategoryLocalModel.EXPLICIT, CategoryLocalModel.NERDY) val randomJokeLocalModel = RandomJokeLocalModel( id, joke, categoryLocalModels ) val categoryDomainModels = listOf(CategoryDomainModel.EXPLICIT, CategoryDomainModel.NERDY) val expected = RandomJokeDomainModel( id, joke, categoryDomainModels ) // When val actualValue = cut.toDomain(randomJokeLocalModel) // Then assertEquals(expected, actualValue) } }
0
Kotlin
1
13
aecbd0054faa15beb29aac1c694eff9db0179432
1,403
MVVM-Modularized
Apache License 2.0
src/main/kotlin/hr/fer/infsus/handymanrepairs/repository/StreetRepository.kt
Theanko1412
783,054,275
false
{"Kotlin": 222286, "Dockerfile": 106}
package hr.fer.infsus.handymanrepairs.repository import hr.fer.infsus.handymanrepairs.model.dao.Street import org.springframework.data.jpa.repository.JpaRepository interface StreetRepository : JpaRepository<Street, String> { fun findStreetById(id: String): Street? fun findStreetByName(name: String): Street? fun deleteStreetById(id: String) }
0
Kotlin
0
0
9f278da33e4fc15cf5ce48839e07d31bcdf31e45
360
handyman-repairs
MIT License
src/main/kotlin/me/eugeniomarletti/redux/internal/Undefined.kt
Takhion
64,069,426
false
null
@file:Suppress("NOTHING_TO_INLINE") package me.eugeniomarletti.redux.internal private object UNDEFINED @Suppress("UNCHECKED_CAST") internal inline fun <T> undefined() = UNDEFINED as T internal inline val Any?.isUndefined: Boolean get() = this === UNDEFINED
1
Kotlin
3
6
97c062a1c37d7fdf3ee62b9dc0d6a5cc33b79c4e
265
Redux.kt
MIT License
src/main/java/de/ddkfm/hcloud/monitoring/Main.kt
DDKFM
123,777,058
false
null
package de.ddkfm.hcloud.monitoring import com.xenomachina.argparser.ArgParser import de.ddkfm.hcloud.HCloudApi import de.ddkfm.hcloud.models.Server import org.apache.log4j.* import spark.* import spark.kotlin.Http import spark.kotlin.ignite import spark.Spark.* import spark.template.velocity.VelocityTemplateEngine fun main(args : Array<String>) { var parser = HCloudParser(parser = ArgParser(args)) parser.run { var hcloud = HCloudApi(token); var http : Http = ignite() http.port(port) http.staticFiles.location("/public") http.get("/") { response.redirect("/dashboard")} path("/*") { before("") { req, resp -> var session : Session? = req.session() if(session != null && session.attribute("username")) { } else { halt(401, "You are not welcome here") } } } BasicConfigurator.configure() var db = Databases(url = "jdbc:mysql://localhost:3306/monitoring?useSSL=true", driver= "com.mysql.jdbc.Driver", user = "root", password = "root") db.createTables() db.initAdmin() var controller = Controller(http, hcloud, db) controller.initControllers() initTasks() } } fun List<Server?>.getNames() : String { return this.joinToString(separator = ",", prefix = "[", postfix = "]", transform = { "\"${it?.name}\"" } ); } fun List<Server?>.getOperatingSystems() : Map<String, Int> { var map = mutableMapOf<String, Int>(); for(server in this) { var os = server?.image?.OsFlavor; if (map.containsKey(os)) map.put(os!!, map.get(os)!! + 1) else map.put(os!!, 1) } return map }
0
Kotlin
0
0
823a18297aec5bb0f0693891f127d9f5c13d2915
1,896
HCloudMonitoring
MIT License
app/src/main/java/hu/mostoha/mobile/android/huki/model/network/photon/FeaturesItem.kt
RolandMostoha
386,949,428
false
{"Kotlin": 1025137, "Java": 38751, "Shell": 308}
package hu.mostoha.mobile.android.huki.model.network.photon import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class FeaturesItem( @Json(name = "geometry") val geometry: PhotonGeometry, @Json(name = "type") val type: String, @Json(name = "properties") val properties: Properties )
0
Kotlin
1
9
92587e6dcc68d89b5ffb2afd8cdd3c0cc47fb7d4
365
HuKi-Android
The Unlicense
app/src/main/kotlin/com/rahulografy/zflickrphotos/ui/main/photos/adapter/PhotoAdapter.kt
RahulSDeshpande
374,418,953
false
null
package com.rahulografy.zflickrphotos.ui.main.photos.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.rahulografy.zflickrphotos.R import com.rahulografy.zflickrphotos.data.source.remote.photos.model.Photo import com.rahulografy.zflickrphotos.ui.base.adapter.BaseListAdapter class PhotoAdapter : BaseListAdapter<Photo, PhotoViewHolder>( diffCallback = PhotosDiffUtilItemCallback() ) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ) = PhotoViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.item_photo, parent, false ) ) override fun onBindViewHolder( viewHolder: PhotoViewHolder, position: Int ) = viewHolder.bind( photo = getItem(position) ) override fun setData(data: List<Photo>?) { submitList(data) } override fun addData(data: List<Photo>?) { // TODO | API PAGINATION } }
0
Kotlin
0
0
f90d32259c787294a31818892141706ece28dfab
1,090
mvvm-flickr-photos-android
MIT License
webflux-example/src/main/kotlin/com/github/hyeyoom/webfluxexample/document/Item.kt
hyeyoom
234,559,842
false
null
package com.github.hyeyoom.webfluxexample.document import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document @Document // @Entity data class Item( @Id var id: String?, val description: String, var price: Double )
0
Kotlin
0
0
8d7f7a11b3a05ddf727ebd3a1ee40fe951fe0a28
283
spring-examples
MIT License
app/src/main/java/io/github/wulkanowy/data/db/entities/StudentNickAndAvatar.kt
wezuwiusz
827,505,734
false
{"Kotlin": 1759089, "HTML": 1949, "Shell": 257}
package io.github.wulkanowy.data.db.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity data class StudentNickAndAvatar( val nick: String, @ColumnInfo(name = "avatar_color") var avatarColor: Long ) : Serializable { @PrimaryKey var id: Long = 0 }
1
Kotlin
6
28
82b4ea930e64d0d6e653fb9024201b372cdb5df2
357
neowulkanowy
Apache License 2.0
core/src/commonMain/kotlin/com/river/core/FlowByteExt.kt
River-Kt
539,201,163
false
{"Kotlin": 450835, "Shell": 268, "Python": 126}
package com.river.core import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.fold import kotlinx.coroutines.flow.map /** * Converts the [Flow] of [Byte] to a [Flow] of [ByteArray]. * * @return A new [Flow] of [ByteArray] converted from the original [Flow] of [Byte]. */ fun Flow<Byte>.asByteArray( groupStrategy: GroupStrategy = GroupStrategy.Count(8) ): Flow<ByteArray> = chunked(groupStrategy) .map { it.toByteArray() } /** * Converts the [Flow] of [Byte] to a [Flow] of [String]. * * @return A new [Flow] of [String] converted from the original [Flow] of [Byte]. */ fun Flow<Byte>.asString( groupStrategy: GroupStrategy = GroupStrategy.Count(8) ): Flow<String> = asByteArray(groupStrategy) .asString() /** * Sums the elements of this [Flow] of [Byte] and returns the result. * * @return The sum of all elements emitted by the source Flow. * * Example usage: * ``` * val flow = flowOf(1, 2, 3, 4, 5).map { it.toByte() } * val sum = runBlocking { flow.sum() } * println(sum) // prints: 15 * ``` */ suspend fun Flow<Byte>.sum(): Long = fold(0L) { acc, i -> acc + i }
30
Kotlin
3
79
9841047b27268172a42e0e1ec74b095c0202a2cc
1,140
river
MIT License
about/src/commonMain/kotlin/com/opencritic/about/di/Module.kt
MAX-POLKOVNIK
797,563,657
false
{"Kotlin": 502940, "Swift": 141399}
package com.opencritic.about.di import com.opencritic.about.ui.AboutViewModel import com.opencritic.mvvm.viewModelOf import org.koin.dsl.module val aboutModule = module { registerInteractor(this) viewModelOf(::AboutViewModel) }
0
Kotlin
0
1
d9b9f89101ab1a94c05e03cb2a45e332270c81b2
238
OpenCritic
Apache License 2.0