path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/dev/turingcomplete/intellijbytecodeplugin/settings/ByteCodeAnalyserSettingsService.kt
marcelkliemannel
371,950,849
false
null
package dev.turingcomplete.intellijbytecodeplugin.common 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.observable.properties.AtomicBooleanProperty import com.intellij.openapi.observable.properties.AtomicProperty import com.intellij.util.xmlb.annotations.Attribute import dev.turingcomplete.intellijbytecodeplugin.bytecode.MethodDeclarationUtils.MethodDescriptorRenderMode import dev.turingcomplete.intellijbytecodeplugin.bytecode.TypeUtils.TypeNameRenderMode @State(name = "ByteCodeAnalyserSettingsService", storages = [Storage("byte-code-analyser.xml")]) internal class ByteCodeAnalyserSettingsService : PersistentStateComponent<ByteCodeAnalyserSettingsService.State> { // -- Properties -------------------------------------------------------------------------------------------------- // val typeNameRenderMode = AtomicProperty(DEFAULT_TYPE_NAME_RENDER_MODE) val methodDescriptorRenderMode = AtomicProperty(DEFAULT_METHOD_DESCRIPTOR_RENDER_MODE) val showAccessAsHex = AtomicBooleanProperty(DEFAULT_SHOW_ACCESS_AS_HEX) val skipDebug = AtomicBooleanProperty(DEFAULT_SKIP_DEBUG) val skipCode = AtomicBooleanProperty(DEFAULT_SKIP_CODE) val skipFrame = AtomicBooleanProperty(DEFAULT_SKIP_FRAME) // -- Initialization ---------------------------------------------------------------------------------------------- // // -- Exposed Methods --------------------------------------------------------------------------------------------- // override fun getState() = State( typeNameRenderMode = typeNameRenderMode.get().name, methodDescriptorRenderMode = methodDescriptorRenderMode.get().name, showAccessAsHex = showAccessAsHex.get(), skipDebug = skipDebug.get(), skipCode = skipCode.get(), skipFrame = skipFrame.get() ) override fun loadState(state: State) { typeNameRenderMode.set(state.typeNameRenderMode?.let { TypeNameRenderMode.valueOf(it) } ?: DEFAULT_TYPE_NAME_RENDER_MODE) methodDescriptorRenderMode.set(state.methodDescriptorRenderMode?.let { MethodDescriptorRenderMode.valueOf(it) } ?: DEFAULT_METHOD_DESCRIPTOR_RENDER_MODE) showAccessAsHex.set(state.showAccessAsHex ?: DEFAULT_SHOW_ACCESS_AS_HEX) skipDebug.set(state.skipDebug ?: DEFAULT_SKIP_DEBUG) skipCode.set(state.skipCode ?: DEFAULT_SKIP_CODE) skipFrame.set(state.skipFrame ?: DEFAULT_SKIP_FRAME) } // -- Private Methods --------------------------------------------------------------------------------------------- // // -- Inner Type -------------------------------------------------------------------------------------------------- // data class State( @get:Attribute("typeNameRenderMode") var typeNameRenderMode: String? = null, @get:Attribute("methodDescriptorRenderMode") var methodDescriptorRenderMode: String? = null, @get:Attribute("showAccessAsHex") var showAccessAsHex: Boolean? = null, @get:Attribute("skipDebug") var skipDebug: Boolean? = null, @get:Attribute("skipCode") var skipCode: Boolean? = null, @get:Attribute("skipFrame") var skipFrame: Boolean? = null, ) // -- Companion Object -------------------------------------------------------------------------------------------- // companion object { private val DEFAULT_TYPE_NAME_RENDER_MODE = TypeNameRenderMode.QUALIFIED private val DEFAULT_METHOD_DESCRIPTOR_RENDER_MODE = MethodDescriptorRenderMode.DESCRIPTOR private const val DEFAULT_SHOW_ACCESS_AS_HEX = true private const val DEFAULT_SKIP_DEBUG = false private const val DEFAULT_SKIP_CODE = false private const val DEFAULT_SKIP_FRAME = false val instance: ByteCodeAnalyserSettingsService get() = ApplicationManager.getApplication().getService(ByteCodeAnalyserSettingsService::class.java) var typeNameRenderMode by instance.typeNameRenderMode var methodDescriptorRenderMode by instance.methodDescriptorRenderMode var showAccessAsHex by instance.showAccessAsHex var skipDebug by instance.skipDebug var skipCode by instance.skipCode var skipFrame by instance.skipFrame } }
0
null
6
43
71681709383786881698cb7abfea3ea5ffec67d7
4,253
intellij-byte-code-plugin
Apache License 2.0
app/src/main/java/com/jedi1150/subagram/ui/word/components/InputPanel.kt
jedi1150
562,978,715
false
null
package com.jedi1150.subagram.ui.word.components import androidx.compose.animation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.jedi1150.subagram.R import com.jedi1150.subagram.ui.word.AnagramError import com.jedi1150.subagram.ui.word.WordUiState @OptIn(ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class) @Composable fun InputPanel( modifier: Modifier = Modifier, uiState: WordUiState = WordUiState(), onInputChanged: (String) -> Unit, onSubmitClicked: () -> Unit, contentPadding: PaddingValues = PaddingValues(), ) { val layoutDirection = LocalLayoutDirection.current Row( modifier = modifier .padding(8.dp) .padding( bottom = maxOf(contentPadding.calculateBottomPadding(), WindowInsets.ime .asPaddingValues() .calculateBottomPadding()), start = WindowInsets.navigationBars .asPaddingValues() .calculateStartPadding(layoutDirection) + WindowInsets.displayCutout .asPaddingValues() .calculateStartPadding(layoutDirection), end = WindowInsets.navigationBars .asPaddingValues() .calculateEndPadding(layoutDirection) + WindowInsets.displayCutout .asPaddingValues() .calculateEndPadding(layoutDirection), ), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.Top, ) { OutlinedTextField( value = uiState.input, onValueChange = { value -> onInputChanged(value) }, modifier = Modifier .fillMaxWidth() .weight(1f), label = { Text(text = stringResource(R.string.anagram_placeholder)) }, supportingText = { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, ) { AnimatedContent( targetState = uiState.error, transitionSpec = { if (targetState != null && initialState == null) { slideInVertically { height -> height } + fadeIn() with slideOutVertically { height -> -height } + fadeOut() } else { slideInVertically { height -> -height } + fadeIn() with slideOutVertically { height -> height } + fadeOut() }.using(SizeTransform(clip = false)) }, ) { target -> when (target) { AnagramError.EMPTY -> Text(stringResource(R.string.anagram_error_empty)) AnagramError.SHORT -> Text(stringResource(R.string.anagram_error_short)) AnagramError.SAME -> Text(stringResource(R.string.anagram_error_same)) AnagramError.NOT_SINGLE -> Text(stringResource(R.string.anagram_error_not_single)) AnagramError.NOT_ANAGRAM -> Text(stringResource(R.string.anagram_error_not_anagram)) AnagramError.ALREADY_EXISTS -> Text(stringResource(R.string.anagram_error_already_exists)) null -> Text(text = stringResource(R.string.anagram_support)) } } AnimatedContent( targetState = uiState.input.length, transitionSpec = { if (targetState > initialState) { slideInVertically { height -> height } + fadeIn() with slideOutVertically { height -> -height } + fadeOut() } else { slideInVertically { height -> -height } + fadeIn() with slideOutVertically { height -> height } + fadeOut() }.using(SizeTransform(clip = false)) }, ) { targetCount -> Text(text = targetCount.toString()) } } }, trailingIcon = { Crossfade(targetState = uiState.input.isNotEmpty()) { value -> if (value) { IconButton(onClick = { onInputChanged(String()) }) { Icon(imageVector = Icons.Default.Clear, contentDescription = null) } } } }, isError = uiState.error != null, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Words, autoCorrect = false, keyboardType = KeyboardType.Text, imeAction = ImeAction.Done), keyboardActions = KeyboardActions(onDone = { onSubmitClicked() }), singleLine = true, shape = MaterialTheme.shapes.extraLarge, ) FilledTonalButton( onClick = { onSubmitClicked() }, modifier = Modifier .height(59.dp) .padding(top = 8.dp), ) { Text(text = stringResource(id = R.string.submit)) } } } @Preview @Composable private fun PreviewInputPanel() { InputPanel( onInputChanged = {}, onSubmitClicked = {}, ) }
0
Kotlin
0
0
f7ac32f7deccc30cdb5f5bd6b05abf69192fa258
6,322
subagram-android
MIT License
livemap/src/commonMain/kotlin/org/jetbrains/letsPlot/livemap/chart/Locator.kt
JetBrains
176,771,727
false
{"Kotlin": 6240844, "Python": 1160203, "Shell": 3495, "C": 3039, "JavaScript": 931, "Dockerfile": 94}
/* * Copyright (c) 2023. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package org.jetbrains.letsPlot.livemap.chart import org.jetbrains.letsPlot.commons.intern.typedGeometry.Vec import org.jetbrains.letsPlot.livemap.Client import org.jetbrains.letsPlot.livemap.core.ecs.EcsEntity import org.jetbrains.letsPlot.livemap.mapengine.RenderHelper data class HoverObject( val layerIndex: Int, val index: Int, val distance: Double, val locator: Locator // TODO: move it out from HoverObject ) interface Locator { fun search(coord: Vec<org.jetbrains.letsPlot.livemap.Client>, target: EcsEntity, renderHelper: RenderHelper): HoverObject? fun reduce(hoverObjects: Collection<HoverObject>): HoverObject? }
128
Kotlin
47
1,414
9ec69ce19177d7aeb5763e6bb423022fa97945ba
796
lets-plot
MIT License
app/src/main/java/com/nafanya/mp3world/features/albums/di/AlbumModule.kt
AlexSoWhite
445,900,000
false
null
package com.nafanya.mp3world.features.albums.di import androidx.lifecycle.ViewModel import com.nafanya.mp3world.core.di.ViewModelKey import com.nafanya.mp3world.features.albums.viewModel.AlbumListViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module interface AlbumModule { @Binds @[IntoMap ViewModelKey(AlbumListViewModel::class)] fun providesAlbumListViewModel(albumListViewModel: AlbumListViewModel): ViewModel }
0
Kotlin
0
0
480fa9c16460890d393ece7c8aa2466c031d8f78
472
mp3world
MIT License
app/src/main/java/com/feduss/timerwear/view/settings/SettingsView.kt
feduss
839,081,219
false
{"Kotlin": 235539}
package com.feduss.timerwear.view.settings import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.wear.compose.material.Text import com.feduss.timerwear.BuildConfig import com.feduss.timerwear.uistate.extension.PurpleCustom import com.feduss.timerwear.uistate.settings.SettingsViewModel import com.feduss.timerwear.view.component.header.LeftIconTextHeader import com.google.android.horologist.annotations.ExperimentalHorologistApi import com.google.android.horologist.compose.layout.ScalingLazyColumn import com.google.android.horologist.compose.layout.ScalingLazyColumnState @OptIn(ExperimentalHorologistApi::class) @Composable fun SettingsView( viewModel: SettingsViewModel = hiltViewModel(), columnState: ScalingLazyColumnState, onEmailFeedbackTapped: () -> Unit ) { val versionName = BuildConfig.VERSION_NAME val versionCode = BuildConfig.VERSION_CODE ScalingLazyColumn( modifier = Modifier .fillMaxSize() .padding(horizontal = 12.dp), columnState = columnState ) { item { LeftIconTextHeader( title = stringResource(viewModel.headerTextId) ) } item { Spacer(modifier = Modifier.height(8.dp)) } item { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(viewModel.feedbackTextId), textAlign = TextAlign.Center ) Text( modifier = Modifier.clickable { onEmailFeedbackTapped() }, text = viewModel.feedbackEmail, textAlign = TextAlign.Center, textDecoration = TextDecoration.Underline, color = Color.PurpleCustom ) } } item { Spacer(modifier = Modifier.height(8.dp)) } item { Text( text = stringResource(viewModel.appVersionTextId, versionName, versionCode), textAlign = TextAlign.Center ) } } }
0
Kotlin
0
2
1c61177726dd45c97ea3a1663b9380916097bef0
2,979
TimerWear
MIT License
app/src/main/java/com/duckduckgo/app/browser/favorites/AddItemAdapter.kt
Rachelmorrell
132,979,208
true
{"Kotlin": 3143821, "HTML": 42259, "Ruby": 7252, "JavaScript": 6544, "C++": 1820, "CMake": 1298, "Shell": 712}
/* * Copyright (c) 2021 DuckDuckGo * * 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.duckduckgo.app.browser.favorites import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.duckduckgo.app.browser.databinding.ViewItemAddItemBinding class AddItemAdapter( private val onItemSelected: () -> Unit, ) : RecyclerView.Adapter<AddItemAdapter.AddItemViewHolder>() { class AddItemViewHolder(val binding: ViewItemAddItemBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddItemViewHolder { return AddItemViewHolder(ViewItemAddItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)) } override fun onBindViewHolder(holder: AddItemViewHolder, position: Int) { holder.binding.quickAccessAddItemCard.setOnClickListener { onItemSelected.invoke() } } override fun getItemCount(): Int = 1 }
4
Kotlin
0
3
c03633f7faee192948e68c3897c526c323ee0f2e
1,501
Android
Apache License 2.0
linkbait-plugins/plugin-tags/src/main/kotlin/de/langerhans/linkbait/tags/TagsPlugin.kt
nishtahir
137,824,742
false
{"Kotlin": 126854, "Groovy": 57211, "HTML": 9162, "Scala": 3961, "Java": 2035, "JavaScript": 1470, "Shell": 596}
package de.langerhans.linkbait.tags import com.j256.ormlite.jdbc.JdbcConnectionSource import com.nishtahir.linkbait.plugin.LinkbaitPlugin import com.nishtahir.linkbait.plugin.PluginContext /** * Created by maxke on 16.08.2016. * Main entry for the tags plugin */ class TagsPlugin : LinkbaitPlugin() { private lateinit var handler: TagsHandler override fun start(context: PluginContext) { InjektModule.scope.addSingleton(JdbcConnectionSource("jdbc:sqlite:data/tags.sqlite")) InjektModule.scope.addFactory { TagService() } handler = TagsHandler(context) context.registerListener(handler) } override fun stop(context: PluginContext) { context.unregisterListener(handler) } override fun onPluginStateChanged() { // Here be Nutella } }
0
Kotlin
0
1
81ff2c65c03497da7de204d5ed0268a95d3f22cd
817
linkbait
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/cloudfront/OriginAccessIdentityPropsDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.cloudfront import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.cloudfront.OriginAccessIdentityProps /** * Properties of CloudFront OriginAccessIdentity. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.cloudfront.*; * OriginAccessIdentityProps originAccessIdentityProps = OriginAccessIdentityProps.builder() * .comment("comment") * .build(); * ``` */ @CdkDslMarker public class OriginAccessIdentityPropsDsl { private val cdkBuilder: OriginAccessIdentityProps.Builder = OriginAccessIdentityProps.builder() /** @param comment Any comments you want to include about the origin access identity. */ public fun comment(comment: String) { cdkBuilder.comment(comment) } public fun build(): OriginAccessIdentityProps = cdkBuilder.build() }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,232
awscdk-dsl-kotlin
Apache License 2.0
features/detail/src/main/java/com/fappslab/features/detail/presentation/viewmodel/DetailViewModel.kt
F4bioo
708,171,476
false
{"Kotlin": 210868}
package com.fappslab.features.detail.presentation.viewmodel import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import androidx.paging.compose.LazyPagingItems import com.fappslab.core.domain.model.Movie import com.fappslab.core.navigation.DETAILS_ID_ARGS_KEY import com.fappslab.features.detail.domain.model.Pack import com.fappslab.features.detail.domain.usecase.provider.DetailUseCaseProvider import com.fappslab.libraries.arch.extension.orZero import com.fappslab.libraries.arch.viewmodel.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel internal class DetailViewModel @Inject constructor( private val provider: DetailUseCaseProvider, private val savedStateHandle: SavedStateHandle ) : ViewModel<DetailViewState, DetailViewAction>(DetailViewState()) { private val id get() = savedStateHandle.get<Int>(DETAILS_ID_ARGS_KEY) .orZero() /** * Why CoroutineScope here? * * The use of `coroutineScope` in this context is crucial for managing exceptions effectively within asynchronous operations: * - It ensures that exceptions thrown by any of the `async` tasks are captured and handled within the `runCatching` block. * This prevents exceptions from leaking out and terminating the coroutine unexpectedly. * - By grouping multiple asynchronous operations (`async` tasks), `coroutineScope` ensures they are treated as a single unit. * This is particularly useful when these operations are logically connected and their outcomes are interdependent. * - Additionally, `coroutineScope` maintains the parent coroutine's context, ensuring consistent behavior and exception handling * across different parts of the coroutine hierarchy. */ fun getMovieDetail() { viewModelScope.launch { onState { it.copy(shouldShowLoading = true) } .runCatching { coroutineScope { val detailDeferred = async { provider.getMovieDetailUseCase(id) } val isFavoriteDeferred = async { provider.isFavoriteUseCase(id) } val detail = detailDeferred.await() val isFavorite = isFavoriteDeferred.await() detail to isFavorite } } .apply { onState { it.copy(shouldShowLoading = false) } } .onFailure { getMovieDetailFailure(message = it.message) } .onSuccess { getMovieDetailSuccess(successPair = it) } } } private fun getMovieDetailFailure(message: String?) { onState { it.copy(errorMessage = message.orEmpty()) } } private fun getMovieDetailSuccess(successPair: Pair<Pack, Boolean>) { val (pack) = successPair val movies = pack.movies .catch { } .cachedIn(viewModelScope) onState { it.setSuccessState(movies, successPair) } } fun onItemClicked(id: Int) { onAction { DetailViewAction.ItemClicked(id) } } fun onCollapse(shouldCollapse: Boolean) { onState { it.copy(shouldCollapseText = shouldCollapse) } } fun onFavorite(movie: Movie) { viewModelScope.launch { val isFavoriteChecked = state.value.isFavoriteChecked onState { it.copy(shouldShowLoading = true) } .runCatching { if (isFavoriteChecked) { provider.deleteFavoriteUseCase(movie) } else provider.setFavoriteUseCase(movie) } .apply { onState { it.copy(shouldShowLoading = false) } } .onFailure { } .onSuccess { onState { it.copy(isFavoriteChecked = isFavoriteChecked.not()) } } } } fun onTryAgain(pagingItems: LazyPagingItems<Movie>) { onAction { DetailViewAction.TryAgain(pagingItems) } } }
0
Kotlin
0
1
3506b09c7b6b522899486fa45ba9686b404780f2
4,174
TMDBCompose
MIT License
server/src/main/kotlin/com/heerkirov/hedge/server/utils/DateTime.kt
HeerKirov
298,201,781
false
null
package com.heerkirov.hedge.server.utils import java.time.* import java.time.format.DateTimeFormatter /** * 提供时间日期相关内容的统一处理。 * 在此项目中,对于时间使用规范,做出统一规定: * - 在数据库中,所有时间都使用不含时区的LocalDateTime/TIMESTAMP格式存储,存储的时间是UTC时区的时间戳。 * - 对外暴露的接口都使用dateTimeFormat格式定义的标准时间戳,同样不含时区信息,基于UTC时区,这样前端可以最高效地转换利用。 * - 在项目内,总是使用基于用户当前时区的ZonedDateTime处理业务逻辑。在使用到时,利用此工具库提供的转换函数。 */ object DateTime { private val ZONE_UTC = ZoneId.of("UTC") private val DATETIME_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]'Z'") private val DATE_FORMAT: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") /** * 将毫秒时间戳解析为时间。 */ fun Long.parseDateTime(): LocalDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(this), ZONE_UTC) /** * 将字符串解析为yyyy-MM-ddTHH:mm:ssZ的时间格式。 */ fun String.parseDateTime(): LocalDateTime = LocalDateTime.parse(this, DATETIME_FORMAT) /** * 将字符串解析为yyyy-MM-dd的日期格式。 */ fun String.parseDate(): LocalDate = LocalDate.parse(this, DATE_FORMAT) /** * 获得不包含时区的当前UTC时间。 */ fun now(): LocalDateTime = LocalDateTime.now(Clock.systemUTC()) /** * 获得当前系统的默认时区。 */ private fun zone(): ZoneId = ZoneId.systemDefault() /** * 将UTC时间转换为目标时区的时间。 */ fun LocalDateTime.asZonedTime(zoneId: ZoneId): ZonedDateTime = this.atZone(ZONE_UTC).withZoneSameInstant(zoneId) /** * 将UTC时间转换为当前系统时区的时间。 */ fun LocalDateTime.asZonedTime(): ZonedDateTime = asZonedTime(zone()) /** * 将目标时区时间转换为UTC时间。 */ fun ZonedDateTime.asUTCTime(): LocalDateTime = this.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime() /** * 将时间格式化为yyyy-MM-ddThh:mm:ssZ。 */ fun LocalDateTime.toDateTimeString(): String = format(DATETIME_FORMAT) /** * 将日期格式化为yyyy-MM-dd。 */ fun LocalDate.toDateString(): String = format(DATE_FORMAT) /** * 将时间转换为时间戳。 */ fun LocalDateTime.toMillisecond(): Long = toInstant(ZoneOffset.UTC).toEpochMilli() }
0
TypeScript
0
1
8140cd693759a371dc5387c4a3c7ffcef6fb14b2
2,040
Hedge-v2
MIT License
desktop/adapters/src/main/kotlin/com/soyle/stories/location/hostedScene/HostedSceneRenamedNotifier.kt
Soyle-Productions
239,407,827
false
null
package com.soyle.stories.location.hostedScene import com.soyle.stories.common.Notifier import com.soyle.stories.domain.location.events.HostedSceneRenamed class HostedSceneRenamedNotifier : Notifier<HostedSceneRenamedReceiver>(), HostedSceneRenamedReceiver { override suspend fun receiveHostedScenesRenamed(events: List<HostedSceneRenamed>) { notifyAll { it.receiveHostedScenesRenamed(events) } } override suspend fun receiveHostedSceneRenamed(event: HostedSceneRenamed) { notifyAll { it.receiveHostedSceneRenamed(event) } } }
45
Kotlin
0
9
1a110536865250dcd8d29270d003315062f2b032
564
soyle-stories
Apache License 2.0
z2-core/src/commonMain/kotlin/hu/simplexion/z2/adaptive/AdaptiveStateValueBinding.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1768633, "CSS": 171914, "Java": 18941, "JavaScript": 1950, "HTML": 1854}
/* * Copyright © 2020-2024, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.z2.adaptive data class AdaptiveStateValueBinding<VT>( val owner: AdaptiveFragment<*>, val indexInState: Int, val indexInClosure: Int, val metadata: AdaptivePropertyMetadata, val supportFunction: Int ) { @Suppress("UNCHECKED_CAST") var value: VT get() = owner.getThisClosureVariable(indexInClosure) as VT set(v) { owner.setStateVariable(indexInState, v) owner.patchInternal() } override fun toString(): String { return "AdaptiveStateValueBinding(${owner.id}, $indexInState, $indexInClosure, $metadata, $supportFunction)" } }
5
Kotlin
0
1
cc13a72fb54d89dffb91e3edf499ae5152bca0d9
773
z2
Apache License 2.0
core-ktx/src/javafxx/scene/input/ClipboardContent.kt
gitter-badger
143,415,479
true
{"Kotlin": 475058, "HTML": 1425, "Java": 731}
@file:Suppress("NOTHING_TO_INLINE") package javafxx.scene.input import javafx.scene.image.Image import javafx.scene.input.ClipboardContent import java.io.File /** Executes action if string is present in this clipboard content. */ inline fun ClipboardContent.ifStringPresent(action: (String) -> Unit) { if (hasString()) action(string) } /** Executes action if url is present in this clipboard content. */ inline fun ClipboardContent.ifUrlPresent(action: (String) -> Unit) { if (hasUrl()) action(url) } /** Executes action if html is present in this clipboard content. */ inline fun ClipboardContent.ifHtmlPresent(action: (String) -> Unit) { if (hasHtml()) action(html) } /** Executes action if rtf is present in this clipboard content. */ inline fun ClipboardContent.ifRtfPresent(action: (String) -> Unit) { if (hasRtf()) action(rtf) } /** Executes action if image is present in this clipboard content. */ inline fun ClipboardContent.ifImagePresent(action: (Image) -> Unit) { if (hasImage()) action(image) } /** Executes action if files is present in this clipboard content. */ inline fun ClipboardContent.ifFilesPresent(action: (List<File>) -> Unit) { if (hasFiles()) action(files) }
0
Kotlin
0
0
fe550237f725e398e3f78ed2e73a779a133088c2
1,215
javafxx
Apache License 2.0
f2-spring/data/f2-spring-data-mongodb/src/main/kotlin/f2/spring/data/mongodb/MongodbConfig.kt
smartbcity
746,765,045
false
{"Java": 132969, "Kotlin": 130142, "Gherkin": 24157, "JavaScript": 1654, "Dockerfile": 745, "Makefile": 481, "CSS": 102}
package f2.spring.data.mongodb import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.mongodb.core.ReactiveMongoOperations import org.springframework.data.mongodb.repository.support.ReactiveMongoRepositoryFactory import org.springframework.data.repository.core.support.ReactiveRepositoryFactorySupport @Configuration open class MongodbConfig { @Bean open fun reactiveRepositoryFactorySupport(mongoOperations: ReactiveMongoOperations): ReactiveRepositoryFactorySupport { return ReactiveMongoRepositoryFactory(mongoOperations) } }
1
Kotlin
1
0
d7b85f46a13941d3eea728eac52d97d11a2bfb6b
625
fixers-f2
Apache License 2.0
buildSrc/src/main/kotlin/DependencyDelegateExtensions.kt
ThanosFisherman
803,474,948
false
{"Kotlin": 78783, "GLSL": 22476, "Shell": 2608, "HTML": 1316}
import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.ExternalModuleDependency import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.kotlin.dsl.accessors.runtime.externalModuleDependencyFor import org.gradle.kotlin.dsl.add /* * These extensions mimic the extensions that are generated on the fly by Gradle. * They are used here to provide above dependency syntax that mimics Gradle Kotlin DSL * syntax in module\build.gradle.kts files. */ // region dependency extensions fun DependencyHandler.implementation( dependencyNotation: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit, ): Dependency? = add("implementation", dependencyNotation, dependencyConfiguration) fun DependencyHandler.implementation(dependencyNotation: Any): Dependency? = add("implementation", dependencyNotation) fun DependencyHandler.natives(dependencyNotation: Any): Dependency? = add("natives", dependencyNotation) fun DependencyHandler.developmentImplementation(dependencyNotation: Any): Dependency? = add("developmentImplementation", dependencyNotation) fun DependencyHandler.oemImplementation(dependencyNotation: Any): Dependency? = add("oemImplementation", dependencyNotation) fun DependencyHandler.oemCNImplementation(dependencyNotation: Any): Dependency? = add("oemCNImplementation", dependencyNotation) fun DependencyHandler.appStoreImplementation(dependencyNotation: Any): Dependency? = add("appStoreImplementation", dependencyNotation) fun DependencyHandler.appStoreCNImplementation(dependencyNotation: Any): Dependency? = add("appStoreCNImplementation", dependencyNotation) fun DependencyHandler.appStoreNAImplementation(dependencyNotation: Any): Dependency? = add("appStoreNAImplementation", dependencyNotation) fun DependencyHandler.appStoreRUImplementation(dependencyNotation: Any): Dependency? = add("appStoreRUImplementation", dependencyNotation) fun DependencyHandler.operationsImplementation(dependencyNotation: Any): Dependency? = add("operationsImplementation", dependencyNotation) fun DependencyHandler.api(dependencyNotation: Any): Dependency? = add("api", dependencyNotation) fun DependencyHandler.kapt(dependencyNotation: Any): Dependency? = add("kapt", dependencyNotation) fun DependencyHandler.runtimeOnly(dependencyNotation: Any): Dependency? = add("runtimeOnly", dependencyNotation) fun DependencyHandler.annotationProcessor(dependencyNotation: Any): Dependency? = add("annotationProcessor", dependencyNotation) fun DependencyHandler.debugImplementation(dependencyNotation: Any): Dependency? = add("debugImplementation", dependencyNotation) fun DependencyHandler.debugImplementation( dependencyNotation: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit, ): Dependency? = add("debugImplementation", dependencyNotation, dependencyConfiguration) fun DependencyHandler.releaseImplementation(dependencyNotation: String): Dependency? = add("releaseImplementation", dependencyNotation) fun DependencyHandler.releaseImplementation( dependencyNotation: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit, ): Dependency? = add("releaseImplementation", dependencyNotation, dependencyConfiguration) fun DependencyHandler.testImplementation(dependencyNotation: Any): Dependency? = add("testImplementation", dependencyNotation) fun DependencyHandler.androidTestImplementation(dependencyNotation: Any): Dependency? = add("androidTestImplementation", dependencyNotation) fun DependencyHandler.coreLibraryDesugaring(dependencyNotation: Any): Dependency? = add("coreLibraryDesugaring", dependencyNotation) fun DependencyHandler.project( path: String, configuration: String? = null, ): ProjectDependency { val notation = if (configuration != null) { mapOf("path" to path, "configuration" to configuration) } else { mapOf("path" to path) } return uncheckedCast(project(notation)) } @Suppress("unchecked_cast", "nothing_to_inline") private inline fun <T> uncheckedCast(obj: Any?): T = obj as T /** * Custom extension similar to [DependencyHandler.project] but for external library dependency files. * * This extension allows us to redefine a library file name (.jar or .aar) as a constant value in the build system * and add the dependency to other modules. * * Example with this extension: * implementation(external("mabindings-core.jar")) // as string * implementation(external(Dependencies.External.MaBindingsCore)) // as constant * * Example without this extension: * implementation(group = "", name = "mabindings-core", ext = "jar") */ fun DependencyHandler.external(file: String, group: String = ""): ExternalModuleDependency { val name = file.substringBefore(".") val ext = file.substringAfter(".") return externalModuleDependencyFor( dependencyHandler = this, group = group, name = name, version = null, configuration = null, classifier = null, ext = ext ) }
0
Kotlin
2
1
facb4e5a866e733dcc94484664fa3de73929741d
5,148
ApollonianGasket
Apache License 2.0
app/src/main/java/com/rifqimfahmi/alldogbreeds/ui/meme/MemePresenter.kt
rifqimfahmi
125,337,589
false
null
package com.rifqimfahmi.alldogbreeds.ui.meme import android.Manifest import android.content.Context import android.content.Intent import android.os.Environment import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import com.rifqimfahmi.alldogbreeds.R import com.rifqimfahmi.alldogbreeds.data.DataManager import com.rifqimfahmi.alldogbreeds.data.network.model.giphy.ResRandomMeme import com.rifqimfahmi.alldogbreeds.ui.base.BasePresenter import com.rifqimfahmi.alldogbreeds.util.AppConstants import com.rifqimfahmi.alldogbreeds.util.CommonUtils import com.rifqimfahmi.alldogbreeds.util.rx.SchedulerProvider import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.realm.Realm import java.io.* import java.net.UnknownHostException import javax.inject.Inject /* * Created by <NAME> on 26/02/18. */ class MemePresenter<V : MemeMvpView> @Inject constructor(dataManager: DataManager, schedulerProvider: SchedulerProvider, compositeDisposable: CompositeDisposable) : BasePresenter<V>(dataManager, schedulerProvider, compositeDisposable), MemeMvpPresenter<V> { var mResRandomResponse: ResRandomMeme? = null override fun getMeme(context: Context) { val api_key = context.getString(R.string.giphy_api_key) val offset = CommonUtils.getRandomDogMemeOffset() mCompositeDisposable.add( mDataManager.getGiphyApi().getRandomDogMeme(offset, api_key) .subscribeOn(mSchedulerProvider.io()) .observeOn(mSchedulerProvider.ui()) .doOnSubscribe { mMvpView?.showLoadingWithText("Getting Funny Meme..") } .subscribe({ mResRandomResponse = it mMvpView?.loadGif(__getDownSizeGifLink()) }, { mMvpView?.onLoadMemeError() mResRandomResponse = null mMvpView?.hideLoading() if (it is UnknownHostException) { mMvpView?.onError("No internet connection. Try again later!") } else { mMvpView?.onError(null) } }) ) } override fun downloadGif(activity: MemeActivity) { val neededPermissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) if (requestThisPermissions(activity, AppConstants.REQUEST_WRITE_EXT_STORAGE, neededPermissions)) { return } val downloadObservable = Observable.create<Int>( { try { val file: File = Glide.with(activity) .load(__getDownSizeGifLink()) .apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)) .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .get() val imageFileName = "${mResRandomResponse?.data!![0].slug}.gif" val storageDir = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "/dog-meme") storageDir.mkdirs() val dst = File(storageDir, imageFileName) dst.createNewFile() val ins: InputStream = FileInputStream(file) val out: OutputStream = FileOutputStream(dst) val buf = ByteArray(1024) var len: Int while (true) { len = ins.read(buf) if (len == -1) break out.write(buf, 0, len) } it.onNext(1) } catch (e: IOException) { it.onError(e) } }) .subscribeOn(mSchedulerProvider.io()) .observeOn(mSchedulerProvider.ui()) .doOnSubscribe { mMvpView?.showLoadingWithText("Downloading..") } mCompositeDisposable.add( downloadObservable.subscribe( { mMvpView?.hideLoading() mMvpView?.showMessage("Downloaded") }, { mMvpView?.hideLoading() mMvpView?.onError(it.localizedMessage) } ) ) } override fun toggleLovedMeme() { if (mResRandomResponse == null) { return } if (mDataManager.isMemeLoved(mResRandomResponse!!)) { mDataManager.removeLovedMeme(mResRandomResponse!!, Realm.Transaction.OnSuccess { mMvpView?.markUnloved() }) return } mDataManager.saveLovedMeme(mResRandomResponse!!, Realm.Transaction.OnSuccess { mMvpView?.markLoved() mMvpView?.showMessage("Added to your favorite") }) } private fun __getDownSizeGifLink(): String { return mResRandomResponse?.data?.get(0)?.images?.downsized_medium?.url!! } override fun shareCurrentGif(context: Context) { val intent = Intent(Intent.ACTION_SEND) intent.putExtra(Intent.EXTRA_TEXT, "yow. check out this funny dog meme ${mResRandomResponse?.data?.get(0)?.shortLink}") intent.type = "text/plain" context.startActivity(Intent.createChooser(intent, "Share meme")) } override fun checkLovedMeme() { if (mDataManager.isMemeLoved(mResRandomResponse!!)) { mMvpView?.markLoved() } else { mMvpView?.markUnloved() } } override fun resetBreedResponse() { mResRandomResponse = null } }
0
Kotlin
1
4
b29dfdd8c690780f649825ef471ab8c590bebd0c
6,300
all-dog-breeds
Apache License 2.0
src/main/java/com/silverhetch/clotho/connection/socket/SocketConn.kt
fossabot
268,971,219
false
{"Gradle": 2, "YAML": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 139, "Java": 20, "SQL": 1, "XML": 14}
package com.silverhetch.clotho.connection.socket import java.net.Socket /** * Socket stream exchange text base data. */ class SocketConn(private val socket: Socket, private val onMessage: (TextBaseConn, String) -> Unit) : TextBaseConn { private lateinit var textBaseConn: TextBaseConn override fun close() { socket.close() } override fun launch() { textBaseConn = TextBaseConnImpl( socket.getInputStream().bufferedReader(), socket.getOutputStream().bufferedWriter(), onMessage ).apply { launch() } } override fun send(msg: String) { textBaseConn.send(msg) } }
1
null
1
1
aeffa8e69ed87376e7ce1b792d5fe18b188a7e25
662
Clotho
MIT License
app/src/main/java/co/cmedina/weather/util/ImageUtil.kt
camedi445
838,605,641
false
{"Kotlin": 72271}
package co.cmedina.weather.util fun String.ensureHttps(): String { return if (this.startsWith("http://") || this.startsWith("https://")) { this } else { "https://$this" } }
0
Kotlin
0
0
daf144aec7091ab5f0374d1fd2ea569ce93c18c2
201
weather
Apache License 2.0
app/src/main/java/com/iambedant/dagger2tutorial/ApplicationModule.kt
iamBedant
125,260,404
false
null
package com.iambedant.dagger2tutorial import android.app.Application import android.content.Context import dagger.Binds import dagger.Module import dagger.Provides /** * Created by kuliza-233 on 15/03/18. */ @Module abstract class ApplicationModule { @Binds abstract fun bindApplication(application: Application): Context @Binds abstract fun bindAnOrdinaryThing(ordinaryImplementation: AnOrdinaryImplementation): AnOrdinaryInterface @Module companion object { @JvmStatic @Provides fun provideCustomObject(): ACustomObject = ACustomObject() @JvmStatic @Provides fun provideComplexCustomObject(customObject: ACustomObject): AComplexCustomObject = AComplexCustomObject(customObject) } }
0
Kotlin
0
1
421e2578ad53d901e716d1a9a2755748e369527b
771
Dagger2Tutorial
MIT License
initializr-locorepo/src/main/kotlin/io/spring/initializr/locorepo/model/MpsModelFactory.kt
amirmv2006
304,826,019
false
null
package io.spring.initializr.locorepo.model import io.spring.initializr.generator.language.Language import io.spring.initializr.generator.language.LanguageFactory class MpsModelFactory : LanguageFactory { override fun createLanguage(id: String, jvmVersion: String?): Language? = if (MpsModel.ID == id) { MpsModel(jvmVersion) } else null }
1
null
1
1
1c6c239b4dcb3e55ac8593894359e22fc3ed4295
386
initializr
Apache License 2.0
app/src/main/java/com/arturostrowski/quiz/app/ui/find_friends/interactor/FindFriendsMVPInteractor.kt
Mesti193
215,134,193
false
{"Gradle": 3, "Java Properties": 2, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 151, "XML": 93, "Java": 1, "JSON": 2}
package com.arturostrowski.quiz.app.ui.find_friends.interactor import com.arturostrowski.quiz.app.data.database.repository.user.User import com.arturostrowski.quiz.app.data.network.request.AddFriendRequest import com.arturostrowski.quiz.app.data.network.request.SearchFriendsRequest import com.arturostrowski.quiz.app.data.network.response.AddFriendResponse import com.arturostrowski.quiz.app.data.network.response.SearchFriendsResponse import com.arturostrowski.quiz.app.ui.base.interactor.MVPInteractor import io.reactivex.Observable interface FindFriendsMVPInteractor : MVPInteractor { fun addFriend(request: AddFriendRequest): Observable<AddFriendResponse> fun searchFriends(request: SearchFriendsRequest): Observable<SearchFriendsResponse> fun loadUser(): Observable<List<User>> }
0
Kotlin
0
0
1c0cef0108b0b90a4074f18b4690e5533214b41c
801
QuizApp
Apache License 2.0
spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/client/CoExchangeFilterFunction.kt
spring-projects
1,148,753
false
{"Java": 48416901, "Kotlin": 969803, "AspectJ": 31773, "FreeMarker": 31129, "Groovy": 6902, "XSLT": 2945, "HTML": 1140, "Ruby": 1060, "CSS": 1019, "Shell": 961, "Smarty": 717, "PLpgSQL": 305, "JavaScript": 280, "Python": 254}
/* * Copyright 2002-2023 the original author or authors. * * 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 org.springframework.web.reactive.function.client import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.reactor.awaitSingle import kotlinx.coroutines.reactor.mono import reactor.core.publisher.Mono /** * Kotlin-specific implementation of the [ExchangeFilterFunction] interface * that allows for using coroutines. * * @author Sebastien Deleuze * @since 6.1 */ abstract class CoExchangeFilterFunction : ExchangeFilterFunction { final override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> { return mono(Dispatchers.Unconfined) { filter(request, object : CoExchangeFunction { override suspend fun exchange(request: ClientRequest): ClientResponse { return next.exchange(request).awaitSingle() } }) } } /** * Apply this filter to the given request and exchange function. * * The given [CoExchangeFunction] represents the next entity in the * chain, to be invoked via [CoExchangeFunction.exchange] in order to * proceed with the exchange, or not invoked to short-circuit the chain. * * **Note:** When a filter handles the response after the * call to [CoExchangeFunction.exchange], extra care must be taken to * always consume its content or otherwise propagate it downstream for * further handling, for example by the [WebClient]. Please see the * reference documentation for more details on this. * * @param request the current request * @param next the next exchange function in the chain * @return the filtered response */ protected abstract suspend fun filter(request: ClientRequest, next: CoExchangeFunction): ClientResponse } /** * Kotlin-specific adaption of [ExchangeFunction] that allows for coroutines. * * @author Sebastien Deleuze * @since 6.1 */ interface CoExchangeFunction { /** * Exchange the given request for a [ClientResponse]. * * **Note:** When calling this method from an * [CoExchangeFilterFunction] that handles the response in some way, * extra care must be taken to always consume its content or otherwise * propagate it downstream for further handling, for example by the * [WebClient]. Please see the reference documentation for more * details on this. * * @param request the request to exchange * @return the delayed response */ suspend fun exchange(request: ClientRequest): ClientResponse }
264
Java
38106
56,506
52e813d0ad2a5d3439c1880b481b6942a138a8dc
2,994
spring-framework
Apache License 2.0
server/src/main/java/de/zalando/zally/rule/ExtractBasePathRule.kt
innokenty
98,500,750
false
{"YAML": 7, "Markdown": 5, "Text": 4, "Ignore List": 7, "CODEOWNERS": 1, "Gradle": 4, "Shell": 4, "Batchfile": 2, "Java": 91, "OASv2-yaml": 22, "Java Properties": 2, "XML": 1, "NPM Config": 1, "JSON with Comments": 1, "JavaScript": 63, "JSON": 23, "EditorConfig": 1, "SCSS": 1, "Pug": 1, "Go": 28, "OASv2-json": 14, "Dockerfile": 1, "Kotlin": 94, "INI": 1, "SQL": 1}
package de.zalando.zally.rule import de.zalando.zally.dto.ViolationType import io.swagger.models.Swagger import org.springframework.stereotype.Component @Component class ExtractBasePathRule : SwaggerRule() { override val title = "Base path can be extracted" override val url = "/naming/Naming.html" override val violationType = ViolationType.HINT override val code = "H001" private val DESC_PATTERN = "All paths start with prefix '%s'. This prefix could be part of base path." override fun validate(swagger: Swagger): Violation? { val paths = swagger.paths.orEmpty().keys if (paths.size < 2) { return null } val commonPrefix = paths.reduce { s1, s2 -> findCommonPrefix(s1, s2) } return if (commonPrefix.isNotEmpty()) Violation(this, title, DESC_PATTERN.format(commonPrefix), violationType, url, emptyList()) else null } private fun findCommonPrefix(s1: String, s2: String): String { val parts1 = s1.split("/") val parts2 = s2.split("/") val (commonParts, _) = parts1.zip(parts2).takeWhile { (t1, t2) -> !t1.startsWith('{') && t1 == t2 }.unzip() return commonParts.joinToString("/") } }
1
null
1
1
b5caa7292cb70456d1fa5f014e1fd544ad549b20
1,231
zally
MIT License
mobile_app1/module364/src/main/java/module364packageKt0/Foo1467.kt
uber-common
294,831,672
false
null
package module364packageKt0; annotation class Foo1467Fancy @Foo1467Fancy class Foo1467 { fun foo0(){ module364packageKt0.Foo1466().foo6() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } fun foo6(){ foo5() } }
6
Java
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
331
android-build-eval
Apache License 2.0
foldingkit/src/main/java/com/cogitator/foldingit/animation/HeightAnimation.kt
AnkitDroidGit
131,563,607
false
null
package com.cogitator.foldingit.animation import android.view.View import android.view.animation.Animation import android.view.animation.Interpolator import android.view.animation.Transformation /** * Created by ankit on 26/01/2018. */ class HeightAnimation(mView: View, heightFrom: Int, heightTo: Int, duration: Int): Animation() { private val mView: View = mView private val mHeightFrom: Int = heightFrom private val mHeightTo: Int = heightTo init { this.duration = duration.toLong() } fun withInterpolator(interpolator: Interpolator?): HeightAnimation { if (interpolator != null) { this.interpolator = interpolator } return this } override fun applyTransformation(interpolatedTime: Float, t: Transformation) { val newHeight = mHeightFrom + (mHeightTo - mHeightFrom) * interpolatedTime if (interpolatedTime == 1f) { mView.layoutParams.height = mHeightTo } else { mView.layoutParams.height = newHeight.toInt() } mView.requestLayout() } override fun willChangeBounds(): Boolean { return true } override fun isFillEnabled(): Boolean { return false } override fun toString(): String { return "HeightAnimation{" + "mHeightFrom=" + mHeightFrom + ", mHeightTo=" + mHeightTo + ", offset =" + startOffset + ", duration =" + duration + '}'.toString() } }
1
null
4
22
763d715e37fa3afa3dc2cd9494a71c7627edb45e
1,529
FoldingAnimationKotlin-Android
Apache License 2.0
app/src/main/java/science/credo/mobiledetector/database/DetectionStateWrapper.kt
ryszkowski
242,184,782
true
{"Kotlin": 153786, "HTML": 18302, "Java": 5024}
package science.credo.mobiledetector.database import android.content.Context import science.credo.mobiledetector.events.StatsEvent import science.credo.mobiledetector.events.StatsValue class DetectionStateWrapper(context: Context, val prefix: String) : SharedPreferencesWrapper(context) { companion object { fun getTotal(context: Context) : DetectionStateWrapper { return DetectionStateWrapper(context, "total") } fun getLatestSession(context: Context) : DetectionStateWrapper { return DetectionStateWrapper(context, "session") } fun getLatestPing(context: Context) : DetectionStateWrapper { return DetectionStateWrapper(context, "ping") } } var frameWidth: Int get() { return preferences.getInt("${prefix}_frame_width", 0) } set(v) { setInt("${prefix}_frame_width", v) } var frameHeight: Int get() { return preferences.getInt("${prefix}_frame_height", 0) } set(v) { setInt("${prefix}_frame_height", v) } var startDetectionTimestamp: Long get() { return preferences.getLong("${prefix}_start_detection_timestamp", 0) } set(v) { setLong("${prefix}_start_detection_timestamp", v) } var lastFlushTimestamp: Long get() { return preferences.getLong("${prefix}_last_flush_timestamp", 0) } set(v) { setLong("${prefix}_last_flush_timestamp", v) } var lastFrameAchievedTimestamp: Long get() { return preferences.getLong("${prefix}_last_frame_achieved_timestamp", 0) } set(v) { setLong("${prefix}_last_frame_achieved_timestamp", v) } var lastFramePerformedTimestamp: Long get() { return preferences.getLong("${prefix}_last_frame_performed_timestamp", 0) } set(v) { setLong("${prefix}_last_frame_performed_timestamp", v) } var lastHitTimestamp: Long get() { return preferences.getLong("${prefix}_last_hit_timestamp", 0) } set(v) { setLong("${prefix}_last_hit_timestamp", v) } var allFrames: Int get() { return preferences.getInt("${prefix}_all_frames", 0) } set(v) { setInt("${prefix}_all_frames", v) } var performedFrames: Int get() { return preferences.getInt("${prefix}_performed_frames", 0) } set(v) { setInt("${prefix}_performed_frames", v) } var onTime: Long get() { return preferences.getLong("${prefix}_on_time", 0) } set(v) { setLong("${prefix}_on_time", v) } var blacksStats : StatsValue get() { return getStatsValue("${prefix}_blacks") } set(v) { setStatsValue("${prefix}_blacks", v) } var averageStats : StatsValue get() { return getStatsValue("${prefix}_average") } set(v) { setStatsValue("${prefix}_average", v) } var maxStats : StatsValue get() { return getStatsValue("${prefix}_max") } set(v) { setStatsValue("${prefix}_max", v) } private fun getStatsValue(key: String) : StatsValue { return StatsValue( preferences.getFloat("${key}_min", 0f).toDouble(), preferences.getFloat("${key}_max", 0f).toDouble(), preferences.getFloat("${key}_average", 0f).toDouble(), preferences.getInt("${key}_samples", 0) ) } private fun setStatsValue(key: String, v: StatsValue) { setFloat("${key}_min", v.min.toFloat() ?: 0f) setFloat("${key}_max", v.max.toFloat() ?: 0f) setFloat("${key}_average", v.average.toFloat() ?: 0f) setInt("${key}_samples", v.samples) } fun clear() { frameWidth = 0 frameHeight = 0 startDetectionTimestamp = 0 lastFlushTimestamp = 0 lastFrameAchievedTimestamp = 0 lastFramePerformedTimestamp = 0 lastHitTimestamp = 0 allFrames = 0 performedFrames = 0 onTime = 0 blacksStats = StatsValue() averageStats = StatsValue() maxStats = StatsValue() } fun merge(statsEvent: StatsEvent) { frameWidth = statsEvent.frameWidth frameHeight = statsEvent.frameHeight lastFlushTimestamp = System.currentTimeMillis() lastFrameAchievedTimestamp = statsEvent.lastFrameAchievedTimestamp lastFramePerformedTimestamp = statsEvent.lastFramePerformedTimestamp lastHitTimestamp = statsEvent.lastHitTimestamp allFrames += statsEvent.allFrames performedFrames += statsEvent.performedFrames onTime += statsEvent.onTime blacksStats = blacksStats.merge(statsEvent.blacksStats) averageStats = averageStats.merge(statsEvent.averageStats) maxStats = maxStats.merge(statsEvent.maxStats) } }
0
Kotlin
0
0
3f47f33c0cc11c241fc320ca03ffb66fd5effb7c
5,205
credo-detector-android
MIT License
src/test/kotlin/io/kotlintest/properties/EnumGenTest.kt
ruslanas
125,570,929
false
{"Markdown": 4, "Java Properties": 1, "Gradle": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "SVG": 1, "INI": 1, "Kotlin": 86, "Java": 2}
package io.kotlintest.properties import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class EnumGenTest : StringSpec() { init { "enum gen should work generically" { val gen = Gen.oneOf<Weather>() (1..1000).map { gen.generate() }.toSet() shouldBe setOf(Weather.Hot, Weather.Cold, Weather.Dry) } } } enum class Weather { Hot, Cold, Dry }
1
null
1
1
e0f8062f9bed2568601cf52d959ece5baa645b7f
401
kotlintest
Apache License 2.0
backend.native/tests/external/stdlib/numbers/NumbersTest/shortMinMaxValues.kt
acidburn0zzz
110,847,830
true
{"Kotlin": 3712759, "C++": 728274, "C": 132862, "Groovy": 52992, "JavaScript": 7780, "Shell": 6563, "Batchfile": 6379, "Objective-C++": 5203, "Objective-C": 1891, "Python": 1870, "Pascal": 1698, "Java": 782, "HTML": 185}
import kotlin.test.* object NumbersTestConstants { public const val byteMinSucc: Byte = (Byte.MIN_VALUE + 1).toByte() public const val byteMaxPred: Byte = (Byte.MAX_VALUE - 1).toByte() public const val shortMinSucc: Short = (Short.MIN_VALUE + 1).toShort() public const val shortMaxPred: Short = (Short.MAX_VALUE - 1).toShort() public const val intMinSucc: Int = Int.MIN_VALUE + 1 public const val intMaxPred: Int = Int.MAX_VALUE - 1 public const val longMinSucc: Long = Long.MIN_VALUE + 1L public const val longMaxPred: Long = Long.MAX_VALUE - 1L } var one: Int = 1 var oneS: Short = 1 var oneB: Byte = 1 fun box() { assertTrue(Short.MIN_VALUE < 0) assertTrue(Short.MAX_VALUE > 0) assertEquals(NumbersTestConstants.shortMinSucc, Short.MIN_VALUE.inc()) assertEquals(NumbersTestConstants.shortMaxPred, Short.MAX_VALUE.dec()) // overflow behavior expect(Short.MIN_VALUE) { (Short.MAX_VALUE + oneS).toShort() } expect(Short.MAX_VALUE) { (Short.MIN_VALUE - oneS).toShort() } }
1
Kotlin
0
1
7b9cd6c9f4f3f3218d48acc9ba3b9a1dd62cc57f
1,040
kotlin-native
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeArgumentsIntention.kt
PopFisher
93,638,097
true
{"Java": 23489397, "Kotlin": 22948050, "JavaScript": 137649, "Protocol Buffer": 57064, "HTML": 51139, "Lex": 18174, "Groovy": 14228, "ANTLR": 9797, "IDL": 8057, "Shell": 5883, "CSS": 4679, "Batchfile": 4437}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.calls.CallResolver import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) { override fun problemHighlightType(element: KtTypeArgumentList): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL } class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>(KtTypeArgumentList::class.java, "Remove explicit type arguments") { companion object { private fun KtCallExpression.argumentTypesDeducedFromReturnType(context: BindingContext): Boolean { val resolvedCall = getResolvedCall(context) ?: return false val typeParameters = resolvedCall.candidateDescriptor.typeParameters if (typeParameters.isEmpty()) return true val returnType = resolvedCall.candidateDescriptor.returnType ?: return false return returnType.arguments.map { it.type }.containsAll(typeParameters.map { it.defaultType }) } private fun KtCallExpression.hasExplicitExpectedType(context: BindingContext): Boolean { // todo Check with expected type for other expressions // If always use expected type from trace there is a problem with nested calls: // the expression type for them can depend on their explicit type arguments (via outer call), // therefore we should resolve outer call with erased type arguments for inner call val parent = parent return when (parent) { is KtProperty -> parent.initializer == this && parent.typeReference != null is KtDeclarationWithBody -> parent.bodyExpression == this is KtReturnExpression -> true is KtValueArgument -> (parent.parent.parent as? KtCallExpression)?.let { it.typeArgumentList != null || it.hasExplicitExpectedType(context) && it.argumentTypesDeducedFromReturnType(context) }?: false else -> false } } fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean { val callExpression = element.parent as? KtCallExpression ?: return false if (callExpression.typeArguments.isEmpty()) return false val resolutionFacade = callExpression.getResolutionFacade() val context = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL) val calleeExpression = callExpression.calleeExpression ?: return false val scope = calleeExpression.getResolutionScope(context, resolutionFacade) val originalCall = callExpression.getResolvedCall(context) ?: return false val untypedCall = CallWithoutTypeArgs(originalCall.call) val expectedTypeIsExplicitInCode = callExpression.hasExplicitExpectedType(context) val expectedType = if (expectedTypeIsExplicitInCode) { context[BindingContext.EXPECTED_EXPRESSION_TYPE, callExpression] ?: TypeUtils.NO_EXPECTED_TYPE } else { TypeUtils.NO_EXPECTED_TYPE } val dataFlow = context.getDataFlowInfoBefore(callExpression) val callResolver = resolutionFacade.frontendService<CallResolver>() val resolutionResults = callResolver.resolveFunctionCall( BindingTraceContext(), scope, untypedCall, expectedType, dataFlow, false) if (!resolutionResults.isSingleResult) { return false } val args = originalCall.typeArguments val newArgs = resolutionResults.resultingCall.typeArguments fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean { return if (approximateFlexible) { KotlinTypeChecker.DEFAULT.equalTypes(type1, type2) } else { type1 == type2 } } return args.size == newArgs.size && args.values.zip(newArgs.values).all { (argType, newArgType) -> equalTypes(argType, newArgType) } } } override fun isApplicableTo(element: KtTypeArgumentList): Boolean { return isApplicableTo(element, approximateFlexible = false) } private class CallWithoutTypeArgs(call: Call) : DelegatingCall(call) { override fun getTypeArguments() = emptyList<KtTypeProjection>() override fun getTypeArgumentList() = null } override fun applyTo(element: KtTypeArgumentList, editor: Editor?) { element.delete() } }
0
Java
0
1
c851e9d206c92da77cb9f8e8406c6974cbfae855
6,269
kotlin
Apache License 2.0
composeApp/src/desktopMain/kotlin/com/tecknobit/neutron/ui/theme/Type.kt
N7ghtm4r3
799,333,870
false
{"Kotlin": 208851, "Java": 1742}
package com.tecknobit.neutron.ui.theme import androidx.compose.material3.Typography import com.tecknobit.neutron.ui.bodyFontFamily import com.tecknobit.neutron.ui.displayFontFamily /** * **baseline** -> the Neutron's baseline */ val baseline = Typography() /** * **Typography** -> the Neutron's Typography */ val AppTypography = Typography( displayLarge = baseline.displayLarge.copy(fontFamily = displayFontFamily), displayMedium = baseline.displayMedium.copy(fontFamily = displayFontFamily), displaySmall = baseline.displaySmall.copy(fontFamily = displayFontFamily), headlineLarge = baseline.headlineLarge.copy(fontFamily = displayFontFamily), headlineMedium = baseline.headlineMedium.copy(fontFamily = displayFontFamily), headlineSmall = baseline.headlineSmall.copy(fontFamily = displayFontFamily), titleLarge = baseline.titleLarge.copy(fontFamily = displayFontFamily), titleMedium = baseline.titleMedium.copy(fontFamily = displayFontFamily), titleSmall = baseline.titleSmall.copy(fontFamily = displayFontFamily), bodyLarge = baseline.bodyLarge.copy(fontFamily = bodyFontFamily), bodyMedium = baseline.bodyMedium.copy(fontFamily = bodyFontFamily), bodySmall = baseline.bodySmall.copy(fontFamily = bodyFontFamily), labelLarge = baseline.labelLarge.copy(fontFamily = bodyFontFamily), labelMedium = baseline.labelMedium.copy(fontFamily = bodyFontFamily), labelSmall = baseline.labelSmall.copy(fontFamily = bodyFontFamily), )
0
Kotlin
0
0
8d6cef20d4f9692654e20d0eeb2acbc9a8dcf84d
1,492
Neutron-Desktop
MIT License
kotlin-library-development/src/main/kotlin/org/hexworks/kotlincode/libdev/example01/MyComponent.kt
AppCraft-Projects
119,160,613
false
null
package org.hexworks.kotlincode.libdev.example01 import org.hexworks.kotlincode.libdev.Container import org.hexworks.kotlincode.libdev.PixelGraphicsImpl @Suppress("unused", "UNUSED_PARAMETER") class MyComponent( // isFocused wasn't needed after all val children: List<MyComponent>, val drawSurface: PixelGraphicsImpl) { fun requestFocus() { } fun clearFocus() { } // these shouldn't have been exposed internal fun render() { } internal fun attachTo(container: Container) { } }
0
Kotlin
0
0
53f8a4f8a6a0ccf7713c7d7ed0d6766a85d0d64e
547
kotlin-code-examples
Apache License 2.0
tools/sap/src/main/kotlin/top/bettercode/summer/tools/sap/cost/CostSoKostl.kt
top-bettercode
387,652,015
false
{"Kotlin": 2860676, "Java": 23654, "JavaScript": 22541, "CSS": 22336, "HTML": 15833}
package top.bettercode.summer.tools.sap.cost import top.bettercode.summer.tools.lang.util.StringUtil.json import top.bettercode.summer.tools.sap.annotation.SapField class CostSoKostl { /** * @return 借方/贷方符号 (+/-) */ /** * 借方/贷方符号 (+/-) */ @SapField("SIGN") var sign: String? = null private set /** * @return 范围表选项 */ /** * 范围表选项 */ @SapField("OPTION") var option: String? = null private set /** * @return 成本中心 */ /** * 成本中心 */ @SapField("LOW") var low: String? = null private set /** * @return 成本中心 */ /** * 成本中心 */ @SapField("HIGH") var high: String? = null private set /** * 设置借方/贷方符号 (+/-) * * @param sign 借方/贷方符号 (+/-) * @return KOSTL的范围 */ fun setSign(sign: String?): CostSoKostl { this.sign = sign return this } /** * 设置范围表选项 * * @param option 范围表选项 * @return KOSTL的范围 */ fun setOption(option: String?): CostSoKostl { this.option = option return this } /** * 设置成本中心 * * @param low 成本中心 * @return KOSTL的范围 */ fun setLow(low: String?): CostSoKostl { this.low = low return this } /** * 设置成本中心 * * @param high 成本中心 * @return KOSTL的范围 */ fun setHigh(high: String?): CostSoKostl { this.high = high return this } override fun toString(): String { return json(this) } }
0
Kotlin
0
1
da096b3c592335e25869d9ff2cdb91c2551c794c
1,578
summer
Apache License 2.0
cosmos-sdk/src/jvmMain/kotlin/cosmos/evidence/v1beta1/query.grpc.kt
jdekim43
759,720,689
false
{"Kotlin": 8940168, "Java": 3242559}
// Transform from cosmos/evidence/v1beta1/query.proto @file:GeneratorVersion(version = "0.3.1") package cosmos.evidence.v1beta1 import kotlin.coroutines.CoroutineContext import kr.jadekim.protobuf.`annotation`.GeneratorVersion import kr.jadekim.protobuf.grpc.ClientOption import kr.jadekim.protobuf.grpc.GrpcService public actual object Query : GrpcService<Query.Interface, Query.Server, Query.Client> { public override fun createClient(option: ClientOption): Client = Client(option) public actual interface Interface { public actual suspend fun evidence(request: QueryEvidenceRequest): QueryEvidenceResponse public actual suspend fun allEvidence(request: QueryAllEvidenceRequest): QueryAllEvidenceResponse } public actual abstract class Server actual constructor( coroutineContext: CoroutineContext, ) : QueryJvm.Server(coroutineContext), Interface public actual open class Client actual constructor( option: ClientOption, ) : QueryJvm.Client(option), Interface }
0
Kotlin
0
0
eb9b3ba5ad6b798db1d8da208b5435fc5c1f6cdc
1,010
chameleon.proto
Apache License 2.0
msak-android/src/main/java/edu/gatech/cc/cellwatch/msak/ServerLocation.kt
CellWatch
817,407,008
false
{"Kotlin": 56473}
package edu.gatech.cc.cellwatch.msak /** * The location of a server returned by the Locate API. * * @param city The city in which the server is located. * @param country The country in which the server is located. */ data class ServerLocation( val city: String?, val country: String?, )
0
Kotlin
0
0
beff356bc1b9dacedf28ce4cbfe26cfe7db5ca9a
301
msak-android
Apache License 2.0
src/main/kotlin/com/mparticle/kits/ApptimizeKit.kt
mparticle-integrations
68,017,077
false
null
package com.mparticle.kits import android.content.Context import android.text.TextUtils import com.apptimize.Apptimize import com.apptimize.Apptimize.IsFirstTestRun import com.apptimize.Apptimize.OnTestRunListener import com.apptimize.ApptimizeOptions import com.apptimize.ApptimizeTestInfo import com.mparticle.MPEvent import com.mparticle.MParticle import com.mparticle.MParticle.IdentityType import com.mparticle.commerce.CommerceEvent import com.mparticle.kits.KitIntegration.AttributeListener import com.mparticle.kits.KitIntegration.CommerceListener import java.math.BigDecimal class ApptimizeKit : KitIntegration(), AttributeListener, KitIntegration.EventListener, CommerceListener, OnTestRunListener { private fun toMessageList(message: ReportingMessage): List<ReportingMessage> { return listOf(message) } private fun createReportingMessage(messageType: String): ReportingMessage { return ReportingMessage( this, messageType, System.currentTimeMillis(), null ) } override fun onKitCreate( settings: Map<String, String>, context: Context ): List<ReportingMessage> { val appKey = getSettings()[APP_MP_KEY] require(!TextUtils.isEmpty(appKey)) { APP_MP_KEY } val options = buildApptimizeOptions(settings) Apptimize.setup(context, appKey, options) if (java.lang.Boolean.parseBoolean(settings[TRACK_EXPERIMENTS])) { Apptimize.setOnTestRunListener(this) } return emptyList() } private fun buildApptimizeOptions(settings: Map<String, String>): ApptimizeOptions { val o = ApptimizeOptions() o.isThirdPartyEventImportingEnabled = false o.isThirdPartyEventExportingEnabled = false configureApptimizeUpdateMetaDataTimeout(o, settings) configureApptimizeDeviceName(o, settings) configureApptimizeDeveloperModeDisabled(o, settings) configureApptimizeExplicitEnablingRequired(o, settings) configureApptimizeMultiprocessModeEnabled(o, settings) configureApptimizeLogLevel(o, settings) return o } private fun configureApptimizeUpdateMetaDataTimeout( o: ApptimizeOptions, settings: Map<String, String> ) { try { settings[UPDATE_METDATA_TIMEOUT_MP_KEY]?.let { val l = it.toLong() o.setUpdateMetadataTimeout(l) } } catch (nfe: NumberFormatException) { } } private fun configureApptimizeDeviceName(o: ApptimizeOptions, settings: Map<String, String>) { val v = settings[DEVICE_NAME_MP_KEY] o.deviceName = v } private fun configureApptimizeDeveloperModeDisabled( o: ApptimizeOptions, settings: Map<String, String> ) { val b = settings[DEVELOPER_MODE_DISABLED_MP_KEY] o.isDeveloperModeDisabled = b.toBoolean() } private fun configureApptimizeExplicitEnablingRequired( o: ApptimizeOptions, settings: Map<String, String> ) { val b = settings[EXPLICIT_ENABLING_REQUIRED_MP_KEY] o.isExplicitEnablingRequired = b.toBoolean() } private fun configureApptimizeMultiprocessModeEnabled( o: ApptimizeOptions, settings: Map<String, String> ) { val b = settings[MULTIPROCESS_MODE_ENABLED_MP_KEY] o.setMultiprocessMode(b.toBoolean()) } private fun configureApptimizeLogLevel(o: ApptimizeOptions, settings: Map<String, String>) { try { val l = settings[LOG_LEVEL_MP_KEY] ?.let { ApptimizeOptions.LogLevel.valueOf(it) } ?.let { o.logLevel = it } } catch (iae: IllegalArgumentException) { } catch (npe: NullPointerException) { } } override fun getName(): String = KIT_NAME override fun setUserAttribute(key: String, value: String) { Apptimize.setUserAttribute(key, value) } /** * Not supported by the Apptimize kit. */ override fun setUserAttributeList(key: String, list: List<String>) { // not supported } override fun supportsAttributeLists(): Boolean = false /** * @param attributeLists is ignored by the Apptimize kit. */ override fun setAllUserAttributes( attributes: Map<String, String>, attributeLists: Map<String, List<String>> ) { for ((key, value) in attributes) { setUserAttribute(key, value) } } override fun removeUserAttribute(key: String) { Apptimize.clearUserAttribute(key) } /** * @param identityType only Alias and CustomerId are suppoted by the Apptimize kit. */ override fun setUserIdentity(identityType: IdentityType, id: String?) { when (identityType) { IdentityType.Alias, IdentityType.CustomerId -> { Apptimize.setPilotTargetingId(id) } else -> {} } } override fun removeUserIdentity(identityType: IdentityType) { setUserIdentity(identityType, null) } override fun logout(): List<ReportingMessage> { Apptimize.track(LOGOUT_TAG) return toMessageList(ReportingMessage.logoutMessage(this)) } /** * Not supported by the Apptimize kit. */ override fun leaveBreadcrumb(s: String): List<ReportingMessage> = emptyList() /** * Not supported by the Apptimize kit. */ override fun logError(s: String, map: Map<String, String>): List<ReportingMessage> = emptyList() /** * Not supported by the Apptimize kit. */ override fun logException( e: Exception, map: Map<String, String>, s: String ): List<ReportingMessage> = emptyList() override fun logEvent(mpEvent: MPEvent): List<ReportingMessage> { Apptimize.track(mpEvent.eventName) return toMessageList(ReportingMessage.fromEvent(this, mpEvent)) } /** * @param eventAttributes is ignored by the Apptimize kit. */ override fun logScreen( screenName: String, eventAttributes: Map<String, String> ): List<ReportingMessage> { val event = String.format(VIEWED_EVENT_FORMAT, screenName) Apptimize.track(event) return toMessageList( createReportingMessage(ReportingMessage.MessageType.SCREEN_VIEW).setScreenName( screenName ) ) } /** * @param valueTotal is ignored by the Apptimize kit. * @param contextInfo is ignored by the Apptimize kit. */ override fun logLtvIncrease( valueIncreased: BigDecimal, valueTotal: BigDecimal, eventName: String, contextInfo: Map<String, String> ): List<ReportingMessage> { // match the iOS style, where only the delta is sent rather than an absolute final value. Apptimize.track(LTV_TAG, valueIncreased.toDouble()) return toMessageList(createReportingMessage(ReportingMessage.MessageType.COMMERCE_EVENT)) } override fun logEvent(commerceEvent: CommerceEvent): List<ReportingMessage>? { val customEvents = CommerceEventUtils.expand(commerceEvent) if (customEvents.size == 0) { return null } for (event in customEvents) { Apptimize.track(event.eventName) } return toMessageList(ReportingMessage.fromEvent(this, commerceEvent)) } /** * After opting out, it is not possible to opt back in via the Apptimize kit. * @param optedOut only a value of 'true' supported by the Apptimize kit. */ override fun setOptOut(optedOut: Boolean): List<ReportingMessage>? { var ret: List<ReportingMessage>? = null if (optedOut) { Apptimize.disable() ret = toMessageList( createReportingMessage(ReportingMessage.MessageType.OPT_OUT).setOptOut(optedOut) ) } return ret } override fun onTestRun(apptimizeTestInfo: ApptimizeTestInfo, isFirstTestRun: IsFirstTestRun) { if (isFirstTestRun != IsFirstTestRun.YES) { return } val testInfoMap = Apptimize.getTestInfo() val participatedExperiments: MutableList<String> = ArrayList() if (testInfoMap == null) { return } for (key in testInfoMap.keys) { val testInfo = testInfoMap[key] if (testInfo != null) { if (testInfo.userHasParticipated()) { val nameAndVariation = testInfo.testName + "-" + testInfo.enrolledVariantName participatedExperiments.add(nameAndVariation) } } } val user = MParticle.getInstance()!!.Identity().currentUser user?.setUserAttributeList("Apptimize experiment", participatedExperiments) val eventInfo = HashMap<String, String?>(5) eventInfo["VariationID"] = apptimizeTestInfo.enrolledVariantId.toString() eventInfo["ID"] = apptimizeTestInfo.testId.toString() eventInfo["Name"] = apptimizeTestInfo.testName eventInfo["Variation"] = apptimizeTestInfo.enrolledVariantName eventInfo["Name and Variation"] = (apptimizeTestInfo.testName + "-" + apptimizeTestInfo.enrolledVariantName) val event = MPEvent.Builder("Apptimize experiment", MParticle.EventType.Other) .customAttributes(eventInfo) .build() MParticle.getInstance()?.logEvent(event) } companion object { private const val APP_MP_KEY = "appKey" private const val UPDATE_METDATA_TIMEOUT_MP_KEY = "metadataTimeout" private const val DEVICE_NAME_MP_KEY = "deviceName" private const val DEVELOPER_MODE_DISABLED_MP_KEY = "developerModeDisabled" private const val EXPLICIT_ENABLING_REQUIRED_MP_KEY = "explicitEnablingRequired" private const val MULTIPROCESS_MODE_ENABLED_MP_KEY = "multiprocessModeEnabled" private const val LOG_LEVEL_MP_KEY = "logLevel" private const val LOGOUT_TAG = "logout" private const val LTV_TAG = "ltv" private const val VIEWED_EVENT_FORMAT = "screenView %s" private const val TRACK_EXPERIMENTS = "trackExperiments" private const val KIT_NAME = "Apptimize" } }
4
Kotlin
7
1
0a5ae72a088581c510659f31356aebb01416e10d
10,383
mparticle-android-integration-apptimize
Apache License 2.0
app/src/main/java/com/example/animedroid/ui/fragments/AnimeDetailsFragment.kt
jamesdpli
564,412,128
false
null
package com.example.animedroid.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.navArgs import coil.load import com.example.animedroid.databinding.FragmentAnimeDetailsBinding import com.example.animedroid.ui.viewmodels.AnimeDetailFragmentViewModel import com.example.animedroid.ui.viewmodels.ViewModelFactory import dagger.android.support.DaggerFragment import javax.inject.Inject class AnimeDetailsFragment : DaggerFragment() { private val safeArgs: AnimeDetailsFragmentArgs by navArgs() private var _binding: FragmentAnimeDetailsBinding? = null private val binding get() = _binding!! @Inject lateinit var viewModelFactory: ViewModelFactory private val viewModel: AnimeDetailFragmentViewModel by lazy { ViewModelProvider(this, viewModelFactory)[AnimeDetailFragmentViewModel::class.java] } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentAnimeDetailsBinding.inflate(inflater, container, false) setUpUI() return binding.root } private fun setUpUI() { viewModel.getAnimeById(animeId = safeArgs.animeId) viewModel.animeDetailLiveData.observe(viewLifecycleOwner) { response -> binding.animeDetailsName.text = response.data.attributes.canonicalTitle binding.animeDetailsDescription.text = response.data.attributes.description binding.animeDetailsImage.load(response.data.attributes.posterImage.large) } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
null
0
1
87219d47839a191ccf63714f7c105f8f2e393dc7
1,810
AnimeDroid
Apache License 2.0
dsl/src/main/kotlin/cloudshift/awscdk/dsl/cloudassembly/schema/FileAssetDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION") package cloudshift.awscdk.dsl.cloudassembly.schema import cloudshift.awscdk.common.CdkDslMarker import software.amazon.awscdk.cloudassembly.schema.FileAsset import software.amazon.awscdk.cloudassembly.schema.FileDestination import software.amazon.awscdk.cloudassembly.schema.FileSource import kotlin.String import kotlin.Unit import kotlin.collections.Map /** * A file asset. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.cloudassembly.schema.*; * FileAsset fileAsset = FileAsset.builder() * .destinations(Map.of( * "destinationsKey", FileDestination.builder() * .bucketName("bucketName") * .objectKey("objectKey") * // the properties below are optional * .assumeRoleArn("assumeRoleArn") * .assumeRoleExternalId("assumeRoleExternalId") * .region("region") * .build())) * .source(FileSource.builder() * .executable(List.of("executable")) * .packaging(FileAssetPackaging.FILE) * .path("path") * .build()) * .build(); * ``` */ @CdkDslMarker public class FileAssetDsl { private val cdkBuilder: FileAsset.Builder = FileAsset.builder() /** * @param destinations Destinations for this file asset. */ public fun destinations(destinations: Map<String, FileDestination>) { cdkBuilder.destinations(destinations) } /** * @param source Source description for file assets. */ public fun source(source: FileSourceDsl.() -> Unit = {}) { val builder = FileSourceDsl() builder.apply(source) cdkBuilder.source(builder.build()) } /** * @param source Source description for file assets. */ public fun source(source: FileSource) { cdkBuilder.source(source) } public fun build(): FileAsset = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
2,049
awscdk-dsl-kotlin
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/BellSlash.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.BellSlash: ImageVector get() { if (_bellSlash != null) { return _bellSlash!! } _bellSlash = Builder(name = "BellSlash", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(12.01f, 16.981f) lineToRelative(4.414f, 4.414f) curveToRelative(-0.943f, 1.512f, -2.562f, 2.605f, -4.429f, 2.605f) curveToRelative(-2.413f, 0.0f, -4.426f, -1.818f, -5.077f, -4.019f) lineTo(2.774f, 19.981f) curveToRelative(-0.763f, 0.0f, -1.473f, -0.341f, -1.95f, -0.936f) curveToRelative(-0.477f, -0.594f, -0.656f, -1.362f, -0.491f, -2.106f) lineTo(2.485f, 7.456f) lineToRelative(2.507f, 2.507f) lineToRelative(-1.594f, 7.018f) horizontalLineToRelative(8.612f) close() moveTo(21.84f, 23.961f) lineTo(0.04f, 2.161f) lineTo(2.161f, 0.04f) lineToRelative(2.797f, 2.797f) curveToRelative(1.722f, -1.771f, 4.122f, -2.837f, 6.759f, -2.837f) curveToRelative(4.226f, 0.0f, 7.968f, 2.844f, 9.099f, 6.916f) lineToRelative(2.805f, 9.896f) curveToRelative(0.211f, 0.759f, 0.059f, 1.555f, -0.418f, 2.182f) curveToRelative(-0.316f, 0.416f, -0.741f, 0.714f, -1.221f, 0.868f) lineToRelative(1.978f, 1.978f) lineToRelative(-2.121f, 2.121f) close() moveTo(19.103f, 16.981f) horizontalLineToRelative(1.452f) lineToRelative(-2.628f, -9.262f) curveToRelative(-0.771f, -2.778f, -3.325f, -4.719f, -6.208f, -4.719f) curveToRelative(-1.813f, 0.0f, -3.457f, 0.74f, -4.629f, 1.967f) lineToRelative(12.014f, 12.014f) close() } } .build() return _bellSlash!! } private var _bellSlash: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,921
icons
MIT License
app/src/main/java/com/breezefsmp12/features/login/model/productlistmodel/ModelListResponse.kt
DebashisINT
652,463,111
false
null
package com.breezefsmp12.features.login.model.productlistmodel import com.breezefsmp12.app.domain.ModelEntity import com.breezefsmp12.app.domain.ProductListEntity import com.breezefsmp12.base.BaseResponse class ModelListResponse: BaseResponse() { var model_list: ArrayList<ModelEntity>? = null }
0
Kotlin
0
0
4c78c29abaffaf8e95dc9e241dc3d9afc3bd5469
301
StepUpP12
Apache License 2.0
plot-builder/src/commonMain/kotlin/jetbrains/datalore/plot/builder/interact/loc/LayerTargetLocator.kt
tchigher
229,856,588
true
{"Kotlin": 4345032, "Python": 257583, "CSS": 1842, "C": 1638, "Shell": 1590, "JavaScript": 1584}
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.plot.builder.interact.loc import jetbrains.datalore.base.gcommon.base.Preconditions.checkArgument import jetbrains.datalore.base.geometry.DoubleVector import jetbrains.datalore.plot.base.GeomKind import jetbrains.datalore.plot.base.interact.ContextualMapping import jetbrains.datalore.plot.base.interact.GeomTarget import jetbrains.datalore.plot.base.interact.GeomTargetLocator import jetbrains.datalore.plot.base.interact.HitShape.Kind.* import jetbrains.datalore.plot.builder.interact.MathUtil.ClosestPointChecker import kotlin.math.max internal class LayerTargetLocator( private val geomKind: GeomKind, lookupSpec: GeomTargetLocator.LookupSpec, private val contextualMapping: ContextualMapping, targetPrototypes: List<jetbrains.datalore.plot.builder.interact.loc.TargetPrototype>) : GeomTargetLocator { private val myTargets = ArrayList<jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Target>() private val myTargetDetector: jetbrains.datalore.plot.builder.interact.loc.TargetDetector = jetbrains.datalore.plot.builder.interact.loc.TargetDetector(lookupSpec.lookupSpace, lookupSpec.lookupStrategy) private val myCollectingStrategy: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy = if (lookupSpec.lookupSpace === GeomTargetLocator.LookupSpace.X) { jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.APPEND } else if (lookupSpec.lookupStrategy === GeomTargetLocator.LookupStrategy.HOVER) { jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.APPEND } else if (lookupSpec.lookupStrategy === GeomTargetLocator.LookupStrategy.NONE || lookupSpec.lookupSpace === GeomTargetLocator.LookupSpace.NONE) { jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.IGNORE } else { jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.REPLACE } init { fun toProjection(prototype: jetbrains.datalore.plot.builder.interact.loc.TargetPrototype): jetbrains.datalore.plot.builder.interact.loc.TargetProjection { return when (prototype.hitShape.kind) { POINT -> jetbrains.datalore.plot.builder.interact.loc.PointTargetProjection.Companion.create( prototype.hitShape.point.center, lookupSpec.lookupSpace ) RECT -> jetbrains.datalore.plot.builder.interact.loc.RectTargetProjection.Companion.create( prototype.hitShape.rect, lookupSpec.lookupSpace ) POLYGON -> jetbrains.datalore.plot.builder.interact.loc.PolygonTargetProjection.Companion.create( prototype.hitShape.points, lookupSpec.lookupSpace ) PATH -> jetbrains.datalore.plot.builder.interact.loc.PathTargetProjection.Companion.create( prototype.hitShape.points, prototype.indexMapper, lookupSpec.lookupSpace ) } } for (prototype in targetPrototypes) { myTargets.add( jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Target( toProjection(prototype), prototype ) ) } } private fun addLookupResults(collector: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>, targets: MutableList<GeomTargetLocator.LookupResult>) { if (collector.size() == 0) { return } targets.add( GeomTargetLocator.LookupResult( collector.collection(), // Distance can be negative when lookup space is X // In this case use 0.0 as a distance - we have a direct hit. max(0.0, collector.closestPointChecker.distance), geomKind, contextualMapping ) ) } override fun search(coord: DoubleVector): GeomTargetLocator.LookupResult? { if (myTargets.isEmpty()) { return null } val rectCollector = jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>( coord, myCollectingStrategy ) val pointCollector = jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>( coord, myCollectingStrategy ) val pathCollector = jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>( coord, myCollectingStrategy ) // Should always replace because of polygon with holes - only top should have tooltip. val polygonCollector = jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>( coord, jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.REPLACE ) for (target in myTargets) { when (target.prototype.hitShape.kind) { RECT -> processRect(coord, target, rectCollector) POINT -> processPoint(coord, target, pointCollector) PATH -> processPath(coord, target, pathCollector) POLYGON -> processPolygon(coord, target, polygonCollector) } } val lookupResults = ArrayList<GeomTargetLocator.LookupResult>() addLookupResults(pathCollector, lookupResults) addLookupResults(rectCollector, lookupResults) addLookupResults(pointCollector, lookupResults) addLookupResults(polygonCollector, lookupResults) return getClosestTarget(lookupResults) } private fun getClosestTarget(lookupResults: List<GeomTargetLocator.LookupResult>): GeomTargetLocator.LookupResult? { if (lookupResults.isEmpty()) { return null } var closestTargets: GeomTargetLocator.LookupResult = lookupResults[0] checkArgument(closestTargets.distance >= 0) for (lookupResult in lookupResults) { if (lookupResult.distance < closestTargets.distance) { closestTargets = lookupResult } } return closestTargets } private fun processRect(coord: DoubleVector, target: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Target, resultCollector: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>) { if (myTargetDetector.checkRect(coord, target.rectProjection, resultCollector.closestPointChecker)) { val rect = target.prototype.hitShape.rect resultCollector.collect( target.prototype.crateGeomTarget( rect.origin.add(DoubleVector(rect.width / 2, 0.0)), getKeyForSingleObjectGeometry(target.prototype) ) ) } } private fun processPolygon(coord: DoubleVector, target: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Target, resultCollector: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>) { if (myTargetDetector.checkPolygon(coord, target.polygonProjection, resultCollector.closestPointChecker)) { resultCollector.collect( target.prototype.crateGeomTarget( coord, getKeyForSingleObjectGeometry(target.prototype) ) ) } } private fun processPoint(coord: DoubleVector, target: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Target, resultCollector: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>) { if (myTargetDetector.checkPoint(coord, target.pointProjection, resultCollector.closestPointChecker)) { resultCollector.collect( target.prototype.crateGeomTarget( target.prototype.hitShape.point.center, getKeyForSingleObjectGeometry(target.prototype) ) ) } } private fun processPath(coord: DoubleVector, target: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Target, resultCollector: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector<GeomTarget>) { // When searching single point from all targets (REPLACE) - should search nearest projection between every path target. // When searching points for every target (APPEND) - should reset nearest point between every path target. val pointChecker = if (myCollectingStrategy == jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.APPEND) ClosestPointChecker(coord) else resultCollector.closestPointChecker val hitPoint = myTargetDetector.checkPath(coord, target.pathProjection, pointChecker) if (hitPoint != null) { resultCollector.collect( target.prototype.crateGeomTarget( hitPoint.originalCoord, hitPoint.index ) ) } } private fun getKeyForSingleObjectGeometry(prototype: jetbrains.datalore.plot.builder.interact.loc.TargetPrototype): Int { return prototype.indexMapper(0) } internal class Target(private val targetProjection: jetbrains.datalore.plot.builder.interact.loc.TargetProjection, val prototype: jetbrains.datalore.plot.builder.interact.loc.TargetPrototype) { val pointProjection: jetbrains.datalore.plot.builder.interact.loc.PointTargetProjection get() = targetProjection as jetbrains.datalore.plot.builder.interact.loc.PointTargetProjection val rectProjection: jetbrains.datalore.plot.builder.interact.loc.RectTargetProjection get() = targetProjection as jetbrains.datalore.plot.builder.interact.loc.RectTargetProjection val polygonProjection: jetbrains.datalore.plot.builder.interact.loc.PolygonTargetProjection get() = targetProjection as jetbrains.datalore.plot.builder.interact.loc.PolygonTargetProjection val pathProjection: jetbrains.datalore.plot.builder.interact.loc.PathTargetProjection get() = targetProjection as jetbrains.datalore.plot.builder.interact.loc.PathTargetProjection } internal class Collector<T>(cursor: DoubleVector, private val myStrategy: jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy) { private val result = ArrayList<T>() val closestPointChecker: ClosestPointChecker = ClosestPointChecker(cursor) fun collect(data: T) { when (myStrategy) { jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.APPEND -> add(data) jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.REPLACE -> replace(data) jetbrains.datalore.plot.builder.interact.loc.LayerTargetLocator.Collector.CollectingStrategy.IGNORE -> return } } fun collection(): List<T> { return result } fun size(): Int { return result.size } private fun add(data: T) { result.add(data) } private fun replace(locationData: T) { result.clear() result.add(locationData) } internal enum class CollectingStrategy { APPEND, REPLACE, IGNORE } } }
0
null
0
0
f6fd07e9f44c789206a720dcf213d0202392976f
12,301
lets-plot
MIT License
craft/craft-api/src/main/kotlin/me/ddevil/shiroi/craft/config/YAMLFileConfigManager.kt
BrunoSilvaFreire
88,535,533
false
null
package me.ddevil.shiroi.craft.config import me.ddevil.shiroi.craft.plugin.ShiroiPlugin import org.bukkit.configuration.file.YamlConfiguration import java.io.File open class YAMLFileConfigManager<K : FileConfigSource> constructor( plugin: ShiroiPlugin<*, *>, colorDesignKey: FileConfigValue<*, K> ) : AbstractFileConfigManager<K, YamlConfiguration>(plugin, colorDesignKey) { override fun loadConfig(file: File): YamlConfiguration { return YamlConfiguration.loadConfiguration(file) } override fun <T : Any> loadValue(value: FileConfigValue<T, K>, source: YamlConfiguration): Any? { return source[value.path] } }
2
null
1
1
5060ef1b811a3fe5d86e2b3498f6814239dce6d2
664
ShiroiFramework
Do What The F*ck You Want To Public License
src/test/kotlin/org/geepawhill/yz/GameModelTest.kt
GeePawHill
287,302,267
false
null
package org.geepawhill.yz import org.assertj.core.api.Assertions.assertThat import org.geepawhill.yz.event.CanRollChange import org.geepawhill.yz.event.CurrentPlayer import org.geepawhill.yz.event.GameStart import org.geepawhill.yz.event.PipChange import org.geepawhill.yz.game.YzGame import org.geepawhill.yz.ui.GameModel import org.junit.jupiter.api.Test class GameModelTest { val game = YzGame() val model = GameModel(game) @Test fun `handles pips change events`() { game.bus.post(PipChange(4, 6)) assertThat(model.dice[4].pips).isEqualTo(6) } @Test fun `handles canRoll change events`() { game.bus.post(CanRollChange(true)) assertThat(model.canRoll.value).isEqualTo(true) } @Test fun `resets player list on game start`() { game.bus.post(GameStart(listOf("GeePaw", "Molly", "Wally"))) assertThat(model.players.size).isEqualTo(3) assertThat(model.players[0].name).isEqualTo("GeePaw") assertThat(model.players[1].name).isEqualTo("Molly") assertThat(model.players[2].name).isEqualTo("Wally") } @Test fun `changes currency on CurrentPlayer`() { game.bus.post(GameStart(listOf("Wally", "Molly"))) game.bus.post(CurrentPlayer(1)) assertThat(model.players[1].isCurrent.value).isTrue() assertThat(model.players[0].isCurrent.value).isFalse() } @Test fun `NO_PLAYER turns currency off on CurrentPlayer`() { game.bus.post(GameStart(listOf("Wally", "Molly"))) game.bus.post(CurrentPlayer(CurrentPlayer.NO_PLAYER)) assertThat(model.players[1].isCurrent.value).isFalse() assertThat(model.players[0].isCurrent.value).isFalse() } }
0
Kotlin
3
9
6a928ec0a8b0619fd4d29f45573503f2aedac3f3
1,730
yz
MIT License
sdk/src/main/kotlin/com/processout/sdk/api/dispatcher/DefaultEventDispatchers.kt
processout
117,821,122
false
{"Kotlin": 843418, "Java": 85526, "Shell": 696}
package com.processout.sdk.api.dispatcher import com.processout.sdk.api.dispatcher.card.tokenization.POCardTokenizationEventDispatcher import com.processout.sdk.api.dispatcher.card.tokenization.PODefaultCardTokenizationEventDispatcher import com.processout.sdk.api.dispatcher.card.update.POCardUpdateEventDispatcher import com.processout.sdk.api.dispatcher.card.update.PODefaultCardUpdateEventDispatcher import com.processout.sdk.api.dispatcher.napm.PODefaultNativeAlternativePaymentMethodEventDispatcher internal object DefaultEventDispatchers : POEventDispatchers { override val nativeAlternativePaymentMethod: PONativeAlternativePaymentMethodEventDispatcher by lazy { PODefaultNativeAlternativePaymentMethodEventDispatcher } override val cardTokenization: POCardTokenizationEventDispatcher by lazy { PODefaultCardTokenizationEventDispatcher } override val cardUpdate: POCardUpdateEventDispatcher by lazy { PODefaultCardUpdateEventDispatcher } }
0
Kotlin
5
2
d7e4214b244c2664c090c03650080a6996dd7809
1,001
processout-android
MIT License
koin-projects/koin-androidx-viewmodel/src/main/java/org/koin/androidx/viewmodel/scope/ScopeStateVMExt.kt
akram09
187,230,273
true
{"AsciiDoc": 5, "Markdown": 53, "Text": 3, "Ignore List": 6, "Gradle": 27, "Shell": 9, "Java Properties": 2, "Batchfile": 1, "INI": 9, "XML": 54, "Kotlin": 267, "Java": 6, "HTML": 2, "CSS": 1, "JavaScript": 2, "Proguard": 1, "YAML": 1}
/* * Copyright 2017-2018 the original author or authors. * * 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.koin.androidx.viewmodel.scope import android.os.Bundle import androidx.lifecycle.ViewModel import androidx.savedstate.SavedStateRegistryOwner import org.koin.androidx.viewmodel.ViewModelParameter import org.koin.androidx.viewmodel.ext.android.getViewModelStore import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import org.koin.core.scope.Scope import kotlin.reflect.KClass /** * LifecycleOwner extensions to help for ViewModel * * @author Arnaud Giuliani */ inline fun <reified T : ViewModel> Scope.getStateViewModel( owner: SavedStateRegistryOwner, qualifier: Qualifier? = null, bundle: Bundle? = null, noinline parameters: ParametersDefinition? = null ): T { val bundleOrDefault: Bundle = bundle ?: Bundle() return getViewModel( ViewModelParameter( T::class, qualifier, parameters, bundleOrDefault, owner.getViewModelStore(), owner ) ) } fun <T : ViewModel> Scope.getStateViewModel( owner: SavedStateRegistryOwner, clazz: KClass<T>, qualifier: Qualifier? = null, bundle: Bundle? = null, parameters: ParametersDefinition? = null ): T { val bundleOrDefault: Bundle = bundle ?: Bundle() return getViewModel( ViewModelParameter( clazz, qualifier, parameters, bundleOrDefault, owner.getViewModelStore(), owner ) ) } inline fun <reified T : ViewModel> Scope.stateViewModel( owner: SavedStateRegistryOwner, qualifier: Qualifier? = null, bundle: Bundle? = null, noinline parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getStateViewModel(owner, T::class, qualifier, bundle, parameters) } } fun <T : ViewModel> Scope.stateViewModel( owner: SavedStateRegistryOwner, clazz: KClass<T>, qualifier: Qualifier? = null, bundle: Bundle? = null, parameters: ParametersDefinition? = null ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { getStateViewModel(owner, clazz, qualifier, bundle, parameters) } }
0
Kotlin
0
1
654068b498ad5d47f8aa4cef016265263f6d32b8
2,987
koin
Apache License 2.0
client/src/commonTest/kotlin/documentation/parameters/ranking/DocCustomRanking.kt
algolia
153,273,215
false
null
package documentation.parameters.ranking import com.algolia.search.dsl.customRanking import com.algolia.search.dsl.settings import documentation.index import runBlocking import kotlin.test.Ignore import kotlin.test.Test @Ignore internal class DocCustomRanking { // customRanking { // +[Asc](#parameter-option-asc)("attribute1") // +[Desc](#parameter-option-desc)("attribute2") // } @Test fun snippet1() { runBlocking { val settings = settings { customRanking { +Desc("popularity") +Asc("price") } } index.setSettings(settings) } } }
8
null
11
43
1e538208c9aa109653f334ecd22a8205e294c5c1
694
algoliasearch-client-kotlin
MIT License
app/src/main/java/fingerfire/com/valorant/features/weapons/data/response/WeaponDetailResponse.kt
marlonsantini
598,339,783
false
null
package fingerfire.com.valorant.features.weapons.data.response import com.squareup.moshi.Json data class WeaponDetailResponse( @Json(name = "data") val data: WeaponDetailDataResponse, @Json(name = "status") val status: String )
0
Kotlin
0
3
e1b1729a09d23183338ab3e5b79713acf4a0451b
245
ValoGuide
Apache License 2.0
src/main/kotlin/dk/cachet/carp/webservices/study/serdes/StudyServiceRequestDeserializer.kt
cph-cachet
674,650,033
false
{"Kotlin": 658732, "HTML": 11277, "Shell": 2895, "Dockerfile": 922}
package dk.cachet.carp.webservices.study.serdes import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.TreeNode import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import dk.cachet.carp.common.infrastructure.serialization.JSON import dk.cachet.carp.studies.infrastructure.StudyServiceRequest import dk.cachet.carp.webservices.common.configuration.internationalisation.service.MessageBase import dk.cachet.carp.webservices.common.exception.serialization.SerializationException import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import org.springframework.util.StringUtils /** * The Class [StudyServiceRequestDeserializer]. * The [StudyServiceRequestDeserializer] implements the deserialization logic for [StudyServiceRequest]. */ class StudyServiceRequestDeserializer(private val validationMessages: MessageBase): JsonDeserializer<StudyServiceRequest<*>>() { companion object { private val LOGGER: Logger = LogManager.getLogger() } /** * The [deserialize] function is used to deserialize the parsed object. * * @param jsonParser The [jsonParser] object containing the json object parsed. * @throws SerializationException If the [StudyServiceRequest] is blank or empty. * Also, if the [StudyServiceRequest] contains invalid format. * @return The deserialized [StudyServiceRequest] object. */ override fun deserialize(jsonParser: JsonParser?, context: DeserializationContext?): StudyServiceRequest<*> { val studyServiceRequest: String try { studyServiceRequest = jsonParser?.codec?.readTree<TreeNode>(jsonParser).toString() if (!StringUtils.hasLength(studyServiceRequest)) { LOGGER.error("The StudyServiceRequest cannot be blank or empty.") throw SerializationException(validationMessages.get("study.service.deserialization.empty")) } } catch (ex: Exception) { LOGGER.error("The core study request contains bad format. Exception: ${ex.message}") throw SerializationException(validationMessages.get("study.service.deserialization.bad_format", ex.message.toString())) } val parsed: StudyServiceRequest<*> try { parsed = JSON.decodeFromString(StudyServiceRequest.Serializer, studyServiceRequest) } catch (ex: Exception) { LOGGER.error("The core study serializer is not valid. Exception: ${ex.message}") throw SerializationException(validationMessages.get("study.service.deserialization.error", ex.message.toString())) } return parsed } }
6
Kotlin
1
3
c1c9bcee88a4ef8bcdb7319d4352a7403ebeed26
2,791
carp-webservices-spring
MIT License
ui/log/src/main/kotlin/me/gegenbauer/catspy/log/ui/customize/LogMetadataPreviewPanel.kt
Gegenbauer
609,809,576
false
{"Kotlin": 1056932}
package me.gegenbauer.catspy.log.ui.customize import me.gegenbauer.catspy.java.ext.Bundle import me.gegenbauer.catspy.log.metadata.DisplayedLevel import me.gegenbauer.catspy.log.metadata.LogColorScheme import me.gegenbauer.catspy.log.metadata.LogMetadata import me.gegenbauer.catspy.log.serialize.LogMetadataModel import me.gegenbauer.catspy.log.serialize.toLogMetadata import me.gegenbauer.catspy.log.ui.tab.FileLogMainPanel import me.gegenbauer.catspy.view.color.DarkThemeAwareColor import java.awt.Component import java.lang.reflect.Modifier /** * A panel that displays a preview of sample logs based on the given metadata. */ class LogMetadataPreviewPanel : FileLogMainPanel() { override val tag: String = "PreviewPanel" init { templateSelector.isVisible = false logToolBar.isVisible = false splitLogPane.fullLogPanel.isVisible = false configureContext(this) onSetup(Bundle().apply { put(LogMetadata.KEY, LogMetadataModel.default.toLogMetadata()) }) } fun setMetadata(metadataModel: LogMetadataEditModel) { val metadata = generateThemeIgnoredLogMetadata(metadataModel) logConf.setLogMetadata(metadata) startProduceLog(metadata) updateLogFilter() } fun onNightModeChanged(metadataModel: LogMetadataEditModel) { val metadata = generateThemeIgnoredLogMetadata(metadataModel) logConf.setLogMetadata(metadata) } /** * replace all [DarkThemeAwareColor] with a fixed color according to [LogMetadataEditModel.isDarkMode] */ @Suppress("UNCHECKED_CAST") private fun generateThemeIgnoredLogMetadata(editModel: LogMetadataEditModel): LogMetadata { fun generateThemeIgnoredColor(color: DarkThemeAwareColor, isNightMode: Boolean): DarkThemeAwareColor { val targetColor = if (isNightMode) color.nightColor else color.dayColor return DarkThemeAwareColor(targetColor, targetColor) } fun <T> replaceColorFieldsWithFixedColor(obj: Any, isNightMode: Boolean): T { obj.javaClass.declaredFields .filter { it.type == DarkThemeAwareColor::class.java && !Modifier.isStatic(it.modifiers) } .forEach { it.isAccessible = true val color = it.get(obj) as DarkThemeAwareColor val newColor = generateThemeIgnoredColor(color, isNightMode) it.set(obj, newColor) } return obj as T } val newMetadata = editModel.model.toLogMetadata().deepCopy() replaceColorFieldsWithFixedColor<LogColorScheme>(newMetadata.colorScheme, editModel.isDarkMode) newMetadata.levels.forEach { replaceColorFieldsWithFixedColor<DisplayedLevel>(it, editModel.isDarkMode) } return newMetadata } private fun startProduceLog(metadata: LogMetadata) { if (metadata.isDeviceLog) { logViewModel.startProduceCustomDeviceLog() } else { logViewModel.startProduceCustomFileLog() } } override fun getCustomToolbarComponents(): List<Component> { return emptyList() } override fun configureLogTablePopupActions() { // do nothing } }
3
Kotlin
4
23
a868d118c42a9ab0984bfd51ea845d3dcfd16449
3,285
CatSpy
Apache License 2.0
app/src/main/java/com/sopan/currency_conv/views/activity/MainActivity.kt
gitproject09
645,425,641
false
null
package com.sopan.currency_conv.views.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import androidx.appcompat.widget.Toolbar import com.sopan.currency_conv.R class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setToolbar() } private fun setToolbar() { val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) toolbar?.title = getString(R.string.app_name) } override fun onBackPressed() { if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else { super.onBackPressed() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
2
7f7adead3be386af4912bebc1c0586844f86a701
1,056
currencyConversion
Apache License 2.0
subprojects/analysis-java-psi/src/main/kotlin/org/jetbrains/dokka/analysis/java/JavadocTag.kt
Kotlin
21,763,603
false
null
package org.jetbrains.dokka.analysis.java import com.intellij.psi.PsiMethod import org.jetbrains.dokka.InternalDokkaApi @InternalDokkaApi sealed class JavadocTag(val name: String) object AuthorJavadocTag : JavadocTag("author") object DeprecatedJavadocTag : JavadocTag("deprecated") object DescriptionJavadocTag : JavadocTag("description") object ReturnJavadocTag : JavadocTag("return") object SinceJavadocTag : JavadocTag("since") class ParamJavadocTag( val method: PsiMethod, val paramName: String, val paramIndex: Int ) : JavadocTag(name) { companion object { const val name: String = "param" } } class SeeJavadocTag( val qualifiedReference: String ) : JavadocTag(name) { companion object { const val name: String = "see" } } sealed class ThrowingExceptionJavadocTag( name: String, val exceptionQualifiedName: String? ) : JavadocTag(name) class ThrowsJavadocTag(exceptionQualifiedName: String?) : ThrowingExceptionJavadocTag(name, exceptionQualifiedName) { companion object { const val name: String = "throws" } } class ExceptionJavadocTag(exceptionQualifiedName: String?) : ThrowingExceptionJavadocTag(name, exceptionQualifiedName) { companion object { const val name: String = "exception" } }
421
Kotlin
388
3,010
97bccc0e12fdc8c3bd6d178e17fdfb57c3514489
1,293
dokka
Apache License 2.0
app/src/main/kotlin/com/goodwy/keyboard/ime/editor/ImeOptions.kt
Goodwy
811,363,624
false
null
/* * Copyright (C) 2022 Patrick Goldinger * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.patrickgold.florisboard.ime.editor import android.view.inputmethod.EditorInfo import androidx.core.view.inputmethod.EditorInfoCompat /** * Class which holds the same information as an [EditorInfo.imeOptions] int but more accessible and * readable. * * @see EditorInfo.imeOptions for mask table */ @JvmInline value class ImeOptions private constructor(val raw: Int) { val action: Action get() = Action.fromInt(raw and EditorInfo.IME_MASK_ACTION) val flagForceAscii: Boolean get() = raw and EditorInfo.IME_FLAG_FORCE_ASCII != 0 val flagNavigateNext: Boolean get() = raw and EditorInfo.IME_FLAG_NAVIGATE_NEXT != 0 val flagNavigatePrevious: Boolean get() = raw and EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS != 0 val flagNoAccessoryAction: Boolean get() = raw and EditorInfo.IME_FLAG_NO_ACCESSORY_ACTION != 0 val flagNoEnterAction: Boolean get() = raw and EditorInfo.IME_FLAG_NO_ENTER_ACTION != 0 val flagNoExtractUi: Boolean get() = raw and EditorInfo.IME_FLAG_NO_EXTRACT_UI != 0 val flagNoFullScreen: Boolean get() = raw and EditorInfo.IME_FLAG_NO_FULLSCREEN != 0 val flagNoPersonalizedLearning: Boolean get() = raw and EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING != 0 companion object { fun wrap(imeOptions: Int) = ImeOptions(imeOptions) } enum class Action(private val value: Int) { UNSPECIFIED(EditorInfo.IME_ACTION_UNSPECIFIED), DONE(EditorInfo.IME_ACTION_DONE), GO(EditorInfo.IME_ACTION_GO), NEXT(EditorInfo.IME_ACTION_NEXT), NONE(EditorInfo.IME_ACTION_NONE), PREVIOUS(EditorInfo.IME_ACTION_PREVIOUS), SEARCH(EditorInfo.IME_ACTION_SEARCH), SEND(EditorInfo.IME_ACTION_SEND); companion object { fun fromInt(int: Int) = values().firstOrNull { it.value == int } ?: NONE } fun toInt() = value } }
517
null
403
7
472b7eb1a9efcf6e12e55474698f7cc3254c1341
2,562
Keyboard
Apache License 2.0
delegates/src/main/java/com/revolut/recyclerkit/delegates/AbsRecyclerDelegatesAdapter.kt
etiterin
285,885,365
true
{"Kotlin": 129802}
package com.revolut.recyclerkit.delegates import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView /* * Copyright (C) 2019 Revolut * Copyright (C) 2014 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. * * */ private typealias RecyclerDelegate = RecyclerViewDelegate<ListItem, RecyclerView.ViewHolder> abstract class AbsRecyclerDelegatesAdapter( val delegatesManager: DelegatesManager = DelegatesManager() ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = delegatesManager.getDelegateFor(viewType).onCreateViewHolder(parent) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: MutableList<Any>) { getDelegateFor(viewType = holder.itemViewType) .onBindViewHolder( holder = holder, data = getItem(position), pos = position, payloads = payloads ) } @Suppress("unchecked_cast") private fun getDelegateFor(viewType: Int): RecyclerDelegate = delegatesManager.getDelegateFor(viewType = viewType) as RecyclerDelegate override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { this.onBindViewHolder(holder, position, mutableListOf()) } override fun onViewRecycled(holder: RecyclerView.ViewHolder) { getDelegateFor(viewType = holder.itemViewType).onViewRecycled(holder = holder) } override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder) { super.onViewAttachedToWindow(holder) getDelegateFor(viewType = holder.itemViewType).onViewAttachedToWindow(holder) } override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) { super.onViewDetachedFromWindow(holder) getDelegateFor(viewType = holder.itemViewType).onViewDetachedFromWindow(holder) } override fun getItemViewType(position: Int): Int = delegatesManager.getViewTypeFor(position, getItem(position)) abstract fun getItem(position: Int): ListItem }
0
Kotlin
0
0
00b66772137593820537a8e801531b63a9e4a23b
2,664
RecyclerKit
Apache License 2.0
src/main/kotlin/com/github/tuchg/nonasciicodecompletionhelper/config/PluginSettingsState.kt
tuchg
282,809,702
false
{"Kotlin": 149097, "Java": 29876}
package com.github.tuchg.nonasciicodecompletionhelper.config import com.intellij.openapi.components.ServiceManager.getService import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil.copyBean /** * 持久保存用户配置 -Model * @author: tuchg * @date: 2020/11/20 14:01 */ @State(name = "CCompletionHelperSettings", storages = [(Storage("pinyin_completion_helper.xml"))]) class PluginSettingsState : PersistentStateComponent<PluginSettingsState> { // 提示方式设置,如全拼、五笔等 var inputPattern = PatternType.全拼 // 用于解决一词多音不正确显示问题的选项 var enableCompleteMatch = false // 激活强力补全 用于暴力补全部分补全未显示的问题 var enableForceCompletion = true // 自定义码表,支持自定义码表 并提供图形支持,fix: 不能使用 Char类型节省内存,会造成序列化失败 var dict = mutableMapOf<String, ArrayList<String>>() var customLocation = "" // todo 默认增加一个禁用 Ascii、小写开头 intention 的功能 var disableAsciiInspection = false var disableCamelInspection = false companion object { val instance: PluginSettingsState get() = getService(PluginSettingsState::class.java) } /** * 配置项 */ var version = "Unknown" override fun getState() = this override fun loadState(state: PluginSettingsState) { copyBean(state, this) } } enum class PatternType { 全拼, 自定义 }
11
Kotlin
42
1,492
587beb3d4c36dce8804e2a6f3529f36203191063
1,419
ChinesePinyin-CodeCompletionHelper
MIT License
composeApp/src/androidMain/kotlin/de/cacheoverflow/cashflow/security/cryptography/RSACryptoProvider.kt
Cach30verfl0w
808,336,331
false
{"Kotlin": 103104, "Swift": 661}
/* * Copyright 2024 Cach30verfl0w * * 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 de.cacheoverflow.cashflow.security.cryptography import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import de.cacheoverflow.cashflow.security.AndroidKey import de.cacheoverflow.cashflow.security.AndroidSecurityProvider import de.cacheoverflow.cashflow.security.IKey import de.cacheoverflow.cashflow.security.KeyPair import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import java.security.KeyPairGenerator import java.security.PrivateKey import java.security.PublicKey import java.security.Signature import javax.crypto.Cipher class RSACryptoProvider( private val securityProvider: AndroidSecurityProvider, private val usePadding: Boolean = true ): IAsymmetricCryptoProvider { override fun getOrCreatePrivateKey(alias: String, requireAuth: Boolean): Flow<IKey> = flow { val authPossible = securityProvider.areAuthenticationMethodsAvailable() && requireAuth if (authPossible) { securityProvider.wasAuthenticated() } else { flowOf(true) }.collect { if (it) { val privateKey = securityProvider.keyStore.getKey(alias, null) if (privateKey != null) { [email protected](AndroidKey(privateKey, usePadding)) return@collect } generateKeyPair(alias, requireAuth).collect { keyPair -> emit(keyPair.privateKey) } } } } override fun getOrCreatePublicKey(alias: String, requireAuth: Boolean): Flow<IKey> = flow { val authPossible = securityProvider.areAuthenticationMethodsAvailable() && requireAuth if (authPossible) { securityProvider.wasAuthenticated() } else { flowOf(true) }.collect { if (it) { val certificate = securityProvider.keyStore.getCertificate(alias) if (certificate != null) { emit(AndroidKey(certificate.publicKey, usePadding)) return@collect } generateKeyPair(alias, requireAuth).collect { keyPair -> emit(keyPair.publicKey) } } } } override fun createSignature(key: IKey, message: ByteArray): Flow<ByteArray> = flow { val signature = Signature.getInstance("SHA256withRSA") signature.initSign((key as AndroidKey).rawKey as PrivateKey?) signature.update(message) emit(signature.sign()) } override fun verifySignature( key: IKey, signature: ByteArray, original: ByteArray ): Boolean { val verifier = Signature.getInstance("SHA256withRSA") verifier.initVerify((key as AndroidKey).rawKey as PublicKey?) verifier.update(original) return verifier.verify(signature) } override fun encrypt(key: IKey, message: ByteArray): Flow<ByteArray> = flow { val cipher = Cipher.getInstance([email protected]()) cipher.init(Cipher.ENCRYPT_MODE, (key as AndroidKey).rawKey) emit(cipher.doFinal(message)) } override fun decrypt(key: IKey, message: ByteArray): Flow<ByteArray> = flow { val cipher = Cipher.getInstance([email protected]()) cipher.init(Cipher.DECRYPT_MODE, (key as AndroidKey).rawKey) emit(cipher.doFinal(message)) } override fun generateKeyPair(alias: String, requireAuth: Boolean, signingKeys: Boolean): Flow<KeyPair> = flow { val authPossible = securityProvider.areAuthenticationMethodsAvailable() && requireAuth val keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidSecurityProvider.KEY_STORE) val purpose = if (signingKeys) { KeyProperties.PURPOSE_VERIFY or KeyProperties.PURPOSE_SIGN } else { KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_ENCRYPT } keyPairGenerator.initialize(KeyGenParameterSpec.Builder(alias, purpose).run { setUserAuthenticationRequired(authPossible) setUserAuthenticationParameters(10000000, AndroidSecurityProvider.KEY_AUTH_REQUIRED) if (usePadding) { if (signingKeys) { setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1) setDigests(KeyProperties.DIGEST_SHA256) setBlockModes(KeyProperties.BLOCK_MODE_ECB) } else { setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) setDigests(KeyProperties.DIGEST_SHA256) setBlockModes(KeyProperties.BLOCK_MODE_ECB) } } else { throw UnsupportedOperationException("RSA without padding isn't supported") } build() }) val keyPair = keyPairGenerator.generateKeyPair() emit(KeyPair( AndroidKey(keyPair.public, true), AndroidKey(keyPair.private, true) )) } override fun getAlgorithm(): String = "RSA/${KeyProperties.BLOCK_MODE_ECB}/${KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1}" override fun getName(): String = "RSA-4096" }
0
Kotlin
0
0
a5cdb3838b6b49de8fd3e249e25e87b7a3141a1f
5,890
cash3fl0w
Apache License 2.0
omni-result/src/main/java/net/asere/omni/result/ResultContainer.kt
martppa
710,453,179
false
{"Kotlin": 14435}
package net.asere.omni.result import net.asere.omni.core.Container interface ResultContainer : Container
0
Kotlin
0
1
d7f1a17d5f90aa77102ae002cb2923ade22699f7
106
omni-ktor
The Unlicense
app/src/main/java/com/sunnyweather/android/logic/model/Weather.kt
liuxianxi
586,512,003
false
null
package com.sunnyweather.android.logic.model //还需要在logic/model包下再定义一个Weather类,用于将Realtime和Daily对象封装起来 data class Weather(val realtime: RealtimeResponse.Realtime, val daily: DailyResponse.Daily)
0
Kotlin
0
0
9006243c13106f5419fe0ceb321d750725b19105
195
SunnyWeather
Apache License 2.0
app/src/main/java/com/popalay/barnee/ui/common/BackButton.kt
morristech
374,454,030
true
{"Kotlin": 158071, "Objective-C": 46407, "Swift": 9886, "Ruby": 2051, "Shell": 510}
package com.popalay.barnee.ui.common import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import com.popalay.barnee.R.drawable import com.popalay.barnee.navigation.LocalNavController @Composable fun BackButton(modifier: Modifier = Modifier) { val navController = LocalNavController.current IconButton( onClick = { navController.popBackStack() }, modifier = modifier ) { Icon( painter = painterResource(drawable.ic_arrow_back), contentDescription = "Back", ) } }
0
null
0
0
5cd786c7002fe7d149724309358729d98536a2cf
690
Barnee
MIT License
src/test/kotlin/com/utopiarise/serialization/godot/core/ScannerTest.kt
utopia-rise
191,568,379
false
null
package com.utopiarise.serialization.godot.core import com.utopiarise.serialization.godot.util.getResourceUrl import org.junit.Assert.assertEquals import org.junit.Test import java.io.File class ScannerTest { private val resourceTokens: List<Token> = Scanner(File(getResourceUrl("data/common/item_db.tres").file).readText()).scanTokens() private val sceneTokens: List<Token> = Scanner(File(getResourceUrl("scenes/TestScene.tscn").file).readText()).scanTokens() @Test fun `resource item_db has 1 GdResource when scanned`() = assertEquals(1, resourceTokens.filterIsInstance<GdResourceToken>().size) @Test fun `resource item_db has 1 ResourceTag when scanned`() = assertEquals(1, resourceTokens.filterIsInstance<ResourceToken>().size) @Test fun `resource item_db has 2 ExtResources when scanned`() = assertEquals(2, resourceTokens.filterIsInstance<ExtResourceToken>().size) @Test fun `resource item_db has 56 tokens when scanned`() = assertEquals(56, resourceTokens.size) @Test fun `scene TestScene has 181 tokens when scanned`() = assertEquals(181, sceneTokens.size) @Test fun `scene TestScene has 1 GdScene when scanned`() = assertEquals(1, sceneTokens.filterIsInstance<GdSceneToken>().size) @Test fun `scene TestScene has 2 ExtResourceTokens when scanned`() = assertEquals(2, sceneTokens.filterIsInstance<ExtResourceToken>().size) @Test fun `scene TestScene has 9 NodeTokens when scanned`() = assertEquals(9, sceneTokens.filterIsInstance<NodeToken>().size) @Test fun `scene TestScene has 2 ConnectionTokens when scanned`() = assertEquals(2, sceneTokens.filterIsInstance<ConnectionToken>().size) @Test fun `scene TestScene has 2 ScriptTokens when scanned`() = assertEquals(2, sceneTokens.filterIsInstance<ScriptToken>().size) }
0
Kotlin
0
1
6b8b35c779b6ee3ade1242a51c3e3a54f4687c73
1,828
jvm-godot-resource-serialization
MIT License
v1_27/src/main/java/de/loosetie/k8s/dsl/manifests/Selfsubjectreviewstatus.kt
loosetie
283,145,621
false
{"Kotlin": 8925107}
package de.loosetie.k8s.dsl.manifests import de.loosetie.k8s.dsl.K8sTopLevel import de.loosetie.k8s.dsl.K8sDslMarker import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasMetadata @K8sDslMarker interface Selfsubjectreviewstatus_authentication_k8s_io_v1beta1: K8sManifest { /** User attributes of the user making this request. */ val userInfo: UserInfo_authentication_k8s_io_v1? }
0
Kotlin
0
2
57d56ab780bc3134c43377e647e7f0336a5f17de
401
k8s-dsl
Apache License 2.0
app/src/main/kotlin/com/flxrs/dankchat/login/LoginViewModel.kt
flex3r
186,238,019
false
null
package com.flxrs.dankchat.login import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.flxrs.dankchat.data.api.ApiManager import com.flxrs.dankchat.data.api.dto.ValidateUserDto import com.flxrs.dankchat.preferences.DankChatPreferenceStore import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import java.util.* import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val apiManager: ApiManager, private val dankChatPreferenceStore: DankChatPreferenceStore, ) : ViewModel() { data class TokenParseEvent(val successful: Boolean) private val eventChannel = Channel<TokenParseEvent>(Channel.BUFFERED) val events = eventChannel.receiveAsFlow() fun parseToken(fragment: String) = viewModelScope.launch { if (!fragment.startsWith("access_token")) { eventChannel.send(TokenParseEvent(successful = false)) return@launch } val token = fragment .substringAfter("access_token=") .substringBefore("&scope=") val result = apiManager.validateUser(token) val successful = saveLoginDetails(token, result) eventChannel.send(TokenParseEvent(successful)) } private fun saveLoginDetails(oAuth: String, validateDto: ValidateUserDto?): Boolean { return when { validateDto == null || validateDto.login.isBlank() -> false else -> { dankChatPreferenceStore.apply { oAuthKey = "oauth:$oAuth" userName = validateDto.login.lowercase(Locale.getDefault()) userIdString = validateDto.userId isLoggedIn = true } true } } } }
41
Kotlin
35
130
fb8e658d4b532502e128b1241c98c202e5c9b84e
1,945
DankChat
MIT License
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/proguard/patterns/ReplacersRunner.kt
RikkaW
389,105,112
true
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.processor.transform.proguard.patterns /** * Runs multiple [GroupsReplacer]s on given strings. */ class ReplacersRunner(val replacers: List<GroupsReplacer>) { /** * Runs all the [GroupsReplacer]s on the given [input]. * * The replacers have to be distinct as this method can't guarantee that output of one replacer * won't be matched by another replacer. */ fun applyReplacers(input: String): String { val sb = StringBuilder() var lastSeenChar = 0 var processedInput = input for (replacer in replacers) { val matcher = replacer.pattern.matcher(processedInput) while (matcher.find()) { if (lastSeenChar < matcher.start()) { sb.append(processedInput, lastSeenChar, matcher.start()) } val result = replacer.runReplacements(matcher) sb.append(result.joinToString(System.lineSeparator())) lastSeenChar = matcher.end() } if (lastSeenChar == 0) { continue } if (lastSeenChar <= processedInput.length - 1) { sb.append(processedInput, lastSeenChar, processedInput.length) } lastSeenChar = 0 processedInput = sb.toString() sb.setLength(0) } return processedInput } }
0
Java
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
2,060
androidx
Apache License 2.0
app/src/main/java/com/shzlabs/mamopay/data/DataManager.kt
shahzar
245,971,747
false
null
package com.shzlabs.mamopay.data import com.shzlabs.mamopay.data.local.database.DatabaseService import com.shzlabs.mamopay.data.model.TransactionModel import com.shzlabs.mamopay.data.repository.ApiService import com.shzlabs.mamopay.util.config.AppConfig import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import retrofit2.HttpException import java.io.IOException import javax.inject.Inject class DataManager @Inject constructor(private val remoteDataSrc: ApiService, private val localDataSrc: DatabaseService) { private suspend fun <T> safeApiCall(apiCall: suspend () -> T) = withContext(Dispatchers.IO) { try { apiCall.invoke() } catch (throwable: Throwable) { when(throwable) { is IOException -> throw IOException("Network Error. Please check your internet.") is HttpException -> throw Exception("Error: ${throwable.message()}") else -> throw Exception("Some error occured") } } } suspend fun getSampleData() = safeApiCall { remoteDataSrc.getSampleData() } suspend fun getTransactionData() = safeApiCall { localDataSrc.transactionDao().getAll() } suspend fun addTransactionData(transactionModel: TransactionModel) = safeApiCall { localDataSrc.transactionDao().insert(transactionModel) } suspend fun fetchUserBalance() = getFakeData() suspend fun addMoney() = getFakeData() private suspend fun getFakeData() = safeApiCall { //TODO: interviewer review delay(AppConfig.NETWORK_DELAY) remoteDataSrc.getSampleData() } }
0
Kotlin
0
3
403d5112b7c890ceec06f92f54f365debc575f81
1,687
Fintech-Startup
Apache License 2.0
app/src/main/java/com/moonfleet/movies/view/TouchBlockingLayout.kt
moonfleet
204,317,107
false
null
package com.moonfleet.movies.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.widget.RelativeLayout open class TouchBlockingLayout : RelativeLayout { constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {} override fun onTouchEvent(event: MotionEvent): Boolean { return true } override fun performClick(): Boolean { return true } }
1
null
1
1
2237bc63a21f759aa885c2a8fb6892896d33a860
623
mvx-movies
MIT License
app/src/main/java/com/moonfleet/movies/view/TouchBlockingLayout.kt
moonfleet
204,317,107
false
null
package com.moonfleet.movies.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.widget.RelativeLayout open class TouchBlockingLayout : RelativeLayout { constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {} override fun onTouchEvent(event: MotionEvent): Boolean { return true } override fun performClick(): Boolean { return true } }
1
null
1
1
2237bc63a21f759aa885c2a8fb6892896d33a860
623
mvx-movies
MIT License
app/src/main/java/com/kromer/openweather/core/di/modules/RoomModule.kt
kerolloskromer
386,706,637
false
null
package com.kromer.openweather.core.di.modules import android.content.Context import androidx.room.Room import com.kromer.openweather.core.local.MyDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RoomModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): MyDatabase = Room.databaseBuilder(context, MyDatabase::class.java, MyDatabase.DATABASE_NAME).build() }
0
Kotlin
0
1
245804157b67faca2bc40286416bb10d31f9fd8f
636
open-weather
MIT License
app/src/main/java/com/jvmartinez/finanzapp/core/model/Countries.kt
jvmartinez
795,597,347
false
{"Kotlin": 177653}
package com.jvmartinez.finanzapp.core.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class Countries( @JsonProperty("countries") val countries: List<Country> )
0
Kotlin
0
0
5134b648a8323fcce4ec6e6eb1160af0bd6b2b0d
287
FinanzApp
Creative Commons Attribution 4.0 International
app/src/main/java/de/lemke/studiportal/domain/DeleteAllExamsUseCase.kt
Lemkinator
564,451,316
false
{"Kotlin": 181701}
package de.lemke.studiportal.domain import de.lemke.studiportal.data.ExamsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class DeleteAllExamsUseCase @Inject constructor( private val examsRepository: ExamsRepository, ) { suspend operator fun invoke() = withContext(Dispatchers.Default) { examsRepository.deleteAllExams() } }
0
Kotlin
0
4
c54421c53ef18a8366e3e9657d75b9655230d75c
413
Studiportal
MIT License
app/src/main/java/de/lemke/studiportal/domain/DeleteAllExamsUseCase.kt
Lemkinator
564,451,316
false
{"Kotlin": 181701}
package de.lemke.studiportal.domain import de.lemke.studiportal.data.ExamsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class DeleteAllExamsUseCase @Inject constructor( private val examsRepository: ExamsRepository, ) { suspend operator fun invoke() = withContext(Dispatchers.Default) { examsRepository.deleteAllExams() } }
0
Kotlin
0
4
c54421c53ef18a8366e3e9657d75b9655230d75c
413
Studiportal
MIT License
src/main/kotlin/io/tcds/orm/column/nullable/NullableEnumColumn.kt
tcds-io
560,178,616
false
{"Kotlin": 144151}
package io.tcds.orm.column.nullable import io.tcds.orm.Column import java.sql.PreparedStatement import java.sql.Types class NullableEnumColumn<Entity, T : Enum<*>>(name: String, value: (Entity) -> T?) : Column<Entity, T?>(name, value) { override fun bind(stmt: PreparedStatement, index: Int, value: T?) { when (value) { null -> stmt.setNull(index, Types.VARCHAR) else -> stmt.setString(index, value.name) } } }
1
Kotlin
0
0
9cf74a43a668c70a7ad69395f0a8d0159d07624f
461
kotlin-orm
MIT License
kontroller/src/main/kotlin/no/ssb/kostra/validation/rule/sosial/sosialhjelp/rule/Rule020BViktigsteKildeTilLivsOppholdKode3.kt
statisticsnorway
414,216,275
false
{"Kotlin": 1524176, "TypeScript": 58079, "HTML": 694, "SCSS": 110}
package no.ssb.kostra.validation.rule.sosial.sosialhjelp.rule import no.ssb.kostra.area.sosial.sosialhjelp.SosialhjelpColumnNames import no.ssb.kostra.area.sosial.sosialhjelp.SosialhjelpColumnNames.TRYGDESIT_COL_NAME import no.ssb.kostra.area.sosial.sosialhjelp.SosialhjelpColumnNames.VKLO_COL_NAME import no.ssb.kostra.area.sosial.sosialhjelp.SosialhjelpFieldDefinitions.fieldDefinitions import no.ssb.kostra.program.KostraRecord import no.ssb.kostra.program.extension.byColumnName import no.ssb.kostra.validation.report.Severity import no.ssb.kostra.validation.rule.AbstractNoArgsRule import no.ssb.kostra.validation.rule.sosial.sosialhjelp.SosialhjelpRuleId class Rule020BViktigsteKildeTilLivsOppholdKode3 : AbstractNoArgsRule<List<KostraRecord>>( SosialhjelpRuleId.SOSIALHJELP_K020B_TRYGD.title, Severity.ERROR ) { override fun validate(context: List<KostraRecord>) = context .filter { it[VKLO_COL_NAME] == "3" } .filterNot { it[TRYGDESIT_COL_NAME] in validCodes } .map { createValidationReportEntry( "Mottakerens viktigste kilde til livsopphold ved siste kontakt med sosial-/NAV-kontoret " + "er Trygd/pensjon. Trygdesituasjonen er '(${it[TRYGDESIT_COL_NAME]})', " + "forventet én av '(${ fieldDefinitions.byColumnName(TRYGDESIT_COL_NAME).codeList .filter { item -> item.code in validCodes } })'. Feltet er obligatorisk å fylle ut.", lineNumbers = listOf(it.lineNumber) ).copy( caseworker = it[SosialhjelpColumnNames.SAKSBEHANDLER_COL_NAME], journalId = it[SosialhjelpColumnNames.PERSON_JOURNALNR_COL_NAME], ) }.ifEmpty { null } companion object { private val validCodes = listOf("01", "02", "04", "05", "06", "07", "09", "10", "11") } }
3
Kotlin
0
1
6a77c6d7886d7847b59d6ef24da2a9c48145bc0a
1,937
kostra-kontrollprogram
MIT License
app/src/main/java/com/linecy/dilidili/ui/cartoon/adapter/CartoonCategoryAdapter.kt
linecyc
138,257,601
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 4, "Java": 19, "XML": 83, "Kotlin": 93}
package com.linecy.dilidili.ui.cartoon.adapter import android.content.Context import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView.ViewHolder import android.view.LayoutInflater import android.view.ViewGroup import com.linecy.dilidili.BR import com.linecy.dilidili.R import com.linecy.dilidili.data.model.Category import com.linecy.dilidili.databinding.ItemCartoonCategoryBinding import com.linecy.dilidili.databinding.ItemCartoonYearBinding import com.linecy.dilidili.ui.misc.EventHandling /** * @author by linecy. */ class CartoonCategoryAdapter( context: Context) : RecyclerView.Adapter<ViewHolder>() { private val list = ArrayList<Category>() private val inflater = LayoutInflater.from(context) private var yearsCount = 0//年份日期数据的大小 private val typeCategory = 0 private val typeYear = 1 override fun getItemViewType(position: Int): Int { return if (position < yearsCount) { typeYear } else { typeCategory } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { when (viewType) { typeCategory -> { val dataBinding: ItemCartoonCategoryBinding = DataBindingUtil.inflate(inflater, R.layout.item_cartoon_category, parent, false) dataBinding.eventHandling = EventHandling() return CategoryViewHolder(dataBinding) } else -> { val dataBinding: ItemCartoonYearBinding = DataBindingUtil.inflate(inflater, R.layout.item_cartoon_year, parent, false) dataBinding.eventHandling = EventHandling() return YearViewHolder(dataBinding) } } } override fun getItemCount(): Int { return list.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { when (getItemViewType(position)) { typeCategory -> (holder as CategoryViewHolder).bindData(list[position]) typeYear -> (holder as YearViewHolder).bindData(list[position]) } } class CategoryViewHolder(private val dataBinding: ViewDataBinding) : ViewHolder( dataBinding.root) { fun bindData(category: Category) { dataBinding.setVariable(BR.itemCartoonCategory, category) dataBinding.executePendingBindings() } } class YearViewHolder(private val dataBinding: ViewDataBinding) : ViewHolder(dataBinding.root) { fun bindData(category: Category) { dataBinding.setVariable(BR.itemCartoonYear, category) dataBinding.executePendingBindings() } } /** * 先加载年份,在加载类型 */ fun refreshData(years: List<Category>?, categories: List<Category>?) { this.list.clear() yearsCount = 0 if (years != null && years.isNotEmpty()) { this.list.addAll(years) yearsCount = years.size } if (categories != null && categories.isNotEmpty()) { this.list.addAll(categories) } notifyDataSetChanged() } }
1
null
1
1
b80dde7a69282816701b48e8010930f57b1d82cb
3,000
Dilidili
Apache License 2.0
백준/A → B.kt
jisungbin
382,889,087
false
null
import java.io.BufferedReader import java.io.BufferedWriter import java.io.InputStreamReader import java.io.OutputStreamWriter import java.util.LinkedList import java.util.Queue fun main() { val br = BufferedReader(InputStreamReader(System.`in`)) val bw = BufferedWriter(OutputStreamWriter(System.out)) val (A, B) = br.readLine()!!.split(" ").map { it.toLong() } var count = -1L val bfsQueue: Queue<List<Long>> = LinkedList() // 숫자, 카운트 bfsQueue.offer(listOf(A, 1)) while (bfsQueue.isNotEmpty()) { var (_A, _count) = bfsQueue.poll() if (_A == B) { count = _count break } _count++ if (_A * 2 <= B) { bfsQueue.offer(listOf(_A * 2, _count)) } _A = "${_A}1".toLong() if (_A <= B) { bfsQueue.offer(listOf(_A, _count)) } } bw.write("$count") br.close() bw.flush() bw.close() }
0
Kotlin
1
9
ee43375828ca7e748e7c79fbed63a3b4d27a7a2c
944
algorithm-code
MIT License
app/src/main/java/com/taitascioredev/android/tvseriesdemo/data/entity/mapper/ShowsListMapper.kt
phanghos
119,651,014
false
null
package com.taitascioredev.android.tvseriesdemo.data.entity.mapper import com.taitascioredev.android.tvseriesdemo.data.entity.ResultsItem import com.taitascioredev.android.tvseriesdemo.data.entity.ShowsListResponseEntity import com.taitascioredev.android.tvseriesdemo.domain.model.MovieDbTvShow /** * Created by rrtatasciore on 24/01/18. */ open class ShowsListMapper { open fun map(showsListResponseEntity: ShowsListResponseEntity): List<MovieDbTvShow> { val list = ArrayList<MovieDbTvShow>() showsListResponseEntity.results?.forEach { list.add(map(it!!)) } return list } open fun map(resultsItem: ResultsItem): MovieDbTvShow { val tvShow = MovieDbTvShow( id = resultsItem.id, name = resultsItem.name, overview = resultsItem.overview, posterPath = resultsItem.posterPath, voteAverage = resultsItem.voteAverage, voteCount = resultsItem.voteCount) return tvShow } }
0
Kotlin
0
1
f2992ac104f0733d0707027e1c025d1f3ed6bf85
1,022
tv-series-demo
MIT License
kslides-core/src/main/kotlin/com/kslides/config/KSlidesConfig.kt
kslides
337,601,940
false
null
package com.kslides.config import com.kslides.CssFile import com.kslides.JsFile import com.kslides.StaticRoot class KSlidesConfig { val httpStaticRoots = mutableListOf( StaticRoot("assets"), StaticRoot("css"), StaticRoot("dist"), StaticRoot("js"), StaticRoot("plugin"), ) val cssFiles = mutableListOf( CssFile("dist/reveal.css"), CssFile("dist/reset.css"), ) val jsFiles = mutableListOf( JsFile("dist/reveal.js"), ) var playgroundSelector = "playground-code" var playgroundUrl = "https://unpkg.com/kotlin-playground@1" //var plotlyUrl = "https://cdn.plot.ly/plotly-1.54.6.min.js" var krokiUrl = "https://kroki.io" }
0
Kotlin
3
79
d7cd6c7582b47adca8ab459a11c2ffddc88e80dd
706
kslides
Apache License 2.0
feature/main/src/debug/kotlin/com/masselis/tpmsadvanced/feature/main/interfaces/composable/Settings.kt
VincentMasselis
501,773,706
false
{"Kotlin": 589677}
package com.masselis.tpmsadvanced.feature.main.interfaces.composable import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.isEnabled import androidx.compose.ui.test.isNotEnabled import androidx.compose.ui.test.junit4.ComposeTestRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo import com.masselis.tpmsadvanced.core.androidtest.EnterExitComposable import com.masselis.tpmsadvanced.core.androidtest.EnterExitComposable.ExitToken import com.masselis.tpmsadvanced.core.androidtest.EnterExitComposable.Instructions import com.masselis.tpmsadvanced.core.androidtest.check import com.masselis.tpmsadvanced.core.androidtest.onEnterAndOnExit import com.masselis.tpmsadvanced.core.androidtest.process context (ComposeTestRule) @OptIn(ExperimentalTestApi::class) public class Settings( private val backButtonTag: String, private val containerTag: String, ) : EnterExitComposable<Settings> by onEnterAndOnExit( { waitUntilExactlyOneExists(hasTestTag(containerTag)) }, { waitUntilDoesNotExist(hasTestTag(containerTag)) } ) { private val backButton get() = onNodeWithTag(backButtonTag) private val deleteVehicleButton get() = onNodeWithTag(DeleteVehicleButtonTags.Button.tag) private val clearFavouritesButton get() = onNodeWithTag(ClearBoundSensorsButtonTags.root) private val deleteVehicleDialogTest = DeleteVehicleDialog() public fun assertVehicleSettingsDisplayed() { onNodeWithTag(containerTag).assertIsDisplayed() } public fun deleteVehicle(instructions: Instructions<DeleteVehicleDialog>): ExitToken<Settings> { deleteVehicleButton.performScrollTo() deleteVehicleButton.performClick() deleteVehicleDialogTest.process(instructions) return exitToken } public fun assertVehicleDeleteIsNotEnabled() { deleteVehicleButton.assertIsNotEnabled() } public fun clearFavourites() { clearFavouritesButton.performScrollTo() clearFavouritesButton.performClick() } public fun waitClearFavouritesEnabled(): Unit = waitUntil { clearFavouritesButton.check(isEnabled()) } public fun waitClearFavouritesDisabled() { waitUntil { clearFavouritesButton.check(isNotEnabled()) } } public fun leave(): ExitToken<Settings> { backButton.performClick() return exitToken } }
6
Kotlin
3
5
ec907303d91ec732a4110dc195dc26060e1a02a4
2,622
TPMS-advanced
Apache License 2.0
core/src/commonTest/kotlin/maryk/core/properties/definitions/contextual/ContextualValueDefinitionTest.kt
marykdb
290,454,412
false
{"Kotlin": 3277548, "JavaScript": 1004}
package maryk.core.properties.definitions.contextual import maryk.checkProtoBufConversion import maryk.core.properties.IsPropertyContext import maryk.core.properties.definitions.IsValueDefinition import maryk.core.properties.definitions.StringDefinition import maryk.test.ByteCollector import kotlin.test.Test import kotlin.test.expect private class ValueContext : IsPropertyContext { val valueDefinition = StringDefinition() } class ContextualValueDefinitionTest { private val valuesToTest = listOf( "test1", "test2" ) @Suppress("UNCHECKED_CAST") private val def = ContextualValueDefinition( contextualResolver = { context: ValueContext? -> context!!.valueDefinition as IsValueDefinition<Any, IsPropertyContext> } ) private val context = ValueContext() @Test fun testTransportConversion() { val bc = ByteCollector() for (value in valuesToTest) { checkProtoBufConversion(bc, value, this.def, this.context) } } @Test fun convertString() { for (value in valuesToTest) { val b = def.asString(value, this.context) expect(value) { def.fromString(b, this.context) } } } }
1
Kotlin
1
8
378d20bfd6334160a7a00cd06c984609495b71f0
1,245
maryk
Apache License 2.0
mybatis-flex-kotlin-codegen/src/main/kotlin/package-info.kt
KAMO030
678,726,164
false
{"Kotlin": 271220, "Smarty": 4372, "Java": 218}
package com.mybatisflex.kotlin.codegen
0
Kotlin
4
27
11e692587e25d49fdfe64e73fc99f47ef5fa23a1
38
MyBatis-Flex-Kotlin
Apache License 2.0
feature/waiting/src/main/java/easydone/feature/waiting/WaitingScreen.kt
kamerok
192,063,678
false
{"Kotlin": 209086}
package easydone.feature.waiting import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridItemSpan import androidx.compose.foundation.lazy.staggeredgrid.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.ContentAlpha import androidx.compose.material.LocalTextStyle import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material3.adaptive.currentWindowAdaptiveInfo import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.ExperimentalUnitApi import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.window.core.layout.WindowWidthSizeClass.Companion.COMPACT import easydone.core.domain.DomainRepository import easydone.coreui.design.AppTheme import easydone.coreui.design.EasyDoneAppBar import easydone.coreui.design.FoldPreviews import easydone.coreui.design.TaskCard import easydone.coreui.design.UiTask import java.time.DayOfWeek import java.time.LocalDate import java.time.Period import java.time.Year import java.time.YearMonth import java.time.format.DateTimeFormatter import java.util.UUID @Composable fun WaitingRoute( repository: DomainRepository, navigator: WaitingNavigator ) { val viewModel: WaitingViewModel = viewModel { WaitingViewModel(repository, navigator) } val state by viewModel.state.collectAsState() WaitingScreen( state = state, onTaskClick = viewModel::onTaskClick ) } @Composable internal fun WaitingScreen( state: State, onTaskClick: (UiTask) -> Unit ) { AppTheme { FullscreenContent { Column { EasyDoneAppBar(modifier = Modifier.statusBarsPadding()) { Text("Waiting") } val windowSizeClass = currentWindowAdaptiveInfo().windowSizeClass val columns by remember(windowSizeClass) { derivedStateOf { if (windowSizeClass.windowWidthSizeClass == COMPACT) 1 else 2 } } LazyVerticalStaggeredGrid( horizontalArrangement = Arrangement.spacedBy(16.dp), verticalItemSpacing = 16.dp, contentPadding = PaddingValues(16.dp), columns = StaggeredGridCells.Fixed(columns) ) { item(span = StaggeredGridItemSpan.FullLine) { val significantDays by remember { derivedStateOf { state.tasks.keys } } val months = remember { val currentMonth = YearMonth.now() (0..(12 * 10)).map { currentMonth.plusMonths(it.toLong()) } } LazyRow( horizontalArrangement = Arrangement.spacedBy(10.dp) ) { items(months) { month -> CalendarMonth( month = month, significantDays = significantDays ) } } } //TODO: reuse format logic val formatter = DateTimeFormatter.ofPattern("d MMM y") state.tasks.entries .sortedBy { it.key } .forEach { (date, tasks) -> item(span = StaggeredGridItemSpan.FullLine) { val period = Period.between(LocalDate.now(), date) val dateText = buildString { append(formatter.format(date)) append(" (") if (period.years > 0) { append("${period.years}y ") } if (period.months > 0) { append("${period.months}m ") } if (period.days > 0) { append("${period.days}d") } append(")") } Text( text = dateText, style = MaterialTheme.typography.h5, ) } items(tasks) { task -> TaskCard( task = task, modifier = Modifier .fillMaxWidth() .clickable { onTaskClick(task) } ) } item(span = StaggeredGridItemSpan.FullLine) { Spacer(modifier = Modifier.navigationBarsPadding()) } } } } } } } @Composable private fun FullscreenContent( content: @Composable () -> Unit ) { Surface( color = MaterialTheme.colors.background, modifier = Modifier.fillMaxSize() ) { content() } } @Composable private fun CalendarMonth( month: YearMonth, modifier: Modifier = Modifier, significantDays: Set<LocalDate> = emptySet() ) { val formatter = remember { DateTimeFormatter.ofPattern( if (Year.now().value == month.year) "MMM" else "MMM y" ) } Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier ) { Text( text = month.format(formatter), style = MaterialTheme.typography.body2 ) Column( verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(4.dp) ) { val days: List<LocalDate> = remember(month) { buildList { val firstDay = month.atDay(1) val firstMonday = if (firstDay.dayOfWeek == DayOfWeek.MONDAY) { firstDay } else { firstDay.minusDays(firstDay.dayOfWeek.value - 1L) } (0..5).forEach { weekIndex -> (0..6).forEach { dayIndex -> add(firstMonday.plusDays((7 * weekIndex + dayIndex).toLong())) } } } } days.chunked(7).forEach { weekDays -> Row(horizontalArrangement = Arrangement.spacedBy(1.dp)) { weekDays.forEach { localDate -> CalendarDay( number = localDate.dayOfMonth, isEnabled = YearMonth.from(localDate) == month, isToday = localDate == LocalDate.now(), isAction = significantDays.contains(localDate) ) } } } } } } @OptIn(ExperimentalUnitApi::class) @Composable private fun CalendarDay( number: Int, isEnabled: Boolean, isToday: Boolean, isAction: Boolean ) { Surface( color = if (isAction) MaterialTheme.colors.primary else Color.Transparent, shape = CircleShape, border = if (isToday) { BorderStroke(1.dp, MaterialTheme.colors.onSurface) } else { null }, modifier = Modifier .size(16.dp) .alpha(if (isEnabled) 1f else ContentAlpha.disabled) ) { Box( contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize() ) { Text( text = "$number", fontSize = TextUnit(10f, TextUnitType.Sp), fontWeight = FontWeight.Medium, style = LocalTextStyle.current.merge( TextStyle( lineHeightStyle = LineHeightStyle( alignment = LineHeightStyle.Alignment.Center, trim = LineHeightStyle.Trim.Both ) ) ) ) } } } @Preview(showBackground = true, device = "spec:width=1080px,height=2340px,dpi=440") @Composable private fun MonthPreview() { AppTheme { CalendarMonth( month = YearMonth.now(), significantDays = setOf( LocalDate.now().plusDays(5), LocalDate.now().minusDays(2), LocalDate.now() ) ) } } @Preview @Composable private fun DayPreview() { AppTheme { Row { CalendarDay(number = 10, isEnabled = true, isToday = false, isAction = false) CalendarDay(number = 10, isEnabled = true, isToday = true, isAction = false) CalendarDay(number = 10, isEnabled = true, isToday = false, isAction = true) CalendarDay(number = 10, isEnabled = false, isToday = false, isAction = false) CalendarDay(number = 10, isEnabled = false, isToday = true, isAction = false) CalendarDay(number = 10, isEnabled = false, isToday = false, isAction = true) } } } @FoldPreviews @Composable private fun WaitingPreview() { fun generateTasks(number: Int) = (1..number).map { UiTask(UUID.randomUUID().toString(), "task $it", true, true, true) } WaitingScreen( state = State( mapOf( LocalDate.now().plusDays(1) to generateTasks(5), LocalDate.now().plusDays(2) to generateTasks(5), ) ), onTaskClick = {} ) }
0
Kotlin
0
4
d8dff0a567a7e6209ae8518c8060f252b04679fc
11,764
EasyDone
Apache License 2.0
src/test/java/org/ujorm/kotlin/core/CoreTest.kt
pponec
382,561,643
false
null
/* * Copyright 2021-2022 Pavel Ponec, https://github.com/pponec * * 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.ujorm.kotlin.core import org.junit.jupiter.api.Test import org.ujorm.kotlin.core.entity.* import java.time.LocalDate import ch.tutteli.atrium.api.fluent.en_GB.* import ch.tutteli.atrium.api.verbs.* import org.ujorm.kotlin.core.impl.ComposedPropertyImpl import org.ujorm.kotlin.core.impl.ComposedPropertyNullableImpl internal class CoreTest { @Test fun createEntities() { // Get the metamodel(s): val employees: Employees = Entities.employees val departments: Departments = Entities.departments // Create some new entities: val development: Department = departments.new { id = 1 name = "development" created = LocalDate.of(2021, 10, 15) } val lucy: Employee = employees.new { id = 2 name = "Lucy" senior = true contractDay = LocalDate.of(2022, 1, 1) supervisor = null department = development } val joe: Employee = employees.new { id = 3 name = "Joe" senior = false contractDay = LocalDate.of(2022, 2, 1) supervisor = lucy department = development } expect(development.id).toEqual(1) expect(joe.name).toEqual("Joe") expect(joe.senior).toEqual(false) expect(joe.department.name).toEqual("development") expect(joe.supervisor?.name).toEqual("Lucy") expect(joe.supervisor?.department?.name).toEqual("development") expect(development.toString()).toEqual("Department{id=1" + ", name=\"development\"" + ", created=2021-10-15" + ", members=?}") expect(lucy.toString()).toEqual("Employee{id=2" + ", name=\"Lucy\"" + ", senior=true" + ", contractDay=2022-01-01" + ", department=Department{id=1, name=\"development\",...}" + ", supervisor=null}") expect(joe.toString()).toEqual("Employee{id=3" + ", name=\"Joe\"" + ", senior=false" + ", contractDay=2022-02-01" + ", department=Department{id=1, name=\"development\",...}" + ", supervisor=Employee{id=2, name=\"Lucy\", senior=t...}}") } /** Test writing and reading to the object using the metamodel. */ @Test fun readAndWrite() { val employees = Entities.employees // Employee metamodel val departments = Entities.departments // Department metamodel val employee: Employee = employees.new { // Create new employee object id = 11 name = "John" senior = false contractDay = LocalDate.now() department = getDepartment(2, "D") } // Read and Write values by property descriptors: val id: Int = employee[employees.id] val name: String = employee[employees.name] val senior: Boolean = employee[employees.senior] val contractDay: LocalDate = employee[employees.contractDay] val department: Department = employee[employees.department] val supervisor: Employee? = employee[employees.supervisor] employee[employees.id] = id employee[employees.name] = name employee[employees.senior] = senior employee[employees.contractDay] = contractDay employee[employees.department] = department employee[employees.supervisor] = supervisor // Composed properties: employee[employees.department + departments.id] = 3 employee[employees.department + departments.name] = "C" expect(employee.department.id).toEqual(3) expect(employee.department.name).toEqual("C") expect(employee[employees.department + departments.id]).toEqual(3) expect(employee[employees.department + departments.name]).toEqual("C") // Create relation instance(s): // TODO: val employee2 = employees.new() val departmentNameProperty = employees.department + departments.name // employee2[departmentNameProperty] = "Test" } /** Test conditions */ @Test fun conditions() { val employees = Entities.employees // Employee Entity metamodel val departments = Entities.departments // Department Entity metamodel val employee: Employee = employees.new { // Create new employee object id = 11 name = "John" senior = false contractDay = LocalDate.now() department = getDepartment(2, "D") } // Criterion conditions: val crn1 = employees.name EQ "Lucy" val crn2 = employees.id GT 1 val crn3 = (employees.department + departments.id) LT 99 val crn4 = crn1 OR (crn2 AND crn3) val crn5 = crn1.not() OR (crn2 AND crn3) expect(crn1(employee)).equals(false) // Invalid employee expect(crn4(employee)).equals(true) // Valid employee expect(crn1.toString()).toEqual("""Employee: name EQ "Lucy"""") expect(crn2.toString()).toEqual("""Employee: id GT 1""") expect(crn3.toString()).toEqual("""Employee: department.id LT 99""") expect(crn4.toString()).toEqual("""Employee: (name EQ "Lucy") OR (id GT 1) AND (department.id LT 99)""") expect(crn5.toString()).toEqual("""Employee: (NOT (name EQ "Lucy")) OR (id GT 1) AND (department.id LT 99)""") } /** Sample of usage */ @Test fun extendedFunctions() { val employees = Entities.employees // Employee Entity metamodel val departments = Entities.departments // Department Entity metamodel val employee: Employee = employees.new { // Create new employee object id = 11 name = "John" senior = false contractDay = LocalDate.now() department = getDepartment(2, "D") } val id: Int = employees.id[employee] val name: String = employees.name[employee] // Get a name of the employee val supervisor: Employee? = employees.supervisor[employee] expect(name).toEqual("John") // employee name expect(id).toEqual(11) // employee id expect(supervisor).toEqual(null) // employee supervisor employees.name[employee] = "James" // Set a name to the user employees.supervisor[employee] = null expect(employees.id.name()).toEqual("id") // property id expect(employees.id.toString()).toEqual("Employee.id") // property id expect(employees.id.info()).toEqual("Employee.id") // property id expect(employees.id()).toEqual("id") // A shortcut for the name() val properties = employees.utils().properties expect(properties.size).toEqual(6) // Count of properties expect(properties[0].name()).toEqual("id") // property id expect(properties[1].name()).toEqual("name") // property name expect(properties[2].name()).toEqual("senior") // property name expect(properties[3].name()).toEqual("contractDay")// ContractDay expect(properties[4].name()).toEqual("department") // property department expect(properties[5].name()).toEqual("supervisor") // property supervisor // Value type expect(employees.id.data().valueClass).toEqual(Int::class) expect(employees.contractDay.data().valueClass).toEqual(LocalDate::class) // Entity type (alias domain type) expect(employees.id.data().entityClass).toEqual(Employee::class) expect(employees.contractDay.data().entityClass).toEqual(Employee::class) // Composed properties: val employeeDepartmentNameProp: Property<Employee, String> = employees.department + departments.name expect(employeeDepartmentNameProp.info()).toEqual("Employee.department.name") expect(employeeDepartmentNameProp.toString()).toEqual("department.name") } @org.junit.jupiter.api.Disabled @Test fun createNewRelationBySpecialSetter() { val entities = Entities.close<Entities>() val employees = entities.employees val departments = entities.departments val employee: Employee = employees.new() val deparmentIdProperty = (employees.department + departments.id) as ComposedPropertyNullableImpl<Employee, *, Int> deparmentIdProperty.set(employee, 88, Entities) // Method creates new Department employee[employees.department + departments.name] = "Catherine" expect(employee[deparmentIdProperty]).toEqual(88) expect(employee[employees.department + departments.name]).toEqual("Catherine") val deparmentIdOfDSupervisorProperty = (employees.supervisor + employees.department + departments.id) as ComposedPropertyNullableImpl<Employee, *, Int> deparmentIdOfDSupervisorProperty.set(employee, 99, Entities) // Method creates new Department expect(employee[deparmentIdOfDSupervisorProperty]).toEqual(99) } /** Create new object by a constructor (for immutable objects) */ @Test fun entityHashAndAlias() { val aliasEmployees: Employees = Entities.employees.alias("e") val aliasDepartment: Departments = Entities.departments.alias("d") println(aliasEmployees.id.status()) expect(aliasEmployees.id.entityAlias()).toEqual("e") expect(aliasEmployees.name.entityAlias()).toEqual("e") expect(aliasEmployees.department.entityAlias()).toEqual("e") expect(aliasDepartment.id.entityAlias()).toEqual("d") expect(aliasDepartment.name.entityAlias()).toEqual("d") expect(aliasEmployees.id.info()).toEqual("Employee(e).id") expect(aliasEmployees.department.info()).toEqual("Employee(e).department") var idAliasHash = aliasEmployees.id.hashCode() var idHash = Entities.employees.id.hashCode() var nameAliasHash = aliasEmployees.name.hashCode() var idAliasName = aliasEmployees.id.name() var idName = aliasEmployees.id.name() var idAlias2 = aliasEmployees.id.entityAlias("e") // Alias for a single property var idAlias3 = aliasEmployees.id("e") // Shortcut for new alias expect(idAliasName).toEqual(idName) expect(idAliasHash).notToEqual(idHash) // Different hash codes expect(idAliasHash).notToEqual(nameAliasHash) // Different hash codes expect(aliasEmployees.id).notToEqual(Entities.employees.id) // Different properties expect(idAliasHash).toEqual(idAlias2.hashCode()) expect(aliasEmployees.id).toEqual(idAlias2) expect(idAlias2).toEqual(idAlias3) } /** Create new object by a constructor (for immutable objects) */ @Test fun entityHashAndEquals() { val department1 = getDepartment(1, "development") val department2 = getDepartment(1, "development") val department3 = getDepartment(1, "accounting") expect(department1.hashCode()).toEqual(department2.hashCode()) expect(department1.hashCode()).notToEqual(department3.hashCode()) expect(department2.hashCode()).notToEqual(department3.hashCode()) expect(department1 is AbstractEntity<*>).toEqual(true) expect(department1).toEqual(department1) expect(department1).toEqual(department2) expect(department1).notToEqual(department3) expect(department2).notToEqual(department3) } } /** Helper method to create new department */ private fun getDepartment(id: Int, name: String): Department = Entities.departments.new { this.id = id this.name = name }
0
Kotlin
0
0
eb1645376043c345b255d758fa8d4c2aeb7d8733
12,318
ujormKt
Apache License 2.0
app/src/main/java/com/macormap/kotlintestui/MainAdapter.kt
CarloMacor
125,410,329
false
null
package com.macormap.kotlintestui import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.macormap.kotlintestui.Data.Obj_post /** * Created by carlo on 15/03/2018. */ class MainAdapter : RecyclerView.Adapter<MainAdapter.MyViewHolder>() { private var listPostAdapter: List<Obj_post>? = null private var onClick: OnItemClicked? = null interface OnItemClicked { fun onItemClick(view : View, position: Int) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.card_row, parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val obj_post = listPostAdapter!!.get(position) holder.picAuthor.setImageResource(obj_post.author_idImg) holder.picImgPost.setImageResource(obj_post.post_idImg) holder.nameAuthor.setText(obj_post.author_name) holder.mainCommentAuthor.setText(obj_post.mainComment) holder.txt_num_watch.setText(String.format("%,d", obj_post.num_watch)) holder.txt_num_subcomment.setText(String.format("%,d", obj_post.num_subcomment)) holder.txt_num_love.setText(String.format("%,d", obj_post.num_love)) holder.cardView.setOnClickListener(View.OnClickListener { onClick?.onItemClick(it, position) Log.d("APP","clicked on " +position.toString()) } ) } fun setOnClick(onClick: OnItemClicked) { this.onClick = onClick } override fun getItemCount(): Int { return if (listPostAdapter == null) 0 else listPostAdapter!!.size } inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var cardView: CardView var picAuthor: ImageView var picImgPost: ImageView var nameAuthor: TextView var mainCommentAuthor: TextView var txt_num_watch: TextView var txt_num_subcomment: TextView var txt_num_love: TextView init { cardView = itemView.findViewById<View>(R.id.idCardrow) as CardView picAuthor = itemView.findViewById<View>(R.id.idPicAuthor) as ImageView picImgPost = itemView.findViewById<View>(R.id.idImgPost) as ImageView nameAuthor = itemView.findViewById<View>(R.id.idNameAuthor) as TextView mainCommentAuthor = itemView.findViewById<View>(R.id.idCommentAuthor) as TextView txt_num_watch = itemView.findViewById<View>(R.id.idNumWatch) as TextView txt_num_subcomment = itemView.findViewById<View>(R.id.idNumSubComment) as TextView txt_num_love = itemView.findViewById<View>(R.id.idNumLove) as TextView } } fun updateListData(listPost: List<Obj_post>) { listPostAdapter = listPost notifyDataSetChanged() } }
0
Kotlin
0
0
5f7682c8cd9a36c954f7778750c9b2fe509c32a4
3,131
KotlinTestUI
Apache License 2.0
calendarheatmaplib/src/main/java/com/eudycontreras/calendarheatmaplibrary/common/BubbleLayout.kt
EudyContreras
256,645,326
false
null
package com.eudycontreras.calendarheatmaplibrary.common import com.eudycontreras.calendarheatmaplibrary.Action import com.eudycontreras.calendarheatmaplibrary.properties.Coordinate /** * Copyright (C) 2020 Project X * * @Project ProjectX * @author <NAME>. * @since April 2020 */ internal interface BubbleLayout { val bubbleX: Float val bubbleY: Float val bubbleScaleX: Float val bubbleScaleY: Float val bubbleWidth: Float val bubbleHeight: Float val boundsWidth: Float val boundsHeight: Float val bubbleElevation: Float var bubblePointerLength: Float var bubbleCornerRadius: Float var bubbleColor: Int val drawOverlay: DrawOverlay? fun onLayout(delay: Long = 0, action: Action) fun toFront(offset: Float, pivotX: Float, pivotY: Float, duration: Long = 0) fun reveal(offset: Float, pivot: Coordinate, duration: Long = 0, onDone: Action? = null) fun conceal(offset: Float, pivot: Coordinate, duration: Long = 0, onDone: Action? = null) fun onMove(x: Float, y: Float, bubbleX: Float, offsetX: Float, offsetY: Float) fun setPointerOffset(offset: Float) fun onDataIntercepted(data: Any) fun setDataInteceptListener(dataListener: (Any) -> Unit) }
1
Kotlin
1
8
973203fb1e063ded41133b44925ce87a018ba6ec
1,232
Calendar-HeatMap
MIT License
app/src/androidTest/java/com/phicdy/mycuration/uitest/AddFeedTest.kt
phicdy
24,188,186
false
null
package com.phicdy.mycuration.uitest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.ActivityTestRule import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.UiObject2 import androidx.test.uiautomator.Until import com.phicdy.mycuration.BuildConfig import com.phicdy.mycuration.top.TopActivity import org.hamcrest.CoreMatchers.`is` import org.junit.After import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertThat import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 18) class AddFeedTest : UiTest() { @JvmField @Rule var activityTestRule = ActivityTestRule(TopActivity::class.java) @Before fun setup() { super.setup(activityTestRule.activity) } @After public override fun tearDown() { super.tearDown() } @Test fun addYahooNews() { // RSS 2.0 addAndCheckUrl( "https://news.yahoo.co.jp/rss/topics/top-picks.xml", "Yahoo!ニュース・トピックス - 主要" ) } @Test fun addYamBlog() { // Atom addAndCheckUrl("http://y-anz-m.blogspot.com/feeds/comments/default", "Y.A.M の 雑記帳") } private fun addAndCheckUrl(url: String, title: String) { val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) TopActivityControl.goToRssTab() TopActivityControl.clickAddRssButton() // Show edit text for URL if needed val searchButton = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "search_button")), 5000) searchButton?.click() // Open RSS URL val urlEditText = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "search_src_text")), 5000) assertNotNull("URL edit text was not found", urlEditText) urlEditText.text = url device.pressEnter() Thread.sleep(5000) // Assert RSS was added val feedTitles = device.wait(Until.findObjects( By.res(BuildConfig.APPLICATION_ID, "feedTitle")), 5000) assertNotNull("Feed was not found", feedTitles) if (feedTitles.size != 1) fail("Feed was not added") assertThat(feedTitles[0].text, `is`(title)) val footerTitle = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "tv_rss_footer_title")), 5000) assertThat(footerTitle.text, `is`("全てのRSSを表示")) // Assert articles of RSS were added val feedUnreadCountList = device.wait(Until.findObjects( By.res(BuildConfig.APPLICATION_ID, "feedCount")), 5000) assertNotNull("Feed count was not found", feedUnreadCountList) // Feed count list does not include show/hide option row, the size is 1 if (feedUnreadCountList.size != 1) fail("Feed count was not added") assertTrue(Integer.valueOf(feedUnreadCountList[0].text) >= -1) // Assert all article view shows val allArticleView = device.wait( Until.findObject( By.res(BuildConfig.APPLICATION_ID, "tv_rss_footer_title") ), 5000 ) assertNotNull(allArticleView) device.pressBack() } @Test fun tryInvalidUrl() { val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) takeScreenshot(device, "start_of_tryInvalidUrl_" + System.currentTimeMillis()) device.wait(Until.findObject(By.res(BuildConfig.APPLICATION_ID, "add")), 5000) takeScreenshot(device, "after_startActivity_" + System.currentTimeMillis()) TopActivityControl.goToRssTab() // Get current RSS size var rssList: UiObject2? = device.findObject(By.res(BuildConfig.APPLICATION_ID, "rv_rss")) var numOfRss = 0 if (rssList != null) { numOfRss = rssList.childCount } TopActivityControl.clickAddRssButton() // Show edit text for URL if needed val searchButton = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "search_button")), 5000) searchButton?.click() // Open invalid RSS URL val urlEditText = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "search_src_text")), 5000) assertNotNull("URL edit text was not found", urlEditText) urlEditText.text = "http://ghaorgja.co.jp/rss.xml" device.pressEnter() rssList = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "rv_rss")), 5000) if (numOfRss == 0) { assertNull(rssList) } else { assertThat(rssList!!.childCount, `is`(numOfRss)) } } @Test fun clickFabWithoutUrlOpen() { val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) TopActivityControl.goToRssTab() TopActivityControl.clickAddRssButton() // Open invalid RSS URL var fab = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "fab")), 5000) assertNotNull("Fab was not found") fab.click() // Fab still exists fab = device.wait(Until.findObject( By.res(BuildConfig.APPLICATION_ID, "fab")), 5000) assertNotNull(fab) } }
30
Kotlin
7
17
fb059cb8f9527e7efdf3c16ebd63e2506dc7398f
5,681
MyCuration
MIT License
app/src/main/java/com/marcossalto/peopleapp/presentation/users/edit/components/EditBottomBar.kt
marcossalto
843,101,377
false
{"Kotlin": 40412}
package com.marcossalto.peopleapp.presentation.users.edit.components import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.marcossalto.peopleapp.R @Composable fun EditBottomBar( modifier: Modifier = Modifier, textButton: String, enabled: Boolean = false, onAddUser: () -> Unit ) { Button( modifier = modifier .fillMaxWidth() .padding( horizontal = 20.dp, vertical = 32.dp, ) .height(48.dp), onClick = { onAddUser() }, enabled = enabled ) { Text( text = textButton ) } }
0
Kotlin
0
0
e89dbecc4cc1cc50db48e2aa0db999f54a7a1773
1,220
people-app
Apache License 2.0
phrecycler/src/main/java/dev/phlogiston/phrecycler/PhrecyclerAdapter.kt
phlogistonCode
253,092,350
false
null
package dev.phlogiston.phrecycler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException import java.lang.reflect.Modifier abstract class PhrecyclerAdapter<LT>(private val funcs: Array<out (LT) -> Unit>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var dataSet: List<LT> = ArrayList() abstract val setViewHolders: Map<Class<out PhrecyclerViewHolder<LT>>, Int> open fun setupViewType(): (LT) -> Class<out PhrecyclerViewHolder<LT>> = { setViewHolders.keys.first() } final override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): RecyclerView.ViewHolder { setViewHolders.keys.find { getViewHolderType(it) == viewType }?.let { setViewHolders[it]?.let { layoutId -> createBaseGenericKInstance(it, createViewLayout(parent, layoutId))?.let { vh -> when (vh) { is PhrecyclerViewHolder<*> -> { if (funcs.isNotEmpty()) { if (vh.wholeClick != -1) vh.wholeClickListener = View.OnClickListener { funcs[vh.wholeClick](dataSet[vh.adapterPosition]) } vh.viewClicks.values.forEach { id -> vh.viewsClickListeners.add(View.OnClickListener { funcs[id](dataSet[vh.adapterPosition]) }) } vh.createClickListeners() } } } return vh } ?: return createBaseViewHolder(parent) } ?: return createBaseViewHolder(parent) } ?: return createBaseViewHolder(parent) } final override fun getItemViewType(position: Int) = if (setViewHolders.keys.size == 1) setViewHolders.getValue(setViewHolders.keys.first()) else getViewHolderType(setupViewType().invoke(dataSet[position])) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { holder.tryCast<PhrecyclerViewHolder<LT>> { this.bind(dataSet[position]) } } override fun getItemCount() = dataSet.size fun append(item: LT) { this.dataSet = this.dataSet + item notifyItemRangeInserted(this.dataSet.size - 1, 1) } fun append(dataSet: List<LT>) { this.dataSet = this.dataSet + dataSet notifyItemRangeInserted(this.dataSet.size, dataSet.size) } fun prepend(item: LT) { this.dataSet = listOf(item) + this.dataSet notifyItemRangeInserted(0, 1) } fun prepend(dataSet: List<LT>) { this.dataSet.prepend(dataSet) notifyItemRangeInserted(0, dataSet.size) } fun add(item: LT, position: Int) { if (position < 0) { this.dataSet.addAfter(item, 0) notifyItemRangeInserted(0, 1) } else { this.dataSet.addAfter(item, position) notifyItemRangeInserted(position, 1) } } fun add(dataSet: List<LT>, position: Int) { if (position < 0) { this.dataSet.addAfter(dataSet, 0) notifyItemRangeInserted(0, dataSet.size) } else { this.dataSet.addAfter(dataSet, position) notifyItemRangeInserted(position, dataSet.size) } } fun addAfterItem(item: LT, by: LT.() -> Boolean) { add(item, dataSet.indexOfFirst(by) + 1) } fun addAfterItem(dataSet: List<LT>, by: LT.() -> Boolean) { add(dataSet, this.dataSet.indexOfFirst(by) + 1) } fun addBeforeItem(item: LT, by: LT.() -> Boolean) { add(item, dataSet.indexOfFirst(by)) } fun addBeforeItem(dataSet: List<LT>, by: LT.() -> Boolean) { add(dataSet, dataSet.indexOfFirst(by)) } fun replace(dataSet: List<LT>) { this.dataSet = dataSet notifyItemRangeChanged(0, dataSet.size) } fun replace(item: LT, position: Int) { if (position < 0) { // this.dataSet.replaceStart(item) // notifyItemChanged(0) } else { if (position < this.dataSet.size) { this.dataSet.replaceInPos(item, position) notifyItemChanged(position) } } } fun replace(dataSet: List<LT>, position: Int) { if (position < 0) { // this.dataSet.replaceStart(dataSet) // notifyItemRangeChanged(0, dataSet.size) } else { this.dataSet.replaceInPos(dataSet, position) } } fun replace(item: LT, by: LT.() -> Boolean) { replace(item, dataSet.indexOfFirst(by)) } fun replace(dataSet: List<LT>, by: LT.() -> Boolean) { replace(dataSet, this.dataSet.indexOfFirst(by)) } fun replaceStart(item: LT) { this.dataSet.replaceStart(item) notifyItemChanged(0) } fun replaceStart(dataSet: List<LT>) { this.dataSet.replaceStart(dataSet) notifyItemRangeChanged(0, dataSet.size) } fun replaceEnd(item: LT) { this.dataSet.replaceEnd(item) notifyItemChanged(this.dataSet.size - 1) } fun replaceEnd(dataSet: List<LT>) { this.dataSet.replaceEnd(dataSet) notifyItemRangeChanged(this.dataSet.size - dataSet.size, dataSet.size) } fun deleteStart() { this.dataSet = dataSet.drop(1) notifyItemRemoved(0) } fun deleteStart(size: Int) { this.dataSet = dataSet.drop(size) notifyItemRangeRemoved(0, size) } fun deleteEnd() { this.dataSet = dataSet.dropLast(1) notifyItemRemoved(this.dataSet.size) } fun deleteEnd(size: Int) { if (size >= this.dataSet.size) clearData() else { this.dataSet = dataSet.dropLast(size) notifyItemRangeRemoved(this.dataSet.size, size) } } fun delete(position: Int) { if (position < 0) { if (this.dataSet.isNotEmpty()) { this.dataSet = dataSet.drop(1) notifyItemRemoved(0) } } else { if (position < this.dataSet.size) { val tempList = this.dataSet.split(position) this.dataSet = tempList.first this.dataSet = this.dataSet + tempList.second.drop(1) notifyItemRemoved(tempList.first.size) } } } fun delete(size: Int, position: Int) { if (position < 0) { if (this.dataSet.isNotEmpty()) { if (this.dataSet.size < size) { clearData() } else { this.dataSet = this.dataSet.drop(size) notifyItemRangeRemoved(0, size) } } } else { if (position < this.dataSet.size) { if (this.dataSet.size - position < size) { val newSize = this.dataSet.size - position this.dataSet = this.dataSet.dropLast(newSize) notifyItemRangeRemoved(this.dataSet.size, newSize) } else { val tempList = this.dataSet.split(position) this.dataSet = tempList.first this.dataSet = this.dataSet + tempList.second.drop(size) notifyItemRangeRemoved(tempList.first.size, size) } } } } fun delete(item: LT) { val pos = dataSet.indexOf(item) dataSet = dataSet - item notifyItemRemoved(pos) } fun delete(by: LT.() -> Boolean) { dataSet.find(by)?.let { delete(it) } } fun clearData() { val tempSize = dataSet.size dataSet = emptyList() notifyItemRangeRemoved(0, tempSize) } fun getPosition(item: LT) = dataSet.indexOf(item) fun getPosition(by: LT.() -> Boolean) { dataSet.find(by)?.let { getPosition(it) } } fun getPositions(list: List<LT>): List<Int> { val positions = mutableListOf<Int>() list.forEach { positions.add(dataSet.indexOf(it)) } return positions } fun getScreenPositions(layoutManager: RecyclerView.LayoutManager?): List<Int?> { return getPositions(getScreenItems(layoutManager)) } fun getScreenPosition(layoutManager: RecyclerView.LayoutManager?, by: LT.() -> Boolean): Int? { return getScreenItem(layoutManager, by)?.let { getPosition(it) } } fun getScreenPositionFirst(layoutManager: RecyclerView.LayoutManager?): Int? { return getScreenItemFirst(layoutManager)?.let { getPosition(it) } } fun getScreenPositionLast(layoutManager: RecyclerView.LayoutManager?): Int? { return getScreenItemLast(layoutManager)?.let { getPosition(it) } } fun update(item: LT) = notifyItemChanged(dataSet.indexOf(item)) fun update(list: List<LT>) { list.forEach { item -> notifyItemChanged(dataSet.indexOf(item)) } } fun update(size: Int, position: Int) = notifyItemRangeChanged(position, size) fun update(by: LT.() -> Boolean) { notifyItemChanged(dataSet.indexOfFirst(by)) } fun updateStart(size: Int) = notifyItemRangeChanged(0, size) fun updateEnd(size: Int) = notifyItemRangeChanged(dataSet.size - size, size) fun updateScreen(layoutManager: RecyclerView.LayoutManager?) { update(getScreenItems(layoutManager)) } fun updateScreen(layoutManager: RecyclerView.LayoutManager?, by: LT.() -> Boolean) { getScreenItem(layoutManager, by)?.let { update(it) } } fun updateScreenFirst(layoutManager: RecyclerView.LayoutManager?) { getScreenItemFirst(layoutManager)?.let { update(it) } } fun updateScreenLast(layoutManager: RecyclerView.LayoutManager?) { getScreenItemLast(layoutManager)?.let { update(it) } } fun updateSoftAll() = notifyItemRangeChanged(0, dataSet.size) fun updateHardAll() = notifyDataSetChanged() fun getItem(position: Int) = dataSet[position] fun getFirstItem() = dataSet.first() fun getLastItem() = dataSet.last() fun getItem(by: LT.() -> Boolean) = dataSet.find(by) fun getItems(by: LT.() -> Boolean) = dataSet.filter(by) fun getScreenItems(layoutManager: RecyclerView.LayoutManager?): List<LT> { return when(layoutManager) { is LinearLayoutManager -> { val firstId = layoutManager.findFirstVisibleItemPosition() val lastId = layoutManager.findLastVisibleItemPosition() dataSet.subList(firstId, lastId) } is GridLayoutManager -> { val firstId = layoutManager.findFirstVisibleItemPosition() val lastId = layoutManager.findLastVisibleItemPosition() dataSet.subList(firstId, lastId) } else -> listOf() } } fun getScreenItem(layoutManager: RecyclerView.LayoutManager?, by: LT.() -> Boolean): LT? { return when(layoutManager) { is LinearLayoutManager -> { val firstId = layoutManager.findFirstVisibleItemPosition() val lastId = layoutManager.findLastVisibleItemPosition() dataSet.subList(firstId, lastId).find(by) } is GridLayoutManager -> { val firstId = layoutManager.findFirstVisibleItemPosition() val lastId = layoutManager.findLastVisibleItemPosition() dataSet.subList(firstId, lastId).find(by) } else -> null } } fun getScreenItemFirst(layoutManager: RecyclerView.LayoutManager?): LT? { return when(layoutManager) { is LinearLayoutManager -> { val firstId = layoutManager.findFirstVisibleItemPosition() dataSet[firstId] } is GridLayoutManager -> { val firstId = layoutManager.findFirstVisibleItemPosition() dataSet[firstId] } else -> null } } fun getScreenItemLast(layoutManager: RecyclerView.LayoutManager?): LT? { return when(layoutManager) { is LinearLayoutManager -> { val lastId = layoutManager.findLastVisibleItemPosition() dataSet[lastId] } is GridLayoutManager -> { val lastId = layoutManager.findLastVisibleItemPosition() dataSet[lastId] } else -> null } } fun getDataSet() = this.dataSet fun change(item: LT, change: LT.() -> Unit) { dataSet.find { it == item }?.let { it.change() notifyItemChanged(dataSet.indexOf(it)) } } fun vhClassToLayout(vararg pairs: Pair<Class<out PhrecyclerViewHolder<LT>>, Int>) : Map<Class<out PhrecyclerViewHolder<LT>>, Int> = mapOf(*pairs) private fun createBaseViewHolder(parent: ViewGroup) = BaseViewHolder(createViewLayout(parent, R.layout.item_baseviewholder)) private fun createViewLayout(parent: ViewGroup, @LayoutRes layoutResId: Int) = LayoutInflater.from(parent.context).inflate( layoutResId, parent, false ) private fun getViewHolderType(viewHolderClass: Class<*>) = viewHolderClass.hashCode() private fun createBaseGenericKInstance(z: Class<*>, view: View): RecyclerView.ViewHolder? { try { val constructor: Constructor<*> // inner and unstatic class return if (z.isMemberClass && !Modifier.isStatic(z.modifiers)) { constructor = z.getDeclaredConstructor(javaClass, View::class.java) constructor.isAccessible = true constructor.newInstance(this, view) as RecyclerView.ViewHolder } else { constructor = z.getDeclaredConstructor(View::class.java) constructor.isAccessible = true constructor.newInstance(view) as RecyclerView.ViewHolder } } catch (e: NoSuchMethodException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } catch (e: InstantiationException) { e.printStackTrace() } catch (e: InvocationTargetException) { e.printStackTrace() } return null } private inline fun <reified T> Any?.tryCast(block: T.() -> Unit) { if (this is T) { block() } } private fun List<LT>.prepend(list: List<LT>) { val tempList = this dataSet = list dataSet = dataSet + tempList } private fun List<LT>.addAfter(list: List<LT>, position: Int) { if (position < this.size) { val tempList = this.split(position) dataSet = tempList.first dataSet = dataSet + list dataSet = dataSet + tempList.second } else { dataSet = dataSet + list } } private fun List<LT>.addAfter(item: LT, position: Int) { if (position < this.size) { val tempList = this.split(position) dataSet = tempList.first dataSet = dataSet + item dataSet = dataSet + tempList.second } else { dataSet = dataSet + item } } private fun List<LT>.replaceStart(list: List<LT>) { if (this.size <= list.size) { dataSet = list } else { val tempList = this.drop(list.size) dataSet = list dataSet = dataSet + tempList } } private fun List<LT>.replaceEnd(list: List<LT>) { if (this.size <= list.size) { dataSet = list } else { val tempList = this.take(this.size - list.size) dataSet = tempList dataSet = dataSet + list } } private fun List<LT>.replaceInPos(list: List<LT>, position: Int) { if (this.size <= list.size) { dataSet = list notifyItemRangeChanged(0, dataSet.size) } else { if (position < this.size && this.size - position > list.size) { val tempList = this.split(position) dataSet = tempList.first dataSet = dataSet + list dataSet = dataSet + tempList.second.drop(list.size) notifyItemRangeChanged(position, list.size) } else { val tempList = this.take(position) dataSet = tempList dataSet = dataSet + list notifyItemRangeChanged(position, this.size - position) notifyItemRangeInserted(this.size, list.size - (this.size - position)) } } } private fun List<LT>.replaceStart(item: LT) { if (this.size <= 1) { dataSet = listOf(item) } else { val tempList = this.drop(1) dataSet = listOf(item) dataSet = dataSet + tempList } } private fun List<LT>.replaceEnd(item: LT) { if (this.size <= 1) { dataSet = listOf(item) } else { val tempList = this.take(this.size - 1) dataSet = tempList dataSet = dataSet + item } } private fun List<LT>.replaceInPos(item: LT, position: Int) { if (this.size <= 1) { dataSet = listOf(item) } else { if (position < this.size) { val tempList = this.split(position) dataSet = tempList.first dataSet = dataSet + item dataSet = dataSet + tempList.second.drop(1) } } } }
0
Kotlin
0
1
60c4e3864255cae5fb04f99e7a73d08b6c8e5924
18,316
phrecycler
Apache License 2.0
app/src/main/java/com/example/mykotlinapp/model/mappers/impl/comment/create/CreateCommentMapper.kt
vbounyasit
522,266,559
false
{"Kotlin": 507212}
package com.example.mykotlinapp.model.mappers.impl.comment.create import com.example.mykotlinapp.model.dto.inputs.form.comment.CreateCommentInput import com.example.mykotlinapp.model.mappers.NetworkRequestMapper import com.example.mykotlinapp.network.dto.requests.comment.CreateCommentRequest object CreateCommentMapper : NetworkRequestMapper<CreateCommentInput, CreateCommentRequest> { override fun toNetworkRequest(entity: CreateCommentInput): CreateCommentRequest { return CreateCommentRequest(entity.content, entity.parentRemoteId) } }
0
Kotlin
0
1
a9812a061f9214b44ba326b77afe335a003cc22e
557
MyAndroidApp
Apache License 2.0
src/main/kotlin/com/github/std/kacket/analysis/exten/DefineDatatypeAnalyzer.kt
ShorterThanDijkstra
557,325,223
false
null
package com.github.std.kacket.analysis.exten import com.github.std.kacket.analysis.* import com.github.std.kacket.expr.* import com.github.std.kacket.expr.exten.DefineDatatype import com.github.std.kacket.expr.exten.ExtExpr import kotlin.math.exp object DefineDatatypeAnalyzer : ExtAnalyzer { override fun modifyEnv(env: InitProcEnv, expr: ExtExpr) { val dtdf = expr as DefineDatatype env.addRule(dtdf.predName, arityEqual(1)) for (variant in dtdf.variants) { env.addRule(variant.name, arityEqual(variant.fields.size)) } } override fun support(expr: ExtExpr): Boolean = expr is DefineDatatype override fun analyze(expr: ExtExpr, env: ProcEnv, root: ProcCallAnalyzer) { val dtdf = expr as DefineDatatype for (variant in dtdf.variants) { for (pred in variant.fields.values) { when (pred) { is Var -> { try { env.applyRule(pred.id.value, 1) } catch (ex: AnalysisError) { println("Expect a procedure with 1 arity, at (${pred.lineNumber()}, ${pred.columnNumber()}), procedure:${pred.id.value}") } } is Procedure -> { if (pred.args.size != 1) { println("Expect a procedure with 1 arity, at (${pred.lineNumber()}, ${pred.columnNumber()}): procedure:<procedure>") } root.analyzeExpr(pred, env) } is Const -> { throw AnalysisError("Expect a procedure, at (${pred.lineNumber()}, ${pred.columnNumber()})") } is Define -> { throw AnalysisError("Expect a procedure, at (${pred.lineNumber()}, ${pred.columnNumber()})") } is Quote -> { throw AnalysisError("Expect a procedure, at (${pred.lineNumber()}, ${pred.columnNumber()})") } else -> { root.analyzeExpr(pred, env) } } } } } }
0
Kotlin
0
0
7e9638ac25ef81583c4610c9f042cc1a79d8362a
2,281
Kacket
MIT License
app/src/main/java/com/ngthphong92/gitstar/utils/FunctionBuilder.kt
ngthphong92
391,243,062
false
null
package com.ngthphong92.gitstar.utils import androidx.appcompat.app.AppCompatActivity import androidx.databinding.ViewDataBinding inline fun toolbarFunctionQueue(init: FunctionBuilder.ToolbarBuilder.() -> Unit) = FunctionBuilder.ToolbarBuilder().apply(init).build() interface FunctionBuilder { class ToolbarBuilder { private var funcQueue: ((activity: AppCompatActivity?, toolbar: ViewDataBinding?) -> Unit)? = null fun func(messageFunc: ((activity: AppCompatActivity?, toolbar: ViewDataBinding?) -> Unit)): ToolbarBuilder { this.funcQueue = messageFunc return this } fun build(): (((activity: AppCompatActivity?, toolbar: ViewDataBinding?) -> Unit)?) { return this.funcQueue } } }
0
Kotlin
0
1
131fbdae62c54319191ba7e9f230d56bd90f02d0
786
GitStar
The Unlicense
app/src/main/java/com/dscout/membranevideoroomdemo/styles/button.kt
jellyfish-dev
481,725,130
false
{"Kotlin": 219447, "Shell": 697}
package com.dscout.membranevideoroomdemo.styles import androidx.compose.material.ButtonColors import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.graphics.Color fun AppButtonColors(): ButtonColors { return DefaultButtonColors( backgroundColor = Blue, contentColor = Color.White, disabledBackgroundColor = Blue.darker(0.2f), disabledContentColor = Color.White.darker(0.2f) ) } private data class DefaultButtonColors( private val backgroundColor: Color, private val contentColor: Color, private val disabledBackgroundColor: Color, private val disabledContentColor: Color ) : ButtonColors { @Composable override fun backgroundColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) backgroundColor else disabledBackgroundColor) } @Composable override fun contentColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) contentColor else disabledContentColor) } }
0
Kotlin
3
5
f117f5d9a6995d873f6a8287215cd7069e9385ac
1,118
membrane-webrtc-android
Apache License 2.0
core/src/ru/serdjuk/zxsna/app/palette/PaletteUtils.kt
vito-Z80
302,118,445
false
null
package ru.serdjuk.zxsna.app.palette import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.math.Rectangle import ru.serdjuk.zxsna.app.resources.hexColor256 import ru.serdjuk.zxsna.app.resources.hexColor512 import ru.serdjuk.zxsna.app.system.res import kotlin.math.abs import kotlin.math.min @ExperimentalUnsignedTypes object PaletteUtils { // fun convertPaletteTo(): ByteArray { // val result = com.badlogic.gdx.utils.ByteArray() // val ba = com.badlogic.gdx.utils.ByteArray() // Array<String>(16) { // val str = StringBuilder() // ba.clear() // repeat(16) { index -> // val c = convertTo9bpp(PaletteData.paletteTables.userTable[it * 16 + index].colorId) // val bit9 = c and 256 shr 8 // val byte = c and 255 // // TODO add hex variation // str.append("$byte, $bit9, ") // ba.add(byte.toByte(), bit9.toByte()) // } // result.addAll(ba) // str.toString() // } // return result.toArray() // } // // fun convertPaletteFrom(byteArray: ByteArray) { //// PaletteData.paletteTables.userRegion.flip(false,true) // // если бит 9bpp включен то умножаем первый байт на 2 + 1 // PaletteData.paletteTables.userTable.forEachIndexed { id, cell -> // val colorId = if (byteArray[id * 2 + 1].toUByte().toInt() == 0) { // byteArray[id * 2].toUByte().toInt() * 2 // } else { // byteArray[id * 2].toUByte().toInt() * 2 + 1 // } // cell.colorId = colorId // cell.hexColor = hexColor512[colorId].hex // drawCellFill(PaletteData.paletteTables.userTable[id], hexColor512[colorId].int) // } //// PaletteData.paletteTables.userRegion.flip(false,true) // // res.textureUpdate() // } fun convertImage(encodedData: ByteArray, colorsNumber: Int) { res.disposeUploadImage() val pixmap = Pixmap(encodedData, 0, encodedData.size) // FIXME при Blending.NONE получаю пустые пиксели (дохуя, как на реале) // походу с альфой залупа // pixmap.blending = Pixmap.Blending.None res.uploadImagePixmap = pixmap lazy { convertToNextColors(res.uploadImagePixmap!!, colorsNumber) }.value lazy { res.uploadImageTexture = Texture(res.uploadImagePixmap) }.value } private fun averageByte(int: Int): Int { var m = 255 var r = 255 for (i in allBytes.indices) { if (min(abs(allBytes[i] - int), m) < m) { m = min(abs(allBytes[i] - int), m) r = i } } return allBytes[r] } private fun averageBlueByte(int: Int): Int { var m = 255 var r = 255 for (i in blueBytes.indices) { if (min(abs(blueBytes[i] - int), m) < m) { m = min(abs(blueBytes[i] - int), m) r = i } } return blueBytes[r] } // для 256 цветов синий состоит только из 4-х значений private val blueBytes = intArrayOf(0x00, 0x6d, 0xb6, 0xff) // для 512 цветов rgb имеют по 8 значений private val allBytes = intArrayOf(0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff) var readyForSaveImage: ByteArray? = null private fun convertToNextColors(pixmap: Pixmap, colorsNumber: Int) { readyForSaveImage = ByteArray(pixmap.width * pixmap.height) var byteCounter = 0 repeat(pixmap.height) { y -> repeat(pixmap.width) { x -> val color = pixmap.getPixel(x, y) // TODO добавить Флойда – Стейнберга // перемножаем цвета с альфаканалом val aC = ((color and 255)) / 255f val rC = (color ushr 24 and 255) / 255f * aC val gC = (color ushr 16 and 255) / 255f * aC val bC = (color ushr 8 and 255) / 255f * aC // ищем усредненный цвет для каждого канала r,g,b val r = averageByte((rC * 255f).toInt()) and 255 shl 24 val g = averageByte((gC * 255).toInt()) and 255 shl 16 val b = if (colorsNumber == 512) averageByte((bC * 255).toInt()) and 255 shl 8 else averageBlueByte((bC * 255).toInt()) and 255 shl 8 val hex = StringBuilder((r or g or b or 255).toUInt().toString(16)) while (hex.length < 8) { hex.insert(0, "0") } readyForSaveImage!![byteCounter++] = hexColor256.indexOfFirst { it.hex == hex.toString() }.toByte() // println("HEX =: $hex") // val h = hexColor256.find { it.hex == hex.toString() } // if (h == null) { // println("${r or g or b or 255}") // println((r or g or b or 255).toString(16)) // // throw Exception("ИДИ НА ХОЙ ЦВЕТ !!!!") // } // если цвет получился полностью прозрачным то стриаем пиксель if (r or g or b == 0) { pixmap.drawPixel(x, y, Color.CLEAR.toIntBits()) } else { pixmap.drawPixel(x, y, hex.toString().toLong(16).toInt()) } } } } // индекс цвета делится на 2 и если есть остаток то включить бит для 9bpp private fun convertTo9bpp(colorId: Int) = (colorId / 2) or (colorId % 2 shl 8) // not used, be removed fun convertImageArea(bounds: Rectangle, colorsNumber: Int): ByteArray { val byteArray = ByteArray((bounds.height * bounds.width).toInt()) var counter = 0 repeat(bounds.height.toInt()) { h -> repeat(bounds.width.toInt()) { w -> // val hex = res.uploadImagePixmap?.getPixel((w + bounds.x).toInt(), (bounds.height - 1 - h + bounds.y).toInt())?.toUInt()?.toString(16)!! // val hexId = if (colorsNumber == 512) hexColor512.indexOfFirst { it.hex.contains(hex) } // else hexColor256.indexOfFirst { it.hex.contains(hex) } // FIXME некоторые цвета хуйню порят val int = res.uploadImagePixmap?.getPixel((w + bounds.x).toInt(), (h + bounds.y).toInt())!! val hex = StringBuilder(int.toUInt().toString(16)) while (hex.length < 8) { hex.insert(0, "0") } val intId = if (colorsNumber == 512) hexColor512.indexOfFirst { it.int == int } else hexColor256.indexOfFirst { it.hex == hex.toString() } if (intId < 0) { println(hex) } // println(res.uploadImagePixmap?.getPixel((w + bounds.x).toInt(), (h + bounds.y).toInt())!!.toString(16)) // val palId = Agent.data.paletteData.indexOf(hexId.toByte()) // println(intId) // fColor.set(layer.pixmap.getPixel(w + x, height - 1 - h + y)) // byteArray[counter++] = AppColor.rgbaColors.indexOf(fColor).toByte() // byteArray[counter++] = hexId.toByte().toUByte().toByte() byteArray[counter++] = intId.toByte() } } return byteArray } }
1
null
1
1
8e19849cb1d6f71fc6a155940a2c3180db98e89d
7,421
ZXSNAv2
Apache License 2.0
src/main/java/siosio/doma/DaoType.kt
Bhanditz
168,947,337
true
{"Kotlin": 49222, "Java": 19150, "HTML": 104}
package siosio.doma import com.intellij.codeInsight.* import com.intellij.psi.* import siosio.doma.inspection.dao.* /** * Daoのメソッドタイプを表す列挙型。 * * @author sioiso */ enum class DaoType( val annotationName: String, val rule: DaoInspectionRule, val extension: String = "sql") { SELECT("org.seasar.doma.Select", selectMethodRule), UPDATE("org.seasar.doma.Update", updateMethodRule), INSERT("org.seasar.doma.Insert", insertMethodRule), DELETE("org.seasar.doma.Delete", deleteMethodRule), BATCH_INSERT("org.seasar.doma.BatchInsert", batchInsertMethodRule), BATCH_UPDATE("org.seasar.doma.BatchUpdate", batchUpdateMethodRule), BATCH_DELETE("org.seasar.doma.BatchDelete", batchDeleteMethodRule), SCRIPT("org.seasar.doma.Script", scriptMethodRule, "script"); companion object { /** * メソッドのタイプを取得する。 * * この列挙型がサポートしないタイプの場合は`null` * * @param method メソッド * @return タイプ */ fun valueOf(method: PsiMethod): DaoType? { return values().firstOrNull { AnnotationUtil.isAnnotated(method, it.annotationName, AnnotationUtil.CHECK_TYPE) } } } }
0
Kotlin
0
0
85920064544a546d42081492ca56c67f21b728d6
1,208
DomaSupport
MIT License
app/src/main/java/com/bernaferrari/changedetection/forms/FormInputText.kt
karthikbompada
166,797,089
true
{"Kotlin": 300880, "Java": 50940}
package com.bernaferrari.changedetection.forms import android.text.Editable import android.view.animation.AnimationUtils import androidx.core.view.isVisible import com.bernaferrari.changedetection.R import com.bernaferrari.changedetection.extensions.onTextChanged import com.xwray.groupie.kotlinandroidextensions.ViewHolder import kotlinx.android.synthetic.main.dialog_input_text.* class FormInputText( var textInput: String, val title: String, val kind: String ) : com.xwray.groupie.kotlinandroidextensions.Item() { private var visibleHolder: ViewHolder? = null override fun getLayout(): Int = R.layout.dialog_input_text override fun bind(holder: ViewHolder, position: Int) { visibleHolder = holder Forms.setImage(holder.kind_input, kind) val queryClear = holder.clear_input queryClear.isVisible = textInput.isNotEmpty() // TooltipCompat.setTooltipText(queryClear, queryClear.contentDescription) queryClear.setOnClickListener { holder.text_input.setText("") } holder.kind_input.setOnClickListener { // request focus on input when icon is tapped holder.text_input.requestFocus() } holder.text_input.apply { this.text = Editable.Factory.getInstance().newEditable(textInput) this.inputType = Forms.inputType(kind) this.hint = Forms.getHint(this.context, kind) this.onTextChanged { queryClear.isVisible = it.isNotEmpty() } } } fun shakeIt() { // inspired by Hurry from <NAME> visibleHolder?.containerView?.let { it.startAnimation(AnimationUtils.loadAnimation(it.context, R.anim.shake)) } } override fun unbind(holder: ViewHolder) { textInput = holder.text_input.text.toString() super.unbind(holder) } internal fun retrieveText(): String { return visibleHolder?.text_input?.text?.toString() ?.replace(Regex("\\s+"), " ")?.trim() ?: textInput.replace(Regex("\\s+"), " ").trim() } }
0
Kotlin
0
1
702bd4a63f453cee0fa604b6a07415849da1ad12
2,131
ChangeDetection
Apache License 2.0
app/src/main/java/com/krm/animations/anim/zooming_exits/ZoomOutUpAnimator.kt
cadet29manikandan
245,152,765
false
null
package com.krm.animations.anim.zooming_exits import android.animation.ObjectAnimator import android.view.View import com.krm.animations.anim.BaseViewAnimator class ZoomOutUpAnimator : BaseViewAnimator() { override fun prepare(target: View?) { animatorAgent!!.playTogether( ObjectAnimator.ofFloat(target, "alpha", 1f, 1f, 0f), ObjectAnimator.ofFloat(target, "scaleX", 1f, 0.475f, 0.1f), ObjectAnimator.ofFloat(target, "scaleY", 1f, 0.475f, 0.1f), ObjectAnimator.ofFloat(target, "translationY", 0f, 60f, -target!!.bottom.toFloat()) ) } }
0
Kotlin
0
0
64af1b1155887b72f6a63bb7bdb72508a8e132af
610
Animations
Apache License 2.0
core/src/main/java/com/kanyideveloper/core/data/MealTimePreferences.kt
JoelKanyi
554,742,212
false
null
/* * Copyright 2022 Joel Kanyi. * * 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.kanyideveloper.core.data import androidx.appcompat.app.AppCompatDelegate import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import com.kanyideveloper.core.model.MealPlanPreference import com.kanyideveloper.core.util.Constants.ALLERGIES import com.kanyideveloper.core.util.Constants.DISH_TYPES import com.kanyideveloper.core.util.Constants.NUMBER_OF_PEOPLE import com.kanyideveloper.core.util.Constants.THEME_OPTIONS import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class MealTimePreferences( private val dataStore: DataStore<Preferences> ) { suspend fun saveTheme(themeValue: Int) { dataStore.edit { preferences -> preferences[THEME_OPTIONS] = themeValue } } suspend fun saveMealPlanPreferences( allergies: List<String>, numberOfPeople: String, dishTypes: List<String> ) { dataStore.edit { preferences -> preferences[ALLERGIES] = allergies.toSet() preferences[NUMBER_OF_PEOPLE] = numberOfPeople preferences[DISH_TYPES] = dishTypes.toSet() } } val getTheme: Flow<Int> = dataStore.data.map { preferences -> preferences[THEME_OPTIONS] ?: AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM } val mealPlanPreferences: Flow<MealPlanPreference?> = dataStore.data.map { preferences -> MealPlanPreference( numberOfPeople = preferences[NUMBER_OF_PEOPLE] ?: "0", dishTypes = preferences[DISH_TYPES]?.toList() ?: listOf(""), allergies = preferences[ALLERGIES]?.toList() ?: listOf("") ) } }
12
Kotlin
9
69
040b552070450d2e2b34cd1817eece7145fb2086
2,302
MealTime
Apache License 2.0
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/apiv2/embed/GfycatItem.kt
xxczaki
149,495,162
true
{"Kotlin": 905217, "Java": 181094}
package io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.embed import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class GfycatItem( @JsonProperty("mp4Url") val mp4Url : String, @JsonProperty("gifUrl") val gifUrl : String, @JsonProperty("webmUrl") val webmUrl : String )
0
Kotlin
0
0
b2a66fab000b35bbb9d1e8b84b7e75478a0bee03
438
WykopMobilny
MIT License
navuitest/src/main/java/com/hutchins/navuitest/TweakSettingsDelegate.kt
taekwonjoe01
184,627,574
false
{"Kotlin": 136889}
package com.hutchins.navuitest import android.view.View import androidx.appcompat.widget.AppCompatButton import com.hutchins.navui.jetpack.JetpackNavUIController import com.hutchins.navui.jetpack.JetpackToolbarDelegate class TweakSettingsDelegate( private val jetpackNavUIController: JetpackNavUIController, private val view: View ) { init { view.apply { findViewById<AppCompatButton>(R.id.buttonChangeTitle)?.setOnClickListener { jetpackNavUIController.setToolbarTitle("Tweaked Title") } findViewById<AppCompatButton>(R.id.buttonSetVisible)?.setOnClickListener { jetpackNavUIController.setToolbarVisibility(JetpackToolbarDelegate.ToolbarVisibilityState.VISIBLE) } findViewById<AppCompatButton>(R.id.buttonSetGone)?.setOnClickListener { jetpackNavUIController.setToolbarVisibility(JetpackToolbarDelegate.ToolbarVisibilityState.GONE) } findViewById<AppCompatButton>(R.id.buttonSetInvisible)?.setOnClickListener { jetpackNavUIController.setToolbarVisibility(JetpackToolbarDelegate.ToolbarVisibilityState.INVISIBLE) } findViewById<AppCompatButton>(R.id.buttonAnimateVisible)?.setOnClickListener { jetpackNavUIController.animateToolbarVisibility(JetpackToolbarDelegate.ToolbarVisibilityState.VISIBLE, 500L) } findViewById<AppCompatButton>(R.id.buttonAnimateGone)?.setOnClickListener { jetpackNavUIController.animateToolbarVisibility(JetpackToolbarDelegate.ToolbarVisibilityState.GONE, 500L) } findViewById<AppCompatButton>(R.id.buttonAnimateInvisible)?.setOnClickListener { jetpackNavUIController.animateToolbarVisibility(JetpackToolbarDelegate.ToolbarVisibilityState.INVISIBLE, 500L) } findViewById<AppCompatButton>(R.id.buttonSetOverrideUp)?.setOnClickListener { jetpackNavUIController.setToolbarOverrideUp(true) } findViewById<AppCompatButton>(R.id.buttonRemoveOverrideUp)?.setOnClickListener { jetpackNavUIController.setToolbarOverrideUp(false) } findViewById<AppCompatButton>(R.id.buttonSetNavViewVisibile)?.setOnClickListener { jetpackNavUIController.setNavViewVisibility(true) } findViewById<AppCompatButton>(R.id.buttonSetNavViewGone)?.setOnClickListener { jetpackNavUIController.setNavViewVisibility(false) } } } }
3
Kotlin
0
1
34678141c021a4d775c0ce79d7bbd071fbfd01b9
2,593
BetterJetpackNav
MIT License
features/scheduler/src/main/kotlin/dev/triumphteam/scheduler/Scheduler.kt
TriumphTeam
221,935,145
false
null
package dev.triumphteam.scheduler import dev.triumphteam.core.TriumphApplication import dev.triumphteam.core.dsl.TriumphDsl import dev.triumphteam.core.feature.ApplicationFeature import dev.triumphteam.core.feature.attribute.AttributeKey import dev.triumphteam.core.feature.attribute.key import dev.triumphteam.core.feature.featureOrNull import dev.triumphteam.core.feature.install import dev.triumphteam.scheduler.schedule.DateSchedule import dev.triumphteam.scheduler.schedule.DayTimeSchedule import dev.triumphteam.scheduler.schedule.Schedule import dev.triumphteam.scheduler.schedule.TimerSchedule import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import java.time.Clock import java.time.DayOfWeek import java.time.LocalDateTime import java.time.LocalTime import java.time.temporal.ChronoUnit import java.util.EnumSet import java.util.concurrent.Executors import kotlin.coroutines.CoroutineContext import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds /** * Simple coroutine based scheduler. */ public class Scheduler : CoroutineScope { private val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() private val job = Job() override val coroutineContext: CoroutineContext get() = job + dispatcher private val schedules = mutableListOf<Schedule>() private var clock = Clock.systemDefaultZone() private var started = false /** * Runs a task at a given date time. */ public fun runTaskAt(date: LocalDateTime, action: suspend () -> Unit) { schedules.add(DateSchedule(date, action)) } /** * Runs task after a given duration. */ public fun runTaskIn(time: Duration, task: suspend () -> Unit) { schedules.add(TimerSchedule(0, time.inWholeSeconds, false, task)) } /** * Runs task every `x` duration after `y` duration. */ public fun runTaskEvery(period: Duration, delay: Duration, task: suspend () -> Unit) { schedules.add(TimerSchedule(period.inWholeSeconds, delay.inWholeSeconds, true, task)) } /** * Runs task every given days at a given time. */ public fun runTaskEvery(days: Set<DayOfWeek>, at: LocalTime, task: suspend () -> Unit) { schedules.add(DayTimeSchedule(days, at, true, task)) } /** * Start the timer logic. */ private fun start(): Scheduler { launch { var lastCheck: LocalDateTime? = null while (true) { val second = LocalDateTime.now(clock).truncatedTo(ChronoUnit.SECONDS) if (lastCheck != second) { lastCheck = second coroutineScope { launchSchedules(second) } } delay(50) } } started = true return this } /** * Launches each schedule. */ private fun launchSchedules(nowMinute: LocalDateTime) { schedules.forEach { launch { if (!it.shouldRun(nowMinute)) return@launch it.execute() if (!it.repeating) schedules.remove(it) } } } /** * Feature companion, which is a factory for the [Scheduler]. */ public companion object Feature : ApplicationFeature<TriumphApplication, Scheduler, Scheduler> { /** * The locale [AttributeKey]. */ override val key: AttributeKey<Scheduler> = key("scheduler") /** * Installation function to create a [Scheduler] feature. */ override fun install(application: TriumphApplication, configure: Scheduler.() -> Unit): Scheduler { return Scheduler().apply(configure).apply { start() } } } } /** * Runs task after a given duration. */ @TriumphDsl public fun TriumphApplication.runTaskIn(time: Duration, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskIn(time, task) } /** * Runs a task at a given date time. */ @TriumphDsl public fun TriumphApplication.runTaskAt(date: LocalDateTime, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskAt(date, task) } /** * Runs a task at a given time. */ @TriumphDsl public fun TriumphApplication.runTaskAt(time: LocalTime, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskAt(time.atDate(LocalDateTime.now().toLocalDate()), task) } /** * Runs task every `x` duration after `y` duration. */ @TriumphDsl public fun TriumphApplication.runTaskEvery(period: Duration, delay: Duration = 0.seconds, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskEvery(period, delay, task) } /** * Runs task every given days at a given time. */ @TriumphDsl public fun TriumphApplication.runTaskEvery(days: Set<DayOfWeek>, at: LocalTime, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskEvery(days, at, task) } /** * Runs task every given days at a given time. */ @TriumphDsl public fun TriumphApplication.runTaskEvery(vararg days: DayOfWeek, at: LocalTime, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskEvery(days.toCollection(EnumSet.noneOf(DayOfWeek::class.java)), at, task) } /** * Runs task every given day at a given time. */ @TriumphDsl public fun TriumphApplication.runTaskEvery(day: DayOfWeek, at: LocalTime, task: suspend () -> Unit) { val scheduler = featureOrNull(Scheduler) ?: install(Scheduler) return scheduler.runTaskEvery(EnumSet.of(day), at, task) }
0
Kotlin
0
2
e6869b76934302deb3fb360550e084c543f03676
6,042
triumph-core
MIT License
src/main/kotlin/com/cccc/essentials/creations/Cat.kt
Cosmic-Coding-Community-Club
553,430,065
false
{"Kotlin": 42783}
package com.cccc.essentials.creations class Cat : Feline
0
Kotlin
0
2
0a76599a0f416b59e4e653666e9d0ea3de7c34b0
57
essential-kotlin-course
Apache License 2.0
app/src/main/java/fr/phlab/notesrapides/data/bdd/Category.kt
pierre-henriLeroux
861,836,618
false
{"Kotlin": 120047}
package fr.phlab.notesrapides.data.bdd import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Category( @PrimaryKey(autoGenerate = true) val id: Long, val name: String, val isPref: Boolean, )
0
Kotlin
0
0
d925ed1df1c663ee0e8681b627a052414843db92
231
Notes-Rapides
MIT License
app/src/main/java/com/example/wetterbericht/data/local/source/habits/HabitsLocalDataSource.kt
Alstonargodi
481,945,403
false
{"Kotlin": 176326}
package com.example.wetterbericht.data.local.source.habits import android.content.Context import androidx.lifecycle.LiveData import androidx.paging.DataSource import androidx.sqlite.db.SupportSQLiteQuery import com.example.wetterbericht.data.local.database.LocalDatabase import com.example.wetterbericht.data.local.entity.dailyhabits.ColorHabits import com.example.wetterbericht.data.local.entity.dailyhabits.DailyHabits import com.example.wetterbericht.data.local.entity.dailyhabits.IconHabits import java.util.concurrent.Executors class HabitsLocalDataSource(val context: Context): IHabitsLocalDataSource { private val habitsDao = LocalDatabase.setInstance(context).habitsDao() private val executorService = Executors.newSingleThreadExecutor() override fun getHabits(query: SupportSQLiteQuery): DataSource.Factory<Int, DailyHabits> { return habitsDao.getHabits(query) } override fun readHabitsLocal(): LiveData<List<DailyHabits>> { return habitsDao.readHabits() } override fun insertHabitsLocal(data: DailyHabits) { executorService.execute { habitsDao.insertHabits(data) } } override fun deleteHabitsLocal(name: String) { habitsDao.deleteHabits(name) } override fun getHabitsIcon(): LiveData<List<IconHabits>> { return habitsDao.readHabitsIcon() } override fun getHabitsColors(): LiveData<List<ColorHabits>> { return habitsDao.readHabitsColor() } }
0
Kotlin
0
0
f5c72c30fab903dc206632f665a14774d43ca8fa
1,463
Plan
Apache License 2.0
app/src/main/java/ru/poetofcode/whatahorror/presentation/BaseFragment.kt
poetofcode
345,447,605
false
null
package ru.poetofcode.whatahorror.presentation import androidx.fragment.app.Fragment open class BaseFragment : Fragment() { protected fun gameLogic() = mainActivity().gameLogic!! protected fun mainActivity(): MainActivity { return requireActivity() as MainActivity } protected fun finish() { mainActivity().closeFragment(this) } }
0
Kotlin
0
1
e95c109118934ffa404c3531d14aaa1514b70ac9
371
MovieQuizApp
Apache License 2.0