path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/ashraf/movie/discovery/di/DomainModule.kt
|
ashraf-atef
| 294,040,236
| false
| null |
package com.ashraf.movie.discovery.di
import com.ashraf.movie.discovery.details.domain.GettingMoviesPhotosUseCase
import org.koin.dsl.module
val domainModule = module {
factory { GettingMoviesPhotosUseCase(get()) }
}
| 0
|
Kotlin
|
0
| 0
|
404335d17764b1d69607c7702d61ae7b64ffa900
| 222
|
Movie-App2.0.0
|
MIT License
|
payments-core/src/main/java/com/stripe/android/PaymentIntentResult.kt
|
stripe
| 6,926,049
| false
| null |
package com.stripe.android
import androidx.annotation.RestrictTo
import com.stripe.android.model.PaymentIntent
import kotlinx.parcelize.Parcelize
/**
* A model representing the result of a [PaymentIntent] confirmation via [Stripe.confirmPayment]
* or handling of next actions via [Stripe.handleNextActionForPayment].
*/
@Parcelize
data class PaymentIntentResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // For paymentsheet
constructor(
override val intent: PaymentIntent,
@Outcome private val outcomeFromFlow: Int = 0,
override val failureMessage: String? = null
) : StripeIntentResult<PaymentIntent>(outcomeFromFlow)
| 64
|
Kotlin
|
522
| 935
|
bec4fc5f45b5401a98a310f7ebe5d383693936ea
| 638
|
stripe-android
|
MIT License
|
feature-governance-impl/src/main/java/io/novafoundation/nova/feature_governance_impl/di/GovernanceFeatureModule.kt
|
novasamatech
| 496,649,319
| false
|
{"Kotlin": 5949531, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_governance_impl.di
import dagger.Module
import dagger.Provides
import io.novafoundation.nova.common.address.AddressIconGenerator
import io.novafoundation.nova.common.data.storage.Preferences
import io.novafoundation.nova.common.di.scope.FeatureScope
import io.novafoundation.nova.common.resources.ResourceManager
import io.novafoundation.nova.feature_account_api.domain.account.identity.IdentityProvider
import io.novafoundation.nova.feature_account_api.domain.account.identity.LocalIdentity
import io.novafoundation.nova.feature_account_api.domain.account.identity.OnChainIdentity
import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountRepository
import io.novafoundation.nova.feature_governance_api.data.repository.TreasuryRepository
import io.novafoundation.nova.feature_governance_api.data.source.GovernanceSource
import io.novafoundation.nova.feature_governance_api.data.source.GovernanceSourceRegistry
import io.novafoundation.nova.feature_governance_impl.data.GovernanceSharedState
import io.novafoundation.nova.feature_governance_impl.data.preimage.PreImageSizer
import io.novafoundation.nova.feature_governance_impl.data.preimage.RealPreImageSizer
import io.novafoundation.nova.feature_governance_impl.data.repository.RealTreasuryRepository
import io.novafoundation.nova.feature_governance_impl.data.source.RealGovernanceSourceRegistry
import io.novafoundation.nova.feature_governance_impl.di.modules.GovernanceDAppsModule
import io.novafoundation.nova.feature_governance_impl.di.modules.GovernanceUpdatersModule
import io.novafoundation.nova.feature_governance_impl.di.modules.GovernanceV1
import io.novafoundation.nova.feature_governance_impl.di.modules.GovernanceV1Module
import io.novafoundation.nova.feature_governance_impl.di.modules.GovernanceV2
import io.novafoundation.nova.feature_governance_impl.di.modules.GovernanceV2Module
import io.novafoundation.nova.feature_governance_impl.di.modules.screens.DelegateModule
import io.novafoundation.nova.feature_governance_impl.di.modules.screens.ReferendumDetailsModule
import io.novafoundation.nova.feature_governance_impl.di.modules.screens.ReferendumListModule
import io.novafoundation.nova.feature_governance_impl.di.modules.screens.ReferendumUnlockModule
import io.novafoundation.nova.feature_governance_impl.di.modules.screens.ReferendumVoteModule
import io.novafoundation.nova.feature_governance_impl.di.modules.screens.ReferendumVotersModule
import io.novafoundation.nova.feature_governance_impl.domain.identity.GovernanceIdentityProviderFactory
import io.novafoundation.nova.feature_governance_impl.domain.referendum.common.RealReferendaConstructor
import io.novafoundation.nova.feature_governance_impl.domain.referendum.common.ReferendaConstructor
import io.novafoundation.nova.feature_governance_impl.domain.track.RealTracksUseCase
import io.novafoundation.nova.feature_governance_impl.domain.track.TracksUseCase
import io.novafoundation.nova.feature_governance_impl.domain.track.category.RealTrackCategorizer
import io.novafoundation.nova.feature_governance_impl.domain.track.category.TrackCategorizer
import io.novafoundation.nova.feature_governance_impl.presentation.common.conviction.ConvictionValuesProvider
import io.novafoundation.nova.feature_governance_impl.presentation.common.conviction.RealConvictionValuesProvider
import io.novafoundation.nova.feature_governance_impl.presentation.common.locks.LocksFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.common.locks.RealLocksFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.referenda.common.RealReferendumFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.referenda.common.ReferendumFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.track.RealTrackFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.track.TrackFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.common.voters.RealVotersFormatter
import io.novafoundation.nova.feature_governance_impl.presentation.common.voters.VotersFormatter
import io.novafoundation.nova.feature_wallet_api.domain.AssetUseCase
import io.novafoundation.nova.feature_wallet_api.domain.TokenUseCase
import io.novafoundation.nova.feature_wallet_api.domain.implementations.AssetUseCaseImpl
import io.novafoundation.nova.feature_wallet_api.domain.implementations.SharedStateTokenUseCase
import io.novafoundation.nova.feature_wallet_api.domain.interfaces.TokenRepository
import io.novafoundation.nova.feature_wallet_api.domain.interfaces.WalletRepository
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.assetSelector.AssetSelectorFactory
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.FeeLoaderMixin
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.create
import io.novafoundation.nova.runtime.di.REMOTE_STORAGE_SOURCE
import io.novafoundation.nova.runtime.multiNetwork.ChainRegistry
import io.novafoundation.nova.runtime.repository.ChainStateRepository
import io.novafoundation.nova.runtime.storage.source.StorageDataSource
import javax.inject.Named
@Module(
includes = [
GovernanceV2Module::class,
GovernanceV1Module::class,
GovernanceUpdatersModule::class,
ReferendumDetailsModule::class,
ReferendumListModule::class,
ReferendumVotersModule::class,
ReferendumVoteModule::class,
ReferendumUnlockModule::class,
DelegateModule::class,
GovernanceDAppsModule::class
]
)
class GovernanceFeatureModule {
@Provides
@FeatureScope
fun provideAssetSharedState(
chainRegistry: ChainRegistry,
preferences: Preferences,
) = GovernanceSharedState(chainRegistry, preferences)
@Provides
@FeatureScope
fun provideTokenUseCase(
tokenRepository: TokenRepository,
sharedState: GovernanceSharedState,
): TokenUseCase = SharedStateTokenUseCase(tokenRepository, sharedState)
@Provides
@FeatureScope
fun provideAssetUseCase(
walletRepository: WalletRepository,
accountRepository: AccountRepository,
assetSharedState: GovernanceSharedState,
): AssetUseCase = AssetUseCaseImpl(
walletRepository = walletRepository,
accountRepository = accountRepository,
sharedState = assetSharedState,
)
@Provides
@FeatureScope
fun provideAssetSelectorMixinFactory(
assetUseCase: AssetUseCase,
assetSharedState: GovernanceSharedState,
resourceManager: ResourceManager
) = AssetSelectorFactory(
assetUseCase = assetUseCase,
singleAssetSharedState = assetSharedState,
resourceManager = resourceManager
)
@Provides
@FeatureScope
fun provideFeeLoaderMixin(
feeLoaderMixinFactory: FeeLoaderMixin.Factory,
tokenUseCase: TokenUseCase,
): FeeLoaderMixin.Presentation = feeLoaderMixinFactory.create(tokenUseCase)
@Provides
@FeatureScope
fun provideGovernanceSourceRegistry(
@GovernanceV2 governanceV2Source: GovernanceSource,
@GovernanceV1 governanceV1Source: GovernanceSource,
): GovernanceSourceRegistry = RealGovernanceSourceRegistry(
governanceV2Source = governanceV2Source,
governanceV1Source = governanceV1Source
)
@Provides
@FeatureScope
fun provideTreasuryRepository(
@Named(REMOTE_STORAGE_SOURCE) storageSource: StorageDataSource
): TreasuryRepository = RealTreasuryRepository(storageSource)
@Provides
@FeatureScope
fun provideReferendumConstructor(
governanceSourceRegistry: GovernanceSourceRegistry,
chainStateRepository: ChainStateRepository
): ReferendaConstructor = RealReferendaConstructor(governanceSourceRegistry, chainStateRepository)
@Provides
@FeatureScope
fun provideGovernanceIdentityProviderFactory(
@LocalIdentity localProvider: IdentityProvider,
@OnChainIdentity onChainProvider: IdentityProvider
): GovernanceIdentityProviderFactory = GovernanceIdentityProviderFactory(
localProvider = localProvider,
onChainProvider = onChainProvider
)
@Provides
@FeatureScope
fun providePreImageSizer(): PreImageSizer = RealPreImageSizer()
@Provides
@FeatureScope
fun provideTrackCategorizer(): TrackCategorizer = RealTrackCategorizer()
@Provides
@FeatureScope
fun provideTracksFormatter(
trackCategorizer: TrackCategorizer,
resourceManager: ResourceManager
): TrackFormatter = RealTrackFormatter(trackCategorizer, resourceManager)
@Provides
@FeatureScope
fun provideReferendumFormatter(
resourceManager: ResourceManager,
trackFormatter: TrackFormatter,
): ReferendumFormatter = RealReferendumFormatter(resourceManager, trackFormatter)
@Provides
@FeatureScope
fun provideVotersFormatter(
resourceManager: ResourceManager,
addressIconGenerator: AddressIconGenerator
): VotersFormatter = RealVotersFormatter(addressIconGenerator, resourceManager)
@Provides
@FeatureScope
fun provideLocksFormatter(resourceManager: ResourceManager): LocksFormatter = RealLocksFormatter(resourceManager)
@Provides
@FeatureScope
fun provideConvictionValuesProvider(): ConvictionValuesProvider = RealConvictionValuesProvider()
@Provides
@FeatureScope
fun provideTracksUseCase(
governanceSharedState: GovernanceSharedState,
governanceSourceRegistry: GovernanceSourceRegistry,
): TracksUseCase = RealTracksUseCase(governanceSharedState, governanceSourceRegistry)
}
| 5
|
Kotlin
|
9
| 28
|
fcd118ab5cbedded709ec062ae5d4bc890aaf96d
| 9,722
|
nova-android-app
|
Apache License 2.0
|
app/src/main/java/tech/salroid/filmy/fragment/CrewFragment.kt
|
salRoid
| 64,316,425
| false
| null |
package tech.salroid.filmy.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import tech.salroid.filmy.R
import tech.salroid.filmy.activities.CharacterDetailsActivity
import tech.salroid.filmy.activities.FullCrewActivity
import tech.salroid.filmy.adapters.CrewAdapter
import tech.salroid.filmy.databinding.CrewFragmentBinding
import tech.salroid.filmy.parser.MovieDetailsActivityParseWork
class CrewFragment : Fragment() {
private var jsonCrew: String? = null
private var movieId: String? = null
private var movieTitle: String? = null
private var _binding: CrewFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = CrewFragmentBinding.inflate(inflater, container, false)
val view = binding.root
binding.crewRecycler.layoutManager = LinearLayoutManager(activity)
binding.crewRecycler.isNestedScrollingEnabled = false
binding.crewRecycler.visibility = View.INVISIBLE
binding.crewMore.setOnClickListener {
if (jsonCrew != null && movieTitle != null) {
val intent = Intent(activity, FullCrewActivity::class.java)
intent.putExtra("crew_json", jsonCrew)
intent.putExtra("toolbar_title", movieTitle)
startActivity(intent)
}
}
return view
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
movieId = arguments?.getString("movie_id")
movieTitle = arguments?.getString("movie_title")
}
fun parseCrewOutput(crewResult: String) {
val parser = MovieDetailsActivityParseWork(crewResult)
val crewList = parser.parseCrewMembers()
jsonCrew = crewResult
binding.crewRecycler.adapter = CrewAdapter(crewList, true) { member, _, view ->
val intent = Intent(activity, CharacterDetailsActivity::class.java)
intent.putExtra("id", member.crewMemberId)
val p1 = Pair.create(view.findViewById<View>(R.id.crew_poster), "profile")
val p2 = Pair.create(view.findViewById<View>(R.id.crew_name), "name")
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity!!, p1, p2)
startActivity(intent, options.toBundle())
}
when {
crewList.size > 4 -> {
binding.crewMore.visibility = View.VISIBLE
}
crewList.isEmpty() -> {
binding.crewMore.visibility = View.INVISIBLE
binding.cardHolder.visibility = View.INVISIBLE
}
else -> {
binding.crewMore.visibility = View.INVISIBLE
}
}
binding.breathingProgressFragment.visibility = View.GONE
binding.crewRecycler.visibility = View.VISIBLE
binding.detailFragmentViewsLayout.minimumHeight = 0
}
companion object {
fun newInstance(movieId: String?, movieTitle: String?): CrewFragment {
val fragment = CrewFragment()
val args = Bundle()
args.putString("movie_id", movieId)
args.putString("movie_title", movieTitle)
fragment.arguments = args
return fragment
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
185
| 710
|
11935a87f16f546b15b6e98f7ec3f2cbdf037b5f
| 3,769
|
Filmy
|
Apache License 2.0
|
SuperSpEditText/src/main/java/com/xxf/view/mentionedittext/span/DataSpan.kt
|
NBXXF
| 333,649,364
| false
| null |
package com.xxf.view.mentionedittext.span
import java.io.Serializable
/**
* @Author: XGod <EMAIL> 17611639080
* Date: 1/28/21 12:58 PM
* Description:仅用来标记数据,获取span的时候方便处理
*/
interface DataSpan : Serializable
| 0
|
Kotlin
|
0
| 0
|
98d6bb6e6770950cc61fcaef5dc76303d50baa28
| 215
|
SpEditTool
|
MIT License
|
app/src/main/java/com/rajchenbergstudios/hoygenda/ui/core/pastday/DayDetailsViewModel.kt
|
Davidhk2891
| 524,378,818
| false
| null |
package com.rajchenbergstudios.hoygenda.ui.core.pastday
import androidx.lifecycle.*
import com.rajchenbergstudios.hoygenda.data.day.Day
import com.rajchenbergstudios.hoygenda.data.prefs.SortOrder
import com.rajchenbergstudios.hoygenda.data.today.journalentry.JournalEntry
import com.rajchenbergstudios.hoygenda.data.today.task.Task
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
const val TAG = "DayDetailsViewModel"
@FlowPreview
@ExperimentalCoroutinesApi
@HiltViewModel
class DayDetailsViewModel @Inject constructor(
stateHandle: SavedStateHandle
) : ViewModel(){
// DayDetailsFragment operations ---
// This is the reason why this is a shared viewModel.
// The data comes from this day value below.
// Past from the selected day in Days list.
val day = stateHandle.get<Day>("day")
val dayWeekDay = stateHandle["weekDay"] ?: day?.dayOfWeek ?: "null"
val dayMonth = stateHandle["month"] ?: day?.month ?: "null"
val dayYear = stateHandle["year"] ?: day?.year ?: "null"
val dayMonthDay = stateHandle["monthDay"] ?: day?.dayOfMonth ?: "null"
var formattedDate: String = ""
init {
formattedDate = "${formatMonth(dayMonth)} $dayMonthDay, $dayYear"
}
private fun formatMonth(month: String): String {
val dayMonthLowercase = month.lowercase()
val dayMonthFirstLetterCap = dayMonthLowercase.replaceFirst(
dayMonthLowercase.first().toString()
,dayMonthLowercase.first().uppercase()
)
return dayMonthFirstLetterCap.substring(0, 3)
}
// PDTasksListFragment/PDJEntriesListFragment operations ---
// Search query flow for tasks
val pastDaySearchQuery = MutableStateFlow("")
// Search query flow for journal entries
val pastDaySearchQueryJEntries = MutableStateFlow("")
// TODO /////////////////////////////////////////////////////////////////
// Sort order flow for tasks
val pastDaySortOrderQuery = MutableStateFlow(SortOrder.BY_TIME)
// Sort order flow for journal entries
val pastDaySortOrderQueryJEntries = MutableStateFlow(SortOrder.BY_TIME)
// Data source tasks
val tasksList: List<Task>? = day?.listOfTasks
// Data source journal entries
val jEntriesList: List<JournalEntry>? = day?.listOfJEntries
// Converted tasks data source to Flow
private val tasksListFlow: Flow<List<Task>>? = tasksList?.let { tasksList -> flowOf(tasksList) }
// Converted journal entries data source to Flow
private val jEntriesListFlow: Flow<List<JournalEntry>>? = jEntriesList?.let { jEntriesList -> flowOf(jEntriesList) }
// TASKS ---
// Combined flow from pastDaySearchQuery and pastDaySortOrderQuery
// private val combinedFlow = tasksListFlow?.flatMapMerge { tasks ->
// pastDaySearchQuery.flatMapLatest { query ->
// pastDaySortOrderQuery.flatMapLatest { sortBy ->
// val filteredTasks = tasks.filter { task ->
// task.title.contains(query, ignoreCase = true)
// }
// flowOf(
// when (sortBy) {
// SortOrder.BY_TIME -> filteredTasks.sortedBy { it.createdTimeFormat }
// SortOrder.BY_NAME -> filteredTasks.sortedBy { it.title }
// }
// )
// }
// }
// }
private val filteredTasksFlow = tasksListFlow?.flatMapMerge { tasks ->
pastDaySearchQuery.flatMapLatest { query ->
flowOf(tasks.filter { task ->
task.title.contains(query, ignoreCase = true)
})
// Nothing can be written here
}
}
// Expose the flow as LiveData to the Fragment so it can be observed
val tasks = filteredTasksFlow?.asLiveData()
// ---------
// JOURNAL ENTRIES-
// Apply searchQuery to jEntriesListFlow and filter in the result that match the query
private val filteredJEntriesFlow = jEntriesListFlow?.flatMapMerge { jEntries ->
pastDaySearchQueryJEntries.flatMapLatest { query ->
flowOf(jEntries.filter { jEntry ->
jEntry.content.contains(query, ignoreCase = true)
})
// Nothing can be written here
}
}
// Apply sortOrder to filteredJEntriesFlow and sort the list bt the requested sorting
// private val sortedJEntriesFlow = filteredJEntriesFlow?.flatMapLatest { jEntries ->
// pastDaySortOrderQueryJEntries.map { sortBy ->
// when (sortBy) {
// SortOrder.BY_TIME -> jEntries.sortedBy { it.createdTimeFormat }
// SortOrder.BY_NAME -> jEntries.sortedBy { it.content }
// }
// }
// }
// Expose the flow as LiveData to the Fragment so it can be observed
val jEntries = filteredJEntriesFlow?.asLiveData()
// ---------
// ----------------------------------------------------------------------
// Past day Task & JEntries Channels
private val pastDayTaskEventChannel = Channel<PastDayTaskEvent>()
private val pastDayJEntryEventChannel = Channel<PastDayJEntryEvent>()
// Past day Task & JEntries events
val pastDayTaskEvent = pastDayTaskEventChannel.receiveAsFlow()
val pastDayJEntryEvent = pastDayJEntryEventChannel.receiveAsFlow()
// Past day Task & JEntries functions with Coroutines
fun onPastDayTaskClick(task: Task, date: String) = viewModelScope.launch {
pastDayTaskEventChannel.send(PastDayTaskEvent.NavigateToTaskDetailsScreen(task, date))
}
fun onPastDayJEntryClick(journalEntry: JournalEntry, date: String) = viewModelScope.launch {
pastDayJEntryEventChannel.send(
PastDayJEntryEvent.NavigateToJEntryDetailsScreen(
journalEntry,
date
)
)
}
// Past day Task & JEntry Events wrapper class
sealed class PastDayTaskEvent {
data class NavigateToTaskDetailsScreen(val task: Task, val date: String) : PastDayTaskEvent()
}
sealed class PastDayJEntryEvent {
data class NavigateToJEntryDetailsScreen(val journalEntry: JournalEntry, val date: String) : PastDayJEntryEvent()
}
}
| 0
|
Kotlin
|
0
| 0
|
1154bbfb5865cb48a87497582b3149573c17efae
| 6,412
|
Rajchenberg_Studios-Hoytask
|
Apache License 2.0
|
src/main/kotlin/com/github/subtixx/omnicraft/utils/NumberUtil.kt
|
Subtixx
| 850,089,269
| false
|
{"Kotlin": 217619}
|
@file:Suppress("unused")
package com.github.subtixx.omnicraft.utils
import java.util.*
import kotlin.math.ln
import kotlin.math.pow
object NumberUtil {
/**
* Format number to K, M, G, T, P, E, Z, Y
*
* @param number
* @return
*/
@JvmStatic
fun formatNumber(number: Int): String {
if (number < 1000) return number.toString()
var num = number.toDouble()
var index = 0
for (i in 0..7) {
if (num < 1000) break
num /= 1000
index = i + 1
}
return String.format(Locale.ENGLISH, "%.2f%s", num, "KMGTPEZY"[index])
}
/**
* Returns a human readable string of the bytes passed in e.g. 1024 kB
*
* @param bytes amount of bytes
* @param si true if using SI units
* @return human readable string
*/
@JvmStatic
fun humanReadableByteCount(bytes: Long, si: Boolean = false): String {
val units = if (si) 1000 else 1024
if (bytes < units) return "$bytes B"
val exp = (ln(bytes.toDouble()) / ln(units.toDouble())).toInt()
val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i"
return String.format("%.1f %sB", bytes / units.toDouble().pow(exp.toDouble()), pre)
}
/**
* Returns a human readable string of the time passed in seconds e.g. 2:00:00
*
* @param time
* @return
*/
@JvmStatic
fun humanReadableTime(time: Long): String {
val hours = time / 3600
val minutes = (time - hours * 3600) / 60
val seconds = (time - hours * 3600 - minutes * 60)
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
/**
* Returns a human readable string of the time passed in seconds e.g. 2 hours ago
*
* @param time the time in seconds
* @return a human readable string
*/
@JvmStatic
fun humanReadableAgo(time: Long): String {
val hours = time / 3600
val minutes = (time - hours * 3600) / 60
val days = hours / 24
return if (days > 0) String.format("%d days ago", days)
else if (hours > 0) String.format("%d hours ago", hours)
else if (minutes > 0) String.format("%d minutes ago", minutes)
else String.format("%d seconds ago", time)
}
}
| 33
|
Kotlin
|
0
| 0
|
5a9602bc59afe1a2bf9e3f09c8418f99e5693316
| 2,318
|
OmniCraft
|
MIT License
|
defensor-gradle-plugin/src/main/java/com/panda912/defensor/plugin/internal/processor/DirectoryProcessor.kt
|
porum
| 402,665,073
| false
| null |
package com.panda912.defensor.plugin.internal.processor
import com.android.build.api.transform.Status
import com.panda912.defensor.plugin.TransformContext
import com.panda912.defensor.plugin.utils.FileUtils
import com.panda912.defensor.plugin.utils.isDefensorClass
import java.io.File
/**
* Created by panda on 2021/9/14 17:47
*/
class DirectoryProcessor : QualifiedContentProcessor {
override fun process(context: TransformContext, injector: BytecodeInjector) {
with(context) {
getAllDirs().forEach { directoryInput ->
val inputDir = directoryInput.file
val outputDir = getOutputFile(directoryInput)
if (isIncremental()) {
getChangedFiles()
.filter { it.key.startsWith(inputDir) }
.forEach { (changedFile, status) ->
val outputFile = FileUtils.getOutputFile(inputDir, changedFile, outputDir)
if (status == Status.REMOVED) {
FileUtils.deleteIfExists(outputFile)
} else if (status == Status.ADDED || status == Status.CHANGED) {
doTransform(context, injector, changedFile, outputFile)
}
}
} else {
outputDir.deleteRecursively()
inputDir.walkTopDown().toList().parallelStream().filter { it.isFile }.forEach {
val outputFile = FileUtils.getOutputFile(inputDir, it, outputDir)
doTransform(context, injector, it, outputFile)
}
}
}
}
}
private fun doTransform(
context: TransformContext,
injector: BytecodeInjector,
inputFile: File,
outputFile: File
) {
if (inputFile.extension == "class" && !inputFile.invariantSeparatorsPath.isDefensorClass()) {
val bytes = inputFile.readBytes()
val preCheckResult = injector.preCheck(context, bytes)
if (preCheckResult.ignored) {
inputFile.copyTo(outputFile, true)
} else {
FileUtils.ensureParentDirsCreated(outputFile)
outputFile.writeBytes(
injector.inject(
inputFile.absolutePath,
preCheckResult.className,
bytes
)
)
}
} else {
inputFile.copyTo(outputFile, true)
}
}
}
| 0
| null |
1
| 2
|
58a60e0ee68d7d323c358720e90b6b9f66987650
| 2,218
|
Defensor
|
Apache License 2.0
|
feature-staking-impl/src/main/java/jp/co/soramitsu/feature_staking_impl/presentation/staking/StakingViewModel.kt
|
kingofthebongo2008
| 346,603,452
| true
|
{"Kotlin": 1066068}
|
package jp.co.soramitsu.feature_staking_impl.presentation.staking
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import jp.co.soramitsu.common.account.AddressIconGenerator
import jp.co.soramitsu.common.account.AddressModel
import jp.co.soramitsu.common.base.BaseViewModel
import jp.co.soramitsu.common.resources.ResourceManager
import jp.co.soramitsu.common.utils.formatAsCurrency
import jp.co.soramitsu.feature_staking_api.domain.model.StakingAccount
import jp.co.soramitsu.feature_staking_impl.domain.StakingInteractor
import jp.co.soramitsu.feature_staking_impl.domain.rewards.RewardCalculator
import jp.co.soramitsu.feature_staking_impl.domain.rewards.RewardCalculatorFactory
import jp.co.soramitsu.feature_staking_impl.presentation.StakingRouter
import jp.co.soramitsu.feature_staking_impl.presentation.common.StakingSharedState
import jp.co.soramitsu.feature_staking_impl.presentation.common.mapAssetToAssetModel
import jp.co.soramitsu.feature_staking_impl.presentation.staking.model.RewardEstimation
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.launch
private const val CURRENT_ICON_SIZE = 40
private const val PERIOD_MONTH = 30
private const val PERIOD_YEAR = 365
class ReturnsModel(
val monthly: RewardEstimation,
val yearly: RewardEstimation
)
class StakingViewModel(
private val router: StakingRouter,
private val interactor: StakingInteractor,
private val addressIconGenerator: AddressIconGenerator,
private val rewardCalculatorFactory: RewardCalculatorFactory,
private val resourceManager: ResourceManager,
private val stakingSharedState: StakingSharedState
) : BaseViewModel() {
val currentAddressModelLiveData = currentAddressModelFlow().asLiveData()
private val currentAsset = interactor.currentAssetFlow()
val asset = currentAsset.map { mapAssetToAssetModel(it, resourceManager) }.asLiveData()
val enteredAmountFlow = MutableStateFlow(stakingSharedState.amount.toString())
private val parsedAmountFlow = enteredAmountFlow.mapNotNull { it.toBigDecimalOrNull() }
val amountFiat = parsedAmountFlow.combine(currentAsset) { amount, asset -> asset.token.fiatAmount(amount)?.formatAsCurrency() }
.filterNotNull()
.asLiveData()
val returns: LiveData<ReturnsModel> = currentAsset.combine(parsedAmountFlow) { asset, amount ->
val monthly = rewardCalculator().calculateReturns(amount, PERIOD_MONTH, true)
val yearly = rewardCalculator().calculateReturns(amount, PERIOD_YEAR, true)
val monthlyEstimation = RewardEstimation(monthly.gainAmount, monthly.gainPercentage, asset.token)
val yearlyEstimation = RewardEstimation(yearly.gainAmount, yearly.gainPercentage, asset.token)
ReturnsModel(monthlyEstimation, yearlyEstimation)
}.asLiveData()
private val rewardCalculator = viewModelScope.async { rewardCalculatorFactory.create() }
fun onAmountChanged(text: String) {
viewModelScope.launch {
enteredAmountFlow.emit(text)
}
}
fun nextClicked() {
launch {
stakingSharedState.amount = parsedAmountFlow.first()
router.openSetupStaking()
}
}
private fun currentAddressModelFlow(): Flow<AddressModel> {
return interactor.selectedAccountFlow()
.map { generateAddressModel(it, CURRENT_ICON_SIZE) }
}
private suspend fun generateAddressModel(account: StakingAccount, sizeInDp: Int): AddressModel {
return addressIconGenerator.createAddressModel(account.address, sizeInDp, account.name)
}
private suspend fun rewardCalculator(): RewardCalculator {
return rewardCalculator.await()
}
}
| 0
| null |
0
| 0
|
fbbe4a87199a2ff6a1590fc22f8f67972aa18c2f
| 3,988
|
fearless-Android
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/ui/Models.kt
|
natieklopper
| 342,986,377
| false
| null |
package com.example.androiddevchallenge.ui
abstract class Models(
var isLoading: Boolean = true
)
data class PetDetailsModel(
val pets: List<String> = arrayListOf(),
var pet: String = "Start"
) : Models()
| 0
|
Kotlin
|
0
| 0
|
74296e3f7fc5a73699a85d69e348b38c140551d6
| 219
|
petfinder
|
Apache License 2.0
|
app/src/main/java/com/trainerapp/enums/ProfilePicture.kt
|
samuolis
| 156,589,399
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 56, "Kotlin": 69}
|
package com.trainerapp.enums
import com.trainerapp.R
enum class ProfilePicture(drawableId: Int) {
man(R.drawable.men),
girl(R.drawable.girl);
val drawableId :Int = drawableId
}
| 1
| null |
1
| 1
|
dee7f5c23993d2142a1155068667af734023fce3
| 193
|
Training-Buddy
|
Apache License 2.0
|
src/main/kotlin/io/github/llh4github/kinoapi/service/BaseService.kt
|
llh4github
| 643,129,201
| false
| null |
package io.github.llh4github.kinoapi.service
import io.github.llh4github.kinoapi.model.BaseModel
import io.github.llh4github.kinoapi.repository.BaseRepository
import org.babyfish.jimmer.sql.fetcher.Fetcher
/**
*
*
* Created At 2023/8/11 16:43
* @author llh
*/
interface BaseService<E> : DataExistenceChecker<E> {
fun fetchById(id: Int, fetcher: Fetcher<E>? = null): E?
}
abstract class BaseServiceImpl<E : BaseModel>(
private val repository: BaseRepository<E>
) : BaseService<E> {
override fun fetchById(id: Int, fetcher: Fetcher<E>?): E? {
return repository.findNullable(id, fetcher)
}
override fun findById(id: Int): E? {
return repository.findNullable(id)
}
override fun idsInDb(idInput: List<Int>): List<Int> {
// 加入缓存后再看看这里的查询效率。
return repository.findByIds(idInput)
.map { it.id }
.distinct()
.toList()
}
}
| 0
|
Kotlin
|
0
| 0
|
c81d535f0a01bafbab47c97b3a159d81addd9fe4
| 924
|
kino-api
|
MIT License
|
app/src/main/java/org/p2p/wallet/common/mvp/BaseMvpActivity.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.wallet.common.mvp
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import org.p2p.core.common.TextContainer
import org.p2p.uikit.natives.showSnackbarShort
import org.p2p.uikit.utils.toast
import org.p2p.wallet.R
import org.p2p.wallet.utils.getErrorMessage
import org.p2p.wallet.utils.showErrorDialog
import org.p2p.wallet.utils.snackbar
abstract class BaseMvpActivity<V : MvpView, P : MvpPresenter<V>> : AppCompatActivity(), MvpView {
abstract val presenter: P
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@Suppress("UNCHECKED_CAST")
presenter.attach(this as V)
}
@CallSuper
override fun onDestroy() {
super.onDestroy()
presenter.detach()
}
override fun showErrorMessage(messageResId: Int) {
showErrorDialog(messageRes = messageResId)
}
override fun showErrorMessage(e: Throwable?) {
showErrorDialog(e)
}
override fun showErrorSnackBar(messageResId: Int, actionResId: Int?, block: (() -> Unit)?) {
snackbar {
it.setMessage(getString(messageResId))
.setIcon(R.drawable.ic_close_red)
.setAction(actionResId, block)
}
}
override fun showErrorSnackBar(message: String, actionResId: Int?, block: (() -> Unit)?) {
snackbar {
it.setMessage(message)
.setIcon(R.drawable.ic_close_red)
.setAction(actionResId, block)
}
}
override fun showSuccessSnackBar(messageResId: Int, actionResId: Int?, block: (() -> Unit)?) {
snackbar {
it.setMessage(getString(messageResId))
.setIcon(R.drawable.ic_done)
.setAction(actionResId, block)
}
}
override fun showErrorSnackBar(e: Throwable, actionResId: Int?, block: (() -> Unit)?) {
snackbar {
it.setMessage(e.getErrorMessage { res -> getString(res) })
.setIcon(R.drawable.ic_close_red)
.setAction(actionResId, block)
}
}
override fun showSuccessSnackBar(message: String, actionResId: Int?, block: (() -> Unit)?) {
snackbar {
it.setMessage(message)
.setIcon(R.drawable.ic_done)
.setAction(actionResId, block)
}
}
override fun showInfoSnackBar(message: String, iconResId: Int?, actionResId: Int?, actionBlock: (() -> Unit)?) {
snackbar {
it.setMessage(message)
.setAction(actionResId, actionBlock)
iconResId?.let { icon ->
it.setIcon(icon)
}
}
}
override fun showToast(message: TextContainer) {
toast(message.getString(this))
}
override fun showUiKitSnackBar(
message: String?,
messageResId: Int?,
onDismissed: () -> Unit,
actionButtonResId: Int?,
actionBlock: ((Snackbar) -> Unit)?
) {
require(message != null || messageResId != null) {
"Snackbar text must be set from `message` or `messageResId` params"
}
val snackbarText: String = message ?: messageResId?.let(::getString)!!
val root = findViewById<View>(android.R.id.content) as ViewGroup
if (actionButtonResId != null && actionBlock != null) {
root.showSnackbarShort(
snackbarText = snackbarText,
actionButtonText = getString(actionButtonResId),
actionButtonListener = actionBlock
)
} else {
root.showSnackbarShort(
snackbarText = snackbarText,
onDismissed = onDismissed
)
}
}
}
| 9
|
Kotlin
|
14
| 23
|
2badf683d824c57654b12ea0c023f96e1a5d0c19
| 3,909
|
key-app-android
|
MIT License
|
app/src/main/java/xhh/example/com/fristproject/mydrawable/InsetActivity.kt
|
xhh4215
| 135,407,503
| false
|
{"Kotlin": 10028}
|
package xhh.example.com.fristproject.mydrawable
import android.graphics.drawable.ClipDrawable
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_clip.*
import xhh.example.com.fristproject.R
class InsetActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scale)
// button_clip.setOnClickListener{
// val drawable = image_clip.background as ClipDrawable
//// level 的变大会使裁剪量减少
// drawable.setLevel(drawable.level +7000)
// }
}
}
| 0
|
Kotlin
|
0
| 0
|
41691bdb1c7fb4ec7fdb1bcb6bc25644c54ace7e
| 673
|
FristProject
|
Apache License 2.0
|
android/app/src/main/kotlin/com/example/mobile_app_midterm/MainActivity.kt
|
Black-Garlic
| 423,379,886
| false
|
{"Dart": 97064, "C++": 20482, "CMake": 8001, "HTML": 3719, "C": 734, "Swift": 404, "Kotlin": 266, "Objective-C": 38}
|
package com.example.mobile_app_midterm
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 0
|
89b2599b31605f306a4a2f1714868bb9d8c2e485
| 135
|
Mobile-App-Dev-Finalterm
|
Apache License 2.0
|
src/main/kotlin/com/projectcitybuild/platforms/spigot/commands/BanCommand.kt
|
projectcitybuild
| 42,997,941
| false
| null |
package com.projectcitybuild.platforms.spigot.commands
import com.projectcitybuild.core.contracts.Commandable
import com.projectcitybuild.modules.bans.CreateBanAction
import com.projectcitybuild.core.network.APIRequestFactory
import com.projectcitybuild.core.entities.CommandResult
import com.projectcitybuild.core.extensions.joinWithWhitespaces
import com.projectcitybuild.core.entities.CommandInput
import com.projectcitybuild.core.entities.Failure
import com.projectcitybuild.core.entities.Success
import com.projectcitybuild.core.network.APIClient
import com.projectcitybuild.platforms.spigot.environment.send
import com.projectcitybuild.platforms.spigot.extensions.getOfflinePlayer
import org.bukkit.ChatColor
import org.bukkit.entity.Player
class BanCommand(
private val apiRequestFactory: APIRequestFactory,
private val apiClient: APIClient
): Commandable {
override val label: String = "ban"
override val permission: String = "pcbridge.ban.ban"
override suspend fun execute(input: CommandInput): CommandResult {
if (!input.hasArguments) return CommandResult.INVALID_INPUT
val staffPlayer = if (input.isConsole) null else input.sender as Player
val reason = input.args.joinWithWhitespaces(1 until input.args.size)
val targetPlayerName = input.args.first()
val uuid = input.sender.server.getOfflinePlayer(
name = targetPlayerName,
apiRequestFactory = apiRequestFactory,
apiClient = apiClient
)
if (uuid == null) {
input.sender.sendMessage("Error: Failed to retrieve UUID of given player")
return CommandResult.EXECUTED
}
val action = CreateBanAction(apiRequestFactory, apiClient)
val result = action.execute(
playerId = uuid,
playerName = targetPlayerName,
staffId = staffPlayer?.uniqueId,
reason = reason
)
when (result) {
is Failure -> {
input.sender.send().error(
when (result.reason) {
is CreateBanAction.FailReason.HTTPError -> "Bad response received from the ban server. Please contact an admin"
is CreateBanAction.FailReason.NetworkError -> "Failed to contact auth server. Please contact an admin"
is CreateBanAction.FailReason.PlayerAlreadyBanned -> "$targetPlayerName is already banned"
}
)
}
is Success -> {
input.sender.server.broadcast(
"${ChatColor.GRAY}${input.args.first()} has been banned by ${input.sender.name}: ${reason?.isNotEmpty() ?: "No reason given"}",
"*"
)
val player = input.sender.server.onlinePlayers.firstOrNull { player ->
player.name.lowercase() == targetPlayerName.lowercase()
}
player?.kickPlayer("You have been banned")
}
}
return CommandResult.EXECUTED
}
}
| 3
|
Kotlin
|
0
| 1
|
1244cdb6ebb465f7fe6f3c6ee40339d8e39ae8fc
| 3,092
|
PCBridge
|
MIT License
|
modules/feature/app_settings/src/main/kotlin/kekmech/ru/feature_app_settings/screens/main/elm/AppSettingsStoreFactory.kt
|
tonykolomeytsev
| 203,239,594
| false
| null |
package kekmech.ru.feature_app_settings.screens.main.elm
import kekmech.ru.common_feature_toggles.FeatureToggles
import vivid.money.elmslie.coroutines.ElmStoreCompat
internal class AppSettingsFeatureFactory(
private val actor: AppSettingsActor,
private val featureToggles: FeatureToggles,
) {
fun create() =
ElmStoreCompat(
initialState = AppSettingsState(
isFeatureToggleSnowFlakesEnabled = featureToggles.isSnowFlakesEnabled,
),
reducer = AppSettingsReducer(),
actor = actor,
startEvent = AppSettingsEvent.Ui.Init,
)
}
| 20
| null |
4
| 27
|
51d12bcb00d8e722ce003c99408f847b2638665d
| 628
|
mpeiapp
|
MIT License
|
kvision-modules/kvision-material/src/jsMain/kotlin/io/kvision/material/menu/MdMenuItem.kt
|
rjaros
| 120,835,750
| false
|
{"Kotlin": 3524783, "CSS": 25183, "JavaScript": 16390, "HTML": 2425}
|
/*
* Copyright (c) 2017-present <NAME>
* Copyright (c) 2024 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.kvision.material.menu
import io.kvision.material.ExperimentalMaterialApi
import io.kvision.material.slot.HasHeadlineSlot
import io.kvision.material.slot.HasLeadingSlot
import io.kvision.material.slot.HasSupportingTextSlot
import io.kvision.material.slot.HasTrailingSlot
import io.kvision.material.util.addBool
import io.kvision.material.widget.LinkTarget
import io.kvision.material.widget.MdItemWidget
import io.kvision.material.widget.Slot
import io.kvision.core.AttributeSetBuilder
import io.kvision.core.Component
import io.kvision.snabbdom.VNode
enum class MenuItemType(internal val value: String) {
MenuItem("menuitem"),
Option("option"),
Button("button"),
Link("link")
}
/**
* Menu items are element that belongs to a menu.
*
* @author <NAME> <<EMAIL>>
*/
@ExperimentalMaterialApi
open class MdMenuItem(
disabled: Boolean = false,
type: MenuItemType = MenuItemType.MenuItem,
href: String? = null,
target: LinkTarget? = null,
keepOpen: Boolean = false,
selected: Boolean = false,
typeaheadText: String? = null,
className: String? = null,
init: (@MaterialMenuDsl MdMenuItem.() -> Unit)? = null
) : MdItemWidget(
tag = "md-menu-item",
className = className
), HasHeadlineSlot,
HasLeadingSlot,
HasSupportingTextSlot,
HasTrailingSlot {
/**
* Disables the item and makes it non-selectable and non-interactive.
*/
var disabled by refreshOnUpdate(disabled)
/**
* Sets the behavior and role of the menu item.
*/
var type by refreshOnUpdate(type)
/**
* The URL that the item points to.
*/
var href by refreshOnUpdate(href)
/**
* Where to display the linked href URL for a link button.
* Common options include _blank to open in a new tab.
*/
var target by refreshOnUpdate(target)
/**
* Keeps the menu open if clicked or keyboard selected.
*/
var keepOpen by refreshOnUpdate(keepOpen)
/**
* Sets the item in the selected visual state when a submenu is opened.
*/
var selected by syncOnUpdate(selected)
/**
* The text that is selectable via typeahead. If not set, defaults to the innerText of the item
* slotted into the `headline` slot.
*/
var typeaheadText by syncOnUpdate(typeaheadText)
init {
init?.let { this.it() }
}
///////////////////////////////////////////////////////////////////////////
// Lifecycle
///////////////////////////////////////////////////////////////////////////
override fun afterCreate(node: VNode) {
super.afterCreate(node)
typeaheadText?.let { getElementD().typeaheadText = translate(it) }
}
///////////////////////////////////////////////////////////////////////////
// Attributes
///////////////////////////////////////////////////////////////////////////
override fun buildAttributeSet(attributeSetBuilder: AttributeSetBuilder) {
super.buildAttributeSet(attributeSetBuilder)
attributeSetBuilder.add("type", type.value)
if (disabled) {
attributeSetBuilder.addBool("disabled")
}
href?.let {
attributeSetBuilder.add("href", it)
}
target?.let {
attributeSetBuilder.add("target", it.value)
}
if (keepOpen) {
attributeSetBuilder.addBool("keep-open")
}
if (selected) {
attributeSetBuilder.addBool("selected")
}
}
///////////////////////////////////////////////////////////////////////////
// Slots
///////////////////////////////////////////////////////////////////////////
override fun headline(component: Component?) {
Slot.Headline(component)
}
override fun leading(component: Component?) {
Slot.Leading(component)
}
override fun supportingText(component: Component?) {
Slot.SupportingText(component)
}
override fun trailing(component: Component?) {
Slot.Trailing(component)
}
}
@ExperimentalMaterialApi
fun MdMenu.menuItem(
disabled: Boolean = false,
type: MenuItemType = MenuItemType.MenuItem,
href: String? = null,
target: LinkTarget? = null,
keepOpen: Boolean = false,
selected: Boolean = false,
typeaheadText: String? = null,
className: String? = null,
init: (@MaterialMenuDsl MdMenuItem.() -> Unit)? = null
) = MdMenuItem(
disabled = disabled,
type = type,
href = href,
target = target,
keepOpen = keepOpen,
selected = selected,
typeaheadText = typeaheadText,
className = className,
init = init
).also(this::add)
| 17
|
Kotlin
|
65
| 1,235
|
7daa34594be70c037bfbaeefbfd1e3d7629e1e0b
| 5,824
|
kvision
|
MIT License
|
editadapterlib/src/main/java/top/i97/editadapterlib/adapter/BaseQuickEditModeAdapter.kt
|
maximilianMao
| 286,661,074
| false
| null |
/*
MIT License
Copyright (c) 2020 Plain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package top.i97.editadapterlib.adapter
import android.view.View
import android.widget.CheckBox
import android.widget.CompoundButton
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import top.i97.editadapterlib.entity.Selected
import top.i97.editadapterlib.inter.IEditSelectedListener
/**
* 基础编辑列表适配器
*
* @author Plain
*/
abstract class BaseQuickEditModeAdapter<T : Selected, VH : BaseViewHolder>(
@LayoutRes private val layoutResId: Int,
data: MutableList<T>? = null
) : BaseQuickAdapter<T, VH>(layoutResId, data) {
companion object {
const val SHOW_MODE = 0x101
const val EDIT_MODE = 0x202
const val SELECT_MODE_PARENT = 0x201
const val SELECT_MODE_CHILD = 0x202
}
var currentMode = SHOW_MODE
set(value) {
if (field != value) field = value
}
private var oldItemClickListener: OnItemClickListener? = null
var editSelectedListener: IEditSelectedListener? = null
private val selectedList = mutableMapOf<Any, Selected>()
private var externalCheckBox: CheckBox? = null
override fun convert(holder: VH, item: T) {
// 处理编辑模式的核心方法
editKernel(holder, item)
// 外部重写该方法,填充Item的内容
convertView(holder, item)
}
/**
* 填充Item的内容
*/
protected abstract fun convertView(helper: VH, item: T)
/**
* 获取指定的复选框
*
* @param helper [BaseViewHolder]
* @return [CheckBox]复选框
*/
abstract fun getCheckBox(helper: VH): CheckBox?
/**
* 获取当切换显示模式[BaseQuickEditModeAdapter.SHOW_MODE]和
* 编辑模式[BaseQuickEditModeAdapter.EDIT_MODE]时, 需要隐藏的View,
* 一般为复选框[IEditKernelView.getCheckBox]
*/
abstract fun getHideView(helper: VH): View?
/**
* 获取选择模式
*
* 默认 [SELECT_MODE_PARENT]
*
*/
open fun getSelectMode(): Int {
return SELECT_MODE_PARENT
}
/**
* 编辑模式核心
*/
private fun editKernel(vh: VH, t: T) {
val hideView = getHideView(vh) ?: throw IllegalArgumentException("未指定HideView!!!")
if (currentMode == EDIT_MODE) {
hideView.visibility = View.VISIBLE
// 如果进入编辑模式,则进入编辑模式核心方法
touchModeKernel(vh, t)
} else {
hideView.visibility = View.GONE
// 将切换到编辑模式前的 `ItemClickListener`,复原
if (oldItemClickListener != null) {
vh.itemView.setOnClickListener {
var position: Int = vh.adapterPosition
if (position == RecyclerView.NO_POSITION) {
return@setOnClickListener
}
position -= headerLayoutCount
setOnItemClickListener(oldItemClickListener)
setOnItemClick(it, position)
}
}
// 长按item进入编辑模式,进入的操作由外部实现
vh.itemView.setOnLongClickListener {
// 长按item判断下当前所处模式,如果是编辑模式就不响应
if (!checkEditMode() && null != editSelectedListener) {
editSelectedListener?.onLongClickEnterEditMode()
appendItemForSelectedList(t)
callBackSelectedCount()
return@setOnLongClickListener true
}
false
}
}
}
/**
* 根据当前[getSelectMode]选择模式,调用不用的方案
*/
private fun touchModeKernel(vh: VH, t: T) {
when {
getSelectMode() == SELECT_MODE_PARENT -> {
selectModeParentKernel(vh, t)
}
getSelectMode() == SELECT_MODE_CHILD -> {
selectModeChildKernel(vh, t)
}
else -> {
throw IllegalArgumentException("未指定触摸模式,重写 `getTouchMode()` 进行指定," +
"可选 `SELECT_MODE_PARENT` 和 `SELECT_MODE_CHILD` !")
}
}
}
/**
* 选择模式[SELECT_MODE_PARENT]核心
*/
private fun selectModeParentKernel(vh: VH, t: T) {
val itemView: View = vh.itemView
val checkBox = getCheckBox(vh) ?: throw IllegalArgumentException("未指定CheckBox!!!")
checkBox.isClickable = false
checkBox.isChecked = t.isSelected
// 缓存在 `SHOW_MODE` 时设置的 `OnItemClickListener`, 切换回去后进行还原
oldItemClickListener = getOnItemClickListener()
itemView.setOnClickListener {
val selected = !t.isSelected
checkBox.isChecked = selected
processSelected(t, selected)
callBackSelectedCount()
}
}
/**
* 选择模式[SELECT_MODE_CHILD]核心
*/
private fun selectModeChildKernel(vh: VH, t: T) {
val checkBox = getCheckBox(vh) ?: throw IllegalArgumentException("未指定CheckBox!!!")
checkBox.isClickable = true
checkBox.isChecked = t.isSelected
if (currentMode == EDIT_MODE) {
checkBox.setOnCheckedChangeListener { buttonView: CompoundButton, isChecked: Boolean ->
//过滤非人为点击
if (!buttonView.isPressed) {
return@setOnCheckedChangeListener
}
processSelected(t, isChecked)
callBackSelectedCount()
}
}
}
/**
* 选择状态设置
*/
private fun processSelected(t: T, isSelected: Boolean) {
if (isSelected) {
appendItemForSelectedList(t)
} else {
removeItemForSelectedList(t)
}
}
/**
* 添加Item到已选择列表[selectedList]
*/
private fun appendItemForSelectedList(t: T) {
t.isSelected = true
val identityHashCode = System.identityHashCode(t)
if (!selectedList.contains(identityHashCode)) {
selectedList[identityHashCode] = t
}
}
/**
* 删除Item从已选择列表[selectedList]
*/
private fun removeItemForSelectedList(t: T) {
val identityHashCode = System.identityHashCode(t)
t.isSelected = false
selectedList.remove(identityHashCode)
}
/**
* 变更显示模式
*
* 显示模式: [SHOW_MODE]
* 编辑模式: [EDIT_MODE]
*/
open fun changeMode(mode: Int) {
// 切换到显示模式,外部 `CheckBox` 复原到未选择状态
externalCheckBox?.apply {
if (mode == SHOW_MODE && isChecked) {
isChecked = false
}
}
currentMode = mode
restoreUnSelected()
notifyDataSetChanged()
}
/**
* 恢复所有已选择Item[selectedList]为未选择状态
*/
private fun restoreUnSelected() {
if (selectedList.isNotEmpty()) {
for (selected in selectedList) {
if (selected.value.isSelected) {
selected.value.isSelected = false
}
}
selectedList.clear()
}
}
/**
* 选择全部Item
*/
open fun selectedAllItem() {
if (data.isNotEmpty() && checkEditMode()) {
for (i in data.indices) {
val t = data[i]
appendItemForSelectedList(t)
notifyItemChanged(i)
}
callBackSelectedCount()
}
}
/**
* 取消选择全部Item
*/
open fun unSelectedAllItem() {
if (data.isNotEmpty() && checkEditMode()) {
for (i in data.indices) {
val t = data[i]
removeItemForSelectedList(t)
notifyItemChanged(i)
}
callBackSelectedCount()
}
}
/**
* 删除选中Item[selectedList]
*/
open fun removeSelectedItem() {
if (data.isNotEmpty() && checkEditMode()) {
// 循环内删除元素需要倒序删除
for (i in data.indices.reversed()) {
val t = data[i]
val identityHashCode = System.identityHashCode(t)
if (selectedList.contains(identityHashCode)) {
selectedList.remove(data.removeAt(i))
removeItem(i)
}
}
callBackSelectedCount()
}
}
/**
* 获取已选择Item[selectedList]的数量
*/
open fun getSelectedItemCount(): Int {
return if (selectedList.isNotEmpty() && checkEditMode()) selectedList.size else 0
}
/**
* 删除Item[BaseQuickAdapter.data]
*/
private fun removeItem(pos: Int) {
notifyItemRemoved(pos)
notifyItemRangeChanged(0, itemCount)
}
/**
* 获取是否选择全部数据
*
* true: 选择全部
* false: 未选中全部
*/
open fun isSelectedAllItem(): Boolean {
return getSelectedItemCount() == data.size
}
/**
* 回调当前选择数量
*/
private fun callBackSelectedCount() {
if (null != editSelectedListener) {
val count = getSelectedItemCount()
// 检查是否选中全部,并联动外部 `CheckBox` 状态
externalCheckBox?.isChecked = count > 0 && count == data.size
editSelectedListener?.onSelectedItemCount(count)
}
}
/**
* 检查当前是否处于[EDIT_MODE]编辑模式
*
* true: 编辑模式[EDIT_MODE]
* false: 显示模式[SHOW_MODE]
*/
private fun checkEditMode(): Boolean {
return currentMode == EDIT_MODE
}
/**
* 获取已选择的Item[selectedList]
*/
open fun getSelectedList(): List<Selected> {
return selectedList.values.toList()
}
/**
* 获取要删除的Item (外部实现)
*
* 一般删除item都是需要传给接口id的,可以在适配器中重写此方法,来实现自己的逻辑
* 获取以选择的item集合可通过[getSelectedList]获得
*
*/
open fun getDeleteParams(): String? {
return null
}
/**
* 绑定外部CheckBox[externalCheckBox],使其跟随列表联动
*/
@JvmOverloads
open fun bindExternalCheckBox(externalCheckBox: CheckBox?, checkedChangeListener: CompoundButton.OnCheckedChangeListener? = null) {
if (null != externalCheckBox) {
this.externalCheckBox = externalCheckBox
externalCheckBox.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView: CompoundButton, isChecked: Boolean ->
checkedChangeListener?.onCheckedChanged(buttonView, isChecked)
// 过滤非任务点击行为
if (!buttonView.isPressed) return@OnCheckedChangeListener
if (data.isNotEmpty()) {
if (!isChecked || isSelectedAllItem()) {
unSelectedAllItem() // 取消全选
} else {
selectedAllItem() // 全选
}
} else {
buttonView.isChecked = false
}
})
}
}
}
| 0
| null |
0
| 2
|
3411806de02d3e1ed56c209de96b3f4a6af9af52
| 11,735
|
EditAdapter
|
MIT License
|
idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt
|
staygold1
| 79,351,914
| true
|
{"Markdown": 39, "XML": 1025, "Gradle": 163, "Ant Build System": 52, "Shell": 12, "Ignore List": 8, "Batchfile": 11, "Git Attributes": 1, "Kotlin": 29677, "Java": 4756, "Protocol Buffer": 7, "Text": 8925, "JavaScript": 194, "JAR Manifest": 3, "Roff": 191, "Roff Manpage": 19, "Java Properties": 16, "AsciiDoc": 1, "INI": 52, "HTML": 299, "Groovy": 24, "JSON": 13, "Maven POM": 105, "CSS": 2, "Proguard": 5, "JFlex": 2, "ANTLR": 1}
|
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.facet
import com.intellij.facet.impl.ui.libraries.DelegatingLibrariesValidatorContext
import com.intellij.facet.ui.*
import com.intellij.facet.ui.libraries.FrameworkLibraryValidator
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.TargetPlatformKind
import java.awt.BorderLayout
import javax.swing.JCheckBox
import javax.swing.JComboBox
import javax.swing.JComponent
import javax.swing.JPanel
class KotlinFacetEditorGeneralTab(
private val configuration: KotlinFacetConfiguration,
private val editorContext: FacetEditorContext,
validatorsManager: FacetValidatorsManager,
private val compilerTab: KotlinFacetEditorCompilerTab
) : FacetEditorTab() {
inner class VersionValidator : FacetEditorValidator() {
override fun check(): ValidationResult {
val apiLevel = apiVersionComboBox.selectedItem as? LanguageVersion? ?: return ValidationResult.OK
val languageLevel = languageVersionComboBox.selectedItem as? LanguageVersion? ?: return ValidationResult.OK
val targetPlatform = targetPlatformComboBox.selectedItem as TargetPlatformKind<*>?
val libraryLevel = getLibraryLanguageLevel(editorContext.module, editorContext.rootModel, targetPlatform)
if (languageLevel < apiLevel || libraryLevel < apiLevel) {
return ValidationResult("Language version/Runtime version may not be less than API version", null)
}
return ValidationResult.OK
}
}
private val useProjectSettingsCheckBox = JCheckBox("Use project settings")
private val languageVersionComboBox =
JComboBox<LanguageVersion>(LanguageVersion.values()).apply {
setRenderer(DescriptionListCellRenderer())
}
private val apiVersionComboBox =
JComboBox<LanguageVersion>(LanguageVersion.values()).apply {
setRenderer(DescriptionListCellRenderer())
}
private val targetPlatformComboBox =
JComboBox<TargetPlatformKind<*>>(TargetPlatformKind.ALL_PLATFORMS.toTypedArray()).apply {
setRenderer(DescriptionListCellRenderer())
}
private val libraryValidator: FrameworkLibraryValidator
private val versionValidator = VersionValidator()
init {
libraryValidator = FrameworkLibraryValidatorWithDynamicDescription(
DelegatingLibrariesValidatorContext(editorContext),
validatorsManager,
"kotlin"
) { targetPlatformComboBox.selectedItem as TargetPlatformKind<*> }
validatorsManager.registerValidator(libraryValidator)
validatorsManager.registerValidator(versionValidator)
useProjectSettingsCheckBox.addActionListener {
useProjectSettingsChanged()
}
languageVersionComboBox.addActionListener {
validatorsManager.validate()
}
apiVersionComboBox.addActionListener {
validatorsManager.validate()
}
targetPlatformComboBox.addActionListener {
validatorsManager.validate()
updateCompilerTab()
}
updateCompilerTab()
reset()
}
private fun useProjectSettingsChanged() {
val useModuleSpecific = !useProjectSettingsCheckBox.isSelected
languageVersionComboBox.isEnabled = useModuleSpecific
apiVersionComboBox.isEnabled = useModuleSpecific
updateCompilerTab()
}
private fun updateCompilerTab() {
compilerTab.compilerConfigurable.setTargetPlatform(chosenPlatform)
UIUtil.setEnabled(compilerTab.compilerConfigurable.contentPane, !useProjectSettingsCheckBox.isSelected, true)
}
override fun isModified(): Boolean {
if (useProjectSettingsCheckBox.isSelected != configuration.settings.useProjectSettings) return true
return with(configuration.settings.versionInfo) {
if (useProjectSettingsCheckBox.isSelected) return targetPlatformComboBox.selectedItem != targetPlatformKind
languageVersionComboBox.selectedItem != languageLevel
|| targetPlatformComboBox.selectedItem != targetPlatformKind
|| apiVersionComboBox.selectedItem != apiLevel
}
}
override fun reset() {
useProjectSettingsCheckBox.isSelected = configuration.settings.useProjectSettings
with(configuration.settings.versionInfo) {
languageVersionComboBox.selectedItem = languageLevel
apiVersionComboBox.selectedItem = apiLevel
targetPlatformComboBox.selectedItem = targetPlatformKind
}
useProjectSettingsChanged()
}
override fun apply() {
configuration.settings.useProjectSettings = useProjectSettingsCheckBox.isSelected
with(configuration.settings.versionInfo) {
if (!useProjectSettingsCheckBox.isSelected) {
languageLevel = languageVersionComboBox.selectedItem as LanguageVersion?
apiLevel = apiVersionComboBox.selectedItem as LanguageVersion?
}
targetPlatformKind = targetPlatformComboBox.selectedItem as TargetPlatformKind<*>?
}
}
override fun getDisplayName() = "General"
override fun createComponent(): JComponent {
val mainPanel = JPanel(BorderLayout())
val contentPanel = FormBuilder
.createFormBuilder()
.addComponent(useProjectSettingsCheckBox)
.addLabeledComponent("&Language version: ", languageVersionComboBox)
.addLabeledComponent("&Standard library API version: ", apiVersionComboBox)
.addLabeledComponent("&Target platform: ", targetPlatformComboBox)
.panel
mainPanel.add(contentPanel, BorderLayout.NORTH)
return mainPanel
}
override fun disposeUIResources() {
}
val chosenPlatform: TargetPlatformKind<*>?
get() = targetPlatformComboBox.selectedItem as TargetPlatformKind<*>?
}
| 0
|
Java
|
0
| 1
|
284b9d2ba692d292605d7b6cdc763b15320d8c2e
| 6,734
|
kotlin
|
Apache License 2.0
|
drop-in/src/main/java/com/adyen/checkout/dropin/internal/ui/BacsDirectDebitDialogFragment.kt
|
Adyen
| 91,104,663
| false
| null |
/*
* Copyright (c) 2021 Adyen N.V.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by ozgur on 19/11/2021.
*/
package com.adyen.checkout.dropin.internal.ui
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import com.adyen.checkout.bacs.BacsDirectDebitComponent
import com.adyen.checkout.core.AdyenLogLevel
import com.adyen.checkout.core.internal.util.adyenLog
import com.adyen.checkout.dropin.databinding.FragmentBacsDirectDebitComponentBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.R as MaterialR
internal class BacsDirectDebitDialogFragment : BaseComponentDialogFragment() {
private var _binding: FragmentBacsDirectDebitComponentBinding? = null
private val binding: FragmentBacsDirectDebitComponentBinding get() = requireNotNull(_binding)
private val bacsDirectDebitComponent: BacsDirectDebitComponent by lazy { component as BacsDirectDebitComponent }
companion object : BaseCompanion<BacsDirectDebitDialogFragment>(BacsDirectDebitDialogFragment::class.java)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentBacsDirectDebitComponentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adyenLog(AdyenLogLevel.DEBUG) { "onViewCreated" }
binding.header.text = paymentMethod.name
binding.bacsView.attach(bacsDirectDebitComponent, viewLifecycleOwner)
if (bacsDirectDebitComponent.isConfirmationRequired()) {
setInitViewState(BottomSheetBehavior.STATE_EXPANDED)
binding.bacsView.requestFocus()
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
adyenLog(AdyenLogLevel.DEBUG) { "onCreateDialog" }
val dialog = super.onCreateDialog(savedInstanceState)
setDialogToFullScreen(dialog)
return dialog
}
override fun onBackPressed(): Boolean {
return if (bacsDirectDebitComponent.handleBackPress()) {
true
} else {
super.onBackPressed()
}
}
private fun setDialogToFullScreen(dialog: Dialog) {
dialog.setOnShowListener {
val bottomSheetDialog = dialog as BottomSheetDialog
val bottomSheet =
bottomSheetDialog.findViewById<FrameLayout>(MaterialR.id.design_bottom_sheet)
val layoutParams = bottomSheet?.layoutParams
val behavior = bottomSheet?.let { BottomSheetBehavior.from(it) }
behavior?.isDraggable = false
layoutParams?.height = WindowManager.LayoutParams.MATCH_PARENT
bottomSheet?.layoutParams = layoutParams
behavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
}
| 28
|
Kotlin
|
66
| 96
|
1f000e27e07467f3a30bb3a786a43de62be003b2
| 3,312
|
adyen-android
|
MIT License
|
composeApp/src/iosMain/kotlin/org/example/grocery/core/database/DatabaseFactory.ios.kt
|
ckam99
| 798,453,071
| false
|
{"Kotlin": 43884, "Swift": 594}
|
package org.example.grocery.core.database
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
import org.example.grocery.cache.GroceryDatabase
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
actual class DatabaseDriverFactory {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(
schema = GroceryDatabase.Schema,
name = groceryDatabaseName
)
}
}
| 0
|
Kotlin
|
0
| 0
|
9a862eecdaa2ca8a990933246045c633ccc2132a
| 469
|
compose-multiplatform
|
MIT License
|
kzen-auto-common/src/commonMain/kotlin/tech/kzen/auto/common/paradigm/dataflow/service/active/ActiveVisualProvider.kt
|
alexoooo
| 131,353,826
| false
| null |
package tech.kzen.auto.common.paradigm.dataflow.service.active
import tech.kzen.auto.common.paradigm.dataflow.model.exec.VisualDataflowModel
import tech.kzen.auto.common.paradigm.dataflow.model.exec.VisualVertexModel
import tech.kzen.auto.common.paradigm.dataflow.model.exec.VisualVertexTransition
import tech.kzen.auto.common.paradigm.dataflow.service.visual.VisualDataflowProvider
import tech.kzen.lib.common.model.document.DocumentPath
import tech.kzen.lib.common.model.locate.ObjectLocation
class ActiveVisualProvider(
private val activeDataflowRepository: ActiveDataflowRepository
):
VisualDataflowProvider
{
override suspend fun inspectDataflow(
host: DocumentPath
): VisualDataflowModel {
return activeDataflowRepository.inspect(host)
}
override suspend fun inspectVertex(
host: DocumentPath,
vertexLocation: ObjectLocation
): VisualVertexModel {
return activeDataflowRepository.inspectVertex(host, vertexLocation)
}
override suspend fun executeVertex(
host: DocumentPath,
vertexLocation: ObjectLocation
): VisualVertexTransition {
return activeDataflowRepository.executeVisual(host, vertexLocation)
}
override suspend fun resetDataflow(host: DocumentPath): VisualDataflowModel {
return activeDataflowRepository.reset(host)
}
}
| 1
|
Kotlin
|
1
| 1
|
97a140f0599d1eb3dc9dd3075b6a4fdbc5daaba0
| 1,395
|
kzen-auto
|
MIT License
|
src/main/java/com/fynd/nitrozen/nitrozeninput/drawer/ErrorTextDrawer.kt
|
gofynd
| 238,860,720
| false
| null |
package com.fynd.nitrozen.nitrozeninput.drawer
import android.graphics.Typeface
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.fynd.nitrozen.R
import com.fynd.nitrozen.nitrozenbutton.utils.pxToDp
import com.fynd.nitrozen.nitrozeninput.NInput
import com.fynd.nitrozen.nitrozeninput.model.NitrozenInput
import com.fynd.nitrozen.utils.Drawer
class ErrorTextDrawer(val view: NInput, val input: NitrozenInput) :
Drawer<NInput, NitrozenInput>(view, input) {
private var textView: TextView = TextView(view.context)
override fun draw() {
if (isReady()) {
init()
isViewAdded = true
view.addView(textView)
}
}
override fun isReady(): Boolean {
return !input.errorText.isNullOrEmpty() && input.hintText.isNullOrEmpty()
}
private fun init() {
if (isReady()) {
val params =
LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
textView.includeFontPadding = false
textView.setPadding(0, pxToDp(10f).toInt(), 0, 0)
textView.gravity = Gravity.CENTER_VERTICAL
params.setMargins(
pxToDp(5f).toInt(),
pxToDp(5f).toInt(), 0, 0
)
textView.text = input.errorText
textView.setTextColor(ContextCompat.getColor(view.context, R.color.colorError))
textView.setSingleLine()
textView.ellipsize = TextUtils.TruncateAt.END
textView.setLines(1)
textView.layoutParams = params
textView.textSize = input.titleTextSize
try {
val tf = ResourcesCompat.getFont(view.context, R.font.poppins)
textView.setTypeface(tf, Typeface.NORMAL)
} catch (e: Exception) {
}
textView.visibility = View.VISIBLE
} else {
textView.visibility = View.GONE
}
}
override fun updateLayout() {
if (isViewAdded) {
init()
} else {
draw()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
9b98a8eaeec547c44ddb35c345b5ac3dff2d0a6f
| 2,372
|
nitrozen-android
|
MIT License
|
places-compose/src/main/java/com/google/android/libraries/places/compose/autocomplete/models/geocoder/AddressDto.kt
|
googlemaps
| 836,962,804
| false
|
{"Kotlin": 241617}
|
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.places.compose.autocomplete.models.geocoder
import com.google.gson.annotations.SerializedName
data class ReverseGeocodingResponse(
@SerializedName("status") val status: String,
@SerializedName("address_descriptor") val addressDescriptor: AddressDescriptor?,
@SerializedName("plus_code") val plusCode: PlusCode?,
@SerializedName("results") val addresses: List<AddressDto>
)
data class AddressDescriptor(
@SerializedName("areas") val areas: List<Area>,
@SerializedName("landmarks") val landmarks: List<Landmark>
)
data class Area(
@SerializedName("containment") val containment: String,
@SerializedName("display_name") val displayName: DisplayName,
@SerializedName("place_id") val placeId: String
)
data class Landmark(
@SerializedName("display_name") val displayName: DisplayName,
@SerializedName("place_id") val placeId: String,
@SerializedName("spatial_relationship") val spatialRelationship: String,
@SerializedName("straight_line_distance_meters") val straightLineDistanceMeters: Double,
@SerializedName("travel_distance_meters") val travelDistanceMeters: Double,
@SerializedName("types") val types: List<String>
)
data class DisplayName(
@SerializedName("language_code") val languageCode: String,
@SerializedName("text") val text: String
)
data class PlusCode(
@SerializedName("compound_code") val compoundCode: String,
@SerializedName("global_code") val globalCode: String
)
data class AddressDto(
@SerializedName("address_components") val addressComponents: List<AddressComponent>,
@SerializedName("formatted_address") val formattedAddress: String,
@SerializedName("geometry") val geometry: Geometry,
@SerializedName("place_id") val placeId: String,
@SerializedName("plus_code") val plusCode: PlusCode,
@SerializedName("types") val types: List<String>
) {
fun getCountryCode(): String? {
return addressComponents.firstOrNull { it.types.contains("country") }?.shortName
}
}
data class AddressComponent(
@SerializedName("long_name") val longName: String,
@SerializedName("short_name") val shortName: String,
val types: List<String>
)
data class Geometry(
val location: Location,
@SerializedName("location_type") val locationType: String,
val viewport: Viewport,
val bounds: Bounds?
)
data class Location(
val lat: Double,
val lng: Double
)
data class Viewport(
val northeast: Location,
val southwest: Location
)
data class Bounds(
val northeast: Location,
val southwest: Location
)
| 3
|
Kotlin
|
1
| 5
|
6169bf5359878abb2462e1d73ef0663a1963780d
| 3,192
|
android-places-compose
|
Apache License 2.0
|
shcDecoder/src/androidTest/java/ca/bc/gov/shcdecoder/BcCardVerifierTest.kt
|
bcgov
| 399,972,903
| false
| null |
package ca.bc.gov.shcdecoder
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import ca.bc.gov.shcdecoder.model.ImmunizationStatus
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class BcCardVerifierTest {
private lateinit var bcCardVerifier: BcCardVerifier
@Before
fun setUp() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
bcCardVerifier = BcCardVerifier(context)
}
@Test
fun shouldBeFullyImmunizedOnTwoDoseVaccine() = runBlocking{
val shcUri =
"shc:/56762909524320603460292437404460312229595326546034602925" +
"4077280433602870286471674522280928613331456437653141590" +
"6402203064504590856435503414245413640370636654171372412" +
"3638030437562204673740753232392543344332605736011041301" +
"0537174742435744144043462034473657503626862762120623252" +
"2027525474696822660444620835583838407208600933007704290" +
"3233410235567280558597239325426524223052252236467055543" +
"0856637141254038405873445452005920264300550828765200251" +
"276044277374508122306350906530040766670442424295827042007392358252357507625087741066662527336450827690675034352417436090642540427660311595435036766065854293470644041532128362363700336432904327744504028376668567263720335656603073325046437325530317275122603766832262467613776577455692435670735622520562441446940616210662065565861303611307343333036281111727222202800312507387330361075224238077568322804043037276577637565352709427469297738757542716700240752053274406967244050213235404455414545624263006368235734547334602473560662765033095908347521556059367533453906353322576120740060433573385832262254073238256220445005655208377159426472053877211211362704093639380943680377091045086923100670700625712254217039215941453636665077331170456853233367346771102445073676707238255738415204455474537459590452280338066444042606405900414176747104606269440421036543405206423037600521557133043035765856755020087372777311424250351073610010345365667055715375086956614150093057254105632157732766726457081211011029654236102129372638037029095964532156046953052122612138350557110032070574007433720857327255610862436953543134763052095629527703325808037272596174435333754435397540115836"
val result = bcCardVerifier.verify(shcUri)
assertEquals(ImmunizationStatus.FULLY_IMMUNIZED, result.status)
}
@Test
fun shouldBePartiallyImmunizationOnSingleDoseOfTwoDoseVaccine() = runBlocking {
val shcUri =
"shc:/567629095243206034602924374044603122295953265460346029254077280433602870286471674522280928613331456437653141590640220306450459085643550341424541364037063665417137241236380304375622046737407532323925433443326057360157413131537170742435764144277366374050654441652771605936122128585243662857302142300770042774292968434423504372437063346237376721637641655961341000743864095220725376077368056777414274386233082323430328580950777332252927252207556254640975770850685504560800592659712844243066657620542107310911365029520025223903302535667154500008406731255804731275407273377625116038267356213030554525717244297020346469292122654006556111282077374071553112032334370803526969286030046273656507443952706644616033273706385042285777595729343609584144694139621007204357626130741130734333303644111100722220545025301130062728570823232922030363245230634423100730070740395731563924086544754171677525075205320754696724545029322840525754412541524330566933547577116868391164036543500872100620057158201054643660090542723436245737216112035811123020664029775829372665666605054345122205037276424535106620006577217327665669433469337363705742086305053403072425542627226868585837736443084406410426533855235306262507366872726831356069046441752050344227416924033806644409357267390767691168034230556325443438090977390821523120663304034344695052212427323565723365570705525073065836590772104372225672107555506565002336016608634243773033372510101132583669050010557774422406245275126959712120426904112344293453440841753034700342555544753461742173520426755756231237703464262020411024566974201136"
val result = bcCardVerifier.verify(shcUri)
assertEquals(ImmunizationStatus.PARTIALLY_IMMUNIZED, result.status)
}
@Test
fun shouldBePartiallyImmunizedOnDaysNotPassedSinceVaccinated() = runBlocking{
val shcUri =
"shc:/567629095243206034602924374044603122295953265460346029254077280433602870286471674522280928613331456437653141590640220306450459085643550341424541364037063665417137241236380304375622046737407532323925433443326057360157413131537170742435764144277366374050654441652771605936122128585243662857302142300770042774292968434423504372437063346237376721637641655961341000743864095220725376077368056777414274386233082323430328580950777332252927252207556254640975770850685504560800592659712844243066657620542107310911365029520025223903302535667154500008406731255804731275407273377625116038267356213030554525717244297020346469292122654006556111282077374071553112032334370803526969286030046273656507443952706644616033273706385042285777595729343609584144694139621007204357626130741130734333303644111100722220545025301130062728570823232922030363245230634423100730070740395731563924086544754171677525075205320754696724545029322840525754412541524330566933547577116868391164036543500872100620057158201054643660090542723436245737216112035811123020664029775829372665666605054345122205037276424535106620006577217327665669433469337363705742086305053403072425542627226868585837736443084406410426533855235306262507366872726831356069046441752050344227416924033806644409357267390767691168034230556325443438090977390821523120663304034344695052212427323565723365570705525073065836590772104372225672107555506565002336015032441143053610202654423144004353423728380722653721584461060534262010300609283708695252280640762873375704117434316042645352547327240824206239360309261025092125367705355558"
val result = bcCardVerifier.verify(shcUri)
assertEquals(ImmunizationStatus.PARTIALLY_IMMUNIZED, result.status)
}
@Test
fun shouldValidateYukonQR() = runBlocking{
val shcUri = "shc:/567629095243206034602924374044603122295953265460346029254077280433602870286471674522280928645973372408413923414540772126330432073264712652050864562329744562253639241270414233714562296632634103406321415426116057360110413531537133202535054344567344275854106065560361403725380326623820596332376357297435777034455924522911203350256106272739682541031029637454533877297510106165064334002954281040453471120800667009066856346922120729237274635661401107762311086560207158384031037260400469525339706877305267693445773659353857046573595521093900502973333042531225676103420038756143707527605375582537350707373836447373772072616574417603077226777062682855752220126631296100241237575835626768711129002134706039030456676563306238505665584355382858442211072476052408762257275900376659062061295330333869222106522527452008380663682958317309346257200656242411397203585041755962772138323040623259274371117025045707705924120923612312105450570874717773276800733133586874340927207103350325110826327772572559332929436727232839626759770773085031596131726172582744585840556800095334763724584254370744202730507407225355772771381231436640400752594420717264682775687672522572387436703056543807036520117300075836567334442540640654674452721163605567623939545310530611076006740524596834765853755441213166545343206055413959224024266511050923427232740464564408675332680558575326687360313945650621705321394322554531255923102506742565613962077706757474056866396630277232763009552160435320744128675926417075657310683758047256604523252775125407267165586805002150705805226938412656223144684550127070307307003640016838057441334052354361336058104004696828665561086538285643682822395436270459766069612330413630540431550023723237096209670465075338310536770545001243660410390607335563095758"
val result = bcCardVerifier.verify(shcUri)
assertEquals(ImmunizationStatus.FULLY_IMMUNIZED, result.status)
}
}
| 6
|
Kotlin
|
6
| 22
|
57d929c8c73620021b59386c084536091cbfe91a
| 8,306
|
BCVAX-Android
|
Apache License 2.0
|
app/src/main/java/com/primalabs/primatodo/ui/MainActivity.kt
|
zprima
| 343,185,198
| false
| null |
package com.primalabs.primatodo.ui
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.HiltViewModelFactory
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.primalabs.primatodo.ui.theme.PrimaTodoTheme
import com.primalabs.primatodo.ui.screens.AddTodoScreen
import com.primalabs.primatodo.ui.screens.ListTodoScreen
import com.primalabs.primatodo.ui.screens.Screens
import com.primalabs.primatodo.ui.viewmodels.AddTodoViewModel
import com.primalabs.primatodo.ui.viewmodels.ListTodoViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TodoApp()
}
}
}
@Composable
fun TodoApp() {
val navController = rememberNavController()
PrimaTodoTheme(darkTheme = false) {
NavHost(navController, startDestination = Screens.ListTodoScreen.screenName) {
composable(Screens.ListTodoScreen.screenName) { backStackEntry ->
val listTodoViewModel: ListTodoViewModel = viewModel(factory =
HiltViewModelFactory(context = LocalContext.current, navBackStackEntry = backStackEntry)
)
ListTodoScreen(navController = navController, listTodoViewModel = listTodoViewModel)
}
composable(Screens.AddTodoScreen.screenName) { backStackEntry ->
val addTodoViewModel: AddTodoViewModel = viewModel(factory =
HiltViewModelFactory(context = LocalContext.current, navBackStackEntry = backStackEntry)
)
AddTodoScreen(navController = navController, addTodoViewModel = addTodoViewModel)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
63e18f072a8fc10263fb7219a0f04e07b7e6f0de
| 2,121
|
compose-todo-app
|
Apache License 2.0
|
idea/idea-core/src/org/jetbrains/kotlin/idea/core/script/KotlinScriptConfigurationManager.kt
|
gigliovale
| 89,726,097
| false
| null |
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.core.script
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.NonClasspathDirectoriesScope
import com.intellij.util.io.URLUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.script.KotlinScriptDefinitionProvider
import org.jetbrains.kotlin.script.KotlinScriptExternalImportsProvider
import org.jetbrains.kotlin.script.StandardScriptDefinition
import org.jetbrains.kotlin.script.makeScriptDefsFromTemplatesProviderExtensions
import java.io.File
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
@Suppress("SimplifyAssertNotNull")
class KotlinScriptConfigurationManager(
private val project: Project,
private val dumbService: DumbService,
private val scriptDefinitionProvider: KotlinScriptDefinitionProvider,
private val scriptExternalImportsProvider: KotlinScriptExternalImportsProvider
) {
init {
reloadScriptDefinitions()
StartupManager.getInstance(project).registerPostStartupActivity {
cacheAllScriptsExtraImports()
invalidateLocalCaches()
notifyRootsChanged()
}
project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener.Adapter() {
override fun after(events: List<VFileEvent>) {
updateExternalImportsCache(events.mapNotNull { it.file }) {
invalidateLocalCaches()
notifyRootsChanged()
}
}
})
}
private val cacheLock = ReentrantReadWriteLock()
private val allScriptsClasspathCache = ClearableLazyValue(cacheLock) {
toVfsRoots(scriptExternalImportsProvider.getKnownCombinedClasspath().distinct())
}
private val allScriptsClasspathScope = ClearableLazyValue(cacheLock) {
NonClasspathDirectoriesScope(getAllScriptsClasspath())
}
private val allLibrarySourcesCache = ClearableLazyValue(cacheLock) {
toVfsRoots(scriptExternalImportsProvider.getKnownSourceRoots().distinct())
}
private val allLibrarySourcesScope = ClearableLazyValue(cacheLock) {
NonClasspathDirectoriesScope(getAllLibrarySources())
}
private fun notifyRootsChanged() {
// TODO: it seems invokeLater leads to inconsistent behaviour (at least in tests)
ApplicationManager.getApplication().invokeLater {
runWriteAction {
if (project.isDisposed) return@runWriteAction
ProjectRootManagerEx.getInstanceEx(project)?.makeRootsChange(EmptyRunnable.getInstance(), false, true)
dumbService.runWhenSmart {
ScriptDependenciesModificationTracker.getInstance(project).incModificationCount()
}
}
}
}
fun getScriptClasspath(file: VirtualFile): List<VirtualFile> = toVfsRoots(
scriptExternalImportsProvider.getExternalImports(file)?.classpath ?: emptyList()
)
fun getAllScriptsClasspath(): List<VirtualFile> = allScriptsClasspathCache.get()
fun getAllLibrarySources(): List<VirtualFile> = allLibrarySourcesCache.get()
fun getAllScriptsClasspathScope() = allScriptsClasspathScope.get()
fun getAllLibrarySourcesScope() = allLibrarySourcesScope.get()
private fun reloadScriptDefinitions() {
makeScriptDefsFromTemplatesProviderExtensions(project, { ep, ex -> log.warn("[kts] Error loading definition from ${ep.id}", ex) }).let {
if (it.isNotEmpty()) {
scriptDefinitionProvider.setScriptDefinitions(it + StandardScriptDefinition)
}
}
}
private fun cacheAllScriptsExtraImports() {
runReadAction {
scriptExternalImportsProvider.apply {
invalidateCaches()
cacheExternalImports(
scriptDefinitionProvider.getAllKnownFileTypes()
.flatMap { FileTypeIndex.getFiles(it, GlobalSearchScope.allScope(project)) })
}
}
}
private fun updateExternalImportsCache(files: Iterable<VirtualFile>, onChange: () -> Unit) {
val isChanged = scriptExternalImportsProvider.updateExternalImportsCache(files).any()
if (isChanged) {
onChange()
}
}
private fun invalidateLocalCaches() {
allScriptsClasspathCache.clear()
allScriptsClasspathScope.clear()
allLibrarySourcesCache.clear()
allLibrarySourcesScope.clear()
}
companion object {
@JvmStatic
fun getInstance(project: Project): KotlinScriptConfigurationManager =
ServiceManager.getService(project, KotlinScriptConfigurationManager::class.java)
fun toVfsRoots(roots: Iterable<File>): List<VirtualFile> {
return roots.mapNotNull { it.classpathEntryToVfs() }
}
private fun File.classpathEntryToVfs(): VirtualFile? {
val res = when {
!exists() -> null
isDirectory -> StandardFileSystems.local()?.findFileByPath(this.canonicalPath) ?: null
isFile -> StandardFileSystems.jar()?.findFileByPath(this.canonicalPath + URLUtil.JAR_SEPARATOR) ?: null
else -> null
}
// TODO: report this somewhere, but do not throw: assert(res != null, { "Invalid classpath entry '$this': exists: ${exists()}, is directory: $isDirectory, is file: $isFile" })
return res
}
internal val log = Logger.getInstance(KotlinScriptConfigurationManager::class.java)
@TestOnly
fun reloadScriptDefinitions(project: Project) {
with (getInstance(project)) {
reloadScriptDefinitions()
scriptExternalImportsProvider.invalidateCaches()
invalidateLocalCaches()
}
}
}
}
private class ClearableLazyValue<out T : Any>(private val lock: ReentrantReadWriteLock, private val compute: () -> T) {
private var value: T? = null
fun get(): T {
lock.read {
if (value == null) {
lock.write {
value = compute()
}
}
return value!!
}
}
fun clear() {
lock.write {
value = null
}
}
}
| 1
| null |
4
| 6
|
ce145c015d6461c840050934f2200dbc11cb3d92
| 7,840
|
kotlin
|
Apache License 2.0
|
accounts/src/main/kotlin/pl/edu/pw/ia/accounts/application/model/CreateAccountRequest.kt
|
ERSMS-24L
| 768,705,060
| false
|
{"Kotlin": 75027, "CSS": 5011, "HTML": 1892, "JavaScript": 1300, "Dockerfile": 666, "Shell": 288}
|
package pl.edu.pw.ia.accounts.application.model
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import java.util.UUID
import org.hibernate.validator.constraints.Length
import pl.edu.pw.ia.shared.domain.command.CreateAccountCommand
data class CreateAccountRequest(
@Schema(maxLength = 50)
@field:NotBlank(message = "Name cannot be blank")
@field:Length(max = 50, message = "Maximum allowed name length is 50 characters")
val name: String,
@Schema(maxLength = 320)
@field:Email
@field:NotBlank(message = "Email cannot be blank")
@field:Length(max = 50, message = "Maximum allowed email length is 320 characters")
val email: String,
) {
fun toCommand() =
CreateAccountCommand(
accountId = UUID.randomUUID(),
name = name,
email = email,
)
}
| 28
|
Kotlin
|
2
| 1
|
9b7107c5b22b4bf4f111bf9fda6ca2f7c7c1a216
| 857
|
ERSMS-24L
|
MIT License
|
src/main/kotlin/icu/windea/pls/lang/codeInsight/completion/PlsCompletionPriorities.kt
|
DragonKnightOfBreeze
| 328,104,626
| false
|
{"Kotlin": 3379031, "Java": 164839, "Lex": 44775, "HTML": 23935, "Shell": 2741}
|
package icu.windea.pls.lang.codeInsight.completion
object ParadoxCompletionPriorities {
const val pinnedPriority = 1000.0
const val keywordPriority = 10.0
const val rootKeyPriority = 100.0
const val constantPriority = 90.0
const val enumPriority = 88.0
const val complexEnumPriority = 80.0
const val scopeLinkPrefixPriority = 70.0
const val valueLinkPrefixPriority = 70.0
const val databaseObjectTypePriority = 70.0
const val systemScopePriority = 60.0
const val scopePriority = 60.0
const val scopeMismatchOffset = -500
}
| 17
|
Kotlin
|
5
| 33
|
823c0d1fe3eec4bb181d645aa56e13f3be65a9e4
| 577
|
Paradox-Language-Support
|
MIT License
|
photoselector/src/main/java/com/kelin/photoselector/callback/factory/TakePictureCallbackFactory.kt
|
kelinZhou
| 279,769,026
| false
|
{"Kotlin": 149010}
|
package com.kelin.photoselector.callback.factory
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.media.MediaMetadataRetriever
import android.media.MediaScannerConnection
import android.os.*
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentActivity
import com.kelin.okpermission.OkActivityResult
import com.kelin.photoselector.PhotoSelector
import com.kelin.photoselector.cache.DistinctManager
import com.kelin.photoselector.callback.BaseCallback
import com.kelin.photoselector.callback.LeakProofCallback
import com.kelin.photoselector.model.Picture
import com.kelin.photoselector.model.PictureType
import com.kelin.photoselector.model.formatToDurationString
import com.kelin.photoselector.model.toUri
import com.kelin.photoselector.widget.ProgressDialog
import com.kelin.photoselector.utils.compressAndRotateByDegree
import java.io.File
import java.io.FileInputStream
import java.text.SimpleDateFormat
import java.util.*
/**
* **描述:** 拍照录像回调工厂。
*
* **创建人:** kelin
*
* **创建时间:** 2020/8/7 10:10 AM
*
* **版本:** v 1.0.0
*/
class TakePictureCallbackFactory(private val id: Int, private val action: String, private val targetFile: File, private val fileProvider: String, val isVideoAction: Boolean = action == MediaStore.ACTION_VIDEO_CAPTURE) : CallbackFactory<File?> {
private val handler by lazy { Handler(Looper.getMainLooper()) }
private var progressDialog: ProgressDialog? = null
override fun createCallback(): LeakProofCallback<File?> {
return TakePictureCallback()
}
private inner class TakePictureCallback : BaseCallback<File?>() {
override fun onAttach(context: Context) {
val intent = Intent(action)
// Ensure that there's a camera activity to handle the intent
// 官方注释,确保有一个活动来打开相机意图
if (intent.resolveActivity(context.packageManager) != null) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
if (targetFile.exists()) {
targetFile.delete()
} else if (targetFile.parentFile?.exists() == false) {
targetFile.parentFile?.mkdirs()
}
val uri = targetFile.toUri(context, fileProvider)
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
OkActivityResult.startActivityForCode(context as Activity, intent) { resultCode ->
if (resultCode == Activity.RESULT_OK && targetFile.exists() && contextOrNull != null) {
val duration = if (isVideoAction) {
MediaMetadataRetriever().let { m ->
m.setDataSource(targetFile.absolutePath)
m.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong() ?: 1
}
} else {
0
}
val picture = Picture(
targetFile.absolutePath,
targetFile.length(),
if (isVideoAction) PictureType.VIDEO else PictureType.PHOTO, duration.formatToDurationString(),
SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date())
)
if (PhotoSelector.isAutoCompress && !isVideoAction) {
picture.compressAndRotateByDegree()
}
insertToAlbum()
onTakePictureFinished(picture)
} else {
callback(null)
}
}
}
}
private fun onTakePictureFinished(picture: Picture) {
if (!PhotoSelector.isAutoCompress || picture.isComposeFinished) {
if (progressDialog != null) {
progressDialog!!.dismiss()
}
DistinctManager.instance.addSelected(id, picture)
callback(File(picture.uri))
} else {
if (progressDialog == null) {
progressDialog = ProgressDialog().also { dialog ->
val context = contextOrNull
val fm = if (context is FragmentActivity) {
context.supportFragmentManager
} else {
null
}
if (fm != null) {
dialog.show(fm, id.toString())
}
}
}
handler.postDelayed({
onTakePictureFinished(picture)
}, 100)
}
}
private fun insertToAlbum() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
MediaScannerConnection.scanFile(contextOrNull, arrayOf(targetFile.absolutePath), arrayOf(if (isVideoAction) "video/mp4" else "image/jpeg"), null)
} else {
contextOrNull?.also { context ->
context.contentResolver.also { resolver ->
val values = getVideoContentValues(targetFile)
resolver.insert(if (isVideoAction) MediaStore.Video.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)?.also { uri ->
resolver.openOutputStream(uri)?.use { os ->
val `is` = FileInputStream(targetFile)
FileUtils.copy(`is`, os)
`is`.close()
os.close()
}
}
}
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
fun getVideoContentValues(file: File): ContentValues {
val values = ContentValues()
values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
values.put(MediaStore.MediaColumns.MIME_TYPE, if (isVideoAction) "video/mp4" else "image/jpeg")
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
return values
}
}
}
| 3
|
Kotlin
|
6
| 24
|
5fe6fded2f47ff5e5619746e0ac9cd0b6e3ff090
| 6,508
|
PhotoSelector
|
Apache License 2.0
|
app/src/main/java/co/app/UIResult.kt
|
p-vincen-t
| 238,182,140
| false
|
{"Kotlin": 475105, "Java": 46450, "HTML": 41642}
|
/*
* Copyright 2020, {{App}}
* Licensed under the Apache License, Version 2.0, "{{App}} Inc".
* 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 co.app
/**
* A generic class that holds a value with its loading status.
* @param <T>
*/
sealed class UIResult<out T : Any> {
class Success<out T : Any>(val data: T) : UIResult<T>() {
/**
* any extra info to be passed together with the data
*/
var args: Any? = null
/**
* if the info is null return new object
*/
get() = field ?: Any()
/**
* if the info is null pass new object to the ergs
*/
set(value) {
field = value ?: Any()
}
}
class Error<out E : Throwable>(val exception: E) : UIResult<E>()
override fun toString(): String = when (this) {
is Success<*> -> "Success[data=$data, args=$args]"
is Error -> "Error[exception=$exception"
}
}
| 1
|
Kotlin
|
1
| 1
|
74d1af99f1a563b6aa5ace72eb303e055c6ace5a
| 1,436
|
android-template
|
Apache License 2.0
|
Example/TestApp/src/main/java/org/audienzz/mobile/testapp/adapter/GamRenderApiInterstitialAdHolder.kt
|
audienzz
| 756,759,435
| false
|
{"Kotlin": 347075, "Ruby": 137}
|
package org.audienzz.mobile.testapp.adapter
import android.app.Activity
import android.content.res.Configuration
import android.view.ViewGroup
import org.audienzz.mobile.api.data.AudienzzAdUnitFormat
import org.audienzz.mobile.api.exceptions.AudienzzAdException
import org.audienzz.mobile.api.rendering.AudienzzInterstitialAdUnit
import org.audienzz.mobile.api.rendering.listeners.AudienzzInterstitialAdUnitListener
import org.audienzz.mobile.eventhandlers.AudienzzGamInterstitialEventHandler
import org.audienzz.mobile.testapp.R
import org.audienzz.mobile.util.addOnBecameVisibleOnScreenListener
import java.util.EnumSet
class GamRenderApiInterstitialAdHolder(parent: ViewGroup) : AdHolder(parent) {
override val titleRes: Int
get() = R.string.gam_render_interstitial_title
private var displayAdUnit: AudienzzInterstitialAdUnit? = null
private var videoAdUnit: AudienzzInterstitialAdUnit? = null
override fun createAds() {
addDisplayInterstitialAd()
addVideoInterstitialAd()
}
private fun addDisplayInterstitialAd() {
val button = createButton(R.string.show_display_interstitial)
val orientation = adContainer.resources.configuration.orientation
val eventHandler = AudienzzGamInterstitialEventHandler(
adContainer.context as Activity,
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
DISPLAY_AD_UNIT_ID
} else {
FALLBACK_AD_UNIT_ID
},
)
displayAdUnit = AudienzzInterstitialAdUnit(
adContainer.context,
DISPLAY_CONFIG_ID,
eventHandler,
)
displayAdUnit?.setInterstitialAdUnitListener(object : AudienzzInterstitialAdUnitListener {
override fun onAdLoaded(interstitialAdUnit: AudienzzInterstitialAdUnit) {
button.isEnabled = true
button.setOnClickListener {
displayAdUnit?.show()
}
}
override fun onAdDisplayed(interstitialAdUnit: AudienzzInterstitialAdUnit) {}
override fun onAdFailed(
interstitialAdUnit: AudienzzInterstitialAdUnit,
exception: AudienzzAdException?,
) {
showErrorDialog(
adContainer.context,
exception?.message.orEmpty(),
)
}
override fun onAdClicked(interstitialAdUnit: AudienzzInterstitialAdUnit) {}
override fun onAdClosed(interstitialAdUnit: AudienzzInterstitialAdUnit) {}
})
button.addOnBecameVisibleOnScreenListener {
displayAdUnit?.loadAd()
}
}
private fun addVideoInterstitialAd() {
val button = createButton(R.string.show_video_interstitial)
val eventHandler = AudienzzGamInterstitialEventHandler(
adContainer.context as Activity,
VIDEO_AD_UNIT_ID,
)
videoAdUnit = AudienzzInterstitialAdUnit(
adContainer.context,
VIDEO_CONFIG_ID,
EnumSet.of(AudienzzAdUnitFormat.VIDEO),
eventHandler,
)
videoAdUnit?.setInterstitialAdUnitListener(object : AudienzzInterstitialAdUnitListener {
override fun onAdLoaded(interstitialAdUnit: AudienzzInterstitialAdUnit) {
button.isEnabled = true
button.setOnClickListener {
interstitialAdUnit.show()
}
}
override fun onAdDisplayed(interstitialAdUnit: AudienzzInterstitialAdUnit) {}
override fun onAdFailed(
interstitialAdUnit: AudienzzInterstitialAdUnit,
exception: AudienzzAdException?,
) {
showErrorDialog(
adContainer.context,
exception?.message.orEmpty(),
)
}
override fun onAdClicked(interstitialAdUnit: AudienzzInterstitialAdUnit) {}
override fun onAdClosed(interstitialAdUnit: AudienzzInterstitialAdUnit) {}
})
button.addOnBecameVisibleOnScreenListener { videoAdUnit?.loadAd() }
}
override fun onDetach() {
displayAdUnit?.destroy()
videoAdUnit?.destroy()
}
companion object {
private const val DISPLAY_AD_UNIT_ID = "/21808260008/prebid_oxb_html_interstitial"
private const val DISPLAY_CONFIG_ID = "prebid-demo-display-interstitial-320-480"
private const val VIDEO_AD_UNIT_ID =
"/21808260008/prebid_oxb_interstitial_video"
const val VIDEO_CONFIG_ID = "prebid-demo-video-interstitial-320-480"
private const val FALLBACK_AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712"
}
}
| 0
|
Kotlin
|
0
| 0
|
e49072379d8e09863972f2585e4268c01d03ccab
| 4,793
|
audienzz-android-sdk
|
Apache License 2.0
|
src/main/kotlin/ui/packages/PackagesViewModel.kt
|
oss-review-toolkit
| 436,895,138
| false
| null |
package org.ossreviewtoolkit.workbench.ui.packages
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.ossreviewtoolkit.model.Identifier
import org.ossreviewtoolkit.model.Package
import org.ossreviewtoolkit.model.PackageCurationResult
import org.ossreviewtoolkit.model.Provenance
import org.ossreviewtoolkit.model.ScanResult
import org.ossreviewtoolkit.model.ScannerDetails
import org.ossreviewtoolkit.model.licenses.ResolvedLicenseInfo
import org.ossreviewtoolkit.utils.spdx.SpdxSingleLicenseExpression
import org.ossreviewtoolkit.workbench.model.DependencyReference
import org.ossreviewtoolkit.workbench.model.FilterData
import org.ossreviewtoolkit.workbench.model.OrtModel
import org.ossreviewtoolkit.workbench.model.ResolvedIssue
import org.ossreviewtoolkit.workbench.model.ResolvedRuleViolation
import org.ossreviewtoolkit.workbench.model.ResolvedVulnerability
import org.ossreviewtoolkit.workbench.utils.SpdxExpressionStringComparator
import org.ossreviewtoolkit.workbench.utils.matchAnyValue
import org.ossreviewtoolkit.workbench.utils.matchExclusionStatus
import org.ossreviewtoolkit.workbench.utils.matchIssueStatus
import org.ossreviewtoolkit.workbench.utils.matchString
import org.ossreviewtoolkit.workbench.utils.matchStringContains
import org.ossreviewtoolkit.workbench.utils.matchViolationStatus
import org.ossreviewtoolkit.workbench.utils.matchVulnerabilityStatus
class PackagesViewModel(private val ortModel: OrtModel = OrtModel.INSTANCE) {
private val scope = CoroutineScope(Dispatchers.Default)
private val packages = MutableStateFlow(emptyList<PackageInfo>())
private val filter = MutableStateFlow(PackagesFilter())
private val _state = MutableStateFlow(PackagesState.INITIAL)
val state: StateFlow<PackagesState> get() = _state
init {
scope.launch {
ortModel.api.collect { api ->
val projectPackages = api.result.getProjects().mapTo(mutableSetOf()) {
it.toPackage().toCuratedPackage()
}
val projectsAndPackages = (projectPackages + api.result.getPackages()).sortedBy { it.metadata.id }
packages.value = projectsAndPackages.map { pkg ->
val references = api.getReferences(pkg.metadata.id)
val issues = api.getIssues().filter { it.id == pkg.metadata.id }
val violations = api.getViolations().filter { it.pkg == pkg.metadata.id }
val vulnerabilities = api.getVulnerabilities().filter { it.pkg == pkg.metadata.id }
val scanResultInfos = api.getScanResults(pkg.metadata.id).map { it.toInfo() }
PackageInfo(
metadata = pkg.metadata,
curations = pkg.curations,
resolvedLicenseInfo = api.licenseInfoResolver.resolveLicenseInfo(pkg.metadata.id),
references = references,
issues = issues,
violations = violations,
vulnerabilities = vulnerabilities,
scanResultInfos = scanResultInfos
)
}
}
}
scope.launch { packages.collect { initState(it) } }
scope.launch {
filter.collect { newFilter ->
val oldState = state.value
_state.value = oldState.copy(
packages = packages.value.filter(newFilter::check),
textFilter = newFilter.text,
exclusionStatusFilter = oldState.exclusionStatusFilter.copy(
selectedItem = newFilter.exclusionStatus
),
issueStatusFilter = oldState.issueStatusFilter.copy(selectedItem = newFilter.issueStatus),
licenseFilter = oldState.licenseFilter.copy(selectedItem = newFilter.license),
namespaceFilter = oldState.namespaceFilter.copy(selectedItem = newFilter.namespace),
projectFilter = oldState.projectFilter.copy(selectedItem = newFilter.project),
scopeFilter = oldState.scopeFilter.copy(selectedItem = newFilter.scope),
typeFilter = oldState.typeFilter.copy(selectedItem = newFilter.type),
violationStatusFilter = oldState.violationStatusFilter.copy(
selectedItem = newFilter.violationStatus
),
vulnerabilityStatusFilter = oldState.vulnerabilityStatusFilter.copy(
selectedItem = newFilter.vulnerabilityStatus
)
)
}
}
}
private fun initState(packages: List<PackageInfo>) {
_state.value = PackagesState(
packages = packages,
textFilter = "",
exclusionStatusFilter = FilterData(ExclusionStatus.values().toList()),
issueStatusFilter = FilterData(IssueStatus.values().toList()),
licenseFilter = FilterData(
packages.flatMapTo(sortedSetOf(SpdxExpressionStringComparator())) {
it.resolvedLicenseInfo.licenses.map { it.license }
}.toList()
),
namespaceFilter = FilterData(packages.mapTo(sortedSetOf()) { it.metadata.id.namespace }.toList()),
projectFilter = FilterData(packages.flatMapTo(sortedSetOf()) { it.references.map { it.project } }.toList()),
scopeFilter = FilterData(
packages.flatMapTo(sortedSetOf()) {
it.references.flatMap { it.scopes.map { it.scope } }
}.toList()
),
typeFilter = FilterData(packages.mapTo(sortedSetOf()) { it.metadata.id.type }.toList()),
violationStatusFilter = FilterData(ViolationStatus.values().toList()),
vulnerabilityStatusFilter = FilterData(VulnerabilityStatus.values().toList())
)
}
fun updateTextFilter(text: String) {
filter.value = filter.value.copy(text = text)
}
fun updateExclusionStatusFilter(exclusionStatus: ExclusionStatus?) {
filter.value = filter.value.copy(exclusionStatus = exclusionStatus)
}
fun updateIssueStatusFilter(issueStatus: IssueStatus?) {
filter.value = filter.value.copy(issueStatus = issueStatus)
}
fun updateLicenseFilter(license: SpdxSingleLicenseExpression?) {
filter.value = filter.value.copy(license = license)
}
fun updateNamespaceFilter(namespace: String?) {
filter.value = filter.value.copy(namespace = namespace)
}
fun updateProjectFilter(project: Identifier?) {
filter.value = filter.value.copy(project = project)
}
fun updateScopeFilter(scope: String?) {
filter.value = filter.value.copy(scope = scope)
}
fun updateTypeFilter(type: String?) {
filter.value = filter.value.copy(type = type)
}
fun updateViolationStatusFilter(violationStatus: ViolationStatus?) {
filter.value = filter.value.copy(violationStatus = violationStatus)
}
fun updateVulnerabilityStatusFilter(vulnerabilityStatus: VulnerabilityStatus?) {
filter.value = filter.value.copy(vulnerabilityStatus = vulnerabilityStatus)
}
}
data class PackageInfo(
val metadata: Package,
val curations: List<PackageCurationResult>,
val resolvedLicenseInfo: ResolvedLicenseInfo,
val references: List<DependencyReference>,
val issues: List<ResolvedIssue>,
val violations: List<ResolvedRuleViolation>,
val vulnerabilities: List<ResolvedVulnerability>,
val scanResultInfos: List<ScanResultInfo>
) {
fun isExcluded() = references.all { it.isExcluded || it.scopes.all { it.isExcluded } }
}
data class ScanResultInfo(
val scanner: ScannerDetails,
val provenance: Provenance
)
data class PackagesFilter(
val text: String = "",
val type: String? = null,
val namespace: String? = null,
val project: Identifier? = null,
val scope: String? = null,
val license: SpdxSingleLicenseExpression? = null,
val issueStatus: IssueStatus? = null,
val violationStatus: ViolationStatus? = null,
val vulnerabilityStatus: VulnerabilityStatus? = null,
val exclusionStatus: ExclusionStatus? = null
) {
fun check(pkg: PackageInfo) =
matchStringContains(text, pkg.metadata.id.toCoordinates())
&& matchString(type, pkg.metadata.id.type)
&& matchString(namespace, pkg.metadata.id.namespace)
&& matchAnyValue(project, pkg.references.map { it.project })
&& matchString(scope, pkg.references.flatMap { it.scopes.map { it.scope } })
&& matchAnyValue(license, pkg.resolvedLicenseInfo.licenses.map { it.license })
&& matchIssueStatus(issueStatus, pkg.issues)
&& matchViolationStatus(violationStatus, pkg.violations)
&& matchVulnerabilityStatus(vulnerabilityStatus, pkg.vulnerabilities)
&& matchExclusionStatus(exclusionStatus, pkg.isExcluded())
}
enum class IssueStatus {
HAS_ISSUES,
NO_ISSUES
}
enum class ViolationStatus {
HAS_VIOLATIONS,
NO_VIOLATIONS
}
enum class VulnerabilityStatus {
HAS_VULNERABILITY,
NO_VULNERABILITY
}
enum class ExclusionStatus {
EXCLUDED,
INCLUDED
}
private fun ScanResult.toInfo() = ScanResultInfo(scanner, provenance)
| 8
|
Kotlin
|
1
| 17
|
d8045a290020a536fa3391f15c10b3d5c78f6ce6
| 9,609
|
ort-workbench
|
Apache License 2.0
|
lib/src/main/java/com/niallermoran/charteasy/Helper.kt
|
niallermoran
| 719,766,312
| false
|
{"Kotlin": 88852}
|
import android.graphics.Color
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.niallermoran.charteasy.AxisLabel
import com.niallermoran.charteasy.AxisType
import com.niallermoran.charteasy.BottomAxisArea
import com.niallermoran.charteasy.Config
import com.niallermoran.charteasy.Dimensions
import com.niallermoran.charteasy.LeftAxisArea
import com.niallermoran.charteasy.OffsetDp
import com.niallermoran.charteasy.PlotArea
import com.niallermoran.charteasy.RightAxisArea
import com.niallermoran.charteasy.SizeDp
import com.niallermoran.charteasy.VerticalAxisConfig
import kotlin.math.ceil
import kotlin.random.Random
/**
* Calculates all required dimensions for the chart to be built
*/
fun calculateDimensions(
density: Density,
textMeasurer: TextMeasurer,
availableHeight: Dp,
availableWidth: Dp,
config: Config
): Dimensions {
val dimensions = Dimensions()
dimensions.chart.chartSize =
SizeDp(width = availableWidth, height = availableHeight)
val points = if (config.leftAxisConfig.type == AxisType.Bar) config.leftAxisConfig.dataPoints else config.leftAxisConfig.dataPoints.sortedBy { it.xValue }
val pointsWithRightValue = points.filter { it.yValueRightAxis != null }
// calculate data specific dimensions
dimensions.dataValues.points = points
dimensions.dataValues.yMin = config.leftAxisConfig.minY ?: dimensions.dataValues.points.minOf { it.yValue }
dimensions.dataValues.yMax = config.leftAxisConfig.maxY ?: dimensions.dataValues.points.maxOf { it.yValue }
dimensions.dataValues.yMinRight = config.rightAxisConfig?.minY ?: if( pointsWithRightValue.isEmpty() ) 0f else dimensions.dataValues.points.filter { it.yValueRightAxis != null }.minOf { it.yValueRightAxis!! }
dimensions.dataValues.yMaxRight = config.rightAxisConfig?.maxY ?: if( pointsWithRightValue.isEmpty() ) 0f else dimensions.dataValues.points.filter { it.yValueRightAxis != null }.maxOf { it.yValueRightAxis!! }
dimensions.dataValues.xMin = dimensions.dataValues.points.minOf { it.xValue }
dimensions.dataValues.xMax = dimensions.dataValues.points.maxOf { it.xValue }
// calculate dimensions for chart axes and plot area
calculateAxisDimensions(
config = config,
dimensions = dimensions,
textMeasurer = textMeasurer,
density = density
)
calculateLabels(
config = config,
dimensions = dimensions,
textMeasurer = textMeasurer
)
return dimensions
}
fun getRandomColour() : Int
{
val random = Color.argb(255, Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))
return random
}
/**
* Calculates the position for all labels and ticks for all axes in Dp
*/
private fun calculateLabels(
config: Config,
dimensions: Dimensions,
textMeasurer: TextMeasurer
) {
val points = dimensions.dataValues.points
// get left axis labels/ticks
if (config.leftAxisConfig.displayLabels || config.leftAxisConfig.displayTicks) {
val axisConfig = config.leftAxisConfig
val formatter = axisConfig.formatAxisLabel
val labelCount =
if (axisConfig.maxNumberOfLabelsToDisplay == null || axisConfig.maxNumberOfLabelsToDisplay > points.size) points.size else axisConfig.maxNumberOfLabelsToDisplay
val distanceBetweenTicks = dimensions.chart.plotArea.innerHeight / (labelCount - 1)
// add tick and label dimensions
for (i: Int in 0..<labelCount) {
val distanceAlongYAxis = i.dp * distanceBetweenTicks.value
// get the value of x that would be represented by the label
val yValue =
dimensions.dataValues.yMin + ((dimensions.dataValues.yMax - dimensions.dataValues.yMin) * i / (labelCount - 1))
val labelText = if (formatter == null) String.format(
java.util.Locale.ENGLISH,
"%.2f",
yValue
) else formatter(yValue)
val textMeasure = textMeasurer.measure(labelText, style = axisConfig.labelStyle)
val label = AxisLabel(text = textMeasure, distanceAlongYAxis)
dimensions.leftAxisLabels.add(label)
}
}
// get right axis labels/ticks
if (config.rightAxisConfig != null && (config.rightAxisConfig.displayLabels || config.rightAxisConfig.displayTicks)) {
val axisConfig = config.rightAxisConfig
val formatter = axisConfig.formatAxisLabel
val labelCount =
if (axisConfig.maxNumberOfLabelsToDisplay == null || axisConfig.maxNumberOfLabelsToDisplay > points.size) points.size else axisConfig.maxNumberOfLabelsToDisplay
val distanceBetweenTicks = dimensions.chart.plotArea.innerHeight / (labelCount - 1)
// add tick and label dimensions
for (i: Int in 0..<labelCount) {
val distanceAlongYAxis = i.dp * distanceBetweenTicks.value
// get the value of x that would be represented by the label
val yValue =
dimensions.dataValues.yMinRight + ((dimensions.dataValues.yMaxRight - dimensions.dataValues.yMinRight) * i / (labelCount - 1))
val labelText = if (formatter == null) String.format(
java.util.Locale.ENGLISH,
"%.2f",
yValue
) else formatter(yValue)
val textMeasure = textMeasurer.measure(labelText, style = axisConfig.labelStyle)
val label = AxisLabel(text = textMeasure, distanceAlongYAxis)
dimensions.rightAxisLabels.add(label)
}
}
// get bottom axis labels/ticks
if (config.bottomAxisConfig.displayLabels || config.bottomAxisConfig.displayTicks)
{
val bottomAxisFormatter = config.bottomAxisConfig.formatAxisLabel
val bottomAxisLabelCount =
if (config.bottomAxisConfig.maxNumberOfLabelsToDisplay > points.size
) points.size
else config.bottomAxisConfig.maxNumberOfLabelsToDisplay
val distanceBetweenTicks =
dimensions.chart.plotArea.innerWidth / (bottomAxisLabelCount - 1)
// if either vertical axis is a bar chart then the ticks and labels must
// align with actual x values whereas for line charts the x-values can be equally dispersed
if (config.leftAxisConfig.type == AxisType.Bar || ( config.rightAxisConfig != null && config.rightAxisConfig.type == AxisType.Bar) ) {
// for bar chart each point gets a label as long as we don;t go over the max
// each point gets a tick
points.forEachIndexed { index, chartPoint ->
// we can only show up to maxLabelsToDisplay, but we will alwyas show first and last
var showLabel = if( index == 0 || index == dimensions.dataValues.points.size - 1) true else false
// calculate how many labels should be displayed for every data point
val skip = if( config.bottomAxisConfig.maxNumberOfLabelsToDisplay >= dimensions.dataValues.points.size) 1
else ceil( dimensions.dataValues.points.size.toDouble() / config.bottomAxisConfig.maxNumberOfLabelsToDisplay ).toInt()
if ( index % skip == 0 && config.bottomAxisConfig.maxNumberOfLabelsToDisplay != 2)
showLabel = true
if( showLabel == true) {
val distanceAlongXAxis = index.dp * distanceBetweenTicks.value
val labelText = if (bottomAxisFormatter == null) String.format(
java.util.Locale.ENGLISH,
"%.2f",
chartPoint.xValue
) else bottomAxisFormatter(chartPoint.xValue)
val textMeasure =
textMeasurer.measure(labelText, style = config.bottomAxisConfig.labelStyle)
dimensions.bottomAxisLabels.add(
AxisLabel(
text = textMeasure,
centerDistanceAlongAxis = distanceAlongXAxis
)
)
}
}
} else {
// for lines the bottom axis labels represent values equally divided amongst width
for (i: Int in 0..<bottomAxisLabelCount) {
val distanceAlongXAxis = i.dp * distanceBetweenTicks.value
// get the value of x that would be represented by the label
val xValue =
dimensions.dataValues.xMin + ((dimensions.dataValues.xMax - dimensions.dataValues.xMin) * i / (bottomAxisLabelCount - 1))
val labelText = if (bottomAxisFormatter == null) String.format(
java.util.Locale.ENGLISH,
"%.2f",
xValue
) else bottomAxisFormatter(xValue)
val textMeasure =
textMeasurer.measure(labelText, style = config.bottomAxisConfig.labelStyle)
val label = AxisLabel(text = textMeasure, distanceAlongXAxis)
dimensions.bottomAxisLabels.add(label)
}
}
}
}
/**
* Gets a list of labels for the appropriate axis and adds to dimensions
*/
private fun getVerticalAxisLabels(
config: VerticalAxisConfig,
dimensions: Dimensions,
textMeasurer: TextMeasurer,
):ArrayList<AxisLabel> {
val points = dimensions.dataValues.points
val formatter = config.formatAxisLabel
val labelCount = if (config.maxNumberOfLabelsToDisplay == null || config.maxNumberOfLabelsToDisplay > points.size) points.size else config.maxNumberOfLabelsToDisplay
val labelsList: ArrayList<AxisLabel> = ArrayList()
val distanceBetweenTicks = dimensions.chart.plotArea.innerHeight/(labelCount-1)
// add tick and label dimensions
for (i: Int in 0..<labelCount) {
val distanceAlongYAxis = i.dp * distanceBetweenTicks.value
// get the value of x that would be represented by the label
val yValue = dimensions.dataValues.yMin + ((dimensions.dataValues.yMax - dimensions.dataValues.xMin) * i / (labelCount-1))
val labelText = if (formatter == null) String.format(
java.util.Locale.ENGLISH,
"%.2f",
yValue
) else formatter(yValue)
val textMeasure = textMeasurer.measure(labelText, style = config.labelStyle)
val label = AxisLabel(text = textMeasure, distanceAlongYAxis)
labelsList.add(label)
}
return labelsList
}
/**
* Calculates the width of the left axis and the height of the bottom axis in Dp
*/
private fun calculateAxisDimensions(
density: Density,
config: Config,
dimensions: Dimensions,
textMeasurer: TextMeasurer
) {
val formatLeftAxisLabelLambda = config.leftAxisConfig.formatAxisLabel
val formatRightAxisLabelLambda = config.rightAxisConfig?.formatAxisLabel
val formatBottomAxisLabelLambda = config.bottomAxisConfig.formatAxisLabel
val yTextLeft = if (formatLeftAxisLabelLambda != null) formatLeftAxisLabelLambda(
dimensions.dataValues.yMax
) else String.format(java.util.Locale.ENGLISH, "%.2f", dimensions.dataValues.yMax)
val yTextRight = if (formatRightAxisLabelLambda != null) formatRightAxisLabelLambda(
dimensions.dataValues.yMax
) else String.format(java.util.Locale.ENGLISH, "%.2f", dimensions.dataValues.yMaxRight)
val xText = if (formatBottomAxisLabelLambda != null) formatBottomAxisLabelLambda(
dimensions.dataValues.xMax
) else String.format(java.util.Locale.ENGLISH, "%.2f", dimensions.dataValues.xMax)
// calculate bottom axis height
var bottomAxisHeight =
config.bottomAxisConfig.labelPadding.calculateBottomPadding().value + config.bottomAxisConfig.labelPadding.calculateTopPadding().value
if (config.bottomAxisConfig.displayTicks) {
bottomAxisHeight += config.bottomAxisConfig.tickLength.value
}
if (config.bottomAxisConfig.displayLabels) {
// text measures return pixels
with(density) {
bottomAxisHeight += textMeasurer.measure(
text = xText,
style = config.bottomAxisConfig.labelStyle,
maxLines = config.bottomAxisConfig.labelMaxLines
).size.height.toDp().value
}
}
// calculate the vertical axis widths
var leftAxisWidth = 0.dp
if( config.leftAxisConfig.display ) {
config.leftAxisConfig.labelPadding.calculateLeftPadding(LayoutDirection.Ltr) + config.leftAxisConfig.labelPadding.calculateRightPadding(
LayoutDirection.Ltr
)
if (config.leftAxisConfig.displayLabels) {
with(density) {
val labelWidth = textMeasurer.measure(
yTextLeft,
style = config.leftAxisConfig.labelStyle,
maxLines = config.leftAxisConfig.labelMaxLines
).size.width.toDp()
leftAxisWidth += labelWidth
}
}
if (config.leftAxisConfig.displayTicks) {
leftAxisWidth += config.leftAxisConfig.tickLength
}
}
var rightAxisWidth = 0.dp
if( config.rightAxisConfig != null && config.rightAxisConfig.display ) {
config.rightAxisConfig.labelPadding.calculateLeftPadding(LayoutDirection.Ltr) + config.rightAxisConfig.labelPadding.calculateRightPadding(
LayoutDirection.Ltr
)
if (config.rightAxisConfig.displayLabels) {
with(density) {
val labelWidth = textMeasurer.measure(
yTextRight,
style = config.rightAxisConfig.labelStyle,
maxLines = config.rightAxisConfig.labelMaxLines
).size.width.toDp()
rightAxisWidth += labelWidth
}
}
if (config.rightAxisConfig.displayTicks) {
rightAxisWidth += config.rightAxisConfig.tickLength
}
}
dimensions.chart.bottomAxisArea = BottomAxisArea(
size = SizeDp(
width = dimensions.chart.chartSize.width - leftAxisWidth.value.dp - rightAxisWidth.value.dp,
height = bottomAxisHeight.dp
),
offset = OffsetDp(
leftAxisWidth.value.dp,
dimensions.chart.chartSize.height - bottomAxisHeight.dp
)
)
dimensions.chart.leftAxisArea = LeftAxisArea(
size = SizeDp(
width = leftAxisWidth.value.dp,
height = dimensions.chart.chartSize.height - bottomAxisHeight.dp
),
topLeftOffset = OffsetDp(0.dp, 0.dp)
)
dimensions.chart.rightAxisArea = RightAxisArea(
size = SizeDp(
width = rightAxisWidth.value.dp,
height = dimensions.chart.chartSize.height - bottomAxisHeight.dp
),
topLeftOffset = OffsetDp( dimensions.chart.chartSize.width.value.dp - leftAxisWidth - rightAxisWidth , 0.dp)
)
val plotAreaOuterWidth = dimensions.chart.chartSize.width - leftAxisWidth - rightAxisWidth
val plotAreaOuterHeight = dimensions.chart.chartSize.height - bottomAxisHeight.dp
// calculate padding for plot area
var padding = config.chartConfig.plotAreaPadding ?: PaddingValues(0.dp)
var barWidth = 0.dp
// calculate bar widths for left and/or right axis
if (config.leftAxisConfig.type == AxisType.Bar || config.rightAxisConfig?.type == AxisType.Bar) {
// calculate the bar width allowing for half a width padding at start and right
val numberOfBars = dimensions.dataValues.points.size
val barWidthFraction = config.chartConfig.barChartFraction
// calculate auto padding
if (config.chartConfig.plotAreaPadding == null) {
val divisor = (numberOfBars / barWidthFraction ) + ( numberOfBars + 1 )
val space = plotAreaOuterWidth / divisor
padding = PaddingValues(
start = space,
end = space
)
barWidth = space / barWidthFraction
}
// calculate padding when defined
if (config.chartConfig.plotAreaPadding != null) {
val innerWidth = plotAreaOuterWidth -config.chartConfig.plotAreaPadding.calculateLeftPadding(LayoutDirection.Ltr) - config.chartConfig.plotAreaPadding.calculateRightPadding(LayoutDirection.Ltr)
val divisor = (numberOfBars / barWidthFraction) + numberOfBars.toFloat() - 1
val space = innerWidth / divisor
padding = PaddingValues(
start = config.chartConfig.plotAreaPadding.calculateLeftPadding(LayoutDirection.Ltr),
end = config.chartConfig.plotAreaPadding.calculateRightPadding(LayoutDirection.Ltr)
)
barWidth = space / barWidthFraction
}
}
dimensions.chart.plotArea = PlotArea(
size = SizeDp(
width = plotAreaOuterWidth,
height = plotAreaOuterHeight
),
offset = OffsetDp(
leftAxisWidth,
0.dp
),
padding = padding,
innerTopLeftOffset = OffsetDp(
leftAxisWidth + padding.calculateLeftPadding(LayoutDirection.Ltr).value.dp,
padding.calculateTopPadding().value.dp
),
barWidth = barWidth
)
}
| 2
|
Kotlin
|
0
| 1
|
f4ee0c6450f7acd332ebe2b06f1123412d92f0a1
| 17,700
|
ChartEasy
|
Apache License 2.0
|
shipments/src/androidTest/java/com/calebk/shipments/shipment/ShipmentScreenTest.kt
|
CalebKL
| 867,208,470
| false
|
{"Kotlin": 149963}
|
/*
* Copyright 2024 Movemate
*
* 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.calebk.shipments.shipment
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.isDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.calebk.shipments.ui.shipment.ShipmentScreen
import com.calebk.shipments.utils.FakeGeneratorUtil.fakeShipmentItems
import org.junit.Rule
import org.junit.Test
class ShipmentScreenTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun testShipmentScreen_initialState_display() {
composeTestRule.setContent {
ShipmentScreen(
shipmentHistory = fakeShipmentItems,
loading = false,
navigateBackHome = {},
)
}
composeTestRule
.onNodeWithText("Shipment History")
.assertIsDisplayed()
composeTestRule
.onNodeWithTag("Navigation bar Items")
.assertIsDisplayed()
}
@Test
fun testBackButton_Navigates_Back_toHomePage() {
composeTestRule.setContent {
ShipmentScreen(
shipmentHistory = fakeShipmentItems,
loading = false,
navigateBackHome = {},
)
}
composeTestRule
.onNodeWithTag("Back Button")
.performClick()
composeTestRule.onNodeWithContentDescription("Search Bar").isDisplayed()
}
}
| 0
|
Kotlin
|
0
| 0
|
3d7a428df7452dd465bf137a5b0b1ea6e5cb8ba7
| 2,197
|
Movemate
|
Apache License 2.0
|
buildSrc/src/main/kotlin/Extensions.kt
|
Kr1ptal
| 712,963,462
| false
|
{"Kotlin": 1200581, "Solidity": 28773}
|
fun isLibraryReleaseMode(): Boolean {
return System.getenv("LIB_RELEASE").equals("true", ignoreCase = true)
}
| 13
|
Kotlin
|
8
| 23
|
3885bbfa3bb190a2adba23b692593ab36165bb55
| 114
|
ethers-kt
|
Apache License 2.0
|
OrderCenter/src/main/java/com/kotlin/order/event/SelectAddressEvent.kt
|
heisexyyoumo
| 145,665,152
| false
|
{"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "Proguard": 8, "Kotlin": 218, "XML": 116, "Java": 14}
|
package com.kotlin.order.event
import com.kotlin.order.data.protocol.ShipAddress
class SelectAddressEvent(val address: ShipAddress)
| 0
|
Kotlin
|
1
| 2
|
27fea0090cea5fb636f8db5025379d274693b1b4
| 133
|
KotlinMall
|
Apache License 2.0
|
src/main/kotlin/org/ionproject/integration/domain/common/Programme.kt
|
i-on-project
| 243,606,271
| false
| null |
package org.ionproject.integration.domain.common
data class Programme(
var name: String = "",
var acr: String = ""
)
| 10
|
Kotlin
|
0
| 3
|
d221d71dd5252da878953f2a0a93734a720a5290
| 126
|
integration
|
Apache License 2.0
|
defitrack-protocols/src/main/java/io/defitrack/protocol/set/PolygonSetProvider.kt
|
decentri-fi
| 426,174,152
| false
|
{"Kotlin": 1038532, "Java": 1948, "Dockerfile": 909}
|
package io.defitrack.protocol.set
import io.defitrack.common.network.Network
import io.ktor.client.*
import org.springframework.stereotype.Component
@Component
class PolygonSetProvider(
httpClient: HttpClient
) : AbstractSetProvider(
Network.POLYGON,
"https://raw.githubusercontent.com/decentri-fi/data/master/protocols/set/set.polygon.tokenlist.json",
httpClient
) {
override fun extraSets(): List<String> {
return listOf(
"0x3ad707da309f3845cd602059901e39c4dcd66473",
"0xf287d97b6345bad3d88856b26fb7c0ab3f2c7976"
)
}
}
| 53
|
Kotlin
|
7
| 9
|
e65843453e4c44f5c2626870ceb923eb7ab3c4d0
| 586
|
defi-hub
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Trillium.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.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.rounded.Icons
public val Icons.Bold.Trillium: ImageVector
get() {
if (_trillium != null) {
return _trillium!!
}
_trillium = Builder(name = "Trillium", defaultWidth = 24.0.dp, defaultHeight = 24.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(13.5f, 13.073f)
curveToRelative(0.0f, 0.828f, -0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
close()
moveTo(23.668f, 19.828f)
curveToRelative(-0.347f, 0.62f, -0.917f, 1.063f, -1.606f, 1.249f)
curveToRelative(-2.283f, 0.616f, -4.206f, 0.925f, -5.754f, 0.925f)
curveToRelative(-0.771f, 0.0f, -1.449f, -0.077f, -2.033f, -0.23f)
curveToRelative(-0.395f, 0.668f, -0.964f, 1.347f, -1.434f, 1.859f)
curveToRelative(-0.453f, 0.493f, -1.229f, 0.493f, -1.682f, 0.0f)
curveToRelative(-0.471f, -0.512f, -1.04f, -1.191f, -1.434f, -1.859f)
curveToRelative(-1.755f, 0.461f, -4.366f, 0.229f, -7.788f, -0.695f)
curveToRelative(-0.688f, -0.186f, -1.258f, -0.629f, -1.605f, -1.249f)
curveToRelative(-0.346f, -0.619f, -0.426f, -1.336f, -0.224f, -2.018f)
curveToRelative(0.903f, -3.054f, 1.942f, -5.255f, 3.099f, -6.575f)
curveToRelative(-0.465f, -0.667f, -0.858f, -1.544f, -1.128f, -2.236f)
curveToRelative(-0.243f, -0.624f, 0.097f, -1.32f, 0.739f, -1.51f)
curveToRelative(0.864f, -0.256f, 2.055f, -0.538f, 2.959f, -0.481f)
curveToRelative(0.516f, -1.713f, 1.974f, -3.798f, 4.352f, -6.222f)
curveToRelative(0.996f, -1.014f, 2.746f, -1.013f, 3.742f, 0.0f)
curveToRelative(2.378f, 2.424f, 3.836f, 4.509f, 4.352f, 6.223f)
curveToRelative(0.904f, -0.058f, 2.095f, 0.224f, 2.959f, 0.481f)
curveToRelative(0.642f, 0.19f, 0.983f, 0.887f, 0.739f, 1.51f)
curveToRelative(-0.27f, 0.692f, -0.662f, 1.569f, -1.128f, 2.236f)
curveToRelative(1.158f, 1.321f, 2.196f, 3.522f, 3.098f, 6.576f)
curveToRelative(0.202f, 0.681f, 0.123f, 1.396f, -0.224f, 2.017f)
close()
moveTo(20.899f, 18.281f)
curveToRelative(-1.006f, -3.261f, -2.143f, -5.107f, -2.845f, -5.498f)
curveToRelative(-0.532f, -0.298f, -1.147f, -0.457f, -1.798f, -0.427f)
curveToRelative(-0.557f, -0.012f, -1.052f, -0.271f, -1.326f, -0.742f)
curveToRelative(-0.275f, -0.469f, -0.274f, -1.05f, 0.0f, -1.519f)
curveToRelative(0.334f, -0.566f, 0.503f, -1.161f, 0.503f, -1.768f)
curveToRelative(0.0f, -0.8f, -1.064f, -2.691f, -3.435f, -5.162f)
curveToRelative(-2.37f, 2.471f, -3.435f, 4.362f, -3.435f, 5.162f)
curveToRelative(0.0f, 0.605f, 0.169f, 1.2f, 0.503f, 1.767f)
curveToRelative(0.276f, 0.469f, 0.277f, 1.05f, 0.002f, 1.52f)
curveToRelative(-0.275f, 0.469f, -0.789f, 0.743f, -1.326f, 0.742f)
curveToRelative(-0.663f, -0.016f, -1.266f, 0.13f, -1.799f, 0.427f)
curveToRelative(-0.701f, 0.391f, -1.838f, 2.237f, -2.845f, 5.498f)
curveToRelative(3.322f, 0.854f, 5.5f, 0.855f, 6.202f, 0.464f)
curveToRelative(0.578f, -0.321f, 1.055f, -0.809f, 1.378f, -1.409f)
curveToRelative(0.262f, -0.485f, 0.769f, -0.788f, 1.32f, -0.788f)
reflectiveCurveToRelative(1.059f, 0.303f, 1.32f, 0.788f)
curveToRelative(0.324f, 0.601f, 0.8f, 1.088f, 1.378f, 1.409f)
curveToRelative(0.702f, 0.392f, 2.88f, 0.39f, 6.201f, -0.464f)
close()
}
}
.build()
return _trillium!!
}
private var _trillium: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,880
|
icons
|
MIT License
|
app/src/main/java/com/lovenottiesmobile/lovenotties_v1/LoadingActivity.kt
|
ST10084225
| 727,899,202
| false
|
{"Kotlin": 64879}
|
package com.lovenottiesmobile.lovenotties_v1
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.google.android.material.bottomnavigation.BottomNavigationView
class BlogPagesIBT : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_blog_pages_ibt)
//Nav Bar
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigation)
bottomNavigationView.selectedItemId = R.id.bottom_stories
//CardViews
val whatsOn = findViewById<TextView>(R.id.textViewBlog)
val environment = findViewById<TextView>(R.id.textViewSS)
val humanity = findViewById<TextView>(R.id.textViewOP)
val layout = findViewById<LinearLayout>(R.id.mainLin)
val layoutHeader = findViewById<LinearLayout>(R.id.HeaderLayout)
//setup background gradient animations
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
val animDrawable = layout.background as AnimationDrawable
animDrawable.setEnterFadeDuration(750)
animDrawable.setExitFadeDuration(1500)
animDrawable.start()
val animDrawable2 = layoutHeader.background as AnimationDrawable
animDrawable2.setEnterFadeDuration(750)
animDrawable2.setExitFadeDuration(1500)
animDrawable2.start()
val animDrawable3 = bottomNavigationView.background as AnimationDrawable
animDrawable3.setEnterFadeDuration(750)
animDrawable3.setExitFadeDuration(1500)
animDrawable3.start()
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.bottom_home -> {
startActivity(Intent(applicationContext, LoadingActivity::class.java))
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
finish()
true
}
R.id.bottom_stories -> {
startActivity(Intent(applicationContext, BlogPagesIBT::class.java))
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
finish()
true
}
R.id.bottom_info -> {
startActivity(Intent(applicationContext, Info::class.java))
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
finish()
true
}
R.id.bottom_donate -> {
startActivity(Intent(applicationContext, Donate::class.java))
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
finish()
true
}
else -> false
}
}//Nav bar nav ends
// For the 3 Buttons
whatsOn.setOnClickListener {
val intent = Intent(this, Blog::class.java)
startActivity(intent)
}
environment.setOnClickListener {
val intent = Intent(this, SuccessStories::class.java)
startActivity(intent)
}
humanity.setOnClickListener {
val intent = Intent(this, OurPeople::class.java)
startActivity(intent)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3fbf15e56594864c6305c0c87674763daa4bacbc
| 3,620
|
LoveNottiesApp
|
MIT License
|
presentation/src/main/java/com/krakert/tracker/ui/tracker/overview/TrackerOverviewScreen.kt
|
Krakert
| 500,599,145
| false
| null |
package com.krakert.tracker.ui.tracker.overview
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.rotary.onRotaryScrollEvent
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavHostController
import androidx.wear.compose.foundation.ExperimentalWearFoundationApi
import androidx.wear.compose.foundation.lazy.AutoCenteringParams
import androidx.wear.compose.foundation.lazy.ScalingLazyColumn
import androidx.wear.compose.foundation.lazy.ScalingLazyListState
import androidx.wear.compose.foundation.rememberActiveFocusRequester
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.PositionIndicator
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.Vignette
import androidx.wear.compose.material.VignettePosition
import com.krakert.tracker.ui.components.CenterElement
import com.krakert.tracker.ui.components.Divider
import com.krakert.tracker.ui.components.Loading
import com.krakert.tracker.ui.components.OnDisplay
import com.krakert.tracker.ui.components.OnError
import com.krakert.tracker.ui.components.OnLoading
import com.krakert.tracker.ui.components.Screen
import com.krakert.tracker.ui.components.ShowProblem
import com.krakert.tracker.ui.tracker.model.ProblemState.EMPTY
import com.krakert.tracker.ui.tracker.model.ProblemState.SSL
import com.krakert.tracker.ui.tracker.overview.components.OverviewBottomBar
import com.krakert.tracker.ui.tracker.overview.components.OverviewMarketChart
import com.krakert.tracker.ui.tracker.overview.model.OverviewCoinDisplay
import kotlinx.coroutines.launch
@Composable
fun TrackerOverviewScreen(
viewModel: OverviewViewModel,
navController: NavHostController,
lifeCycleOwner: LifecycleOwner = LocalLifecycleOwner.current
) {
val scrollState = ScalingLazyListState()
Scaffold(
timeText = {
if (!scrollState.isScrollInProgress) {
TimeText()
}
},
vignette = {
Vignette(vignettePosition = VignettePosition.TopAndBottom)
},
positionIndicator = {
PositionIndicator(
scalingLazyListState = scrollState
)
}
) {
DisposableEffect(lifeCycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
viewModel.getAllOverviewData()
}
}
lifeCycleOwner.lifecycle.addObserver(observer)
onDispose {
lifeCycleOwner.lifecycle.removeObserver(observer)
}
}
when (val response = viewModel.overviewViewState.collectAsState().value) {
is OnLoading -> Loading()
is OnError -> {
ShowProblem(response.errorDisplay) {
when (response.errorDisplay) {
SSL -> viewModel.openSettings()
EMPTY -> navController.navigate(Screen.Add.route)
else -> viewModel.getAllOverviewData()
}
}
}
is OnDisplay ->
ShowStatsCoins(
scrollState = scrollState,
result = response.display,
navController = navController
)
}
}
}
@OptIn(ExperimentalWearFoundationApi::class)
@Composable
fun ShowStatsCoins(
scrollState: ScalingLazyListState,
result: OverviewCoinDisplay,
navController: NavHostController,
) {
val focusRequester = rememberActiveFocusRequester()
val coroutineScope = rememberCoroutineScope()
ScalingLazyColumn(
modifier = Modifier
.fillMaxSize()
.onRotaryScrollEvent {
coroutineScope.launch {
scrollState.scrollBy(it.verticalScrollPixels)
scrollState.animateScrollBy(0f)
}
true
}
.focusRequester(focusRequester)
.focusable(),
contentPadding = PaddingValues(
top = 8.dp,
bottom = 32.dp
),
verticalArrangement = Arrangement.Center,
autoCentering = AutoCenteringParams(itemIndex = 0),
state = scrollState
) {
result.result.forEach {
item {
Column(
modifier = Modifier
.fillMaxSize()
.clickable(
onClick = {
navController.currentBackStackEntry?.savedStateHandle?.set(
key = "Coin",
value = it.id
)
navController.navigate(Screen.Details.route)
}
)
) {
CenterElement {
Text(
text = buildAnnotatedString {
append(it.name)
if (result.tileCoin == it.id) {
appendInlineContent("inlineContent", "[icon]")
}
},
modifier = Modifier.padding(bottom = 8.dp),
textAlign = TextAlign.Center,
color = MaterialTheme.colors.primary,
fontSize = 20.sp,
inlineContent = if (result.tileCoin == it.id) addIconFavorite() else emptyMap()
)
OverviewMarketChart(marketChart = it.marketChart)
Text(text = it.currentPrice)
Divider()
}
}
}
}
item {
OverviewBottomBar(
openListCoins = { navController.navigate(Screen.Add.route) },
openSettings = { navController.navigate(Screen.Settings.route) })
}
}
}
private fun addIconFavorite(): Map<String, InlineTextContent> {
val myId = "inlineContent"
val inlineContent = mapOf(
Pair(
myId,
InlineTextContent(
Placeholder(
width = 16.sp,
height = 16.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.Center
)
) {
Icon(Icons.Filled.Star, "", tint = MaterialTheme.colors.secondaryVariant)
}
)
)
return inlineContent
}
| 4
| null |
1
| 7
|
2e1a3741faa4f66d7a7b013c4544c8c7a18508c6
| 8,164
|
Crypto-Tracker
|
MIT License
|
tangle-api/src/main/kotlin/tangle/inject/internal/TangleInjectorComponent.kt
|
RBusarow
| 382,741,106
| false
| null |
/*
* Copyright (C) 2021 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tangle.inject.internal
import tangle.inject.InternalTangleApi
import javax.inject.Provider
@InternalTangleApi
public interface TangleScopeMapProviderComponent {
public val scopeMapProvider: TangleScopeMapProvider
}
@InternalTangleApi
public interface TangleInjectorComponent {
public val injectors: Map<Class<*>, @JvmSuppressWildcards Provider<TangleInjector<*>>>
}
| 27
|
Kotlin
|
112
| 76
|
e3db551e3285ff46f0eda7d2a4d8d1102cf7c9c9
| 976
|
Tangle
|
Apache License 2.0
|
kafka-connect-upload-source/src/main/java/org/radarbase/connect/upload/converter/altoidav2/AltoidaScreenElementXmlProcessor.kt
|
RADAR-base
| 179,307,077
| false
| null |
package org.radarbase.connect.upload.converter.altoidav2
import org.radarbase.connect.upload.converter.TopicData
import org.radarbase.connect.upload.converter.xml.XmlNodeProcessorFactory
import org.radarcns.connector.upload.altoida.AltoidaTestScreenElement
import org.w3c.dom.Element
open class AltoidaScreenElementXmlProcessor : XmlNodeProcessorFactory() {
override val fileNameSuffix: String = "altoida_data.xml"
override val nodeName: String = "screen_elements"
override fun convertToSingleRecord(
root: Element,
timeReceived: Double,
assessmentName: String?,
): TopicData {
val parent = (if (assessmentName == "ContrastVisionTest") root.parentNode.parentNode.parentNode else root.parentNode.parentNode) as Element
val colorElement = root.childOrNull("color")
return TopicData(
topic = "connect_upload_altoida_screen_elements",
value = AltoidaTestScreenElement.newBuilder().apply {
time = parent.attributeToTime("start_ts")
this.assessmentName = parent.assessmentName(assessmentName)
id = root.getAttribute("circle_id").toIntOrNull()
name = root.tagName
width = root.childOrNull("width").attribute("value").toDoubleOrNull()
height = root.childOrNull("height").attribute("value").toDoubleOrNull()
radius = root.childOrNull("radius").attribute("value").toDoubleOrNull()
xCenterOffset = root.childOrNull("x_center_offset").attribute("value").toDoubleOrNull()
yCenterOffset = root.childOrNull("y_center_offset").attribute("value").toDoubleOrNull()
colorAlpha = colorElement.attribute("alpha").toFloatOrNull()
colorRed = colorElement.attribute("r").toFloatOrNull()
colorGreen = colorElement.attribute("g").toFloatOrNull()
colorBlue = colorElement.attribute("b").toFloatOrNull()
}.build(),
)
}
private fun Element.assessmentName(assessmentName: String?): String? {
val objectName = getAttribute("object_name")
return when {
assessmentName != "ARTest" -> assessmentName
objectName.isEmpty() -> "ARTest_$tagName"
else -> "ARTest_${tagName}_$objectName"
}
}
override fun nodeConversions(
root: Element,
timeReceived: Double,
assessmentName: String?,
): Sequence<TopicData> {
val elements = if (assessmentName == "ContrastVisionTest") root.firstChild.childNodes else root.childNodes
return elements.asSequence()
.filter { it.hasChildNodes() && it is Element }
.map { convertToSingleRecord(it as Element, timeReceived, assessmentName) }
}
}
| 22
|
Kotlin
|
1
| 1
|
7da101d69fef7b36ac688275758f77019cb3f03b
| 2,805
|
radar-upload-source-connector
|
Apache License 2.0
|
Common/src/main/kotlin/possible_triangle/skygrid/data/xml/impl/Side.kt
|
PssbleTrngle
| 174,212,271
| false
| null |
package possible_triangle.skygrid.data.xml.impl
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import net.minecraft.core.BlockPos
import net.minecraft.core.Direction
import net.minecraft.core.Registry
import net.minecraft.world.level.block.Block
import possible_triangle.skygrid.data.xml.BlockProvider
import possible_triangle.skygrid.data.xml.Extra
import kotlin.random.Random
@Serializable
@SerialName("side")
data class Side(
val on: String,
override val providers: List<BlockProvider>,
val offset: Int = 1,
override val probability: Double = 1.0,
override val shared: Boolean = false,
) : Extra() {
override fun internalValidate(blocks: Registry<Block>): Boolean {
return Direction.byName(on) != null && offset > 0
}
override fun offset(pos: BlockPos, random: Random): BlockPos {
val direction = Direction.byName(on) ?: throw NullPointerException("Unknown direction '$on'")
return pos.relative(direction, offset)
}
}
| 3
|
Kotlin
|
1
| 11
|
d7f8e7d8722a1b0607bc74cd11047517f6eb4b82
| 1,020
|
Skygrid
|
Creative Commons Zero v1.0 Universal
|
increase-kotlin-core/src/main/kotlin/com/increase/api/models/SimulationCardAuthorizationCreateParams.kt
|
Increase
| 614,596,742
| false
| null |
// File generated from our OpenAPI spec by Stainless.
package com.increase.api.models
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.increase.api.core.Enum
import com.increase.api.core.ExcludeMissing
import com.increase.api.core.JsonField
import com.increase.api.core.JsonValue
import com.increase.api.core.NoAutoDetect
import com.increase.api.core.toUnmodifiable
import com.increase.api.errors.IncreaseInvalidDataException
import com.increase.api.models.*
import java.util.Objects
import java.util.Optional
class SimulationCardAuthorizationCreateParams
constructor(
private val amount: Long,
private val authenticatedCardPaymentId: String?,
private val cardId: String?,
private val declineReason: DeclineReason?,
private val digitalWalletTokenId: String?,
private val direction: Direction?,
private val eventSubscriptionId: String?,
private val merchantAcceptorId: String?,
private val merchantCategoryCode: String?,
private val merchantCity: String?,
private val merchantCountry: String?,
private val merchantDescriptor: String?,
private val physicalCardId: String?,
private val additionalQueryParams: Map<String, List<String>>,
private val additionalHeaders: Map<String, List<String>>,
private val additionalBodyProperties: Map<String, JsonValue>,
) {
fun amount(): Long = amount
fun authenticatedCardPaymentId(): Optional<String> =
Optional.ofNullable(authenticatedCardPaymentId)
fun cardId(): Optional<String> = Optional.ofNullable(cardId)
fun declineReason(): Optional<DeclineReason> = Optional.ofNullable(declineReason)
fun digitalWalletTokenId(): Optional<String> = Optional.ofNullable(digitalWalletTokenId)
fun direction(): Optional<Direction> = Optional.ofNullable(direction)
fun eventSubscriptionId(): Optional<String> = Optional.ofNullable(eventSubscriptionId)
fun merchantAcceptorId(): Optional<String> = Optional.ofNullable(merchantAcceptorId)
fun merchantCategoryCode(): Optional<String> = Optional.ofNullable(merchantCategoryCode)
fun merchantCity(): Optional<String> = Optional.ofNullable(merchantCity)
fun merchantCountry(): Optional<String> = Optional.ofNullable(merchantCountry)
fun merchantDescriptor(): Optional<String> = Optional.ofNullable(merchantDescriptor)
fun physicalCardId(): Optional<String> = Optional.ofNullable(physicalCardId)
@JvmSynthetic
internal fun getBody(): SimulationCardAuthorizationCreateBody {
return SimulationCardAuthorizationCreateBody(
amount,
authenticatedCardPaymentId,
cardId,
declineReason,
digitalWalletTokenId,
direction,
eventSubscriptionId,
merchantAcceptorId,
merchantCategoryCode,
merchantCity,
merchantCountry,
merchantDescriptor,
physicalCardId,
additionalBodyProperties,
)
}
@JvmSynthetic internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams
@JvmSynthetic internal fun getHeaders(): Map<String, List<String>> = additionalHeaders
@JsonDeserialize(builder = SimulationCardAuthorizationCreateBody.Builder::class)
@NoAutoDetect
class SimulationCardAuthorizationCreateBody
internal constructor(
private val amount: Long?,
private val authenticatedCardPaymentId: String?,
private val cardId: String?,
private val declineReason: DeclineReason?,
private val digitalWalletTokenId: String?,
private val direction: Direction?,
private val eventSubscriptionId: String?,
private val merchantAcceptorId: String?,
private val merchantCategoryCode: String?,
private val merchantCity: String?,
private val merchantCountry: String?,
private val merchantDescriptor: String?,
private val physicalCardId: String?,
private val additionalProperties: Map<String, JsonValue>,
) {
/** The authorization amount in cents. */
@JsonProperty("amount") fun amount(): Long? = amount
/**
* The identifier of a Card Payment with a `card_authentication` if you want to simulate an
* authenticated authorization.
*/
@JsonProperty("authenticated_card_payment_id")
fun authenticatedCardPaymentId(): String? = authenticatedCardPaymentId
/** The identifier of the Card to be authorized. */
@JsonProperty("card_id") fun cardId(): String? = cardId
/** Forces a card decline with a specific reason. No real time decision will be sent. */
@JsonProperty("decline_reason") fun declineReason(): DeclineReason? = declineReason
/** The identifier of the Digital Wallet Token to be authorized. */
@JsonProperty("digital_wallet_token_id")
fun digitalWalletTokenId(): String? = digitalWalletTokenId
/**
* The direction describes the direction the funds will move, either from the cardholder to
* the merchant or from the merchant to the cardholder.
*/
@JsonProperty("direction") fun direction(): Direction? = direction
/**
* The identifier of the Event Subscription to use. If provided, will override the default
* real time event subscription. Because you can only create one real time decision event
* subscription, you can use this field to route events to any specified event subscription
* for testing purposes.
*/
@JsonProperty("event_subscription_id")
fun eventSubscriptionId(): String? = eventSubscriptionId
/**
* The merchant identifier (commonly abbreviated as MID) of the merchant the card is
* transacting with.
*/
@JsonProperty("merchant_acceptor_id") fun merchantAcceptorId(): String? = merchantAcceptorId
/**
* The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is
* transacting with.
*/
@JsonProperty("merchant_category_code")
fun merchantCategoryCode(): String? = merchantCategoryCode
/** The city the merchant resides in. */
@JsonProperty("merchant_city") fun merchantCity(): String? = merchantCity
/** The country the merchant resides in. */
@JsonProperty("merchant_country") fun merchantCountry(): String? = merchantCountry
/** The merchant descriptor of the merchant the card is transacting with. */
@JsonProperty("merchant_descriptor") fun merchantDescriptor(): String? = merchantDescriptor
/** The identifier of the Physical Card to be authorized. */
@JsonProperty("physical_card_id") fun physicalCardId(): String? = physicalCardId
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var amount: Long? = null
private var authenticatedCardPaymentId: String? = null
private var cardId: String? = null
private var declineReason: DeclineReason? = null
private var digitalWalletTokenId: String? = null
private var direction: Direction? = null
private var eventSubscriptionId: String? = null
private var merchantAcceptorId: String? = null
private var merchantCategoryCode: String? = null
private var merchantCity: String? = null
private var merchantCountry: String? = null
private var merchantDescriptor: String? = null
private var physicalCardId: String? = null
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(
simulationCardAuthorizationCreateBody: SimulationCardAuthorizationCreateBody
) = apply {
this.amount = simulationCardAuthorizationCreateBody.amount
this.authenticatedCardPaymentId =
simulationCardAuthorizationCreateBody.authenticatedCardPaymentId
this.cardId = simulationCardAuthorizationCreateBody.cardId
this.declineReason = simulationCardAuthorizationCreateBody.declineReason
this.digitalWalletTokenId =
simulationCardAuthorizationCreateBody.digitalWalletTokenId
this.direction = simulationCardAuthorizationCreateBody.direction
this.eventSubscriptionId = simulationCardAuthorizationCreateBody.eventSubscriptionId
this.merchantAcceptorId = simulationCardAuthorizationCreateBody.merchantAcceptorId
this.merchantCategoryCode =
simulationCardAuthorizationCreateBody.merchantCategoryCode
this.merchantCity = simulationCardAuthorizationCreateBody.merchantCity
this.merchantCountry = simulationCardAuthorizationCreateBody.merchantCountry
this.merchantDescriptor = simulationCardAuthorizationCreateBody.merchantDescriptor
this.physicalCardId = simulationCardAuthorizationCreateBody.physicalCardId
additionalProperties(simulationCardAuthorizationCreateBody.additionalProperties)
}
/** The authorization amount in cents. */
@JsonProperty("amount") fun amount(amount: Long) = apply { this.amount = amount }
/**
* The identifier of a Card Payment with a `card_authentication` if you want to simulate
* an authenticated authorization.
*/
@JsonProperty("authenticated_card_payment_id")
fun authenticatedCardPaymentId(authenticatedCardPaymentId: String) = apply {
this.authenticatedCardPaymentId = authenticatedCardPaymentId
}
/** The identifier of the Card to be authorized. */
@JsonProperty("card_id") fun cardId(cardId: String) = apply { this.cardId = cardId }
/** Forces a card decline with a specific reason. No real time decision will be sent. */
@JsonProperty("decline_reason")
fun declineReason(declineReason: DeclineReason) = apply {
this.declineReason = declineReason
}
/** The identifier of the Digital Wallet Token to be authorized. */
@JsonProperty("digital_wallet_token_id")
fun digitalWalletTokenId(digitalWalletTokenId: String) = apply {
this.digitalWalletTokenId = digitalWalletTokenId
}
/**
* The direction describes the direction the funds will move, either from the cardholder
* to the merchant or from the merchant to the cardholder.
*/
@JsonProperty("direction")
fun direction(direction: Direction) = apply { this.direction = direction }
/**
* The identifier of the Event Subscription to use. If provided, will override the
* default real time event subscription. Because you can only create one real time
* decision event subscription, you can use this field to route events to any specified
* event subscription for testing purposes.
*/
@JsonProperty("event_subscription_id")
fun eventSubscriptionId(eventSubscriptionId: String) = apply {
this.eventSubscriptionId = eventSubscriptionId
}
/**
* The merchant identifier (commonly abbreviated as MID) of the merchant the card is
* transacting with.
*/
@JsonProperty("merchant_acceptor_id")
fun merchantAcceptorId(merchantAcceptorId: String) = apply {
this.merchantAcceptorId = merchantAcceptorId
}
/**
* The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is
* transacting with.
*/
@JsonProperty("merchant_category_code")
fun merchantCategoryCode(merchantCategoryCode: String) = apply {
this.merchantCategoryCode = merchantCategoryCode
}
/** The city the merchant resides in. */
@JsonProperty("merchant_city")
fun merchantCity(merchantCity: String) = apply { this.merchantCity = merchantCity }
/** The country the merchant resides in. */
@JsonProperty("merchant_country")
fun merchantCountry(merchantCountry: String) = apply {
this.merchantCountry = merchantCountry
}
/** The merchant descriptor of the merchant the card is transacting with. */
@JsonProperty("merchant_descriptor")
fun merchantDescriptor(merchantDescriptor: String) = apply {
this.merchantDescriptor = merchantDescriptor
}
/** The identifier of the Physical Card to be authorized. */
@JsonProperty("physical_card_id")
fun physicalCardId(physicalCardId: String) = apply {
this.physicalCardId = physicalCardId
}
fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.clear()
this.additionalProperties.putAll(additionalProperties)
}
@JsonAnySetter
fun putAdditionalProperty(key: String, value: JsonValue) = apply {
this.additionalProperties.put(key, value)
}
fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.putAll(additionalProperties)
}
fun build(): SimulationCardAuthorizationCreateBody =
SimulationCardAuthorizationCreateBody(
checkNotNull(amount) { "`amount` is required but was not set" },
authenticatedCardPaymentId,
cardId,
declineReason,
digitalWalletTokenId,
direction,
eventSubscriptionId,
merchantAcceptorId,
merchantCategoryCode,
merchantCity,
merchantCountry,
merchantDescriptor,
physicalCardId,
additionalProperties.toUnmodifiable(),
)
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return /* spotless:off */ other is SimulationCardAuthorizationCreateBody && this.amount == other.amount && this.authenticatedCardPaymentId == other.authenticatedCardPaymentId && this.cardId == other.cardId && this.declineReason == other.declineReason && this.digitalWalletTokenId == other.digitalWalletTokenId && this.direction == other.direction && this.eventSubscriptionId == other.eventSubscriptionId && this.merchantAcceptorId == other.merchantAcceptorId && this.merchantCategoryCode == other.merchantCategoryCode && this.merchantCity == other.merchantCity && this.merchantCountry == other.merchantCountry && this.merchantDescriptor == other.merchantDescriptor && this.physicalCardId == other.physicalCardId && this.additionalProperties == other.additionalProperties /* spotless:on */
}
private var hashCode: Int = 0
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode = /* spotless:off */ Objects.hash(amount, authenticatedCardPaymentId, cardId, declineReason, digitalWalletTokenId, direction, eventSubscriptionId, merchantAcceptorId, merchantCategoryCode, merchantCity, merchantCountry, merchantDescriptor, physicalCardId, additionalProperties) /* spotless:on */
}
return hashCode
}
override fun toString() =
"SimulationCardAuthorizationCreateBody{amount=$amount, authenticatedCardPaymentId=$authenticatedCardPaymentId, cardId=$cardId, declineReason=$declineReason, digitalWalletTokenId=$digitalWalletTokenId, direction=$direction, eventSubscriptionId=$eventSubscriptionId, merchantAcceptorId=$merchantAcceptorId, merchantCategoryCode=$merchantCategoryCode, merchantCity=$merchantCity, merchantCountry=$merchantCountry, merchantDescriptor=$merchantDescriptor, physicalCardId=$physicalCardId, additionalProperties=$additionalProperties}"
}
fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams
fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders
fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return /* spotless:off */ other is SimulationCardAuthorizationCreateParams && this.amount == other.amount && this.authenticatedCardPaymentId == other.authenticatedCardPaymentId && this.cardId == other.cardId && this.declineReason == other.declineReason && this.digitalWalletTokenId == other.digitalWalletTokenId && this.direction == other.direction && this.eventSubscriptionId == other.eventSubscriptionId && this.merchantAcceptorId == other.merchantAcceptorId && this.merchantCategoryCode == other.merchantCategoryCode && this.merchantCity == other.merchantCity && this.merchantCountry == other.merchantCountry && this.merchantDescriptor == other.merchantDescriptor && this.physicalCardId == other.physicalCardId && this.additionalQueryParams == other.additionalQueryParams && this.additionalHeaders == other.additionalHeaders && this.additionalBodyProperties == other.additionalBodyProperties /* spotless:on */
}
override fun hashCode(): Int {
return /* spotless:off */ Objects.hash(amount, authenticatedCardPaymentId, cardId, declineReason, digitalWalletTokenId, direction, eventSubscriptionId, merchantAcceptorId, merchantCategoryCode, merchantCity, merchantCountry, merchantDescriptor, physicalCardId, additionalQueryParams, additionalHeaders, additionalBodyProperties) /* spotless:on */
}
override fun toString() =
"SimulationCardAuthorizationCreateParams{amount=$amount, authenticatedCardPaymentId=$authenticatedCardPaymentId, cardId=$cardId, declineReason=$declineReason, digitalWalletTokenId=$digitalWalletTokenId, direction=$direction, eventSubscriptionId=$eventSubscriptionId, merchantAcceptorId=$merchantAcceptorId, merchantCategoryCode=$merchantCategoryCode, merchantCity=$merchantCity, merchantCountry=$merchantCountry, merchantDescriptor=$merchantDescriptor, physicalCardId=$physicalCardId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}"
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
@NoAutoDetect
class Builder {
private var amount: Long? = null
private var authenticatedCardPaymentId: String? = null
private var cardId: String? = null
private var declineReason: DeclineReason? = null
private var digitalWalletTokenId: String? = null
private var direction: Direction? = null
private var eventSubscriptionId: String? = null
private var merchantAcceptorId: String? = null
private var merchantCategoryCode: String? = null
private var merchantCity: String? = null
private var merchantCountry: String? = null
private var merchantDescriptor: String? = null
private var physicalCardId: String? = null
private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(
simulationCardAuthorizationCreateParams: SimulationCardAuthorizationCreateParams
) = apply {
this.amount = simulationCardAuthorizationCreateParams.amount
this.authenticatedCardPaymentId =
simulationCardAuthorizationCreateParams.authenticatedCardPaymentId
this.cardId = simulationCardAuthorizationCreateParams.cardId
this.declineReason = simulationCardAuthorizationCreateParams.declineReason
this.digitalWalletTokenId = simulationCardAuthorizationCreateParams.digitalWalletTokenId
this.direction = simulationCardAuthorizationCreateParams.direction
this.eventSubscriptionId = simulationCardAuthorizationCreateParams.eventSubscriptionId
this.merchantAcceptorId = simulationCardAuthorizationCreateParams.merchantAcceptorId
this.merchantCategoryCode = simulationCardAuthorizationCreateParams.merchantCategoryCode
this.merchantCity = simulationCardAuthorizationCreateParams.merchantCity
this.merchantCountry = simulationCardAuthorizationCreateParams.merchantCountry
this.merchantDescriptor = simulationCardAuthorizationCreateParams.merchantDescriptor
this.physicalCardId = simulationCardAuthorizationCreateParams.physicalCardId
additionalQueryParams(simulationCardAuthorizationCreateParams.additionalQueryParams)
additionalHeaders(simulationCardAuthorizationCreateParams.additionalHeaders)
additionalBodyProperties(
simulationCardAuthorizationCreateParams.additionalBodyProperties
)
}
/** The authorization amount in cents. */
fun amount(amount: Long) = apply { this.amount = amount }
/**
* The identifier of a Card Payment with a `card_authentication` if you want to simulate an
* authenticated authorization.
*/
fun authenticatedCardPaymentId(authenticatedCardPaymentId: String) = apply {
this.authenticatedCardPaymentId = authenticatedCardPaymentId
}
/** The identifier of the Card to be authorized. */
fun cardId(cardId: String) = apply { this.cardId = cardId }
/** Forces a card decline with a specific reason. No real time decision will be sent. */
fun declineReason(declineReason: DeclineReason) = apply {
this.declineReason = declineReason
}
/** The identifier of the Digital Wallet Token to be authorized. */
fun digitalWalletTokenId(digitalWalletTokenId: String) = apply {
this.digitalWalletTokenId = digitalWalletTokenId
}
/**
* The direction describes the direction the funds will move, either from the cardholder to
* the merchant or from the merchant to the cardholder.
*/
fun direction(direction: Direction) = apply { this.direction = direction }
/**
* The identifier of the Event Subscription to use. If provided, will override the default
* real time event subscription. Because you can only create one real time decision event
* subscription, you can use this field to route events to any specified event subscription
* for testing purposes.
*/
fun eventSubscriptionId(eventSubscriptionId: String) = apply {
this.eventSubscriptionId = eventSubscriptionId
}
/**
* The merchant identifier (commonly abbreviated as MID) of the merchant the card is
* transacting with.
*/
fun merchantAcceptorId(merchantAcceptorId: String) = apply {
this.merchantAcceptorId = merchantAcceptorId
}
/**
* The Merchant Category Code (commonly abbreviated as MCC) of the merchant the card is
* transacting with.
*/
fun merchantCategoryCode(merchantCategoryCode: String) = apply {
this.merchantCategoryCode = merchantCategoryCode
}
/** The city the merchant resides in. */
fun merchantCity(merchantCity: String) = apply { this.merchantCity = merchantCity }
/** The country the merchant resides in. */
fun merchantCountry(merchantCountry: String) = apply {
this.merchantCountry = merchantCountry
}
/** The merchant descriptor of the merchant the card is transacting with. */
fun merchantDescriptor(merchantDescriptor: String) = apply {
this.merchantDescriptor = merchantDescriptor
}
/** The identifier of the Physical Card to be authorized. */
fun physicalCardId(physicalCardId: String) = apply { this.physicalCardId = physicalCardId }
fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply {
this.additionalQueryParams.clear()
putAllQueryParams(additionalQueryParams)
}
fun putQueryParam(name: String, value: String) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value)
}
fun putQueryParams(name: String, values: Iterable<String>) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply {
additionalQueryParams.forEach(this::putQueryParams)
}
fun removeQueryParam(name: String) = apply {
this.additionalQueryParams.put(name, mutableListOf())
}
fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
this.additionalHeaders.clear()
putAllHeaders(additionalHeaders)
}
fun putHeader(name: String, value: String) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value)
}
fun putHeaders(name: String, values: Iterable<String>) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
additionalHeaders.forEach(this::putHeaders)
}
fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) }
fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply {
this.additionalBodyProperties.clear()
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply {
this.additionalBodyProperties.put(key, value)
}
fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) =
apply {
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun build(): SimulationCardAuthorizationCreateParams =
SimulationCardAuthorizationCreateParams(
checkNotNull(amount) { "`amount` is required but was not set" },
authenticatedCardPaymentId,
cardId,
declineReason,
digitalWalletTokenId,
direction,
eventSubscriptionId,
merchantAcceptorId,
merchantCategoryCode,
merchantCity,
merchantCountry,
merchantDescriptor,
physicalCardId,
additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalBodyProperties.toUnmodifiable(),
)
}
class DeclineReason
@JsonCreator
private constructor(
private val value: JsonField<String>,
) : Enum {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return /* spotless:off */ other is DeclineReason && this.value == other.value /* spotless:on */
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
@JvmField val CARD_NOT_ACTIVE = DeclineReason(JsonField.of("card_not_active"))
@JvmField
val PHYSICAL_CARD_NOT_ACTIVE = DeclineReason(JsonField.of("physical_card_not_active"))
@JvmField val ENTITY_NOT_ACTIVE = DeclineReason(JsonField.of("entity_not_active"))
@JvmField val GROUP_LOCKED = DeclineReason(JsonField.of("group_locked"))
@JvmField val INSUFFICIENT_FUNDS = DeclineReason(JsonField.of("insufficient_funds"))
@JvmField val CVV2_MISMATCH = DeclineReason(JsonField.of("cvv2_mismatch"))
@JvmField
val CARD_EXPIRATION_MISMATCH = DeclineReason(JsonField.of("card_expiration_mismatch"))
@JvmField
val TRANSACTION_NOT_ALLOWED = DeclineReason(JsonField.of("transaction_not_allowed"))
@JvmField val BREACHES_LIMIT = DeclineReason(JsonField.of("breaches_limit"))
@JvmField val WEBHOOK_DECLINED = DeclineReason(JsonField.of("webhook_declined"))
@JvmField val WEBHOOK_TIMED_OUT = DeclineReason(JsonField.of("webhook_timed_out"))
@JvmField
val DECLINED_BY_STAND_IN_PROCESSING =
DeclineReason(JsonField.of("declined_by_stand_in_processing"))
@JvmField
val INVALID_PHYSICAL_CARD = DeclineReason(JsonField.of("invalid_physical_card"))
@JvmField
val MISSING_ORIGINAL_AUTHORIZATION =
DeclineReason(JsonField.of("missing_original_authorization"))
@JvmField val SUSPECTED_FRAUD = DeclineReason(JsonField.of("suspected_fraud"))
@JvmStatic fun of(value: String) = DeclineReason(JsonField.of(value))
}
enum class Known {
CARD_NOT_ACTIVE,
PHYSICAL_CARD_NOT_ACTIVE,
ENTITY_NOT_ACTIVE,
GROUP_LOCKED,
INSUFFICIENT_FUNDS,
CVV2_MISMATCH,
CARD_EXPIRATION_MISMATCH,
TRANSACTION_NOT_ALLOWED,
BREACHES_LIMIT,
WEBHOOK_DECLINED,
WEBHOOK_TIMED_OUT,
DECLINED_BY_STAND_IN_PROCESSING,
INVALID_PHYSICAL_CARD,
MISSING_ORIGINAL_AUTHORIZATION,
SUSPECTED_FRAUD,
}
enum class Value {
CARD_NOT_ACTIVE,
PHYSICAL_CARD_NOT_ACTIVE,
ENTITY_NOT_ACTIVE,
GROUP_LOCKED,
INSUFFICIENT_FUNDS,
CVV2_MISMATCH,
CARD_EXPIRATION_MISMATCH,
TRANSACTION_NOT_ALLOWED,
BREACHES_LIMIT,
WEBHOOK_DECLINED,
WEBHOOK_TIMED_OUT,
DECLINED_BY_STAND_IN_PROCESSING,
INVALID_PHYSICAL_CARD,
MISSING_ORIGINAL_AUTHORIZATION,
SUSPECTED_FRAUD,
_UNKNOWN,
}
fun value(): Value =
when (this) {
CARD_NOT_ACTIVE -> Value.CARD_NOT_ACTIVE
PHYSICAL_CARD_NOT_ACTIVE -> Value.PHYSICAL_CARD_NOT_ACTIVE
ENTITY_NOT_ACTIVE -> Value.ENTITY_NOT_ACTIVE
GROUP_LOCKED -> Value.GROUP_LOCKED
INSUFFICIENT_FUNDS -> Value.INSUFFICIENT_FUNDS
CVV2_MISMATCH -> Value.CVV2_MISMATCH
CARD_EXPIRATION_MISMATCH -> Value.CARD_EXPIRATION_MISMATCH
TRANSACTION_NOT_ALLOWED -> Value.TRANSACTION_NOT_ALLOWED
BREACHES_LIMIT -> Value.BREACHES_LIMIT
WEBHOOK_DECLINED -> Value.WEBHOOK_DECLINED
WEBHOOK_TIMED_OUT -> Value.WEBHOOK_TIMED_OUT
DECLINED_BY_STAND_IN_PROCESSING -> Value.DECLINED_BY_STAND_IN_PROCESSING
INVALID_PHYSICAL_CARD -> Value.INVALID_PHYSICAL_CARD
MISSING_ORIGINAL_AUTHORIZATION -> Value.MISSING_ORIGINAL_AUTHORIZATION
SUSPECTED_FRAUD -> Value.SUSPECTED_FRAUD
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
CARD_NOT_ACTIVE -> Known.CARD_NOT_ACTIVE
PHYSICAL_CARD_NOT_ACTIVE -> Known.PHYSICAL_CARD_NOT_ACTIVE
ENTITY_NOT_ACTIVE -> Known.ENTITY_NOT_ACTIVE
GROUP_LOCKED -> Known.GROUP_LOCKED
INSUFFICIENT_FUNDS -> Known.INSUFFICIENT_FUNDS
CVV2_MISMATCH -> Known.CVV2_MISMATCH
CARD_EXPIRATION_MISMATCH -> Known.CARD_EXPIRATION_MISMATCH
TRANSACTION_NOT_ALLOWED -> Known.TRANSACTION_NOT_ALLOWED
BREACHES_LIMIT -> Known.BREACHES_LIMIT
WEBHOOK_DECLINED -> Known.WEBHOOK_DECLINED
WEBHOOK_TIMED_OUT -> Known.WEBHOOK_TIMED_OUT
DECLINED_BY_STAND_IN_PROCESSING -> Known.DECLINED_BY_STAND_IN_PROCESSING
INVALID_PHYSICAL_CARD -> Known.INVALID_PHYSICAL_CARD
MISSING_ORIGINAL_AUTHORIZATION -> Known.MISSING_ORIGINAL_AUTHORIZATION
SUSPECTED_FRAUD -> Known.SUSPECTED_FRAUD
else -> throw IncreaseInvalidDataException("Unknown DeclineReason: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
class Direction
@JsonCreator
private constructor(
private val value: JsonField<String>,
) : Enum {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return /* spotless:off */ other is Direction && this.value == other.value /* spotless:on */
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
@JvmField val SETTLEMENT = Direction(JsonField.of("settlement"))
@JvmField val REFUND = Direction(JsonField.of("refund"))
@JvmStatic fun of(value: String) = Direction(JsonField.of(value))
}
enum class Known {
SETTLEMENT,
REFUND,
}
enum class Value {
SETTLEMENT,
REFUND,
_UNKNOWN,
}
fun value(): Value =
when (this) {
SETTLEMENT -> Value.SETTLEMENT
REFUND -> Value.REFUND
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
SETTLEMENT -> Known.SETTLEMENT
REFUND -> Known.REFUND
else -> throw IncreaseInvalidDataException("Unknown Direction: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
}
| 1
| null |
0
| 5
|
dc1361d08cb41ff45817c2e7638f53356f15cf8e
| 35,558
|
increase-kotlin
|
Apache License 2.0
|
src/main/kotlin/past/003-d.kt
|
kirimin
| 197,707,422
| false
| null |
package past
import utilities.debugLog
import java.util.*
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val n = sc.nextInt()
val s = (0 until 5).map { sc.next() }
println(problem3d(n, s))
}
fun problem3d(n: Int, s: List<String>): String {
val numbers = arrayOf(
arrayOf(
'#', '#', '#',
'#', '.', '#',
'#', '.', '#',
'#', '.', '#',
'#', '#', '#'
).joinToString(""),
arrayOf(
'.', '#', '.',
'#', '#', '.',
'.', '#', '.',
'.', '#', '.',
'#', '#', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'.', '.', '#',
'#', '#', '#',
'#', '.', '.',
'#', '#', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'.', '.', '#',
'#', '#', '#',
'.', '.', '#',
'#', '#', '#'
).joinToString(""),
arrayOf(
'#', '.', '#',
'#', '.', '#',
'#', '#', '#',
'.', '.', '#',
'.', '.', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'#', '.', '.',
'#', '#', '#',
'.', '.', '#',
'#', '#', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'#', '.', '.',
'#', '#', '#',
'#', '.', '#',
'#', '#', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'.', '.', '#',
'.', '.', '#',
'.', '.', '#',
'.', '.', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'#', '.', '#',
'#', '#', '#',
'#', '.', '#',
'#', '#', '#'
).joinToString(""),
arrayOf(
'#', '#', '#',
'#', '.', '#',
'#', '#', '#',
'.', '.', '#',
'#', '#', '#'
).joinToString("")
)
var ans = ""
for (i in 0 until n) {
val s1 = s[0].drop(4 * i + 1).take(3)
val s2 = s[1].drop(4 * i + 1).take(3)
val s3 = s[2].drop(4 * i + 1).take(3)
val s4 = s[3].drop(4 * i + 1).take(3)
val s5 = s[4].drop(4 * i + 1).take(3)
val display = arrayOf(s1, s2, s3, s4, s5).joinToString("")
for (j in 0 until numbers.size) {
if (numbers[j] == display) {
ans += j
}
}
}
return ans
}
// j桁目 = 4j - 2, 4j - 1, 4j = 1桁目 > 4, 3, 2列目
// 1 2 3,
// 5 6 7,
// 9 10 11,
// 13 14 15
| 0
|
Kotlin
|
1
| 5
|
87f20b4aa2031c130867c546dd5533890f1978ee
| 2,684
|
AtCoderLog
|
The Unlicense
|
typescript-kotlin/src/jsMain/kotlin/typescript/JSDocTagInfo.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6915863}
|
// Automatically generated - do not modify!
package typescript
import js.array.ReadonlyArray
sealed external interface JSDocTagInfo {
var name: String
var text: ReadonlyArray<SymbolDisplayPart>?
}
| 0
|
Kotlin
|
7
| 31
|
d1315f1524758eb6883a4f7e0a0da46816152ed8
| 208
|
types-kotlin
|
Apache License 2.0
|
data/src/main/java/com/keelim/cnubus/data/api/response/mapper/ArrivalsMapper.kt
|
keelim
| 202,127,420
| false
| null |
/*
* Designed and developed by 2021 keelim (Jaehyun Kim)
*
* 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.keelim.cnubus.data.api.response.mapper
import com.keelim.cnubus.data.api.response.RealtimeArrival
import com.keelim.cnubus.data.model.ArrivalInformation
import com.keelim.cnubus.data.model.Subway
import java.text.SimpleDateFormat
import java.util.Locale
private val apiDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.'0'", Locale.KOREA)
private val dateFormat = SimpleDateFormat("HH:mm:ss", Locale.KOREA)
private const val INVALID_FIELD = "-"
fun RealtimeArrival.toArrivalInformation(): ArrivalInformation =
ArrivalInformation(
subway = Subway.findById(subwayId),
direction = trainLineNm?.split("-")
?.get(1)
?.trim()
?: INVALID_FIELD,
destination = bstatnNm ?: INVALID_FIELD,
message = arvlMsg2
?.replace(statnNm.toString(), "당역")
?.replace("[\\[\\]]".toRegex(), "")
?: INVALID_FIELD,
updatedAt = recptnDt
?.let { apiDateFormat.parse(it) }
?.let { dateFormat.format(it) }
?: INVALID_FIELD
)
fun List<RealtimeArrival>.toArrivalInformation(): List<ArrivalInformation> =
map { it.toArrivalInformation() }
| 6
|
Kotlin
|
0
| 1
|
836c7fca6793ed74249f9430c798466b1a7aaa27
| 1,799
|
project_cnuBus
|
Apache License 2.0
|
src/test/kotlin/no/nb/bikube/core/controller/CoreControllerIntegrationTest.kt
|
NationalLibraryOfNorway
| 694,135,748
| false
| null |
package no.nb.bikube.core.controller
import com.ninjasquad.springmockk.MockkBean
import io.mockk.every
import io.mockk.verify
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsModelEmptyRecordListMock
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsModelMockAllTitles
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsModelMockItemA
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsModelMockManifestationA
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsModelMockTitleA
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsPartsObjectMockItemA
import no.nb.bikube.catalogue.collections.CollectionsModelMockData.Companion.collectionsPartsObjectMockManifestationA
import no.nb.bikube.catalogue.collections.enum.CollectionsFormat
import no.nb.bikube.catalogue.collections.mapper.mapCollectionsObjectToGenericTitle
import no.nb.bikube.catalogue.collections.model.*
import no.nb.bikube.catalogue.collections.repository.CollectionsRepository
import no.nb.bikube.core.enum.MaterialType
import no.nb.bikube.core.model.Item
import no.nb.bikube.core.model.Title
import no.nb.bikube.core.util.DateUtils
import no.nb.bikube.newspaper.service.TitleIndexService
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.ProblemDetail
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec
import org.springframework.test.web.reactive.server.expectBody
import org.springframework.test.web.reactive.server.returnResult
import reactor.core.publisher.Mono
import reactor.kotlin.test.test
import java.time.Duration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class CoreControllerIntegrationTest (
@Autowired private var webClient: WebTestClient
){
@MockkBean
private lateinit var collectionsRepository: CollectionsRepository
@MockkBean
private lateinit var titleIndexService: TitleIndexService
private val titleId = "1"
private val manifestationId = "3"
private val itemId = "4"
@BeforeEach
fun beforeEach() {
// Needed to run properly in GitHub Actions
webClient = webClient.mutate().responseTimeout(Duration.ofSeconds(60)).build()
every { collectionsRepository.getSingleCollectionsModel(collectionsModelMockManifestationA.getFirstId()!!) } returns Mono.just(collectionsModelMockManifestationA.copy())
every { collectionsRepository.getSingleCollectionsModelWithoutChildren(any()) } returns Mono.just(collectionsModelEmptyRecordListMock.copy())
every { collectionsRepository.getSingleCollectionsModelWithoutChildren(titleId) } returns Mono.just(collectionsModelMockTitleA.copy())
every { collectionsRepository.getSingleCollectionsModelWithoutChildren(manifestationId) } returns Mono.just(collectionsModelMockManifestationA.copy())
every { collectionsRepository.getSingleCollectionsModelWithoutChildren(itemId) } returns Mono.just(collectionsModelMockItemA.copy())
every { collectionsRepository.getManifestations(any(), any()) } returns Mono.just(collectionsModelEmptyRecordListMock.copy())
every { collectionsRepository.getManifestations(any(), titleId) } returns Mono.just(collectionsModelMockManifestationA.copy())
every { titleIndexService.searchTitle(any()) } returns
collectionsModelMockAllTitles.getObjects()!!.map { mapCollectionsObjectToGenericTitle(it) }
}
private fun getItem(itemId: String, materialType: MaterialType): ResponseSpec {
return webClient
.get()
.uri { uri ->
uri.pathSegment("item")
.queryParam("catalogueId", itemId)
.queryParam("materialType", materialType)
.build()
}
.exchange()
}
private fun getTitle(titleId: String, materialType: MaterialType): ResponseSpec {
return webClient
.get()
.uri { uri ->
uri.pathSegment("title")
.queryParam("catalogueId", titleId)
.queryParam("materialType", materialType)
.build()
}
.exchange()
}
private fun searchTitle(search: String, materialType: MaterialType): ResponseSpec {
return webClient
.get()
.uri { uri ->
uri.pathSegment("title", "search")
.queryParam("searchTerm", search)
.queryParam("materialType", materialType)
.build()
}
.exchange()
}
@Test
fun `get-item endpoint should return 200 OK with item`() {
getItem(itemId, MaterialType.NEWSPAPER)
.expectStatus().isOk
.expectBody<Item>()
}
@Test
fun `get-item endpoint should return 400 Bad Request for manuscripts`() {
getItem(itemId, MaterialType.MANUSCRIPT)
.expectStatus().isBadRequest
}
@Test
fun `get-item endpoint should return 400 Bad Request for monographs`() {
getItem(itemId, MaterialType.MONOGRAPH)
.expectStatus().isBadRequest
}
@Test
fun `get-item endpoint should return 400 Bad Request for periodicals`() {
getItem(itemId, MaterialType.PERIODICAL)
.expectStatus().isBadRequest
}
@Test
fun `get-item endpoint should return correctly mapped item`() {
val testItem = collectionsModelMockItemA.getFirstObject()
getItem(itemId, MaterialType.NEWSPAPER)
.expectStatus().isOk
.returnResult<Item>()
.responseBody
.test()
.expectNext(
Item(
catalogueId = testItem.priRef,
name = testItem.getName(),
date = testItem.getDate(),
materialType = testItem.getMaterialTypeFromParent()!!.norwegian,
titleCatalogueId = testItem.getTitleCatalogueId(),
titleName = testItem.getTitleName(),
digital = testItem.getFormat() == CollectionsFormat.DIGITAL,
urn = testItem.getUrn(),
location = testItem.locationBarcode,
parentCatalogueId = testItem.getParentId()
)
)
.verifyComplete()
}
@Test
fun `get-item endpoint should return 404 when item does not exist`() {
getItem("9903892", MaterialType.NEWSPAPER)
.expectStatus().isNotFound
}
@Test
fun `get-item endpoint should return 404 with message when ID belongs to title or manifestation`() {
getItem(titleId, MaterialType.NEWSPAPER)
.expectStatus().isNotFound
.returnResult<ProblemDetail>()
.responseBody
.test()
.assertNext { problemDetail ->
Assertions.assertEquals("Not Found", problemDetail.title)
Assertions.assertTrue(problemDetail.detail!!.lowercase().contains("object is not of type item"))
Assertions.assertNotNull(problemDetail.instance)
}
.verifyComplete()
getItem(manifestationId, MaterialType.NEWSPAPER)
.expectStatus().isNotFound
.returnResult<ProblemDetail>()
.responseBody
.test()
.assertNext { response ->
Assertions.assertEquals("Not Found", response.title)
Assertions.assertTrue(response.detail!!.lowercase().contains("object is not of type item"))
Assertions.assertNotNull(response.instance)
}
.verifyComplete()
}
@Test
fun `get-title endpoint should return 200 OK with title`() {
getTitle(titleId, MaterialType.NEWSPAPER)
.expectStatus().isOk
.expectBody<Title>()
}
@Test
fun `get-title endpoint should return 400 bad request for manuscripts`() {
getTitle(titleId, MaterialType.MANUSCRIPT)
.expectStatus().isBadRequest
}
@Test
fun `get-title endpoint should return 400 bad request for monographs`() {
getTitle(titleId, MaterialType.MONOGRAPH)
.expectStatus().isBadRequest
}
@Test
fun `get-title endpoint should return 400 bad request for periodicals`() {
getTitle(titleId, MaterialType.PERIODICAL)
.expectStatus().isBadRequest
}
@Test
fun `get-title endpoint should return correctly mapped title`() {
val testTitle = collectionsModelMockTitleA.getFirstObject()
getTitle(titleId, MaterialType.NEWSPAPER)
.expectStatus().isOk
.returnResult<Title>()
.responseBody
.test()
.expectNext(
Title(
name = testTitle.getName(),
startDate = testTitle.getStartDate(),
endDate = testTitle.getEndDate(),
publisher = testTitle.getPublisher(),
publisherPlace = testTitle.getPublisherPlace(),
language = testTitle.getLanguage(),
materialType = testTitle.getMaterialType()!!.norwegian,
catalogueId = testTitle.priRef
)
)
.verifyComplete()
}
@Test
fun `get-title endpoint should return 404 when title does not exist`() {
getTitle("9903892", MaterialType.NEWSPAPER)
.expectStatus().isNotFound
}
@Test
fun `get-title endpoint should return 404 with message when ID belongs to manifestation or item`() {
getTitle(itemId, MaterialType.NEWSPAPER)
.expectStatus().isNotFound
.returnResult<ProblemDetail>()
.responseBody
.test()
.assertNext { problemDetail ->
Assertions.assertEquals("Not Found", problemDetail.title)
Assertions.assertTrue(problemDetail.detail!!.lowercase().contains("object is not of type work"))
Assertions.assertNotNull(problemDetail.instance)
}
.verifyComplete()
getTitle(manifestationId, MaterialType.NEWSPAPER)
.expectStatus().isNotFound
.returnResult<ProblemDetail>()
.responseBody
.test()
.assertNext { problemDetail ->
Assertions.assertEquals("Not Found", problemDetail.title)
Assertions.assertTrue(problemDetail.detail!!.lowercase().contains("object is not of type work"))
Assertions.assertNotNull(problemDetail.instance)
}
.verifyComplete()
}
@Test
fun `get-title-search endpoint should return 200 OK with all titles`() {
searchTitle("*", MaterialType.NEWSPAPER)
.expectStatus().isOk
.returnResult<Title>()
.responseBody
.test()
.expectSubscription()
.expectNextCount(collectionsModelMockAllTitles.getObjects()!!.size.toLong())
.verifyComplete()
}
@Test
fun `get-title-search endpoint should return mapped items`() {
searchTitle("*", MaterialType.NEWSPAPER)
.returnResult<Title>()
.responseBody
.test()
.expectNext(mapCollectionsObjectToGenericTitle(collectionsModelMockAllTitles.getObjects()!![0]))
.expectNext(mapCollectionsObjectToGenericTitle(collectionsModelMockAllTitles.getObjects()!![1]))
.expectNext(mapCollectionsObjectToGenericTitle(collectionsModelMockAllTitles.getObjects()!![2]))
.verifyComplete()
}
@Test
fun `get-title-search endpoint should return 400 bad request for manuscripts`() {
searchTitle("*", MaterialType.MANUSCRIPT)
.expectStatus().isBadRequest
}
@Test
fun `get-title-search endpoint should return 400 bad request for monographs`() {
searchTitle("*", MaterialType.MONOGRAPH)
.expectStatus().isBadRequest
}
@Test
fun `get-title-search endpoint should return 400 bad request for periodicals`() {
searchTitle("*", MaterialType.PERIODICAL)
.expectStatus().isBadRequest
}
@Test
fun `get-title-search endpoint should return empty flux when no items match search term`() {
every { titleIndexService.searchTitle("no match") } returns emptyList()
searchTitle("no match", MaterialType.NEWSPAPER)
.returnResult<Title>()
.responseBody
.test()
.expectSubscription()
.expectNextCount(0)
.verifyComplete()
}
@Test
fun `search-item endpoint should return 200 OK with all items`() {
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.NEWSPAPER)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isOk
.returnResult<Item>()
.responseBody
.test()
.expectSubscription()
.expectNextCount(collectionsModelMockItemA.getObjects()!!.size.toLong())
.verifyComplete()
}
@Test
fun `search-item endpoint should return mapped items`() {
val expectedItem = Item(
catalogueId = collectionsPartsObjectMockItemA.partsReference!!.priRef,
name = collectionsPartsObjectMockItemA.partsReference!!.titleList!!.first().title!!,
date = DateUtils.parseYearOrDate(
collectionsPartsObjectMockItemA.partsReference!!.titleList!!.first().title!!.takeLast(10)
)!!,
materialType = MaterialType.NEWSPAPER.value,
titleCatalogueId = collectionsModelMockTitleA.getFirstId(),
titleName = collectionsPartsObjectMockManifestationA.partsReference!!.titleList!!.first().title!!,
digital = collectionsPartsObjectMockItemA.partsReference!!.getFormat() == CollectionsFormat.DIGITAL,
urn = null,
parentCatalogueId = null
)
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.NEWSPAPER)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.returnResult<Item>()
.responseBody
.test()
.expectNext(expectedItem)
.verifyComplete()
verify(exactly = 1) { collectionsRepository.getManifestations(any(), "1") }
verify(exactly = 1) { collectionsRepository.getSingleCollectionsModel(collectionsModelMockManifestationA.getFirstId()!!) }
}
@Test
fun `search-item endpoint should return 400 bad request for manuscripts`() {
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.MANUSCRIPT)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
}
@Test
fun `search-item endpoint should return 400 bad request for monographs`() {
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.MONOGRAPH)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
}
@Test
fun `search-item endpoint should return 400 bad request for periodicals`() {
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.PERIODICAL)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
}
@Test
fun `search-item endpoint should return empty flux when no items match search term`() {
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "no match")
.queryParam("materialType", MaterialType.NEWSPAPER)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.returnResult<Item>()
.responseBody
.test()
.expectSubscription()
.expectNextCount(0)
.verifyComplete()
}
@Test
fun `search-item endpoint should return 400 bad request if date is invalid`() {
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.NEWSPAPER)
.queryParam("date", "9999-99-99")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
}
@Test
fun `search-item endpoint should return 400 bad request if required request params are omitted`() {
// Missing date
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("materialType", MaterialType.NEWSPAPER)
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
// Missing title ID
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("materialType", MaterialType.NEWSPAPER)
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
// Missing material type
webClient
.get()
.uri { uri ->
uri.pathSegment("item", "search")
.queryParam("titleCatalogueId", "1")
.queryParam("date", "2020-01-01")
.queryParam("isDigital", "true")
.build()
}
.exchange()
.expectStatus().isBadRequest
}
}
| 3
| null |
0
| 3
|
f5e436f07cb39aeb5b9011544927fc65fc32ca94
| 19,963
|
bikube
|
Apache License 2.0
|
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/groups/methods/GroupsGetBannedMethod.kt
|
alatushkin
| 156,866,851
| false
| null |
package name.alatushkin.api.vk.generated.groups.methods
import com.fasterxml.jackson.core.type.TypeReference
import name.alatushkin.api.vk.VkMethod
import name.alatushkin.api.vk.api.VkList
import name.alatushkin.api.vk.api.VkSuccess
import name.alatushkin.api.vk.generated.groups.OwnerXtrBanInfo
/**
* Returns a list of users on a community blacklist.
*
* [https://vk.com/dev/groups.getBanned]
* @property [group_id] Community ID.
* @property [offset] Offset needed to return a specific subset of users.
* @property [count] Number of users to return.
* @property [fields]
* @property [user_id]
*/
class GroupsGetBannedMethod() : VkMethod<VkList<OwnerXtrBanInfo>>(
"groups.getBanned",
HashMap()
) {
var groupId: Long? by props
var offset: Long? by props
var count: Long? by props
var fields: Array<String>? by props
var userId: Long? by props
constructor(
groupId: Long? = null,
offset: Long? = null,
count: Long? = null,
fields: Array<String>? = null,
userId: Long? = null
) : this() {
this.groupId = groupId
this.offset = offset
this.count = count
this.fields = fields
this.userId = userId
}
fun setGroupId(groupId: Long): GroupsGetBannedMethod {
this.groupId = groupId
return this
}
fun setOffset(offset: Long): GroupsGetBannedMethod {
this.offset = offset
return this
}
fun setCount(count: Long): GroupsGetBannedMethod {
this.count = count
return this
}
fun setFields(fields: Array<String>): GroupsGetBannedMethod {
this.fields = fields
return this
}
fun setUserId(userId: Long): GroupsGetBannedMethod {
this.userId = userId
return this
}
override val classRef = GroupsGetBannedMethod.classRef
companion object {
val classRef = object : TypeReference<VkSuccess<VkList<OwnerXtrBanInfo>>>() {}
}
}
| 2
|
Kotlin
|
3
| 10
|
123bd61b24be70f9bbf044328b98a3901523cb1b
| 1,986
|
kotlin-vk-api
|
MIT License
|
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/groups/methods/GroupsGetBannedMethod.kt
|
alatushkin
| 156,866,851
| false
| null |
package name.alatushkin.api.vk.generated.groups.methods
import com.fasterxml.jackson.core.type.TypeReference
import name.alatushkin.api.vk.VkMethod
import name.alatushkin.api.vk.api.VkList
import name.alatushkin.api.vk.api.VkSuccess
import name.alatushkin.api.vk.generated.groups.OwnerXtrBanInfo
/**
* Returns a list of users on a community blacklist.
*
* [https://vk.com/dev/groups.getBanned]
* @property [group_id] Community ID.
* @property [offset] Offset needed to return a specific subset of users.
* @property [count] Number of users to return.
* @property [fields]
* @property [user_id]
*/
class GroupsGetBannedMethod() : VkMethod<VkList<OwnerXtrBanInfo>>(
"groups.getBanned",
HashMap()
) {
var groupId: Long? by props
var offset: Long? by props
var count: Long? by props
var fields: Array<String>? by props
var userId: Long? by props
constructor(
groupId: Long? = null,
offset: Long? = null,
count: Long? = null,
fields: Array<String>? = null,
userId: Long? = null
) : this() {
this.groupId = groupId
this.offset = offset
this.count = count
this.fields = fields
this.userId = userId
}
fun setGroupId(groupId: Long): GroupsGetBannedMethod {
this.groupId = groupId
return this
}
fun setOffset(offset: Long): GroupsGetBannedMethod {
this.offset = offset
return this
}
fun setCount(count: Long): GroupsGetBannedMethod {
this.count = count
return this
}
fun setFields(fields: Array<String>): GroupsGetBannedMethod {
this.fields = fields
return this
}
fun setUserId(userId: Long): GroupsGetBannedMethod {
this.userId = userId
return this
}
override val classRef = GroupsGetBannedMethod.classRef
companion object {
val classRef = object : TypeReference<VkSuccess<VkList<OwnerXtrBanInfo>>>() {}
}
}
| 2
|
Kotlin
|
3
| 10
|
123bd61b24be70f9bbf044328b98a3901523cb1b
| 1,986
|
kotlin-vk-api
|
MIT License
|
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/ui/studygroup/members/StudyGroupMembersComponent.kt
|
denchic45
| 435,895,363
| false
|
{"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
|
package com.denchic45.studiversity.ui.studygroup.members
import com.arkivanov.decompose.ComponentContext
import com.denchic45.studiversity.api.role.model.Capability
import com.denchic45.studiversity.api.role.model.Role
import com.denchic45.studiversity.domain.model.GroupMembers
import com.denchic45.studiversity.domain.model.toUserItem
import com.denchic45.studiversity.domain.resource.Resource
import com.denchic45.studiversity.domain.resource.mapResource
import com.denchic45.studiversity.domain.resource.onSuccess
import com.denchic45.studiversity.domain.resource.stateInResource
import com.denchic45.studiversity.domain.usecase.*
import com.denchic45.studiversity.ui.confirm.ConfirmDialogInteractor
import com.denchic45.studiversity.ui.confirm.ConfirmState
import com.denchic45.studiversity.ui.uiTextOf
import com.denchic45.studiversity.util.componentScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import me.tatarka.inject.annotations.Assisted
import me.tatarka.inject.annotations.Inject
import java.util.*
@Inject
class StudyGroupMembersComponent(
findGroupMembersUseCase: FindGroupMembersUseCase,
checkUserCapabilitiesInScopeUseCase: CheckUserCapabilitiesInScopeUseCase,
private val assignUserRoleInScopeUseCase: AssignUserRoleInScopeUseCase,
private val removeUserRoleFromScopeUseCase: RemoveUserRoleFromScopeUseCase,
private val removeMemberFromScopeUseCase: RemoveMemberFromScopeUseCase,
private val confirmDialogInteractor: ConfirmDialogInteractor,
@Assisted
private val onMemberOpen: (memberId: UUID) -> Unit,
@Assisted
private val onMemberEdit: (memberId: UUID) -> Unit,
@Assisted
private val studyGroupId: UUID,
@Assisted
componentContext: ComponentContext,
) : ComponentContext by componentContext {
private val componentScope = componentScope()
private val checkUserCapabilities = checkUserCapabilitiesInScopeUseCase(
scopeId = studyGroupId,
capabilities = listOf(Capability.WriteStudyGroup)
).shareIn(componentScope, SharingStarted.Lazily)
val allowEditMembers = checkUserCapabilities
.mapResource { it.hasCapability(Capability.WriteStudyGroup) }
.stateInResource(componentScope)
val members: StateFlow<Resource<GroupMembers>> = flow {
emit(findGroupMembersUseCase(studyGroupId))
}.mapResource { scopeMembers ->
val curatorMember = scopeMembers.firstOrNull { member -> Role.Curator in member.roles }
val groupCurator = curatorMember?.user?.toUserItem()
val students = (curatorMember?.let { scopeMembers - it }
?: scopeMembers).map {
it.user.toUserItem(if (it.roles.contains(Role.Headman)) "Староста" else null)
}
GroupMembers(
groupId = studyGroupId,
curator = groupCurator,
headmanId = scopeMembers.find { member -> Role.Headman in member.roles }?.user?.id,
students = students
)
}.stateInResource(componentScope)
val memberActions = MutableStateFlow<Pair<List<MemberAction>, UUID>?>(null)
fun onMemberSelect(memberId: UUID) {
onMemberOpen(memberId)
}
fun onMemberEditClick(memberId: UUID) {
onMemberEdit(memberId)
}
fun onMemberRemoveClick(memberId: UUID) {
componentScope.launch {
if (confirmDialogInteractor.confirmRequest(
ConfirmState(
uiTextOf("Удалить члена группы?"),
uiTextOf("Удалятся все данные, связанные с данным пользователем в группе")
)
)
) {
removeMemberFromScopeUseCase(memberId, studyGroupId)
}
}
}
fun onMemberSetHeadmanClick(memberId: UUID) {
componentScope.launch {
assignUserRoleInScopeUseCase(
memberId,
Role.Headman.id,
studyGroupId
)
}
}
fun onMemberRemoveHeadmanClick(memberId: UUID) {
componentScope.launch {
removeUserRoleFromScopeUseCase(
memberId,
Role.Headman.id,
studyGroupId
)
}
}
fun onMemberActionsExpand(memberId: UUID) {
members.value.onSuccess { members ->
memberActions.update {
buildList {
if (members.students.any { it.id == memberId }) {
add(
if (members.headmanId != memberId) MemberAction.SET_HEADMAN
else MemberAction.REMOVE_HEADMAN
)
}
add(MemberAction.EDIT)
add(MemberAction.REMOVE)
} to memberId
}
}
}
fun onDismissActions() {
memberActions.value = null
}
enum class MemberAction { EDIT, REMOVE, SET_HEADMAN, REMOVE_HEADMAN }
}
| 0
|
Kotlin
|
0
| 7
|
93947301de4c4a9cb6c3d9fa36903f857c50e6c2
| 4,972
|
Studiversity
|
Apache License 2.0
|
app/src/main/kotlin/kr/ac/snu/hcil/omnitrack/core/auth/IAuthServerAPI.kt
|
yghokim
| 62,933,149
| false
| null |
package kr.ac.snu.hcil.omnitrack.core.auth
import com.google.gson.JsonObject
import io.reactivex.Completable
import io.reactivex.Single
import io.realm.internal.Keep
import kr.ac.snu.hcil.omnitrack.core.database.OTDeviceInfo
interface IAuthServerAPI {
@Keep
data class AuthResponseData(val token: String, val deviceLocalKey: String?, val appFlags: JsonObject?)
@Keep
data class PasswordResetRequestResult(val success: Boolean, val email: String)
fun register(
username: String,
email: String,
password: String,
deviceInfo: OTDeviceInfo,
invitationCode: String?,
demographicData: JsonObject?): Single<AuthResponseData>
fun authenticate(username: String, password: String, deviceInfo: OTDeviceInfo): Single<AuthResponseData>
fun updateEmail(email: String): Single<AuthResponseData>
fun changePassword(original: String, newPassword: String): Single<AuthResponseData>
fun refreshToken(token: String): Single<String>
fun signOut(deviceInfo: OTDeviceInfo): Completable
fun requestResetPassword(username: String): Single<PasswordResetRequestResult>
fun dropOutFromStudy(reason: String?): Completable
}
| 9
| null |
4
| 8
|
f13e5c157d5646c3f9493c4fdc25ed3b1fc2e296
| 1,227
|
omnitrack_android
|
MIT License
|
adapter/src/test/kotlin/org/javacs/ktda/DebugAdapterTestFixture.kt
|
fwcd
| 144,839,079
| false
|
{"Kotlin": 80289}
|
package org.javacs.ktda
import java.nio.file.Path
import java.nio.file.Paths
import org.eclipse.lsp4j.debug.ConfigurationDoneArguments
import org.eclipse.lsp4j.debug.InitializeRequestArguments
import org.eclipse.lsp4j.debug.DisconnectArguments
import org.eclipse.lsp4j.debug.OutputEventArguments
import org.eclipse.lsp4j.debug.services.IDebugProtocolClient
import org.javacs.ktda.adapter.KotlinDebugAdapter
import org.javacs.ktda.jdi.launch.JDILauncher
import org.junit.After
import org.junit.Assert.assertThat
import org.junit.Before
import org.hamcrest.Matchers.equalTo
abstract class DebugAdapterTestFixture(
relativeWorkspaceRoot: String,
private val mainClass: String
) : IDebugProtocolClient {
val absoluteWorkspaceRoot: Path = Paths.get(DebugAdapterTestFixture::class.java.getResource("/Anchor.txt").toURI()).parent.resolve(relativeWorkspaceRoot)
lateinit var debugAdapter: KotlinDebugAdapter
@Before fun startDebugAdapter() {
// Build the project first
val process = ProcessBuilder("./gradlew", "assemble")
.directory(absoluteWorkspaceRoot.toFile())
.inheritIO()
.start()
process.waitFor()
assertThat(process.exitValue(), equalTo(0))
debugAdapter = JDILauncher()
.let(::KotlinDebugAdapter)
.also {
it.connect(this)
val configDone = it.configurationDone(ConfigurationDoneArguments())
it.initialize(InitializeRequestArguments().apply {
adapterID = "test-debug-adapter"
linesStartAt1 = true
columnsStartAt1 = true
}).join()
// Slightly hacky workaround to ensure someone is
// waiting on the ConfigurationDoneResponse. See
// KotlinDebugAdapter.kt:performInitialization for
// details.
Thread {
configDone.join()
}.start()
// Wait until the thread has blocked on the future
while (configDone.numberOfDependents == 0) {
Thread.sleep(100)
}
}
}
fun launch() {
println("Launching...")
debugAdapter.launch(mapOf(
"projectRoot" to absoluteWorkspaceRoot.toString(),
"mainClass" to mainClass
)).join()
println("Launched")
}
@After fun closeDebugAdapter() {
debugAdapter.disconnect(DisconnectArguments()).join()
}
override fun output(args: OutputEventArguments) {
println(args.output)
}
}
| 32
|
Kotlin
|
19
| 96
|
7f05669b642d21afa46ac7b75307fa5d523a7263
| 2,649
|
kotlin-debug-adapter
|
MIT License
|
src/main/kotlin/com/virtlink/collections/MutableDisjointMap.kt
|
Virtlink
| 235,369,099
| false
| null |
package com.virtlink.collections
/**
* A transient disjoint map.
*
* @param K the type of keys
* @param V the type of values
*/
interface MutableDisjointMap<K, V> : DisjointMap<K, V> {
/**
* Sets the [value] of the set that contains the specified [key].
*
* If the key is not part of this map, it is added.
*
* @param key the key
* @param value the value to associate with the set that contains the specified [key]
* @return the value associated with the previous set that contained the key,
* or `null` if the key was not present in the map
*/
operator fun set(key: K, value: V): V?
/**
* Removes the specified [key] from this map.
*
* When the removed key was the final key in the set,
* the set is removed as well.
*
* @return the value associated with the previous set that contained the key,
* or `null` if the key was not present in the map
*/
fun remove(key: K): V?
/**
* Removes all sets from this map.
*/
fun clear()
/**
* Unifies the sets that include the given keys.
*
* When one or both of the keys don't exist in the map, they are added.
*
* @param key1 one key
* @param key2 another key
* @param default function that provides a default value to use when no value is specified
* @param compare function that compares the keys: the higher is used as the new representative;
* or 0 to use the rank to determine this
* @param unify function that unifies the associated values of each of the sets,
* where the first value is from the representative
*/
fun union(key1: K, key2: K, default: () -> V, compare: Comparator<K> = Comparator { _, _ -> 0 }, unify: (V, V) -> V)
/**
* Disunifies the given key from its set.
*
* This will create a new set with the given key and the value of the original set.
*
* @param key the key to disunify
* @throws NoSuchElementException the key is not in the map
*/
fun disunion(key: K)
/**
* Computes the value associated with the set that includes the given key.
*
* @param key the key to find
* @param mapping the mapping from the representative key and its existing value (or `null` when it doesn't exist) to a new value
* @return the computed value of the set that includes the given key
*/
fun compute(key: K, mapping: (K, V?) -> V): V
/**
* Computes the value if the set that includes the given key does already have an associated value.
*
* @param key the key to find
* @param mapping the mapping from the representative key and its existing value to a new value
* @return the computed value of the set that includes the given key; or `null` when it was not present
*/
fun computeIfPresent(key: K, mapping: (K, V) -> V): V?
/**
* Computes the value if the set that includes the given key does not already have an associated value.
*
* @param key the key to find
* @param mapping the mapping from the representative key to a value
* @return the computed value of the set that includes the given element
*/
fun computeIfAbsent(key: K, mapping: (K) -> V): V
/**
* Copies the sets from this disjoint map to a new map.
*
* @return the new map
*/
override fun toMap(): MutableMap<Set<K>, V>
}
| 1
| null |
1
| 1
|
e6bb272ac299737afd74a2293b9ada868b2eb9ad
| 3,421
|
disjoint-map
|
Apache License 2.0
|
engine/src/main/kotlin/de/hanno/hpengine/graphics/renderer/deferred/extensions/BvHPointLightSecondPassExtension.kt
|
hannomalie
| 330,376,962
| false
|
{"Kotlin": 911757, "GLSL": 695972, "JavaScript": 3160, "Shell": 137, "Batchfile": 65}
|
package de.hanno.hpengine.graphics.renderer.deferred.extensions
import BvhNodeGpuImpl.Companion.type
import Vector4fStruktImpl.Companion.sizeInBytes
import Vector4fStruktImpl.Companion.type
import de.hanno.hpengine.config.Config
import de.hanno.hpengine.graphics.GraphicsApi
import de.hanno.hpengine.graphics.state.RenderStateContext
import de.hanno.hpengine.graphics.light.point.PointLightSystem
import de.hanno.hpengine.graphics.profiled
import de.hanno.hpengine.graphics.renderer.addAABBLines
import de.hanno.hpengine.graphics.renderer.addLine
import de.hanno.hpengine.graphics.constants.TextureTarget
import de.hanno.hpengine.graphics.renderer.drawLines
import de.hanno.hpengine.graphics.renderer.deferred.DeferredRenderExtension
import de.hanno.hpengine.graphics.renderer.pipelines.IntStrukt
import de.hanno.hpengine.graphics.buffer.typed
import de.hanno.hpengine.graphics.shader.ProgramManager
import de.hanno.hpengine.graphics.state.RenderState
import de.hanno.hpengine.math.Vector4fStrukt
import de.hanno.hpengine.transform.AABB
import de.hanno.hpengine.transform.AABBData.Companion.getSurroundingAABB
import de.hanno.hpengine.Transform
import de.hanno.hpengine.model.EntitiesStateHolder
import de.hanno.hpengine.buffers.enlarge
import de.hanno.hpengine.graphics.state.PrimaryCameraStateHolder
import de.hanno.hpengine.graphics.Access
import de.hanno.hpengine.graphics.light.point.PointLightStateHolder
import de.hanno.hpengine.graphics.renderer.deferred.DeferredRenderingBuffer
import de.hanno.hpengine.graphics.shader.LinesProgramUniforms
import de.hanno.hpengine.graphics.shader.define.Defines
import de.hanno.hpengine.ressources.StringBasedCodeSource
import org.joml.Vector3f
import org.joml.Vector3fc
import org.joml.Vector4f
import org.koin.core.annotation.Single
import org.lwjgl.BufferUtils
import struktgen.api.Strukt
import struktgen.api.forIndex
import java.nio.ByteBuffer
interface BvhNodeGpu : Strukt {
context(ByteBuffer) val positionRadius: Vector4fStrukt
context(ByteBuffer) val missPointer: IntStrukt
context(ByteBuffer) val lightIndex: IntStrukt
context(ByteBuffer) val dummy0: IntStrukt
context(ByteBuffer) val dummy1: IntStrukt
companion object
}
typealias BoundingSphere = Vector4f
typealias Bvh = BvhNode
sealed class BvhNode(val boundingSphere: BoundingSphere) {
var parent: BvhNode? = null
class Inner(boundingSphere: BoundingSphere) : BvhNode(boundingSphere) {
val children = mutableListOf<BvhNode>()
fun add(child: BvhNode) {
child.parent = this
children.add(child)
}
}
class Leaf(boundingSphere: BoundingSphere, var lightIndex: Int) : BvhNode(boundingSphere)
}
val BvhNode.nodes: List<BvhNode>
get() = when (this) {
is BvhNode.Inner -> mutableListOf(this) + children.flatMap { it.nodes }
is BvhNode.Leaf -> mutableListOf(this)
}
val Bvh.nodeCount: Int
get() = when (this) {
is BvhNode.Inner -> 1 + children.sumBy { it.nodeCount }
is BvhNode.Leaf -> 1
}
fun MutableList<out BvhNode>.clustersOfN(n: Int = 4): MutableList<BvhNode.Inner> {
val result = mutableListOf<BvhNode.Inner>()
while (isNotEmpty()) {
val first = first()
remove(first)
val nearest =
asSequence().sortedBy { first.boundingSphere.xyz.distance(it.boundingSphere.xyz) }.take(n - 1).toList()
removeAll(nearest)
val nearestAndSelf = nearest + first
val pointsPerSphere = 8
val dimensions = 3
// val arrayPointSet = ArrayPointSet(dimensions, pointsPerSphere * nearestAndSelf.size).apply {
// nearestAndSelf.forEachIndexed { sphereIndex, bvhNode ->
// val min = bvhNode.boundingSphere.xyz.sub(Vector3f(bvhNode.boundingSphere.w))
// val max = bvhNode.boundingSphere.xyz.add(Vector3f(bvhNode.boundingSphere.w))
// val points = AABB(min, max).getPoints()
// points.forEachIndexed { pointIndex, point ->
// this.set(sphereIndex* pointsPerSphere + pointIndex, 0, point.x.toDouble())
// this.set(sphereIndex* pointsPerSphere + pointIndex, 1, point.y.toDouble())
// this.set(sphereIndex* pointsPerSphere + pointIndex, 2, point.z.toDouble())
// }
// }
// }
// val enclosingSphere = Miniball(arrayPointSet).run {
// Vector4f(center()[0].toFloat(), center()[1].toFloat(), center()[2].toFloat(), radius().toFloat())
// }
val enclosingSphere = nearestAndSelf.map { bvhNode ->
val min = bvhNode.boundingSphere.xyz.sub(Vector3f(bvhNode.boundingSphere.w))
val max = bvhNode.boundingSphere.xyz.add(Vector3f(bvhNode.boundingSphere.w))
AABB(min, max)
}.getSurroundingAABB()
.let { Vector4f(it.center.x, it.center.y, it.center.z, it.halfExtents.get(it.halfExtents.maxComponent())) }
val innerNode = BvhNode.Inner(enclosingSphere).apply {
nearestAndSelf.forEach {
this@apply.add(it)
}
}
result.add(innerNode)
}
return result
}
fun List<BvhNode.Leaf>.toTree(): BvhNode.Inner {
var candidates: MutableList<out BvhNode> = toMutableList()
while (candidates.any { it is BvhNode.Leaf } || candidates.size > 1) {
candidates = candidates.clustersOfN()
}
return candidates.first() as BvhNode.Inner
}
val Vector4f.xyz: Vector3f
get() = Vector3f(x, y, z)
@Single(binds = [BvHPointLightSecondPassExtension::class, DeferredRenderExtension::class])
class BvHPointLightSecondPassExtension(
private val config: Config,
private val graphicsApi: GraphicsApi,
private val renderStateContext: RenderStateContext,
private val programManager: ProgramManager,
private val deferredRenderingBuffer: DeferredRenderingBuffer,
private val pointLightStateHolder: PointLightStateHolder,
private val entitiesStateHolder: EntitiesStateHolder,
private val primaryCameraStateHolder: PrimaryCameraStateHolder,
) : DeferredRenderExtension {
private val lineVertices = graphicsApi.PersistentShaderStorageBuffer(100 * Vector4fStrukt.sizeInBytes).typed(Vector4fStrukt.type)
private val secondPassPointBvhComputeProgram =
programManager.getComputeProgram(config.EngineAsset("shaders/second_pass_point_trivial_bvh_compute.glsl"))
private val linesProgram = programManager.run {
val uniforms = LinesProgramUniforms(graphicsApi)
getProgram(
StringBasedCodeSource(
"mvp_vertex_vec4", """
//include(globals_structs.glsl)
${uniforms.shaderDeclarations}
in vec4 in_Position;
out vec4 pass_Position;
out vec4 pass_WorldPosition;
void main()
{
vec4 vertex = vertices[gl_VertexID];
vertex.w = 1;
pass_WorldPosition = ${uniforms::modelMatrix.name} * vertex;
pass_Position = ${uniforms::projectionMatrix.name} * ${uniforms::viewMatrix.name} * pass_WorldPosition;
gl_Position = pass_Position;
}
""".trimIndent()
),
StringBasedCodeSource(
"simple_color_vec3", """
${uniforms.shaderDeclarations}
layout(location=0)out vec4 out_color;
void main()
{
out_color = vec4(${uniforms::color.name},1);
}
""".trimIndent()
), null, Defines(), uniforms
)
}
private val identityMatrix44Buffer = BufferUtils.createFloatBuffer(16).apply {
Transform().get(this)
}
val bvh = graphicsApi.PersistentShaderStorageBuffer(BvhNodeGpu.type.sizeInBytes).typed(BvhNodeGpu.type)
fun Vector4f.set(other: Vector3f) {
x = other.x
y = other.y
z = other.z
}
private var bvhReconstructedInCycle = -1L
var nodeCount = 0
var tree: Bvh? = null
private fun BvhNode.Inner.putToBuffer() {
this@BvHPointLightSecondPassExtension.nodeCount = nodeCount
bvh.typedBuffer.enlarge(nodeCount)
var counter = 0
fun BvhNode.putToBufferHelper() {
when (this) {
is BvhNode.Inner -> {
bvh.typedBuffer.forIndex(counter) {
it.positionRadius.set(boundingSphere)
it.missPointer.value = counter + nodeCount
}
counter++
children.forEach { it.putToBufferHelper() }
}
is BvhNode.Leaf -> {
bvh.typedBuffer.forIndex(counter) {
it.positionRadius.set(boundingSphere)
it.missPointer.value = counter + 1
lightIndex = this@putToBufferHelper.lightIndex
}
counter++
}
}.let {}
}
putToBufferHelper()
}
override fun renderSecondPassFullScreen(renderState: RenderState) = graphicsApi.run {
val pointLightState = renderState[pointLightStateHolder.lightState]
if (pointLightState.pointLights.isEmpty()) {
return
}
val entitiesState = renderState[entitiesStateHolder.entitiesState]
// TODO: Move this to update
if (bvhReconstructedInCycle < pointLightState.pointLightMovedInCycle) {
// TODO: Reimplement this
// bvhReconstructedInCycle = renderState.cycle
// val leafNodes = renderState.lightState.pointLights.mapIndexed { index, light ->
// BvhNode.Leaf(Vector4f().apply {
// set(light.entity.transform.position)
// w = light.radius
// }, index)
// }.toMutableList()
// tree = leafNodes.toTree().apply {
// putToBuffer()
// }
}
profiled("Seconds pass PointLights BVH") {
val camera = renderState[primaryCameraStateHolder.camera]
val viewMatrix = camera.viewMatrixAsBuffer
val projectionMatrix = camera.projectionMatrixAsBuffer
graphicsApi.bindTexture(0, TextureTarget.TEXTURE_2D, deferredRenderingBuffer.positionMap)
graphicsApi.bindTexture(1, TextureTarget.TEXTURE_2D, deferredRenderingBuffer.normalMap)
graphicsApi.bindTexture(2, TextureTarget.TEXTURE_2D, deferredRenderingBuffer.colorReflectivenessMap)
graphicsApi.bindTexture(3, TextureTarget.TEXTURE_2D, deferredRenderingBuffer.motionMap)
graphicsApi.bindTexture(4, TextureTarget.TEXTURE_2D, deferredRenderingBuffer.lightAccumulationMapOneId)
graphicsApi.bindTexture(5, TextureTarget.TEXTURE_2D, deferredRenderingBuffer.visibilityMap)
pointLightState.pointLightShadowMapStrategy.bindTextures()
graphicsApi.bindImageTexture(
4,
deferredRenderingBuffer.lightAccumulationMapOneId,
0,
false,
0,
Access.ReadWrite,
InternalTextureFormat.RGBA16F
)
secondPassPointBvhComputeProgram.use()
secondPassPointBvhComputeProgram.setUniform("nodeCount", nodeCount)
secondPassPointBvhComputeProgram.setUniform("pointLightCount",
pointLightState.pointLights.size)
secondPassPointBvhComputeProgram.setUniform("screenWidth", config.width.toFloat())
secondPassPointBvhComputeProgram.setUniform("screenHeight", config.height.toFloat())
secondPassPointBvhComputeProgram.setUniformAsMatrix4("viewMatrix", viewMatrix)
secondPassPointBvhComputeProgram.setUniformAsMatrix4("projectionMatrix", projectionMatrix)
secondPassPointBvhComputeProgram.setUniform(
"maxPointLightShadowmaps",
PointLightSystem.MAX_POINTLIGHT_SHADOWMAPS
)
secondPassPointBvhComputeProgram.bindShaderStorageBuffer(1, entitiesState.materialBuffer)
secondPassPointBvhComputeProgram.bindShaderStorageBuffer(2,
pointLightState.pointLightBuffer)
secondPassPointBvhComputeProgram.bindShaderStorageBuffer(3, bvh)
secondPassPointBvhComputeProgram.dispatchCompute(config.width / 16, config.height / 16, 1)
}
}
override fun renderEditor(renderState: RenderState) {
if (config.debug.drawBvhInnerNodes) {
val linePoints = mutableListOf<Vector3fc>().apply {
tree?.run {
val innerNodes = nodes.filterIsInstance<BvhNode.Inner>()
innerNodes.forEach {
val centerSelf = it.boundingSphere.xyz
addAABBLines(
it.boundingSphere.xyz.sub(Vector3f(it.boundingSphere.w)),
it.boundingSphere.xyz.add(Vector3f(it.boundingSphere.w))
)
it.children.forEach { child ->
addLine(centerSelf, child.boundingSphere.xyz)
}
}
}
}
deferredRenderingBuffer.finalBuffer.use(false)
graphicsApi.blend = false
val camera = renderState[primaryCameraStateHolder.camera]
graphicsApi.drawLines(
programManager,
linesProgram,
lineVertices,
linePoints,
viewMatrix = camera.viewMatrixAsBuffer,
projectionMatrix = camera.projectionMatrixAsBuffer,
color = Vector3f(1f, 0f, 0f)
)
}
}
}
| 1
|
Kotlin
|
0
| 0
|
e6e84da028f30622d555209cf08f0df48348f4fa
| 13,865
|
hpengine
|
MIT License
|
app/src/main/java/com/tamzi/speakers/navigation/SpeakerNavHost.kt
|
tamzi
| 633,718,475
| false
| null |
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tamzi.speakers.navigation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import com.tamzi.speakers.feature.bookmarks.navigation.bookmarksScreen
import com.tamzi.speakers.feature.foryou.navigation.forYouNavigationRoute
import com.tamzi.speakers.feature.foryou.navigation.forYouScreen
import com.tamzi.speakers.feature.interests.navigation.interestsGraph
import com.tamzi.speakers.feature.search.navigation.searchScreen
import com.tamzi.speakers.feature.topic.navigation.navigateToTopic
import com.tamzi.speakers.feature.topic.navigation.topicScreen
import com.tamzi.speakers.navigation.TopLevelDestination.INTERESTS
import com.tamzi.speakers.ui.SpeakerAppState
/**
* Top-level navigation graph. Navigation is organized as explained at
* https://d.android.com/jetpack/compose/nav-adaptive
*
* The navigation graph defined in this file defines the different top level routes. Navigation
* within each route is handled using state and Back Handlers.
*/
@Composable
fun SpeakerNavHost(
appState: SpeakerAppState,
modifier: Modifier = Modifier,
startDestination: String = forYouNavigationRoute,
) {
val navController = appState.navController
NavHost(
navController = navController,
startDestination = startDestination,
modifier = modifier,
) {
// TODO: handle topic clicks from each top level destination
forYouScreen(onTopicClick = {})
bookmarksScreen(onTopicClick = {})
searchScreen(
onBackClick = navController::popBackStack,
onInterestsClick = { appState.navigateToTopLevelDestination(INTERESTS) },
onTopicClick = navController::navigateToTopic,
)
interestsGraph(
onTopicClick = { topicId ->
navController.navigateToTopic(topicId)
},
nestedGraphs = {
topicScreen(
onBackClick = navController::popBackStack,
onTopicClick = {},
)
},
)
}
}
| 0
|
Kotlin
|
0
| 0
|
e89849386575462b23029fc1961faad1217e3ed2
| 2,751
|
speakers
|
Apache License 2.0
|
app/src/main/java/com/example/myapplication/widget/FGandBGWidgets/BuildRequest.kt
|
hitmansixteen
| 800,499,147
| false
|
{"Kotlin": 331925}
|
package com.example.myapplication.widget.FGandBGWidgets
import androidx.compose.runtime.mutableStateOf
import okhttp3.FormBody
import okhttp3.Request
var selectedColors=null
val httpLink="https://183a-2400-adc5-458-8a00-8918-3c29-6c5f-9880.ngrok-free.app"
val url=httpLink+"/req"
fun buildRequest(formBody: FormBody): Request {
return Request.Builder()
.url(url)
.post(formBody)
.build()
}
| 0
|
Kotlin
|
0
| 0
|
ba9dbe7d132ee097a681df4ddd76904aa5adb095
| 421
|
instant-studio
|
MIT License
|
app/src/main/java/com/example/myapplication/widget/FGandBGWidgets/BuildRequest.kt
|
hitmansixteen
| 800,499,147
| false
|
{"Kotlin": 331925}
|
package com.example.myapplication.widget.FGandBGWidgets
import androidx.compose.runtime.mutableStateOf
import okhttp3.FormBody
import okhttp3.Request
var selectedColors=null
val httpLink="https://183a-2400-adc5-458-8a00-8918-3c29-6c5f-9880.ngrok-free.app"
val url=httpLink+"/req"
fun buildRequest(formBody: FormBody): Request {
return Request.Builder()
.url(url)
.post(formBody)
.build()
}
| 0
|
Kotlin
|
0
| 0
|
ba9dbe7d132ee097a681df4ddd76904aa5adb095
| 421
|
instant-studio
|
MIT License
|
JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/ext/download/DownLoadManager.kt
|
q735510971
| 316,208,478
| false
| null |
package me.hgj.jetpackmvvm.ext.download
import android.os.Looper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.ext.util.logi
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.io.File
import java.util.concurrent.TimeUnit
/**
* @author : hgj
* @date : 2020/7/13
*/
object DownLoadManager {
private val retrofitBuilder by lazy {
Retrofit.Builder()
.baseUrl("https://www.baidu.com")
.client(
OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS).build()
).build()
}
/**
*开始下载
* @param tag String 标识
* @param url String 下载的url
* @param savePath String 保存的路径
* @param saveName String 保存的名字
* @param reDownload Boolean 如果文件已存在是否需要重新下载 默认不需要重新下载
* @param loadListener OnDownLoadListener
*/
suspend fun downLoad(
tag: String,
url: String,
savePath: String,
saveName: String,
reDownload: Boolean = false,
loadListener: OnDownLoadListener
) {
withContext(Dispatchers.IO) {
doDownLoad(tag, url, savePath, saveName, reDownload, loadListener, this)
}
}
/**
* 取消下载
* @param key String 取消的标识
*/
fun cancel(key: String) {
val path = DownLoadPool.getPathFromKey(key)
if (path != null) {
val file = File(path)
if (file.exists()) {
file.delete()
}
}
DownLoadPool.remove(key)
}
/**
* 暂停下载
* @param key String 暂停的标识
*/
fun pause(key: String) {
val listener = DownLoadPool.getListenerFromKey(key)
listener?.onDownLoadPause(key)
DownLoadPool.pause(key)
}
/**
* 取消所有下载
*/
fun doDownLoadCancelAll() {
DownLoadPool.getListenerMap().forEach {
cancel(it.key)
}
}
/**
* 暂停所有下载
*/
fun doDownLoadPauseAll() {
DownLoadPool.getListenerMap().forEach {
pause(it.key)
}
}
/**
*下载
* @param tag String 标识
* @param url String 下载的url
* @param savePath String 保存的路径
* @param saveName String 保存的名字
* @param reDownload Boolean 如果文件已存在是否需要重新下载 默认不需要重新下载
* @param loadListener OnDownLoadListener
* @param coroutineScope CoroutineScope 上下文
*/
private suspend fun doDownLoad(
tag: String,
url: String,
savePath: String,
saveName: String,
reDownload: Boolean,
loadListener: OnDownLoadListener,
coroutineScope: CoroutineScope
) {
//判断是否已经在队列中
val scope = DownLoadPool.getScopeFromKey(tag)
if (scope != null && scope.isActive) {
"已经在队列中".logi()
return
} else if (scope != null && !scope.isActive) {
"key $tag 已经在队列中 但是已经不再活跃 remove".logi()
DownLoadPool.removeExitSp(tag)
}
if (saveName.isEmpty()) {
withContext(Dispatchers.Main) {
loadListener.onDownLoadError(tag, Throwable("save name is Empty"))
}
return
}
if (Looper.getMainLooper().thread == Thread.currentThread()) {
withContext(Dispatchers.Main) {
loadListener.onDownLoadError(tag, Throwable("current thread is in main thread"))
}
return
}
val file = File("$savePath/$saveName")
val currentLength = if (!file.exists()) {
0L
} else {
ShareDownLoadUtil.getLong(tag, 0)
}
if (file.exists()&¤tLength == 0L && !reDownload) {
//文件已存在了
loadListener.onDownLoadSuccess(tag, file.path, file.length())
return
}
"startDownLoad current $currentLength".logi()
try {
//添加到pool
DownLoadPool.add(tag, coroutineScope)
DownLoadPool.add(tag, "$savePath/$saveName")
DownLoadPool.add(tag, loadListener)
withContext(Dispatchers.Main) {
loadListener.onDownLoadPrepare(key = tag)
}
val response = retrofitBuilder.create(DownLoadService::class.java)
.downloadFile("bytes=$currentLength-", url)
val responseBody = response.body()
if (responseBody == null) {
"responseBody is null".logi()
withContext(Dispatchers.Main) {
loadListener.onDownLoadError(
key = tag,
throwable = Throwable("responseBody is null please check download url")
)
}
DownLoadPool.remove(tag)
return
}
FileTool.downToFile(
tag,
savePath,
saveName,
currentLength,
responseBody,
loadListener
)
} catch (throwable: Throwable) {
withContext(Dispatchers.Main) {
loadListener.onDownLoadError(key = tag, throwable = throwable)
}
DownLoadPool.remove(tag)
}
}
}
| 1
| null |
1
| 3
|
22a993aacbd3b8d5f10caa0c11e055d71e8c1b9d
| 5,448
|
JetpackMvvm
|
Apache License 2.0
|
solar/src/main/java/com/chiksmedina/solar/boldduotone/call/RecordMinimalistic.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.boldduotone.call
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 com.chiksmedina.solar.boldduotone.CallGroup
val CallGroup.RecordMinimalistic: ImageVector
get() {
if (_recordMinimalistic != null) {
return _recordMinimalistic!!
}
_recordMinimalistic = Builder(
name = "RecordMinimalistic", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(22.0f, 12.0f)
curveTo(22.0f, 14.2091f, 20.2091f, 16.0f, 18.0f, 16.0f)
curveTo(15.7909f, 16.0f, 14.0f, 14.2091f, 14.0f, 12.0f)
curveTo(14.0f, 9.7909f, 15.7909f, 8.0f, 18.0f, 8.0f)
curveTo(20.2091f, 8.0f, 22.0f, 9.7909f, 22.0f, 12.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(10.0f, 12.0f)
curveTo(10.0f, 14.2091f, 8.2091f, 16.0f, 6.0f, 16.0f)
curveTo(3.7909f, 16.0f, 2.0f, 14.2091f, 2.0f, 12.0f)
curveTo(2.0f, 9.7909f, 3.7909f, 8.0f, 6.0f, 8.0f)
curveTo(8.2091f, 8.0f, 10.0f, 9.7909f, 10.0f, 12.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha
= 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(6.0f, 16.0f)
horizontalLineTo(18.0f)
curveTo(16.9856f, 16.0f, 16.0593f, 15.6224f, 15.3542f, 15.0f)
horizontalLineTo(8.6458f)
curveTo(7.9407f, 15.6224f, 7.0145f, 16.0f, 6.0f, 16.0f)
close()
}
}
.build()
return _recordMinimalistic!!
}
private var _recordMinimalistic: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 2,873
|
SolarIconSetAndroid
|
MIT License
|
valiktor-samples/valiktor-sample-custom-formatter/src/test/kotlin/org/valiktor/sample/SampleApplicationTest.kt
|
Hc747
| 193,990,150
| true
|
{"Kotlin": 1795725}
|
/*
* Copyright 2018-2019 https://www.valiktor.org
*
* 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.valiktor.sample
import org.assertj.core.api.Assertions.assertThat
import org.valiktor.ConstraintViolationException
import org.valiktor.DefaultConstraintViolation
import org.valiktor.constraints.Greater
import kotlin.test.Test
import kotlin.test.assertFailsWith
class SampleApplicationTest {
@Test
fun `should validate employee`() {
val exception = assertFailsWith<ConstraintViolationException> {
Employee(document = Document(0))
}
assertThat(exception.constraintViolations).containsExactly(
DefaultConstraintViolation(property = "document", value = Document(0), constraint = Greater(Document(0)))
)
}
}
| 0
|
Kotlin
|
0
| 0
|
6304e77d5d8751ebcb38f619cb2c855ebf2e558b
| 1,296
|
valiktor
|
Apache License 2.0
|
plugins/parcelize/parcelize-compiler/testData/box/functions.kt
|
JetBrains
| 3,432,266
| false
| null |
// WITH_STDLIB
// LAMBDAS: CLASS
@file:JvmName("TestKt")
package test
import kotlinx.android.parcel.*
import android.os.Parcel
import android.os.Parcelable
@Parcelize
data class Test(val callback: () -> Int = { 0 }, val suspendCallback: suspend () -> Int = { 0 }) : Parcelable
fun box() = parcelTest { parcel ->
val test = Test({ 1 }, { 1 })
test.writeToParcel(parcel, 0)
val bytes = parcel.marshall()
parcel.unmarshall(bytes, 0, bytes.size)
parcel.setDataPosition(0)
val test2 = readFromParcel<Test>(parcel)
assert(test.callback() == 1)
}
| 182
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 575
|
kotlin
|
Apache License 2.0
|
wrapper/godot-library/src/main/kotlin/godot/generated/EditorPlugin.kt
|
payload
| 189,718,948
| true
|
{"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574}
|
@file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch")
package godot
import godot.gdnative.*
import godot.core.*
import godot.utils.*
import godot.icalls.*
import kotlinx.cinterop.*
// NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG
open class EditorPlugin : Node {
constructor() : super("EditorPlugin")
constructor(variant: Variant) : super(variant)
internal constructor(mem: COpaquePointer) : super(mem)
internal constructor(name: String) : super(name)
// Enums
enum class DockSlot(val id: Long) {
DOCK_SLOT_LEFT_UL(0),
DOCK_SLOT_LEFT_BL(1),
DOCK_SLOT_LEFT_UR(2),
DOCK_SLOT_LEFT_BR(3),
DOCK_SLOT_RIGHT_UL(4),
DOCK_SLOT_RIGHT_BL(5),
DOCK_SLOT_RIGHT_UR(6),
DOCK_SLOT_RIGHT_BR(7),
DOCK_SLOT_MAX(8),
;
companion object {
fun fromInt(value: Long) = values().single { it.id == value }
}
}
enum class CustomControlContainer(val id: Long) {
CONTAINER_TOOLBAR(0),
CONTAINER_SPATIAL_EDITOR_MENU(1),
CONTAINER_SPATIAL_EDITOR_SIDE(2),
CONTAINER_SPATIAL_EDITOR_BOTTOM(3),
CONTAINER_CANVAS_EDITOR_MENU(4),
CONTAINER_CANVAS_EDITOR_SIDE(5),
CONTAINER_CANVAS_EDITOR_BOTTOM(6),
CONTAINER_PROPERTY_EDITOR_BOTTOM(7),
;
companion object {
fun fromInt(value: Long) = values().single { it.id == value }
}
}
// Signals
class Signal {
companion object {
const val MAIN_SCREEN_CHANGED: String = "main_screen_changed"
const val SCENE_CLOSED: String = "scene_closed"
const val SCENE_CHANGED: String = "scene_changed"
const val RESOURCE_SAVED: String = "resource_saved"
}
}
companion object {
infix fun from(other: Node): EditorPlugin = EditorPlugin("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Object): EditorPlugin = EditorPlugin("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Variant): EditorPlugin = fromVariant(EditorPlugin(""), other)
// Constants
const val CONTAINER_TOOLBAR: Long = 0
const val CONTAINER_SPATIAL_EDITOR_MENU: Long = 1
const val CONTAINER_SPATIAL_EDITOR_SIDE: Long = 2
const val CONTAINER_SPATIAL_EDITOR_BOTTOM: Long = 3
const val CONTAINER_CANVAS_EDITOR_MENU: Long = 4
const val CONTAINER_CANVAS_EDITOR_SIDE: Long = 5
const val CONTAINER_CANVAS_EDITOR_BOTTOM: Long = 6
const val CONTAINER_PROPERTY_EDITOR_BOTTOM: Long = 7
const val DOCK_SLOT_LEFT_UL: Long = 0
const val DOCK_SLOT_LEFT_BL: Long = 1
const val DOCK_SLOT_LEFT_UR: Long = 2
const val DOCK_SLOT_LEFT_BR: Long = 3
const val DOCK_SLOT_RIGHT_UL: Long = 4
const val DOCK_SLOT_RIGHT_BL: Long = 5
const val DOCK_SLOT_RIGHT_UR: Long = 6
const val DOCK_SLOT_RIGHT_BR: Long = 7
const val DOCK_SLOT_MAX: Long = 8
}
// Properties
// Methods
open fun forward_canvas_gui_input(event: InputEvent): Boolean {
throw NotImplementedError("forward_canvas_gui_input is not implemented for EditorPlugin")
}
open fun forward_draw_over_viewport(overlay: Control) {
}
open fun forward_force_draw_over_viewport(overlay: Control) {
}
open fun forward_spatial_gui_input(camera: Camera, event: InputEvent): Boolean {
throw NotImplementedError("forward_spatial_gui_input is not implemented for EditorPlugin")
}
open fun create_spatial_gizmo(forSpatial: Spatial): EditorSpatialGizmo {
throw NotImplementedError("create_spatial_gizmo is not implemented for EditorPlugin")
}
open fun get_plugin_name(): String {
throw NotImplementedError("get_plugin_name is not implemented for EditorPlugin")
}
open fun get_plugin_icon(): Object {
throw NotImplementedError("get_plugin_icon is not implemented for EditorPlugin")
}
open fun has_main_screen(): Boolean {
throw NotImplementedError("has_main_screen is not implemented for EditorPlugin")
}
open fun make_visible(visible: Boolean) {
}
open fun edit(_object: Object) {
}
open fun handles(_object: Object): Boolean {
throw NotImplementedError("handles is not implemented for EditorPlugin")
}
open fun get_state(): Dictionary {
throw NotImplementedError("get_state is not implemented for EditorPlugin")
}
open fun set_state(state: Dictionary) {
}
open fun clear() {
}
open fun save_external_data() {
}
open fun apply_changes() {
}
open fun get_breakpoints(): PoolStringArray {
throw NotImplementedError("get_breakpoints is not implemented for EditorPlugin")
}
open fun set_window_layout(layout: ConfigFile) {
}
open fun get_window_layout(layout: ConfigFile) {
}
open fun build(): Boolean {
throw NotImplementedError("build is not implemented for EditorPlugin")
}
private val addControlToContainerMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_control_to_container") }
open fun addControlToContainer(container: Long, control: Object) {
_icall_Unit_Long_Object(addControlToContainerMethodBind, this.rawMemory, container, control)
}
private val addControlToBottomPanelMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_control_to_bottom_panel") }
open fun addControlToBottomPanel(control: Object, title: String): ToolButton {
return _icall_ToolButton_Object_String(addControlToBottomPanelMethodBind, this.rawMemory, control, title)
}
private val addControlToDockMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_control_to_dock") }
open fun addControlToDock(slot: Long, control: Object) {
_icall_Unit_Long_Object(addControlToDockMethodBind, this.rawMemory, slot, control)
}
private val removeControlFromDocksMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_control_from_docks") }
open fun removeControlFromDocks(control: Object) {
_icall_Unit_Object(removeControlFromDocksMethodBind, this.rawMemory, control)
}
private val removeControlFromBottomPanelMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_control_from_bottom_panel") }
open fun removeControlFromBottomPanel(control: Object) {
_icall_Unit_Object(removeControlFromBottomPanelMethodBind, this.rawMemory, control)
}
private val removeControlFromContainerMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_control_from_container") }
open fun removeControlFromContainer(container: Long, control: Object) {
_icall_Unit_Long_Object(removeControlFromContainerMethodBind, this.rawMemory, container, control)
}
private val addToolMenuItemMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_tool_menu_item") }
open fun addToolMenuItem(name: String, handler: Object, callback: String, ud: Variant? = null) {
_icall_Unit_String_Object_String_nVariant(addToolMenuItemMethodBind, this.rawMemory, name, handler, callback, ud)
}
private val addToolSubmenuItemMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_tool_submenu_item") }
open fun addToolSubmenuItem(name: String, submenu: Object) {
_icall_Unit_String_Object(addToolSubmenuItemMethodBind, this.rawMemory, name, submenu)
}
private val removeToolMenuItemMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_tool_menu_item") }
open fun removeToolMenuItem(name: String) {
_icall_Unit_String(removeToolMenuItemMethodBind, this.rawMemory, name)
}
private val addCustomTypeMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_custom_type") }
open fun addCustomType(type: String, base: String, script: Script, icon: Texture) {
_icall_Unit_String_String_Object_Object(addCustomTypeMethodBind, this.rawMemory, type, base, script, icon)
}
private val removeCustomTypeMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_custom_type") }
open fun removeCustomType(type: String) {
_icall_Unit_String(removeCustomTypeMethodBind, this.rawMemory, type)
}
private val addAutoloadSingletonMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_autoload_singleton") }
open fun addAutoloadSingleton(name: String, path: String) {
_icall_Unit_String_String(addAutoloadSingletonMethodBind, this.rawMemory, name, path)
}
private val removeAutoloadSingletonMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_autoload_singleton") }
open fun removeAutoloadSingleton(name: String) {
_icall_Unit_String(removeAutoloadSingletonMethodBind, this.rawMemory, name)
}
private val updateOverlaysMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "update_overlays") }
open fun updateOverlays(): Long {
return _icall_Long(updateOverlaysMethodBind, this.rawMemory)
}
private val makeBottomPanelItemVisibleMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "make_bottom_panel_item_visible") }
open fun makeBottomPanelItemVisible(item: Object) {
_icall_Unit_Object(makeBottomPanelItemVisibleMethodBind, this.rawMemory, item)
}
private val hideBottomPanelMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "hide_bottom_panel") }
open fun hideBottomPanel() {
_icall_Unit(hideBottomPanelMethodBind, this.rawMemory)
}
private val getUndoRedoMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "get_undo_redo") }
open fun getUndoRedo(): UndoRedo {
return _icall_UndoRedo(getUndoRedoMethodBind, this.rawMemory)
}
private val queueSaveLayoutMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "queue_save_layout") }
open fun queueSaveLayout() {
_icall_Unit(queueSaveLayoutMethodBind, this.rawMemory)
}
private val addImportPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_import_plugin") }
open fun addImportPlugin(importer: EditorImportPlugin) {
_icall_Unit_Object(addImportPluginMethodBind, this.rawMemory, importer)
}
private val removeImportPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_import_plugin") }
open fun removeImportPlugin(importer: EditorImportPlugin) {
_icall_Unit_Object(removeImportPluginMethodBind, this.rawMemory, importer)
}
private val addSceneImportPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_scene_import_plugin") }
open fun addSceneImportPlugin(sceneImporter: EditorSceneImporter) {
_icall_Unit_Object(addSceneImportPluginMethodBind, this.rawMemory, sceneImporter)
}
private val removeSceneImportPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_scene_import_plugin") }
open fun removeSceneImportPlugin(sceneImporter: EditorSceneImporter) {
_icall_Unit_Object(removeSceneImportPluginMethodBind, this.rawMemory, sceneImporter)
}
private val addExportPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_export_plugin") }
open fun addExportPlugin(plugin: EditorExportPlugin) {
_icall_Unit_Object(addExportPluginMethodBind, this.rawMemory, plugin)
}
private val removeExportPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_export_plugin") }
open fun removeExportPlugin(plugin: EditorExportPlugin) {
_icall_Unit_Object(removeExportPluginMethodBind, this.rawMemory, plugin)
}
private val addInspectorPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "add_inspector_plugin") }
open fun addInspectorPlugin(plugin: EditorInspectorPlugin) {
_icall_Unit_Object(addInspectorPluginMethodBind, this.rawMemory, plugin)
}
private val removeInspectorPluginMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "remove_inspector_plugin") }
open fun removeInspectorPlugin(plugin: EditorInspectorPlugin) {
_icall_Unit_Object(removeInspectorPluginMethodBind, this.rawMemory, plugin)
}
private val setInputEventForwardingAlwaysEnabledMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "set_input_event_forwarding_always_enabled") }
open fun setInputEventForwardingAlwaysEnabled() {
_icall_Unit(setInputEventForwardingAlwaysEnabledMethodBind, this.rawMemory)
}
private val setForceDrawOverForwardingEnabledMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "set_force_draw_over_forwarding_enabled") }
open fun setForceDrawOverForwardingEnabled() {
_icall_Unit(setForceDrawOverForwardingEnabledMethodBind, this.rawMemory)
}
private val getEditorInterfaceMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "get_editor_interface") }
open fun getEditorInterface(): EditorInterface {
return _icall_EditorInterface(getEditorInterfaceMethodBind, this.rawMemory)
}
private val getScriptCreateDialogMethodBind: CPointer<godot_method_bind> by lazy { getMB("EditorPlugin", "get_script_create_dialog") }
open fun getScriptCreateDialog(): ScriptCreateDialog {
return _icall_ScriptCreateDialog(getScriptCreateDialogMethodBind, this.rawMemory)
}
}
| 0
|
Kotlin
|
1
| 2
|
70473f9b9a0de08d82222b735e7f9b07bbe91700
| 13,976
|
kotlin-godot-wrapper
|
Apache License 2.0
|
.teamcity/patches/buildTypes/WindowsNetFxTesting_2019.kts
|
OctopusDeploy
| 294,316,810
| false
|
{"C#": 210802, "Kotlin": 41551, "PowerShell": 3005, "Shell": 2342, "Batchfile": 214}
|
package patches.buildTypes
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.CommitStatusPublisher
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.commitStatusPublisher
import jetbrains.buildServer.configs.kotlin.v2019_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, change the buildType with id = 'NetcoreTesting_CentOS'
accordingly, and delete the patch script.
*/
changeBuildType(RelativeId("NetcoreTesting_CentOS")) {
vcs {
add(DslContext.settingsRoot.id!!)
}
features {
val feature1 = find<CommitStatusPublisher> {
commitStatusPublisher {
publisher = github {
githubUrl = "https://api.github.com"
authType = personalToken {
token = "<PASSWORD><PASSWORD>"
}
}
}
}
feature1.apply {
publisher = github {
githubUrl = "https://api.github.com"
authType = personalToken {
token = "<PASSWORD><PASSWORD>"
}
}
}
}
}
| 0
|
C#
|
3
| 1
|
9d6a8e9c97f66f1c0ab24a22f9ddc00e30d25b13
| 1,242
|
Sashimi.AzureAppService
|
Apache License 2.0
|
src/main/java/com/wald/mainject/inject/definition/ComponentKey.kt
|
Waldemared
| 338,810,220
| false
| null |
package com.wald.mainject.inject.definition
import com.wald.mainject.inject.InstanceBasedQualifierDescriptor
import com.wald.mainject.inject.QualifierDescriptor
import com.wald.mainject.inject.TypeBasedQualifierDescriptor
import com.wald.mainject.inject.qualify.AnnotationType
import kotlin.reflect.KType
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.typeOf
/**
* @author vkosolapov
* @since
*/
interface ComponentKey {
val type: KType
val qualifiers: List<QualifierDescriptor>
}
class PlainComponentKey(override val type: KType,
override val qualifiers: List<QualifierDescriptor>) : ComponentKey {
constructor(javaType: Class<*>, qualifiers: List<QualifierDescriptor>) : this(
type = javaType.kotlin.starProjectedType,
qualifiers = qualifiers
)
}
fun ComponentKey.satisfies(specificationKey: ComponentKey) =
type.isSubtypeOf(specificationKey.type) && qualifiers.containsAll(specificationKey.qualifiers)
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified T : Any> keyOfType(builder: ComponentKeyBuilder.() -> Unit): ComponentKey {
return ComponentKeyBuilder(typeOf<T>()).apply(builder).build()
}
class ComponentKeyBuilder(private var type: KType) {
private var qualifiers = mutableListOf<QualifierDescriptor>()
inline fun <reified T : Annotation> qualifiedWith() = qualifiedWith(T::class)
fun qualifiedWith(qualifier: Annotation) = apply { qualifiers += InstanceBasedQualifierDescriptor(qualifier) }
fun qualifiedWith(qualifierType: AnnotationType) = apply { qualifiers += TypeBasedQualifierDescriptor(qualifierType) }
fun build() = PlainComponentKey(type, qualifiers)
}
| 1
| null |
1
| 1
|
eb8ea2dc2697f1d96636cceb1e97ca044b2fd89f
| 1,737
|
mainject-core
|
MIT License
|
data/trailers/api/src/commonMain/kotlin/com.thomaskioko.tvmaniac.data.trailers.implementation/TrailerRepository.kt
|
thomaskioko
| 361,393,353
| false
| null |
package com.thomaskioko.tvmaniac.data.trailers.implementation
import com.thomaskioko.tvmaniac.core.db.Trailers
import com.thomaskioko.tvmaniac.core.networkutil.model.Either
import com.thomaskioko.tvmaniac.core.networkutil.model.Failure
import kotlinx.coroutines.flow.Flow
interface TrailerRepository {
fun isYoutubePlayerInstalled(): Flow<Boolean>
fun observeTrailersStoreResponse(id: Long): Flow<Either<Failure, List<Trailers>>>
suspend fun fetchTrailersByShowId(id: Long): List<Trailers>
}
| 7
| null |
24
| 217
|
90d74c48f6d6016c0081363eca2271fe5591b692
| 502
|
tv-maniac
|
Apache License 2.0
|
dataforge-meta/src/commonMain/kotlin/space/kscience/dataforge/meta/exoticValues.kt
|
SciProgCentre
| 148,831,678
| false
|
{"Kotlin": 408170}
|
package space.kscience.dataforge.meta
import space.kscience.dataforge.names.Name
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
/**
* A value built from string which content and type are parsed on-demand
*/
public class LazyParsedValue(public val string: String) : Value {
private val parsedValue by lazy { Value.parse(string) }
override val value: Any? get() = parsedValue.value
override val type: ValueType get() = parsedValue.type
override fun toString(): String = string
override fun equals(other: Any?): Boolean = other is Value && this.parsedValue == other
override fun hashCode(): Int = string.hashCode()
}
public fun String.lazyParseValue(): LazyParsedValue = LazyParsedValue(this)
/**
* A performance optimized version of list value for doubles
*/
public class DoubleArrayValue(override val value: DoubleArray) : Value, Iterable<Double> {
override val type: ValueType get() = ValueType.LIST
override val list: List<Value> get() = value.map { NumberValue(it) }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Value) return false
return when (other) {
is DoubleArrayValue -> value.contentEquals(other.value)
else -> list == other.list
}
}
override fun hashCode(): Int = value.contentHashCode()
override fun toString(): String = list.joinToString(prefix = "[", postfix = "]")
override fun iterator(): Iterator<Double> = value.iterator()
}
public fun DoubleArray.asValue(): Value = if (isEmpty()) Null else DoubleArrayValue(this)
public val Value.doubleArray: DoubleArray
get() = if (this is DoubleArrayValue) {
value
} else {
DoubleArray(list.size) { list[it].double }
}
public val Meta?.doubleArray: DoubleArray? get() = this?.value?.doubleArray
public fun MetaProvider.doubleArray(
vararg default: Double,
key: Name? = null,
): ReadOnlyProperty<Any?, DoubleArray> = value(
key,
reader = { it?.doubleArray ?: doubleArrayOf(*default) },
)
public fun MutableMetaProvider.doubleArray(
vararg default: Double,
key: Name? = null,
): ReadWriteProperty<Any?, DoubleArray> = value(
key,
writer = { DoubleArrayValue(it) },
reader = { it?.doubleArray ?: doubleArrayOf(*default) },
)
public class ByteArrayValue(override val value: ByteArray) : Value, Iterable<Byte> {
override val type: ValueType get() = ValueType.LIST
override val list: List<Value> get() = value.map { NumberValue(it) }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Value) return false
return when (other) {
is ByteArrayValue -> value.contentEquals(other.value)
else -> list == other.list
}
}
override fun hashCode(): Int = value.contentHashCode()
override fun toString(): String = list.joinToString(prefix = "[", postfix = "]")
override fun iterator(): Iterator<Byte> = value.iterator()
}
public fun ByteArray.asValue(): Value = ByteArrayValue(this)
public val Value.byteArray: ByteArray
get() = if (this is ByteArrayValue) {
value
} else {
ByteArray(list.size) { list[it].number.toByte() }
}
public val Meta?.byteArray: ByteArray? get() = this?.value?.byteArray
public fun MetaProvider.byteArray(
vararg default: Byte,
key: Name? = null,
): ReadOnlyProperty<Any?, ByteArray> = value(
key,
reader = { it?.byteArray ?: byteArrayOf(*default) },
)
public fun MutableMetaProvider.byteArray(
vararg default: Byte,
key: Name? = null,
): ReadWriteProperty<Any?, ByteArray> = value(
key,
writer = { ByteArrayValue(it) },
reader = { it?.byteArray ?: byteArrayOf(*default) },
)
| 14
|
Kotlin
|
3
| 25
|
d80846d5fbd4d232b7506f5b4124cddfdc61d17e
| 3,813
|
dataforge-core
|
Apache License 2.0
|
performance/performance/src/main/java/com/emergetools/test/EmergeLocalJUnit4ClassRunner.kt
|
EmergeTools
| 645,957,551
| false
| null |
package com.emergetools.test
import androidx.benchmark.perfetto.ExperimentalPerfettoCaptureApi
import androidx.benchmark.perfetto.ExperimentalPerfettoTraceProcessorApi
import androidx.benchmark.perfetto.PerfettoTrace
import androidx.benchmark.perfetto.PerfettoTraceProcessor
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import com.emergetools.test.annotations.EmergeInit
import com.emergetools.test.annotations.EmergeSetup
import com.emergetools.test.annotations.EmergeStartupTest
import com.emergetools.test.annotations.EmergeTest
import com.emergetools.test.utils.clearTargetAppData
import com.emergetools.test.utils.maybeForceStopApp
import com.emergetools.test.utils.perfetto.querySpans
import hu.webarticum.treeprinter.Insets
import hu.webarticum.treeprinter.SimpleTreeNode
import hu.webarticum.treeprinter.decorator.BorderTreeNodeDecorator
import hu.webarticum.treeprinter.decorator.PadTreeNodeDecorator
import hu.webarticum.treeprinter.printer.listing.ListingTreePrinter
import hu.webarticum.treeprinter.text.AnsiFormat
import hu.webarticum.treeprinter.text.ConsoleText
import org.junit.internal.runners.model.ReflectiveCallable
import org.junit.internal.runners.statements.Fail
import org.junit.runner.notification.RunNotifier
import org.junit.runners.model.FrameworkMethod
import org.junit.runners.model.Statement
/**
* Runs tests annotated with @EmergeTest as well as related @EmergeInit and @EmergeSetup functions.
*/
@OptIn(
ExperimentalPerfettoTraceProcessorApi::class,
ExperimentalPerfettoCaptureApi::class
)
class EmergeLocalJUnit4ClassRunner(testClass: Class<*>) : AndroidJUnit4ClassRunner(testClass) {
private val initMethods = this.testClass.getAnnotatedMethods(EmergeInit::class.java)
private val setupMethods = this.testClass.getAnnotatedMethods(EmergeSetup::class.java)
private val testMethods = this.testClass.getAnnotatedMethods(EmergeTest::class.java)
private val startupTestMethods = this.testClass.getAnnotatedMethods(EmergeStartupTest::class.java)
private val summaries = mutableListOf<MethodSummary>()
private var initCalled = false
private val targetPackageName by lazy {
checkNotNull(InstrumentationRegistry.getArguments().getString(ARG_PACKAGE_NAME)) {
"Missing argument: $ARG_PACKAGE_NAME"
}
}
override fun run(notifier: RunNotifier?) {
super.run(notifier)
initMethods.drop(1).forEach {
addSummary(EmergeInit::class.java, it) {
"Only one $EMERGE_INIT method per class is supported"
}
}
setupMethods.drop(1).forEach {
addSummary(EmergeSetup::class.java, it) {
"Only one $EMERGE_SETUP method per class is supported"
}
}
printResults()
}
override fun methodBlock(method: FrameworkMethod): Statement {
val test: Any = try {
object : ReflectiveCallable() {
@Throws(Throwable::class)
override fun runReflectiveCall(): Any {
return createTest()
}
}.run()
} catch (e: Throwable) {
return Fail(e)
}
val emergeInit = if (!initCalled) {
initCalled = true
emergeInitInvoker(test)
} else {
null
}
val emergeSetup = emergeSetupInvoker(test)
var statement = methodInvoker(method, test)
statement = possiblyExpectingExceptions(method, test, statement)
statement = withBefores(method, test, statement)
statement = withAfters(method, test, statement)
return object : Statement() {
override fun evaluate() {
UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).pressHome()
emergeInit?.let {
maybeForceStopApp()
clearTargetAppData()
it.evaluate()
}
maybeForceStopApp()
emergeSetup.evaluate()
statement.evaluate()
}
}
}
override fun computeTestMethods(): MutableList<FrameworkMethod> {
val emergeTestMethods = testClass.getAnnotatedMethods(EmergeTest::class.java)
val emergeStartupTestMethods = testClass.getAnnotatedMethods(EmergeStartupTest::class.java)
return mutableListOf<FrameworkMethod>().apply {
addAll(emergeTestMethods.union(emergeStartupTestMethods))
}
}
private fun addSummary(
annotation: Class<*>,
method: FrameworkMethod,
result: MethodResult = MethodResult.SKIPPED,
message: (() -> String)? = null,
): MethodSummary = addSummary(
listOf(annotation),
method,
result,
message
)
private fun addSummary(
annotations: List<Class<*>>,
method: FrameworkMethod,
result: MethodResult = MethodResult.SKIPPED,
message: (() -> String)? = null,
): MethodSummary {
val messages = mutableListOf<String>()
if (message != null) messages.add(message())
val summary = MethodSummary(annotations, method, result, messages)
summaries.add(summary)
return summary
}
private fun emergeInitInvoker(target: Any): Statement {
val initMethod = initMethods.firstOrNull() ?: return EMPTY_STATEMENT
val summary = addSummary(EmergeInit::class.java, initMethod)
if (initMethod.getAnnotation(EmergeSetup::class.java) != null ||
initMethod.getAnnotation(EmergeTest::class.java) != null ||
initMethod.getAnnotation(EmergeStartupTest::class.java) != null
) {
summary.result = MethodResult.FAILURE
val duplicateMethodMessage =
"${initMethod.name} cannot be annotated with multiple Emerge annotations"
val existingSummary = summaries.find { it.method.name == initMethod.name }
if (existingSummary != null && !existingSummary.messages.contains(duplicateMethodMessage)) {
summary.messages.add(duplicateMethodMessage)
}
}
return object : Statement() {
override fun evaluate() {
try {
initMethod.invokeExplosively(target)
// Don't mark method as success if it's already marked as failure
if (summary.result !== MethodResult.FAILURE) {
summary.result = MethodResult.SUCCESS
}
} catch (e: Throwable) {
summary.result = MethodResult.FAILURE
summary.messages.add("Failed with an exception: $e")
throw e
}
}
}
}
private fun emergeSetupInvoker(target: Any): Statement {
val setupMethod = setupMethods.firstOrNull() ?: return EMPTY_STATEMENT
val summary = addSummary(EmergeSetup::class.java, setupMethod)
if (setupMethod.getAnnotation(EmergeInit::class.java) != null ||
setupMethod.getAnnotation(EmergeTest::class.java) != null ||
setupMethod.getAnnotation(EmergeStartupTest::class.java) != null
) {
summary.result = MethodResult.FAILURE
val duplicateMethodMessage =
"${setupMethod.name} cannot be annotated with multiple Emerge annotations"
val existingSummary = summaries.find { it.method.name == setupMethod.name }
if (existingSummary != null && !existingSummary.messages.contains(duplicateMethodMessage)) {
summary.messages.add(duplicateMethodMessage)
}
}
return object : Statement() {
override fun evaluate() {
try {
setupMethod.invokeExplosively(target)
// Don't mark method as success if it's already marked as failure
if (summary.result !== MethodResult.FAILURE) {
summary.result = MethodResult.SUCCESS
}
} catch (e: Throwable) {
summary.result = MethodResult.FAILURE
summary.messages.add("Failed with an exception: $e")
throw e
}
}
}
}
override fun methodInvoker(
method: FrameworkMethod,
test: Any?,
): Statement {
val superMethodInvoker = super.methodInvoker(method, test)
val emergeTestAnnotation = method.getAnnotation(EmergeTest::class.java)
val hasEmergeTestAnnotation = emergeTestAnnotation != null
val hasEmergeStartupTestAnnotation = method.getAnnotation(EmergeStartupTest::class.java) != null
val annotationSummary = if (hasEmergeTestAnnotation && hasEmergeStartupTestAnnotation) {
val existingSummary = summaries.find { it.method.name == method.name }
if (existingSummary != null) {
if (!existingSummary.messages.contains(DUPLICATE_TEST_ANNOTATION_MESSAGE)) {
existingSummary.messages.add(DUPLICATE_TEST_ANNOTATION_MESSAGE)
}
existingSummary
} else {
addSummary(
annotations = listOf(EmergeTest::class.java, EmergeStartupTest::class.java),
method = method,
result = MethodResult.FAILURE,
) {
"Method cannot have both @EmergeTest and @EmergeStartupTest annotations"
}
}
} else {
val summary = if (hasEmergeTestAnnotation) {
addSummary(EmergeTest::class.java, method).also { methodSummary ->
emergeTestAnnotation.spans.map { ExpectedSpan(it) }
.let(methodSummary.expectedSpans::addAll)
}
} else {
addSummary(EmergeStartupTest::class.java, method)
}
// Show error if they have Init or Setup annotations
if (method.getAnnotation(EmergeInit::class.java) != null ||
method.getAnnotation(EmergeSetup::class.java) != null
) {
summary.result = MethodResult.FAILURE
val duplicateMethodMessage =
"${method.name} cannot be annotated with multiple Emerge annotations"
val existingSummary = summaries.find { it.method.name == method.name }
if (existingSummary != null && !existingSummary.messages.contains(duplicateMethodMessage)) {
summary.messages.add(duplicateMethodMessage)
}
}
summary
}
return object : Statement() {
override fun evaluate() {
try {
// Only profile over the test if expected spans are present
if (annotationSummary.expectedSpans.isNotEmpty()) {
PerfettoTrace.record(
method.name,
appTagPackages = listOf(targetPackageName),
traceCallback = { trace ->
val foundSpans = PerfettoTraceProcessor.runServer {
loadTrace(trace) {
querySpans(
spanNames = annotationSummary.expectedSpans.map(ExpectedSpan::name),
packageName = targetPackageName,
)
}
}
annotationSummary.expectedSpans.forEach { expectedSpan ->
val foundSpan = foundSpans.find { it.name == expectedSpan.name }
expectedSpan.wasFound = foundSpan != null
if (foundSpan != null) {
expectedSpan.durationMs = foundSpan.durMs
val message = if (foundSpan.durMs < SHORT_SPAN_DURATION_MS) {
"Found span \'${foundSpan.name}\' with duration ${foundSpan.durMs}ms, " +
"short spans can lead to inconclusive results $WARN_CHAR"
} else {
"Found span \'${foundSpan.name}\' with duration ${foundSpan.durMs}ms " +
SUCCESS_CHAR
}
annotationSummary.messages.add(message)
} else {
annotationSummary.result = MethodResult.FAILURE
annotationSummary.messages.add(
"Did not find expected span \'${expectedSpan.name}\' $ERROR_CHAR"
)
}
}
}
) { superMethodInvoker.evaluate() }
} else {
superMethodInvoker.evaluate()
}
// Don't mark method as success if it's already marked as failure
if (annotationSummary.result !== MethodResult.FAILURE) {
annotationSummary.result = MethodResult.SUCCESS
}
} catch (e: Throwable) {
annotationSummary.result = MethodResult.FAILURE
annotationSummary.messages.add("Failed with an exception: $e")
}
}
}
}
private fun printResults() {
if (testMethods.isEmpty() && startupTestMethods.isEmpty()) {
val classNode = SimpleTreeNode(this.testClass.name)
classNode.addChild(
SimpleTreeNode("No $EMERGE_TEST or $EMERGE_STARTUP_TEST methods $ERROR_CHAR")
)
val decoratedClassNode = BorderTreeNodeDecorator.builder().inherit(false).buildFor(
PadTreeNodeDecorator(classNode, Insets(0, 1))
)
EmergeLocalInstrumentationResultPrinter.addSummary(
"$testClass",
ListingTreePrinter().stringify(decoratedClassNode)
)
return
}
if (testMethods.isNotEmpty()) {
val classNode = SimpleTreeNode("${this.testClass.name} $EMERGE_TEST")
if (initMethods.isEmpty()) {
classNode.addChild(SimpleTreeNode("No $EMERGE_INIT method"))
}
if (setupMethods.isEmpty()) {
classNode.addChild(SimpleTreeNode("No $EMERGE_SETUP method"))
}
summaries.forEach { summary ->
summary.annotation.forEach { annotation ->
if (!listOf(
EmergeTest::class.java,
EmergeInit::class.java,
EmergeSetup::class.java
).contains(annotation)
) {
return@forEach
}
classNode.addChild(
SimpleTreeNode(
ConsoleText.of("@${annotation.simpleName} ${summary.method.name}")
.format(AnsiFormat.BOLD)
.concat(ConsoleText.of(summary.suffix))
).apply {
summary.messages.forEach {
addChild(SimpleTreeNode(it))
}
}
)
}
}
val decoratedClassNode = BorderTreeNodeDecorator.builder().inherit(false).buildFor(
PadTreeNodeDecorator(classNode, Insets(0, 1))
)
EmergeLocalInstrumentationResultPrinter.addSummary(
"$testClass-$EMERGE_TEST",
ListingTreePrinter().stringify(decoratedClassNode)
)
}
if (startupTestMethods.isNotEmpty()) {
val classNode = SimpleTreeNode("${this.testClass.name} $EMERGE_STARTUP_TEST")
if (initMethods.isEmpty()) {
classNode.addChild(SimpleTreeNode("No $EMERGE_INIT method"))
}
summaries.forEach { summary ->
summary.annotation.forEach { annotation ->
if (!listOf(
EmergeStartupTest::class.java,
EmergeInit::class.java,
).contains(annotation)
) {
return@forEach
}
classNode.addChild(
SimpleTreeNode(
ConsoleText.of("@${annotation.simpleName} ${summary.method.name}")
.format(AnsiFormat.BOLD)
.concat(ConsoleText.of(summary.suffix))
).apply {
summary.messages.forEach {
addChild(SimpleTreeNode(it))
}
}
)
}
}
val decoratedClassNode = BorderTreeNodeDecorator.builder().inherit(false).buildFor(
PadTreeNodeDecorator(classNode, Insets(0, 1))
)
EmergeLocalInstrumentationResultPrinter.addSummary(
"$testClass-$EMERGE_STARTUP_TEST",
ListingTreePrinter().stringify(decoratedClassNode)
)
}
}
companion object {
private const val ARG_PACKAGE_NAME = "packageName"
private const val SUCCESS_CHAR = "✅"
private const val WARN_CHAR = "⚠️"
private const val ERROR_CHAR = "❌"
private const val SKIPPED_CHAR = "⏭️"
private val EMERGE_INIT = "@${EmergeInit::class.java.simpleName}"
private val EMERGE_SETUP = "@${EmergeSetup::class.java.simpleName}"
private val EMERGE_TEST = "@${EmergeTest::class.java.simpleName}"
private val EMERGE_STARTUP_TEST = "@${EmergeStartupTest::class.java.simpleName}"
private const val DUPLICATE_TEST_ANNOTATION_MESSAGE =
"Method cannot have both @EmergeTest and @EmergeStartupTest annotations"
/**
* Relatively arbitrary, taken from observations we've seen around short spans and inconclusive
* perf results.
*/
private const val SHORT_SPAN_DURATION_MS = 200L
val EMPTY_STATEMENT = object : Statement() {
override fun evaluate() {
// Do nothing
}
}
enum class MethodResult(val suffix: String) {
SUCCESS(SUCCESS_CHAR),
FAILURE(ERROR_CHAR),
SKIPPED(SKIPPED_CHAR),
}
data class ExpectedSpan(
val name: String,
var wasFound: Boolean = false,
var durationMs: Long? = null,
)
data class MethodSummary(
val annotation: List<Class<*>>,
val method: FrameworkMethod,
var result: MethodResult,
val messages: MutableList<String> = mutableListOf(),
val expectedSpans: MutableList<ExpectedSpan> = mutableListOf(),
) {
val suffix: String
get() = " " + result.suffix
}
}
}
| 9
| null |
2
| 9
|
8174b9c6e2d7791e01363aabd4d287736bfa38c4
| 16,928
|
emerge-android
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/klage/infrastruktur/health/BrevHealth.kt
|
navikt
| 524,953,794
| false
|
{"Kotlin": 623807, "Dockerfile": 153}
|
package no.nav.familie.klage.infrastruktur.health
import no.nav.familie.http.health.AbstractHealthIndicator
import no.nav.familie.klage.brev.BrevClient
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component
@Component
@Profile("!local")
class BrevHealth(client: BrevClient) :
AbstractHealthIndicator(client, "familie.brev")
| 9
|
Kotlin
|
0
| 2
|
c0eb06e0682c6970f64a564784a4813d1bb2884b
| 377
|
familie-klage
|
MIT License
|
app/src/test/java/io/github/wulkanowy/data/repositories/message/MessageRepositoryTest.kt
|
mafineeek
| 297,426,962
| true
|
{"Kotlin": 966636, "HTML": 1949, "Shell": 220}
|
package io.github.wulkanowy.data.repositories.message
import io.github.wulkanowy.data.Status
import io.github.wulkanowy.data.db.entities.MessageWithAttachment
import io.github.wulkanowy.data.db.entities.Student
import io.github.wulkanowy.getMessageEntity
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import java.net.UnknownHostException
class MessageRepositoryTest {
@MockK
lateinit var local: MessageLocal
@MockK
lateinit var remote: MessageRemote
@MockK
lateinit var student: Student
private lateinit var repo: MessageRepository
@Before
fun setUp() {
MockKAnnotations.init(this)
every { student.userName } returns "Jan"
repo = MessageRepository(local, remote)
}
@Test
fun `throw error when message is not in the db`() {
val testMessage = getMessageEntity(1, "", false)
coEvery { local.getMessageWithAttachment(student, testMessage) } throws NullPointerException("No message in database")
val message = runCatching { runBlocking { repo.getMessage(student, testMessage).toList()[1] } }
assertEquals(NullPointerException::class.java, message.exceptionOrNull()?.javaClass)
}
@Test
fun `get message when content already in db`() {
val testMessage = getMessageEntity(123, "Test", false)
val messageWithAttachment = MessageWithAttachment(testMessage, emptyList())
coEvery { local.getMessageWithAttachment(student, testMessage) } returns flowOf(messageWithAttachment)
val message = runBlocking { repo.getMessage(student, testMessage).toList() }
assertEquals(Status.SUCCESS, message[1].status)
assertEquals("Test", message[1].data!!.message.content)
}
@Test
fun `get message when content in db is empty`() {
val testMessage = getMessageEntity(123, "", true)
val testMessageWithContent = testMessage.copy().apply { content = "Test" }
val mWa = MessageWithAttachment(testMessage, emptyList())
val mWaWithContent = MessageWithAttachment(testMessageWithContent, emptyList())
coEvery { local.getMessageWithAttachment(student, testMessage) } returnsMany listOf(flowOf(mWa), flowOf(mWaWithContent))
coEvery { remote.getMessagesContentDetails(student, any(), any()) } returns ("Test" to emptyList())
coEvery { local.updateMessages(any()) } just Runs
coEvery { local.saveMessageAttachments(any()) } just Runs
val message = runBlocking { repo.getMessage(student, testMessage).toList() }
assertEquals(Status.SUCCESS, message[2].status)
assertEquals("Test", message[2].data!!.message.content)
coVerify { local.updateMessages(listOf(testMessageWithContent)) }
}
@Test
fun `get message when content in db is empty and there is no internet connection`() {
val testMessage = getMessageEntity(123, "", false)
val messageWithAttachment = MessageWithAttachment(testMessage, emptyList())
coEvery { local.getMessageWithAttachment(student, testMessage) } throws UnknownHostException()
val message = runCatching { runBlocking { repo.getMessage(student, testMessage).toList()[1] } }
assertEquals(UnknownHostException::class.java, message.exceptionOrNull()?.javaClass)
}
@Test
fun `get message when content in db is empty, unread and there is no internet connection`() {
val testMessage = getMessageEntity(123, "", true)
val messageWithAttachment = MessageWithAttachment(testMessage, emptyList())
coEvery { local.getMessageWithAttachment(student, testMessage) } throws UnknownHostException()
val message = runCatching { runBlocking { repo.getMessage(student, testMessage).toList()[1] } }
assertEquals(UnknownHostException::class.java, message.exceptionOrNull()?.javaClass)
}
}
| 0
| null |
0
| 0
|
b0b3ccfd530e2b450804c194365b4e4fe225c754
| 4,187
|
wulkanowy
|
Apache License 2.0
|
app/src/main/java/com/jthou/wanandroidkotlin/fragment/KnowledgeSystemFragment.kt
|
jthou20121212
| 210,117,827
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 101, "XML": 78, "Java": 11}
|
package com.jthou.wanandroidkotlin.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.jthou.wanandroidkotlin.adapter.KnowledgeSystemAdapter
import com.jthou.wanandroidkotlin.base.BaseFragment
import com.jthou.wanandroidkotlin.data.entity.KnowledgeSystem
import com.jthou.wanandroidkotlin.databinding.FragmentKnowledgeSystemBinding
import com.jthou.wanandroidkotlin.viewmodel.KnowledgeSystemViewModel
import com.jthou.wanandroidkotlin.viewmodel.Provider
import java.util.*
/**
*
*
* @author jthou
* @version 1.0.0
* @date 11-08-2019
*/
class KnowledgeSystemFragment : BaseFragment<FragmentKnowledgeSystemBinding, KnowledgeSystemViewModel>() {
override fun createViewModel() = Provider.knowledgeSystemViewModel()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mDataBinding = FragmentKnowledgeSystemBinding.inflate(inflater, container, false)
return mDataBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mDataBinding.recyclerView.layoutManager = LinearLayoutManager(context)
val data: MutableList<KnowledgeSystem> = ArrayList()
val adapter = KnowledgeSystemAdapter(requireContext(), data)
mDataBinding.recyclerView.adapter = adapter
mViewModel.getKnowledgeSystemList().observe(viewLifecycleOwner, Observer { it ->
it.data.let {
data.addAll(it!!)
adapter.notifyDataSetChanged()
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
7518eccff844b4c9191f69b7d9c6b72b13373f49
| 1,766
|
WanAndroidKotlin
|
Apache License 2.0
|
tests/integration-tests/src/test/kotlin/config/VaultAuthType.kt
|
hyperledger
| 512,835,706
| false
|
{"Scala": 2982192, "Kotlin": 242404, "TypeScript": 61063, "Shell": 30427, "Gherkin": 25384, "Python": 13723, "JavaScript": 3988, "Smarty": 2922}
|
package config
enum class VaultAuthType {
APP_ROLE,
TOKEN
}
| 42
|
Scala
|
22
| 80
|
c5071d5707e8c79b450f82c0c891f77d2eb26b95
| 69
|
identus-cloud-agent
|
Apache License 2.0
|
src/main/kotlin/com/github/secretx33/imagetopdf/util/Util.kt
|
SecretX33
| 669,934,271
| false
|
{"Kotlin": 34971, "Batchfile": 1935}
|
package com.github.secretx33.imagetopdf.util
import com.drew.metadata.Metadata
import com.drew.metadata.exif.ExifIFD0Directory
import com.github.secretx33.imagetopdf.exception.QuitApplicationException
import com.github.secretx33.imagetopdf.model.ImageMirroring
import com.github.secretx33.imagetopdf.model.ImageRotation
import org.jnativehook.GlobalScreen
import java.io.ByteArrayOutputStream
import java.lang.invoke.MethodHandles
import java.nio.file.Path
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale
import java.util.logging.Level
import java.util.logging.Logger
import kotlin.io.path.Path
import kotlin.io.path.absolute
import kotlin.io.path.fileSize
import kotlin.time.Duration
private val thisClass = MethodHandles.lookup().lookupClass()
val cpuThreadAmount: Int get() = Runtime.getRuntime().availableProcessors()
fun printError(message: String) = System.err.println(message)
fun bail(message: String): Nothing = throw QuitApplicationException(message, exitCode = 1)
fun quitProgram(): Nothing = throw QuitApplicationException(exitCode = 0)
val Path.absoluteParent: Path get() = (parent ?: Path("")).absolute()
fun Path.formattedFileSize(): String = fileSize().bytesToHumanReadableSize()
fun getTextResource(path: String): String = thisClass.classLoader.getResourceAsStream(path)
?.bufferedReader()
?.use { it.readText() }
?: throw IllegalArgumentException("$path was not found in classpath")
private fun Long.bytesToHumanReadableSize(): String = when {
this == Long.MIN_VALUE || this < 0 -> "N/A"
this < 1024L -> "$this bytes"
this <= 0xfffccccccccccccL shr 40 -> "%.1f KB".format(Locale.ROOT, toDouble() / (0x1 shl 10))
this <= 0xfffccccccccccccL shr 30 -> "%.1f MB".format(Locale.ROOT, toDouble() / (0x1 shl 20))
this <= 0xfffccccccccccccL shr 20 -> "%.1f GB".format(Locale.ROOT, toDouble() / (0x1 shl 30))
this <= 0xfffccccccccccccL shr 10 -> "%.1f TB".format(Locale.ROOT, toDouble() / (0x1 shl 40))
this <= 0xfffccccccccccccL -> "%.1f PB".format(Locale.ROOT, (this shr 10).toDouble() / (0x1 shl 40))
else -> "%.1f EB".format(Locale.ROOT, (this shr 20).toDouble() / (0x1 shl 40))
}
/**
* Returns a string representation of the duration in seconds, with increased precision when the time is below one
* second.
*
* @return a formatted string representation of the duration in seconds.
*/
fun Duration.formattedSeconds(): String {
val secondsDouble = inWholeMilliseconds.toDouble() / 1000.0
val pattern = when {
inWholeSeconds <= 0 -> "#.##"
else -> "#,###.#"
}
val format = DecimalFormat(pattern, DecimalFormatSymbols(Locale.US))
return format.format(secondsDouble)
}
/**
* Bye bye, annoying `info` logger from JNativeHook.
*/
fun disableAnnoyingJnativehookLogger() {
// Get the logger for "org.jnativehook" and set the level to warning.
val logger = Logger.getLogger(GlobalScreen::class.java.getPackage().name)
logger.level = Level.WARNING
// Don't forget to disable the parent handlers.
logger.useParentHandlers = false
}
fun <T> lazyNone(block: () -> T): Lazy<T> = lazy(LazyThreadSafetyMode.NONE, block)
fun byteArrayOutputStream(block: (ByteArrayOutputStream) -> Unit): ByteArray = ByteArrayOutputStream().use {
block(it)
it.toByteArray()
}
val Metadata.imageRotation: ImageRotation get() {
val exif = getFirstDirectoryOfType(ExifIFD0Directory::class.java) ?: return ImageRotation.NONE
val orientation = exif.getInt(ExifIFD0Directory.TAG_ORIENTATION)
return ImageRotation.from(orientation)
}
val Metadata.imageMirroring: ImageMirroring get() {
val exif = getFirstDirectoryOfType(ExifIFD0Directory::class.java) ?: return ImageMirroring.NONE
val orientation = exif.getInt(ExifIFD0Directory.TAG_ORIENTATION)
return ImageMirroring.from(orientation)
}
| 0
|
Kotlin
|
0
| 1
|
fd6f834829f175f79fb457d98ca0f89728845190
| 3,862
|
ImageToPdf
|
MIT License
|
kt/godot-library/src/main/kotlin/godot/gen/godot/NavigationPolygon.kt
|
ShalokShalom
| 343,354,086
| true
|
{"Kotlin": 516486, "GDScript": 294955, "C++": 262753, "C#": 11670, "CMake": 2060, "Shell": 1628, "C": 959, "Python": 75}
|
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName")
package godot
import godot.annotation.GodotBaseType
import godot.core.PoolIntArray
import godot.core.PoolVector2Array
import godot.core.TransferContext
import godot.core.VariantArray
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.POOL_INT_ARRAY
import godot.core.VariantType.POOL_VECTOR2_ARRAY
import godot.util.VoidPtr
import kotlin.Any
import kotlin.Long
import kotlin.NotImplementedError
import kotlin.Suppress
@GodotBaseType
open class NavigationPolygon : Resource() {
open var vertices: PoolVector2Array
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_GET_VERTICES,
POOL_VECTOR2_ARRAY)
return TransferContext.readReturnValue(POOL_VECTOR2_ARRAY, false) as PoolVector2Array
}
set(value) {
TransferContext.writeArguments(POOL_VECTOR2_ARRAY to value)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_SET_VERTICES,
NIL)
}
override fun __new(): VoidPtr = TransferContext.invokeConstructor(ENGINECLASS_NAVIGATIONPOLYGON)
open fun _getOutlines(): VariantArray<Any?> {
throw NotImplementedError("_get_outlines is not implemented for NavigationPolygon")
}
open fun _getPolygons(): VariantArray<Any?> {
throw NotImplementedError("_get_polygons is not implemented for NavigationPolygon")
}
open fun _setOutlines(outlines: VariantArray<Any?>) {
}
open fun _setPolygons(polygons: VariantArray<Any?>) {
}
open fun addOutline(outline: PoolVector2Array) {
TransferContext.writeArguments(POOL_VECTOR2_ARRAY to outline)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_ADD_OUTLINE, NIL)
}
open fun addOutlineAtIndex(outline: PoolVector2Array, index: Long) {
TransferContext.writeArguments(POOL_VECTOR2_ARRAY to outline, LONG to index)
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_ADD_OUTLINE_AT_INDEX, NIL)
}
open fun addPolygon(polygon: PoolIntArray) {
TransferContext.writeArguments(POOL_INT_ARRAY to polygon)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_ADD_POLYGON, NIL)
}
open fun clearOutlines() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_CLEAR_OUTLINES,
NIL)
}
open fun clearPolygons() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_CLEAR_POLYGONS,
NIL)
}
open fun getOutline(idx: Long): PoolVector2Array {
TransferContext.writeArguments(LONG to idx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_GET_OUTLINE,
POOL_VECTOR2_ARRAY)
return TransferContext.readReturnValue(POOL_VECTOR2_ARRAY, false) as PoolVector2Array
}
open fun getOutlineCount(): Long {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_GET_OUTLINE_COUNT,
LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
open fun getPolygon(idx: Long): PoolIntArray {
TransferContext.writeArguments(LONG to idx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_GET_POLYGON,
POOL_INT_ARRAY)
return TransferContext.readReturnValue(POOL_INT_ARRAY, false) as PoolIntArray
}
open fun getPolygonCount(): Long {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_GET_POLYGON_COUNT,
LONG)
return TransferContext.readReturnValue(LONG, false) as Long
}
open fun makePolygonsFromOutlines() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr,
ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_MAKE_POLYGONS_FROM_OUTLINES, NIL)
}
open fun removeOutline(idx: Long) {
TransferContext.writeArguments(LONG to idx)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_REMOVE_OUTLINE,
NIL)
}
open fun setOutline(idx: Long, outline: PoolVector2Array) {
TransferContext.writeArguments(LONG to idx, POOL_VECTOR2_ARRAY to outline)
TransferContext.callMethod(rawPtr, ENGINEMETHOD_ENGINECLASS_NAVIGATIONPOLYGON_SET_OUTLINE, NIL)
}
}
| 0
| null |
0
| 1
|
7b9b195de5be4a0b88b9831c3a02f9ca06aa399c
| 4,673
|
godot-jvm
|
MIT License
|
app/src/main/java/ir/digireza/tmdb/app/constants/Constant.kt
|
rezanasirzadeh
| 577,109,305
| false
|
{"Kotlin": 172041}
|
package ir.digireza.tmdb.app.constants
class Constant {
companion object {
const val BASE_URL = "https://api.themoviedb.org/3/"
const val TMDB_TOKEN = "<PASSWORD>"
const val IMAGE_ADDRESS = "https://image.tmdb.org/t/p/w500/"
// Intent params
const val PAGE_TITLE_KEY = "page_title_key"
const val PAGE_DATA_TYPE = "page_data_type"
const val CLICKED_ITEM_ID = "clicked_item_id"
}
}
enum class MoviesType{ populraMovies, featuredMovies, upcomingMovies}
enum class TvshowType{ populraTvshows, featuredTvshows}
| 0
|
Kotlin
|
0
| 1
|
83a8d11ffa2febc03b3cbeac0e13865ede8cf9f9
| 576
|
tmdb-android
|
Apache License 2.0
|
app/src/test/java/com/javiermarsicano/sportsfixture/views/fixtureslist/FixturesListPresenterTest.kt
|
jmarsican
| 219,083,685
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 1, "Kotlin": 44, "XML": 13, "JSON": 2}
|
package com.javiermarsicano.sportsfixture.views.fixtureslist
import com.javiermarsicano.sportsfixture.TrampolineSchedulerRule
import com.javiermarsicano.sportsfixture.data.repository.FixtureRepository
import com.javiermarsicano.sportsfixture.views.models.Fixture
import io.reactivex.Single
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Matchers.anyString
import org.mockito.Mockito.*
import java.io.IOException
class FixturesListPresenterTest {
@get:Rule
val schedulersRule = TrampolineSchedulerRule()
private lateinit var repository: FixtureRepository
private lateinit var view: FixtureView
private lateinit var presenter: FixturesListPresenter
private val fixture = Fixture(id = 0)
@Before
fun setUp() {
view = mock(FixtureView::class.java)
repository = mock(FixtureRepository::class.java)
presenter = FixturesListPresenterImpl(repository)
presenter.onBindView(view)
}
@Test
fun `get and show fixture data successful`() {
//given
val data = listOf(fixture)
`when`(repository.getFixtures()).thenReturn(Single.just(data))
//when
presenter.getFixtures()
//then
verify(view).showFixtures(data)
thenShowAndHideProgress()
}
@Test
fun `some error occurs when asking for fixtures`() {
//given
`when`(repository.getFixtures()).thenReturn(Single.error(IOException()))
//when
presenter.getFixtures()
//then
verify(view).onError(anyString())
thenShowAndHideProgress()
}
private fun thenShowAndHideProgress() {
verify(view).showLoading()
verify(view).hideLoading()
}
}
| 1
| null |
1
| 1
|
3b301603f1d283d2e09d925ac7a0fb6a6b3a8b7a
| 1,753
|
sports-fixture
|
Apache License 2.0
|
app/src/main/java/com/m3rc/beerbox/di/module/ActivityModule.kt
|
M3rcur14l
| 171,579,998
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 41, "XML": 46, "Java": 5}
|
package com.m3rc.beerbox.di.module
import com.m3rc.beerbox.app.beer.BeerActivity
import com.m3rc.beerbox.di.module.fragment.BeerFragmentModule
import com.m3rc.beerbox.di.scope.ActivityScoped
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ActivityModule {
@ActivityScoped
@ContributesAndroidInjector(modules = [BeerFragmentModule::class])
abstract fun mainActivity(): BeerActivity
}
| 1
| null |
1
| 1
|
7647e42d4c1011ee125b6f848e914b8d090d795b
| 444
|
Beer-Box
|
Apache License 2.0
|
app/src/main/java/com/android/tvflix/config/FeatureFlagModule.kt
|
reactivedroid
| 98,877,626
| false
|
{"Kotlin": 98758}
|
package com.android.tvflix.config
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@InstallIn(SingletonComponent::class)
@Module
object FeatureFlagModule {
@FavoritesFeatureFlag
@Provides
fun provideFavoritesFeatureFlag(appConfig: AppConfig): Boolean {
return appConfig.getBoolean(ConfigDefaults.ConfigKeys.FEATURE_FAVORITES_ENABLE)
}
}
| 0
|
Kotlin
|
59
| 412
|
3f36749698316000b6dfbe2195f8be9cdf10e155
| 435
|
TvFlix
|
MIT License
|
example/app-jvm/src/main/java/ru/unit/orchestra_features/example/jvm/TestSecond.kt
|
why-iskra
| 689,642,973
| false
|
{"Kotlin": 102496}
|
package ru.unit.orchestra_features.example.jvm
import ru.unit.orchestra_features.common.annotation.FeatureScope
@FeatureScope(dependsOn = [TestFirst.sc::class])
class TestSecond
| 0
|
Kotlin
|
0
| 1
|
7b9b9301f4b377cae180d0025d03dbff86af8bfd
| 179
|
orchestra-features
|
MIT License
|
dicoding/belajar-fundamental-aplikasi-android/AndroidKtxSingleEvent/app/src/main/java/id/my/mrgsrylm/androidktxsingleevent/ReviewAdapter.kt
|
mrgsrylm
| 740,344,950
| false
|
{"Kotlin": 306052}
|
package id.my.mrgsrylm.androidktxsingleevent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ReviewAdapter(private val listReview: List<String>) :
RecyclerView.Adapter<ReviewAdapter.ViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) =
ViewHolder(
LayoutInflater.from(viewGroup.context).inflate(R.layout.item_review, viewGroup, false)
)
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.tvItem.text = listReview[position]
}
override fun getItemCount() = listReview.size
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvItem: TextView = view.findViewById(R.id.tvItem)
}
}
| 0
|
Kotlin
|
0
| 1
|
253f1300c8afa19fb23eb29eedf0e8f10940114e
| 860
|
kotlin-sandbox
|
MIT License
|
composeApp/src/commonMain/kotlin/data/EmojiList.kt
|
anwar-pasaribu
| 772,492,453
| false
|
{"Kotlin": 259142, "Ruby": 4931, "Swift": 568, "HTML": 304}
|
package data
import androidx.compose.ui.graphics.Color
import kotlinx.collections.immutable.toImmutableList
import ui.screen.emojis.model.EmojiUiModel
object EmojiList {
private val emojiList by lazy {
listOf(
"\uD83D\uDE00", // 😀 Grinning Face
"\uD83D\uDE01", // 😁 Beaming Face with Smiling Eyes
"\uD83D\uDE02", // 😂 Face with Tears of Joy
"\uD83D\uDE03", // 😃 Grinning Face with Big Eyes
"\uD83D\uDE04", // 😄 Grinning Face with Smiling Eyes
"\uD83D\uDE05", // 😅 Grinning Face with Sweat
"\uD83D\uDE06", // 😆 Grinning Squinting Face
"\uD83D\uDE07", // 😇 Smiling Face with Halo
"\uD83D\uDE08", // 😈 Smiling Face with Horns
"\uD83D\uDE09", // 😉 Winking Face
"\uD83D\uDE0A", // 😊 Smiling Face with Smiling Eyes
"\uD83D\uDE0B", // 😋 Face Savoring Food
"\uD83D\uDE0C", // 😌 Relieved Face
"\uD83D\uDE0D", // 😍 Smiling Face with Heart-Eyes
"\uD83D\uDE0E", // 😎 Smiling Face with Sunglasses
"\uD83D\uDE0F", // 😏 Smirking Face
"\uD83D\uDE10", // 😐 Neutral Face
"\uD83D\uDE11", // 😑 Expressionless Face
"\uD83D\uDE12", // 😒 Unamused Face
"\uD83D\uDE13", // 😓 Downcast Face with Sweat
"\uD83D\uDE14", // 😔 Pensive Face
"\uD83D\uDE15", // 😕 Confused Face
"\uD83D\uDE16", // 😖 Confounded Face
"\uD83D\uDE17", // 😗 Kissing Face
"\uD83D\uDE18", // 😘 Face Blowing a Kiss
"\uD83D\uDE19", // 😙 Kissing Face with Smiling Eyes
"\uD83D\uDE1A", // 😚 Kissing Face with Closed Eyes
"\uD83D\uDE1B", // 😛 Face with Tongue
"\uD83D\uDE1C", // 😜 Winking Face with Tongue
"\uD83D\uDE1D", // 😝 Squinting Face with Tongue
"\uD83D\uDE1E", // 😞 Disappointed Face
"\uD83D\uDE1F", // 😟 Worried Face
"\uD83D\uDE20", // 😠 Angry Face
"\uD83D\uDE21", // 😡 Pouting Face
"\uD83D\uDE22", // 😢 Crying Face
"\uD83D\uDE23", // 😣 Persevering Face
"\uD83D\uDE24", // 😤 Face with Steam From Nose
"\uD83D\uDE25", // 😥 Sad but Relieved Face
"\uD83D\uDE26", // 😦 Frowning Face with Open Mouth
"\uD83D\uDE27", // 😧 Anguished Face
"\uD83D\uDE28", // 😨 Fearful Face
"\uD83D\uDE29", // 😩 Weary Face
"\uD83D\uDE2A", // 😪 Sleepy Face
"\uD83D\uDE2B", // 😫 Tired Face
"\uD83D\uDE2C", // 😬 Grimacing Face
"\uD83D\uDE2D", // 😭 Loudly Crying Face
"\uD83D\uDE2E", // 😮 Face with Open Mouth
"\uD83D\uDE2F", // 😯 Hushed Face
"\uD83D\uDE30", // 😰 Face with Open Mouth & Cold Sweat
"\uD83D\uDE31", // 😱 Face Screaming in Fear
"\uD83D\uDE32", // 😲 Astonished Face
"\uD83D\uDE33", // 😳 Flushed Face
"\uD83D\uDE34", // 😴 Sleeping Face
"\uD83D\uDE35", // 😵 Dizzy Face
"\uD83D\uDE36", // 😶 Face Without Mouth
"\uD83D\uDE37", // 😷 Face with Medical Mask
"\uD83D\uDE2E\u200D\uD83D\uDCA8", // 😮💨face exhaling
"\uD83D\uDE38", // 😸 Grinning Cat Face
"\uD83D\uDE39", // 😹 Cat with Tears of Joy
"\uD83D\uDE3A", // 😺 Smiling Cat Face
"\uD83D\uDE3B", // 😻 Heart-Eyes Cat
"\uD83D\uDE3C", // 😼 Cat with Wry Smile
"\uD83D\uDE3D", // 😽 Kissing Cat
"\uD83D\uDE3E", // 😾 Pouting Cat
"\uD83D\uDE3F", // 😿 Crying Cat
"\uD83D\uDE40", // 🙀 Weary Cat
"\uD83D\uDE41", // 🙁 Slightly Frowning Face
"\uD83D\uDE42", // 🙂 Slightly Smiling Face
"\uD83D\uDE43", // 🙃 Upside-Down Face
"\uD83D\uDE44", // 🙄 Face with Rolling Eyes
"\uD83D\uDE45", // 🙅 Person Gesturing No
"\uD83D\uDE46", // 🙆 Person Gesturing OK
"\uD83D\uDE47", // 🙇 Person Bowing
"\uD83D\uDE48", // 🙈 See-No-Evil Monkey
"\uD83D\uDE49", // 🙉 Hear-No-Evil Monkey
"\uD83D\uDE4A", // 🙊 Speak-No-Evil Monkey
"\uD83D\uDE4B", // 🙋 Happy Person Raising One Hand
"\uD83D\uDE4C", // 🙌 Person Raising Both Hands in Celebration
"\uD83D\uDE4D", // 🙍 Person Frowning
"\uD83D\uDE4E", // 🙎 Person Pouting
"\uD83D\uDE4F", // 🙏 Person with Folded Hands
"\uD83E\uDD10", // 🤐 Zipper-Mouth Face
"\uD83E\uDD11", // 🤑 Money-Mouth Face
"\uD83E\uDD13", // 🤓 Nerd Face
"\uD83E\uDD14", // 🤔 Thinking Face
"\uD83E\uDD15", // 🤕 Face with Head-Bandage
"\uD83E\uDD17", // 🤗 Hugging Face
"\uD83E\uDD18", // 🤘 Sign of the Horns
"\uD83E\uDD75", // 🥵 Hot Face
"\uD83E\uDD76", // 🥶 Cold Face
"\uD83E\uDD8A", // 🦊 Fox Face
"\uD83E\uDDCD", // 🧍 Person Standing
"\uD83E\uDDCE", // 🧎 Person Kneeling
"\uD83E\uDDCF", // 🧏 Person Standing: Medium-Light Skin Tone
"\uD83E\uDDD0", // 🧐 Face with Monocle
)
}
val moodPleasantness = mapOf(
-1 to "Tidak Ada Data",
1 to "Sangat Senang", // Very Pleasant
2 to "Senang", // Pleasant
3 to "Agak Senang", // Slightly Pleasant
4 to "Netral", // Neutral
5 to "Agak Tidak Senang", // Slightly Unpleasant
6 to "Tidak Senang", // Unpleasant
7 to "Sangat Tidak Senang", // Very Unpleasant
)
val moodPleasantnessEmojiMapping = mapOf(
-1 to "",
1 to "\uD83D\uDE0D", // Very Pleasant
2 to "\uD83D\uDE03", // Grinning Face with Big Eyes
3 to "\uD83D\uDE00", // Grinning Face
4 to "\uD83D\uDE10", // Neutral Face
5 to "\uD83D\uDE14", // 😔 Pensive Face
6 to "\uD83D\uDE29", // 😩 Weary Face
7 to "\uD83D\uDE2B", // 😫 Very Unpleasant
)
val MOOD_UNKNOWN = -1
val MOOD_1 = 1
val MOOD_2 = 2
val MOOD_3 = 3
val MOOD_4 = 4
val MOOD_5 = 5
val MOOD_6 = 6
val MOOD_7 = 7
val emojiWeights = mapOf(
"\uD83D\uDE00" to 1, // 😀 Grinning Face
"\uD83D\uDE01" to 1, // 😁 Beaming Face with Smiling Eyes
"\uD83D\uDE02" to 1, // 😂 Face with Tears of Joy
"\uD83D\uDE03" to 1, // 😃 Grinning Face with Big Eyes
"\uD83D\uDE04" to 1, // 😄 Grinning Face with Smiling Eyes
"\uD83D\uDE05" to 2, // 😅 Grinning Face with Sweat
"\uD83D\uDE06" to 2, // 😆 Grinning Squinting Face
"\uD83D\uDE07" to 1, // 😇 Smiling Face with Halo
"\uD83D\uDE08" to 6, // 😈 Smiling Face with Horns
"\uD83D\uDE09" to 2, // 😉 Winking Face
"\uD83D\uDE0A" to 1, // 😊 Smiling Face with Smiling Eyes
"\uD83D\uDE0B" to 1, // 😋 Face Savoring Food
"\uD83D\uDE0C" to 1, // 😌 Relieved Face
"\uD83D\uDE0D" to 1, // 😍 Smiling Face with Heart-Eyes
"\uD83D\uDE0E" to 2, // 😎 Smiling Face with Sunglasses
"\uD83D\uDE0F" to 2, // 😏 Smirking Face
"\uD83D\uDE10" to 4, // 😐 Neutral Face
"\uD83D\uDE11" to 4, // 😑 Expressionless Face
"\uD83D\uDE12" to 5, // 😒 Unamused Face
"\uD83D\uDE13" to 5, // 😓 Downcast Face with Sweat
"\uD83D\uDE14" to 5, // 😔 Pensive Face
"\uD83D\uDE15" to 5, // 😕 Confused Face
"\uD83D\uDE16" to 6, // 😖 Confounded Face
"\uD83D\uDE17" to 1, // 😗 Kissing Face
"\uD83D\uDE18" to 1, // 😘 Face Blowing a Kiss
"\uD83D\uDE19" to 1, // 😙 Kissing Face with Smiling Eyes
"\uD83D\uDE1A" to 1, // 😚 Kissing Face with Closed Eyes
"\uD83D\uDE1B" to 1, // 😛 Face with Tongue
"\uD83D\uDE1C" to 1, // 😜 Winking Face with Tongue
"\uD83D\uDE1D" to 1, // 😝 Squinting Face with Tongue
"\uD83D\uDE1E" to 5, // 😞 Disappointed Face
"\uD83D\uDE1F" to 5, // 😟 Worried Face
"\uD83D\uDE20" to 6, // 😠 Angry Face
"\uD83D\uDE21" to 6, // 😡 Pouting Face
"\uD83D\uDE22" to 7, // 😢 Crying Face
"\uD83D\uDE23" to 6, // 😣 Persevering Face
"\uD83D\uDE24" to 6, // 😤 Face with Steam From Nose
"\uD83D\uDE25" to 5, // 😥 Sad but Relieved Face
"\uD83D\uDE26" to 5, // 😦 Frowning Face with Open Mouth
"\uD83D\uDE27" to 6, // 😧 Anguished Face
"\uD83D\uDE28" to 6, // 😨 Fearful Face
"\uD83D\uDE29" to 6, // 😩 Weary Face
"\uD83D\uDE2A" to 6, // 😪 Sleepy Face
"\uD83D\uDE2B" to 6, // 😫 Tired Face
"\uD83D\uDE2C" to 6, // 😬 Grimacing Face
"\uD83D\uDE2D" to 7, // 😭 Loudly Crying Face
"\uD83D\uDE2E" to 4, // 😮 Face with Open Mouth
"\uD83D\uDE2F" to 4, // 😯 Hushed Face
"\uD83D\uDE30" to 5, // 😰 Face with Open Mouth & Cold Sweat
"\uD83D\uDE31" to 7, // 😱 Face Screaming in Fear
"\uD83D\uDE32" to 6, // 😲 Astonished Face
"\uD83D\uDE33" to 5, // 😳 Flushed Face
"\uD83D\uDE34" to 5, // 😴 Sleeping Face
"\uD83D\uDE35" to 5, // 😵 Dizzy Face
"\uD83D\uDE36" to 4, // 😶 Face Without Mouth
"\uD83D\uDE37" to 6, // 😷 Face with Medical Mask
"\uD83D\uDE38" to 1, // 😸 Grinning Cat Face
"\uD83D\uDE39" to 1, // 😹 Cat with Tears of Joy
"\uD83D\uDE3A" to 1, // 😺 Smiling Cat Face
"\uD83D\uDE3B" to 1, // 😻 Heart-Eyes Cat
"\uD83D\uDE3C" to 1, // 😼 Cat with Wry Smile
"\uD83D\uDE3D" to 1, // 😽 Kissing Cat
"\uD83D\uDE3E" to 5, // 😾 Pouting Cat
"\uD83D\uDE3F" to 7, // 😿 Crying Cat
"\uD83D\uDE40" to 6, // 🙀 Weary Cat
"\uD83D\uDE41" to 5, // 🙁 Slightly Frowning Face
"\uD83D\uDE42" to 1, // 🙂 Slightly Smiling Face
"\uD83D\uDE43" to 4, // 🙃 Upside-Down Face
"\uD83D\uDE44" to 5, // 🙄 Face with Rolling Eyes
"\uD83D\uDE45" to 5, // 🙅 Person Gesturing No
"\uD83D\uDE46" to 5, // 🙆 Person Gesturing OK
"\uD83D\uDE47" to 1, // 🙇 Person Bowing
"\uD83D\uDE48" to 2, // 🙈 See-No-Evil Monkey
"\uD83D\uDE49" to 2, // 🙉 Hear-No-Evil Monkey
"\uD83D\uDE4A" to 2, // 🙊 Speak-No-Evil Monkey
"\uD83D\uDE4B" to 2, // 🙋 Happy Person Raising One Hand
"\uD83D\uDE4C" to 2, // 🙌 Person Raising Both Hands in Celebration
"\uD83D\uDE4D" to 5, // 🙍 Person Frowning
"\uD83D\uDE4E" to 5, // 🙎 Person Pouting
"\uD83D\uDE4F" to 1, // 🙏 Person with Folded Hands
"\uD83E\uDD10" to 4, // 🤐 Zipper-Mouth Face
"\uD83E\uDD11" to 5, // 🤑 Money-Mouth Face
"\uD83E\uDD13" to 3, // 🤓 Nerd Face
"\uD83E\uDD14" to 3, // 🤔 Thinking Face
"\uD83E\uDD15" to 5, // 🤕 Face with Head-Bandage
"\uD83E\uDD17" to 1, // 🤗 Hugging Face
"\uD83E\uDD18" to 1, // 🤘 Sign of the Horns
"\uD83E\uDD75" to 6, // 🥵 Hot Face
"\uD83E\uDD76" to 6, // 🥶 Cold Face
"\uD83E\uDD8A" to 4, // 🦊 Fox Face
"\uD83E\uDDCD" to 2, // 🧍 Person Standing
"\uD83E\uDDCE" to 2, // 🧎 Person Kneeling
"\uD83E\uDDCF" to 2, // 🧏 Person Standing: Medium-Light Skin Tone
"\uD83E\uDDD0" to 3, // 🧐 Face with Monocle
)
fun getBackgroundColorForMood(moodRating: Int): List<Color> {
return when (moodRating) {
EmojiList.MOOD_1 -> listOf(
Color(0xFF50C878),
Color(0xFF00755E)
) // Vibrant and modern color for very pleasant mood
EmojiList.MOOD_2 -> listOf(Color(0xFF71C5E8), Color(0xFF0C81E6)) // Pleasant mood
EmojiList.MOOD_3 -> listOf(Color(0xFFFFD700), Color(0xFFFFA500)) // Slightly pleasant mood
EmojiList.MOOD_4 -> listOf(Color(0xFFFFFFFF), Color(0xFFD3D3D3)) // Neutral mood
EmojiList.MOOD_5 -> listOf(Color(0xFFFF6347), Color(0xFFCD5C5C)) // Slightly unpleasant mood
EmojiList.MOOD_6 -> listOf(Color(0xFF8B0000), Color(0xFFB22222)) // Unpleasant mood
EmojiList.MOOD_7 -> listOf(Color(0xFF696969), Color(0xFF363636)) // Very unpleasant mood
else -> listOf(
Color(0xFFE0E0E0),
Color(0xFFBEBEBE)
) // Default grayish gradient for unknown mood
}.toImmutableList()
}
fun generateEmojiForUI(): List<EmojiUiModel> = emojiList.mapIndexed { index, emojiItem ->
EmojiUiModel(id = index, emojiUnicode = emojiItem)
}
}
| 0
|
Kotlin
|
0
| 0
|
6b0fd1a88645a400072722d8ee63f56dfb9391cc
| 12,400
|
Mabia
|
MIT License
|
app/src/main/java/com/serhatd/streamtapedownloader/ui/helper/ToastManager.kt
|
serhat-demir
| 619,237,956
| false
| null |
package com.serhatd.streamtapedownloader.ui.helper
import android.content.Context
import android.widget.Toast
import com.serhatd.streamtapedownloader.R
class ToastManager(private val context: Context) {
fun showMessage(toastMessage: ToastMessage, message: String = "") {
val msg = when(toastMessage) {
ToastMessage.VIDEO_URL_EMPTY -> context.resources.getString(R.string.msg_video_url_empty)
ToastMessage.VIDEO_URL_INVALID -> context.resources.getString(R.string.msg_video_url_invalid)
ToastMessage.VIDEO_READY_TO_DOWNLOAD -> context.resources.getString(R.string.video_is_ready_to_download)
ToastMessage.SOMETHING_WENT_WRONG -> context.resources.getString(R.string.msg_something_went_wrong)
ToastMessage.SERVER_DOWN -> context.resources.getString(R.string.msg_server_down)
}
if (message.isEmpty()) Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
else Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
| 1
|
Kotlin
|
0
| 2
|
63302410a49663f317845fdee4ca2be2d51f18e2
| 1,025
|
streamtape-downloader
|
MIT License
|
src/main/kotlin/io/github/vyo/strakh/goap/engine/Analyser.kt
|
vyo
| 44,870,177
| false
|
{"Kotlin": 16105}
|
package io.github.vyo.strakh.goap.engine
/**
* Created by <NAME> on 21.11.2015.
*/
| 0
|
Kotlin
|
0
| 0
|
520882888973aa775295fafde8d017613cc58247
| 86
|
strakh
|
MIT License
|
app/src/main/java/com/sinthoras/randograf/cardviews/CardView.kt
|
SinTh0r4s
| 444,149,281
| false
| null |
package com.sinthoras.randograf.cardviews
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.sinthoras.randograf.cards.Card
abstract class CardView protected constructor(contentLayerID: Int) : Fragment(contentLayerID) {
companion object {
val PARAMETER_CARD_KEY: String = "card"
}
private lateinit var card: Card
protected fun <T: Card> getCard() = card as T
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
card = arguments?.getSerializable(PARAMETER_CARD_KEY) as Card
}
}
| 1
| null |
1
| 1
|
5319ccb2ebbb9e90f957a065794ad5aebff20459
| 708
|
Randograf
|
MIT License
|
restassured/src/test/kotlin/org/mex/restassured/ReqresPojoTest.kt
|
xomarnd
| 625,173,819
| false
| null |
package org.mex.restassured
import io.qameta.allure.Feature
import io.restassured.RestAssured
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.mex.restassured.colors.Data
import org.mex.restassured.registration.Register
import org.mex.restassured.registration.SuccessUserReg
import org.mex.restassured.registration.UnsuccessUserReg
import org.mex.restassured.users.UserData
import org.mex.restassured.users.UserTime
import org.mex.restassured.users.UserTimeResponse
import java.time.Clock
import java.util.function.Consumer
import java.util.function.Function
import java.util.function.Predicate
import java.util.stream.Collectors
@DisplayName("Апи тесты с Pojo классами")
@Feature("Api Regres Pojo")
class ReqresPojoTest {
private val URL = "https://reqres.in"
/**
* 1. Получить список пользователей со второй страница на сайте https://reqres.in/
* 2. Убедиться что id пользователей содержаться в их avatar;
* 3. Убедиться, что email пользователей имеет окончание reqres.in;
*/
@Test
@DisplayName("Аватары содержат айди пользователей")
fun checkAvatarContainsIdTest() {
Specifications.installSpecification(
Specifications.requestSpec(URL),
Specifications.responseSpecOK200()
)
//1 способ сравнивать значения напрямую из экземпляров класса
val users = RestAssured.given()
.`when`()["api/users?page=2"]
.then()
.log().all()
.extract().body().jsonPath().getList("data", UserData::class.java)
//проверка аватар содержит айди
users.forEach(Consumer { x: UserData -> Assertions.assertTrue(x.avatar!!.contains(x.id.toString())) })
//проверка почты оканчиваются на reqres.in
Assertions.assertTrue(users.stream().allMatch(Predicate { x: UserData -> x.email!!.endsWith("@reqres.in") }))
//2 способ сравнивать значения через получения списков
//список с аватарками
val realPeopleAvatars = users.stream()
.map(Function { obj: UserData -> obj.avatar })
.collect(Collectors.toList())
//список с айди
val realPeopleIds = users.stream()
.map(Function { x: UserData -> x.id.toString() })
.collect(Collectors.toList())
//проверка через сравнение двух списков
for (i in realPeopleAvatars.indices) {
Assertions.assertTrue(realPeopleAvatars[i]!!.contains(realPeopleIds[i]))
}
}
/**
* 1. Используя сервис https://reqres.in/ протестировать регистрацию пользователя в системе
* 2. Тест для успешной регистрации
*/
@Test
@DisplayName("Успешная регистрация")
fun successUserRegTest() {
val UserId = 4
val UserPassword = "<PASSWORD>"
Specifications.installSpecification(Specifications.requestSpec(URL), Specifications.responseSpecOK200())
val user = Register("<EMAIL>", "pistol")
val successUserReg = RestAssured.given()
.body(user)
.`when`()
.post("api/register")
.then()
.log().all()
.extract().`as`(SuccessUserReg::class.java)
Assertions.assertNotNull(successUserReg.id)
Assertions.assertNotNull(successUserReg.token)
Assertions.assertEquals(UserId, successUserReg.id)
Assertions.assertEquals(UserPassword, successUserReg.token)
}
/**
* 1. Используя сервис https://reqres.in/ протестировать регистрацию пользователя в системе
* 2. Тест для неуспешной регистрации (не введен пароль)
*/
@Test
@DisplayName("Не успешная регистрация")
fun unSuccessUserRegTest() {
Specifications.installSpecification(Specifications.requestSpec(URL), Specifications.responseSpecError400())
val peopleSecond = Register("<EMAIL>", "")
val unSuccessUserReg = RestAssured.given()
.body(peopleSecond)
.`when`()
.post("/api/register")
.then() //.assertThat().statusCode(400) проверить статус ошибки, если не указана спецификация
.log().body()
.extract().`as`(UnsuccessUserReg::class.java)
Assertions.assertNotNull(unSuccessUserReg.error)
Assertions.assertEquals("Missing password", unSuccessUserReg.error)
}
/**
* Используя сервис https://reqres.in/ убедиться, что операция LIST<RESOURCE> возвращает данные,
* отсортированные по годам.
</RESOURCE> */
@Test
@DisplayName("Года правильно отсортированы")
fun checkSortedYearsTest() {
Specifications.installSpecification(Specifications.requestSpec(URL), Specifications.responseSpecOK200())
val data = RestAssured.given()
.`when`()["/api/unknown"]
.then()
.log().all()
.extract().body().jsonPath().getList("data", Data::class.java)
val dataYears = data.stream().map(Function { obj: Data -> obj.year }).collect(Collectors.toList())
val sortedDataYears = dataYears.stream().sorted().collect(Collectors.toList())
Assertions.assertEquals(dataYears, sortedDataYears)
println(dataYears)
println(sortedDataYears)
}
/**
* Тест 4.1
* Используя сервис https://reqres.in/ попробовать удалить второго пользователя и сравнить статус-код
*/
@Test
@DisplayName("Удаление пользователя")
fun deleteUserTest() {
Specifications.installSpecification(Specifications.requestSpec(URL), Specifications.responseSpec(204))
RestAssured.given().`when`().delete("/api/users/2")
.then()
.log().all()
}
/**
* Используя сервис https://reqres.in/ обновить информацию о пользователе и сравнить дату обновления с текущей датой на машине
*/
@Test
@DisplayName("Время сервера и компьютера совпадают")
fun checkServerAndPcDateTest() {
Specifications.installSpecification(Specifications.requestSpec(URL), Specifications.responseSpecOK200())
val user = UserTime("morpheus", "zion resident")
val response = RestAssured.given()
.body(user)
.`when`()
.put("/api/users/2")
.then().log().all()
.extract().`as`(UserTimeResponse::class.java)
//так как время считается в плоть до миллисекунд, необходимо убрать последние 5 символов, чтобы время было одинаковое
val regex = "(.{5})$"
val currentTime = Clock.systemUTC().instant().toString().replace(regex.toRegex(), "")
Assertions.assertEquals(response.updatedAt.replace(regex.toRegex(), ""), currentTime)
}
}
| 0
|
Kotlin
|
0
| 0
|
108705f4f50bc3f567ae17ac408dbc727c3008cd
| 6,681
|
aqa-project
|
Apache License 2.0
|
src/pomodoro/actions.kt
|
dkandalov
| 691,476
| false
|
{"Kotlin": 39380, "Java": 10075}
|
package pomodoro
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import pomodoro.model.PomodoroState.Mode.*
import pomodoro.model.time.Time
class StartOrStopPomodoro : AnAction(), DumbAware {
override fun actionPerformed(event: AnActionEvent) {
service<PomodoroService>().model.onUserSwitchToNextState(Time.now())
}
override fun update(event: AnActionEvent) {
val mode = service<PomodoroService>().model.state.mode
event.presentation.text = when (mode) {
Run -> "Stop Pomodoro Timer"
Break -> "Stop Pomodoro Timer"
Stop -> "Start Pomodoro Timer"
}
}
}
class ResetPomodorosCounter : AnAction("Reset Pomodoros Counter"), DumbAware {
override fun actionPerformed(event: AnActionEvent) {
service<PomodoroService>().model.resetPomodoros()
}
}
| 8
|
Kotlin
|
22
| 129
|
37586ed88c1b7f51e9e70f4105adae1bb73ce51b
| 995
|
pomodoro-tm
|
Apache License 2.0
|
app/src/main/java/com/projectAnya/stunthink/presentation/screen/monitoring/child/list/ChildListViewModel.kt
|
StuntedProject
| 514,847,131
| false
|
{"Kotlin": 522096}
|
package com.projectAnya.stunthink.presentation.screen.monitoring.child.list
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.projectAnya.stunthink.domain.common.Resource
import com.projectAnya.stunthink.domain.use_case.monitoring.child.GetChildListUseCase
import com.projectAnya.stunthink.utils.DateUtils
import com.projectAnya.stunthink.utils.StringUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@HiltViewModel
class ChildListViewModel @Inject constructor(
private val getChildListUseCase: GetChildListUseCase
): ViewModel() {
private val _state = mutableStateOf(ChildListState())
val state: State<ChildListState> = _state
fun getChilds(token: String) {
getChildListUseCase(token).onEach { result ->
when (result) {
is Resource.Success -> {
_state.value = ChildListState(childList = result.data?.map {
com.projectAnya.stunthink.data.remote.dto.child.ChildDto(
id = it.id,
jenisKelamin = StringUtils.convertGenderEnum(it.jenisKelamin),
namaLengkap = it.namaLengkap,
parentId = it.parentId,
tanggalLahir = DateUtils.formatDateToIndonesianDate(it.tanggalLahir),
tempatLahir = it.tempatLahir
)
} ?: emptyList())
}
is Resource.Error -> {
_state.value = ChildListState(
error = result.message ?: "An unexpected error occured"
)
}
is Resource.Loading -> {
_state.value = ChildListState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
}
| 0
|
Kotlin
|
0
| 1
|
fb2cd6cb887908070962c8a4e05c87197c333d53
| 2,070
|
Mobile
|
Freetype Project License
|
app/src/androidTest/java/com/adammcneilly/toa/addtask/ui/AddTaskContentTest.kt
|
AdamMc331
| 402,227,056
| false
| null |
package com.adammcneilly.toa.addtask.ui
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import com.adammcneilly.toa.addtask.domain.model.TaskInput
import com.adammcneilly.toa.core.ui.UIText
import org.junit.Rule
import org.junit.Test
class AddTaskContentTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun renderInitialViewState() {
val viewState = AddTaskViewState.Initial()
composeTestRule.setContent {
AddTaskContent(
viewState = viewState,
onTaskDescriptionChanged = {},
onTaskScheduledDateChanged = {},
onSubmitClicked = {},
)
}
composeTestRule
.onNodeWithTag(ADD_TASK_DESCRIPTION_INPUT_TAG)
.assertIsFocused()
}
@Test
fun renderInvalidInputMessages() {
val descriptionError = "Description error"
val viewState = AddTaskViewState.Active(
taskInput = TaskInput(),
descriptionInputErrorMessage = UIText.StringText(descriptionError),
)
composeTestRule.setContent {
AddTaskContent(
viewState = viewState,
onTaskDescriptionChanged = {},
onTaskScheduledDateChanged = {},
onSubmitClicked = {},
)
}
composeTestRule.onNodeWithText(descriptionError).assertIsDisplayed()
}
}
| 41
| null |
19
| 146
|
ef4f4ba033fd46a45f42d26897800a2936e07ad3
| 1,631
|
TOA
|
MIT License
|
app/src/main/java/com/example/aifash/ui/users/VoucherAdapter.kt
|
takamanu
| 711,208,871
| false
|
{"Kotlin": 207697}
|
package com.example.aifash.ui.users
import android.content.Context
import android.content.SharedPreferences
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.aifash.R
import com.example.aifash.auth.login.LoginResponse
import com.example.aifash.datamodel.VoucherItem
import com.example.aifash.ui.users.dashboard.DashboardViewModel
import com.google.gson.Gson
class VoucherAdapter(
private val voucherItems: List<VoucherItem>,
private val viewModel: DashboardViewModel,
private val context: Context
) : RecyclerView.Adapter<VoucherAdapter.VoucherViewHolder>() {
private lateinit var sharedPreferences: SharedPreferences
inner class VoucherViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleTextView: TextView = itemView.findViewById(R.id.titleTextView)
val contentTextView: TextView = itemView.findViewById(R.id.contentTextView)
val statusTextView: TextView = itemView.findViewById(R.id.tv_status_history)
val imageView: ImageView = itemView.findViewById(R.id.fashionImage)
val button: Button = itemView.findViewById(R.id.btn_reedem)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VoucherViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_product, parent, false)
return VoucherViewHolder(itemView)
}
override fun onBindViewHolder(holder: VoucherViewHolder, position: Int) {
sharedPreferences = context.getSharedPreferences("session", Context.MODE_PRIVATE)
val loginResponseJson = sharedPreferences.getString("loginResponse", null)
val gson = Gson()
val loginResponse = gson.fromJson(loginResponseJson, LoginResponse::class.java)
// val userId = loginResponse.user?.id
val userId = 1
val item = voucherItems[position]
holder.titleTextView.text = item.voucherName
holder.contentTextView.text = "Redeem for ${item.voucherPrice} points"
holder.statusTextView.text = item.voucherCode
holder.button.setOnClickListener {
item.iD?.let { it1 ->
if (userId != null) {
viewModel.redeemVoucher(userId, it1)
}
}
}
Glide.with(holder.imageView)
.load(item.voucherUrlImage)
.into(holder.imageView)
}
override fun getItemCount(): Int {
return voucherItems.size
}
}
| 0
|
Kotlin
|
0
| 0
|
7ef369e0211026141f78da0b70d4d6eebada20a9
| 2,682
|
mobile_aplikasi_fashion
|
MIT License
|
src/test/kotlin/no/ssb/timeusesurveyapi/domain/householdmembertest/HouseholdMemberControllerTest.kt
|
statisticsnorway
| 566,324,955
| false
| null |
package no.ssb.timeusesurveyapi.domain.householdmembertest
import no.ssb.timeusesurveyapi.*
import no.ssb.timeusesurveyapi.domain.householdmember.deleteHouseholdMembersByIdPath
import no.ssb.timeusesurveyapi.domain.householdmember.getHouseholdMembersPath
import no.ssb.timeusesurveyapi.domain.householdmember.postHouseholdMembersPath
import no.ssb.timeusesurveyapi.domain.householdmember.putHouseholdMembersByIdPath
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod.*
import org.springframework.http.HttpStatus
import org.springframework.test.context.ActiveProfiles
import java.util.*
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@AutoConfigureWireMock(port = 9999)
@ActiveProfiles("test")
class HouseholdMemberControllerTest {
@Autowired
lateinit var restTemplate: TestRestTemplate
private val respondentId = UUID.randomUUID()
private val sessionTokenHeader = HttpHeaders().also {
it.set("Cookie", "sessionToken=<PASSWORD>")
}
@Test
fun `Getting household members should respond with same payload as from timeuse-survey-service`() {
stubGetRequest(getHouseholdMembersPath(respondentId), householdMembersJson)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member",
GET, HttpEntity<String>(sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.OK, it.statusCode)
assertEquals(householdMembersJson, it.body)
}
}
@Test
fun `Getting household members without sessionToken cookie should respond with 403`() {
restTemplate.getForEntity("/v1/respondent/$respondentId/household-member", String::class.java).also {
assertEquals(HttpStatus.FORBIDDEN, it.statusCode)
}
}
@Test
fun `404 from timeuse-survey-service when getting household members should give 404 from controller`() {
stubGetRequest(getHouseholdMembersPath(respondentId), statusCode = 404)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member",
GET, HttpEntity<String>(sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.NOT_FOUND, it.statusCode)
}
}
@Test
fun `Posting household members work as expected`(){
stubPostRequest(postHouseholdMembersPath(respondentId), householdMembersJson, statusCode = 201)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member",
POST, HttpEntity(householdMemberJson, sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.CREATED, it.statusCode)
assertEquals(householdMembersJson, it.body)
}
}
@Test
fun `400 from timeuse-survey-service when posting household members should give 400 from controller`(){
stubPostRequest(postHouseholdMembersPath(respondentId), householdMembersJson, statusCode = 400)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member",
POST, HttpEntity(householdMemberJson, sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.BAD_REQUEST, it.statusCode)
}
}
@Test
fun `Updating household members work as expected`(){
val householdMemberId = "123"
stubPutRequest(putHouseholdMembersByIdPath(respondentId, householdMemberId), payload = householdMemberJson)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member/$householdMemberId",
PUT, HttpEntity(householdMemberJson, sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.OK, it.statusCode)
assertEquals(householdMemberJson, it.body)
}
}
@Test
fun `400 from timeuse-survey-service when updating household members should give 400 from controller`(){
val householdMemberId = "123"
stubPutRequest(putHouseholdMembersByIdPath(respondentId, householdMemberId), 400, householdMemberJson)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member/$householdMemberId",
PUT, HttpEntity(householdMemberJson, sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.BAD_REQUEST, it.statusCode)
}
}
@Test
fun `404 from timeuse-survey-service when updating household members should give 404 from controller`(){
val householdMemberId = "123"
stubPutRequest(putHouseholdMembersByIdPath(respondentId, householdMemberId), 404, householdMemberJson)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member/$householdMemberId",
PUT, HttpEntity(householdMemberJson, sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.NOT_FOUND, it.statusCode)
}
}
@Test
fun `Delete household member by id work as expected`(){
val householdMemberId = "123"
stubDeleteRequest(deleteHouseholdMembersByIdPath(respondentId, householdMemberId))
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member/$householdMemberId",
DELETE, HttpEntity<String>(sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.OK, it.statusCode)
}
}
@Test
fun `404 from timeuse-survey-service when delete household member by id should give 404 from controller`(){
val householdMemberId = "123"
stubDeleteRequest(deleteHouseholdMembersByIdPath(respondentId, householdMemberId), 404)
restTemplate.exchange(
"/v1/respondent/$respondentId/household-member/$householdMemberId",
DELETE, HttpEntity<String>(sessionTokenHeader), String::class.java
).also {
assertEquals(HttpStatus.NOT_FOUND, it.statusCode)
}
}
}
| 2
|
Kotlin
|
0
| 1
|
5d88e0e719d784de460a9ca24eb866c64ad17ea8
| 6,418
|
timeuse-survey-api
|
MIT License
|
api/coroutines/v1.5.0/src/commonMain/kotlin/dev/whyoleg/ktd/api/file/CancelUploadFile.kt
|
whyoleg
| 202,767,670
| false
| null |
@file:Suppress(
"unused"
)
@file:UseExperimental(
BotsOnly::class,
TestingOnly::class
)
package dev.whyoleg.ktd.api.file
import dev.whyoleg.ktd.*
import dev.whyoleg.ktd.api.*
import dev.whyoleg.ktd.api.TdApi.*
/**
* Stops the uploading of a file
* Supported only for files uploaded by using uploadFile
* For other files the behavior is undefined
*
* @fileId - Identifier of the file to stop uploading
*/
suspend fun TelegramClient.cancelUploadFile(
fileId: Int = 0
): Ok = file(
CancelUploadFile(
fileId
)
)
/**
* Stops the uploading of a file
* Supported only for files uploaded by using uploadFile
* For other files the behavior is undefined
*/
suspend fun TelegramClient.file(
f: CancelUploadFile
): Ok = exec(f) as Ok
| 7
|
Kotlin
|
11
| 45
|
7284eeabef0bd002dc72634351ab751b048900e9
| 772
|
ktd
|
Apache License 2.0
|
ospf-kotlin-utils/src/main/fuookami/ospf/kotlin/utils/parallel/SumOf.kt
|
fuookami
| 359,831,793
| false
|
{"Kotlin": 1866628, "Python": 6629}
|
package fuookami.ospf.kotlin.utils.parallel
import kotlinx.coroutines.*
import fuookami.ospf.kotlin.utils.math.*
import fuookami.ospf.kotlin.utils.error.*
import fuookami.ospf.kotlin.utils.operator.*
import fuookami.ospf.kotlin.utils.functional.*
suspend inline fun <T, U> Iterable<T>.sumOfParallelly(
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendExtractor<U, T>
): U
where U : Arithmetic<U>, U : Plus<U, U> {
return this.sumOfParallelly(UInt64.ten, constants, extractor)
}
suspend inline fun <T, U> Iterable<T>.sumOfParallelly(
segment: UInt64,
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendExtractor<U, T>
): U
where U : Arithmetic<U>, U : Plus<U, U> {
var sum = constants.zero
coroutineScope {
val promises = ArrayList<Deferred<U>>()
val iterator = this@sumOfParallelly.iterator()
while (iterator.hasNext()) {
val thisSegment = ArrayList<T>()
var i = UInt64.zero
while (iterator.hasNext() && i != segment) {
thisSegment.add(iterator.next())
++i
}
promises.add(async(Dispatchers.Default) {
thisSegment.map { extractor(it) }.sum(constants)
})
}
promises.forEach {
sum += it.await()
}
}
return sum
}
suspend inline fun <T, U> Iterable<T>.trySumOfParallelly(
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendTryExtractor<U, T>
): Ret<U>
where U : Arithmetic<U>, U : Plus<U, U> {
return this.trySumOfParallelly(UInt64.ten, constants, extractor)
}
suspend inline fun <T, U> Iterable<T>.trySumOfParallelly(
segment: UInt64,
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendTryExtractor<U, T>
): Ret<U>
where U : Arithmetic<U>, U : Plus<U, U> {
var error: Error? = null
var sum = constants.zero
return try {
coroutineScope {
val promises = ArrayList<Deferred<U>>()
val iterator = this@trySumOfParallelly.iterator()
while (iterator.hasNext()) {
val thisSegment = ArrayList<T>()
var i = UInt64.zero
while (iterator.hasNext() && i != segment) {
thisSegment.add(iterator.next())
++i
}
promises.add(async(Dispatchers.Default) {
thisSegment.map {
when (val result = extractor(it)) {
is Ok -> {
result.value
}
is Failed -> {
error = result.error
cancel()
constants.zero
}
}
}.sum(constants)
})
}
promises.forEach {
sum += it.await()
}
}
Ok(sum)
} catch (e: CancellationException) {
error?.let { Failed(it) } ?: Ok(constants.zero)
}
}
suspend inline fun <T, U> Collection<T>.sumOfParallelly(
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendExtractor<U, T>
): U
where U : Arithmetic<U>, U : Plus<U, U> {
return (this as Iterable<T>).sumOfParallelly(
defaultConcurrentAmount,
constants,
extractor
)
}
suspend inline fun <T, U> Collection<T>.sumOfParallelly(
concurrentAmount: UInt64,
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendExtractor<U, T>
): U
where U : Arithmetic<U>, U : Plus<U, U> {
return (this as Iterable<T>).sumOfParallelly(this.usize / concurrentAmount, constants, extractor)
}
suspend inline fun <T, U> Collection<T>.trySumOfParallelly(
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendTryExtractor<U, T>
): Ret<U>
where U : Arithmetic<U>, U : Plus<U, U> {
return (this as Iterable<T>).trySumOfParallelly(
defaultConcurrentAmount,
constants,
extractor
)
}
suspend inline fun <T, U> Collection<T>.trySumOfParallelly(
concurrentAmount: UInt64,
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendTryExtractor<U, T>
): Ret<U>
where U : Arithmetic<U>, U : Plus<U, U> {
return (this as Iterable<T>).trySumOfParallelly(this.usize / concurrentAmount, constants, extractor)
}
suspend inline fun <T, U> List<T>.sumOfParallelly(
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendExtractor<U, T>
): U
where U : Arithmetic<U>, U : Plus<U, U> {
return this.sumOfParallelly(
defaultConcurrentAmount,
constants,
extractor
)
}
suspend inline fun <T, U> List<T>.sumOfParallelly(
concurrentAmount: UInt64,
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendExtractor<U, T>
): U
where U : Arithmetic<U>, U : Plus<U, U> {
var sum = constants.zero
coroutineScope {
val promises = ArrayList<Deferred<U>>()
val segmentAmount = this@sumOfParallelly.size / concurrentAmount.toInt()
var i = 0
while (i != this@sumOfParallelly.size) {
val j = i
val k = i + minOf(
segmentAmount,
this@sumOfParallelly.size - i
)
promises.add(async(Dispatchers.Default) {
this@sumOfParallelly.subList(j, k).map { extractor(it) }.sum(constants)
})
i = k
}
promises.forEach {
sum += it.await()
}
}
return sum
}
suspend inline fun <T, U> List<T>.trySumOfParallelly(
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendTryExtractor<U, T>
): Ret<U>
where U : Arithmetic<U>, U : Plus<U, U> {
return this.trySumOfParallelly(
defaultConcurrentAmount,
constants,
extractor
)
}
suspend inline fun <T, U> List<T>.trySumOfParallelly(
concurrentAmount: UInt64,
constants: ArithmeticConstants<U>,
crossinline extractor: SuspendTryExtractor<U, T>
): Ret<U>
where U : Arithmetic<U>, U : Plus<U, U> {
var error: Error? = null
var sum = constants.zero
return try {
coroutineScope {
val promises = ArrayList<Deferred<U>>()
val segmentAmount = this@trySumOfParallelly.size / concurrentAmount.toInt()
var i = 0
while (i != this@trySumOfParallelly.size) {
val j = i
val k = i + minOf(
segmentAmount,
this@trySumOfParallelly.size - i
)
promises.add(async(Dispatchers.Default) {
this@trySumOfParallelly.subList(j, k).map {
when (val result = extractor(it)) {
is Ok -> {
result.value
}
is Failed -> {
error = result.error
cancel()
constants.zero
}
}
}.sum(constants)
})
i = k
}
promises.forEach {
sum += it.await()
}
}
Ok(sum)
} catch (e: CancellationException) {
error?.let { Failed(it) } ?: Ok(constants.zero)
}
}
| 0
|
Kotlin
|
0
| 1
|
3b61f048a470c1dc24b0bbe90793b59cba193b77
| 7,627
|
ospf-kotlin
|
Apache License 2.0
|
app/src/test/java/org/p2p/wallet/swap/serum/utils/CoroutineTest.kt
|
p2p-org
| 306,035,988
| false
| null |
package org.p2p.wallet.swap.serum.utils
import org.junit.Rule
open class CoroutineTest {
@get:Rule
val rule = CoroutinesTestWatcher()
}
| 9
|
Kotlin
|
14
| 23
|
2badf683d824c57654b12ea0c023f96e1a5d0c19
| 147
|
key-app-android
|
MIT License
|
library/src/main/java/com/github/pelmenstar1/rangecalendar/selection/DefaultSelectionTransitionController.kt
|
pelmenstar1
| 454,918,220
| false
|
{"Kotlin": 666840}
|
package com.github.pelmenstar1.rangecalendar.selection
import android.graphics.PointF
import android.graphics.RectF
import androidx.core.graphics.component1
import androidx.core.graphics.component2
import com.github.pelmenstar1.rangecalendar.CellMeasureManager
import com.github.pelmenstar1.rangecalendar.utils.lerp
class DefaultSelectionTransitionController : SelectionTransitionController {
override fun handleTransition(
state: SelectionState.Transitive,
measureManager: CellMeasureManager,
fraction: Float
) {
when (state) {
// Cell transitions
is DefaultSelectionState.AppearAlpha -> {
state.alpha = fraction.reversedIf(state.isReversed)
}
is DefaultSelectionState.DualAlpha -> {
state.startAlpha = 1f - fraction
state.endAlpha = fraction
}
is DefaultSelectionState.CellAppearBubble -> {
val f = fraction.reversedIf(state.isReversed)
bubbleAnimation(state.baseState, f, state.bounds)
}
is DefaultSelectionState.CellDualBubble -> {
bubbleAnimation(state.start, 1f - fraction, state.startBounds)
bubbleAnimation(state.end, fraction, state.endBounds)
}
is DefaultSelectionState.CellMoveToCell -> {
val startShapeInfo = state.start.shapeInfo
val endShapeInfo = state.end.shapeInfo
val currentShapeInfo = state.shapeInfo
val currentLeft = lerp(startShapeInfo.startLeft, endShapeInfo.startLeft, fraction)
val currentTop = lerp(startShapeInfo.startTop, endShapeInfo.startTop, fraction)
currentShapeInfo.startLeft = currentLeft
currentShapeInfo.startTop = currentTop
currentShapeInfo.endRight = currentLeft + currentShapeInfo.cellWidth
val cell = measureManager.getCellAt(
currentLeft, currentTop,
relativity = CellMeasureManager.CoordinateRelativity.GRID
)
currentShapeInfo.range = CellRange.single(cell)
}
is DefaultSelectionState.RangeToRange -> {
val newStartCellDist =
lerp(state.startStateStartCellDistance, state.endStateStartCellDistance, fraction)
val newEndCellDist = lerp(state.startStateEndCellDistance, state.endStateEndCellDistance, fraction)
state.currentStartCellDistance = newStartCellDist
state.currentEndCellDistance = newEndCellDist
val newStartCell = measureManager.getCellAndPointByDistance(newStartCellDist, point)
val (newStartCellLeft, newStartCellTop) = point
val newEndCell = measureManager.getCellAndPointByDistance(newEndCellDist, point)
val (newEndCellRight, newEndCellTop) = point
state.shapeInfo.apply {
startLeft = newStartCellLeft
startTop = newStartCellTop
endRight = newEndCellRight
endTop = newEndCellTop
range = CellRange(newStartCell, newEndCell)
}
}
}
}
companion object {
private val point = PointF()
private fun Float.reversedIf(flag: Boolean) = if (flag) 1f - this else this
private fun bubbleAnimation(
state: DefaultSelectionState,
fraction: Float,
outRect: RectF
) {
val shapeInfo = state.shapeInfo
val rx = shapeInfo.cellWidth * 0.5f
val ry = shapeInfo.cellHeight * 0.5f
val cx = shapeInfo.startLeft + rx
val cy = shapeInfo.startTop + ry
val frx = rx * fraction
val fry = ry * fraction
outRect.apply {
left = cx - frx
top = cy - fry
right = cx + frx
bottom = cy + fry
}
}
}
}
| 2
|
Kotlin
|
0
| 13
|
c3b64a254a0e5e9bfb9a1b4db53261d1d5373be5
| 4,116
|
RangeCalendar
|
MIT License
|
feature_favourite/src/main/kotlin/com/igorwojda/showcase/feature/favourite/domain/FavouriteDomainModule.kt
|
igorwojda
| 158,460,787
| false
| null |
package com.igorwojda.showcase.feature.favourite.domain
import com.igorwojda.showcase.feature.favourite.MODULE_NAME
import org.kodein.di.Kodein
internal val domainModule = Kodein.Module("${MODULE_NAME}DomainModule") { }
| 36
|
Kotlin
|
762
| 5,527
|
f7919d0a9a718433b85583b285b1b99e19df27f0
| 222
|
android-showcase
|
MIT License
|
library/src/main/java/org/jetbrains/anko/collections/Collections.kt
|
chenfei0928
| 130,954,695
| false
|
{"Kotlin": 928525, "Java": 336337}
|
package org.jetbrains.anko.collections
/**
* Iterate the receiver [List] backwards using an index.
*
* @f an action to invoke on each list element (index, element).
*/
inline fun <T> List<T>.forEachReversedWithIndex(f: (Int, T) -> Unit) {
var i = size - 1
while (i >= 0) {
f(i, get(i))
i--
}
}
| 0
|
Kotlin
|
0
| 7
|
da7041e5f2c665dea27e56223112046bdf9c3910
| 328
|
Util
|
MIT License
|
src/main/kotlin/no/nav/syfo/behandler/kafka/dialogmeldingfrombehandler/KafkaDialogmeldingFromBehandlerDTO.kt
|
navikt
| 378,118,189
| false
| null |
package no.nav.syfo.behandler.kafka.dialogmeldingfrombehandler
import java.time.LocalDateTime
data class KafkaDialogmeldingFromBehandlerDTO(
val msgId: String,
val navLogId: String,
val mottattTidspunkt: LocalDateTime,
val personIdentPasient: String,
val personIdentBehandler: String,
val legekontorOrgNr: String?,
val legekontorHerId: String?,
val legekontorOrgName: String,
val legehpr: String?,
val fellesformatXML: String,
)
| 0
|
Kotlin
|
1
| 0
|
ac0942c5fde21a82e3f4bbe1c3500fa03264c051
| 471
|
isdialogmelding
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.