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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
arrow-libs/fx/arrow-fx-coroutines/src/jvmTest/kotlin/examples/example-circuitbreaker-02.kt
|
arrow-kt
| 86,057,409
| false
| null |
// This file was automatically generated from CircuitBreaker.kt by Knit tool. Do not edit.
package arrow.fx.coroutines.examples.exampleCircuitbreaker02
import arrow.core.Either
import arrow.fx.coroutines.CircuitBreaker
import arrow.fx.coroutines.Schedule
import arrow.fx.coroutines.retry
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import kotlinx.coroutines.delay
@ExperimentalTime
suspend fun main(): Unit {
suspend fun apiCall(): Unit {
println("apiCall . . .")
throw RuntimeException("Overloaded service")
}
//sampleStart
val circuitBreaker = CircuitBreaker.of(
maxFailures = 2,
resetTimeout = seconds(2),
exponentialBackoffFactor = 2.0, // enable exponentialBackoffFactor
maxResetTimeout = seconds(60), // limit exponential back-off time
)
suspend fun <A> resilient(schedule: Schedule<Throwable, *>, f: suspend () -> A): A =
schedule.retry { circuitBreaker.protectOrThrow(f) }
Either.catch {
resilient(Schedule.recurs(5), ::apiCall)
}.let { println("recurs(5) apiCall twice and 4x short-circuit result from CircuitBreaker: $it") }
delay(2000)
println("CircuitBreaker ready to half-open")
// Retry once and when the CircuitBreaker opens after 2 failures then retry with exponential back-off with same time as CircuitBreaker's resetTimeout
val fiveTimesWithBackOff = Schedule.recurs<Throwable>(1) andThen
Schedule.exponential(seconds(2)) and Schedule.recurs(5)
Either.catch {
resilient(fiveTimesWithBackOff, ::apiCall)
}.let { println("exponential(seconds(2)) and recurs(5) always retries with actual apiCall: $it") }
//sampleEnd
}
| 38
| null |
436
| 5,958
|
5f0da6334b834bad481c7e3c906bee5a34c1237b
| 1,650
|
arrow
|
Apache License 2.0
|
kuksa-sdk/src/test/kotlin/org/eclipse/kuksa/connectivity/databroker/DataBrokerConnectorTest.kt
|
eclipse-kuksa
| 687,949,615
| false
|
{"Kotlin": 339819, "Java": 9058, "Shell": 2409}
|
/*
* Copyright (c) 2023 Contributors to the Eclipse Foundation
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.eclipse.kuksa.connectivity.databroker
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldNotBe
import org.eclipse.kuksa.connectivity.databroker.docker.DataBrokerDockerContainer
import org.eclipse.kuksa.connectivity.databroker.docker.InsecureDataBrokerDockerContainer
import org.eclipse.kuksa.test.kotest.Insecure
import org.eclipse.kuksa.test.kotest.InsecureDataBroker
import org.eclipse.kuksa.test.kotest.Integration
class DataBrokerConnectorTest : BehaviorSpec({
tags(Integration, Insecure, InsecureDataBroker)
var databrokerContainer: DataBrokerDockerContainer? = null
beforeSpec {
databrokerContainer = InsecureDataBrokerDockerContainer()
.apply {
start()
}
}
afterSpec {
databrokerContainer?.stop()
}
given("A DataBrokerConnectorProvider") {
val dataBrokerConnectorProvider = DataBrokerConnectorProvider()
and("an insecure DataBrokerConnector with valid Host and Port") {
val dataBrokerConnector = dataBrokerConnectorProvider.createInsecure()
`when`("Trying to establish an insecure connection") {
val connection = dataBrokerConnector.connect()
then("It should return a valid connection") {
connection shouldNotBe null
}
}
}
and("a DataBrokerConnector with INVALID Host and Port") {
val invalidHost = "0.0.0.0"
val invalidPort = 12345
val dataBrokerConnector = dataBrokerConnectorProvider.createInsecure(invalidHost, invalidPort)
`when`("Trying to establish a connection") {
val exception = shouldThrow<DataBrokerException> {
dataBrokerConnector.connect()
}
then("It should throw a DataBrokerException") {
exception shouldNotBe null
}
}
}
}
})
| 8
|
Kotlin
|
1
| 2
|
a03cf49b66d9f2116474cabdd5741f21a0511926
| 2,715
|
kuksa-android-sdk
|
Apache License 2.0
|
library/lorcana-data/src/commonMain/kotlin/eu/codlab/lorcana/cards/Erratas.kt
|
great-illuminary
| 710,799,476
| false
|
{"Kotlin": 35876, "TypeScript": 4085, "Shell": 438}
|
package eu.codlab.lorcana.cards
import kotlinx.serialization.Serializable
@Serializable
data class Erratas<C>(
val classifications: List<C>? = null
)
fun Erratas<String>.to(
mapOfClassifications: Map<String, ClassificationHolder>
): Erratas<ClassificationHolder> = Erratas(
classifications = classifications?.map { slug ->
try {
mapOfClassifications[slug]!!
} catch (@Suppress("TooGenericExceptionCaught") err: Throwable) {
println("Exception thrown because $slug couldn't be mapped")
throw err
}
}
)
| 0
|
Kotlin
|
0
| 5
|
a93d0d5c8dc5d0a7102928b4bd5fac24690429e4
| 580
|
lorcana-data
|
MIT License
|
lawnchair/src/app/lawnchair/search/LawnchairSearchAdapterProvider.kt
|
DariaRnD
| 481,438,445
| true
|
{"Java Properties": 1, "YAML": 14, "Text": 9, "Markdown": 6, "XML": 880, "INI": 2, "Makefile": 3, "Gradle": 7, "Shell": 1, "EditorConfig": 1, "Git Attributes": 1, "Batchfile": 1, "Soong": 3, "Python": 5, "Proguard": 1, "Ignore List": 1, "Git Config": 1, "AIDL": 12, "Java": 899, "Kotlin": 319, "JSON": 6, "Protocol Buffer": 6}
|
package app.lawnchair.search
import android.util.SparseIntArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.util.containsKey
import app.lawnchair.LawnchairLauncher
import app.lawnchair.allapps.SearchItemDecorator
import app.lawnchair.allapps.SearchResultView
import app.lawnchair.allapps.SearchResultView.Companion.EXTRA_QUICK_LAUNCH
import com.android.app.search.LayoutType
import com.android.launcher3.R
import com.android.launcher3.allapps.AllAppsContainerView
import com.android.launcher3.allapps.AllAppsGridAdapter
import com.android.launcher3.allapps.search.DefaultSearchAdapterProvider
class LawnchairSearchAdapterProvider(
launcher: LawnchairLauncher,
private val appsView: AllAppsContainerView
) : DefaultSearchAdapterProvider(launcher, appsView) {
private val decorator = SearchItemDecorator(appsView)
private val layoutIdMap = SparseIntArray().apply {
append(SEARCH_RESULT_ICON, R.layout.search_result_icon)
append(SEARCH_RESULT_ICON_ROW, R.layout.search_result_tall_icon_row)
append(SEARCH_RESULT_SMALL_ICON_ROW, R.layout.search_result_small_icon_row)
append(SEARCH_RESULT_DIVIDER, R.layout.search_result_divider)
}
private var quickLaunchItem: SearchResultView? = null
set(value) {
field = value
appsView.searchUiManager.setFocusedResultTitle(field?.titleText)
}
override fun isViewSupported(viewType: Int): Boolean = layoutIdMap.containsKey(viewType)
override fun onBindView(holder: AllAppsGridAdapter.ViewHolder, position: Int) {
val adapterItem = appsView.apps.adapterItems[position] as SearchAdapterItem
if ((adapterItem.viewType and SEARCH_RESULT_DIVIDER) != 0) return
val itemView = holder.itemView as SearchResultView
itemView.bind(adapterItem.searchTarget, emptyList())
if (itemView.isQuickLaunch) {
quickLaunchItem = itemView
}
}
override fun onCreateViewHolder(
layoutInflater: LayoutInflater,
parent: ViewGroup?,
viewType: Int
): AllAppsGridAdapter.ViewHolder =
AllAppsGridAdapter.ViewHolder(layoutInflater.inflate(layoutIdMap[viewType], parent, false))
override fun getItemsPerRow(viewType: Int, appsPerRow: Int) =
if (viewType != SEARCH_RESULT_ICON) 1 else super.getItemsPerRow(viewType, appsPerRow)
override fun launchHighlightedItem(): Boolean = quickLaunchItem?.launch() ?: false
override fun getHighlightedItem() = quickLaunchItem as View?
override fun getDecorator() = decorator
companion object {
private const val SEARCH_RESULT_ICON = (1 shl 8) or AllAppsGridAdapter.VIEW_TYPE_ICON
private const val SEARCH_RESULT_ICON_ROW = 1 shl 9
private const val SEARCH_RESULT_SMALL_ICON_ROW = 1 shl 10
private const val SEARCH_RESULT_DIVIDER = 1 shl 11
val viewTypeMap = mapOf(
LayoutType.ICON_SINGLE_VERTICAL_TEXT to SEARCH_RESULT_ICON,
LayoutType.ICON_HORIZONTAL_TEXT to SEARCH_RESULT_ICON_ROW,
LayoutType.SMALL_ICON_HORIZONTAL_TEXT to SEARCH_RESULT_SMALL_ICON_ROW,
LayoutType.HORIZONTAL_MEDIUM_TEXT to SEARCH_RESULT_SMALL_ICON_ROW,
LayoutType.EMPTY_DIVIDER to SEARCH_RESULT_DIVIDER,
)
fun setFirstItemQuickLaunch(items: List<SearchAdapterItem>) {
val hasQuickLaunch = items.any { it.searchTarget.extras.getBoolean(EXTRA_QUICK_LAUNCH, false) }
if (!hasQuickLaunch) {
items.firstOrNull()?.searchTarget?.extras?.apply {
putBoolean(EXTRA_QUICK_LAUNCH, true)
}
}
}
}
}
| 7
|
Java
|
1
| 5
|
1b13066090b80104c6524e93bd09856f76b2f814
| 3,722
|
lawnchair
|
Apache License 2.0
|
petblocks-api/src/main/kotlin/com/github/shynixn/petblocks/api/business/service/CarryPetService.kt
|
Shynixn
| 78,876,167
| false
| null |
package com.github.shynixn.petblocks.api.business.service
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
interface CarryPetService {
/**
* Starts the given [player] carry his pet if is is currently spawned.
* Does nothing if the pet is already getting carried.
* @param P the type of the player.
*/
fun <P> carryPet(player: P)
/**
* Lets the given [player] drop his pet if he is currently carrying it.
* Does nothing if the player isn't carrying it.
* Returns when the action was completed.
* @param P the type of the player.
*/
fun <P> dropPet(player: P)
/**
* Lets the given [player] throw his pet if he is currently carrying.
* Does automatically drop it and does nothing if the player isn't carrying it.
* Returns when the action was completed.
* @param P the type of the player.
*/
fun <P> throwPet(player: P)
/**
* Gets the itemstack from the carrying pet.
* Returns an empty optional if the player is carrying anything.
* @param P the type of the player.
*/
fun <P, I> getCarryPetItemStack(player: P): I?
/**
* Gets if the given player is carrying a pet.
* @param P the type of the player.
*/
fun <P> isCarryingPet(player: P): Boolean
/**
* Clears all resources the given [player] may have allocated.
* @param P the type of the player.
*/
fun <P> clearResources(player: P)
}
| 22
| null |
12
| 71
|
730e19e9e70dea1dcdafa3a98f9356b9577565db
| 2,615
|
PetBlocks
|
Apache License 2.0
|
kotlin-mui/src/main/generated/mui/material/Container.classes.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
package mui.material
external interface ContainerClasses {
/** Styles applied to the root element. */
var root: String
/** Styles applied to the root element if `disableGutters={true}`. */
var disableGutters: String
/** Styles applied to the root element if `fixed={true}`. */
var fixed: String
/** Styles applied to the root element if `maxWidth="xs"`. */
var maxWidthXs: String
/** Styles applied to the root element if `maxWidth="sm"`. */
var maxWidthSm: String
/** Styles applied to the root element if `maxWidth="md"`. */
var maxWidthMd: String
/** Styles applied to the root element if `maxWidth="lg"`. */
var maxWidthLg: String
/** Styles applied to the root element if `maxWidth="xl"`. */
var maxWidthXl: String
}
| 10
|
Kotlin
|
145
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 839
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/kotlin/com/teixeira/gdx/App.kt
|
teixeira0x
| 848,011,066
| false
|
{"Kotlin": 8306}
|
package com.teixeira.gdx
import com.teixeira.gdx.command.DEFAULT_LANGUAGE
import com.teixeira.gdx.command.DEFAULT_MIN_SDK
import com.teixeira.gdx.command.DEFAULT_TARGET_SDK
import com.teixeira.gdx.command.OPT_LANGUAGE
import com.teixeira.gdx.command.OPT_MIN_SDK
import com.teixeira.gdx.command.OPT_NAME
import com.teixeira.gdx.command.OPT_PACKAGE
import com.teixeira.gdx.command.OPT_TARGET_SDK
import com.teixeira.gdx.command.getCommandOptions
import com.teixeira.gdx.command.printCommandHelp
import com.teixeira.gdx.writer.ProjectWriter
import kotlin.system.exitProcess
import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
fun main(args: Array<String>) {
val app = App()
exitProcess(
if (args.isNotEmpty()) {
app.run(args)
} else {
app.runApp()
}
)
}
class App {
companion object {
val REGEX_JAVA_OR_KOTLIN = Regex("^(java|kotlin)$")
}
// Run command
fun run(args: Array<String>): Int {
val command: CommandLine? =
try {
DefaultParser().parse(getCommandOptions(), args)
} catch (e: Exception) {
println(e.localizedMessage)
println()
printCommandHelp()
null
}
if (command == null) {
return 1
}
val name = command.getOptionValue(OPT_NAME).trim()
val packageName = command.getOptionValue(OPT_PACKAGE).trim()
val language = command.getOptionValue(OPT_LANGUAGE, DEFAULT_LANGUAGE).trim()
val minSdk = command.getOptionValue(OPT_MIN_SDK, DEFAULT_MIN_SDK).trim()
val targetSdk = command.getOptionValue(OPT_TARGET_SDK, DEFAULT_TARGET_SDK).trim()
if (!language.matches(REGEX_JAVA_OR_KOTLIN)) {
print("Choose between kotlin or java language.")
return 1
}
val writer = ProjectWriter(language, name, packageName, minSdk, targetSdk)
writer.write { message -> println(message) }
return 0
}
// Run application
fun runApp(): Int {
println("Welcome to the LibGDX project builder for AndroidIDE!")
println("Let's start creating")
println()
print("Enter the project name:")
val name = readLine()
if (name?.isEmpty() ?: true) {
println("The name cannot be empty!")
return 1
}
print("Enter the app package:")
val packageName = readLine()
if (packageName?.isEmpty() ?: true) {
println("The app package cannot be empty!")
return 1
}
print("Enter the project language (Default $DEFAULT_LANGUAGE):")
var language = readLine()
if (language?.isEmpty() ?: true) {
language = DEFAULT_LANGUAGE
}
if (!language!!.matches(REGEX_JAVA_OR_KOTLIN)) {
print("Choose between kotlin or java language.")
return 1
}
print("Enter the project minSdk (Default $DEFAULT_MIN_SDK):")
var minSdk = readLine()
if (minSdk?.isEmpty() ?: true) {
minSdk = DEFAULT_MIN_SDK
}
print("Enter the project targetSdk (Default $DEFAULT_TARGET_SDK):")
var targetSdk = readLine()
if (targetSdk?.isEmpty() ?: true) {
targetSdk = DEFAULT_TARGET_SDK
}
println()
val writer = ProjectWriter(language!!, name!!, packageName!!, minSdk!!, targetSdk!!)
writer.write { message -> println(message) }
return 0
}
}
| 0
|
Kotlin
|
0
| 6
|
26cb28c0c554aecc55ec4e36e183b44a5f8a685b
| 3,237
|
androidide-libgdx
|
Apache License 2.0
|
app/src/main/java/br/com/monteoliva/githubuserslist/ui/features/BaseFragment.kt
|
monteoliva
| 630,295,904
| false
| null |
package br.com.monteoliva.githubuserslist.ui.features
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
abstract class BaseFragment<T: ViewDataBinding> : Fragment() {
protected var binding: T? = null
override fun onAttach(context: Context) {
super.onAttach(context)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
DataBindingUtil.inflate<T>(inflater, getLayoutId(), container, false).also {
binding = it
}
return binding?.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startInitViews()
}
override fun onResume() {
super.onResume()
startViewModel()
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
private fun startInitViews() {
Handler(Looper.getMainLooper()).postDelayed({ initViews() }, 60)
}
private fun startViewModel() {
Handler(Looper.getMainLooper()).postDelayed({ initViewModel() }, 60)
}
fun errorMsg(@StringRes msg: Int) { errorMsg(getString(msg)) }
fun errorMsg(message: String) { (activity as? BaseActivity<*>)?.errorMsg(message) }
fun boxMsg(@StringRes msg: Int, callback: () -> Unit) { boxMsg(getString(msg)) {callback.invoke()}}
fun boxMsg(message: String, callback: () -> Unit) {
(activity as? BaseActivity<*>)?.boxMsg(message) { callback.invoke() }
}
fun setLoading(isLoading: Boolean) { (activity as? BaseActivity<*>)?.setLoading(isLoading) }
@LayoutRes
abstract fun getLayoutId() : Int
abstract fun initViews()
abstract fun initViewModel()
}
| 0
|
Kotlin
|
0
| 0
|
a545c0676a412f2fd6162a22e91f0753d94f2a57
| 2,100
|
githubuserslist
|
Apache License 2.0
|
common/src/commonMain/kotlin/com/artemchep/keyguard/ui/shimmer/rememberShimmer.kt
|
AChep
| 669,697,660
| false
| null |
package com.valentinilk.shimmer
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Rect
import kotlinx.coroutines.flow.MutableStateFlow
@Composable
fun rememberShimmer(shimmerBounds: ShimmerBounds): Shimmer {
val theme = LocalShimmerTheme.current
val effect = rememberShimmerEffect(theme)
val bounds = rememberShimmerBounds(shimmerBounds)
return remember(theme, effect, bounds) {
Shimmer(theme, effect, bounds)
}
}
/**
* Shimmer describes a shimmer fully, without Theme!?
*
*/
class Shimmer internal constructor(
internal val theme: ShimmerTheme,
internal val effect: ShimmerEffect,
bounds: Rect?,
) {
internal val boundsFlow = MutableStateFlow(bounds)
fun updateBounds(bounds: Rect?) {
boundsFlow.value = bounds
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Shimmer
if (theme != other.theme) return false
if (effect != other.effect) return false
return true
}
override fun hashCode(): Int {
var result = theme.hashCode()
result = 31 * result + effect.hashCode()
return result
}
}
| 66
| null |
5
| 995
|
557bf42372ebb19007e3a8871e3f7cb8a7e50739
| 1,302
|
keyguard-app
|
Linux Kernel Variant of OpenIB.org license
|
statik-kotlin-psi/src/main/kotlin/com/rickbusarow/statik/element/kotlin/psi/compiler/StatikPsiFileFactoryImpl.kt
|
rickbusarow
| 764,452,627
| false
|
{"Kotlin": 523926, "Shell": 4217}
|
/*
* Copyright (C) 2024 <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 com.rickbusarow.statik.compiler.impl
import com.rickbusarow.statik.compiler.KotlinEnvironment
import com.rickbusarow.statik.compiler.StatikPsiFileFactory
import com.rickbusarow.statik.utils.lazy.LazyDeferred
import com.rickbusarow.statik.utils.lazy.lazyDeferred
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.com.intellij.openapi.vfs.StandardFileSystems
import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFileManager
import org.jetbrains.kotlin.com.intellij.psi.PsiFile
import org.jetbrains.kotlin.com.intellij.psi.PsiManager
import java.io.File
import java.io.FileNotFoundException
import java.util.concurrent.ConcurrentHashMap
/**
* A real implementation of [StatikPsiFileFactory] using a curated [KotlinEnvironment].
*
* The files created from this factory are backed by a meaningful
* [BindingContext][org.jetbrains.kotlin.resolve.BindingContext] which
* is aware of the full classpath and may be used for type resolution.
*/
internal class StatikPsiFileFactoryImpl(
kotlinEnvironment: KotlinEnvironment
) : AbstractStatikPsiFileFactory(),
StatikPsiFileFactory {
override val coreEnvironment: LazyDeferred<KotlinCoreEnvironment> =
kotlinEnvironment.coreEnvironment
private val fileCache = ConcurrentHashMap<File, PsiFile>()
private val psiProjectDeferred = lazyDeferred { coreEnvironment.await().project }
private val psiManager = lazyDeferred {
PsiManager.getInstance(psiProjectDeferred.await())
}
private val virtualFileSystem = lazyDeferred {
// make sure that the PsiManager has initialized, or we'll get NPE's when trying to initialize
// the VirtualFileManager instance
psiManager.await()
VirtualFileManager.getInstance()
.getFileSystem(StandardFileSystems.FILE_PROTOCOL)
}
override suspend fun create(file: File): PsiFile {
return fileCache.getOrPut(file) {
if (!file.exists()) throw FileNotFoundException("could not find file $file")
val vFile = virtualFileSystem.await().findFileByPath(file.absolutePath)
?: throw FileNotFoundException("could not find file $file")
val psi = psiManager.await().findFile(vFile)
when (file.extension) {
"java" -> psi as PsiFile
"kt", "kts" -> psi as PsiFile
else -> error(
"file extension must be one of [java, kt, kts], but it was `${file.extension}`."
)
}
}
}
}
| 6
|
Kotlin
|
0
| 9
|
850e77a03017d2c73452a5f005709dffdbd06de1
| 3,022
|
statik
|
Apache License 2.0
|
DiceGame.kt
|
Cambrian-ITCAMD
| 600,304,106
| false
| null |
/*
Jay Patel : A00254220
Viren Moliya : A00245404
Smith Parekh : A00241603
*/
fun main() {
println("Creating a default d6...")
var default = Dice()
print("\nCreating a d")
var userSide:Int = readln().toInt()
var d20 = Dice(userSide)
print("\nPlease enter name:")
var userName:String = readln()
print("Please enter sides:")
var userSideDice2:Int = readln().toInt()
println("\nCreating $userName dice (a special sides $userSideDice2)...")
var percentile = Dice(userName, userSideDice2)
println("The current side up for " + default.getName()+" is "+ default.getSideIsUp())
println("The current side up for " + d20.getName() + " is " + d20.getSideIsUp())
println("The current side up for " + percentile.getName() + " is " + percentile.getSideIsUp())
println("\nTesting the roll method\n")
println("Rolling the " + default.getName() + "...")
println("The new value is " + default.getNewSide())
println("Rolling the " + d20.getName() + "...")
println("The new value is " + d20.getNewSide())
println("Rolling the " + percentile.getName() + "...")
println("The new value is " + percentile.getNewSide())
println("\nSetting the " + d20.getName() + " to show 20...")
d20.setSide()
println("The side up is now " + d20.getSideIsUp())
println("\nCreating 5 d6...")
var dice1 = Dice() //creating 5 default d6 dices
var dice2 = Dice()
var dice3 = Dice()
var dice4 = Dice()
var dice5 = Dice()
var attemp:Int = 0
var desiredSide:Int = 5
while (dice1.getNewSide() != desiredSide || //while to check the our desirable outcome i.e 5 of a kind
dice2.getNewSide() != desiredSide ||
dice3.getNewSide() != desiredSide ||
dice4.getNewSide() != desiredSide ||
dice5.getNewSide() != desiredSide
){
attemp++
}
println("YAHTZEE! It took $attemp rolls")
}
| 0
|
Kotlin
|
0
| 0
|
d73b7ec743ede7a78f881461fcedadfd54c3ca74
| 1,930
|
MAPD-LAB1-JVS
|
The Unlicense
|
src/main/kotlin/dev/mfazio/wc2022/types/db/MatchStatusDbModel.kt
|
MFazio23
| 519,368,317
| false
| null |
package dev.mfazio.wc2022.types.db
import dev.mfazio.wc2022.types.domain.MatchStatus
enum class MatchStatusDbModel {
Played,
ToBePlayed,
Live,
Abandoned,
Postponed,
Cancelled,
Forfeited,
LineUps,
Suspended,
Unknown;
fun toMatchStatus() = when(this) {
Played -> MatchStatus.Played
ToBePlayed -> MatchStatus.ToBePlayed
Live -> MatchStatus.Live
Abandoned -> MatchStatus.Abandoned
Postponed -> MatchStatus.Postponed
Cancelled -> MatchStatus.Cancelled
Forfeited -> MatchStatus.Forfeited
LineUps -> MatchStatus.LineUps
Suspended -> MatchStatus.Suspended
else -> MatchStatus.Unknown
}
companion object {
fun fromMatchStatus(matchStatus: MatchStatus) = when(matchStatus) {
MatchStatus.Played -> Played
MatchStatus.ToBePlayed -> ToBePlayed
MatchStatus.Live -> Live
MatchStatus.Abandoned -> Abandoned
MatchStatus.Postponed -> Postponed
MatchStatus.Cancelled -> Cancelled
MatchStatus.Forfeited -> Forfeited
MatchStatus.LineUps -> LineUps
MatchStatus.Suspended -> Suspended
else -> Unknown
}
}
}
| 8
|
Kotlin
|
1
| 4
|
cc6036580e2076bd65357a26486404e47c2fea25
| 1,260
|
wc2022-api
|
MIT License
|
app/src/main/java/com/lateinit/rightweight/ui/exercise/ExerciseFragment.kt
|
boostcampwm-2022
| 563,132,819
| false
|
{"Kotlin": 320392}
|
package com.lateinit.rightweight.ui.exercise
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.NavDeepLinkBuilder
import androidx.navigation.fragment.findNavController
import com.lateinit.rightweight.R
import com.lateinit.rightweight.databinding.FragmentExerciseBinding
import com.lateinit.rightweight.service.TimerService
import com.lateinit.rightweight.service.TimerService.Companion.IS_TIMER_RUNNING_INTENT_EXTRA
import com.lateinit.rightweight.service.TimerService.Companion.MANAGE_ACTION_NAME
import com.lateinit.rightweight.service.TimerService.Companion.PAUSE
import com.lateinit.rightweight.service.TimerService.Companion.PENDING_INTENT_TAG
import com.lateinit.rightweight.service.TimerService.Companion.SET_TIME_COUNT
import com.lateinit.rightweight.service.TimerService.Companion.START
import com.lateinit.rightweight.service.TimerService.Companion.STATUS
import com.lateinit.rightweight.service.TimerService.Companion.STATUS_ACTION_NAME
import com.lateinit.rightweight.service.TimerService.Companion.STOP
import com.lateinit.rightweight.service.TimerService.Companion.TIME_COUNT_INTENT_EXTRA
import com.lateinit.rightweight.ui.dialog.CommonDialogFragment
import com.lateinit.rightweight.ui.dialog.CommonDialogFragment.Companion.END_EXERCISE_DIALOG_TAG
import com.lateinit.rightweight.ui.model.history.HistoryExerciseSetUiModel
import com.lateinit.rightweight.ui.model.history.HistoryExerciseUiModel
import com.lateinit.rightweight.ui.model.routine.ExercisePartTypeUiModel
import com.lateinit.rightweight.util.collectOnLifecycle
import com.lateinit.rightweight.util.convertTimeStamp
import com.lateinit.rightweight.util.convertTimeStampToTimeCount
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ExerciseFragment : Fragment() {
private var _binding: FragmentExerciseBinding? = null
private val binding
get() = checkNotNull(_binding) { "binding was accessed outside of view lifecycle" }
private val viewModel: ExerciseViewModel by viewModels()
private lateinit var timerServiceIntent: Intent
private val dialog = CommonDialogFragment { endExercise() }
private lateinit var historyExerciseAdapter: HistoryExerciseAdapter
private var timeCount = 0
private var isTimerRunning = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startServiceWithDeeplink()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentExerciseBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHistoryExerciseAdapter()
setButtonClickListeners()
collectHistory()
handleNavigationEvent()
}
override fun onResume() {
super.onResume()
startTimerServiceWithMode(STATUS)
setBroadcastReceiver()
}
private fun startServiceWithDeeplink() {
val pendingIntent = NavDeepLinkBuilder(requireActivity())
.setGraph(R.navigation.nav_graph)
.setDestination(R.id.navigation_exercise)
.createPendingIntent()
timerServiceIntent = Intent(requireContext(), TimerService::class.java)
timerServiceIntent.putExtra(PENDING_INTENT_TAG, pendingIntent)
requireActivity().startService(timerServiceIntent)
timerServiceIntent.removeExtra(PENDING_INTENT_TAG)
}
private fun startTimerServiceWithMode(mode: String) {
timerServiceIntent.putExtra(MANAGE_ACTION_NAME, mode)
requireActivity().startService(timerServiceIntent)
timerServiceIntent.removeExtra(MANAGE_ACTION_NAME)
}
private fun setBroadcastReceiver() {
val intentFilter = IntentFilter().apply {
addAction(STATUS_ACTION_NAME)
}
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
isTimerRunning = intent.getBooleanExtra(IS_TIMER_RUNNING_INTENT_EXTRA, false)
timeCount = intent.getIntExtra(TIME_COUNT_INTENT_EXTRA, 0)
updateViews()
}
}
}
requireActivity().registerReceiver(receiver, intentFilter)
}
private fun updateViews() {
_binding ?: return
binding.timeString = convertTimeStamp(timeCount)
binding.isTimerRunning = isTimerRunning
}
private fun setButtonClickListeners() {
binding.buttonExerciseStartAndPause.setOnClickListener {
if (isTimerRunning) {
startTimerServiceWithMode(PAUSE)
} else {
startTimerServiceWithMode(START)
}
}
binding.buttonExerciseAdd.setOnClickListener {
viewModel.addHistoryExercise()
}
binding.buttonExerciseEnd.setOnClickListener {
if (viewModel.isAllHistorySetsChecked.not() && dialog.isAdded.not()) {
dialog.show(
parentFragmentManager,
END_EXERCISE_DIALOG_TAG, R.string.end_exercise_message
)
} else {
endExercise()
}
}
}
private fun setHistoryExerciseAdapter() {
val exerciseParts = ExercisePartTypeUiModel.values().map { exercisePart ->
getString(exercisePart.partName)
}
val exercisePartAdapter =
ArrayAdapter(requireContext(), R.layout.item_exercise_part, exerciseParts)
val historyEventListener = object : HistoryEventListener {
override fun addHistorySet(historyExerciseId: String) {
viewModel.addHistorySet(historyExerciseId)
}
override fun updateHistorySet(historyExerciseSetUiModel: HistoryExerciseSetUiModel) {
viewModel.updateHistorySet(historyExerciseSetUiModel)
}
override fun updateHistoryExercise(historyExerciseUiModel: HistoryExerciseUiModel) {
viewModel.updateHistoryExercise(historyExerciseUiModel)
}
override fun removeHistorySet(historySetId: String) {
viewModel.removeHistorySet(historySetId)
}
override fun removeHistoryExercise(historyExerciseId: String) {
viewModel.removeHistoryExercise(historyExerciseId)
}
}
historyExerciseAdapter = HistoryExerciseAdapter(exercisePartAdapter, historyEventListener)
binding.recyclerViewHistory.apply {
adapter = historyExerciseAdapter
itemAnimator = null
}
}
private fun collectHistory() {
viewLifecycleOwner.collectOnLifecycle {
viewModel.historyUiModel.collect {
it ?: return@collect
sendSavedTimeCountToService(convertTimeStampToTimeCount(it.time))
historyExerciseAdapter.submitList(it.exercises)
}
}
}
private fun sendSavedTimeCountToService(timeCount: Int) {
timerServiceIntent.putExtra(SET_TIME_COUNT, timeCount)
requireActivity().startService(timerServiceIntent)
timerServiceIntent.removeExtra(SET_TIME_COUNT)
startTimerServiceWithMode(STATUS)
}
private fun handleNavigationEvent() {
viewLifecycleOwner.collectOnLifecycle {
viewModel.navigationEvent.collect {
findNavController().navigateUp()
}
}
}
private fun endExercise() {
viewModel.endExercise(binding.timeString ?: "")
startTimerServiceWithMode(STOP)
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
}
| 8
|
Kotlin
|
0
| 27
|
ff6116ee9e49bd8ed493d3c6928d0b9a7f892689
| 8,264
|
android09-RightWeight
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/neptune/CfnDBInstancePropsDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.neptune
import cloudshift.awscdk.common.CdkDslMarker
import cloudshift.awscdk.dsl.CfnTagDsl
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.neptune.CfnDBInstanceProps
/**
* Properties for defining a `CfnDBInstance`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.neptune.*;
* CfnDBInstanceProps cfnDBInstanceProps = CfnDBInstanceProps.builder()
* .dbInstanceClass("dbInstanceClass")
* // the properties below are optional
* .allowMajorVersionUpgrade(false)
* .autoMinorVersionUpgrade(false)
* .availabilityZone("availabilityZone")
* .dbClusterIdentifier("dbClusterIdentifier")
* .dbInstanceIdentifier("dbInstanceIdentifier")
* .dbParameterGroupName("dbParameterGroupName")
* .dbSnapshotIdentifier("dbSnapshotIdentifier")
* .dbSubnetGroupName("dbSubnetGroupName")
* .preferredMaintenanceWindow("preferredMaintenanceWindow")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-neptune-dbinstance.html)
*/
@CdkDslMarker
public class CfnDBInstancePropsDsl {
private val cdkBuilder: CfnDBInstanceProps.Builder = CfnDBInstanceProps.builder()
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* @param allowMajorVersionUpgrade Indicates that major version upgrades are allowed.
* Changing this parameter doesn't result in an outage and the change is asynchronously applied as
* soon as possible. This parameter must be set to true when specifying a value for the EngineVersion
* parameter that is a different major version than the DB instance's current version.
*
* When you change this parameter for an existing DB cluster, CloudFormation will replace your
* existing DB cluster with a new, empty one that uses the engine version you specified.
*/
public fun allowMajorVersionUpgrade(allowMajorVersionUpgrade: Boolean) {
cdkBuilder.allowMajorVersionUpgrade(allowMajorVersionUpgrade)
}
/**
* @param allowMajorVersionUpgrade Indicates that major version upgrades are allowed.
* Changing this parameter doesn't result in an outage and the change is asynchronously applied as
* soon as possible. This parameter must be set to true when specifying a value for the EngineVersion
* parameter that is a different major version than the DB instance's current version.
*
* When you change this parameter for an existing DB cluster, CloudFormation will replace your
* existing DB cluster with a new, empty one that uses the engine version you specified.
*/
public fun allowMajorVersionUpgrade(allowMajorVersionUpgrade: IResolvable) {
cdkBuilder.allowMajorVersionUpgrade(allowMajorVersionUpgrade)
}
/**
* @param autoMinorVersionUpgrade Indicates that minor version patches are applied automatically.
* When updating this property, some interruptions may occur.
*/
public fun autoMinorVersionUpgrade(autoMinorVersionUpgrade: Boolean) {
cdkBuilder.autoMinorVersionUpgrade(autoMinorVersionUpgrade)
}
/**
* @param autoMinorVersionUpgrade Indicates that minor version patches are applied automatically.
* When updating this property, some interruptions may occur.
*/
public fun autoMinorVersionUpgrade(autoMinorVersionUpgrade: IResolvable) {
cdkBuilder.autoMinorVersionUpgrade(autoMinorVersionUpgrade)
}
/**
* @param availabilityZone Specifies the name of the Availability Zone the DB instance is located
* in.
*/
public fun availabilityZone(availabilityZone: String) {
cdkBuilder.availabilityZone(availabilityZone)
}
/**
* @param dbClusterIdentifier If the DB instance is a member of a DB cluster, contains the name of
* the DB cluster that the DB instance is a member of.
*/
public fun dbClusterIdentifier(dbClusterIdentifier: String) {
cdkBuilder.dbClusterIdentifier(dbClusterIdentifier)
}
/**
* @param dbInstanceClass Contains the name of the compute and memory capacity class of the DB
* instance.
* If you update this property, some interruptions may occur.
*/
public fun dbInstanceClass(dbInstanceClass: String) {
cdkBuilder.dbInstanceClass(dbInstanceClass)
}
/**
* @param dbInstanceIdentifier Contains a user-supplied database identifier.
* This identifier is the unique key that identifies a DB instance.
*/
public fun dbInstanceIdentifier(dbInstanceIdentifier: String) {
cdkBuilder.dbInstanceIdentifier(dbInstanceIdentifier)
}
/**
* @param dbParameterGroupName The name of an existing DB parameter group or a reference to an
* AWS::Neptune::DBParameterGroup resource created in the template.
* If any of the data members of the referenced parameter group are changed during an update, the
* DB instance might need to be restarted, which causes some interruption. If the parameter group
* contains static parameters, whether they were changed or not, an update triggers a reboot.
*/
public fun dbParameterGroupName(dbParameterGroupName: String) {
cdkBuilder.dbParameterGroupName(dbParameterGroupName)
}
/**
* @param dbSnapshotIdentifier This parameter is not supported.
* `AWS::Neptune::DBInstance` does not support restoring from snapshots.
*
* `AWS::Neptune::DBCluster` does support restoring from snapshots.
*/
public fun dbSnapshotIdentifier(dbSnapshotIdentifier: String) {
cdkBuilder.dbSnapshotIdentifier(dbSnapshotIdentifier)
}
/**
* @param dbSubnetGroupName A DB subnet group to associate with the DB instance.
* If you update this value, the new subnet group must be a subnet group in a new virtual private
* cloud (VPC).
*/
public fun dbSubnetGroupName(dbSubnetGroupName: String) {
cdkBuilder.dbSubnetGroupName(dbSubnetGroupName)
}
/**
* @param preferredMaintenanceWindow Specifies the weekly time range during which system
* maintenance can occur, in Universal Coordinated Time (UTC).
*/
public fun preferredMaintenanceWindow(preferredMaintenanceWindow: String) {
cdkBuilder.preferredMaintenanceWindow(preferredMaintenanceWindow)
}
/**
* @param tags An arbitrary set of tags (key-value pairs) for this DB instance.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* @param tags An arbitrary set of tags (key-value pairs) for this DB instance.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
public fun build(): CfnDBInstanceProps {
if(_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 7,159
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/tool/xfy9326/milink/nfc/activity/XiaomiNfcReaderActivity.kt
|
XFY9326
| 724,531,401
| false
|
{"Kotlin": 275449}
|
package tool.xfy9326.milink.nfc.activity
import android.nfc.NfcAdapter
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import tool.xfy9326.milink.nfc.R
import tool.xfy9326.milink.nfc.data.NdefReadData
import tool.xfy9326.milink.nfc.ui.screen.XiaomiNfcReaderScreen
import tool.xfy9326.milink.nfc.ui.theme.AppTheme
import tool.xfy9326.milink.nfc.ui.vm.XiaomiNfcReaderViewModel
import tool.xfy9326.milink.nfc.utils.MIME_ALL
import tool.xfy9326.milink.nfc.utils.enableNdefReaderMode
import tool.xfy9326.milink.nfc.utils.ignoreTagUntilRemoved
import tool.xfy9326.milink.nfc.utils.isNullOrEmpty
import tool.xfy9326.milink.nfc.utils.showToast
import tool.xfy9326.milink.nfc.utils.tryConnect
class XiaomiNfcReaderActivity : ComponentActivity() {
private val viewModel by viewModels<XiaomiNfcReaderViewModel>()
private val exportNdefBin =
registerForActivityResult(ActivityResultContracts.CreateDocument(MIME_ALL)) {
if (it == null) {
showToast(getString(R.string.export_canceled))
} else {
viewModel.exportNdefBin(it)
}
}
private val importNdefBin = registerForActivityResult(ActivityResultContracts.GetContent()) {
if (it == null) {
showToast(getString(R.string.import_canceled))
} else {
viewModel.updateNfcReadData(it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
AppTheme {
XiaomiNfcReaderScreen(
onNavBack = {
onBackPressedDispatcher.onBackPressed()
},
onRequestImportNdefBin = {
importNdefBin.launch(MIME_ALL)
}
)
}
}
observeViewModel()
}
private fun observeViewModel() {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.exportNdefBin.collect {
exportNdefBin.launch(it)
}
}
}
}
private fun makeToast(msg: String): Unit = runOnUiThread { showToast(msg) }
override fun onResume() {
super.onResume()
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
nfcAdapter?.let { adapter ->
adapter.enableNdefReaderMode(this) {
val ndef = Ndef.get(it)
if (ndef != null) {
lifecycleScope.launch(Dispatchers.IO) {
readNdef(adapter, ndef)
}
} else {
if (NdefFormatable.get(it) != null) {
makeToast(getString(R.string.nfc_ndef_formatable))
} else {
makeToast(getString(R.string.nfc_not_ndef))
}
viewModel.clearNfcReadData()
}
}
}
}
override fun onPause() {
NfcAdapter.getDefaultAdapter(this)?.disableReaderMode(this)
super.onPause()
}
private suspend fun readNdef(nfcAdapter: NfcAdapter, ndef: Ndef) = withContext(Dispatchers.IO) {
ndef.tryConnect().onSuccess {
try {
val msg = it.ndefMessage
if (msg.isNullOrEmpty()) {
makeToast(getString(R.string.nfc_empty))
} else {
NdefReadData(
scanTime = System.currentTimeMillis(),
techList = it.tag.techList.map { str -> str.substringAfterLast(".") },
type = it.type,
msg = msg,
maxSize = it.maxSize,
writeable = it.isWritable,
canMakeReadOnly = it.canMakeReadOnly()
).also { data ->
viewModel.updateNfcReadData(data)
}
}
} catch (e: Exception) {
makeToast(getString(R.string.nfc_read_failed))
viewModel.clearNfcReadData()
}
nfcAdapter.ignoreTagUntilRemoved(ndef.tag)
}.onFailure {
makeToast(getString(R.string.nfc_connect_failed))
viewModel.clearNfcReadData()
}
}
}
| 0
|
Kotlin
|
5
| 7
|
40e127ff5a078bd0b8a3697584f4f5fa90722d72
| 4,911
|
MiLinkNFC
|
MIT License
|
ocpp-2-0-json/src/main/kotlin/com/izivia/ocpp/json20/Ocpp20JsonObjectMapper.kt
|
IZIVIA
| 501,708,979
| false
|
{"Kotlin": 1934096}
|
package com.izivia.ocpp.json20
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonValue
import com.fasterxml.jackson.databind.ObjectMapper
import com.izivia.ocpp.core20.model.common.enumeration.MeasurandEnumType
import com.izivia.ocpp.core20.model.common.enumeration.ReadingContextEnumType
import com.izivia.ocpp.core20.model.notifycustomerinformation.NotifyCustomerInformationReq
import com.izivia.ocpp.core20.model.notifyevent.NotifyEventReq
import com.izivia.ocpp.core20.model.notifymonitoringreport.NotifyMonitoringReportReq
import com.izivia.ocpp.core20.model.notifyreport.NotifyReportReq
import com.izivia.ocpp.core20.model.notifyreport.enumeration.DataEnumType
import com.izivia.ocpp.json.OcppJsonMapper
internal object Ocpp20JsonObjectMapper : ObjectMapper(
OcppJsonMapper()
.addMixIn(MeasurandEnumType::class.java, EnumMixin::class.java)
.addMixIn(ReadingContextEnumType::class.java, EnumMixin::class.java)
.addMixIn(DataEnumType::class.java, EnumMixin::class.java)
.addMixIn(NotifyCustomerInformationReq::class.java, HasActionTimestampMixin::class.java)
.addMixIn(NotifyEventReq::class.java, HasActionTimestampMixin::class.java)
.addMixIn(NotifyReportReq::class.java, HasActionTimestampMixin::class.java)
.addMixIn(NotifyMonitoringReportReq::class.java, HasActionTimestampMixin::class.java)
)
private abstract class EnumMixin(
@JsonValue val value: String
)
@JsonIgnoreProperties(value = ["timestamp"])
private abstract class HasActionTimestampMixin
| 7
|
Kotlin
|
7
| 32
|
bd8e7334ae05ea75d02d96a508269acbe076bcd8
| 1,581
|
ocpp-toolkit
|
MIT License
|
src/main/kotlin/dev/moetz/buzzer/template/SiteTemplate.kt
|
FlowMo7
| 443,932,157
| false
|
{"Kotlin": 65212, "JavaScript": 23988, "CSS": 2229, "Dockerfile": 247}
|
package dev.moetz.buzzer.template
import io.ktor.html.*
import kotlinx.html.*
class SiteTemplate(
private val siteTitle: String,
private val description: String = "Online buzzing system for party games.",
private val formButtonColor: String,
private val buzzerButtonColorReady: String,
private val buzzerButtonColorBuzzed: String,
private val path: String,
) : Template<HTML> {
val content = Placeholder<FlowContent>()
val footerContent = Placeholder<FlowContent>()
val additionalHeadStuff = Placeholder<HEAD>()
override fun HTML.apply() {
comment(" This service is open sourced at https://github.com/FlowMo7/kotlin-buzzer. ")
head {
meta(charset = "utf-8")
title { +siteTitle }
script(type = "text/javascript", src = "${path}js/reconnecting-websocket.min.js") {
}
script(type = "text/javascript", src = "${path}js/websocket.js") {
}
script(type = "text/javascript", src = "${path}js/script.js") {
}
style {
unsafe {
+":root {"
+"--button-color: $formButtonColor;"
+"--button-buzzer-ready: $buzzerButtonColorReady;"
+"--button-buzzer-buzzed: $buzzerButtonColorBuzzed;"
+"}"
}
}
link(href = "${path}style/styles.css", rel = "stylesheet", type = "text/css")
meta(name = "robots", content = "index, follow")
meta(name = "og:title", content = siteTitle)
meta(name = "description", content = description)
meta(name = "keywords", content = "buzzer,buzzing,online,party game")
meta(name = "viewport", content = "width=device-width, initial-scale=1.0")
link(href = "${path}icon/apple-touch-icon.png", rel = "apple-touch-icon") { sizes = "180x180" }
link(href = "${path}icon/favicon-32x32.png", type = "image/png", rel = "icon") { sizes = "32x32" }
link(href = "${path}icon/favicon-16x16.png", type = "image/png", rel = "icon") { sizes = "16x16" }
link(href = "${path}site.webmanifest", rel = "manifest")
insert(additionalHeadStuff)
}
body {
main {
insert(content)
}
footer {
insert(footerContent)
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
bad81b716b64c1760227ed3a13ff74a8f635c9cc
| 2,459
|
kotlin-buzzer
|
Apache License 2.0
|
server/src/main/kotlin/net/horizonsend/ion/server/features/multiblock/misc/ShipFactoryMultiblock.kt
|
HorizonsEndMC
| 461,042,096
| false
| null |
package net.horizonsend.ion.server.features.multiblock.type.misc
import net.horizonsend.ion.server.features.multiblock.Multiblock
import net.horizonsend.ion.server.features.multiblock.MultiblockShape
import net.horizonsend.ion.server.features.multiblock.type.InteractableMultiblock
import net.horizonsend.ion.server.features.multiblock.type.PowerStoringMultiblock
import net.horizonsend.ion.server.features.starship.factory.StarshipFactories
import net.horizonsend.ion.server.miscellaneous.utils.Tasks
import net.horizonsend.ion.server.miscellaneous.utils.getFacing
import net.horizonsend.ion.server.miscellaneous.utils.rightFace
import org.bukkit.block.Sign
import org.bukkit.entity.Player
import org.bukkit.event.block.Action
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
object ShipFactoryMultiblock : Multiblock(), PowerStoringMultiblock, InteractableMultiblock {
override val name = "shipfactory"
override val signText = createSignText(
line1 = "&1Ship Factory",
line2 = null,
line3 = null,
line4 = null
)
override val maxPower: Int = 1_000_000
override fun onTransformSign(player: Player, sign: Sign) {
sign.setLine(2, sign.getLine(1))
sign.setLine(1, player.uniqueId.toString())
}
override fun MultiblockShape.buildStructure() {
z(+0) {
y(-1) {
x(+0).ironBlock()
x(+1).ironBlock()
}
y(+0) {
x(+0).furnace()
x(+1).anyPipedInventory()
}
}
}
fun getStorage(sign: Sign): Inventory {
val direction = sign.getFacing().oppositeFace
return (sign.block.getRelative(direction).getRelative(direction.rightFace).state as InventoryHolder).inventory
}
override fun onSignInteract(sign: Sign, player: Player, event: PlayerInteractEvent) {
val leftClick = event.action == Action.LEFT_CLICK_BLOCK && event.player.hasPermission("starlegacy.factory.print.credit")
Tasks.async {
StarshipFactories.process(event.player, sign, leftClick)
}
}
}
| 25
| null |
36
| 9
|
4c52c237f9ebd4a5bf67b8721a9eb10bb6ff3bdc
| 1,995
|
Ion
|
MIT License
|
src/test/kotlin/no/nav/sokos/prosjektnavn/ApplicationTest.kt
|
navikt
| 509,000,535
| false
| null |
package no.nav.sokos.prosjektnavn
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class ApplicationTest : FunSpec ({
test("my first test") {
1 + 2 shouldBe 3
}
})
| 0
|
Kotlin
|
0
| 0
|
58a88c5c2cd19c98aebfdbac79d14afd02f780d4
| 212
|
sokos-ktor-template
|
MIT License
|
app/src/main/java/id/rllyhz/dicodingsubmissionbfaa/ui/activity/settings/SettingsActivity.kt
|
rllyhz
| 355,088,778
| false
| null |
package id.rllyhz.dicodingsubmissionbfaa.ui.activity.settings
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import id.rllyhz.dicodingsubmissionbfaa.R
import id.rllyhz.dicodingsubmissionbfaa.data.pref.ReminderPref
import id.rllyhz.dicodingsubmissionbfaa.databinding.ActivitySettingsBinding
import id.rllyhz.dicodingsubmissionbfaa.ui.feature.picker.TimePickerFragment
import id.rllyhz.dicodingsubmissionbfaa.ui.receiver.AlarmReceiver
import java.text.SimpleDateFormat
import java.util.*
class SettingsActivity : AppCompatActivity(), TimePickerFragment.DialogTimeListener {
private lateinit var binding: ActivitySettingsBinding
private lateinit var alarmReceiver: AlarmReceiver
private lateinit var reminderPref: ReminderPref
private lateinit var nameUserActive: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(binding.root)
// this must be from user that being active.
// but, in this app, it's just dummy data
nameUserActive = resources.getString(R.string.settings_user_dummy)
setupActionBar()
setupUI()
}
private fun setupUI() {
alarmReceiver = AlarmReceiver()
reminderPref = ReminderPref(this)
binding.apply {
tvSettingsLanguageDisplay.text = Locale.getDefault().displayLanguage
tvSettingsLanguageDisplay.setOnClickListener {
startActivity(
Intent(Settings.ACTION_LOCALE_SETTINGS)
)
}
switchSettingsReminder.isChecked = reminderPref.isAlarmAlreadySet()
switchSettingsReminder.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
val time = binding.tvSettingsTimeReminder.text.toString()
alarmReceiver.setRepeatingAlarm(
this@SettingsActivity,
time,
resources.getString(R.string.settings_reminder_message, nameUserActive)
)
} else {
alarmReceiver.setOffRepeatingAlarm(this@SettingsActivity)
}
}
tvSettingsTimeReminder.text = reminderPref.getTimeOfActiveReminder()
tvSettingsTimeReminder.setOnClickListener {
changeTimeReminder()
}
tvSettingsTimeReminderLabel.setOnClickListener {
changeTimeReminder()
}
}
}
private fun changeTimeReminder() {
TimePickerFragment().show(supportFragmentManager, TIME_PICKER_TAG)
}
private fun setupActionBar() {
supportActionBar?.apply {
title = getString(R.string.action_bar_title_settings)
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(R.drawable.ic_arrow_left)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onDialogTimeSet(tag: String?, hourOfDay: Int, minute: Int) {
val calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hourOfDay)
set(Calendar.MINUTE, minute)
}
val dateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
binding.tvSettingsTimeReminder.text = dateFormat.format(calendar.time)
}
companion object {
private const val TIME_PICKER_TAG = "TimePickerOnce"
}
}
| 0
|
Kotlin
|
0
| 0
|
ac3d77f3c885603c71f5ccc78b5739e957d6a0d9
| 3,839
|
bfaa-final-submission
|
Apache License 2.0
|
sample/src/main/kotlin/app/futured/donutsample/tools/extensions/ViewExtensions.kt
|
futuredapp
| 215,500,960
| false
|
{"Kotlin": 40474, "Ruby": 1068}
|
package com.softcross.onepiece.core.common.extension
import android.view.View
fun View.visible() {
visibility = View.VISIBLE
}
fun View.gone() {
visibility = View.GONE
}
| 7
|
Kotlin
|
46
| 546
|
2650b27972f6b819a0ac197094f49c0a6fc9470f
| 181
|
donut
|
MIT License
|
src/main/kotlin/no/nav/tiltakspenger/fp/abakusclient/models/Person.kt
|
navikt
| 571,962,480
| false
|
{"Kotlin": 40640, "Shell": 1093, "Dockerfile": 504}
|
package no.nav.tiltakspenger.fp.abakusclient.models
data class Person(
val identType: String = "FNR",
val ident: String
)
| 1
|
Kotlin
|
1
| 1
|
6d8265c22a013708aba80d534857545c4868963d
| 131
|
tiltakspenger-fp
|
MIT License
|
src/main/kotlin/com/igorivkin/website/controller/api/MarkdownController.kt
|
IgorIvkin
| 341,263,198
| false
| null |
package com.igorivkin.website.controller.api
import com.igorivkin.website.controller.dto.markdown.MarkdownRequest
import com.igorivkin.website.controller.dto.markdown.MarkdownResponse
import com.igorivkin.website.service.MarkdownParserService
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
@RestController
class MarkdownController(
private val markdownParserService: MarkdownParserService
) {
@PostMapping(
value = ["/api/markdown/"],
consumes = [MediaType.APPLICATION_JSON_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE]
)
fun generateHtmlFromMarkDown(@RequestBody body: MarkdownRequest): ResponseEntity<MarkdownResponse> {
val response = MarkdownResponse(content = markdownParserService.parse(body.content))
return ResponseEntity.ok(response)
}
}
| 0
|
Kotlin
|
0
| 1
|
71d78154621ac9c1ce4cddb86d385af898c89ae8
| 1,038
|
igor-ivkin-website-kotlin
|
Apache License 2.0
|
kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/extensions/MountableExtensionTest.kt
|
kotest
| 47,071,082
| false
| null |
package com.sksamuel.kotest.engine.extensions
import io.kotest.core.extensions.MountableExtension
import io.kotest.core.extensions.install
import io.kotest.core.listeners.BeforeSpecListener
import io.kotest.core.spec.Spec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import java.util.concurrent.atomic.AtomicBoolean
class MountableExtensionTest : FunSpec() {
private val mountable = MyMountable()
private val control = install(mountable) {
a = "bar"
}
init {
test("mountable extensions should invoke configuration block") {
control.a shouldBe "bar"
}
test("mountable extensions should be installed as regular extensions") {
mountable.before.get() shouldBe true
}
}
}
data class Config(var a: String)
class MyMountable : MountableExtension<Config, Config>, BeforeSpecListener {
override val name: String = "MyMountable"
val before = AtomicBoolean(false)
override suspend fun beforeSpec(spec: Spec) {
before.set(true)
}
override fun mount(configure: (Config) -> Unit): Config {
val config = Config("foo")
configure(config)
return config
}
}
| 160
| null |
648
| 4,435
|
2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f
| 1,185
|
kotest
|
Apache License 2.0
|
AdventureXplore/app/src/main/java/com/example/adventerlife/Activity/AdaminActivity.kt
|
Puravish08
| 698,056,809
| false
|
{"Kotlin": 121016}
|
package com.example.adventerlife.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.adventerlife.ModelClass.HomeModel
import com.example.adventerlife.databinding.ActivityAdaminBinding
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import java.util.UUID
class AdaminActivity : AppCompatActivity() {
lateinit var binding: ActivityAdaminBinding
private val PICK_IMAGE_REQUEST = 100
lateinit var uri: Uri
lateinit var ImageUri: Uri
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAdaminBinding.inflate(layoutInflater)
setContentView(binding.root)
initview()
}
private fun initview() {
var reference = FirebaseDatabase.getInstance().reference
binding.btnselectimag.setOnClickListener {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(
Intent.createChooser(
intent,
"Select Image from here..."
),
PICK_IMAGE_REQUEST
)
binding.BtnAdd.setOnClickListener {
var palce = binding.edtPlace.text.toString()
var city = binding.edtCity.text.toString()
var phonenumber = binding.edtnumber.text.toString()
var email = binding.edtemail.text.toString()
var price = binding.edtprice.text.toString()
var Discription = binding.edtdescription.text.toString()
var Rating = binding.edtrate.text.toString()
var Day=binding.edtDay.text.toString()
var Favourite=binding.edtFavourite.text.toString()
var key = reference.root.child("AdminTb").push().key ?: ""
var modelClass = HomeModel(
palce,
email,
phonenumber,
Discription,
city,
price,
Rating,
Day,
Favourite,
key, ImageUri
)
reference.root.child("AllDataTb").child(key).setValue(modelClass)
.addOnCompleteListener {
if (it.isSuccessful) {
Toast.makeText(this, "Data Added Successful", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener { Log.e("TAG", "Error: " + it) }
}
}
}
fun uploadImage() {
if (uri != null) {
// Code for showing progressDialog while uploading
val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Uploading...")
progressDialog.show()
// Defining the child of storageReference
val ref: StorageReference = FirebaseStorage.getInstance().getReference()
.child("images/" + UUID.randomUUID().toString())
// adding listeners on upload
// or failure of image
if (ref != null) {
ref.putFile(uri).continueWith {
ref.downloadUrl.addOnCompleteListener {
ImageUri = it.result
}
}
.addOnSuccessListener { // Image uploaded successfully
// Dismiss dialog
progressDialog.dismiss()
Toast
.makeText(
this@AdaminActivity,
"Image Uploaded!!",
Toast.LENGTH_SHORT
)
.show()
}
.addOnFailureListener { e -> // Error, Image not uploaded
progressDialog.dismiss()
Toast
.makeText(
this@AdaminActivity,
"Failed " + e.message,
Toast.LENGTH_SHORT
)
.show()
}
}
}
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(
requestCode,
resultCode,
data
)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == AppCompatActivity.RESULT_OK && data != null && data.data != null) {
// Get the Uri of data
uri = data.data!!
uploadImage()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
097ec8cf2f543d619b01a21e4cee36d82b6d4d45
| 5,114
|
AdavantureLife
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsauditapi/services/AuditService.kt
|
ministryofjustice
| 340,068,469
| false
|
{"Kotlin": 160437, "Mustache": 1803, "Dockerfile": 1319}
|
package uk.gov.justice.digital.hmpps.hmppsauditapi.services
import com.microsoft.applicationinsights.TelemetryClient
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.domain.Sort.Direction.DESC
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.hmppsauditapi.config.trackEvent
import uk.gov.justice.digital.hmpps.hmppsauditapi.jpa.AuditRepository
import uk.gov.justice.digital.hmpps.hmppsauditapi.listeners.HMPPSAuditListener.AuditEvent
import uk.gov.justice.digital.hmpps.hmppsauditapi.model.AuditFilterDto
import uk.gov.justice.digital.hmpps.hmppsauditapi.resource.AuditDto
import java.util.UUID
@Service
class AuditService(
private val telemetryClient: TelemetryClient,
private val auditRepository: AuditRepository,
private val auditS3Client: AuditS3Client,
@Value("\${hmpps.repository.saveToS3Bucket}") private val saveToS3Bucket: Boolean,
) {
private companion object {
private val log = LoggerFactory.getLogger(this::class.java)
}
fun audit(auditEvent: AuditEvent) {
telemetryClient.trackEvent("hmpps-audit", auditEvent.asMap())
if (saveToS3Bucket) {
auditEvent.id = UUID.randomUUID()
auditS3Client.save(auditEvent)
} else {
auditRepository.save(auditEvent)
}
}
fun findAll(): List<AuditDto> = auditRepository.findAll(Sort.by(DESC, "when")).map { AuditDto(it) }
fun findPage(
pageable: Pageable = Pageable.unpaged(),
auditFilterDto: AuditFilterDto,
): Page<AuditDto> {
with(auditFilterDto) {
log.info(
"Searching audit events by startDate {} endDate {} service {} subjectId {} subjectType {} correlationId {} what {} who {}",
startDateTime,
endDateTime,
service,
subjectId,
subjectType,
correlationId,
what,
who,
)
return auditRepository.findPage(
pageable,
startDateTime,
endDateTime,
service,
subjectId,
subjectType,
correlationId,
what,
who,
)
.map { AuditDto(it) }
}
}
}
private fun AuditEvent.asMap(): Map<String, String> {
val items = mutableMapOf("what" to what, "when" to `when`.toString())
items.addIfNotNull("who", who)
items.addIfNotNull("operationId", operationId)
items.addIfNotNull("subjectId", subjectId)
items.addIfNotNull("subjectType", subjectType)
items.addIfNotNull("correlationId", correlationId)
items.addIfNotNull("service", service)
return items.toMap()
}
| 0
|
Kotlin
|
2
| 0
|
3276f5855e598dd66790de6e6bdda9783e07ac55
| 2,700
|
hmpps-audit-api
|
MIT License
|
incubator.clients.kroviz/src/main/kotlin/org/apache/isis/client/kroviz/core/event/EventStore.kt
|
joerg-rade
| 163,651,410
| false
| null |
package org.apache.isis.client.kroviz.core.event
import org.apache.isis.client.kroviz.core.aggregator.BaseAggregator
import org.apache.isis.client.kroviz.to.TObject
import org.apache.isis.client.kroviz.to.mb.Menubars
import org.apache.isis.client.kroviz.ui.kv.UiManager
import pl.treksoft.kvision.panel.SimplePanel
import pl.treksoft.kvision.state.observableListOf
/**
* Keeps a log of remote invocations and the responses.
* Subsequent invocations are served from this cache.
* UI events (Dialogs, Windows, etc.) are logged here as well.
*
* @see "https://en.wikipedia.org/wiki/Proxy_pattern"
* @see "https://martinfowler.com/eaaDev/EventSourcing.html"
*/
object EventStore {
var log = observableListOf<LogEntry>()
private var logStartTime: Int = 0
private fun log(logEntry: LogEntry) {
log.add(logEntry)
if (log.size == 1) {
logStartTime = logEntry.createdAt.getMilliseconds()
}
}
fun start(reSpec: ResourceSpecification,
method: String,
body: String = "",
aggregator: BaseAggregator? = null): LogEntry {
val entry = LogEntry(reSpec.url, method, request = body, subType = reSpec.subType)
if (aggregator != null) {
entry.addAggregator(aggregator)
}
log(entry)
updateStatus(entry)
return entry
}
fun add(reSpec: ResourceSpecification) {
val entry = LogEntry(url = reSpec.url)
log(entry)
updateStatus(entry)
}
fun addView(title: String, aggregator: BaseAggregator, panel: SimplePanel) {
val entry = LogEntry(title = title, aggregator = aggregator)
entry.obj = panel
log(entry)
updateStatus(entry)
}
fun closeView(title: String) {
val logEntry = findView(title)
if (null != logEntry) {
logEntry.setClose()
logEntry.getAggregator()!!.reset()
updateStatus(logEntry)
}
}
fun end(reSpec: ResourceSpecification, response: String): LogEntry? {
val entry: LogEntry? = find(reSpec)
if (entry != null) {
entry.response = response
entry.setSuccess()
updateStatus(entry)
}
return entry
}
fun fault(reSpec: ResourceSpecification, fault: String) {
val entry: LogEntry? = find(reSpec)
entry!!.setError(fault)
updateStatus(entry)
}
fun cached(reSpec: ResourceSpecification): LogEntry {
val entry: LogEntry? = find(reSpec)
entry!!.setCached()
return entry
}
private fun updateStatus(entry: LogEntry) {
UiManager.updateStatus(entry)
}
/**
* Answers the first matching entry.
*/
fun find(reSpec: ResourceSpecification): LogEntry? {
return if (reSpec.isRedundant()) {
findEquivalent(reSpec)
} else {
findExact(reSpec)
}
}
fun find(tObject: TObject): LogEntry? {
log.forEach {
val obj = it.obj
if (obj is TObject
&& obj.instanceId == tObject.instanceId)
return it
}
return null
}
fun findBy(aggregator: BaseAggregator): LogEntry? {
return log.firstOrNull { it.getAggregator() == aggregator }
}
fun findMenuBars(): LogEntry? {
this.log.forEach {
if (it.obj is Menubars)
return it
}
return null
}
internal fun findExact(reSpec: ResourceSpecification): LogEntry? {
return log.firstOrNull { it.matches(reSpec) }
}
internal fun findView(title: String): LogEntry? {
return log.firstOrNull { it.title == title && it.isView() }
}
internal fun findEquivalent(reSpec: ResourceSpecification): LogEntry? {
return log.firstOrNull { reSpec.matches(it) }
}
fun isCached(reSpec: ResourceSpecification, method: String): Boolean {
val le = find(reSpec)
return when {
le == null -> false
le.hasResponse() && le.method == method && le.subType == reSpec.subType -> true
le.isView() -> true
else -> false
}
}
fun reset() {
log.removeAll(log)
}
}
| 20
| null |
1
| 10
|
07e7ed9aa6dabc7e8a9a0100451d89ae18e46950
| 4,270
|
kroviz
|
Apache License 2.0
|
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/okonomi/models/RefusjonskravDto.kt
|
navikt
| 435,813,834
| false
|
{"Kotlin": 1627414, "TypeScript": 1445375, "SCSS": 41073, "JavaScript": 27458, "PLpgSQL": 14591, "Handlebars": 3189, "HTML": 2263, "Dockerfile": 1423, "CSS": 1145, "Shell": 396}
|
package no.nav.mulighetsrommet.api.okonomi.models
import kotlinx.serialization.Serializable
import no.nav.mulighetsrommet.domain.serializers.UUIDSerializer
import java.util.*
@Serializable
data class RefusjonskravDto(
@Serializable(with = UUIDSerializer::class)
val id: UUID,
val tiltakstype: Tiltakstype,
val gjennomforing: Gjennomforing,
val arrangor: Arrangor,
val beregning: RefusjonKravBeregning,
) {
@Serializable
data class Gjennomforing(
@Serializable(with = UUIDSerializer::class)
val id: UUID,
val navn: String,
)
@Serializable
data class Arrangor(
@Serializable(with = UUIDSerializer::class)
val id: UUID,
val organisasjonsnummer: String,
val navn: String,
val slettet: Boolean,
)
@Serializable
data class Tiltakstype(
val navn: String,
)
}
| 2
|
Kotlin
|
2
| 7
|
ee39b300c4f1d01462fc37851fc039ba9d16531b
| 888
|
mulighetsrommet
|
MIT License
|
app/src/main/java/com/whalescale/binit/utils/GameUtils.kt
|
Ninise
| 605,546,083
| false
|
{"Kotlin": 257417}
|
package com.whalescale.binit.utils
import android.app.Activity
import android.content.Context
import com.whalescale.binit.R
import com.whalescale.binit.models.GameObject
import com.whalescale.binit.models.QuizObject
import com.whalescale.binit.models.RecycleType
import kotlin.random.Random
object GameUtils {
const val DND_ITEMS_AMOUNT = 10
const val QUIZ_AMOUNT = 5
private const val TOTAL_AMOUNT = "total_amount"
private const val LAST_INDEX = "last_index"
private const val LAST_QUESTION_INDEX = "last_question_index"
private val gameSet = arrayListOf(
GameObject(
R.drawable.ic_game_item_credit_card_garb,
"Credit card",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_cup_2_garb,
"Ceramic garb",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_shopping_bags_garb,
"Shopping bags",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_pencil_garb,
"Pencil",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_pen_garb,
"Pen",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_clothes_garb,
"Clothes",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_balloon_garb,
"Balloon",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_sponge_garb,
"Sponge",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_reuse_bug_garb,
"Reuse bag",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_receipt_garb,
"Receipt",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_label_garb,
"Label",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_key_,
"Keys",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_wood_garb,
"Wood",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_toothbrush_garb,
"Toothbrush",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_soap_garb,
"Soap",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_paintbrush_garb,
"Paintbrush",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_optical_disk_garb,
"Optical disk",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_bolt_garb,
"Bolt",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_thread_garb,
"Thread",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_razor_garb,
"Razor",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_cigarette_garb,
"Cigarette",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_styrofoam_box_garb,
"Styrofoam box",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_cup_2_garb,
"Cup",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_tube_garb,
"Tube",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_hair_brush_barg,
"Hairbrush",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_corks_garb,
"Corks",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_broken_glass_garb,
"Broken glass",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_chip_bag_rec,
"Chip bag",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_facemusk_garb,
"Facemusk",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_candle_garb,
"Candle",
RecycleType.GARBAGE),
GameObject(
R.drawable.ic_game_item_egg_org,
"Egg",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_fish_org,
"Fish",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_peanuts_org,
"Peanuts",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_bread_org,
"Bread",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_banana_org,
"Banana",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_lemon_org,
"Lemon",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_kiwi_fruit_org,
"Kiwi",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_vegetable_org,
"Vegetable",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_bagel_org,
"Bagel",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_orange_org,
"Orange",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_meat_on_bone_org,
"Meat on bone",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_pizza_2_org,
"Pizza 2",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_pizza_3_org,
"Pizza 3",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_coffee_beans_org,
"Coffee beans",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_pie_2_org,
"Pie 2",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_pie_3_org,
"Pie 3",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_bread_2_org,
"Bread 2",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_sandwich,
"Sandwich",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_diaper_org,
"Diaper",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_flower_org,
"Flower",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_egg_shell_org,
"Egg shell",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_tea_bug_org,
"Tea bag",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_coffee_filter_org,
"Tea bag",
RecycleType.ORGANIC),
GameObject(
R.drawable.ic_game_item_lotion_bottle_rec,
"Lotion bottle",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_toilet_towel_rec,
"Toilet towel",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_glass_bottle_2_rec,
"Glass bottle 2",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_notebook_2_rec,
"Notebook",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_canned_food_3_rec,
"Canned food 3",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_can_rec,
"Can 2",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_cardbord_rec,
"Cardboard",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_tissue_box_rec,
"Tissue box",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_pizza_box_rec,
"Pizza box",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_water_bottle_rec,
"Water bottle",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_yogurt_rec,
"Yogurt box",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_takeout_box_rec,
"Takeout box",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_lotion_bottle_2_rec,
"Lotion bottle 2",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_plastic_cup_rec,
"Plastic cp",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_canned_rec,
"Canned food",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_baby_bottle_rec,
"Baby bottle",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_package_rec,
"Package unwaxed",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_toilet_paper_rec,
"Toilet paper",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_notebook_2_rec,
"Notebook",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_newspaper_rec,
"Newspaper",
RecycleType.RECYCLE),
GameObject(
R.drawable.ic_game_item_champain_bottle_rec,
"Champain",
RecycleType.RECYCLE),
)
private val questionsList = arrayListOf<QuizObject>()
fun getBatchOfQuestions(activity: Activity) : MutableList<QuizObject> {
val totalAmount = questionsList.size
val lastIndex = getData(activity, LAST_QUESTION_INDEX)
return if (lastIndex + 5 < totalAmount) {
saveData(activity,lastIndex + 5, LAST_QUESTION_INDEX)
val list = arrayListOf<QuizObject>()
list.addAll(questionsList.subList(lastIndex, lastIndex + 5))
list
} else {
saveData(activity,0, LAST_QUESTION_INDEX)
questionsList.shuffle(Random(10))
val list = arrayListOf<QuizObject>()
list.addAll(questionsList.subList(0, 4))
list
}
}
fun saveQuizQuestions(questions: List<QuizObject>) {
questionsList.addAll(questions)
}
fun getBatchOfItems(activity: Activity) : MutableList<GameObject> {
// save total number of elements
// save last item index
// check if last index + 10 is more than total amount
// if yes -> start over
// if not -> get next 10 elements
val totalAmount = gameSet.size
val lastIndex = getData(activity, LAST_INDEX)
if (lastIndex == 0) {
gameSet.shuffle(Random(40))
}
return if (lastIndex + 10 < totalAmount) {
saveData(activity,lastIndex + 10, LAST_INDEX)
val list = arrayListOf<GameObject>()
list.addAll(gameSet.subList(lastIndex, lastIndex + 10))
list
} else {
saveData(activity,0, LAST_INDEX)
gameSet.shuffle(Random(40))
val list = arrayListOf<GameObject>()
list.addAll(gameSet.subList(0, 10))
list
}
}
private fun saveData(activity: Activity, num: Int, name: String) {
val sharedPref = activity.getPreferences(Context.MODE_PRIVATE)
sharedPref.edit().putInt(name, num).apply()
}
private fun getData(activity: Activity, name: String) : Int {
val sharedPref = activity.getPreferences(Context.MODE_PRIVATE)
return sharedPref.getInt(name, 0)
}
fun getCongratsTextBasedOnScore(score: Int) : String {
return when(score) {
1 -> Utils.string(R.string.congrats_1_title)
2 -> Utils.string(R.string.congrats_2_title)
3 -> Utils.string(R.string.congrats_3_title)
4 -> Utils.string(R.string.congrats_4_title)
5 -> Utils.string(R.string.congrats_5_title)
else -> Utils.string(R.string.congrats_1_title)
}
}
fun getCongratsSubsTextBasedOnScore(score: Int) : String {
return when(score) {
1 -> Utils.string(R.string.congrats_3_sub)
2 -> Utils.string(R.string.congrats_3_sub)
3 -> Utils.string(R.string.congrats_3_sub)
4 -> Utils.string(R.string.congrats_4_sub)
5 -> Utils.string(R.string.congrats_4_sub)
else -> Utils.string(R.string.congrats_4_sub)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
de62fef294b81bb46164d8aa13e9587f9eadad93
| 13,180
|
BinitAndroid
|
Apache License 2.0
|
intellij-plugin/educational-core/branches/232/src/com/jetbrains/edu/learning/feedback/compatibilityUtils.kt
|
JetBrains
| 43,696,115
| false
|
{"Kotlin": 4929631, "HTML": 3417303, "Python": 18771, "Java": 13512, "CSS": 12216, "JavaScript": 302, "Shell": 71}
|
package com.jetbrains.edu.learning.feedback
import com.intellij.feedback.common.dialog.showFeedbackSystemInfoDialog
import com.intellij.openapi.project.Project
import com.intellij.ui.dsl.builder.Panel
// BACKCOMPAT: 2023.2
typealias SystemDataJsonSerializable = com.intellij.feedback.common.dialog.JsonSerializable
typealias CommonFeedbackSystemData = com.intellij.feedback.common.dialog.CommonFeedbackSystemInfoData
typealias BlockBasedFeedbackDialogWithEmail<T> = com.intellij.feedback.common.dialog.BlockBasedFeedbackDialogWithEmail<T>
typealias FeedbackBlock = com.intellij.feedback.common.dialog.uiBlocks.FeedbackBlock
typealias TopLabelBlock = com.intellij.feedback.common.dialog.uiBlocks.TopLabelBlock
typealias DescriptionBlock = com.intellij.feedback.common.dialog.uiBlocks.DescriptionBlock
typealias RatingBlock = com.intellij.feedback.common.dialog.uiBlocks.RatingBlock
typealias TextAreaBlock = com.intellij.feedback.common.dialog.uiBlocks.TextAreaBlock
fun showFeedbackSystemInfoDialog(project: Project?, systemInfoData: CommonFeedbackSystemData, addSpecificRows: Panel.() -> Unit) =
showFeedbackSystemInfoDialog(project, systemInfoData, addSpecificRows)
| 6
|
Kotlin
|
44
| 135
|
b00e7100e8658a07e79700a20ffe576872d494db
| 1,172
|
educational-plugin
|
Apache License 2.0
|
compose/src/main/java/de/jensklingenberg/jetpackcomposeplayground/ui/samples/mysamples/other/CounterModel.kt
|
ravishankarsingh1996
| 223,398,680
| false
| null |
package de.jensklingenberg.jetpackcomposeplayground.ui.samples.mysamples.other
import androidx.compose.Composable
import androidx.compose.state
import androidx.compose.unaryPlus
import androidx.ui.core.Text
import androidx.ui.layout.Center
import androidx.ui.layout.Column
import androidx.ui.material.Button
import androidx.ui.material.MaterialTheme
class CounterModel {
val counter = +state { 0 }
var header = "Counter demo"
}
@Composable
fun CounterModelDemo() {
MaterialTheme {
val countState =
CounterModel()
Center {
Column {
CounterHeader(
countState
)
AddSubtractButtons(
countState
)
CounterLabel(
countState
)
}
}
}
}
@Composable
fun CounterHeader(counterModel: CounterModel) {
Text(text = counterModel.header, style = (+MaterialTheme.typography()).h4)
}
@Composable
fun AddSubtractButtons(
counterModel: CounterModel
) {
Button(
text = "Add",
onClick = {
counterModel.counter.value++
})
Button(
text = "Subtract",
onClick = { counterModel.counter.value-- })
}
@Composable
fun CounterLabel(counterModel: CounterModel) {
Text(text = "Clicks: ${counterModel.counter.value}", style = (+MaterialTheme.typography()).h4)
}
| 0
| null |
0
| 4
|
2d87fa9dbdd7f89b0d0e3e97f143910e5a3a9e54
| 1,443
|
Jetpack-Compose-Playground
|
MIT License
|
font-awesome/src/commonMain/kotlin/compose/icons/fontawesomeicons/brands/Npm.kt
|
DevSrSouza
| 311,134,756
| false
| null |
package compose.icons.fontawesomeicons.brands
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 compose.icons.fontawesomeicons.BrandsGroup
public val BrandsGroup.Npm: ImageVector
get() {
if (_npm != null) {
return _npm!!
}
_npm = Builder(name = "Npm", defaultWidth = 576.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 576.0f, viewportHeight = 512.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(288.0f, 288.0f)
horizontalLineToRelative(-32.0f)
verticalLineToRelative(-64.0f)
horizontalLineToRelative(32.0f)
verticalLineToRelative(64.0f)
close()
moveTo(576.0f, 160.0f)
verticalLineToRelative(192.0f)
lineTo(288.0f, 352.0f)
verticalLineToRelative(32.0f)
lineTo(160.0f, 384.0f)
verticalLineToRelative(-32.0f)
lineTo(0.0f, 352.0f)
lineTo(0.0f, 160.0f)
horizontalLineToRelative(576.0f)
close()
moveTo(160.0f, 192.0f)
lineTo(32.0f, 192.0f)
verticalLineToRelative(128.0f)
horizontalLineToRelative(64.0f)
verticalLineToRelative(-96.0f)
horizontalLineToRelative(32.0f)
verticalLineToRelative(96.0f)
horizontalLineToRelative(32.0f)
lineTo(160.0f, 192.0f)
close()
moveTo(320.0f, 192.0f)
lineTo(192.0f, 192.0f)
verticalLineToRelative(160.0f)
horizontalLineToRelative(64.0f)
verticalLineToRelative(-32.0f)
horizontalLineToRelative(64.0f)
lineTo(320.0f, 192.0f)
close()
moveTo(544.0f, 192.0f)
lineTo(352.0f, 192.0f)
verticalLineToRelative(128.0f)
horizontalLineToRelative(64.0f)
verticalLineToRelative(-96.0f)
horizontalLineToRelative(32.0f)
verticalLineToRelative(96.0f)
horizontalLineToRelative(32.0f)
verticalLineToRelative(-96.0f)
horizontalLineToRelative(32.0f)
verticalLineToRelative(96.0f)
horizontalLineToRelative(32.0f)
lineTo(544.0f, 192.0f)
close()
}
}
.build()
return _npm!!
}
private var _npm: ImageVector? = null
| 17
| null |
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,220
|
compose-icons
|
MIT License
|
editor/src/main/kotlin/CanvasWindow.kt
|
Pengiie
| 411,461,323
| false
| null |
import dev.pengie.kotaro.Application
import dev.pengie.kotaro.events.Event
import dev.pengie.kotaro.events.EventManager
import dev.pengie.kotaro.events.input.*
import dev.pengie.kotaro.input.Key
import dev.pengie.kotaro.scene.components.Tag
import dev.pengie.kotaro.window.Window
import editor.EditorState
import editor.components.sceneExplorer.SceneExplorerItem
import org.lwjgl.opengl.GL
import org.lwjgl.opengl.awt.AWTGLCanvas
import org.lwjgl.opengl.awt.GLData
import java.awt.event.*
import kotlin.concurrent.thread
import kotlin.reflect.KClass
class CanvasWindow : Window(0, 0) {
internal val wrapper = CanvasWrapper()
private val time: Double = System.currentTimeMillis().toDouble() / 1000
init {
thread {
Application.invoke(window = this@CanvasWindow, startScene = EDITOR_SCENE, context = {
wrapper.runInContext {
this.wrapper.initGL()
it.invoke()
}
})
}
}
override fun init() {}
override fun update() {}
override fun run() {
while(Application.isRunning) {
wrapper.render()
}
dispose()
}
override fun resizeWindow(width: Int, height: Int) {
}
override fun getTime(): Double =
(System.currentTimeMillis().toDouble() / 1000) - time
override fun lockMouse(value: Boolean) {
}
override fun dispose() {
close!!.invoke()
wrapper.disposeCanvas()
}
@Suppress("UNCHECKED_CAST")
internal inner class CanvasWrapper : AWTGLCanvas(GLData().apply {
this.majorVersion = 3
this.minorVersion = 2
this.profile = GLData.Profile.CORE
}) {
val queuedEvents: MutableList<EventDescriptor<Event>> = mutableListOf()
internal inner class EventDescriptor <T : Event> (val event: Event, val type: KClass<T>)
init {
addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) {
if(e == null)
return
val key = canvasKeyMap[e.keyCode] ?: return
queuedEvents.add(EventDescriptor(KeyDownEvent(key, hashSetOf()), KeyDownEvent::class) as EventDescriptor<Event>)
}
override fun keyReleased(e: KeyEvent?) {
if(e == null)
return
val key = canvasKeyMap[e.keyCode] ?: return
queuedEvents.add(EventDescriptor(KeyUpEvent(key, hashSetOf()), KeyUpEvent::class) as EventDescriptor<Event>)
}
})
addMouseListener(object : MouseListener {
override fun mouseClicked(e: MouseEvent?) {}
override fun mousePressed(e: MouseEvent?) {
if(e != null)
queuedEvents.add(EventDescriptor(MouseButtonDownEvent(e.button), MouseButtonDownEvent::class) as EventDescriptor<Event>)
}
override fun mouseReleased(e: MouseEvent?) {
if(e != null)
queuedEvents.add(EventDescriptor(MouseButtonUpEvent(e.button), MouseButtonUpEvent::class) as EventDescriptor<Event>)
}
override fun mouseEntered(e: MouseEvent?) {}
override fun mouseExited(e: MouseEvent?) {}
})
addMouseMotionListener(object : MouseMotionListener {
override fun mouseDragged(e: MouseEvent?) {
if(e == null)
return
this@CanvasWindow.mousePosition.x = e.x.toFloat()
this@CanvasWindow.mousePosition.y = e.y.toFloat()
}
override fun mouseMoved(e: MouseEvent?) {
if(e == null)
return
this@CanvasWindow.mousePosition.x = e.x.toFloat()
this@CanvasWindow.mousePosition.y = e.y.toFloat()
}
})
addMouseWheelListener {
if(it == null)
return@addMouseWheelListener
queuedEvents.add(EventDescriptor(MouseScrollEvent(0f, it.preciseWheelRotation.toFloat()), MouseScrollEvent::class) as EventDescriptor<Event>)
}
}
override fun initGL() {
GL.createCapabilities()
}
override fun paintGL() {
// Add one to account for flooring values cause the library person decided to do that for some reason
val w = framebufferWidth + 1
val h = framebufferHeight + 1
if(this@CanvasWindow.width != w || this@CanvasWindow.height != h)
this@CanvasWindow.resize(w, h)
val events = queuedEvents.toList()
events.forEach { EventManager.submitEvent(it.type, it.event)}
queuedEvents.clear()
loop!!.invoke()
val scene = SceneExplorerItem(Presence.presence!!.project.scenes[Presence.presence!!.currentScene!!].name, -1, 0)
val entityList = Application.scene.createView(Tag::class).map {
SceneExplorerItem(Application.scene.getComponent<Tag>(it)!!.name, it, 1)
}
EditorState.sceneList = listOf(scene, *(entityList.toTypedArray()))
swapBuffers()
}
}
}
val canvasKeyMap = hashMapOf(
Pair(65, Key.A),
Pair(66, Key.B),
Pair(67, Key.C),
Pair(68, Key.D),
Pair(69, Key.E),
Pair(70, Key.F),
Pair(71, Key.G),
Pair(72, Key.H),
Pair(73, Key.I),
Pair(74, Key.J),
Pair(75, Key.K),
Pair(76, Key.L),
Pair(77, Key.M),
Pair(78, Key.N),
Pair(79, Key.O),
Pair(80, Key.P),
Pair(81, Key.Q),
Pair(82, Key.R),
Pair(83, Key.S),
Pair(84, Key.T),
Pair(85, Key.U),
Pair(86, Key.V),
Pair(87, Key.W),
Pair(88, Key.X),
Pair(89, Key.Y),
Pair(90, Key.Z),
Pair(32, Key.SPACE),
Pair(16, Key.SHIFT),
Pair(17, Key.CTRL),
Pair(18, Key.ALT),
Pair(27, Key.ESCAPE)
)
| 0
|
Kotlin
|
0
| 0
|
b9f75232ae7d2ad815478307d0c731d0f1ce9bbd
| 6,100
|
kotarOld
|
Apache License 2.0
|
fetch2core/src/main/java/com/tonyodev/fetch2core/server/FileResponse.kt
|
Kutikov
| 731,088,336
| false
| null |
package com.tonyodev.fetch2core.server
import android.os.Parcel
import android.os.Parcelable
import java.io.Serializable
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.util.*
/**
* Response object sent to the client as JSON.
* **/
data class FileResponse(val status: Int = HttpURLConnection.HTTP_UNSUPPORTED_TYPE,
val type: Int = FileRequest.TYPE_INVALID,
val connection: Int = CLOSE_CONNECTION,
val date: Long = Date().time,
val contentLength: Long = 0,
val md5: String = "",
val sessionId: String = "") : Parcelable, Serializable {
val toJsonString: String
get() {
val builder = StringBuilder()
.append('{')
.append("\"Status\":").append(status).append(',')
.append("\"Md5\":").append("\"$md5\"").append(',')
.append("\"Connection\":").append(connection).append(',')
.append("\"Date\":").append(date).append(',')
.append("\"Content-Length\":").append(contentLength).append(',')
.append("\"Type\":").append(type).append(',')
.append("\"SessionId\":").append(sessionId)
.append('}')
return builder.toString()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(status)
dest.writeInt(type)
dest.writeInt(connection)
dest.writeLong(date)
dest.writeLong(contentLength)
dest.writeString(md5)
dest.writeString(sessionId)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<FileResponse> {
const val CLOSE_CONNECTION = 0
const val OPEN_CONNECTION = 1
const val FIELD_STATUS = "Status"
const val FIELD_TYPE = "Type"
const val FIELD_CONNECTION = "Connection"
const val FIELD_DATE = "Date"
const val FIELD_CONTENT_LENGTH = "Content-Length"
const val FIELD_MD5 = "Md5"
const val FIELD_SESSION_ID = "SessionId"
override fun createFromParcel(source: Parcel): FileResponse {
return FileResponse(
status = source.readInt(),
type = source.readInt(),
connection = source.readInt(),
date = source.readLong(),
contentLength = source.readLong(),
md5 = source.readString() ?: "",
sessionId = source.readString() ?: "")
}
override fun newArray(size: Int): Array<FileResponse?> {
return arrayOfNulls(size)
}
}
}
| 122
| null |
342
| 6
|
c450f681035ed47d2bd6e5e2b7cf4b921665e669
| 2,823
|
fetch2-android
|
Apache License 2.0
|
core/src/com/maattss/intro/exercise/states/State.kt
|
maattss
| 235,056,301
| false
| null |
package com.maattss.intro.exercise.states
import com.badlogic.gdx.graphics.g2d.SpriteBatch
abstract class State(protected var gsm: GameStateManager) {
protected abstract fun handleInput()
abstract fun update(dt: Float)
abstract fun render(sb: SpriteBatch)
abstract fun dispose()
}
| 0
|
Kotlin
|
0
| 0
|
2348a560973d45d865aca5c895a4fb794fdb711b
| 298
|
tdt4240-intro-exercise
|
MIT License
|
compose/ui/ui/src/test/kotlin/androidx/compose/ui/gesture/LongPressGestureFilterTest.kt
|
tikurahul
| 334,969,342
| true
|
{"Java": 45895688, "Kotlin": 28840351, "Python": 297324, "Shell": 121288, "C++": 30502, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.gesture
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.gesture.customevents.LongPressFiredEvent
import androidx.compose.ui.input.pointer.CustomEventDispatcher
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.consumeDownChange
import androidx.compose.ui.input.pointer.consumePositionChange
import androidx.compose.ui.input.pointer.down
import androidx.compose.ui.input.pointer.invokeOverAllPasses
import androidx.compose.ui.input.pointer.moveBy
import androidx.compose.ui.input.pointer.moveTo
import androidx.compose.ui.input.pointer.up
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.milliseconds
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import kotlinx.coroutines.CoroutineScope
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.concurrent.TimeUnit
@kotlinx.coroutines.ObsoleteCoroutinesApi
@RunWith(JUnit4::class)
class LongPressGestureFilterTest {
private val LongPressTimeoutMillis = 100.milliseconds
@Suppress("DEPRECATION")
private val testContext = kotlinx.coroutines.test.TestCoroutineContext()
private val onLongPress: (Offset) -> Unit = mock()
private val customEventDispatcher: CustomEventDispatcher = mock()
private lateinit var filter: LongPressGestureFilter
@Before
fun setup() {
filter = LongPressGestureFilter(CoroutineScope(testContext))
filter.onLongPress = onLongPress
filter.longPressTimeout = LongPressTimeoutMillis
filter.onInit(customEventDispatcher)
}
// Tests that verify conditions under which onLongPress will not be called.
@Test
fun onPointerEvent_down_eventNotFired() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_downWithinTimeout_eventNotFired() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
testContext.advanceTimeBy(99, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_DownMoveConsumed_eventNotFired() {
val down = down(0)
val move =
down.moveBy(50.milliseconds, 1f, 1f).apply { consumePositionChange(1f, 0f) }
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_2Down1MoveConsumed_eventNotFired() {
val down0 = down(0)
val down1 = down(1)
val move0 =
down0.moveBy(50.milliseconds, 1f, 1f).apply { consumePositionChange(1f, 0f) }
val move1 = down0.moveBy(50.milliseconds, 0f, 0f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down0, down1))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move0, move1))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_DownUpConsumed_eventNotFired() {
val down = down(0)
val up = down.up(50.milliseconds).apply { consumeDownChange() }
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(up))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_DownUpNotConsumed_eventNotFired() {
val down = down(0)
val up = down.up(50.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(up))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_2DownIndependentlyUnderTimeoutAndDoNotOverlap_eventNotFired() {
// Arrange
val down0 = down(0)
val up0 = down0.up(50.milliseconds)
val down1 = down(1, 51.milliseconds)
// Act
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down0))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(up0))
testContext.advanceTimeBy(1, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down1))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
// Assert
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onPointerEvent_downMoveOutOfBoundsWait_eventNotFired() {
var pointer = down(0, 0.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer), IntSize(1, 1))
pointer = pointer.moveTo(50.milliseconds, 1f, 0f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer), IntSize(1, 1))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
// Tests that verify conditions under which onLongPress will be called.
@Test
fun onPointerEvent_downBeyondTimeout_eventFiredOnce() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
@Test
fun onPointerEvent_2DownBeyondTimeout_eventFiredOnce() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0), down(1)))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
@Test
fun onPointerEvent_downMoveOutOfBoundsWaitUpThenDownWait_eventFiredOnce() {
var pointer = down(0, 0.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer), IntSize(1, 1))
pointer = pointer.moveTo(50.milliseconds, 1f, 0f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer), IntSize(1, 1))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
pointer = pointer.up(105.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer), IntSize(1, 1))
pointer = down(1, 200.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer), IntSize(1, 1))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
@Test
fun onPointerEvent_2DownIndependentlyUnderTimeoutButOverlapTimeIsOver_eventFiredOnce() {
// Arrange
val down0 = down(0)
val move0 = down0.moveTo(50.milliseconds, 0f, 0f)
val down1 = down(1, 50.milliseconds)
val up0 = move0.up(75.milliseconds)
val move1 = down1.moveTo(75.milliseconds, 0f, 0f)
// Act
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(down0)
)
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(move0, down1)
)
testContext.advanceTimeBy(25, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(up0, move1)
)
testContext.advanceTimeBy(25, TimeUnit.MILLISECONDS)
// Assert
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
@Test
fun onPointerEvent_downMoveNotConsumed_eventFiredOnce() {
val down = down(0)
val move = down.moveBy(50.milliseconds, 1f, 1f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
// Tests that verify correctness of PxPosition value passed to onLongPress
@Test
fun onPointerEvent_down_onLongPressCalledWithDownPosition() {
val down = down(0, x = 13f, y = 17f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(Offset(13f, 17f))
}
@Test
fun onPointerEvent_downMove_onLongPressCalledWithMovePosition() {
val down = down(0, x = 13f, y = 17f)
val move = down.moveTo(50.milliseconds, 7f, 5f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(Offset(7f, 5f))
}
@Test
fun onPointerEvent_downThenDown_onLongPressCalledWithFirstDownPosition() {
val down0 = down(0, x = 13f, y = 17f)
val move0 = down0.moveBy(50.milliseconds, 0f, 0f)
val down1 = down(1, 50.milliseconds, 11f, 19f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down0))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move0, down1))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(Offset(13f, 17f))
}
@Test
fun onPointerEvent_down0ThenDown1ThenUp0_onLongPressCalledWithDown1Position() {
val down0 = down(0, x = 13f, y = 17f)
val move0 = down0.moveTo(50.milliseconds, 27f, 29f)
val down1 = down(1, 50.milliseconds, 11f, 19f)
val up0 = move0.up(75.milliseconds)
val move1 = down1.moveBy(25.milliseconds, 0f, 0f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down0))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move0, down1))
testContext.advanceTimeBy(25, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(up0, move1))
testContext.advanceTimeBy(25, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(Offset(11f, 19f))
}
@Test
fun onPointerEvent_down0ThenMove0AndDown1_onLongPressCalledWithMove0Position() {
val down0 = down(0, x = 13f, y = 17f)
val move0 = down0.moveTo(50.milliseconds, 27f, 29f)
val down1 = down(1, 50.milliseconds, 11f, 19f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down0))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move0, down1))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(Offset(27f, 29f))
}
@Test
fun onPointerEvent_down0Down1Move1Up0_onLongPressCalledWithMove1Position() {
val down0 = down(0, x = 13f, y = 17f)
val move0 = down0.moveBy(25.milliseconds, 0f, 0f)
val down1 = down(1, 25.milliseconds, 11f, 19f)
val up0 = move0.up(50.milliseconds)
val move1 = down1.moveTo(50.milliseconds, 27f, 23f)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down0))
testContext.advanceTimeBy(25, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(move0, down1))
testContext.advanceTimeBy(25, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(up0, move1))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(Offset(27f, 23f))
}
// Tests that verify that consumption behavior
@Test
fun onPointerEvent_1Down_notConsumed() {
val down = down(0)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down))
assertThat(down.consumed.downChange).isFalse()
}
@Test
fun onPointerEvent_1DownThen1Down_notConsumed() {
// Arrange
val down0 = down(0, 0.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(down0)
)
// Act
testContext.advanceTimeBy(10, TimeUnit.MILLISECONDS)
val move0 = down0.moveTo(10.milliseconds, 0f, 0f)
val down1 = down(0, 10.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(move0, down1)
)
// Assert
assertThat(move0.consumed.downChange).isFalse()
assertThat(down1.consumed.downChange).isFalse()
}
@Test
fun onPointerEvent_1DownUnderTimeUp_upNotConsumed() {
// Arrange
val down0 = down(0, 0.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(down0)
)
// Act
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
val up = down0.up(50.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(up))
// Assert
assertThat(up.consumed.downChange).isFalse()
}
@Test
fun onPointerEvent_1DownOverTimeUp_upConsumedOnInitial() {
// Arrange
val down0 = down(0, 0.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(
pointerEventOf(down0)
)
// Act
testContext.advanceTimeBy(101, TimeUnit.MILLISECONDS)
val up0 = down0.up(100.milliseconds)
filter.onPointerEvent(
pointerEventOf(up0),
PointerEventPass.Initial,
IntSize(0, 0)
)
// Assert
assertThat(up0.consumed.downChange).isTrue()
}
@Test
fun onPointerEvent_1DownOverTimeMoveConsumedUp_upNotConsumed() {
// Arrange
var pointer = down(0, 0.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer))
testContext.advanceTimeBy(50, TimeUnit.MILLISECONDS)
pointer = pointer.moveTo(50.milliseconds, 5f).apply { consumePositionChange(1f, 0f) }
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer))
// Act
testContext.advanceTimeBy(51, TimeUnit.MILLISECONDS)
pointer = pointer.up(100.milliseconds)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(pointer))
// Assert
assertThat(pointer.consumed.downChange).isFalse()
}
// Tests that verify correct behavior around cancellation.
@Test
fun onCancel_downCancelBeyondTimeout_eventNotFired() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
filter.onCancel()
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onCancel_downAlmostTimeoutCancelTimeout_eventNotFired() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
testContext.advanceTimeBy(99, TimeUnit.MILLISECONDS)
filter.onCancel()
testContext.advanceTimeBy(1, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onCancel_downCancelDownTimeExpires_eventFiredOnce() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
testContext.advanceTimeBy(99, TimeUnit.MILLISECONDS)
filter.onCancel()
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
// Verify correct behavior around responding to LongPressFiredEvent
@Test
fun onCustomEvent_downCustomEventTimeout_eventNotFired() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
filter::onCustomEvent.invokeOverAllPasses(LongPressFiredEvent)
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress, never()).invoke(any())
verify(customEventDispatcher, never()).dispatchCustomEvent(any())
}
@Test
fun onCustomEvent_downCustomEventTimeoutDownTimeout_eventFiredOnce() {
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
filter::onCustomEvent.invokeOverAllPasses(LongPressFiredEvent)
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
filter::onPointerEvent.invokeOverAllPasses(pointerEventOf(down(0, 0.milliseconds)))
testContext.advanceTimeBy(100, TimeUnit.MILLISECONDS)
verify(onLongPress).invoke(any())
verify(customEventDispatcher).dispatchCustomEvent(LongPressFiredEvent)
}
}
| 0
| null |
0
| 1
|
ccac66729a5e461b3a05944014f42e2dc55337d6
| 19,205
|
androidx
|
Apache License 2.0
|
src/main/kotlin/me/peckb/aoc/_2023/calendar/day22/Shape.kt
|
peckb1
| 433,943,215
| false
|
{"Kotlin": 956123}
|
package me.peckb.aoc._2023.calendar.day22
enum class Shape {
VERTICAL, HORIZONTAL_X, HORIZONTAL_Y, CUBE
}
| 0
|
Kotlin
|
1
| 3
|
732eaf95804825a542c1cbddbc55053383f9127b
| 109
|
advent-of-code
|
MIT License
|
libnavui-voice/src/test/java/com/mapbox/navigation/ui/voice/api/MapboxSpeechProviderTest.kt
|
mapbox
| 87,455,763
| false
| null |
package com.mapbox.navigation.ui.voice.api
import android.net.Uri
import com.mapbox.bindgen.Expected
import com.mapbox.bindgen.ExpectedFactory
import com.mapbox.common.NetworkRestriction
import com.mapbox.common.ResourceLoadError
import com.mapbox.common.ResourceLoadFlags
import com.mapbox.common.ResourceLoadResult
import com.mapbox.common.ResourceLoadStatus
import com.mapbox.navigation.base.internal.accounts.UrlSkuTokenProvider
import com.mapbox.navigation.testing.LoggingFrontendTestRule
import com.mapbox.navigation.testing.MainCoroutineRule
import com.mapbox.navigation.ui.utils.internal.resource.ResourceLoadCallback
import com.mapbox.navigation.ui.utils.internal.resource.ResourceLoadRequest
import com.mapbox.navigation.ui.utils.internal.resource.ResourceLoader
import com.mapbox.navigation.ui.voice.options.MapboxSpeechApiOptions
import com.mapbox.navigation.ui.voice.options.VoiceGender
import com.mapbox.navigation.ui.voice.testutils.Fixtures
import com.mapbox.navigation.utils.internal.InternalJobControlFactory
import com.mapbox.navigation.utils.internal.JobControl
import com.mapbox.navigation.utils.internal.ThreadController
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.slot
import io.mockk.unmockkObject
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.net.URL
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(RobolectricTestRunner::class)
internal class MapboxSpeechProviderTest {
private lateinit var sut: MapboxSpeechProvider
@get:Rule
val coroutineRule = MainCoroutineRule()
@get:Rule
val loggerRule = LoggingFrontendTestRule()
private var accessToken = "access_token"
private val language = "en"
private val apiOptions = MapboxSpeechApiOptions.Builder()
.baseUri("https://example.com")
.gender(VoiceGender.FEMALE)
.build()
private val sku = "SKU"
private lateinit var mockResourceLoader: ResourceLoader
private var stubSkuTokenProvider: UrlSkuTokenProvider = UrlSkuTokenProvider {
URL("$it&sku=$sku")
}
@Before
fun setUp() {
mockkObject(InternalJobControlFactory)
every {
InternalJobControlFactory.createDefaultScopeJobControl()
} returns JobControl(mockk(), coroutineRule.createTestScope())
mockkObject(ThreadController)
mockResourceLoader = mockk(relaxed = true)
sut = MapboxSpeechProvider(
accessToken = accessToken,
language = language,
urlSkuTokenProvider = stubSkuTokenProvider,
options = apiOptions,
resourceLoader = mockResourceLoader
)
}
@After
fun tearDown() {
unmockkObject(ThreadController)
}
@Test
fun `load should use ResourceLoader to load audio data`() = runBlocking {
val instructions = Fixtures.ssmlInstructions()
val requestCapture = slot<ResourceLoadRequest>()
val callbackCapture = slot<ResourceLoadCallback>()
val loadResult = Fixtures.resourceLoadResult(null, ResourceLoadStatus.NOT_FOUND)
every {
mockResourceLoader.load(capture(requestCapture), capture(callbackCapture))
} answers {
callbackCapture.captured.onFinish(
requestCapture.captured,
ExpectedFactory.createValue(loadResult)
)
1L
}
sut.load(instructions)
val loadRequest = requestCapture.captured
val loadRequestUri = Uri.parse(loadRequest.url)
assertEquals("https", loadRequestUri.scheme)
assertEquals("example.com", loadRequestUri.authority)
assertEquals(
"/voice/v1/speak/${UrlUtils.encodePathSegment(instructions.ssmlAnnouncement()!!)}",
loadRequestUri.encodedPath
)
assertEquals(
mapOf(
"textType" to "ssml",
"language" to language,
"access_token" to accessToken,
"gender" to apiOptions.gender,
"sku" to sku
),
loadRequestUri.getQueryParams()
)
assertEquals(
ResourceLoadFlags.ACCEPT_EXPIRED,
loadRequest.flags
)
}
@Test
fun `load should allow network`() = runBlocking {
val instructions = Fixtures.ssmlInstructions()
val requestCapture = slot<ResourceLoadRequest>()
val callbackCapture = slot<ResourceLoadCallback>()
val loadResult = Fixtures.resourceLoadResult(null, ResourceLoadStatus.NOT_FOUND)
every {
mockResourceLoader.load(capture(requestCapture), capture(callbackCapture))
} answers {
callbackCapture.captured.onFinish(
requestCapture.captured,
ExpectedFactory.createValue(loadResult)
)
1L
}
sut.load(instructions)
val loadRequest = requestCapture.captured
assertEquals(
NetworkRestriction.NONE,
loadRequest.networkRestriction
)
}
@Test
fun `load should return Expected with non empty audio BLOB on success`() =
runBlocking {
val instructions = Fixtures.textInstructions()
val blob = byteArrayOf(12, 23, 34)
val loadRequest = ResourceLoadRequest("https://some.url")
val loadResult = Fixtures.resourceLoadResult(
Fixtures.resourceData(blob),
ResourceLoadStatus.AVAILABLE
)
givenResourceLoaderResponse(loadRequest, ExpectedFactory.createValue(loadResult))
val result = sut.load(instructions)
assertEquals(blob, result.value)
}
@Test
fun `load should return Expected with an Error on AVAILABLE loader response with empty BLOB`() =
runBlocking {
val expectedError = "No data available."
val instructions = Fixtures.textInstructions()
val loadRequest = ResourceLoadRequest("https://some.url")
val loadResult = Fixtures.resourceLoadResult(
Fixtures.resourceData(byteArrayOf()),
ResourceLoadStatus.AVAILABLE
)
givenResourceLoaderResponse(loadRequest, ExpectedFactory.createValue(loadResult))
val result = sut.load(instructions)
assertEquals(expectedError, result.error!!.localizedMessage)
}
@Test
fun `load should return Expected with an Error on UNAUTHORIZED loader response`() =
runBlocking {
val expectedError = "Your token cannot access this resource."
val instructions = Fixtures.textInstructions()
val loadRequest = ResourceLoadRequest("https://some.url")
val loadResult = Fixtures.resourceLoadResult(
null,
ResourceLoadStatus.UNAUTHORIZED
)
givenResourceLoaderResponse(loadRequest, ExpectedFactory.createValue(loadResult))
val result = sut.load(instructions)
assertEquals(expectedError, result.error!!.localizedMessage)
}
@Test
fun `load should return Expected with an Error on NOT_FOUND loader response`() =
runBlocking {
val expectedError = "Resource is missing."
val instructions = Fixtures.textInstructions()
val loadRequest = ResourceLoadRequest("https://some.url")
val loadResult = Fixtures.resourceLoadResult(
null,
ResourceLoadStatus.NOT_FOUND
)
givenResourceLoaderResponse(loadRequest, ExpectedFactory.createValue(loadResult))
val result = sut.load(instructions)
assertEquals(expectedError, result.error!!.localizedMessage)
}
@Test
fun `request is cancelled when scope is cancelled`() = coroutineRule.runBlockingTest {
val instructions = Fixtures.textInstructions()
val job = launch { sut.load(instructions) }
job.cancel()
verify(exactly = 1) { mockResourceLoader.cancel(any()) }
}
private fun givenResourceLoaderResponse(
request: ResourceLoadRequest,
response: Expected<ResourceLoadError, ResourceLoadResult>
) {
val loadCallbackSlot = slot<ResourceLoadCallback>()
every { mockResourceLoader.load(any(), capture(loadCallbackSlot)) } answers {
loadCallbackSlot.captured.onFinish(request, response)
0L
}
}
private fun Uri.getQueryParams() =
queryParameterNames.fold(mutableMapOf<String, String?>()) { acc, key ->
acc[key] = getQueryParameter(key)
acc
}
}
| 508
| null |
319
| 621
|
ad73c6011348cb9b24b92a369024ca06f48845ab
| 8,994
|
mapbox-navigation-android
|
Apache License 2.0
|
app/src/main/java/net/shadowxcraft/smartlights/packets/DeleteColorSequencePacket.kt
|
jaredoconnell
| 230,815,009
| false
|
{"Kotlin": 236452}
|
package net.shadowxcraft.smartlights.packets
import net.shadowxcraft.smartlights.ColorSequence
import net.shadowxcraft.smartlights.ESP32
class DeleteColorSequencePacket(controller: ESP32, private val sequence: ColorSequence)
: SendablePacket(controller, 25)
{
override fun send() {
val output = getHeader()
output.addAll(strToByteList(sequence.id)) // Just the ID of the color sequence.
sendData(output.toByteArray())
}
}
| 0
|
Kotlin
|
0
| 1
|
a0325b0185e585c33d2a1b0ccfbb00d8a45374a5
| 459
|
SmartLights_Android
|
Apache License 2.0
|
app/src/main/java/com/nlptech/function/theme/theme_manage/ThemeManageItemViewHolder.kt
|
ahkter-husin
| 208,083,694
| true
|
{"Java": 878274, "Kotlin": 32366}
|
package com.nlptech.function.theme.theme_manage
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import androidx.recyclerview.widget.RecyclerView
import com.android.inputmethod.TestApplication
import com.android.inputmethod.latin.databinding.ViewholderThemeBinding
import com.bumptech.glide.Glide
import com.nlptech.keyboardview.theme.KeyboardTheme
import com.nlptech.keyboardview.theme.KeyboardThemeManager
import com.nlptech.keyboardview.theme.custom.CustomTheme
import com.nlptech.keyboardview.theme.external.ExternalTheme
import kotlinx.android.synthetic.main.activity_main.view.*
import kotlinx.android.synthetic.main.viewholder_theme.view.*
class ThemeManageItemViewHolder(
val binding: ViewholderThemeBinding,
itemWidth: Int,
itemHeight: Int
) : RecyclerView.ViewHolder(binding.root) {
private var previewString = ""
init {
binding.root.viewholder_theme.layoutParams.width = itemWidth
binding.root.viewholder_theme_iv.layoutParams.height = WRAP_CONTENT
binding.executePendingBindings()
}
fun bind(themeManageItem: ThemeManageItem, listener: ThemeManageAdapter.Listener, position: Int) {
binding.themeManageItem = themeManageItem
binding.listener = listener
binding.position = position
binding.executePendingBindings()
setRadioButtonSelected(themeManageItem.isSelected)
setImageDrawable(themeManageItem.keyboardThemeId)
}
private fun setRadioButtonSelected(isSelected: Boolean) {
itemView.viewholder_theme_radio_button_ib.isSelected = isSelected
}
private fun setImageDrawable(keyboardThemeId: Int) {
val context = itemView.context
val keyboardTheme = KeyboardThemeManager.getInstance().getKeyboardTheme(context, keyboardThemeId)
when (keyboardTheme.themeType) {
KeyboardTheme.ThemeType.LOCAL -> {
val previewDrawableResId = KeyboardThemeManager.getInstance().getLocalThemePreviewDrawableResId(TestApplication.getInstance(), keyboardTheme.getStyleId())
Glide.with(itemView.context).load(previewDrawableResId).into(itemView.viewholder_theme_iv)
}
KeyboardTheme.ThemeType.CUSTOM -> {
val customTheme = keyboardTheme as CustomTheme
val previewImageFilePath = customTheme.previewImageFilePath
if (!previewImageFilePath.equals(previewString)) {
previewString = previewImageFilePath
Glide.with(itemView.context).load(previewString).into(itemView.viewholder_theme_iv)
}
}
KeyboardTheme.ThemeType.DOWNLOAD -> {
// TODO
}
KeyboardTheme.ThemeType.EXTERNAL -> {
val externalTheme = keyboardTheme as ExternalTheme
Glide.with(itemView.context).load(externalTheme.info.themePreviewImage).into(itemView.viewholder_theme_iv)
}
}
}
}
| 0
| null |
0
| 0
|
86cffbe6c16703b4e6c9c76f9bf157d4f38d9d1f
| 2,995
|
Android-Keyboard
|
Apache License 2.0
|
app/src/main/java/org/wikipedia/feed/news/NewsViewModel.kt
|
greatfire
| 460,298,221
| true
|
{"Kotlin": 2932557, "Java": 68018, "C++": 37990, "Python": 23673, "CMake": 1104, "Jinja": 533, "Shell": 521}
|
package org.wikipedia.feed.news
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import org.wikipedia.Constants
import org.wikipedia.dataclient.WikiSite
class NewsViewModel(bundle: Bundle) : ViewModel() {
val item = bundle.getParcelable<NewsItem>(NewsActivity.EXTRA_NEWS_ITEM)!!
val wiki = bundle.getParcelable<WikiSite>(Constants.ARG_WIKISITE)!!
class Factory(private val bundle: Bundle) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return NewsViewModel(bundle) as T
}
}
}
| 23
|
Kotlin
|
554
| 38
|
8c8de602274b0132fc5d22b394a2c47fcd0bf2eb
| 662
|
apps-android-wikipedia-envoy
|
Apache License 2.0
|
designernews/src/test/java/io/plaidapp/designernews/ui/story/StoryViewModelTest.kt
|
PatilShreyas
| 191,734,900
| false
| null |
/*
* Copyright 2018 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.ui.story
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.stories.model.Story
import io.plaidapp.core.designernews.data.stories.model.StoryLinks
import io.plaidapp.core.designernews.domain.model.Comment
import io.plaidapp.designernews.domain.GetCommentsWithRepliesAndUsersUseCase
import io.plaidapp.designernews.domain.GetStoryUseCase
import io.plaidapp.designernews.domain.PostReplyUseCase
import io.plaidapp.designernews.domain.PostStoryCommentUseCase
import io.plaidapp.designernews.domain.UpvoteCommentUseCase
import io.plaidapp.designernews.domain.UpvoteStoryUseCase
import io.plaidapp.designernews.flattendCommentsWithReplies
import io.plaidapp.designernews.reply1
import io.plaidapp.test.shared.LiveDataTestUtil
import io.plaidapp.test.shared.provideFakeCoroutinesDispatcherProvider
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import java.io.IOException
import java.util.Date
import java.util.GregorianCalendar
/**
* Tests for [StoryViewModel] mocking all the dependencies.
*/
class StoryViewModelTest {
// Executes tasks in the Architecture Components in the same thread
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private val userId = 5L
private val storyId = 1345L
private val commentId = 999L
private val createdDate: Date = GregorianCalendar(2018, 1, 13).time
private val commentIds = listOf(11L, 12L)
private val storyLinks = StoryLinks(
user = userId,
comments = commentIds,
upvotes = emptyList(),
downvotes = emptyList()
)
private val testStory = Story(
id = storyId,
title = "Plaid 2.0 was released",
createdAt = createdDate,
userId = userId,
links = storyLinks
)
private val getStory: GetStoryUseCase = mock()
private val postStoryComment: PostStoryCommentUseCase = mock()
private val postComment: PostReplyUseCase = mock()
private val getCommentsWithRepliesAndUsers: GetCommentsWithRepliesAndUsersUseCase = mock()
private val upvoteStory: UpvoteStoryUseCase = mock()
private val upvoteComment: UpvoteCommentUseCase = mock()
@Test
fun loadStory_existsInRepo() {
// Given that the repo successfully returns the requested story
// When the view model is constructed
val viewModel = withViewModel()
// Then the story is present
assertNotNull(viewModel.story)
}
@Test(expected = IllegalStateException::class)
fun loadStory_notInRepo() {
// Given that the repo fails to return the requested story
whenever(getStory(storyId)).thenReturn(Result.Error(IllegalStateException()))
// When the view model is constructed
StoryViewModel(
storyId,
getStory,
postStoryComment,
postComment,
getCommentsWithRepliesAndUsers,
upvoteStory,
upvoteComment,
provideFakeCoroutinesDispatcherProvider()
)
// Then it throws
}
@Test
fun commentsRequested_whenViewModelCreated() {
// Given that the repo successfully returns the requested story
// When the view model is constructed
val viewModel = withViewModel()
// Then the correct UI model is created
val event = LiveDataTestUtil.getValue(viewModel.uiModel)
assertEquals(event!!.comments, flattendCommentsWithReplies)
}
@Test
fun upvoteStory_whenUpvoteSuccessful() = runBlocking {
// Given that the use case responds with success
whenever(upvoteStory(storyId)).thenReturn(Result.Success(Unit))
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Unit>? = null
// When upvoting a story
viewModel.storyUpvoteRequested(storyId) { result = it }
// Then the result is successful
assertEquals(Result.Success(Unit), result)
}
@Test
fun upvoteStory_whenUpvoteFailed() = runBlocking {
// Given that the use case responds with error
val response = Result.Error(IOException("Error upvoting"))
whenever(upvoteStory(storyId)).thenReturn(response)
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Unit>? = null
// When upvoting a story
viewModel.storyUpvoteRequested(storyId) { result = it }
// Then the result is an error
assertTrue(result is Result.Error)
}
@Test
fun upvoteComment_whenUpvoteSuccessful() = runBlocking {
// Given that the use case responds with success
whenever(upvoteComment(commentId))
.thenReturn(Result.Success(Unit))
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Unit>? = null
// When upvoting a comment
viewModel.commentUpvoteRequested(commentId) { result = it }
// Then the result is successful
assertEquals(Result.Success(Unit), result)
}
@Test
fun upvoteComment_whenUpvoteFailed() = runBlocking {
// Given that the use case responds with error
val response = Result.Error(IOException("Error upvoting"))
whenever(upvoteComment(commentId)).thenReturn(response)
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Unit>? = null
// When upvoting a comment
viewModel.commentUpvoteRequested(commentId) { result = it }
// Then the result is an error
assertTrue(result is Result.Error)
}
@Test
fun commentReplyRequested_withSuccess() = runBlocking {
// Given that the comment reply is posted successfully
val expected = Result.Success(reply1)
whenever(postComment.invoke(reply1.body, reply1.parentCommentId!!)).thenReturn(expected)
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Comment>? = null
// When posting a comment reply
viewModel.commentReplyRequested(reply1.body, reply1.parentCommentId!!) {
result = it
}
// Then the result is the expected one
assertEquals(expected, result)
}
@Test
fun commentReplyRequested_withError() = runBlocking {
// Given that the comment reply is posted with error
val expected = Result.Error(IOException("Error"))
whenever(postComment.invoke(reply1.body, reply1.parentCommentId!!)).thenReturn(expected)
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Comment>? = null
// When posting a comment reply
viewModel.commentReplyRequested(reply1.body, reply1.parentCommentId!!) {
result = it
}
// Then the result is the expected one
assertEquals(expected, result)
}
@Test
fun storyReplyRequested_withSuccess() = runBlocking {
// Given that the comment reply is posted successfully
val expected = Result.Success(reply1)
whenever(postStoryComment.invoke(reply1.body, storyId))
.thenReturn(expected)
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Comment>? = null
// When posting a comment reply
viewModel.storyReplyRequested(reply1.body) { result = it }
// Then the result is the expected one
assertEquals(expected, result)
}
@Test
fun storyReplyRequested_withError() = runBlocking {
// Given that the comment reply is posted with error
val expected = Result.Error(IOException("Error"))
whenever(postStoryComment.invoke(reply1.body, storyId)).thenReturn(expected)
// And the view model is constructed
val viewModel = withViewModel()
var result: Result<Comment>? = null
// When posting a comment reply
viewModel.storyReplyRequested(reply1.body) { result = it }
// Then the result is the expected one
assertEquals(expected, result)
}
private fun withViewModel(): StoryViewModel {
whenever(getStory(storyId)).thenReturn(Result.Success(testStory))
runBlocking {
whenever(getCommentsWithRepliesAndUsers(commentIds)).thenReturn(
Result.Success(
flattendCommentsWithReplies
)
)
}
return StoryViewModel(
storyId,
getStory,
postStoryComment,
postComment,
getCommentsWithRepliesAndUsers,
upvoteStory,
upvoteComment,
provideFakeCoroutinesDispatcherProvider()
)
}
}
| 1
| null |
0
| 2
|
91f9cf247c1940a0323fd1f6cde84e63f4191687
| 9,737
|
plaid
|
Apache License 2.0
|
shared/feature-y/src/main/java/com/wackaloon/feature_y/FeatureYActivity.kt
|
Wackaloon
| 353,394,945
| false
| null |
package com.wackaloon.feature_y
import android.os.Bundle
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import com.wackaloon.common_core.ErrorNavigator
import com.wackaloon.feature_y.dagger.FeatureYComponent
import javax.inject.Inject
class FeatureYActivity : AppCompatActivity() {
@Inject
lateinit var repository: FeatureYRepository
@Inject
lateinit var errorNavigator: ErrorNavigator
override fun onCreate(savedInstanceState: Bundle?) {
injectDependencies()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feature_y)
setSupportActionBar(findViewById(R.id.toolbar))
findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view ->
errorNavigator.navigateToErrorScreen()
}
}
override fun onStart() {
super.onStart()
repository.fetchData()
}
private fun injectDependencies() {
FeatureYComponent.get(this).inject(this)
}
}
| 0
|
Kotlin
|
0
| 1
|
a65bdff30af9c34c843a0e77b8257beb1d5a57ef
| 1,113
|
megamonolith
|
MIT License
|
maskinporten-client/src/main/kotlin/no/ks/fiks/maskinporten/observability/MaskinportenKlientObservability.kt
|
ks-no
| 157,221,514
| false
|
{"Kotlin": 57762, "Java": 45417}
|
package no.ks.fiks.maskinporten.observability
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder
import org.apache.hc.client5.http.io.HttpClientConnectionManager
/**
* Interface for observability of MaskinportenKlient
* Implementations of this interface can be used to add observability to MaskinportenKlient
* @see MicrometerMaskinportenKlientObservability
* @see DropwizardMetricsMaskinportenKlientObservability
*/
interface MaskinportenKlientObservability {
fun createObservableHttpClientBuilder(): HttpClientBuilder
fun addObservabilityToConnectionManager(httpClientConnectionManager: HttpClientConnectionManager): HttpClientConnectionManager
}
| 7
|
Kotlin
|
3
| 7
|
7d0d613f2afde7969bd26df9e4ab59edf1243105
| 680
|
fiks-maskinporten
|
MIT License
|
backend/bot-service-master/src/main/kotlin/ssilvalucas/botservice/mapper/RegisterExpenseMapper.kt
|
ertprs
| 323,188,779
| false
|
{"CSS": 226007, "Kotlin": 21692, "JavaScript": 20109, "TypeScript": 18275, "Python": 14232, "HTML": 10278, "Shell": 344}
|
package ssilvalucas.botservice.mapper
import org.springframework.stereotype.Component
import ssilvalucas.botservice.model.entity.RegisterExpense
import ssilvalucas.botservice.web.dto.request.RegisterExpenseRequest
@Component
class RegisterExpenseMapper {
fun requestToEntity(driver: String, request: RegisterExpenseRequest): RegisterExpense {
return RegisterExpense(
phoneNumber = driver,
cost = request.cost,
category = request.category
)
}
}
| 0
| null |
0
| 0
|
cdfaa30c6737a4db14cab22816ad5778e3c0f2f0
| 518
|
hackathon-ccr
|
Apache License 2.0
|
app/src/main/java/com/chrismagaa/simple_lector_rss/ui/feed/news/NewsFragment.kt
|
chrismagaa
| 539,040,787
| false
|
{"Kotlin": 43230}
|
package com.chrismagaa.simple_lector_rss.ui.feed.news
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.core.view.MenuProvider
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.chrismagaa.simple_lector_rss.R
import com.chrismagaa.simple_lector_rss.databinding.FragmentFeedBinding
import com.chrismagaa.simple_lector_rss.domain.model.Post
import com.chrismagaa.simple_lector_rss.ui.details.DetailsActivity
import com.chrismagaa.simple_lector_rss.ui.feed.FeedViewModel
import com.chrismagaa.simple_lector_rss.ui.feed.PostAdapter
import com.chrismagaa.simple_lector_rss.ui.settings.SettingsActivity
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class NewsFragment : Fragment() {
private val vmFeed: FeedViewModel by activityViewModels()
private var _binding: FragmentFeedBinding? = null
private val binding get() = _binding!!
private lateinit var adapter: PostAdapter
private var feed: List<Post> = ArrayList()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentFeedBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupMenu()
setuAdapter()
initObservers()
}
private fun initObservers() {
vmFeed.loadingNewPosts.observe(viewLifecycleOwner) {
if (it) {
binding.progressBarFeed.visibility = View.VISIBLE
binding.list.visibility = View.GONE
} else {
binding.progressBarFeed.visibility = View.GONE
binding.list.visibility = View.VISIBLE
}
}
vmFeed.newPosts.observe(viewLifecycleOwner) {
if(it.isNotEmpty()){
feed = it
adapter.setData(it)
}
}
}
private fun setuAdapter() {
adapter = PostAdapter ({
goToDetailsActivity(it)
}) {post, position ->
vmFeed.updatePost(post)
adapter.updateItem(position)
}
binding.list.adapter = adapter
binding.list.layoutManager = LinearLayoutManager(requireContext())
}
private fun setupMenu() {
requireActivity().addMenuProvider(object: MenuProvider{
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu_main, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.action_refresh -> {
vmFeed.getNewPosts()
true
}
R.id.action_settings -> {
goToSettingsActivity()
true
}
else -> false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
private fun goToSettingsActivity(){
val intent = Intent(requireContext(), SettingsActivity::class.java).apply {
putExtra(SettingsActivity.EXTRA_MODE_THEME, vmFeed.modeTheme.value)
putExtra(SettingsActivity.EXTRA_FEEDS_ACTIVATED, Gson().toJson(vmFeed.getActivatedRssHashMap()))
}
startActivity(intent)
}
private fun goToDetailsActivity(item: Post) {
val intent = Intent(requireActivity(), DetailsActivity::class.java).apply {
putExtra(DetailsActivity.EXTRA_ITEM, item)
}
startActivity(intent)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
f7c3c80603ca8b44fa2e811b6a2e64e1babbc5ae
| 4,012
|
wYOBWdZelywKFXZWiupw
|
MIT License
|
wallet-sdk/src/main/java/io/arcblock/walletkit/utils/ArcNumberUtils.kt
|
ArcBlock
| 470,418,674
| false
| null |
package io.arcblock.walletkit.utils
import io.arcblock.walletkit.utils.ArcInputCheckUtils.getMinScale
import java.math.BigDecimal
import java.math.BigInteger
import java.math.RoundingMode.DOWN
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale
import kotlin.math.pow
/**
* Created by Nate on 2018/12/5
*/
object ArcNumberUtils {
var symbolsEN_US: DecimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.US)
fun formatNumberForTokenDisplay(number: String?, decimals: Int): String {
val numberDecimal = string2BigDecimalWithScale(number ?: "0", decimals)
return formatNumberForTokenDisplay(numberDecimal)
}
fun formatNumberForTokenDisplay(number: BigInteger, decimals: Int): String {
val numberDecimal = string2BigDecimalWithScale(number, decimals)
return formatNumberForTokenDisplay(numberDecimal)
}
@JvmStatic
fun formatNumberForTokenDisplay(number: BigDecimal?): String {
if (number == null) {
return "0"
}
val nf = DecimalFormat("#,##0.000000", symbolsEN_US)
nf.roundingMode = DOWN
return removeTheEndZero(nf.format(number))
}
/**
* ***********************************************************
*/
/**
* ********** 格式化 token number 为法币展示用的样式 ******************
*/
fun formatNumberForFiatDisplay(number: String): String {
val numberBigDecimal = try {
BigDecimal(number)
} catch (e: Exception) {
BigDecimal.ZERO
}
return formatNumberForFiatDisplay(numberBigDecimal)
}
fun formatNumberForFiatDisplay(number: BigDecimal): String {
val format = "#,##0.00"
val nf = DecimalFormat(format, symbolsEN_US)
nf.roundingMode = DOWN
return nf.format(number)
}
/**
* ***********************************************************
*/
/**
* ********** 格式化 token number 为输入框用的格式 ******************
*/
fun formatNumberForSend(number: String, decimals: Int): String {
val numberDecimal = string2BigDecimalWithScale(number, decimals)
return formatNumberForSend(numberDecimal)
}
fun formatNumberForSend(number: BigDecimal, decimals: Int): String {
val numberDecimal = string2BigDecimalWithScale(number, decimals)
return formatNumberForSend(numberDecimal)
}
private fun formatNumberForSend(number: BigDecimal): String {
val format = "##0.000000"
val nf = DecimalFormat(format, symbolsEN_US)
nf.roundingMode = DOWN
return removeTheEndZero(nf.format(number))
}
/**
* ***********************************************************
*/
/**
* ********** String 类型的数字转换为去除精度的 BigDecimal ******************
*/
fun string2BigDecimalWithOutScale(number: String, decimals: Int): BigDecimal {
return try {
BigDecimal(number).divide(BigDecimal.valueOf(10.0.pow(decimals.toDouble())))
} catch (e: Exception) {
BigDecimal.ZERO
}
}
/**
* ********** BigInteger 类型的数字转换为去除精度的 BigDecimal ******************
*/
fun string2BigDecimalWithOutScale(number: BigInteger, decimals: Int): BigDecimal {
return try {
BigDecimal(number).divide(BigDecimal.valueOf(10.0.pow(decimals.toDouble())))
} catch (e: Exception) {
BigDecimal.ZERO
}
}
/**
* ********** String 类型的数字转为去除精度的 BigDecimal 并截取一定的小数点位数 ******************
*/
@JvmStatic
fun string2BigDecimalWithScale(number: String?, decimals: Int): BigDecimal {
// 确保构建 BigDecimal 能成功,不成功,默认为 0
val numberBigDecimal = try {
BigDecimal(number)
} catch (e: Exception) {
BigDecimal.ZERO
}
return string2BigDecimalWithScale(numberBigDecimal, decimals)
}
/**
* ********** BigInteger 类型的数字转为去除精度的 BigDecimal 并截取一定的小数点位数 ******************
*/
fun string2BigDecimalWithScale(number: BigInteger?, decimals: Int): BigDecimal {
// 确保构建 BigDecimal 能成功,不成功,默认为 0
val numberBigDecimal = try {
BigDecimal(number)
} catch (e: Exception) {
BigDecimal.ZERO
}
return string2BigDecimalWithScale(numberBigDecimal, decimals)
}
/**
* ********** BigDecimal 去除精度并截取一定的小数点位数 ******************
*/
fun string2BigDecimalWithScale(number: BigDecimal, decimals: Int): BigDecimal {
return try {
val bigDecimalNumber = number.divide(BigDecimal.valueOf(10.0.pow(decimals)))
// 默认截取 6 位,如果 decimals 小于 6,则取 decimals
bigDecimalNumber.setScale(getMinScale(decimals), BigDecimal.ROUND_DOWN)
} catch (e: Exception) {
BigDecimal.ZERO
}
}
fun string2Int(number: String): Int {
return if (isEmpty(number)) {
0
} else try {
number.toInt()
} catch (e: Exception) {
0
}
}
fun stringToBigDecimal(number: String?): BigDecimal {
return if (isEmpty(number)) {
BigDecimal.ZERO
} else try {
BigDecimal(number)
} catch (e: Exception) {
BigDecimal.ZERO
}
}
//big integer to Uint64
fun unsigned(b: BigInteger): BigInteger {
if (b.signum() >= 0) {
return b
}
val a1 = b.toByteArray()
val a2 = ByteArray(a1.size + 1)
a2[0] = 0
System.arraycopy(a1, 0, a2, 1, a1.size)
return BigInteger(a2)
}
private fun removeTheEndZero(input: String): String {
var result = ""
result = if (!isEmpty(input)) {
input
} else {
"0"
}
while (result.endsWith("0")) {
result = result.substring(0, result.length - 1)
}
if (result.endsWith(".")) {
result = result.substring(0, result.length - 1)
}
return result
}
fun checkCanParseStringToBigDecimal(number: String?): Boolean {
return try {
BigDecimal(number)
true
} catch (e: Exception) {
false
}
}
fun checkCanParseStringToInt(number: String?): Boolean {
return try {
number!!.toInt()
true
} catch (e: Exception) {
false
}
}
fun isEmpty(str: CharSequence?): Boolean {
return str == null || str.isEmpty()
}
}
| 3
|
Kotlin
|
0
| 0
|
032105bd4ed9bbe4b484a3458eca67a875139f6f
| 5,901
|
did-wallet-sdk-android
|
Apache License 2.0
|
src/org/jetbrains/r/roxygen/usage/RoxygenUsageTypeProvider.kt
|
JetBrains
| 214,212,060
| false
|
{"Kotlin": 2657599, "Java": 558927, "R": 37082, "Lex": 14307, "HTML": 10063, "Rez": 70, "Rebol": 47}
|
/*
* Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.jetbrains.r.roxygen.usage
import com.intellij.psi.PsiElement
import com.intellij.usages.impl.rules.UsageType
import com.intellij.usages.impl.rules.UsageTypeProvider
import org.jetbrains.r.RBundle
import org.jetbrains.r.roxygen.RoxygenLanguage
class RoxygenUsageTypeProvider : UsageTypeProvider {
override fun getUsageType(element: PsiElement): UsageType? {
return if (element.language === RoxygenLanguage.INSTANCE) ROXYGEN_DOCUMENTATION
else null
}
companion object {
val ROXYGEN_DOCUMENTATION by lazy { UsageType(RBundle.message("usage.in.roxygen")) }
}
}
| 2
|
Kotlin
|
13
| 62
|
8b4f3aac10693cbfb5841f0afff46338bffbc50e
| 740
|
Rplugin
|
Apache License 2.0
|
app/src/main/java/com/lee/leewanandroid/ui/knowledge/KnowledgeFragment.kt
|
Mr1ee
| 186,852,345
| false
| null |
package com.lee.leewanandroid.ui.knowledge
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.lee.leewanandroid.R
import com.lee.leewanandroid.entities.article.KnowledgeTreeData
import com.lee.leewanandroid.ui.base.BaseMvpFragment
import kotlinx.android.synthetic.main.fragment_konwledge_page.*
import kotlinx.android.synthetic.main.fragment_konwledge_page.view.*
class KnowledgeFragment : BaseMvpFragment<Contract.View, KnowledgePresenter>(), Contract.View {
companion object {
private var TAG = KnowledgeFragment::class.java.simpleName
fun newInstance() = KnowledgeFragment()
}
override val mPresenter: KnowledgePresenter = KnowledgePresenter(this)
private lateinit var knowledgeAdapter: KnowledgeAdapter
override fun getLayoutId(): Int = R.layout.fragment_konwledge_page
override fun initView(view: View) {
view.apply {
mPresenter.getKnowledgeTreeData()
knowledgeAdapter = KnowledgeAdapter(R.layout.item_knowledge_tree_list, arrayListOf())
knowledgeAdapter.setOnItemClickListener({ adapter, view, position -> })
rv_knowledge_pager.layoutManager = LinearLayoutManager(activity)
rv_knowledge_pager.setHasFixedSize(true)
rv_knowledge_pager.adapter = knowledgeAdapter
}
}
fun jumpToTheTop() {
rv_knowledge_pager.smoothScrollToPosition(0)
}
override fun showKnowledgeTreeData(knowledgeTreeData: List<KnowledgeTreeData>) {
if (knowledgeAdapter.data.size < knowledgeTreeData.size) {
knowledgeAdapter.replaceData(knowledgeTreeData)
}
}
private fun initRefreshLayout() {
smart_refresh_layout.setOnRefreshListener { refreshLayout ->
mPresenter.getKnowledgeTreeData()
refreshLayout.finishRefresh()
}
}
}
| 1
| null |
1
| 1
|
cd2f059083fcaf6b40f264b2a0ba88e545660b39
| 1,880
|
LeeWanAndroid
|
Apache License 2.0
|
Forge/src/main/kotlin/hantonik/atomic/technology/util/ATTooltips.kt
|
Hantonik
| 689,923,057
| false
|
{"Kotlin": 97427, "Batchfile": 40}
|
package hantonik.atomic.technology.util
import hantonik.atomic.technology.AtomicTechnology
import net.minecraft.network.chat.Component
import net.minecraft.network.chat.MutableComponent
object ATTooltips {
// MENU
val CRUSHER: Component = this.getMenuTooltip("crusher")
// BUTTON
val ALWAYS_ACTIVE: Component = this.getTooltip("redstone_control_always_active");
val SIGNAL_REQUIRED: Component = this.getTooltip("redstone_control_signal_required");
val NEVER_ACTIVE: Component = this.getTooltip("redstone_control_never_active");
private fun getMenuTooltip(key: String) = Component.translatable("menu.${AtomicTechnology.MOD_ID}.$key")
private fun getTooltip(key: String) = Component.translatable("tooltip.${AtomicTechnology.MOD_ID}.$key")
private fun getArgsTooltip(key: String): (List<Any>) -> MutableComponent = { Component.translatable("tooltip.${AtomicTechnology.MOD_ID}.$key", *it.toTypedArray()) }
}
| 0
|
Kotlin
|
0
| 0
|
53fbeed6938ebe0e630cae05491d97a59acb716a
| 945
|
AtomicTechnology
|
MIT License
|
compiler/testData/diagnostics/tests/declarationChecks/multiDeclarations/DoubleDeclForLoop.kt
|
udalov
| 10,645,710
| false
| null |
class A {
fun component1() = 1
fun component2() = 1
}
class C {
fun iterator(): Iterator<A> = null!!
}
fun test() {
for ((x, y) in C()) {
}
}
| 0
| null |
1
| 6
|
3958b4a71d8f9a366d8b516c4c698aae80ecfe57
| 165
|
kotlin-objc-diploma
|
Apache License 2.0
|
admin/src/main/java/com/sampah/admin/ui/settingHarga/SettingHargaAdapter.kt
|
YofhiFauda
| 761,065,041
| false
|
{"Kotlin": 164145}
|
package com.sampah.admin.ui.settingHarga
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sampah.admin.R
import com.sampah.admin.data.model.SettingHargaModel
import com.sampah.admin.ui.penjemputanSampah.detail.DetailPenjemputanSampahActivity
class SettingHargaAdapter(
private val settingHarga: List<SettingHargaModel>,
): RecyclerView.Adapter<SettingHargaAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val subtitleJenisSampah: TextView = itemView.findViewById(R.id.subtitle_jenisSampah)
val subtitleHargaSampah: TextView = itemView.findViewById(R.id.subtitle_hargaSampah)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_setting_harga, parent, false)
return ViewHolder(view)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val settingHarga = settingHarga[position]
holder.subtitleJenisSampah.text = settingHarga.jenis_sampah
holder.subtitleHargaSampah.text = "Rp ${settingHarga.harga_sampah}"
holder.itemView.setOnClickListener {
holder.itemView.setOnClickListener {
val intent = Intent(it.context, AddEditSettingHargaActivity::class.java).apply {
putExtra("harga_sampah", settingHarga.harga_sampah)
putExtra("jenis_sampah", settingHarga.jenis_sampah)
putExtra("settingHargaId", settingHarga.settingHargaId)
putExtra("sampahId", settingHarga.sampahId)
}
it.context.startActivity(intent)
}
}
}
// @SuppressLint("SetTextI18n")
// override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// val settingHarga = settingHarga[position]
// holder.subtitleJenisSampah.text = settingHarga.jenis_sampah
// holder.subtitleHargaSampah.text = "Rp ${settingHarga.harga_sampah}"
// holder.itemView.setOnClickListener {
// holder.itemView.setOnClickListener {
// val intent = Intent(it.context, AddEditSettingHargaActivity::class.java)
// intent.putExtra(AddEditSettingHargaActivity.EXTRA_HARGA, settingHarga)
// intent.putExtra(AddEditSettingHargaActivity.EXTRA_SETTING_HARGA_ID, settingHarga.sampahId) // Pass the document ID
// it.context.startActivity(intent)
// }
// }
// }
override fun getItemCount() = settingHarga.size
}
| 0
|
Kotlin
|
0
| 2
|
0b3f92ef3a082fbff56635e26d3bcdb8e6da0da6
| 2,848
|
Bank-Sampah-Digital
|
MIT License
|
app/src/main/java/com/example/firestore/di/ReferenceQualifiers.kt
|
alisoleimani-android
| 293,226,022
| false
| null |
package com.example.firestore.di
import javax.inject.Qualifier
/**
* We should create a qualifier for each Collection because
* we need to make difference between them for injection.
*/
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class PersonsReference
| 0
|
Kotlin
|
0
| 0
|
a84e1aeb9deaf4654625768086c94986188946ca
| 275
|
CleanFirestore
|
MIT License
|
src/test/kotlin/com/ort/howlingwolf/infrastructure/datasource/village/VillageDataSourceTest.kt
|
h-orito
| 176,481,255
| false
| null |
package com.ort.howlingwolf.infrastructure.datasource.village
import com.ort.dbflute.allcommon.CDef
import com.ort.dbflute.exbhv.*
import com.ort.dbflute.exentity.VillagePlayer
import com.ort.howlingwolf.HowlingWolfTest
import com.ort.howlingwolf.domain.model.camp.Camp
import com.ort.howlingwolf.domain.model.message.MessageType
import com.ort.howlingwolf.domain.model.skill.Skill
import com.ort.howlingwolf.domain.model.skill.SkillRequest
import com.ort.howlingwolf.domain.model.village.Village
import com.ort.howlingwolf.domain.model.village.VillageDay
import com.ort.howlingwolf.domain.model.village.VillageDays
import com.ort.howlingwolf.domain.model.village.VillageStatus
import com.ort.howlingwolf.domain.model.village.blacklist.BlacklistPlayers
import com.ort.howlingwolf.domain.model.village.participant.VillageParticipant
import com.ort.howlingwolf.domain.model.village.participant.VillageParticipants
import com.ort.howlingwolf.domain.model.village.participant.coming_out.ComingOuts
import com.ort.howlingwolf.domain.model.village.setting.*
import com.ort.howlingwolf.dummy.DummyDomainModelCreator
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
@RunWith(SpringRunner::class)
@SpringBootTest
@Transactional
class VillageDataSourceTest : HowlingWolfTest() {
// ===================================================================================
// Attribute
// =========
@Autowired
lateinit var villageDataSource: VillageDataSource
@Autowired
lateinit var villageBhv: VillageBhv
@Autowired
lateinit var villagePlayerBhv: VillagePlayerBhv
@Autowired
lateinit var villageSettingBhv: VillageSettingBhv
@Autowired
lateinit var messageRestrictionBhv: MessageRestrictionBhv
@Autowired
lateinit var villageDayBhv: VillageDayBhv
// ===================================================================================
// Test
// =========
@Test
fun test_registerVillage() {
// ## Arrange ##
val createPlayerId = 1
val startDatetime = LocalDateTime.now().plusDays(2L).withNano(0)
val interval = 24 * 60 * 60
val organization = "狼狼狼狂占霊狩村村村村村村村村村"
val paramVillage = Village.createAutoGeneratedForRegister(
playerId = createPlayerId,
organization = organization,
startDatetime = startDatetime,
silentHours = null,
availableDummySkill = false,
forBeginner = false,
canSkillRequest = false
)
// ## Act ##
val registeredVillage = villageDataSource.registerVillage(paramVillage)
val villageId = registeredVillage.id
// ## Assert ##
// village
val village = villageBhv.selectByPK(villageId).get()
assertThat(village.villageDisplayName).endsWith("村")
assertThat(village.createPlayerId).isEqualTo(createPlayerId)
assertThat(village.villageStatusCodeAsVillageStatus).isEqualTo(CDef.VillageStatus.プロローグ)
assertThat(village.epilogueDay as Int?).isNull()
assertThat(village.winCampCodeAsCamp).isNull()
// village_day
val villageDayList = villageDayBhv.selectList { it.query().setVillageId_Equal(villageId) }
assertThat(villageDayList.size).isEqualTo(1)
assertThat(villageDayList.first()).satisfies { firstDay ->
assertThat(firstDay.day).isEqualTo(0)
assertThat(firstDay.noonnightCodeAsNoonnight).isEqualTo(CDef.Noonnight.昼)
assertThat(firstDay.daychangeDatetime).isEqualTo(startDatetime)
}
// village_settings
val settingList = villageSettingBhv.selectList { it.query().setVillageId_Equal(villageId) }
assertThat(settingList).isNotEmpty
assertThat(settingList.first { it.isVillageSettingItemCodeキャラクターグループid }.villageSettingText).isEqualTo("1")
assertThat(settingList.first { it.isVillageSettingItemCodeコミット可能か }.villageSettingText).isEqualTo("1")
assertThat(settingList.first { it.isVillageSettingItemCodeダミーキャラid }.villageSettingText).isEqualTo("1")
assertThat(settingList.first { it.isVillageSettingItemCode役職希望可能か }.villageSettingText).isEqualTo("1")
assertThat(settingList.first { it.isVillageSettingItemCode更新間隔秒 }.villageSettingText).isEqualTo(interval.toString())
assertThat(settingList.first { it.isVillageSettingItemCode最低人数 }.villageSettingText).isEqualTo(organization.length.toString())
assertThat(settingList.first { it.isVillageSettingItemCode最大人数 }.villageSettingText).isEqualTo(organization.length.toString())
assertThat(settingList.first { it.isVillageSettingItemCode突然死ありか }.villageSettingText).isEqualTo("1")
assertThat(settingList.first { it.isVillageSettingItemCode記名投票か }.villageSettingText).isEqualTo("0")
assertThat(settingList.first { it.isVillageSettingItemCode開始予定日時 }.villageSettingText).isNotNull()
assertThat(settingList.first { it.isVillageSettingItemCode期間形式 }.villageSettingText).isEqualTo(CDef.Term.長期.code())
// message_restriction
val restrictList = messageRestrictionBhv.selectList { it.query().setVillageId_Equal(villageId) }
assertThat(restrictList.size).isEqualTo(4)
assertThat(restrictList.first { it.isMessageTypeCode人狼の囁き }).satisfies { restrict ->
assertThat(restrict.messageMaxLength).isEqualTo(200)
assertThat(restrict.messageMaxNum).isEqualTo(40)
}
assertThat(restrictList.first { it.isMessageTypeCode通常発言 }).satisfies { restrict ->
assertThat(restrict.messageMaxLength).isEqualTo(200)
assertThat(restrict.messageMaxNum).isEqualTo(20)
}
assertThat(restrictList.first { it.isMessageTypeCode死者の呻き }).satisfies { restrict ->
assertThat(restrict.messageMaxLength).isEqualTo(200)
assertThat(restrict.messageMaxNum).isEqualTo(40)
}
assertThat(restrictList.first { it.isMessageTypeCode独り言 }).satisfies { restrict ->
assertThat(restrict.messageMaxLength).isEqualTo(200)
assertThat(restrict.messageMaxNum).isEqualTo(100)
}
}
@Test
fun test_findVillages() {
// ## Arrange ##
val village1 = villageDataSource.registerVillage(DummyDomainModelCreator.createDummyVillageRegisterParam())
insertVillagePlayer(village1.id, createDummyVillageParticipantParam())
insertVillagePlayer(village1.id, createDummyVillageParticipantParam())
insertVillagePlayer(village1.id, createDummyVillageParticipantParam())
val village2 = villageDataSource.registerVillage(DummyDomainModelCreator.createDummyVillageRegisterParam())
insertVillagePlayer(village2.id, createDummyVillageParticipantParam())
insertVillagePlayer(village2.id, createDummyVillageParticipantParam())
insertVillagePlayer(village2.id, createDummyVillageParticipantParam())
val village3 = villageDataSource.registerVillage(DummyDomainModelCreator.createDummyVillageRegisterParam())
insertVillagePlayer(village3.id, createDummyVillageParticipantParam())
insertVillagePlayer(village3.id, createDummyVillageParticipantParam())
insertVillagePlayer(village3.id, createDummyVillageParticipantParam())
// ## Act ##
val villages = villageDataSource.findVillages()
// ## Assert ##
assertThat(villages.list.size).isEqualTo(3)
assertThat(villages.list.first().participant.count).isEqualTo(3)
}
@Test
fun test_findVillage() {
// ## Arrange ##
val param = DummyDomainModelCreator.createDummyVillageRegisterParam()
// ## Act ##
var village = villageDataSource.registerVillage(param)
insertVillagePlayer(village.id, createDummyVillageParticipantParam())
insertVillagePlayer(village.id, createDummyVillageParticipantParam())
insertVillagePlayer(village.id, createDummyVillageParticipantParam())
village = villageDataSource.findVillage(village.id)
// ## Assert ##
assertThat(village.creatorPlayerId).isEqualTo(param.creatorPlayerId)
assertThat(village.status.toCdef()).isEqualTo(param.status.toCdef())
assertThat(village.winCamp).isNull()
assertThat(village.setting).satisfies { settings ->
assertThat(settings.capacity.min).isEqualTo(param.setting.capacity.min)
assertThat(settings.capacity.max).isEqualTo(param.setting.capacity.max)
assertThat(settings.charachip.charachipId).isEqualTo(param.setting.charachip.charachipId)
assertThat(settings.charachip.dummyCharaId).isEqualTo(param.setting.charachip.dummyCharaId)
assertThat(settings.time.termType).isEqualTo(param.setting.time.termType)
assertThat(settings.time.dayChangeIntervalSeconds).isEqualTo(param.setting.time.dayChangeIntervalSeconds)
assertThat(settings.time.startDatetime.truncatedTo(ChronoUnit.SECONDS)).isEqualTo(
param.setting.time.startDatetime.truncatedTo(
ChronoUnit.SECONDS
)
)
assertThat(settings.organizations.organization.toString()).isEqualTo(param.setting.organizations.organization.toString())
assertThat(settings.rules).satisfies { rules ->
assertThat(rules.availableCommit).isEqualTo(param.setting.rules.availableCommit)
assertThat(rules.availableSkillRequest).isEqualTo(param.setting.rules.availableSkillRequest)
assertThat(rules.availableSpectate).isEqualTo(param.setting.rules.availableSpectate)
assertThat(rules.availableSuddenlyDeath).isEqualTo(param.setting.rules.availableSuddenlyDeath)
assertThat(rules.openSkillInGrave).isEqualTo(param.setting.rules.openSkillInGrave)
assertThat(rules.openVote).isEqualTo(param.setting.rules.openVote)
assertThat(rules.visibleGraveMessage).isEqualTo(param.setting.rules.visibleGraveMessage)
assertThat(rules.messageRestrict.restrictList.size).isEqualTo(param.setting.rules.messageRestrict.restrictList.size)
}
assertThat(settings.password.joinPassword).isEqualTo(param.setting.password.joinPassword)
}
assertThat(village.winCamp).isNull()
assertThat(village.participant.count).isEqualTo(3)
assertThat(village.spectator.count).isEqualTo(0)
assertThat(village.day.dayList.size).isEqualTo(1)
}
@Test
fun test_updateDifference() {
// ## Arrange ##
val before = DummyDomainModelCreator.createDummyVillageRegisterParam()
val beforeVillage = villageDataSource.registerVillage(before)
val after = createDummyUpdateVillageParam().copy(id = beforeVillage.id)
// ## Act ##
val village = villageDataSource.updateDifference(beforeVillage, after)
// ## Assert ##
assertThat(village.name).isEqualTo(after.name)
assertThat(village.creatorPlayerId).isEqualTo(after.creatorPlayerId)
assertThat(village.status.toCdef()).isEqualTo(after.status.toCdef())
assertThat(village.winCamp?.toCdef()).isEqualTo(after.winCamp?.toCdef())
assertThat(village.setting).satisfies { settings ->
assertThat(settings.capacity.min).isEqualTo(after.setting.capacity.min)
assertThat(settings.capacity.max).isEqualTo(after.setting.capacity.max)
assertThat(settings.charachip.charachipId).isEqualTo(after.setting.charachip.charachipId)
assertThat(settings.charachip.dummyCharaId).isEqualTo(after.setting.charachip.dummyCharaId)
assertThat(settings.time.termType).isEqualTo(after.setting.time.termType)
assertThat(settings.time.epilogueDay).isEqualTo(after.setting.time.epilogueDay)
assertThat(settings.time.dayChangeIntervalSeconds).isEqualTo(after.setting.time.dayChangeIntervalSeconds)
assertThat(settings.time.startDatetime).isEqualTo(after.setting.time.startDatetime)
assertThat(settings.organizations.organization.toString()).isEqualTo(after.setting.organizations.organization.toString())
assertThat(settings.rules).satisfies { rules ->
assertThat(rules.availableCommit).isEqualTo(after.setting.rules.availableCommit)
assertThat(rules.availableSkillRequest).isEqualTo(after.setting.rules.availableSkillRequest)
assertThat(rules.availableSpectate).isEqualTo(after.setting.rules.availableSpectate)
assertThat(rules.availableSuddenlyDeath).isEqualTo(after.setting.rules.availableSuddenlyDeath)
assertThat(rules.openSkillInGrave).isEqualTo(after.setting.rules.openSkillInGrave)
assertThat(rules.openVote).isEqualTo(after.setting.rules.openVote)
assertThat(rules.visibleGraveMessage).isEqualTo(after.setting.rules.visibleGraveMessage)
assertThat(rules.messageRestrict.restrictList.any { it.type.toCdef() == CDef.MessageType.通常発言 }).isTrue()
assertThat(rules.messageRestrict.restrictList.none { it.type.toCdef() == CDef.MessageType.人狼の囁き }).isTrue()
assertThat(rules.messageRestrict.restrictList.any { it.type.toCdef() == CDef.MessageType.独り言 }).isTrue()
}
assertThat(settings.password.joinPassword).isEqualTo(after.setting.password.joinPassword)
}
assertThat(village.winCamp?.toCdef()).isEqualTo(after.winCamp?.toCdef())
assertThat(village.participant.count).isEqualTo(2)
assertThat(village.spectator.count).isEqualTo(2)
assertThat(village.day.dayList.size).isEqualTo(2)
}
// ===================================================================================
// Assist Logic
// ============
private fun createDummyUpdateVillageParam(): Village {
return Village(
id = 1,
name = "updated_village_name",
creatorPlayerId = 1,
status = VillageStatus(CDef.VillageStatus.進行中),
setting = VillageSettings(
capacity = PersonCapacity(
min = 12,
max = 14
),
time = VillageTime(
termType = CDef.Term.短期.code(),
prologueStartDatetime = LocalDateTime.now(),
epilogueStartDatetime = LocalDateTime.now().plusDays(4L),
epilogueDay = 4,
startDatetime = LocalDateTime.now().plusDays(2L).withNano(0),
dayChangeIntervalSeconds = 48 * 60 * 60,
silentHours = null
),
charachip = VillageCharachip(
dummyCharaId = 1,
charachipId = 1
),
organizations = VillageOrganizations(),
rules = VillageRules(
openVote = true,
availableSkillRequest = false,
availableSpectate = true,
openSkillInGrave = true,
visibleGraveMessage = true,
availableSuddenlyDeath = false,
availableCommit = true,
messageRestrict = VillageMessageRestricts(
existRestricts = true,
restrictList = listOf(
VillageMessageRestrict(
type = MessageType(CDef.MessageType.通常発言),
count = 40,
length = 400,
line = 20
),
VillageMessageRestrict(
type = MessageType(CDef.MessageType.独り言),
count = 30,
length = 300,
line = 20
)
)
)
),
password = VillagePassword(
joinPasswordRequired = true,
joinPassword = "<PASSWORD>"
)
),
participant = VillageParticipants(
count = 2,
memberList = listOf(
createDummyVillageParticipantParam(),
createDummyVillageParticipantParam().copy(
charaId = 2,
playerId = 2,
skillRequest = SkillRequest(Skill(CDef.Skill.狩人), Skill(CDef.Skill.霊能者))
)
)
),
spectator = VillageParticipants(
count = 2,
memberList = listOf(
createDummyVillageParticipantParam().copy(
charaId = 3,
playerId = 3,
isSpectator = true
),
createDummyVillageParticipantParam().copy(
charaId = 4,
playerId = 4,
isSpectator = true
)
)
),
day = VillageDays(
dayList = listOf(
VillageDay(
id = 1,
day = 0,
noonnight = CDef.Noonnight.昼.code(),
startDatetime = LocalDateTime.now(),
dayChangeDatetime = LocalDateTime.now()
),
VillageDay(
id = 1,
day = 1,
noonnight = CDef.Noonnight.昼.code(),
startDatetime = LocalDateTime.now(),
dayChangeDatetime = LocalDateTime.now().plusDays(2L)
)
)
),
winCamp = Camp(CDef.Camp.人狼陣営),
blacklistPlayers = BlacklistPlayers(listOf())
)
}
private fun createDummyVillageParticipantParam(): VillageParticipant {
return VillageParticipant(
id = 1, // dummy
charaId = 1,
playerId = 1,
dead = null,
isSpectator = false,
isGone = false,
skill = null,
skillRequest = SkillRequest(Skill(CDef.Skill.おまかせ), Skill(CDef.Skill.おまかせ)),
isWin = null,
comingOuts = ComingOuts(),
accessInfos = listOf()
)
}
private fun insertVillagePlayer(
villageId: Int,
participant: VillageParticipant
): Int {
val vp = VillagePlayer()
vp.villageId = villageId
vp.playerId = participant.playerId
vp.charaId = participant.charaId
vp.isDead = false
vp.isSpectator = participant.isSpectator
vp.isGone = false
vp.requestSkillCodeAsSkill = participant.skillRequest.first.toCdef()
vp.secondRequestSkillCodeAsSkill = participant.skillRequest.second.toCdef()
villagePlayerBhv.insert(vp)
return vp.villagePlayerId
}
}
| 1
| null |
1
| 3
|
d87c28e952287ccbc1634c1eee093a5f9f15e472
| 19,998
|
wolf4busy-api
|
MIT License
|
app/src/main/java/com/bogdan/codeforceswatcher/room/RoomController.kt
|
nishitkshah
| 223,720,674
| true
|
{"Kotlin": 103352}
|
package com.bogdan.codeforceswatcher.room
import com.bogdan.codeforceswatcher.features.contests.redux.states.ContestsState
import com.bogdan.codeforceswatcher.features.problems.redux.states.ProblemsState
import com.bogdan.codeforceswatcher.features.users.redux.states.UsersState
import com.bogdan.codeforceswatcher.redux.states.AppState
import com.bogdan.codeforceswatcher.store
import com.bogdan.codeforceswatcher.util.Prefs
import org.rekotlin.StoreSubscriber
object RoomController : StoreSubscriber<AppState> {
fun onAppCreated() {
store.subscribe(this) {
it.skipRepeats { oldState, newState ->
oldState.contests == newState.contests
&& oldState.problems == newState.problems
}
}
}
fun fetchAppState(): AppState {
return AppState(
contests = ContestsState(contests = DatabaseClient.contestDao.getUpcomingContests().reversed()),
users = UsersState(
users = DatabaseClient.userDao.getAll(),
sortType = UsersState.SortType.getSortType(Prefs.get().readSpinnerSortPosition().toInt())
),
problems = ProblemsState(
problems = DatabaseClient.problemsDao.getAll()
)
)
}
override fun newState(state: AppState) {
if (DatabaseClient.contestDao.getUpcomingContests() != state.contests.contests) {
DatabaseClient.contestDao.deleteAll()
DatabaseClient.contestDao.insert(state.contests.contests)
}
if (DatabaseClient.problemsDao.getAll() != state.problems.problems) {
DatabaseClient.problemsDao.deleteAll()
DatabaseClient.problemsDao.insert(state.problems.problems)
}
}
}
| 0
| null |
0
| 0
|
c0a20454eb4d958194fec2436966fb6877336a75
| 1,768
|
codeforces_watcher
|
MIT License
|
src/main/java/com/alcosi/lib/utils/PrepareHexService.kt
|
alcosi
| 698,911,809
| false
|
{"Kotlin": 405550, "Java": 82765, "HTML": 3451, "JavaScript": 509, "CSS": 203}
|
/*
* Copyright (c) 2023 Alcosi Group Ltd. and affiliates.
*
* 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.alcosi.lib.utils
import java.util.regex.Pattern
/**
* The PrepareHexService class provides methods to validate and prepare hexadecimal strings and wallet addresses.
*
* @property walletPattern The pattern used for validating wallet addresses.
* @property hexPattern The pattern used for validating hexadecimal strings.
*/
open class PrepareHexService {
val walletPattern: Pattern = Pattern.compile("^[0-9a-f]{40}$")
val hexPattern: Pattern = Pattern.compile("^([0-9a-f][0-9a-f])+$")
/**
* Checks if the given wallet address is valid.
*
* @param wallet The wallet address to be checked.
* @return `true` if the wallet address is valid, `false` otherwise.
*/
open fun isValidWalletAddress(wallet: String): Boolean {
val prepared = prepareHexInternal(wallet)
return walletPattern.matcher(prepared).matches()
}
/**
* Checks if the given string represents a valid hexadecimal value.
*
* @param hex The string to be checked.
* @return `true` if the string is valid hexadecimal, `false` otherwise.
*/
open fun isValidHex(hex: String): Boolean {
val prepared = prepareHexInternal(hex)
return hexPattern.matcher(prepared).matches()
}
/**
* Prepares a wallet address by validating and formatting it.
*
* @param wallet The wallet address to prepare. Cannot be null.
* @return The prepared wallet address as a string.
* @throws IllegalArgumentException If the wallet address is null or invalid.
*/
open fun prepareAddr(wallet: String?): String {
requireNotNull(wallet) { "Wallet is null" }
val prepared = prepareHexInternal(wallet)
require(walletPattern.matcher(prepared).matches()) { wallet + "is invalid wallet address!" }
return prepared
}
/**
* Prepares a hexadecimal matcher string.
*
* @param hex The hexadecimal string to prepare. Must not be null.
* @return The prepared hexadecimal matcher string.
*
* @throws IllegalArgumentException If the hex string is null.
*/
open fun prepareHexNoMatcher(hex: String?): String {
requireNotNull(hex) { "Hex string is null" }
if (hasHexPrefix(hex) && hex.length == 2) return "00"
return prepareHexInternal(hex)
}
/**
* Prepares a hexadecimal string by removing the prefix, converting it to lowercase, and checking its validity.
*
* @param hex The hexadecimal string to be prepared.
* @return The prepared hexadecimal string.
* @throws IllegalArgumentException if the *hex* parameter is null or if the prepared hexadecimal string is invalid.
*/
open fun prepareHex(hex: String?): String {
requireNotNull(hex) { "Hex string is null" }
val prepared = prepareHexInternal(hex)
require(hexPattern.matcher(prepared).matches()) { hex + "is invalid hex string!" }
return prepared
}
/**
* Prepares the hexadecimal representation of a wallet address by removing the hex prefix and converting to lowercase.
*
* @param wallet The wallet address to prepare.
* @return The prepared hexadecimal representation of the wallet address.
*/
protected open fun prepareHexInternal(wallet: String): String = removeHexPrefix(wallet).lowercase()
/**
* Removes the hex prefix from a given wallet address.
*
* @param wallet The wallet address with or without a hex prefix.
* @return The wallet address without the hex prefix.
*/
protected open fun removeHexPrefix(wallet: String): String {
return if (hasHexPrefix(wallet)) {
wallet.substring(2)
} else {
wallet
}
}
/**
* Checks if the given wallet string has a hex prefix.
*
* @param wallet the wallet string to be checked
* @return true if the wallet string has a hex prefix, false otherwise
*/
protected open fun hasHexPrefix(wallet: String): Boolean {
return wallet.length > 1 && wallet[0] == '0' && (wallet[1] == 'x' || wallet[1] == 'X')
}
}
| 0
|
Kotlin
|
0
| 0
|
4c71ef407342eb8a9b8f7aad8fc2f28d6198366f
| 4,742
|
alcosi_commons_library
|
Apache License 2.0
|
ktorfit-lib-core/src/jvmTest/kotlin/de/jensklingenberg/ktorfit/internal/KtorfitClientTest.kt
|
Foso
| 203,655,484
| false
|
{"Kotlin": 330650, "Ruby": 2354, "Java": 692, "Swift": 345}
|
package de.jensklingenberg.ktorfit.internal
import de.jensklingenberg.ktorfit.Ktorfit
import de.jensklingenberg.ktorfit.TestEngine
import de.jensklingenberg.ktorfit.http.GET
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.request.HttpRequestData
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import io.ktor.utils.io.ByteReadChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
interface ClientTestApi {
@GET("posts")
suspend fun checkCorrectHttpMethod(): String
@GET("http://www.example.com/posts")
suspend fun whenUrlValueContainsBaseUrl_ThenRemoveBaseUrl()
@GET("posts")
fun converterMissing(): Flow<String>
}
class ClientTest {
@Test
fun checkIfCorrectHttpMethodIsSet() {
val testBaseUrl = "http://www.example.com/"
val testRelativeUrl = "posts"
val expectedUrl = testBaseUrl + testRelativeUrl
val expectedHTTPMethod = "GET"
val engine =
object : TestEngine() {
override fun getRequestData(data: HttpRequestData) {
assertEquals(expectedHTTPMethod, data.method.value)
assertEquals(expectedUrl, data.url.toString())
}
}
val ktorfit =
Ktorfit
.Builder()
.baseUrl(testBaseUrl)
.httpClient(HttpClient(engine))
.build()
runBlocking {
ktorfit.create<ClientTestApi>(_ClientTestApiProvider()).checkCorrectHttpMethod()
}
}
@Test
fun throwExceptionWhenResponseConverterMissing() {
try {
val mockResponseContent = """{"ip":"127.0.0.1"}"""
val mockEngine =
MockEngine { _ ->
respond(
content = ByteReadChannel(mockResponseContent),
status = HttpStatusCode.OK,
headers = headersOf(HttpHeaders.ContentType, "application/json"),
)
}
val client = HttpClient(mockEngine) {}
val ktorfit =
Ktorfit
.Builder()
.baseUrl("http://www.test.de/")
.httpClient(client)
.build()
runBlocking {
ktorfit.create<ClientTestApi>(_ClientTestApiProvider()).converterMissing()
}
} catch (exception: Exception) {
assertTrue(exception is IllegalStateException)
assertTrue(exception.message?.startsWith("Add a ResponseConverter") ?: false)
}
}
@Test
fun throwExceptionWhenRequestConverterMissing() {
try {
val ktorfit = Ktorfit.Builder().baseUrl("http://www.test.de/").build()
val converted = KtorfitConverterHelper(ktorfit).convertParameterType("4", String::class, Int::class)
assertEquals(4, converted)
} catch (ex: Exception) {
assertTrue(ex is IllegalStateException)
assertEquals(true, ex.message!!.contains("No RequestConverter found to convert "))
}
}
@Test
fun whenUrlValueContainsFullUrl_ThenRemoveBaseUrl() {
val testBaseUrl = "http://www.example.com/"
val testRelativeUrl = "posts"
val expectedUrl = testBaseUrl + testRelativeUrl
val engine =
object : TestEngine() {
override fun getRequestData(data: HttpRequestData) {
val url = data.url.toString()
assertEquals(expectedUrl, url)
}
}
val ktorfit =
Ktorfit
.Builder()
.baseUrl("http://www.example1.com/")
.httpClient(HttpClient(engine))
.build()
try {
runBlocking {
ktorfit.create<ClientTestApi>(_ClientTestApiProvider()).whenUrlValueContainsBaseUrl_ThenRemoveBaseUrl()
}
} catch (ex: Exception) {
}
}
}
| 32
|
Kotlin
|
40
| 1,558
|
16d3481c25b151e5abb37d7cb2ee4e86c5db9d49
| 4,267
|
Ktorfit
|
Apache License 2.0
|
components/persistence/entity-processor-service-impl/src/main/kotlin/net/corda/entityprocessor/impl/internal/EntityMessageProcessor.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.entityprocessor.impl.internal
import net.corda.crypto.core.parseSecureHash
import net.corda.v5.application.flows.FlowContextPropertyKeys.CPK_FILE_CHECKSUM
import net.corda.data.flow.event.FlowEvent
import net.corda.data.persistence.DeleteEntities
import net.corda.data.persistence.DeleteEntitiesById
import net.corda.data.persistence.EntityRequest
import net.corda.data.persistence.EntityResponse
import net.corda.data.persistence.FindAll
import net.corda.data.persistence.FindEntities
import net.corda.data.persistence.FindWithNamedQuery
import net.corda.data.persistence.MergeEntities
import net.corda.data.persistence.PersistEntities
import net.corda.flow.utils.toMap
import net.corda.messaging.api.processor.DurableProcessor
import net.corda.messaging.api.records.Record
import net.corda.orm.utils.transaction
import net.corda.persistence.common.EntitySandboxService
import net.corda.persistence.common.ResponseFactory
import net.corda.persistence.common.getEntityManagerFactory
import net.corda.persistence.common.getSerializationService
import net.corda.sandboxgroupcontext.CurrentSandboxGroupContext
import net.corda.sandboxgroupcontext.SandboxGroupContext
import net.corda.utilities.MDC_CLIENT_ID
import net.corda.utilities.MDC_EXTERNAL_EVENT_ID
import net.corda.utilities.debug
import net.corda.utilities.withMDC
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.virtualnode.toCorda
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
fun SandboxGroupContext.getClass(fullyQualifiedClassName: String) =
this.sandboxGroup.loadClassFromMainBundles(fullyQualifiedClassName)
/**
* Handles incoming requests, typically from the flow worker, and sends responses.
*
* The [EntityRequest] contains the request and a typed payload.
*
* The [EntityResponse] contains the response or an exception-like payload whose presence indicates
* an error has occurred.
*
* [payloadCheck] is called against each AMQP payload in the result (not the entire Avro array of results)
*/
class EntityMessageProcessor(
private val currentSandboxGroupContext: CurrentSandboxGroupContext,
private val entitySandboxService: EntitySandboxService,
private val responseFactory: ResponseFactory,
private val payloadCheck: (bytes: ByteBuffer) -> ByteBuffer,
) : DurableProcessor<String, EntityRequest> {
private companion object {
val logger = LoggerFactory.getLogger(this::class.java.enclosingClass)
}
override val keyClass = String::class.java
override val valueClass = EntityRequest::class.java
override fun onNext(events: List<Record<String, EntityRequest>>): List<Record<*, *>> {
logger.debug { "onNext processing messages ${events.joinToString(",") { it.key }}" }
return events.mapNotNull { event ->
val request = event.value
if (request == null) {
// We received a [null] external event therefore we do not know the flow id to respond to.
return@mapNotNull null
} else {
val clientRequestId =
request.flowExternalEventContext.contextProperties.toMap()[MDC_CLIENT_ID] ?: ""
withMDC(
mapOf(
MDC_CLIENT_ID to clientRequestId,
MDC_EXTERNAL_EVENT_ID to request.flowExternalEventContext.requestId
)
) {
try {
val holdingIdentity = request.holdingIdentity.toCorda()
logger.info("Handling ${request.request::class.java.name} for holdingIdentity ${holdingIdentity.shortHash.value}")
val cpkFileHashes = request.flowExternalEventContext.contextProperties.items
.filter { it.key.startsWith(CPK_FILE_CHECKSUM) }
.map { it.value.toSecureHash() }
.toSet()
val sandbox = entitySandboxService.get(holdingIdentity, cpkFileHashes)
currentSandboxGroupContext.set(sandbox)
processRequestWithSandbox(sandbox, request)
} catch (e: Exception) {
responseFactory.errorResponse(request.flowExternalEventContext, e)
} finally {
currentSandboxGroupContext.remove()
}
}
}
}
}
@Suppress("ComplexMethod")
private fun processRequestWithSandbox(
sandbox: SandboxGroupContext,
request: EntityRequest
): Record<String, FlowEvent> {
// get the per-sandbox entity manager and serialization services
val entityManagerFactory = sandbox.getEntityManagerFactory()
val serializationService = sandbox.getSerializationService()
val persistenceServiceInternal = PersistenceServiceInternal(sandbox::getClass, payloadCheck)
return entityManagerFactory.createEntityManager().transaction {
when (val entityRequest = request.request) {
is PersistEntities -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.persist(serializationService, it, entityRequest)
)
is DeleteEntities -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.deleteEntities(serializationService, it, entityRequest)
)
is DeleteEntitiesById -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.deleteEntitiesByIds(
serializationService,
it,
entityRequest
)
)
is MergeEntities -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.merge(serializationService, it, entityRequest)
)
is FindEntities -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.find(serializationService, it, entityRequest)
)
is FindAll -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.findAll(serializationService, it, entityRequest)
)
is FindWithNamedQuery -> responseFactory.successResponse(
request.flowExternalEventContext,
persistenceServiceInternal.findWithNamedQuery(serializationService, it, entityRequest)
)
else -> {
responseFactory.fatalErrorResponse(
request.flowExternalEventContext,
CordaRuntimeException("Unknown command")
)
}
}
}
}
private fun String.toSecureHash() = parseSecureHash(this)
}
| 114
|
Kotlin
|
10
| 31
|
0fbac93cf5a216650d5228ba014951e34617d677
| 7,233
|
corda-runtime-os
|
Apache License 2.0
|
door-compiler/src/main/kotlin/com/ustadmobile/lib/annotationprocessor/core/ext/KSTypeExt.kt
|
UstadMobile
| 344,538,858
| false
| null |
package com.ustadmobile.lib.annotationprocessor.core.ext
import com.google.devtools.ksp.findActualType
import com.ustadmobile.door.lifecycle.LiveData
import com.ustadmobile.door.paging.DataSourceFactory
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
import com.squareup.kotlinpoet.CodeBlock
import com.ustadmobile.door.DoorDbType
import com.ustadmobile.door.jdbc.TypesKmp
import com.ustadmobile.door.paging.PagingSource
import kotlinx.coroutines.flow.Flow
fun KSType.unwrapComponentTypeIfListOrArray(
resolver: Resolver
): KSType {
return if(isListOrArrayType(resolver)) {
this.arguments.first().type?.resolve()
?: throw IllegalArgumentException("unwrapComponentTypeIfListOrArray: List or array type cannot be resolved!")
}else {
this
}
}
/**
*
* @receiver The return type of a DAO function. This can be a primitive, object, a list or array of a primitive or object
* or LiveData, DataSourceFactory, or Flow with a primitive or object type reference
* e.g. Entity, List<Entity>, LiveData<Entity>, LiveData<List<Entity>> etc.
*
* @param resolver the KSP resolver
*
* @return The result type expected when running the actual query - either the object itself, or a list of objects. This
* will unwrap LiveData, Flow, and DataSourceFactory.
* e.g. Entity, List<Entity>, Entity, List<Entity> etc.
*
*/
fun KSType.unwrapResultType(
resolver: Resolver,
): KSType {
val qualifiedName = this.declaration.qualifiedName?.asString()
if (qualifiedName == LiveData::class.qualifiedName) {
return this.arguments.first().type?.resolve()
?: throw IllegalArgumentException("unwrapLiveDataOrDataSourceFactoryResultType: Cannot resolve LiveData type!")
} else if (qualifiedName == DataSourceFactory::class.qualifiedName ||
qualifiedName == PagingSource::class.qualifiedName
) {
val entityTypeRef = arguments.get(1).type ?: throw IllegalArgumentException("PagingSource/Factory has no type argument")
return resolver.getClassDeclarationByName(resolver.getKSNameFromString("kotlin.collections.List"))
?.asType(listOf(resolver.getTypeArgument(entityTypeRef, Variance.INVARIANT)))
?: throw IllegalArgumentException("unwrapLiveDataOrDataSourceFactoryResultType: could not lookup pagingsource comp type")
}else if(qualifiedName == Flow::class.qualifiedName) {
return this.arguments.first().type?.resolve()
?: throw IllegalArgumentException("unwrapLiveDataOrDataSourceFactoryResultType: Cannot resolve Flow type!")
}
else {
return this
}
}
fun KSType.isList(): Boolean {
return (declaration as? KSClassDeclaration)?.isListDeclaration() == true
}
fun KSType.isListOrArrayType(
resolver: Resolver
): Boolean {
return (this == resolver.builtIns.arrayType) || isList()
}
private fun Resolver.sqliteIntegerTypes(): List<KSType> {
return listOf(builtIns.booleanType, builtIns.byteType, builtIns.shortType, builtIns.intType, builtIns.longType)
.flatMap { listOf(it, it.makeNullable()) }
}
private fun Resolver.sqliteRealTypes(): List<KSType> {
return listOf(builtIns.floatType, builtIns.doubleType).flatMap { listOf(it, it.makeNullable()) }
}
fun KSType.equalsIgnoreNullable(otherType: KSType) : Boolean {
return this == otherType || this == otherType.makeNullable()
}
fun KSType.toSqlType(
dbType: Int,
resolver: Resolver,
): String {
val builtIns = resolver.builtIns
return when {
this.equalsIgnoreNullable(builtIns.stringType) -> "TEXT"
dbType == DoorDbType.SQLITE && this in resolver.sqliteIntegerTypes() -> "INTEGER"
dbType == DoorDbType.SQLITE && this in resolver.sqliteRealTypes() -> "REAl"
this.equalsIgnoreNullable(builtIns.booleanType) -> "BOOL"
this.equalsIgnoreNullable(builtIns.byteType) -> "SMALLINT"
this.equalsIgnoreNullable(builtIns.shortType) -> "SMALLINT"
this.equalsIgnoreNullable(builtIns.intType) -> "INTEGER"
this.equalsIgnoreNullable(builtIns.longType) -> "BIGINT"
this.equalsIgnoreNullable(builtIns.floatType) -> "FLOAT"
this.equalsIgnoreNullable(builtIns.doubleType) -> "DOUBLE PRECISION"
else -> "INVALID UNSUPPORTED TYPE"
}
}
fun KSType.toSqlTypeInt(
dbType: Int,
resolver: Resolver
): Int {
val builtIns = resolver.builtIns
return when {
this.equalsIgnoreNullable(builtIns.stringType) -> TypesKmp.LONGVARCHAR
dbType == DoorDbType.SQLITE && this in resolver.sqliteIntegerTypes() -> TypesKmp.INTEGER
dbType == DoorDbType.SQLITE && this in resolver.sqliteRealTypes() -> TypesKmp.REAL
this.equalsIgnoreNullable(builtIns.booleanType) -> TypesKmp.BOOLEAN
this.equalsIgnoreNullable(builtIns.byteType) -> TypesKmp.SMALLINT
this.equalsIgnoreNullable(builtIns.shortType) -> TypesKmp.SMALLINT
this.equalsIgnoreNullable(builtIns.intType) -> TypesKmp.INTEGER
this.equalsIgnoreNullable(builtIns.longType) -> TypesKmp.BIGINT
this.equalsIgnoreNullable(builtIns.floatType) -> TypesKmp.FLOAT
this.equalsIgnoreNullable(builtIns.doubleType) -> TypesKmp.DOUBLE
else -> 0
}
}
fun KSType.defaultTypeValueCode(
resolver: Resolver
): CodeBlock {
val builtIns = resolver.builtIns
val that = this
return CodeBlock.builder()
.apply {
when {
isMarkedNullable -> add("null")
that == builtIns.intType -> add("0")
that == builtIns.longType -> add("0L")
that == builtIns.byteType -> add("0.toByte()")
that == builtIns.floatType -> add("0.toFloat()")
that == builtIns.doubleType -> add("0.toDouble()")
that == builtIns.booleanType -> add("false")
that == builtIns.stringType -> add("\"\"")
(that.declaration as? KSClassDeclaration)?.isListDeclaration() == true -> {
add("mutableListOf()")
}
(that.declaration as? KSClassDeclaration)?.isListDeclaration() == true -> {
add("emptyList()")
}
}
}
.build()
}
fun KSType.defaultSqlQueryVal(
resolver: Resolver,
dbProductType: Int,
) : String {
return when {
this in resolver.sqlNumericNonNullTypes() -> "0"
dbProductType == DoorDbType.SQLITE && this == resolver.builtIns.booleanType -> "0"
this == resolver.builtIns.booleanType -> "false"
this == resolver.builtIns.stringType -> "''"
else -> "null"
}
}
fun KSType.isArrayType(): Boolean {
return (declaration as? KSClassDeclaration)?.isArrayDeclaration() == true
}
fun KSType.isLongArray(): Boolean {
return (declaration as? KSClassDeclaration)?.qualifiedName?.asString() == "kotlin.LongArray"
}
fun KSType.isIntArray(): Boolean {
return (declaration as? KSClassDeclaration)?.qualifiedName?.asString() == "kotlin.IntArray"
}
fun KSType.isDataSourceFactory() = declaration.isDataSourceFactory()
fun KSType.isPagingSource() = declaration.isPagingSource()
fun KSType.isLiveData() = declaration.isLiveData()
fun KSType.isPagingSourceOrDataSourceFactoryOrLiveDataOrFlow() = declaration.isPagingSourceOrDataSourceFactoryOrLiveDataOrFlow()
fun KSType.isFlow() = declaration.isFlow()
fun KSType.resolveActualTypeIfAliased(): KSType {
return if(declaration is KSTypeAlias) {
(declaration as KSTypeAlias).findActualType().asType(arguments)
}else {
this
}
}
| 0
| null |
0
| 89
|
58f93d9057ece78cc3f8be3d4d235c0204a15f11
| 7,604
|
door
|
Apache License 2.0
|
app/src/main/java/com/breezefsmaddischemicocorporation/features/stockCompetetorStock/api/AddCompStockRepository.kt
|
DebashisINT
| 641,390,752
| false
| null |
package com.breezefsmaddischemicocorporation.features.stockCompetetorStock.api
import com.breezefsmaddischemicocorporation.base.BaseResponse
import com.breezefsmaddischemicocorporation.features.orderList.model.NewOrderListResponseModel
import com.breezefsmaddischemicocorporation.features.stockCompetetorStock.ShopAddCompetetorStockRequest
import com.breezefsmaddischemicocorporation.features.stockCompetetorStock.model.CompetetorStockGetData
import io.reactivex.Observable
class AddCompStockRepository(val apiService:AddCompStockApi){
fun addCompStock(shopAddCompetetorStockRequest: ShopAddCompetetorStockRequest): Observable<BaseResponse> {
return apiService.submShopCompStock(shopAddCompetetorStockRequest)
}
fun getCompStockList(sessiontoken: String, user_id: String, date: String): Observable<CompetetorStockGetData> {
return apiService.getCompStockList(sessiontoken, user_id, date)
}
}
| 0
|
Kotlin
|
0
| 0
|
c08eaf8cb0a1f3ade4f1762526afe1fa3976690d
| 927
|
AddisChemicoCorporation
|
Apache License 2.0
|
rulebook-checkstyle/src/main/kotlin/com/hanggrian/rulebook/checkstyle/IfElseFlatteningCheck.kt
|
hanggrian
| 556,969,715
| false
|
{"Kotlin": 270414, "Python": 71768, "Java": 18644, "CSS": 1653, "Groovy": 323}
|
package com.hanggrian.rulebook.checkstyle
import com.hanggrian.rulebook.checkstyle.internals.Messages
import com.hanggrian.rulebook.checkstyle.internals.children
import com.hanggrian.rulebook.checkstyle.internals.contains
import com.hanggrian.rulebook.checkstyle.internals.isMultiline
import com.puppycrawl.tools.checkstyle.api.DetailAST
import com.puppycrawl.tools.checkstyle.api.TokenTypes.LITERAL_ELSE
import com.puppycrawl.tools.checkstyle.api.TokenTypes.LITERAL_IF
import com.puppycrawl.tools.checkstyle.api.TokenTypes.RCURLY
import com.puppycrawl.tools.checkstyle.api.TokenTypes.SEMI
import com.puppycrawl.tools.checkstyle.api.TokenTypes.SINGLE_LINE_COMMENT
import com.puppycrawl.tools.checkstyle.api.TokenTypes.SLIST
/**
* [See wiki](https://github.com/hanggrian/rulebook/wiki/Rules/#if-else-flattening)
*/
public class IfElseFlatteningCheck : Check() {
override fun getRequiredTokens(): IntArray = intArrayOf(SLIST)
override fun isCommentNodesRequired(): Boolean = true
override fun visitToken(node: DetailAST) {
// get last if
var `if`: DetailAST? = null
for (child in node.children.asIterable().reversed()) {
when (child.type) {
LITERAL_IF -> {
`if` = child
break
}
SEMI, RCURLY, SINGLE_LINE_COMMENT -> continue
else -> return
}
}
`if` ?: return
// checks for violation
val `else` = `if`.findFirstToken(LITERAL_ELSE)
if (`else` != null) {
`else`
.takeUnless { LITERAL_IF in it }
?.takeIf { it.hasMultipleLines() }
?: return
log(`else`, Messages[MSG_LIFT])
return
}
`if`
.takeIf { it.hasMultipleLines() }
?: return
log(`if`, Messages[MSG_INVERT])
}
internal companion object {
const val MSG_INVERT = "if.else.flattening.invert"
const val MSG_LIFT = "if.else.flattening.lift"
private fun DetailAST.hasMultipleLines() =
findFirstToken(SLIST)
?.children
?.filterNot { it.type == RCURLY || it.type == SEMI }
?.let { it.singleOrNull()?.isMultiline() ?: (it.count() > 1) }
?: false
}
}
| 0
|
Kotlin
|
0
| 1
|
a1283fc14004ac7c973c5312dede43035f10daa2
| 2,346
|
rulebook
|
Apache License 2.0
|
build-extensions/src/main/kotlin/extensions.kt
|
CloudNetService
| 187,873,041
| false
| null |
/*
* Copyright 2019-2024 CloudNetService team & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import net.kyori.indra.git.IndraGitExtension
import org.gradle.api.Project
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.artifacts.dsl.RepositoryHandler
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import org.gradle.api.internal.artifacts.repositories.resolver.MavenUniqueSnapshotComponentIdentifier
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.attributes
import org.gradle.kotlin.dsl.findByType
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.the
import java.net.HttpURLConnection
import java.net.URL
fun Project.applyJarMetadata(mainClass: String, module: String) {
applyJarMetadata(mainClass, module, null)
}
fun Project.applyJarMetadata(mainClass: String, module: String, preMain: String?) {
if ("jar" in tasks.names) {
tasks.named<Jar>("jar") {
manifest.attributes(
"Main-Class" to mainClass,
"Automatic-Module-Name" to module,
"Implementation-Vendor" to "CloudNetService",
"Implementation-Title" to Versions.cloudNetCodeName,
"Implementation-Version" to project.version.toString() + "-${shortCommitHash()}")
// apply the pre-main class if given
if (preMain != null) {
manifest.attributes("Premain-Class" to preMain)
}
// apply git information to manifest
git()?.applyVcsInformationToManifest(manifest)
}
}
}
fun Project.shortCommitHash(): String {
return git()?.commit()?.name?.substring(0, 8) ?: "unknown"
}
fun Project.git(): IndraGitExtension? = rootProject.extensions.findByType()
fun Project.sourceSets(): SourceSetContainer = the<JavaPluginExtension>().sourceSets
fun ProjectDependency.sourceSets(): SourceSetContainer = dependencyProject.sourceSets()
fun Project.mavenRepositories(): Iterable<MavenArtifactRepository> = repositories.filterIsInstance<MavenArtifactRepository>()
fun releasesOnly(repository: MavenArtifactRepository) {
repository.mavenContent {
releasesOnly()
}
}
fun snapshotsOnly(repository: MavenArtifactRepository) {
repository.mavenContent {
snapshotsOnly()
}
}
fun Project.exportLanguageFileInformation(): String {
val file = project.layout.buildDirectory.file("languages.txt").get().asFile
file.writeText(project.projectDir.resolve("src/main/resources/lang").listFiles()?.joinToString(separator = "\n") { it.name }!!)
return file.absolutePath
}
fun Project.exportCnlFile(fileName: String, ignoredDependencyGroups: Array<String> = arrayOf()): String {
val stringBuilder = StringBuilder("# CloudNet ${Versions.cloudNetCodeName} ${Versions.cloudNet}\n\n")
.append("# repositories\n")
// add all repositories
mavenRepositories().forEach { repo ->
stringBuilder.append("repo ${repo.name} ${repo.url.toString().dropLastWhile { it == '/' }}\n")
}
// add all dependencies
stringBuilder.append("\n\n# dependencies\n")
configurations.getByName("runtimeClasspath").resolvedConfiguration.resolvedArtifacts.forEach {
// get the module version from the artifact, stop if the dependency is ignored
val id = it.moduleVersion.id
if (id.group.equals(group) || ignoredDependencyGroups.contains(id.group)) {
return@forEach
}
// check if the dependency is a snapshot version - in this case we need to use another artifact url
var version = id.version
if (id.version.endsWith("-SNAPSHOT") && it.id.componentIdentifier is MavenUniqueSnapshotComponentIdentifier) {
// little hack to get the timestamped ("snapshot") version of the identifier
version = (it.id.componentIdentifier as MavenUniqueSnapshotComponentIdentifier).timestampedVersion
}
// try to find the repository associated with the module
val repository = resolveRepository(
"${id.group.replace('.', '/')}/${id.name}/${id.version}/${id.name}-$version.jar",
mavenRepositories()
) ?: throw IllegalStateException("Unable to resolve repository for $id")
// add the repository
val cs = ChecksumHelper.fileShaSum(it.file)
stringBuilder.append("include ${repository.name} ${id.group} ${id.name} ${id.version} $version $cs ${it.classifier ?: ""}\n")
}
// write to the output file
val target = project.layout.buildDirectory.file(fileName).get().asFile
target.writeText(stringBuilder.toString())
return target.absolutePath
}
private fun resolveRepository(
testUrlPath: String,
repositories: Iterable<MavenArtifactRepository>
): MavenArtifactRepository? {
return repositories.firstOrNull {
val url = it.url.resolve(testUrlPath).toURL()
with(url.openConnection() as HttpURLConnection) {
useCaches = false
readTimeout = 30000
connectTimeout = 30000
instanceFollowRedirects = true
setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"
)
connect()
responseCode == 200
}
}
}
| 78
| null |
120
| 378
|
7aaa1cba6d0b6936bb9a380925a732881df74438
| 5,670
|
CloudNet
|
Apache License 2.0
|
app/src/main/java/com/jjosft/android/lottovillage/services/SmsBroadcastReceiver.kt
|
jung2929
| 99,984,015
| false
| null |
package com.jjosft.android.lottovillage.services
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.telephony.SmsMessage
import com.jjosft.android.lottovillage.activities.RegisterActivity
/**
* Created by JJSOFT-DESKTOP on 2017-08-15.
*/
class SmsBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == "android.provider.Telephony.SMS_RECEIVED") {
val bundle: Bundle? = intent.extras // Bundle객체에 문자를 받아온다
if (bundle != null) {
val pduObjects = bundle.get("pdus") as Array<*>
for (i in pduObjects.indices) {
val currentSms = getIncomingMessage(pduObjects[i] as ByteArray, bundle)
//val senderNo = currentSms.displayOriginatingAddress
val message = currentSms.displayMessageBody
if (message.contains("LottoVillage")) {
val certifiedNumber = message.substring(message.indexOf("[") + 1, message.indexOf("]"))
intent.putExtra("certified_number", certifiedNumber)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
intent.setClass(context, RegisterActivity::class.java)
context.startActivity(intent)
}
}
this.abortBroadcast()
}
}
}
private fun getIncomingMessage(aObject: Any, bundle: Bundle): SmsMessage {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val format = bundle.getString("format")
return SmsMessage.createFromPdu(aObject as ByteArray, format)
} else {
return SmsMessage.createFromPdu(aObject as ByteArray)
}
}
}
| 0
|
Kotlin
|
1
| 1
|
b1c176a59697b5858852408371519e3d82e7c412
| 1,995
|
LottoVillageClient
|
MIT License
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/item/exchange/BuyResinReq.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 612536}
|
package org.anime_game_servers.multi_proto.gi.data.item.exchange
import org.anime_game_servers.core.base.Version.GI_0_9_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
@AddedIn(GI_0_9_0)
@ProtoCommand(REQUEST)
internal interface BuyResinReq {
}
| 0
|
Kotlin
|
3
| 6
|
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 404
|
anime-game-multi-proto
|
MIT License
|
app/src/commonMain/kotlin/com/example/kmp/ui/main/MainScreen.kt
|
hadion82
| 797,506,685
| false
|
{"Kotlin": 108361, "Swift": 1033}
|
package com.example.kmp.ui.main
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.PullToRefreshState
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import app.cash.paging.PagingData
import app.cash.paging.compose.LazyPagingItems
import app.cash.paging.compose.collectAsLazyPagingItems
import app.cash.paging.compose.itemKey
import com.example.data.model.CharacterItem
import com.example.kmp.di.scope.UiScope
import com.example.kmp.ui.common.CharacterContent
import com.example.kmp.ui.theme.DefaultSurface
import com.example.shared.dispatcher.ScopedDispatcher
import composemultiplatform.app.generated.resources.Res
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.stringResource
interface MainScreenScope : UiScope<Intention>
class MainScopedDispatcher(
intent: MutableSharedFlow<Intention>,
scope: CoroutineScope
) :
ScopedDispatcher<Intention>(intent, scope)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainContents(mainState: State<Flow<PagingData<CharacterItem>>?>, presenter: MainPresenter) {
val pagingData by mainState
val pagingItems = pagingData?.collectAsLazyPagingItems() ?: return
val pullToRefreshState = rememberPullToRefreshState()
val scaleFraction = if (pullToRefreshState.isRefreshing) 1f else
LinearOutSlowInEasing.transform(pullToRefreshState.progress).coerceIn(0f, 1f)
if (pullToRefreshState.isRefreshing) pagingItems.refresh()
Box(modifier = Modifier.nestedScroll(pullToRefreshState.nestedScrollConnection)) {
CharacterLazyColum(
pullToRefreshState = pullToRefreshState,
pagingItems = pagingItems,
onThumbnailClick = presenter::onThumbnailClick,
onBookmarkClick = presenter::onBookmarkClick
)
AppendIndicator(
loadState = pagingItems.loadState.append,
showMessage = presenter::showMessage
)
RefreshIndicator(
loadState = pagingItems.loadState.refresh,
pullToRefreshState = pullToRefreshState,
modifier = Modifier.align(Alignment.Center),
showMessage = presenter::showMessage
)
PullToRefreshContainer(
modifier = Modifier.align(Alignment.TopCenter)
.graphicsLayer(scaleX = scaleFraction, scaleY = scaleFraction),
state = pullToRefreshState
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CharacterLazyColum(
pullToRefreshState: PullToRefreshState,
pagingItems: LazyPagingItems<CharacterItem>,
onThumbnailClick: (String?) -> Unit,
onBookmarkClick: (CharacterItem) -> Unit
) {
LazyColumn(
contentPadding = PaddingValues(16.dp, 8.dp),
modifier = Modifier.fillMaxSize()
) {
if (pullToRefreshState.isRefreshing.not()) {
items(
count = pagingItems.itemCount,
key = pagingItems.itemKey { it.id }
) { position ->
pagingItems[position]?.let { characterItem ->
CharacterContent(
character = characterItem,
onThumbnailClick = onThumbnailClick,
onBookmarkClick = onBookmarkClick
)
HorizontalDivider()
}
}
}
}
}
@Composable
fun AppendIndicator(
loadState: LoadState,
showMessage: (String) -> Unit
) {
when (loadState) {
is LoadState.Loading -> {/*Nothing*/
}
is LoadState.NotLoading -> { /*Nothing*/
}
is LoadState.Error -> loadState.error.message?.let { showMessage(it) }
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RefreshIndicator(
loadState: LoadState,
pullToRefreshState: PullToRefreshState,
modifier: Modifier,
showMessage: (String) -> Unit
) {
when (loadState) {
is LoadState.Loading -> {
if (pullToRefreshState.isRefreshing.not()) {
CircularProgressIndicator(
color = Color.Black,
modifier = modifier
)
}
}
is LoadState.Error -> loadState.error.message?.let { showMessage(it) }
is LoadState.NotLoading -> pullToRefreshState.endRefresh()
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun SnackBarMessage(
messageState: State<Action.Message?>,
snackBarHostState: SnackbarHostState
) {
val stateValue = messageState.value ?: return
val scope = rememberCoroutineScope()
val message = when (stateValue) {
is Action.Message.FailedToLoadData -> stringResource(Res.string.failed_to_load_data)
is Action.Message.FailedToBookmark -> stringResource(Res.string.failed_to_bookmark)
is Action.Message.FailedToDeleteBookmark -> stringResource(Res.string.failed_to_delete_bookmark)
is Action.Message.SuccessToSaveImage -> stringResource(Res.string.image_saved_successfully)
is Action.Message.FailedToSaveImage -> stringResource(Res.string.failed_to_save_image)
is Action.Message.ShowMessage -> stateValue.message
}
scope.launch {
snackBarHostState
.showSnackbar(message = message, duration = SnackbarDuration.Short)
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun TitleBar(onTitleClick: () -> Unit) {
Box(Modifier.fillMaxWidth()) {
Text(
text = stringResource(Res.string.marvel_characters),
modifier = Modifier
.align(Alignment.CenterStart)
.padding(4.dp, 2.dp)
)
Button(
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(4.dp, 2.dp),
onClick = onTitleClick
) {
Text(text = stringResource(Res.string.label_bookmark))
}
}
}
@Composable
fun MainScreen(
uiState: MainComposableUiState, presenter: MainPresenter
) {
MaterialTheme {
DefaultSurface {
Scaffold(snackbarHost = {
SnackbarHost(uiState.snackBarHostState)
}) {
Column(
Modifier.fillMaxSize()
.windowInsetsPadding(WindowInsets.safeDrawing)
) {
TitleBar(presenter::onTitleClick)
MainContents(uiState.pagingData, presenter)
SnackBarMessage(uiState.message, uiState.snackBarHostState)
}
}
}
}
}
@Composable
expect fun Navigation(state: State<Action.Navigation?>)
| 1
|
Kotlin
|
0
| 0
|
57f36ceffcf386462c338edb3f98d3233321ad09
| 8,438
|
compose-multiplatform-architecture
|
Apache License 2.0
|
ClassWork/CW9Kotlin/src/main/kotlin/exc/Pencil.kt
|
haimadrian
| 306,993,543
| false
| null |
package exc
/**
*
* @author <NAME>
* @since 30-May-21
*/
open class Pencil(length: Double, val company: String) {
var length: Double = length
set(value) {
field = when {
(value > field) -> throw IllegalArgumentException("Increasing pencil length is prohibited. Was: $value, Current: $field")
(value <= 0.0) -> throw IllegalArgumentException("Pencil length cannot be zero or negative. Was: $value")
else -> value
}
}
constructor(another: Pencil) : this(another.length, another.company)
init {
this.length = length
}
fun sharpen(x: Double) {
length -= x
}
override fun toString(): String {
return "company='$company', length=$length"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Pencil) return false
if (company != other.company) return false
if (length != other.length) return false
return true
}
override fun hashCode(): Int {
var result = company.hashCode()
result = 31 * result + length.hashCode()
return result
}
}
| 1
| null |
14
| 10
|
2824c114d0194392e343733e744c82b5e87a4046
| 1,202
|
Android-TexasHoldemPokerOnline
|
MIT License
|
android/src/main/java/com/awsfaceliveness/AwsFaceLiveNessComposeManger.kt
|
nhatdotranminh
| 764,408,474
| false
|
{"Kotlin": 5516, "Ruby": 1744, "Java": 1708, "TypeScript": 1473, "Swift": 906, "Objective-C": 189, "JavaScript": 72}
|
package com.awsfaceliveness;
import android.view.View
import android.view.ViewGroup
import com.facebook.react.uimanager.ThemedReactContext
import android.view.Choreographer
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.ViewGroupManager
class AwsFaceLiveNessComposeManger(
private val reactContext: ReactApplicationContext
) : ViewGroupManager<FrameLayout>() { override fun getName() = REACT_CLASS
/**
* Return a FrameLayout which will later hold the Fragment
*/
override fun createViewInstance(reactContext: ThemedReactContext) =
FrameLayout(reactContext)
/**
* Map the "create" command to an integer
*/
override fun getCommandsMap() = mapOf("create" to COMMAND_CREATE)
/**
* Handle "create" command (called from JS) and call createFragment method
*/
override fun receiveCommand(
root: FrameLayout,
commandId: String,
args: ReadableArray?
) {
super.receiveCommand(root, commandId, args)
val reactNativeViewId = requireNotNull(args).getInt(0)
when (commandId.toInt()) {
COMMAND_CREATE -> createFragment(root, reactNativeViewId)
}
}
/**
* Replace your React Native view with a custom fragment
*/
fun createFragment(root: FrameLayout, reactNativeViewId: Int) {
val parentView = root.findViewById<ViewGroup>(reactNativeViewId)
setupLayout(parentView, root)
val myFragment = AwsFaceLivenessFragment()
val activity = reactContext.currentActivity as FragmentActivity
activity.supportFragmentManager
.beginTransaction()
.replace(reactNativeViewId, myFragment, reactNativeViewId.toString())
.commit()
}
fun setupLayout(view: View, rootView: View) {
Choreographer.getInstance().postFrameCallback(object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
manuallyLayoutChildren(view, rootView)
view.viewTreeObserver.dispatchOnGlobalLayout()
Choreographer.getInstance().postFrameCallback(this)
}
})
}
/**
* Layout all children properly
*/
fun manuallyLayoutChildren(view: View, rootView: View) {
view.measure(
View.MeasureSpec.makeMeasureSpec(rootView.measuredWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(rootView.measuredHeight, View.MeasureSpec.EXACTLY)
)
view.layout(rootView.left, rootView.top, rootView.measuredWidth, rootView.measuredHeight)
}
companion object {
private const val REACT_CLASS = "AwsFaceLiveNessComposeManger"
private const val COMMAND_CREATE = 1
}
}
| 0
|
Kotlin
|
0
| 0
|
2118588f810c496f05d3c6f2d23496719dd89f88
| 2,715
|
react-native-aws-face-live-ness
|
MIT License
|
vector/src/main/java/im/vector/app/features/roomprofile/polls/ended/RoomEndedPollsFragment.kt
|
tchapgouv
| 340,329,238
| false
| null |
/*
* Copyright (c) 2022 New Vector Ltd
*
* 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 im.vector.app.features.roomprofile.polls.ended
import dagger.hilt.android.AndroidEntryPoint
import im.vector.app.R
import im.vector.app.features.roomprofile.polls.RoomPollsType
import im.vector.app.features.roomprofile.polls.list.ui.RoomPollsListFragment
@AndroidEntryPoint
class RoomEndedPollsFragment : RoomPollsListFragment() {
override fun getEmptyListTitle(canLoadMore: Boolean, nbLoadedDays: Int): String {
return if (canLoadMore) {
stringProvider.getQuantityString(R.plurals.room_polls_ended_no_item_for_loaded_period, nbLoadedDays, nbLoadedDays)
} else {
getString(R.string.room_polls_ended_no_item)
}
}
override fun getRoomPollsType(): RoomPollsType {
return RoomPollsType.ENDED
}
}
| 4
| null |
6
| 9
|
9bd50a49e0a5a2a17195507ef3fe96594ddd739e
| 1,379
|
tchap-android
|
Apache License 2.0
|
src/main/kotlin/belicfr/exercises/todolist/utilities/Redirect.kt
|
Sprint-Boot-Kotlin-learning
| 784,185,732
| false
|
{"Kotlin": 11832, "HTML": 5504, "CSS": 4412}
|
package belicfr.exercises.todolist.utilities
import org.springframework.web.servlet.view.RedirectView
object Redirect {
fun to(map: String): RedirectView {
return RedirectView(map)
}
}
| 0
|
Kotlin
|
0
| 0
|
ab7a539ff3d43f7b077380cdae4e5e678a0f49df
| 202
|
todo-list
|
MIT License
|
diktat-rules/src/test/kotlin/com/saveourtool/diktat/ruleset/chapter2/HeaderCommentRuleTest.kt
|
saveourtool
| 275,879,956
| false
|
{"Kotlin": 2386437, "TeX": 190514, "Shell": 2900, "Batchfile": 541, "Makefile": 47}
|
package com.saveourtool.diktat.ruleset.chapter2
import com.saveourtool.diktat.common.config.rules.DIKTAT_RULE_SET_ID
import com.saveourtool.diktat.common.config.rules.RulesConfig
import com.saveourtool.diktat.ruleset.constants.Warnings
import com.saveourtool.diktat.ruleset.constants.Warnings.HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE
import com.saveourtool.diktat.ruleset.constants.Warnings.HEADER_MISSING_OR_WRONG_COPYRIGHT
import com.saveourtool.diktat.ruleset.constants.Warnings.HEADER_NOT_BEFORE_PACKAGE
import com.saveourtool.diktat.ruleset.constants.Warnings.HEADER_WRONG_FORMAT
import com.saveourtool.diktat.ruleset.rules.chapter2.comments.HeaderCommentRule
import com.saveourtool.diktat.util.LintTestBase
import com.saveourtool.diktat.api.DiktatError
import generated.WarningNames
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.nio.file.Path
import java.time.LocalDate
class HeaderCommentRuleTest : LintTestBase(::HeaderCommentRule) {
private val ruleId: String = "$DIKTAT_RULE_SET_ID:${HeaderCommentRule.NAME_ID}"
private val curYear = LocalDate.now().year
private val rulesConfigList: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "Copyright (c) My Company, Ltd. 2012-$curYear. All rights reserved."))
)
private val rulesConfigListWithPattern: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "Copyright (c) My Company, Ltd. 2012-;@currYear;. All rights reserved."))
)
private val rulesConfigListInvalidYear: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "Copyright (c) My Company, Ltd. 2012-2019. All rights reserved."))
)
private val rulesConfigListInvalidYearBeforeCopyright: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "Copyright (c) 2019 My Company, Ltd. All rights reserved."))
)
private val rulesConfigListYear: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "Copyright (c) $curYear My Company, Ltd. All rights reserved."))
)
private val rulesConfigListYearWithPattern: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "Copyright (c) ;@currYear; My Company, Ltd. All rights reserved."))
)
private val rulesConfigListCn: List<RulesConfig> = listOf(
RulesConfig("HEADER_MISSING_OR_WRONG_COPYRIGHT", true,
mapOf("copyrightText" to "版权所有 (c) 华为技术有限公司 2012-$curYear"))
)
private val curYearCopyright = "Copyright (c) My Company, Ltd. 2012-$curYear. All rights reserved."
private val copyrightBlock = """
/*
* $curYearCopyright
*/
""".trimIndent()
@Test
@Tag(WarningNames.HEADER_WRONG_FORMAT)
fun `file header comment (positive example)`() {
lintMethod(
"""
$copyrightBlock
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_WRONG_FORMAT)
fun `file header comment with Chinese version copyright (positive example)`() {
lintMethod(
"""
/*
* 版权所有 (c) 华为技术有限公司 2012-$curYear
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigListCn
)
}
@Test
@Tag(WarningNames.HEADER_MISSING_OR_WRONG_COPYRIGHT)
fun `copyright should not be placed inside KDoc`() {
lintMethod(
"""
/**
* $curYearCopyright
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
DiktatError(1, 1, ruleId, "${HEADER_MISSING_OR_WRONG_COPYRIGHT.warnText()} copyright is placed inside KDoc, but should be inside a block comment", true),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_MISSING_OR_WRONG_COPYRIGHT)
fun `copyright should not be placed inside KDoc (Chinese version)`() {
lintMethod(
"""
/**
* 版权所有 (c) 华为技术有限公司 2012-2020
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
DiktatError(1, 1, ruleId, "${HEADER_MISSING_OR_WRONG_COPYRIGHT.warnText()} copyright is placed inside KDoc, but should be inside a block comment", true),
rulesConfigList = rulesConfigListCn
)
}
@Test
@Tag(WarningNames.HEADER_MISSING_OR_WRONG_COPYRIGHT)
fun `copyright should not be placed inside single line comment`() {
lintMethod(
"""
// $curYearCopyright
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
DiktatError(1, 1, ruleId, "${HEADER_MISSING_OR_WRONG_COPYRIGHT.warnText()} copyright is placed inside KDoc, but should be inside a block comment", true),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year good`() {
lintMethod(
"""
/*
* $curYearCopyright
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year good 2`() {
lintMethod(
"""
/*
* Copyright (c) $curYear My Company, Ltd. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigListYear
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year good 3 - apply pattern`() {
lintMethod(
"""
/*
* Copyright (c) $curYear My Company, Ltd. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigListYearWithPattern
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year good 4 - apply pattern`() {
lintMethod(
"""
/*
* Copyright (c) My Company, Ltd. 2012-$curYear. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigListWithPattern
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year good 5`() {
lintMethod(
"""
/*
Copyright (c) My Company, Ltd. 2021-$curYear. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year good 6`() {
lintMethod(
"""
/*
* Copyright (c) My Company, Ltd. 2002-$curYear. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year bad`() {
lintMethod(
"""
/*
* Copyright (c) My Company, Ltd. 2012-2019. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
DiktatError(1, 1, ruleId, """${Warnings.WRONG_COPYRIGHT_YEAR.warnText()} year should be ${LocalDate.now().year}""", true),
rulesConfigList = rulesConfigListInvalidYear
)
}
@Test
@Tag(WarningNames.WRONG_COPYRIGHT_YEAR)
fun `copyright year bad 2`() {
lintMethod(
"""
/*
* Copyright (c) 2019 My Company, Ltd. All rights reserved.
*/
/**
* Very useful description, why this file has two classes
* foo bar baz
*/
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
DiktatError(1, 1, ruleId, """${Warnings.WRONG_COPYRIGHT_YEAR.warnText()} year should be ${LocalDate.now().year}""", true),
rulesConfigList = rulesConfigListInvalidYearBeforeCopyright
)
}
@Test
@Tag(WarningNames.HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE)
fun `file with zero classes should have header KDoc`() {
lintMethod(
"""
package com.saveourtool.diktat.example
val CONSTANT = 42
fun foo(): Int = 42
""".trimIndent(),
DiktatError(1, 1, ruleId, "${HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE.warnText()} there are 0 declared classes and/or objects", false),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE)
fun `file with multiple classes should have header KDoc`() {
lintMethod(
"""
package com.saveourtool.diktat.example
class Example1 { }
class Example2 { }
""".trimIndent(),
DiktatError(1, 1, ruleId, "${HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE.warnText()} there are 2 declared classes and/or objects", false),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_WRONG_FORMAT)
fun `header KDoc should have newline after it`() {
lintMethod(
"""
|$copyrightBlock
|/**
| * Very useful description
| * foo bar baz
| */
|package com.saveourtool.diktat.example
|
|class Example { }
""".trimMargin(),
DiktatError(4, 1, ruleId, "${HEADER_WRONG_FORMAT.warnText()} header KDoc should have a new line after", true),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_NOT_BEFORE_PACKAGE)
fun `header KDoc should be placed before package and imports`() {
lintMethod(
"""
|package com.saveourtool.diktat.example
|
|import com.saveourtool.diktat.example.Foo
|
|/**
| * This is a code snippet for tests
| */
|
|/**
| * This is an example class
| */
|class Example { }
""".trimMargin(),
DiktatError(5, 1, ruleId, "${HEADER_NOT_BEFORE_PACKAGE.warnText()} header KDoc is located after package or imports", true),
rulesConfigList = emptyList()
)
}
@Test
@Tag(WarningNames.HEADER_NOT_BEFORE_PACKAGE)
fun `header KDoc object check`() {
lintMethod(
"""
|package com.saveourtool.diktat.example
|
|import com.saveourtool.diktat.example.Foo
|
|object TestEntry {
|@JvmStatic
|fun main(args: Array<String>) {
| val properties = TestFrameworkProperties("com/saveourtool/diktat/test/framework/test_framework.properties")
| TestProcessingFactory(TestArgumentsReader(args, properties, javaClass.classLoader)).processTests()
| }
|}
""".trimMargin(),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_NOT_BEFORE_PACKAGE)
fun `header KDoc object and class check`() {
lintMethod(
"""
|package com.saveourtool.diktat.example
|
|import com.saveourtool.diktat.example.Foo
|
|object TestEntry {
|@JvmStatic
|fun main(args: Array<String>) {
| val properties = TestFrameworkProperties("com/saveourtool/diktat/test/framework/test_framework.properties")
| TestProcessingFactory(TestArgumentsReader(args, properties, javaClass.classLoader)).processTests()
| }
|}
|
|class Some {}
""".trimMargin(),
DiktatError(1, 1, ruleId, "${HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE.warnText()} there are 2 declared classes and/or objects"),
rulesConfigList = rulesConfigList
)
}
@Test
@Tag(WarningNames.HEADER_NOT_BEFORE_PACKAGE)
fun `header KDoc in gradle script`(@TempDir tempDir: Path) {
lintMethodWithFile(
"""
|version = "0.1.0-SNAPSHOT"
|
""".trimMargin(),
tempDir = tempDir,
fileName = "src/main/kotlin/com/saveourtool/diktat/builds.gradle.kts"
)
}
@Test
@Tag(WarningNames.HEADER_NOT_BEFORE_PACKAGE)
fun `header KDoc in kts script`(@TempDir tempDir: Path) {
lintMethodWithFile(
"""
|val version = "0.1.0-SNAPSHOT"
|
""".trimMargin(),
tempDir = tempDir,
fileName = "src/main/kotlin/com/saveourtool/diktat/Example.kts",
DiktatError(1, 1, ruleId, "${HEADER_MISSING_IN_NON_SINGLE_CLASS_FILE.warnText()} there are 0 declared classes and/or objects")
)
}
}
| 149
|
Kotlin
|
39
| 535
|
9e73d811d9fd9900af5917ba82ddeed0177ac52e
| 16,889
|
diktat
|
MIT License
|
enro/src/androidTest/java/dev/enro/core/fragment/FragmentDestinationPresentDialog.kt
|
isaac-udy
| 256,179,010
| false
| null |
package dev.enro.core.fragment
import dev.enro.core.compose.ComposableDestination
import dev.enro.core.destinations.*
import org.junit.Test
class FragmentDestinationPresentDialog {
@Test
fun givenFragmentDestination_whenExecutingPresent_andTargetIsDialog_andTargetIsComposableDestination_thenCorrectDestinationIsOpened() {
val root = launchFragmentRoot()
root.assertPresentsTo<ComposableDestination, ComposableDestinations.PresentableDialog>()
}
@Test
fun givenFragmentDestination_whenExecutingPresent_andTargetIsDialog_andTargetIsComposableDestination_andDestinationIsClosed_thenPreviousDestinationIsActive() {
val root = launchFragmentRoot()
root.assertPresentsTo<ComposableDestination, ComposableDestinations.PresentableDialog>()
.assertClosesTo<FragmentDestinations.Fragment, FragmentDestinations.Root>(root.navigation.key)
}
@Test
fun givenFragmentDestination_whenExecutingPresent_andTargetIsDialog_andTargetIsComposableDestination_andDestinationDeliversResult_thenResultIsDelivered() {
val root = launchFragmentRoot()
root.assertPresentsForResultTo<ComposableDestination, ComposableDestinations.PresentableDialog>()
.assertClosesWithResultTo<FragmentDestinations.Fragment, FragmentDestinations.Root>(root.navigation.key)
}
@Test
fun givenFragmentDestination_whenExecutingPresent_andTargetIsDialog_andTargetIsFragmentDestination_thenCorrectDestinationIsOpened() {
val root = launchFragmentRoot()
root.assertPresentsTo<FragmentDestinations.DialogFragment, FragmentDestinations.PresentableDialog>()
}
@Test
fun givenFragmentDestination_whenExecutingPresent_andTargetIsDialog_andTargetIsFragmentDestination_andDestinationIsClosed_thenPreviousDestinationIsActive() {
val root = launchFragmentRoot()
root.assertPresentsTo<FragmentDestinations.DialogFragment, FragmentDestinations.PresentableDialog>()
.assertClosesTo<FragmentDestinations.Fragment, FragmentDestinations.Root>(root.navigation.key)
}
@Test
fun givenFragmentDestination_whenExecutingPresent_andTargetIsDialog_andTargetIsFragmentDestination_andDestinationDeliversResult_thenResultIsDelivered() {
val root = launchFragmentRoot()
root.assertPresentsForResultTo<FragmentDestinations.DialogFragment, FragmentDestinations.PresentableDialog>()
.assertClosesWithResultTo<FragmentDestinations.Fragment, FragmentDestinations.Root>(root.navigation.key)
}
}
| 13
|
Kotlin
|
13
| 217
|
84dbdbd4b6dda314629353b06db6491863431a91
| 2,532
|
Enro
|
Apache License 2.0
|
main-js/src/Main.kt
|
abissell
| 134,173,678
| false
|
{"JavaScript": 1535466, "Kotlin": 913, "HTML": 411}
|
fun main(args: Array<String>) {
val b = B()
b.printSomething()
val c = C(1234.5678)
println(c.toFloat())
}
| 0
|
JavaScript
|
0
| 0
|
77e95d60194f1f583e36b5dba60c45d368b49704
| 123
|
kotlin-multiplatform-sandbox
|
Apache License 2.0
|
extension-style/src/main/java/com/mapbox/maps/extension/style/utils/ExpectedUtils.kt
|
mapbox
| 330,365,289
| false
| null |
package com.mapbox.maps.extension.style.utils
import com.mapbox.bindgen.Expected
import com.mapbox.bindgen.None
import com.mapbox.maps.MapboxStyleException
/**
* Internal function to check if a method invoke on StyleDelegate succeeded, throws exception if not.
*/
internal fun Expected<String, None>?.check() {
this?.also {
it.error?.let { err ->
throw MapboxStyleException(err)
}
} ?: throw MapboxStyleException("Plugin is not added to Style yet.")
}
/**
* Internal function to check if a method invoke on StyleDelegate succeeded, throws exception if not.
*/
internal inline fun <reified T> Expected<String, T>?.take(): T {
this?.also {
it.error?.let { err ->
throw MapboxStyleException(err)
}
it.value?.let { v ->
return v
}
}
throw MapboxStyleException("Plugin is not added to Style yet.")
}
| 216
| null |
131
| 472
|
2700dcaf18e70d23a19fc35b479bff6a2d490475
| 853
|
mapbox-maps-android
|
Apache License 2.0
|
src/main/kotlin/OctocatKDUDialogs.kt
|
N7ghtm4r3
| 737,529,238
| false
|
{"Kotlin": 13470, "Java": 12595}
|
import KDUWorker.logError
import KDUWorker.logMessage
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tecknobit.apimanager.annotations.Wrapper
import com.tecknobit.apimanager.apis.ConsolePainter.ANSIColor.GREEN
import com.tecknobit.apimanager.apis.ConsolePainter.ANSIColor.YELLOW
import com.tecknobit.mantis.Mantis
import java.util.*
import kotlin.system.exitProcess
/**
* Function to create the fake update dialog for testing purposes
*
* @param dialogModifier: the [Modifier] for the [AlertDialog] shown
* @param locale: the locale language to use
* @param shape: the shape of the [AlertDialog]
* @param appName: the name of the application where the dialog will be shown
* @param showFakeUpdate: whether show the dialog
* @param titleModifier: the modifier for the title of the [AlertDialog]
* @param titleColor: the color of the title of the [AlertDialog]
* @param titleFontSize: the font size for the title of the [AlertDialog]
* @param titleFontStyle: the font style for the title of the [AlertDialog]
* @param titleFontWeight: the font weight for the title of the [AlertDialog]
* @param titleFontFamily: the font family for the title of the [AlertDialog]
* @param textModifier: the modifier for the text of the [AlertDialog]
* @param textColor: the color of the text of the [AlertDialog]
* @param textFontSize: the font size for the text of the [AlertDialog]
* @param textFontStyle: the font style for the text of the [AlertDialog]
* @param textFontWeight: the font weight for the text of the [AlertDialog]
* @param textFontFamily: the font family for the text of the [AlertDialog]
* @param dismissAction: the action to execute when the dismiss button has been clicked,
* note this action will be invoked also if the dialog are not displayed
*/
@Wrapper
@Composable
fun FakeUpdaterDialog(
dialogModifier: Modifier = Modifier,
locale: Locale = Locale.getDefault(),
shape: Shape = RoundedCornerShape(15.dp),
appName: String,
showFakeUpdate: Boolean = true,
titleModifier: Modifier = Modifier,
titleColor: Color = Color.Unspecified,
titleFontSize: TextUnit = 18.sp,
titleFontStyle: FontStyle? = null,
titleFontWeight: FontWeight? = null,
titleFontFamily: FontFamily? = null,
textModifier: Modifier = Modifier,
textColor: Color = Color.Unspecified,
textFontSize: TextUnit = 16.sp,
textFontStyle: FontStyle? = null,
textFontWeight: FontWeight? = null,
textFontFamily: FontFamily? = null,
dismissAction: () -> Unit
) {
val mantis = Mantis(locale)
var timer = Timer()
val isInstalling = remember { mutableStateOf(false) }
if(showFakeUpdate) {
KDUDialog(
dialogModifier = dialogModifier,
locale = locale,
shape = shape,
isInstalling = isInstalling,
title = "${mantis.getResource("title_key")} last_version!",
appName = appName,
titleModifier = titleModifier,
titleColor = titleColor,
titleFontSize = titleFontSize,
titleFontStyle = titleFontStyle,
titleFontWeight = titleFontWeight,
titleFontFamily = titleFontFamily,
textModifier = textModifier,
textColor = textColor,
textFontSize = textFontSize,
textFontStyle = textFontStyle,
textFontWeight = textFontWeight,
textFontFamily = textFontFamily,
dismissAction = {
logMessage(
mantis.getResource("no_update_log_key"),
YELLOW
)
dismissAction.invoke()
},
confirmAction = {
if(!isInstalling.value) {
timer.schedule(object : TimerTask() {
override fun run() {
logMessage(
mantis.getResource("installation_message_key"),
GREEN
)
exitProcess(0)
}
}, 5000)
} else {
logError(mantis.getResource("dismiss_update_log_key"))
timer.cancel()
timer = Timer()
}
},
)
} else
dismissAction.invoke()
}
/**
* Function to create the update dialog to update the application to the latest release
*
* @param dialogModifier: the [Modifier] for the [AlertDialog] shown
* @param locale: the locale language to use
* @param shape: the shape of the [AlertDialog]
* @param appName: the name of the application where the dialog will be shown
* @param currentVersion: the current version of the application, it will be used to check if is currently the latest
* version available
* @param titleModifier: the modifier for the title of the [AlertDialog]
* @param titleColor: the color of the title of the [AlertDialog]
* @param titleFontSize: the font size for the title of the [AlertDialog]
* @param titleFontStyle: the font style for the title of the [AlertDialog]
* @param titleFontWeight: the font weight for the title of the [AlertDialog]
* @param titleFontFamily: the font family for the title of the [AlertDialog]
* @param textModifier: the modifier for the text of the [AlertDialog]
* @param textColor: the color of the text of the [AlertDialog]
* @param textFontSize: the font size for the text of the [AlertDialog]
* @param textFontStyle: the font style for the text of the [AlertDialog]
* @param textFontWeight: the font weight for the text of the [AlertDialog]
* @param textFontFamily: the font family for the text of the [AlertDialog]
* @param dismissAction: the action to execute when the dismiss button has been clicked,
* note this action will be invoked also if the dialog are not displayed
*/
@Wrapper
@Composable
fun UpdaterDialog(
dialogModifier: Modifier = Modifier,
locale: Locale = Locale.getDefault(),
shape: Shape = RoundedCornerShape(15.dp),
appName: String,
currentVersion: String,
titleModifier: Modifier = Modifier,
titleColor: Color = Color.Unspecified,
titleFontSize: TextUnit = 18.sp,
titleFontStyle: FontStyle? = null,
titleFontWeight: FontWeight? = null,
titleFontFamily: FontFamily? = null,
textModifier: Modifier = Modifier,
textColor: Color = Color.Unspecified,
textFontSize: TextUnit = 16.sp,
textFontStyle: FontStyle? = null,
textFontWeight: FontWeight? = null,
textFontFamily: FontFamily? = null,
dismissAction: () -> Unit = {}
) {
val mantis = Mantis(locale)
val kduWorker = KDUWorker(appName)
val isInstalling = remember { mutableStateOf(false) }
if(kduWorker.canBeUpdated(currentVersion)) {
KDUDialog(
dialogModifier = dialogModifier,
locale = locale,
shape = shape,
isInstalling = isInstalling,
title = "${mantis.getResource("title_key")} ${kduWorker.lastVersionCode}!",
appName = appName,
titleModifier = titleModifier,
titleColor = titleColor,
titleFontSize = titleFontSize,
titleFontStyle = titleFontStyle,
titleFontWeight = titleFontWeight,
titleFontFamily = titleFontFamily,
textModifier = textModifier,
textColor = textColor,
textFontSize = textFontSize,
textFontStyle = textFontStyle,
textFontWeight = textFontWeight,
textFontFamily = textFontFamily,
dismissAction = dismissAction,
confirmAction = {
if(!isInstalling.value)
kduWorker.installNewVersion()
else
kduWorker.stopInstallation()
},
)
} else
dismissAction.invoke()
}
/**
* Function to create the update dialog to update the application to the latest release
*
* @param dialogModifier: the [Modifier] for the [AlertDialog] shown
* @param locale: the locale language to use
* @param shape: the shape of the [AlertDialog]
* @param isInstalling: the current status of the dialog
* @param title: the title of the [AlertDialog]
* @param appName: the name of the application where the dialog will be shown
* @param titleModifier: the dialogModifier for the title of the [AlertDialog]
* @param titleColor: the color of the title of the [AlertDialog]
* @param titleFontSize: the font size for the title of the [AlertDialog]
* @param titleFontStyle: the font style for the title of the [AlertDialog]
* @param titleFontWeight: the font weight for the title of the [AlertDialog]
* @param titleFontFamily: the font family for the title of the [AlertDialog]
* @param textModifier: the dialogModifier for the text of the [AlertDialog]
* @param textColor: the color of the text of the [AlertDialog]
* @param textFontSize: the font size for the text of the [AlertDialog]
* @param textFontStyle: the font style for the text of the [AlertDialog]
* @param textFontWeight: the font weight for the text of the [AlertDialog]
* @param textFontFamily: the font family for the text of the [AlertDialog]
* @param dismissAction: the action to execute when the dismiss button has been clicked
* @param confirmAction: the action to execute when the confirm button has been clicked
*/
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun KDUDialog(
dialogModifier: Modifier = Modifier,
locale: Locale = Locale.getDefault(),
shape: Shape,
isInstalling: MutableState<Boolean>,
title: String,
appName: String,
titleModifier: Modifier = Modifier,
titleColor: Color = Color.Unspecified,
titleFontSize: TextUnit = 18.sp,
titleFontStyle: FontStyle? = null,
titleFontWeight: FontWeight? = null,
titleFontFamily: FontFamily? = null,
textModifier: Modifier = Modifier,
textColor: Color = Color.Unspecified,
textFontSize: TextUnit = 16.sp,
textFontStyle: FontStyle? = null,
textFontWeight: FontWeight? = null,
textFontFamily: FontFamily? = null,
dismissAction: () -> Unit = {},
confirmAction: () -> Unit = {},
) {
val mantis = Mantis(locale)
var show by remember { mutableStateOf(true) }
if(show) {
AlertDialog(
modifier = dialogModifier,
onDismissRequest = { show = false },
shape = shape,
title = {
Text(
modifier = titleModifier,
text = title,
color = titleColor,
fontSize = titleFontSize,
fontStyle = titleFontStyle,
fontWeight = titleFontWeight,
fontFamily = titleFontFamily
)
},
text = {
if(isInstalling.value) {
Column (
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Text(
text = mantis.getResource("installing_executable_text_key")
)
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth()
)
}
} else {
Text(
modifier = textModifier,
text = "${mantis.getResource("text_part_one_key")} $appName" +
"${mantis.getResource("text_part_two_key")}",
color = textColor,
fontSize = textFontSize,
fontStyle = textFontStyle,
fontWeight = textFontWeight,
fontFamily = textFontFamily
)
}
},
dismissButton = {
if(!isInstalling.value) {
TextButton(
onClick = {
dismissAction.invoke()
show = false
}
) {
Text(mantis.getResource("no_update_key"))
}
}
},
confirmButton = {
TextButton(
onClick = {
confirmAction.invoke()
isInstalling.value = !isInstalling.value
}
) {
Text(
text = if(!isInstalling.value)
mantis.getResource("update_key")
else
mantis.getResource("dismiss_key")
)
}
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
2908bc7f6b97aed209544757cf185db25ad5bc53
| 13,470
|
OctocatKDU
|
MIT License
|
app/src/main/java/online/taxcore/pos/ui/settings/SettingsActivity.kt
|
Data-Tech-International
| 581,201,452
| false
|
{"Kotlin": 359911, "Java": 64900}
|
package online.taxcore.pos.ui.settings
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.secundary_activity.*
import online.taxcore.pos.R
import online.taxcore.pos.extensions.addFragment
import online.taxcore.pos.ui.base.BaseActivity
class SettingsActivity : BaseActivity() {
private val settingsDashFragment by lazy { SettingsDashFragment() }
companion object {
fun start(activity: AppCompatActivity, type: String = "") {
val intent = Intent(activity, SettingsActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK)
}
ActivityCompat.startActivity(activity, intent, null)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.secundary_activity)
initToolbar()
setActiveFragment()
}
private fun initToolbar() {
setSupportActionBar(fragmentToolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
}
private fun setActiveFragment() {
fragmentToolbar.title = getString(R.string.title_settings)
addFragment(settingsDashFragment, R.id.activityFragment)
}
}
| 1
|
Kotlin
|
3
| 4
|
3b71009b206d1ffa579991076200fe1c9a955ed5
| 1,543
|
Taxcore-MobilePOS-Android
|
MIT License
|
src/commonMain/kotlin/data/items/VengefulGladiatorsSalvation.kt
|
marisa-ashkandi
| 332,658,265
| false
| null |
package `data`.items
import `data`.Constants
import `data`.buffs.Buffs
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class VengefulGladiatorsSalvation : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 33743
public override var name: String = "Vengeful Gladiator's Salvation"
public override var itemLevel: Int = 146
public override var quality: Int = 4
public override var icon: String = "inv_mace_56.jpg"
public override var inventorySlot: Int = 21
public override var itemSet: ItemSet? = null
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.WEAPON
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.MACE_1H
public override var allowableClasses: Array<Constants.AllowableClass>? = null
public override var minDmg: Double = 16.1200008392334
public override var maxDmg: Double = 116.12000274658203
public override var speed: Double = 1600.0
public override var stats: Stats = Stats(
stamina = 35,
intellect = 23,
resilienceRating = 21.0
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override val buffs: List<Buff> by lazy {
listOfNotNull(
Buffs.byIdOrName(43460, "Increase Healing 464", this)
)}
}
| 21
|
Kotlin
|
11
| 25
|
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
| 1,660
|
tbcsim
|
MIT License
|
order/src/main/kotlin/kz/kasip/order/ui/offerservice/OfferAServiceViewModelFactory.kt
|
SherkhanAmandyk
| 772,507,371
| false
|
{"Kotlin": 248568}
|
package kz.kasip.order.ui.offerservice
import dagger.assisted.AssistedFactory
import kz.kasip.order.OrderUi
@AssistedFactory
interface OfferAServiceViewModelFactory {
fun create(orderUi: OrderUi): OfferAServiceViewModel
}
| 0
|
Kotlin
|
0
| 0
|
cd2647641c6633a34174402387bdbbb59203b32b
| 227
|
kasip-kz
|
Apache License 2.0
|
app/src/main/java/com/example/nvblog/ui/browser/BrowserViewModel.kt
|
aucd29
| 201,148,243
| false
| null |
package com.example.nvblog.ui.browser
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import javax.inject.Inject
/**
* Created by <a href="mailto:<EMAIL>"><NAME></a> on 2019-08-09 <p/>
*/
class BrowserViewModel @Inject @JvmOverloads constructor(
application: Application
) : AndroidViewModel(application) {
}
| 1
| null |
1
| 1
|
feb3fcc7d1cac80a7db0b6ce392bb0fce54710c7
| 344
|
nvblog
|
Apache License 2.0
|
src/main/java/net/sharplab/epubtranslator/core/service/EPubTranslatorException.kt
|
sharplab
| 273,607,985
| false
| null |
package net.sharplab.epubtranslator.core.service
class EPubTranslatorException(e: Exception?) : RuntimeException(e)
| 8
|
Kotlin
|
7
| 88
|
b7cf3c966b16906618e85ed750d2d515da7c079d
| 116
|
epub-translator
|
Apache License 2.0
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/logs/MetricFilterOptionsDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.logs
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Number
import kotlin.String
import kotlin.collections.Map
import software.amazon.awscdk.services.cloudwatch.Unit
import software.amazon.awscdk.services.logs.IFilterPattern
import software.amazon.awscdk.services.logs.MetricFilterOptions
/**
* Properties for a MetricFilter created from a LogGroup.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.cloudwatch.*;
* import software.amazon.awscdk.services.logs.*;
* IFilterPattern filterPattern;
* MetricFilterOptions metricFilterOptions = MetricFilterOptions.builder()
* .filterPattern(filterPattern)
* .metricName("metricName")
* .metricNamespace("metricNamespace")
* // the properties below are optional
* .defaultValue(123)
* .dimensions(Map.of(
* "dimensionsKey", "dimensions"))
* .filterName("filterName")
* .metricValue("metricValue")
* .unit(Unit.SECONDS)
* .build();
* ```
*/
@CdkDslMarker
public class MetricFilterOptionsDsl {
private val cdkBuilder: MetricFilterOptions.Builder = MetricFilterOptions.builder()
/**
* @param defaultValue The value to emit if the pattern does not match a particular event.
*/
public fun defaultValue(defaultValue: Number) {
cdkBuilder.defaultValue(defaultValue)
}
/**
* @param dimensions The fields to use as dimensions for the metric.
* One metric filter can include as many as three dimensions.
*/
public fun dimensions(dimensions: Map<String, String>) {
cdkBuilder.dimensions(dimensions)
}
/**
* @param filterName The name of the metric filter.
*/
public fun filterName(filterName: String) {
cdkBuilder.filterName(filterName)
}
/**
* @param filterPattern Pattern to search for log events.
*/
public fun filterPattern(filterPattern: IFilterPattern) {
cdkBuilder.filterPattern(filterPattern)
}
/**
* @param metricName The name of the metric to emit.
*/
public fun metricName(metricName: String) {
cdkBuilder.metricName(metricName)
}
/**
* @param metricNamespace The namespace of the metric to emit.
*/
public fun metricNamespace(metricNamespace: String) {
cdkBuilder.metricNamespace(metricNamespace)
}
/**
* @param metricValue The value to emit for the metric.
* Can either be a literal number (typically "1"), or the name of a field in the structure
* to take the value from the matched event. If you are using a field value, the field
* value must have been matched using the pattern.
*
* If you want to specify a field from a matched JSON structure, use '$.fieldName',
* and make sure the field is in the pattern (if only as '$.fieldName = *').
*
* If you want to specify a field from a matched space-delimited structure,
* use '$fieldName'.
*/
public fun metricValue(metricValue: String) {
cdkBuilder.metricValue(metricValue)
}
/**
* @param unit The unit to assign to the metric.
*/
public fun unit(unit: Unit) {
cdkBuilder.unit(unit)
}
public fun build(): MetricFilterOptions = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 3,407
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/com/yubo/han/toe/Services/MetroStationsAdapter.kt
|
Yurockkk
| 120,151,819
| false
| null |
package com.yubo.han.toe.Services
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.yubo.han.toe.R
import com.yubo.han.toe.model.MetroStations
import kotlinx.android.synthetic.main.row_metro_station.view.*
import com.yubo.han.toe.Utilities
/**
* Created by han on 9/25/17.
*/
class MetroStationsAdapter(private var context: Context, private var stationList: ArrayList<MetroStations>): RecyclerView.Adapter<MetroStationsAdapter.ViewHolder>() {
private val LOG_TAG = "MetroStationsAdapter"
lateinit var itemClickListener: OnItemClickListener
override fun getItemCount() = stationList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.row_metro_station, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Set all line button invisiable
holder.itemView.metro_line_primary_button.visibility = View.INVISIBLE
holder.itemView.metro_line_sec_button.visibility = View.INVISIBLE
holder.itemView.metro_line_th_button.visibility = View.INVISIBLE
val station = stationList.get(position)
holder.itemView.stationName.text = station.name
// Set primary metro line icon
val primaryLineColor = Utilities.getLineColor(station.lineCode1)
holder.itemView.metro_line_primary_button.setBackgroundResource(primaryLineColor)
holder.itemView.metro_line_primary_button.visibility = View.VISIBLE
// if more metrolines in this station
if (!station.lineCode2.isNullOrEmpty()) {
val secLineColor = Utilities.getLineColor(station.lineCode2.toString())
holder.itemView.metro_line_sec_button.setBackgroundResource(secLineColor)
holder.itemView.metro_line_sec_button.visibility = View.VISIBLE
if (!station.lineCode3.isNullOrEmpty()) {
val secLineColor = Utilities.getLineColor(station.lineCode3.toString())
holder.itemView.metro_line_th_button.setBackgroundResource(secLineColor)
holder.itemView.metro_line_th_button.visibility = View.VISIBLE
}
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
init {
itemView.stationHolder.setOnClickListener(this)
}
override fun onClick(view: View) = itemClickListener.onItemClick(itemView,
stationList.get(adapterPosition))
}
interface OnItemClickListener {
fun onItemClick(view: View, stationData: MetroStations)
}
// setter method
fun setOnItemClickListener(itemClickListener: OnItemClickListener) {
this.itemClickListener = itemClickListener
}
// Search
fun filterList(filterStations: ArrayList<MetroStations>) {
this.stationList = filterStations
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
0
| 0
|
a3fa47b55a86e1aab4286c0845c8b3471e992f28
| 3,127
|
TOE-DCMetroExplorer
|
MIT License
|
app/src/main/java/com/yubo/han/toe/Services/MetroStationsAdapter.kt
|
Yurockkk
| 120,151,819
| false
| null |
package com.yubo.han.toe.Services
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.yubo.han.toe.R
import com.yubo.han.toe.model.MetroStations
import kotlinx.android.synthetic.main.row_metro_station.view.*
import com.yubo.han.toe.Utilities
/**
* Created by han on 9/25/17.
*/
class MetroStationsAdapter(private var context: Context, private var stationList: ArrayList<MetroStations>): RecyclerView.Adapter<MetroStationsAdapter.ViewHolder>() {
private val LOG_TAG = "MetroStationsAdapter"
lateinit var itemClickListener: OnItemClickListener
override fun getItemCount() = stationList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.row_metro_station, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Set all line button invisiable
holder.itemView.metro_line_primary_button.visibility = View.INVISIBLE
holder.itemView.metro_line_sec_button.visibility = View.INVISIBLE
holder.itemView.metro_line_th_button.visibility = View.INVISIBLE
val station = stationList.get(position)
holder.itemView.stationName.text = station.name
// Set primary metro line icon
val primaryLineColor = Utilities.getLineColor(station.lineCode1)
holder.itemView.metro_line_primary_button.setBackgroundResource(primaryLineColor)
holder.itemView.metro_line_primary_button.visibility = View.VISIBLE
// if more metrolines in this station
if (!station.lineCode2.isNullOrEmpty()) {
val secLineColor = Utilities.getLineColor(station.lineCode2.toString())
holder.itemView.metro_line_sec_button.setBackgroundResource(secLineColor)
holder.itemView.metro_line_sec_button.visibility = View.VISIBLE
if (!station.lineCode3.isNullOrEmpty()) {
val secLineColor = Utilities.getLineColor(station.lineCode3.toString())
holder.itemView.metro_line_th_button.setBackgroundResource(secLineColor)
holder.itemView.metro_line_th_button.visibility = View.VISIBLE
}
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
init {
itemView.stationHolder.setOnClickListener(this)
}
override fun onClick(view: View) = itemClickListener.onItemClick(itemView,
stationList.get(adapterPosition))
}
interface OnItemClickListener {
fun onItemClick(view: View, stationData: MetroStations)
}
// setter method
fun setOnItemClickListener(itemClickListener: OnItemClickListener) {
this.itemClickListener = itemClickListener
}
// Search
fun filterList(filterStations: ArrayList<MetroStations>) {
this.stationList = filterStations
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
0
| 0
|
a3fa47b55a86e1aab4286c0845c8b3471e992f28
| 3,127
|
TOE-DCMetroExplorer
|
MIT License
|
apps/server/src/main/kotlin/com/keygenqt/mb/routing/user/organizers.kt
|
keygenqt
| 815,799,361
| false
|
{"JavaScript": 609467, "Kotlin": 438860, "SCSS": 15489, "PHP": 5404, "HTML": 3459, "CSS": 2509, "Dockerfile": 104}
|
/*
* Copyright 2024 <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 com.keygenqt.mb.routing.guest
import com.keygenqt.mb.base.Exceptions
import com.keygenqt.mb.extension.getNumberParam
import com.keygenqt.mb.extension.getUserRoles
import com.keygenqt.mb.shared.db.entities.toResponse
import com.keygenqt.mb.shared.db.entities.toResponses
import com.keygenqt.mb.shared.db.service.CitiesService
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.koin.ktor.ext.inject
fun Route.guestCities() {
val citiesService: CitiesService by inject()
route("/cities") {
get {
// act
val response = citiesService.transaction {
getAll().toResponses(call.getUserRoles())
}
// response
call.respond(response)
}
get("/{id}") {
// get request
val id = call.getNumberParam()
// act
val response = citiesService.transaction {
findById(id)?.toResponse(call.getUserRoles()) ?: throw Exceptions.NotFound()
}
// response
call.respond(response)
}
}
}
| 0
|
JavaScript
|
1
| 11
|
cac59e138d47d232a349613686af6bad727028bd
| 1,737
|
kmp-mb
|
Apache License 2.0
|
integ-tests/src/commonTest/kotlin/dev/evo/elasticmagic/qf/AttrSimpleFiltersTest.kt
|
anti-social
| 344,848,222
| false
| null |
package dev.evo.elasticmagic.qf
import dev.evo.elasticmagic.ElasticsearchTestBase
import dev.evo.elasticmagic.SearchQuery
import io.kotest.matchers.shouldBe
import kotlin.test.Test
class AttrSimpleFiltersTest : ElasticsearchTestBase() {
override val indexName = "attr-simple-filter"
object ItemQueryFilters : QueryFilters() {
val selectAttrs by AttrSimpleFilter(ItemDoc.selectAttrs, "attr")
val rangeAttrs by AttrRangeSimpleFilter(ItemDoc.rangeAttrs, "attr")
val boolAttrs by AttrBoolSimpleFilter(ItemDoc.boolAttrs, "attr")
}
@Test
fun attrSimpleFilterTest() = runTestWithSerdes {
withFixtures(ItemDoc, FIXTURES) {
val searchQuery = SearchQuery()
val result = searchQuery.search(index)
result.totalHits shouldBe 8
ItemQueryFilters.apply(
searchQuery,
mapOf(listOf("attr", Manufacturer.ATTR_ID.toString(), "any") to listOf("1", "0"))
).let {
val searchResult = searchQuery.search(index)
searchResult.totalHits shouldBe 4
}
}
}
@Test
fun attrBoolSimpleFilterTest() = runTestWithSerdes {
withFixtures(ItemDoc, FIXTURES) {
val searchQuery = SearchQuery()
searchQuery.search(index).totalHits shouldBe 8
ItemQueryFilters.apply(
searchQuery,
mapOf(listOf("attr", ExtensionSlot.ATTR_ID.toString()) to listOf("true"))
).let {
val searchResult = searchQuery.search(index)
searchResult.totalHits shouldBe 3
}
}
}
@Test
fun attrRangeSimpleFilterTest() = runTestWithSerdes {
withFixtures(ItemDoc, FIXTURES) {
val searchQuery = SearchQuery()
searchQuery.search(index).totalHits shouldBe 8
ItemQueryFilters.apply(
searchQuery,
mapOf(listOf("attr", DisplaySize.ATTR_ID.toString(), "gte") to listOf("6.7"))
).let {
val searchResult = searchQuery.search(index)
searchResult.totalHits shouldBe 3
}
}
}
@Test
fun applyAllSimpleFilters() = runTestWithSerdes {
withFixtures(ItemDoc, FIXTURES) {
val searchQuery = SearchQuery()
searchQuery.search(index).totalHits shouldBe 8
ItemQueryFilters.apply(
searchQuery,
mapOf(
listOf("attr", Manufacturer.ATTR_ID.toString(), "any") to listOf("1", "0"),
listOf("attr", ExtensionSlot.ATTR_ID.toString()) to listOf("false"),
listOf("attr", DisplaySize.ATTR_ID.toString(), "gte") to listOf("6.3"),
)
).let {
val searchResult = searchQuery.search(index)
searchResult.totalHits shouldBe 2
val qfResult = it.processResult(searchResult)
qfResult[ItemQueryFilters.selectAttrs].let { filter ->
filter.name shouldBe "selectAttrs"
filter.paramName shouldBe "attr"
}
qfResult[ItemQueryFilters.boolAttrs].let { filter ->
filter.name shouldBe "boolAttrs"
filter.paramName shouldBe "attr"
}
qfResult[ItemQueryFilters.rangeAttrs].let { filter ->
filter.name shouldBe "rangeAttrs"
filter.paramName shouldBe "attr"
}
}
}
}
}
| 9
| null |
5
| 45
|
ab6e9ee73108c6a0520a06ae1855a35ec183ff8d
| 3,601
|
elasticmagic-kt
|
Apache License 2.0
|
core/model/src/commonMain/kotlin/club/nito/core/model/participant/ParticipantDeclaration.kt
|
2rabs
| 711,156,470
| false
|
{"Kotlin": 211834, "Swift": 20406, "Shell": 1287, "HTML": 269, "Makefile": 246}
|
package club.nito.core.model.participant
/**
* 参加表明
* @param scheduleId スケジュールID
* @param memberId メンバーID
* @param comment コメント
*/
data class ParticipantDeclaration(
val scheduleId: String,
val memberId: String,
val comment: String,
)
| 1
|
Kotlin
|
0
| 0
|
d27bfca23e776be569ea217e7a98e19cc1832d0f
| 253
|
nito-app
|
MIT License
|
src/main/kotlin/dev/storozhenko/familybot/services/routers/PaymentRouter.kt
|
AngryJKirk
| 114,262,178
| false
| null |
package space.yaroslav.familybot.services.routers
import org.springframework.stereotype.Component
import org.telegram.telegrambots.meta.api.methods.AnswerPreCheckoutQuery
import org.telegram.telegrambots.meta.api.methods.send.SendMessage
import org.telegram.telegrambots.meta.api.objects.Update
import org.telegram.telegrambots.meta.bots.AbsSender
import space.yaroslav.familybot.common.extensions.key
import space.yaroslav.familybot.common.extensions.parseJson
import space.yaroslav.familybot.common.extensions.toChat
import space.yaroslav.familybot.common.extensions.toUser
import space.yaroslav.familybot.getLogger
import space.yaroslav.familybot.models.dictionary.Phrase
import space.yaroslav.familybot.models.shop.PreCheckOutResponse
import space.yaroslav.familybot.models.shop.ShopPayload
import space.yaroslav.familybot.models.shop.SuccessPaymentResponse
import space.yaroslav.familybot.repos.CommonRepository
import space.yaroslav.familybot.services.payment.PaymentService
import space.yaroslav.familybot.services.settings.ChatEasyKey
import space.yaroslav.familybot.services.talking.Dictionary
import space.yaroslav.familybot.telegram.BotConfig
@Component
class PaymentRouter(
private val paymentService: PaymentService,
private val commonRepository: CommonRepository,
private val dictionary: Dictionary,
private val botConfig: BotConfig
) {
private val log = getLogger()
fun proceedPreCheckoutQuery(update: Update): suspend (AbsSender) -> Unit {
val shopPayload = getPayload(update.preCheckoutQuery.invoicePayload)
val settingsKey = ChatEasyKey(shopPayload.chatId)
val chatId = shopPayload.chatId.toString()
return { sender ->
runCatching { paymentService.processPreCheckoutCheck(shopPayload) }
.onFailure { e ->
log.error("Can not check pre checkout query", e)
val message = dictionary.get(Phrase.SHOP_PRE_CHECKOUT_FAIL, settingsKey)
sender.execute(AnswerPreCheckoutQuery(update.preCheckoutQuery.id, false, message))
sender.execute(SendMessage(chatId, message))
}
.onSuccess { response ->
when (response) {
is PreCheckOutResponse.Success -> {
sender.execute(AnswerPreCheckoutQuery(update.preCheckoutQuery.id, true))
log.info("Pre checkout query is valid")
}
is PreCheckOutResponse.Error -> {
val message = dictionary.get(response.explainPhrase, settingsKey)
sender.execute(
AnswerPreCheckoutQuery(
update.preCheckoutQuery.id,
false,
message
)
)
sender.execute(SendMessage(chatId, message))
}
}
}
}
}
fun proceedSuccessfulPayment(update: Update): suspend (AbsSender) -> Unit {
val shopPayload = getPayload(update.message.successfulPayment.invoicePayload)
return { sender ->
runCatching { paymentService.processSuccessfulPayment(shopPayload) }
.onFailure { e ->
log.error("Can not process payment", e)
onFailure(sender, update, shopPayload)
}
.onSuccess { result ->
log.info("Wow, payment!")
onSuccess(sender, update, result, shopPayload)
}
}
}
private fun onSuccess(
sender: AbsSender,
update: Update,
successPaymentResponse: SuccessPaymentResponse,
shopPayload: ShopPayload
) {
val developerId = botConfig.developerId
val user = update.toUser()
val chatKey = update.toChat().key()
val text = dictionary.get(Phrase.SHOP_THANKS, chatKey)
.replace("$0", user.getGeneralName())
.replace("$1", "@" + botConfig.developer)
val chatId = shopPayload.chatId.toString()
sender.execute(SendMessage(chatId, text))
sender.execute(SendMessage(chatId, dictionary.get(successPaymentResponse.phrase, chatKey)))
successPaymentResponse.customCall(sender)
val chat = commonRepository
.getChatsByUser(user)
.find { shopPayload.chatId == it.id }
?.name ?: "[???]"
val message =
"<b>+${shopPayload.shopItem.price / 100}₽</b> от ${user.getGeneralName()} из чата <b>$chat</b> за <b>${shopPayload.shopItem}</b>"
sender.execute(
SendMessage(developerId, message).apply {
enableHtml(true)
}
)
}
private fun onFailure(
sender: AbsSender,
update: Update,
shopPayload: ShopPayload
) {
val developerId = botConfig.developerId
val text = dictionary.get(Phrase.SHOP_ERROR, update.toChat().key()).replace("$1", "@" + botConfig.developer)
sender.execute(SendMessage(shopPayload.chatId.toString(), text))
sender.execute(SendMessage(developerId, "Payment gone wrong: $update"))
}
private fun getPayload(invoicePayload: String): ShopPayload {
return invoicePayload.parseJson()
}
}
| 0
| null |
4
| 97
|
aff071c72503ffb9ad276fb9cc33d8408196795d
| 5,486
|
familybot
|
Apache License 2.0
|
winter/src/test/kotlin/io/jentz/winter/adapter/ApplicationGraphOnlyAdapterTest.kt
|
AlexWih
| 156,714,313
| true
|
{"Kotlin": 306587, "HTML": 9144, "Java": 5620, "Ruby": 2097}
|
package io.jentz.winter.adapter
import io.jentz.winter.*
import io.kotlintest.matchers.boolean.shouldBeTrue
import io.kotlintest.matchers.types.shouldBeInstanceOf
import io.kotlintest.matchers.types.shouldBeSameInstanceAs
import io.kotlintest.shouldThrow
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class ApplicationGraphOnlyAdapterTest {
private val testApplication = WinterApplication {}
private val tree = WinterTree(testApplication)
private val adapter = ApplicationGraphOnlyAdapter(tree)
private val injection = WinterInjection()
@BeforeEach
fun beforeEach() {
tree.closeIfOpen()
}
@Test
fun `#getGraph should throw an exception if no root graph is open`() {
shouldThrow<WinterException> { adapter.getGraph(Any()) }
}
@Test
fun `#getGraph should return root graph for any argument`() {
val graph = tree.open()
repeat(2) { adapter.getGraph(Any()).shouldBeSameInstanceAs(graph) }
}
@Test
fun `#createGraph should open root graph`() {
adapter.createGraph(Any(), null)
tree.has().shouldBeTrue()
}
@Test
fun `#createGraph should apply builder block`() {
adapter.createGraph(Any()) { constant("") }
tree.get().component.shouldContainService(typeKey<String>())
}
@Test
fun `#createGraph should throw an exception if root graph is already open`() {
tree.open()
shouldThrow<WinterException> { adapter.createGraph(Any(), null) }
}
@Test
fun `#disposeGraph should dispose root graph`() {
tree.open()
expectValueToChange(true, false, { tree.has() }) {
adapter.disposeGraph(Any())
}
}
@Test
fun `#disposeGraph should throw an excpetion if root graph is not open`() {
shouldThrow<WinterException> { adapter.disposeGraph(Any()) }
}
@Test
fun `#useApplicationGraphOnlyAdapter with tree should register adapter with given tree`() {
injection.useApplicationGraphOnlyAdapter(tree)
injection.adapter.shouldBeInstanceOf<ApplicationGraphOnlyAdapter>()
tree.open()
injection.adapter.getGraph(Any()).shouldBeSameInstanceAs(tree.get())
}
@Test
fun `#useApplicationGraphOnlyAdapter with application should register adapter with application`() {
injection.useApplicationGraphOnlyAdapter(testApplication)
injection.adapter.shouldBeInstanceOf<ApplicationGraphOnlyAdapter>()
injection.adapter.createGraph(Any(), null)
.component.shouldBeSameInstanceAs(testApplication.component)
}
}
| 0
|
Kotlin
|
0
| 0
|
3c0ea4336c87fcbe38143dd6787390756fbfc68f
| 2,632
|
winter
|
Apache License 2.0
|
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnDashboardMappedDataSetParameterPropertyDsl.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 63959868}
|
@file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.quicksight.CfnDashboard
/**
* A dataset parameter that is mapped to an analysis parameter.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* MappedDataSetParameterProperty mappedDataSetParameterProperty =
* MappedDataSetParameterProperty.builder()
* .dataSetIdentifier("dataSetIdentifier")
* .dataSetParameterName("dataSetParameterName")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-dashboard-mappeddatasetparameter.html)
*/
@CdkDslMarker
public class CfnDashboardMappedDataSetParameterPropertyDsl {
private val cdkBuilder: CfnDashboard.MappedDataSetParameterProperty.Builder =
CfnDashboard.MappedDataSetParameterProperty.builder()
/**
* @param dataSetIdentifier A unique name that identifies a dataset within the analysis or
* dashboard.
*/
public fun dataSetIdentifier(dataSetIdentifier: String) {
cdkBuilder.dataSetIdentifier(dataSetIdentifier)
}
/** @param dataSetParameterName The name of the dataset parameter. */
public fun dataSetParameterName(dataSetParameterName: String) {
cdkBuilder.dataSetParameterName(dataSetParameterName)
}
public fun build(): CfnDashboard.MappedDataSetParameterProperty = cdkBuilder.build()
}
| 4
|
Kotlin
|
0
| 3
|
c59c6292cf08f0fc3280d61e7f8cff813a608a62
| 1,823
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
cinescout/recommended/data/remote/src/commonMain/kotlin/cinescout/recommended/data/remote/model/TraktScreenplayRecommendedMetadata.kt
|
fardavide
| 280,630,732
| false
| null |
package cinescout.recommended.data.remote.model
import cinescout.screenplay.domain.model.id.ScreenplayIds
import cinescout.screenplay.domain.model.id.TmdbScreenplayId
import cinescout.screenplay.domain.model.id.TraktScreenplayId
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import screenplay.data.remote.trakt.model.TraktContentType
import screenplay.data.remote.trakt.model.TraktMovieMetadataBody
import screenplay.data.remote.trakt.model.TraktTvShowMetadataBody
typealias TraktScreenplaysRecommendedMetadataResponse = List<TraktScreenplayRecommendedMetadataBody>
@Serializable(with = TraktScreenplayRecommendedMetadataSerializer::class)
sealed interface TraktScreenplayRecommendedMetadataBody {
val tmdbId: TmdbScreenplayId
val traktId: TraktScreenplayId
val ids: ScreenplayIds
get() = ScreenplayIds(tmdbId, traktId)
}
@Serializable
private data class TraktScreenplayRecommendedMetadataSurrogate(
@SerialName(TraktContentType.Movie)
val movie: TraktMovieMetadataBody? = null,
@SerialName(TraktContentType.TvShow)
val tvShow: TraktTvShowMetadataBody? = null
)
private object TraktScreenplayRecommendedMetadataSerializer : KSerializer<TraktScreenplayRecommendedMetadataBody> {
override val descriptor = TraktScreenplayRecommendedMetadataSurrogate.serializer().descriptor
override fun deserialize(decoder: Decoder): TraktScreenplayRecommendedMetadataBody {
val surrogate = TraktScreenplayRecommendedMetadataSurrogate.serializer().deserialize(decoder)
return when {
surrogate.movie != null -> TraktMovieRecommendedMetadataBody(surrogate.movie)
surrogate.tvShow != null -> TraktTvShowRecommendedMetadataBody(surrogate.tvShow)
else -> error("Invalid Trakt screenplay watchlist metadata")
}
}
override fun serialize(encoder: Encoder, value: TraktScreenplayRecommendedMetadataBody) {
val surrogate = when (value) {
is TraktMovieRecommendedMetadataBody -> TraktScreenplayRecommendedMetadataSurrogate(movie = value.movie)
is TraktTvShowRecommendedMetadataBody -> TraktScreenplayRecommendedMetadataSurrogate(tvShow = value.tvShow)
}
TraktScreenplayRecommendedMetadataSurrogate.serializer().serialize(encoder, surrogate)
}
}
| 14
|
Kotlin
|
2
| 6
|
f2e3993816452afaf6c3f1e7c7a384eb9a66c06e
| 2,460
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/nora/rickscrate/data/model/EpisodeResponse.kt
|
NoraHeithur
| 508,081,858
| false
|
{"Kotlin": 75432}
|
package com.nora.rickscrate.data.model
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Json
@JsonClass(generateAdapter = true)
data class EpisodeResponse(
@Json(name = "id")
val id: Int,
@Json(name = "name")
val name: String,
@Json(name = "air_date")
val airDate: String,
@Json(name = "episode")
val code: String,
@Json(name = "characters")
val characters: List<String>,
@Json(name = "url")
val episodeEndpoint: String,
@Json(name = "created")
val created: String
)
| 0
|
Kotlin
|
0
| 0
|
bc43b19f719ec19c08eead8f0371a83107d94101
| 537
|
RicksCrate
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/jobsboard/api/jobs/application/GetMatchingCandidateJobsResponse.kt
|
ministryofjustice
| 775,484,528
| false
|
{"Kotlin": 314546, "Dockerfile": 1362}
|
package uk.gov.justice.digital.hmpps.jobsboard.api.jobs.application
import java.time.Instant
import java.time.LocalDate
data class GetMatchingCandidateJobsResponse(
val id: String,
val jobTitle: String,
val employerName: String,
val sector: String,
val postcode: String,
val closingDate: LocalDate? = null,
val hasExpressedInterest: Boolean = false,
val createdAt: Instant? = null,
val distance: Float = 0f,
)
| 1
|
Kotlin
|
0
| 1
|
95e47cf678870a867c50d53ab53f6b3f51a45350
| 430
|
hmpps-jobs-board-api
|
MIT License
|
components/messaging-support/src/test/kotlin/test/collective/messaging/TestCancelHandler.kt
|
lpriyasivakumar
| 695,890,383
| false
|
{"Kotlin": 64097, "CSS": 9510, "FreeMarker": 3587, "Dockerfile": 338, "Shell": 267}
|
package test.collective.messaging
import com.rabbitmq.client.CancelCallback
class TestCancelHandler : CancelCallback {
override fun handle(consumerTag: String?) {
}
}
| 0
|
Kotlin
|
0
| 0
|
2ca16a2fd7ddf343d32a0bc584f6d8db75ff7347
| 176
|
daily-news-feed
|
Apache License 2.0
|
trimindent-compiler/testData/blankLine.kt
|
bennyhuo
| 499,044,675
| false
|
{"Kotlin": 18621}
|
// SOURCE
// FILE: Main.kt [MainKt#main]
val s = """
hello
""".trimIndent()
val s1 = """
$s
""".trimIndent()
val s2 = """
hello
$s
world
""".trimIndent()
fun main() {
println(s)
println(s1)
println(s2)
}
// EXPECT
// FILE: MainKt.main.stdout
hello
hello
hello
hello
world
// FILE: Main.kt.ir
val s: String = "\nhello\n"
val s1: String = "${s}"
val s2: String = " hello\n${s}\n world"
fun main() {
println(s)
println(s1)
println(s2)
}
| 0
|
Kotlin
|
2
| 40
|
c4355d89309c90e23e93543123365896feef498e
| 557
|
Kotlin-Trim-Indent
|
MIT License
|
auth/src/commonMain/kotlin/ResolveRelationsTo.kt
|
crowdproj
| 518,714,370
| false
| null |
package com.crowdproj.rating.auth
import com.crowdproj.rating.common.model.CwpRating
import com.crowdproj.rating.common.model.CwpRatingId
import com.crowdproj.rating.common.model.CwpRatingVisibility
import com.crowdproj.rating.common.permission.CwpRatingPrincipalModel
import com.crowdproj.rating.common.permission.CwpRatingPrincipalRelations
fun CwpRating.resolveRelationsTo(principal: CwpRatingPrincipalModel): Set<CwpRatingPrincipalRelations> =
setOfNotNull(
CwpRatingPrincipalRelations.NONE,
CwpRatingPrincipalRelations.NEW.takeIf { id == CwpRatingId.NONE },
CwpRatingPrincipalRelations.OWN.takeIf { principal.id == ownerId },
CwpRatingPrincipalRelations.MODERATABLE.takeIf { visibility != CwpRatingVisibility.VISIBLE_TO_OWNER },
CwpRatingPrincipalRelations.PUBLIC.takeIf { visibility == CwpRatingVisibility.VISIBLE_PUBLIC },
)
| 0
|
Kotlin
|
2
| 0
|
680c52b3be9161b699c635fc032a0289ce71a239
| 881
|
crowdproj-ratings
|
Apache License 2.0
|
app/src/main/java/com/zlucas2k/mytask/domain/model/Priority.kt
|
zLuCaS2K
| 238,888,752
| false
| null |
package com.zlucas2k.mytask.domain.model
enum class Priority {
HIGH,
MEDIUM,
LOW,
NONE,
}
| 0
| null |
3
| 8
|
4bdcca1f17f45971bdf63253046df63cc805a76c
| 106
|
MyTask
|
MIT License
|
app/src/main/java/com/zlucas2k/mytask/domain/model/Priority.kt
|
zLuCaS2K
| 238,888,752
| false
| null |
package com.zlucas2k.mytask.domain.model
enum class Priority {
HIGH,
MEDIUM,
LOW,
NONE,
}
| 0
| null |
3
| 8
|
4bdcca1f17f45971bdf63253046df63cc805a76c
| 106
|
MyTask
|
MIT License
|
AR-Android-Voice-Base/app/src/main/java/org/ar/ar_android_voice_base/InfoAdapter.kt
|
asdlei99
| 355,028,252
| true
|
{"Objective-C": 17114, "Kotlin": 9782, "Ruby": 285}
|
package org.ar.ar_android_voice_base
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
class InfoAdapter: BaseQuickAdapter<InfoBean,BaseViewHolder>(R.layout.layout_info){
override fun convert(holder: BaseViewHolder, item: InfoBean) {
holder.setText(R.id.userId,item.userId)
if (item.isSelf){
holder.setVisible(R.id.self, true)
holder.setText(R.id.txaudio, item.txAudio.toString()+"Kb/s")
}else{
holder.setVisible(R.id.self, false)
holder.setVisible(R.id.txaudio,false)
}
holder.setText(R.id.rxaudio,item.rxAudio.toString()+"Kb/s")
}
}
| 0
| null |
0
| 0
|
8669630272cd945b48ada0518c888001b549195f
| 725
|
Basic-Audio-Example
|
MIT License
|
samples/starter-mobile-app/src/main/kotlin/researchstack/presentation/screen/task/activity/ActivityInstructionScreen.kt
|
S-ResearchStack
| 520,365,275
| false
|
{"Kotlin": 178868, "AIDL": 4785}
|
package researchstack.presentation.screen.task.activity
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import researchstack.domain.model.task.activity.ActivityInstruction
import researchstack.presentation.component.AppTextButton
import researchstack.presentation.component.ListedText
import researchstack.presentation.component.TopBar
import researchstack.presentation.theme.AppTheme
import java.time.OffsetDateTime
@Composable
internal fun ActivityInstructionScreen(
instruction: ActivityInstruction,
onComplete: (Map<String, Any>) -> Unit,
) {
val startTime = OffsetDateTime.now()
Scaffold(
topBar = {
TopBar(instruction.title) { }
},
bottomBar = {
Row(modifier = Modifier.padding(horizontal = 20.dp, vertical = 5.dp)) {
AppTextButton(
text = instruction.buttonText,
onClick = {
onComplete(
mapOf(
"startTime" to startTime.toString(),
"endTime" to OffsetDateTime.now().toString(),
)
)
}
)
}
}
) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Spacer(Modifier.height(56.dp))
Image(
modifier = Modifier.size(250.dp),
painter = painterResource(instruction.imageId),
contentDescription = "image for view"
)
Spacer(Modifier.height(54.dp))
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
text = instruction.header,
style = AppTheme.typography.headline3,
color = AppTheme.colors.onSurface,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(32.dp))
ListedText(instruction.description)
}
}
}
| 5
|
Kotlin
|
20
| 26
|
e31e8055f96fa226745750b5a653e341cf5f2e6c
| 3,037
|
app-sdk
|
Apache License 2.0
|
archetype/src/main/resources/archetype-resources/local-server/src/main/kotlin/localserver/Main.kt
|
cjkent
| 93,342,396
| false
| null |
package ${package}.localserver
import com.beust.jcommander.JCommander
import ws.osiris.localserver.ServerArgs
import ws.osiris.localserver.runLocalServer
import ${package}.core.api
import ${package}.core.createComponents
/**
* Main function for running the application in an HTTP server (Jetty).
*
* The arguments are:
* * `-p`, `--port` - the port the server listens on. Defaults to 8080.
* * `-r`, `--root` - the context root. This is the base path from which everything is served.
*/
fun main(args: Array<String>) {
val serverArgs = ServerArgs()
JCommander.newBuilder().addObject(serverArgs).build().parse(*args)
val components = createComponents()
runLocalServer(api, components, serverArgs.port, serverArgs.root, "core/src/main/static")
}
| 26
| null |
3
| 39
|
30b1327c9808c015881ae5e33ac0d19a23f1e619
| 773
|
osiris
|
Apache License 2.0
|
backend/data/src/main/kotlin/io/tolgee/repository/OrganizationRepository.kt
|
tolgee
| 303,766,501
| false
|
{"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439}
|
package io.tolgee.repository
import io.tolgee.dtos.queryResults.organization.OrganizationView
import io.tolgee.model.Organization
import io.tolgee.model.UserAccount
import io.tolgee.model.enums.OrganizationRoleType
import org.springframework.context.annotation.Lazy
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
@Repository
@Lazy
interface OrganizationRepository : JpaRepository<Organization, Long> {
@Query(
"""
from Organization o
left join fetch o.basePermission as bp
where o.slug = :slug and o.deletedAt is null
""",
)
fun findBySlug(slug: String): Organization?
@Query(
"""select distinct new io.tolgee.dtos.queryResults.organization.OrganizationView(
o.id,
o.name,
o.slug,
o.description,
bp._scopes,
bp.type,
r.type,
o.avatarHash
)
from Organization o
join o.basePermission bp
left join OrganizationRole r on r.user.id = :userId
and r.organization = o and (r.type = :roleType or :roleType is null)
left join o.projects p on p.deletedAt is null
left join p.permissions perm on perm.user.id = :userId
where (perm is not null or r is not null)
and (:search is null or (lower(o.name) like lower(concat('%', cast(:search as text), '%'))))
and (:exceptOrganizationId is null or (o.id <> :exceptOrganizationId)) and o.deletedAt is null
""",
countQuery =
"""select count(o)
from Organization o
left join OrganizationRole r on r.user.id = :userId
and r.organization = o and (r.type = :roleType or :roleType is null)
left join o.projects p on p.deletedAt is null
left join p.permissions perm on perm.user.id = :userId
where (perm is not null or r is not null)
and (:search is null or (lower(o.name) like lower(concat('%', cast(:search as text), '%'))))
and (:exceptOrganizationId is null or (o.id <> :exceptOrganizationId)) and o.deletedAt is null
""",
)
fun findAllPermitted(
userId: Long?,
pageable: Pageable,
roleType: OrganizationRoleType? = null,
search: String? = null,
exceptOrganizationId: Long? = null,
): Page<OrganizationView>
@Query(
"""
select o
from Organization o
left join fetch o.basePermission bp
left join o.memberRoles mr on mr.user.id = :userId
left join o.projects p on p.deletedAt is null
left join p.permissions perm on perm.user.id = :userId
where (perm is not null or mr is not null) and o.id <> :exceptOrganizationId and o.deletedAt is null
group by mr.id, o.id, bp.id
order by mr.id asc nulls last
""",
)
fun findPreferred(
userId: Long,
exceptOrganizationId: Long,
pageable: Pageable,
): Page<Organization>
@Query(
"""
select count(o) > 0
from Organization o
left join o.memberRoles mr on mr.user.id = :userId
left join o.projects p on p.deletedAt is null
left join p.permissions perm on perm.user.id = :userId
where (perm is not null or mr is not null) and o.id = :organizationId and o.deletedAt is null
""",
)
fun canUserView(
userId: Long,
organizationId: Long,
): Boolean
@Query(
"""
select count(o) > 0
from Organization o
where o.slug = :slug
""",
)
fun organizationWithSlugExists(slug: String): Boolean
@Query(
"""
from Organization o
where o.name = :name and o.deletedAt is null
""",
)
fun findAllByName(name: String): List<Organization>
@Query(
"""
from Organization o
join o.memberRoles mr on mr.user = :user
join mr.user u
where o.name = u.name and mr.type = 1 and o.deletedAt is null
""",
)
fun findUsersDefaultOrganization(user: UserAccount): Organization?
@Query(
"""select distinct new io.tolgee.dtos.queryResults.organization.OrganizationView(
o.id,
o.name,
o.slug,
o.description,
bp._scopes,
bp.type,
r.type,
o.avatarHash
)
from Organization o
join o.basePermission bp
left join OrganizationRole r on r.user.id = :userId and r.organization = o
where (:search is null or (lower(o.name) like lower(concat('%', cast(:search as text), '%'))))
and o.deletedAt is null
""",
countQuery =
"""select count(o)
from Organization o
where (:search is null or (lower(o.name) like lower(concat('%', cast(:search as text), '%'))))
and o.deletedAt is null
""",
)
fun findAllViews(
pageable: Pageable,
search: String?,
userId: Long,
): Page<OrganizationView>
@Query(
"""select o
from Organization o
join o.memberRoles mr on mr.user = :userAccount and mr.type = :type
join o.memberRoles mra on mra.type = :type
where o.deletedAt is null
group by o.id, mr.id
having count(mra.id) = 1
""",
)
fun getAllSingleOwnedByUser(
userAccount: UserAccount,
type: OrganizationRoleType = OrganizationRoleType.OWNER,
): List<Organization>
@Query(
"""
from Organization o
join o.projects p on p.id = :projectId and p.deletedAt is null
join fetch o.basePermission
where o.deletedAt is null
""",
)
fun getProjectOwner(projectId: Long): Organization
@Query(
"""
from Organization o
left join fetch o.basePermission
left join fetch o.mtCreditBucket
where o = :organization
""",
)
fun fetchData(organization: Organization): Organization
@Query(
"""
from Organization o
where o.id = :id and o.deletedAt is null
""",
)
fun find(id: Long): Organization?
@Query(
"""
select new io.tolgee.dtos.queryResults.organization.OrganizationView(
o.id,
o.name,
o.slug,
o.description,
bp._scopes,
bp.type,
r.type,
o.avatarHash
)
from Organization o
join o.basePermission bp
left join o.memberRoles r on r.user.id = :currentUserId
where o.id = :id and o.deletedAt is null
""",
)
fun findView(
id: Long,
currentUserId: Long,
): OrganizationView?
}
| 170
|
TypeScript
|
188
| 1,837
|
6e01eec3a19c151a6e0aca49e187e2d0deef3082
| 6,372
|
tolgee-platform
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.