code
stringlengths 6
1.04M
| language
stringclasses 1
value | AST_depth
int64 -1
40
| alphanumeric_fraction
float64 0
0.97
| max_line_length
int64 0
1k
| avg_line_length
float64 0
171
| num_lines
int64 0
4.25k
| source
stringclasses 1
value |
---|---|---|---|---|---|---|---|
package com.github.daggerok.retry.report
import java.time.LocalDateTime
data class ReportWrapper<T>(
val jobId: Long,
val chunks: List<T>,
val at: LocalDateTime = LocalDateTime.now(),
)
data class LaunchDocument(
val jobId: Long,
)
data class ErrorDocument(
val message: String? = "Unknown error",
)
| kotlin | 8 | 0.709877 | 48 | 18.058824 | 17 | starcoderdata |
<filename>app/src/main/java/com/tomg/githubreleasemonitor/settings/ui/SettingsTopBar.kt<gh_stars>1-10
/*
* Copyright (c) 2020-2021, <NAME> (<EMAIL>)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tomg.githubreleasemonitor.settings.ui
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.tomg.githubreleasemonitor.R
@Composable
fun SettingsTopBar(onNavigateUp: () -> Unit) {
TopAppBar(
title = { Text(text = stringResource(id = R.string.settings)) },
navigationIcon = {
IconButton(onClick = onNavigateUp) {
Icon(
imageVector = Icons.Outlined.ArrowBack,
contentDescription = null,
tint = MaterialTheme.colors.onPrimary.copy(alpha = ContentAlpha.medium)
)
}
}
)
}
| kotlin | 25 | 0.738918 | 101 | 44.12 | 50 | starcoderdata |
buildscript {
// Specifies repositories to use for build.gradle..kts build script classpath,
// used to resolve dependencies specified in `dependencies {}` block below.
// This loads these dependencies to be available for the settings.gradle.kts script
// outside of `buildscript {}` block. It is helpful to load binary plugins that
// might not publish to pom that supports Gradle `plugins {}` DSL
//
// In general, you should avoid using this, unless you have to. Loading plugins with
// `plugins {}` DSL is preferred.
repositories {
mavenCentral()
google()
}
dependencies {
classpath("com.google.guava:guava:31.1-jre")
}
}
// Example of the modern way of loading Gradle plugins. This uses plugin
// repositories defined in settings.gradle.kts `pluginManagement {}` block.
plugins {
id("com.android.application") version "7.3.0-alpha05" apply false
id("java")
}
// Specifies build repositories to use for resolving `dependencies {}` below for this root `:`
// project only. This list of repositories overrides the list of repositories specified in
// settings.gradle.kts `dependencyResolutionManagement {}` block.
//
// Avoid using this, as it only applies to the root project, and it also overrides the centralized
// settings.gradle.kts `dependencyResolutionManagement {}` location that is better.
repositories {
mavenCentral()
google()
}
dependencies {
implementation("com.google.guava:guava:31.1-jre")
}
subprojects {
// Specifies build repositories to use for resolving `dependencies {}` below for all subprojects
// under root `:` project, like `:lib`. This list of repositories overrides the list of
// repositories specified in settings.gradle.kts `dependencyResolutionManagement {}` block.
//
// Avoid using this, as it overrides the centralized settings.gradle.kts
// `dependencyResolutionManagement {}` location that is better.
repositories {
mavenCentral()
google()
}
}
| kotlin | 15 | 0.707101 | 100 | 38 | 52 | starcoderdata |
<gh_stars>1-10
package com.cucerdariancatalin.instagram.common
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.TaskCompletionSource
class TaskSourceOnCompleteListener<T>(private val taskSource: TaskCompletionSource<T>) :
OnCompleteListener<T> {
override fun onComplete(task: Task<T>) {
if (task.isSuccessful) {
taskSource.setResult(task.result)
} else {
taskSource.setException(task.exception!!)
}
}
} | kotlin | 16 | 0.71558 | 88 | 29.722222 | 18 | starcoderdata |
// FILE: inline.kt
// KOTLIN_CONFIGURATION_FLAGS: ASSERTIONS_MODE=jvm
// WITH_RUNTIME
// FULL_JDK
// IGNORE_BACKEND: JVM_IR
// TARGET_BACKEND: JVM
inline fun inlineMe() {
assert(false) { "FROM INLINED" }
}
// FILE: inlineSite.kt
// KOTLIN_CONFIGURATION_FLAGS: ASSERTIONS_MODE=jvm
class CheckerJvmAssertInlineFunctionAssertionsDisabled {
fun check() {
inlineMe()
assert(false) { "FROM INLINESITE" }
}
}
class Dummy
fun disableAssertions(): CheckerJvmAssertInlineFunctionAssertionsDisabled {
val loader = Dummy::class.java.classLoader
loader.setClassAssertionStatus("CheckerJvmAssertInlineFunctionAssertionsDisabled", false)
loader.setClassAssertionStatus("InlineKt", false)
val c = loader.loadClass("CheckerJvmAssertInlineFunctionAssertionsDisabled")
return c.newInstance() as CheckerJvmAssertInlineFunctionAssertionsDisabled
}
fun box(): String {
var c = disableAssertions()
c.check()
return "OK"
} | kotlin | 12 | 0.739627 | 93 | 25.805556 | 36 | starcoderdata |
package d
class T {
fun baz() = 1
}
fun foo() {
public val i = 11
abstract val <!VARIABLE_WITH_NO_TYPE_NO_INITIALIZER!>j<!>
override fun T.baz() = 2
private fun bar() = 2
}
| kotlin | 7 | 0.574359 | 61 | 15.25 | 12 | starcoderdata |
<filename>plugin/src/main/kotlin/mb/coronium/util/TempDir.kt
package mb.coronium.util
import java.io.Closeable
import java.nio.file.DirectoryNotEmptyException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.FileAttribute
/**
* A temporary directory that is deleted when [close]d.
*/
class TempDir(prefix: String) : Closeable {
/**
* Path to the temporary directory.
*/
val path: Path = Files.createTempDirectory(prefix)
/**
* Create a temporary file inside the temporary directory.
*/
fun createTempFile(prefix: String, suffix: String, vararg attrs: FileAttribute<*>): Path {
return Files.createTempFile(path, prefix, suffix, *attrs)
}
/**
* Creates a temporary directory inside the temporary directory.
*/
fun createTempDir(prefix: String, vararg attrs: FileAttribute<*>): Path {
return Files.createTempDirectory(path, prefix, *attrs)
}
/**
* Closes the temporary directory, deleting it and its content.
*/
override fun close() {
try {
deleteNonEmptyDirectoryIfExists(path)
} catch(e: DirectoryNotEmptyException) {
// For some reason, this exception is thrown even though the directory is empty. Ignore it.
}
}
}
| kotlin | 12 | 0.71498 | 97 | 27.72093 | 43 | starcoderdata |
package stream.reconfig.kirinmaru.android.ui.reader
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.TextView
import commons.android.arch.ViewModelFactory
import commons.android.arch.observe
import commons.android.arch.observeNonNull
import commons.android.arch.offline.State
import commons.android.arch.viewModel
import commons.android.core.fragment.DataBindingFragment
import commons.android.core.fullscreen.FullScreenUtil.enterFullscreen
import commons.android.core.fullscreen.FullScreenUtil.exitFullScreen
import commons.android.core.intent.IntentFactory
import stream.reconfig.kirinmaru.android.R
import stream.reconfig.kirinmaru.android.assets.Fonts
import stream.reconfig.kirinmaru.android.databinding.FragmentReaderBinding
import stream.reconfig.kirinmaru.android.databinding.ViewReaderbarBinding
import javax.inject.Inject
class ReaderFragment : DataBindingFragment<FragmentReaderBinding>() {
companion object {
private const val FARGS_READER = "readerParcel"
@JvmStatic
fun createArguments(readerParcel: ReaderParcel) = Bundle().apply { putParcelable(FARGS_READER, readerParcel) }
@JvmStatic
fun newInstance(readerParcel: ReaderParcel): ReaderFragment {
return ReaderFragment().apply { arguments = createArguments(readerParcel) }
}
}
@Inject
lateinit var fonts: Fonts
@Inject
lateinit var vmf: ViewModelFactory
private val rvm by lazy { viewModel(vmf, ReaderViewModel::class.java) }
private val bottomSheetBehavior by lazy { BottomSheetBehavior.from(binding.readerSettingParent) }
override val layoutId = R.layout.fragment_reader
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val readerParcel: ReaderParcel = arguments!!.getParcelable(FARGS_READER)!!
rvm.initReader(readerParcel)
binding.refreshLayout.setColorSchemeColors(
ContextCompat.getColor(context!!, R.color.colorAccent),
ContextCompat.getColor(context!!, R.color.colorPrimary)
)
binding.refreshLayout.setOnRefreshListener { rvm.reader.refresh() }
binding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
handleBottomBarVisibility(verticalOffset, appBarLayout)
})
rvm.reader.observe(this) { readerDetail ->
readerDetail?.let {
updateReaderBar(it)
if (it.hasText()) binding.rawText.setText(it.text, TextView.BufferType.SPANNABLE)
} ?: when (rvm.reader.resourceState.value?.state) {
State.ERROR -> binding.rawText.text = "Chapter can't be retrieved. Try refreshing"
else -> binding.rawText.text = ""
}
binding.refreshLayout.isRefreshing = false
}
rvm.reader.resourceState.observeNonNull(this) {
with(binding.refreshLayout) {
when (it.state) {
State.COMPLETE -> isRefreshing = false
State.LOADING -> isRefreshing = true
State.ERROR -> {
isRefreshing = false
showSnackbar(it.message)
}
}
}
}
rvm.readerSetting.observeNonNull(this) { readerSetting ->
createFontView(readerSetting)
with(binding) {
rawText.apply {
setTextColor(readerSetting.fontColor)
letterSpacing = readerSetting.letterSpacingSp / 100f
setLineSpacing(readerSetting.lineSpacingExtra.toFloat(), 1f)
textSize = readerSetting.fontSizeSp.toFloat()
typeface = fonts.toTypeface(readerSetting.fontName)
}
coordinatorLayout.setBackgroundColor(readerSetting.backgroundColor)
}
}
bindReaderBar(binding.buttonBarTop)
bindReaderBar(binding.buttonBarBottom)
hideFontMenu()
}
private fun bindReaderBar(binding: ViewReaderbarBinding) {
with(binding) {
readerFont.setOnClickListener { showFontMenu() }
readerNext.setOnClickListener { rvm.reader.navigateNext() }
readerPrevious.setOnClickListener { rvm.reader.navigatePrevious() }
readerBrowser.setOnClickListener {
rvm.reader.absoluteUrl()?.let { activity?.startActivity(IntentFactory.createBrowserIntent(it)) }
}
}
}
private fun updateReaderBar(detail: ReaderDetail) {
setReaderBarTitle(detail.title ?: detail.taxon, binding.buttonBarTop)
setReaderBarTitle(detail.title ?: detail.taxon, binding.buttonBarBottom)
setReaderBarNavigation(detail, binding.buttonBarTop)
setReaderBarNavigation(detail, binding.buttonBarBottom)
}
private fun setReaderBarTitle(title: String, binding: ViewReaderbarBinding) {
binding.title.text = title
}
private fun setReaderBarNavigation(readerDetail: ReaderDetail, binding: ViewReaderbarBinding) {
binding.readerNext.isEnabled = readerDetail.canNavigateNext()
binding.readerPrevious.isEnabled = readerDetail.canNavigatePrevious()
}
private fun showFontMenu() {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
private fun hideFontMenu() {
bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
}
private fun createFontView(readerSetting: ReaderSetting) {
ReaderSettingHelper(
fragmentManager = activity!!.supportFragmentManager,
binding = binding.readerSetting,
readerSetting = readerSetting,
fonts = fonts.list,
listener = object : ReaderSettingHelper.Listener {
override fun onComplete(readerSetting: ReaderSetting) {
rvm.readerSetting.postValue(readerSetting)
hideFontMenu()
}
override fun onCancel() {
hideFontMenu()
}
}
)
}
private fun handleBottomBarVisibility(verticalOffset: Int, appBarLayout: AppBarLayout) {
val visibility = binding.buttonBarBottom.container.visibility
if (visibility == View.VISIBLE && verticalOffset == 0) {
binding.buttonBarBottom.container.visibility = View.INVISIBLE
} else if (visibility == View.INVISIBLE
&& appBarLayout.height + verticalOffset == 0
&& rvm.reader.value?.hasText() != null) {
binding.buttonBarBottom.container.visibility = View.VISIBLE
}
}
private fun showSnackbar(message: String) {
Snackbar.make(binding.coordinatorLayout, message, Snackbar.LENGTH_SHORT)
.show()
}
override fun onStart() {
super.onStart()
binding.root.post { enterFullscreen(activity) }
activity?.window?.decorView?.background = null
}
override fun onStop() {
super.onStop()
exitFullScreen(activity)
activity?.window?.decorView?.setBackgroundColor(ContextCompat.getColor(context!!, R.color.colorWindowBackground))
}
}
| kotlin | 29 | 0.736378 | 117 | 34.097938 | 194 | starcoderdata |
// 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 com.intellij.openapi.externalSystem.configurationStore
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.configurationStore.copyFilesAndReloadProject
import com.intellij.testFramework.loadProjectAndCheckResults
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Paths
import kotlin.io.path.div
class ExternalSystemReloadingTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@JvmField
@Rule
val tempDirManager = TemporaryDirectory()
private val testDataRoot
get() = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("platform/external-system-impl/testData/projectReloading")
@Test
fun `change iml of imported module`() {
loadProjectAndCheckResults(listOf(testDataRoot / "changeIml/initial"), tempDirManager) { project ->
val module = ModuleManager.getInstance(project).modules.single()
assertThat(ModuleRootManager.getInstance(module).orderEntries.filterIsInstance<LibraryOrderEntry>()).isEmpty()
copyFilesAndReloadProject(project, testDataRoot / "changeIml/update")
assertThat(ModuleRootManager.getInstance(module).orderEntries.filterIsInstance<LibraryOrderEntry>().single().libraryName).isEqualTo("lib")
}
}
} | kotlin | 27 | 0.809207 | 144 | 40.953488 | 43 | starcoderdata |
package com.synergy.android.di.modules
import androidx.lifecycle.ViewModelProvider
import com.synergy.android.login.LoginViewModel
import com.synergy.android.profile.ProfileViewModel
import com.synergy.android.registration.RegistrationViewModel
import com.synergy.android.util.ViewModelFactory
import com.synergy.android.util.bindViewModel
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import org.kodein.di.generic.provider
import org.kodein.di.generic.singleton
val viewModelModule = Kodein.Module(name = "viewModelModule") {
bind<ViewModelProvider.Factory>() with singleton { ViewModelFactory(dkodein) }
bindViewModel<LoginViewModel>() with provider { LoginViewModel(instance(), instance()) }
bindViewModel<RegistrationViewModel>() with provider {
RegistrationViewModel(instance(), instance())
}
bindViewModel<ProfileViewModel>() with provider { ProfileViewModel(instance()) }
}
| kotlin | 20 | 0.805383 | 92 | 41 | 23 | starcoderdata |
package com.epam.drill.plugin
import com.epam.drill.core.exec
import com.epam.drill.core.plugin.pluginConfigById
import com.epam.drill.plugin.api.processing.AgentPart
actual val storage: MutableMap<String, AgentPart<*, *>>
get() = exec { pstorage }
actual fun AgentPart<*, *>.actualPluginConfig() = pluginConfigById(this.id)
| kotlin | 9 | 0.763473 | 75 | 26.833333 | 12 | starcoderdata |
package net.corda.node.services.vault
import net.corda.core.contracts.ContractState
import net.corda.core.contracts.MAX_ISSUER_REF_SIZE
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.crypto.toStringShort
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.Party
import net.corda.core.node.services.MAX_CONSTRAINT_DATA_SIZE
import net.corda.core.node.services.Vault
import net.corda.core.schemas.*
import net.corda.core.serialization.CordaSerializable
import net.corda.core.utilities.OpaqueBytes
import org.hibernate.annotations.Immutable
import org.hibernate.annotations.Type
import java.io.Serializable
import java.time.Instant
import java.util.*
import javax.persistence.*
/**
* JPA representation of the core Vault Schema
*/
object VaultSchema
/**
* First version of the Vault ORM schema
*/
@CordaSerializable
object VaultSchemaV1 : MappedSchema(
schemaFamily = VaultSchema.javaClass,
version = 1,
mappedTypes = listOf(
VaultStates::class.java,
VaultLinearStates::class.java,
VaultFungibleStates::class.java,
VaultTxnNote::class.java,
PersistentParty::class.java,
StateToExternalId::class.java
)
) {
override val migrationResource = "vault-schema.changelog-master"
@Entity
@Table(name = "vault_states", indexes = [Index(name = "state_status_idx", columnList = "state_status"), Index(name = "lock_id_idx", columnList = "lock_id, state_status")])
class VaultStates(
/** NOTE: serialized transaction state (including contract state) is now resolved from transaction store */
// TODO: create a distinct table to hold serialized state data (once DBTransactionStore is encrypted)
/** refers to the X500Name of the notary a state is attached to */
@Column(name = "notary_name", nullable = false)
var notary: Party,
/** references a concrete ContractState that is [QueryableState] and has a [MappedSchema] */
@Column(name = "contract_state_class_name", nullable = false)
var contractStateClassName: String,
/** state lifecycle: unconsumed, consumed */
@Column(name = "state_status", nullable = false)
var stateStatus: Vault.StateStatus,
/** refers to timestamp recorded upon entering UNCONSUMED state */
@Column(name = "recorded_timestamp", nullable = false)
var recordedTime: Instant,
/** refers to timestamp recorded upon entering CONSUMED state */
@Column(name = "consumed_timestamp", nullable = true)
var consumedTime: Instant? = null,
/** used to denote a state has been soft locked (to prevent double spend)
* will contain a temporary unique [UUID] obtained from a flow session */
@Column(name = "lock_id", nullable = true)
var lockId: String? = null,
/** Used to determine whether a state abides by the relevancy rules of the recording node */
@Column(name = "relevancy_status", nullable = false)
var relevancyStatus: Vault.RelevancyStatus,
/** refers to the last time a lock was taken (reserved) or updated (released, re-reserved) */
@Column(name = "lock_timestamp", nullable = true)
var lockUpdateTime: Instant? = null,
/** refers to constraint type (none, hash, whitelisted, signature) associated with a contract state */
@Column(name = "constraint_type", nullable = false)
var constraintType: Vault.ConstraintInfo.Type,
/** associated constraint type data (if any) */
@Column(name = "constraint_data", length = MAX_CONSTRAINT_DATA_SIZE, nullable = true)
@Type(type = "corda-wrapper-binary")
var constraintData: ByteArray? = null
) : PersistentState()
@Entity
@Table(name = "vault_linear_states", indexes = [Index(name = "external_id_index", columnList = "external_id"), Index(name = "uuid_index", columnList = "uuid")])
class VaultLinearStates(
/** [ContractState] attributes */
/**
* Represents a [LinearState] [UniqueIdentifier]
*/
@Column(name = "external_id", nullable = true)
var externalId: String?,
@Column(name = "uuid", nullable = false)
@Type(type = "uuid-char")
var uuid: UUID
) : PersistentState() {
constructor(uid: UniqueIdentifier) : this(externalId = uid.externalId, uuid = uid.id)
}
@Entity
@Table(name = "vault_fungible_states")
class VaultFungibleStates(
/** [OwnableState] attributes */
/** X500Name of owner party **/
@Column(name = "owner_name", nullable = true)
var owner: AbstractParty?,
/** [FungibleAsset] attributes
*
* Note: the underlying Product being issued must be modelled into the
* custom contract itself (eg. see currency in Cash contract state)
*/
/** Amount attributes */
@Column(name = "quantity", nullable = false)
var quantity: Long,
/** Issuer attributes */
/** X500Name of issuer party **/
@Column(name = "issuer_name", nullable = true)
var issuer: AbstractParty?,
@Column(name = "issuer_ref", length = MAX_ISSUER_REF_SIZE, nullable = true)
@Type(type = "corda-wrapper-binary")
var issuerRef: ByteArray?
) : PersistentState() {
constructor(_owner: AbstractParty, _quantity: Long, _issuerParty: AbstractParty, _issuerRef: OpaqueBytes) :
this(owner = _owner, quantity = _quantity, issuer = _issuerParty, issuerRef = _issuerRef.bytes)
}
@Entity
@Table(name = "vault_transaction_notes", indexes = [Index(name = "seq_no_index", columnList = "seq_no"), Index(name = "transaction_id_index", columnList = "transaction_id")])
class VaultTxnNote(
@Id
@GeneratedValue
@Column(name = "seq_no", nullable = false)
var seqNo: Int,
@Column(name = "transaction_id", length = 64, nullable = true)
var txId: String?,
@Column(name = "note", nullable = true)
var note: String?
) {
constructor(txId: String, note: String) : this(0, txId, note)
}
@Embeddable
@Immutable
data class PersistentStateRefAndKey(/* Foreign key. */ @Embedded override var stateRef: PersistentStateRef?, @Column(name = "public_key_hash", nullable = false) var publicKeyHash: String?) : DirectStatePersistable, Serializable {
constructor() : this(null, null)
}
@Entity
@Table(name = "state_party", indexes = [Index(name = "state_party_idx", columnList = "public_key_hash")])
class PersistentParty(
@EmbeddedId
override val compositeKey: PersistentStateRefAndKey,
@Column(name = "x500_name", nullable = true)
var x500Name: AbstractParty? = null
) : IndirectStatePersistable<PersistentStateRefAndKey> {
constructor(stateRef: PersistentStateRef, abstractParty: AbstractParty)
: this(PersistentStateRefAndKey(stateRef, abstractParty.owningKey.toStringShort()), abstractParty)
}
@Entity
@Immutable
@Table(name = "v_pkey_hash_ex_id_map")
class StateToExternalId(
@EmbeddedId
override val compositeKey: PersistentStateRefAndKey,
@Column(name = "external_id")
@Type(type = "uuid-char")
val externalId: UUID
) : IndirectStatePersistable<PersistentStateRefAndKey>
}
| kotlin | 17 | 0.62626 | 233 | 39.606218 | 193 | starcoderdata |
<gh_stars>1-10
package spb.net.rs.node
/**
* @author Kai
*/
open class Node {
var prev : Node? = null
var next : Node? = null
fun unlink() {
if (next != null) {
next!!.prev = prev
prev!!.next = next
prev = null
next = null
}
}
} | kotlin | 12 | 0.44586 | 30 | 14 | 21 | starcoderdata |
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
import org.jetbrains.kotlin.gradle.internals.MULTIPLATFORM_PROJECT_METADATA_JSON_FILE_NAME
import org.jetbrains.kotlin.gradle.internals.parseKotlinSourceSetMetadataFromJson
import org.jetbrains.kotlin.gradle.native.transformNativeTestProjectWithPluginDsl
import org.jetbrains.kotlin.gradle.plugin.KotlinJsCompilerType
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinProjectStructureMetadata
import org.jetbrains.kotlin.gradle.plugin.mpp.ModuleDependencyIdentifier
import org.jetbrains.kotlin.gradle.plugin.mpp.SourceSetMetadataLayout
import org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSet
import org.jetbrains.kotlin.gradle.util.checkedReplace
import org.jetbrains.kotlin.gradle.util.modify
import java.io.File
import java.util.zip.ZipFile
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class HierarchicalMppIT : BaseGradleIT() {
override val defaultGradleVersion: GradleVersionRequired
get() = gradleVersion
companion object {
private val gradleVersion = GradleVersionRequired.FOR_MPP_SUPPORT
}
@Test
fun testPublishedModules() {
publishThirdPartyLib(withGranularMetadata = false)
transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, "hierarchical-mpp-published-modules").run {
build("publish") {
checkMyLibFoo(this, subprojectPrefix = null)
}
}
transformNativeTestProjectWithPluginDsl("my-lib-bar", gradleVersion, "hierarchical-mpp-published-modules").run {
build("publish") {
checkMyLibBar(this, subprojectPrefix = null)
}
}
transformNativeTestProjectWithPluginDsl("my-app", gradleVersion, "hierarchical-mpp-published-modules").run {
build("assemble") {
checkMyApp(this, subprojectPrefix = null)
}
}
}
@Test
fun testNoSourceSetsVisibleIfNoVariantMatched() {
publishThirdPartyLib(withGranularMetadata = true)
transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, "hierarchical-mpp-published-modules").run {
// --- Move the dependency from jvmAndJsMain to commonMain, where there's a linuxX64 target missing in the lib
gradleBuildScript().modify {
it.checkedReplace("api(\"com.example.thirdparty:third-party-lib:1.0\")", "//") + "\n" + """
dependencies {
"commonMainApi"("com.example.thirdparty:third-party-lib:1.0")
}
""".trimIndent()
}
testDependencyTransformations { reports ->
val thirdPartyLibApiVisibility = reports.filter { report ->
report.groupAndModule.startsWith("com.example.thirdparty:third-party-lib") && report.scope == "api"
}
val jvmJsSourceSets = setOf("jvmMain", "jsMain", "jvmTest", "jsTest", "jvmAndJsMain", "jvmAndJsTest")
thirdPartyLibApiVisibility.forEach {
if (it.sourceSetName in jvmJsSourceSets)
assertTrue("$it") { it.allVisibleSourceSets == setOf("commonMain") }
}
}
}
}
@Test
fun testDependenciesInTests() {
publishThirdPartyLib(withGranularMetadata = true) {
projectDir.resolve("src/jvmMain").copyRecursively(projectDir.resolve("src/linuxX64Main"))
gradleBuildScript().appendText("\nkotlin.linuxX64()")
}
transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, "hierarchical-mpp-published-modules").run {
testDependencyTransformations { reports ->
val testApiTransformationReports =
reports.filter { report ->
report.groupAndModule.startsWith("com.example.thirdparty:third-party-lib") &&
report.sourceSetName.let { it == "commonTest" || it == "jvmAndJsTest" } &&
report.scope == "api"
}
testApiTransformationReports.forEach {
if (it.sourceSetName == "commonTest")
assertTrue("$it") { it.isExcluded } // should not be visible in commonTest
else {
assertTrue("$it") { it.allVisibleSourceSets == setOf("commonMain") }
assertTrue("$it") { it.newVisibleSourceSets == emptySet<String>() }
}
}
// ALso check that the files produced by dependency transformations survive a clean build:
val existingFilesFromReports = reports.flatMap { it.useFiles }.filter { it.isFile }
assertTrue { existingFilesFromReports.isNotEmpty() }
build("clean") {
assertSuccessful()
existingFilesFromReports.forEach { assertTrue("Expected that $it exists after clean build.") { it.isFile } }
}
}
// --- Move the dependency from jvmAndJsMain to commonMain, expect that it is now propagated to commonTest:
gradleBuildScript().modify {
it.checkedReplace("api(\"com.example.thirdparty:third-party-lib:1.0\")", "//") + "\n" + """
dependencies {
"commonMainApi"("com.example.thirdparty:third-party-lib:1.0")
}
""".trimIndent()
}
testDependencyTransformations { reports ->
val testApiTransformationReports =
reports.filter { report ->
report.groupAndModule.startsWith("com.example.thirdparty") &&
report.sourceSetName.let { it == "commonTest" || it == "jvmAndJsTest" } &&
report.scope == "api"
}
testApiTransformationReports.forEach {
assertEquals(setOf("commonMain"), it.allVisibleSourceSets, "$it")
assertEquals(emptySet(), it.newVisibleSourceSets, "$it")
}
}
// --- Remove the dependency from commonMain, add it to commonTest to check that it is correctly picked from a non-published
// source set:
gradleBuildScript().modify {
it.checkedReplace("\"commonMainApi\"(\"com.example.thirdparty:third-party-lib:1.0\")", "//") + "\n" + """
dependencies {
"commonTestApi"("com.example.thirdparty:third-party-lib:1.0")
}
""".trimIndent()
}
testDependencyTransformations { reports ->
reports.single {
it.sourceSetName == "commonTest" && it.scope == "api" && it.groupAndModule.startsWith("com.example.thirdparty")
}.let {
assertEquals(setOf("commonMain"), it.allVisibleSourceSets)
assertEquals(setOf("commonMain"), it.newVisibleSourceSets)
}
reports.single {
it.sourceSetName == "jvmAndJsTest" && it.scope == "api" && it.groupAndModule.startsWith("com.example.thirdparty")
}.let {
assertEquals(setOf("commonMain"), it.allVisibleSourceSets)
assertEquals(emptySet(), it.newVisibleSourceSets)
}
}
}
}
@Test
fun testProjectDependencies() {
publishThirdPartyLib(withGranularMetadata = false)
with(transformNativeTestProjectWithPluginDsl("hierarchical-mpp-project-dependency", gradleVersion)) {
build("publish", "assemble") {
checkMyLibFoo(this, subprojectPrefix = "my-lib-foo")
checkMyLibBar(this, subprojectPrefix = "my-lib-bar")
checkMyApp(this, subprojectPrefix = "my-app")
}
}
}
@Test
fun testHmppWithPublishedJsBothDependency() {
val directoryPrefix = "hierarchical-mpp-with-js-published-modules"
publishThirdPartyLib(
projectName = "third-party-lib",
directoryPrefix = directoryPrefix,
withGranularMetadata = true,
jsCompilerType = KotlinJsCompilerType.BOTH
)
with(transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, directoryPrefix)) {
build(
"publish",
"assemble",
options = defaultBuildOptions().copy(jsCompilerType = KotlinJsCompilerType.IR)
) {
assertSuccessful()
}
}
}
@Test
fun testHmppWithProjectJsIrDependency() {
with(transformNativeTestProjectWithPluginDsl("hierarchical-mpp-with-js-project-dependency", gradleVersion)) {
build(
"assemble",
options = defaultBuildOptions().copy(jsCompilerType = KotlinJsCompilerType.IR)
) {
assertSuccessful()
}
}
}
private fun publishThirdPartyLib(
projectName: String = "third-party-lib",
directoryPrefix: String = "hierarchical-mpp-published-modules",
withGranularMetadata: Boolean,
jsCompilerType: KotlinJsCompilerType = KotlinJsCompilerType.LEGACY,
beforePublishing: Project.() -> Unit = { }
): Project =
transformNativeTestProjectWithPluginDsl(projectName, gradleVersion, directoryPrefix).apply {
beforePublishing()
if (withGranularMetadata) {
projectDir.resolve("gradle.properties").appendText("kotlin.mpp.enableGranularSourceSetsMetadata=true")
}
build(
"publish",
options = defaultBuildOptions().copy(jsCompilerType = jsCompilerType)
) {
assertSuccessful()
}
}
private fun checkMyLibFoo(compiledProject: CompiledProject, subprojectPrefix: String? = null) = with(compiledProject) {
assertSuccessful()
assertTasksExecuted(expectedTasks(subprojectPrefix))
ZipFile(
project.projectDir.parentFile.resolve(
"repo/com/example/foo/my-lib-foo/1.0/my-lib-foo-1.0-all.jar"
)
).use { publishedMetadataJar ->
publishedMetadataJar.checkAllEntryNamesArePresent(
"META-INF/$MULTIPLATFORM_PROJECT_METADATA_JSON_FILE_NAME",
"commonMain/default/manifest",
"commonMain/default/linkdata/package_com.example/",
"jvmAndJsMain/default/manifest",
"jvmAndJsMain/default/linkdata/package_com.example/",
"linuxAndJsMain/default/manifest",
"linuxAndJsMain/default/linkdata/package_com.example/"
)
val parsedProjectStructureMetadata: KotlinProjectStructureMetadata = publishedMetadataJar.getProjectStructureMetadata()
val expectedProjectStructureMetadata = expectedProjectStructureMetadata(
sourceSetModuleDependencies = mapOf(
"jvmAndJsMain" to setOf("com.example.thirdparty" to "third-party-lib"),
"linuxAndJsMain" to emptySet(),
"commonMain" to emptySet()
)
)
assertEquals(expectedProjectStructureMetadata, parsedProjectStructureMetadata)
}
ZipFile(
project.projectDir.parentFile.resolve(
"repo/com/example/foo/my-lib-foo/1.0/my-lib-foo-1.0-sources.jar"
)
).use { publishedSourcesJar ->
publishedSourcesJar.checkAllEntryNamesArePresent(
"commonMain/Foo.kt",
"jvmAndJsMain/FooJvmAndJs.kt",
"linuxAndJsMain/FooLinuxAndJs.kt",
"linuxX64Main/FooLinux.kt"
)
}
}
private fun checkMyLibBar(compiledProject: CompiledProject, subprojectPrefix: String?) = with(compiledProject) {
val taskPrefix = subprojectPrefix?.let { ":$it" }.orEmpty()
assertSuccessful()
assertTasksExecuted(expectedTasks(subprojectPrefix))
ZipFile(
project.projectDir.parentFile.resolve(
"repo/com/example/bar/my-lib-bar/1.0/my-lib-bar-1.0-all.jar"
)
).use { publishedMetadataJar ->
publishedMetadataJar.checkAllEntryNamesArePresent(
"META-INF/$MULTIPLATFORM_PROJECT_METADATA_JSON_FILE_NAME",
"commonMain/default/manifest",
"commonMain/default/linkdata/package_com.example.bar/",
"jvmAndJsMain/default/manifest",
"jvmAndJsMain/default/linkdata/package_com.example.bar/",
"linuxAndJsMain/default/manifest",
"linuxAndJsMain/default/linkdata/package_com.example.bar/"
)
val parsedProjectStructureMetadata: KotlinProjectStructureMetadata = publishedMetadataJar.getProjectStructureMetadata()
val expectedProjectStructureMetadata = expectedProjectStructureMetadata(
sourceSetModuleDependencies = mapOf(
"jvmAndJsMain" to setOf(),
"linuxAndJsMain" to emptySet(),
"commonMain" to setOf("com.example.foo" to "my-lib-foo")
)
)
assertEquals(expectedProjectStructureMetadata, parsedProjectStructureMetadata)
}
ZipFile(
project.projectDir.parentFile.resolve(
"repo/com/example/bar/my-lib-bar/1.0/my-lib-bar-1.0-sources.jar"
)
).use { publishedSourcesJar ->
publishedSourcesJar.checkAllEntryNamesArePresent(
"commonMain/Bar.kt",
"jvmAndJsMain/BarJvmAndJs.kt",
"linuxAndJsMain/BarLinuxAndJs.kt",
"linuxX64Main/BarLinux.kt"
)
}
checkNamesOnCompileClasspath(
"$taskPrefix:compileKotlinMetadata",
shouldInclude = listOf(
"my-lib-foo" to "main"
),
shouldNotInclude = listOf(
"my-lib-foo" to "jvmAndJsMain",
"my-lib-foo" to "linuxAndJsMain",
"third-party-lib-metadata-1.0" to ""
)
)
checkNamesOnCompileClasspath(
"$taskPrefix:compileJvmAndJsMainKotlinMetadata",
shouldInclude = listOf(
"my-lib-foo" to "main",
"my-lib-foo" to "jvmAndJsMain",
"third-party-lib-metadata-1.0" to ""
),
shouldNotInclude = listOf(
"my-lib-foo" to "linuxAndJsMain"
)
)
checkNamesOnCompileClasspath(
"$taskPrefix:compileLinuxAndJsMainKotlinMetadata",
shouldInclude = listOf(
"my-lib-foo" to "linuxAndJsMain",
"my-lib-foo" to "main"
),
shouldNotInclude = listOf(
"my-lib-foo" to "jvmAndJsMain",
"third-party-lib-metadata-1.0" to ""
)
)
}
private fun checkMyApp(compiledProject: CompiledProject, subprojectPrefix: String?) = with(compiledProject) {
val taskPrefix = subprojectPrefix?.let { ":$it" }.orEmpty()
assertSuccessful()
assertTasksExecuted(expectedTasks(subprojectPrefix))
checkNamesOnCompileClasspath(
"$taskPrefix:compileKotlinMetadata",
shouldInclude = listOf(
"my-lib-bar" to "main",
"my-lib-foo" to "main"
),
shouldNotInclude = listOf(
"my-lib-bar" to "jvmAndJsMain",
"my-lib-bar" to "linuxAndJsMain",
"my-lib-foo" to "jvmAndJsMain",
"my-lib-foo" to "linuxAndJsMain",
"third-party-lib-metadata-1.0" to ""
)
)
checkNamesOnCompileClasspath(
"$taskPrefix:compileJvmAndJsMainKotlinMetadata",
shouldInclude = listOf(
"my-lib-bar" to "main",
"my-lib-bar" to "jvmAndJsMain",
"my-lib-foo" to "main",
"my-lib-foo" to "jvmAndJsMain",
"third-party-lib-metadata-1.0" to ""
),
shouldNotInclude = listOf(
"my-lib-bar" to "linuxAndJsMain",
"my-lib-foo" to "linuxAndJsMain"
)
)
checkNamesOnCompileClasspath(
"$taskPrefix:compileLinuxAndJsMainKotlinMetadata",
shouldInclude = listOf(
"my-lib-bar" to "main",
"my-lib-bar" to "linuxAndJsMain",
"my-lib-foo" to "main",
"my-lib-foo" to "linuxAndJsMain"
),
shouldNotInclude = listOf(
"my-lib-bar" to "jvmAndJsMain",
"my-lib-foo" to "jvmAndJsMain",
"third-party-lib-metadata-1.0" to ""
)
)
checkNamesOnCompileClasspath("$taskPrefix:compileLinuxAndJsMainKotlinMetadata")
}
private fun CompiledProject.checkNamesOnCompileClasspath(
taskPath: String,
shouldInclude: Iterable<Pair<String, String>> = emptyList(),
shouldNotInclude: Iterable<Pair<String, String>> = emptyList()
) {
val taskOutput = getOutputForTask(taskPath.removePrefix(":"))
val compilerArgsLine = taskOutput.lines().single { "Kotlin compiler args:" in it }
val classpathItems = compilerArgsLine.substringAfter("-classpath").substringBefore(" -").split(File.pathSeparator)
val actualClasspath = classpathItems.joinToString("\n")
shouldInclude.forEach { (module, sourceSet) ->
assertTrue(
"expected module '$module' source set '$sourceSet' on the classpath of task $taskPath. Actual classpath:\n$actualClasspath"
) {
classpathItems.any { module in it && it.contains(sourceSet, ignoreCase = true) }
}
}
shouldNotInclude.forEach { (module, sourceSet) ->
assertTrue(
"not expected module '$module' source set '$sourceSet' on the compile classpath of task $taskPath. " +
"Actual classpath:\n$actualClasspath"
) {
classpathItems.none { module in it && it.contains(sourceSet, ignoreCase = true) }
}
}
}
private fun expectedTasks(subprojectPrefix: String?) = listOf(
"generateProjectStructureMetadata",
"transformCommonMainDependenciesMetadata",
"transformJvmAndJsMainDependenciesMetadata",
"transformLinuxAndJsMainDependenciesMetadata",
"compileKotlinMetadata",
"compileJvmAndJsMainKotlinMetadata",
"compileLinuxAndJsMainKotlinMetadata"
).map { task -> subprojectPrefix?.let { ":$it" }.orEmpty() + ":" + task }
// the projects used in these tests are similar and only the dependencies differ:
private fun expectedProjectStructureMetadata(
sourceSetModuleDependencies: Map<String, Set<Pair<String, String>>>
): KotlinProjectStructureMetadata {
val jvmSourceSets = setOf("commonMain", "jvmAndJsMain")
val jsSourceSets = setOf("commonMain", "jvmAndJsMain", "linuxAndJsMain")
return KotlinProjectStructureMetadata(
sourceSetNamesByVariantName = mapOf(
"jsApiElements" to jsSourceSets,
"jsRuntimeElements" to jsSourceSets,
"jvmApiElements" to jvmSourceSets,
"jvmRuntimeElements" to jvmSourceSets,
"linuxX64ApiElements" to setOf("commonMain", "linuxAndJsMain")
),
sourceSetsDependsOnRelation = mapOf(
"jvmAndJsMain" to setOf("commonMain"),
"linuxAndJsMain" to setOf("commonMain"),
"commonMain" to emptySet()
),
sourceSetModuleDependencies = sourceSetModuleDependencies.mapValues { (_, pairs) ->
pairs.map {
ModuleDependencyIdentifier(it.first, it.second)
}.toSet()
},
hostSpecificSourceSets = emptySet(),
sourceSetBinaryLayout = sourceSetModuleDependencies.mapValues { SourceSetMetadataLayout.KLIB },
isPublishedAsRoot = true
)
}
private fun ZipFile.checkAllEntryNamesArePresent(vararg expectedEntryNames: String) {
val entryNames = entries().asSequence().map { it.name }.toSet()
val entryNamesString = entryNames.joinToString()
expectedEntryNames.forEach {
assertTrue("expecting entry $it in entry names $entryNamesString") { it in entryNames }
}
}
private fun ZipFile.getProjectStructureMetadata(): KotlinProjectStructureMetadata {
val json = getInputStream(getEntry("META-INF/$MULTIPLATFORM_PROJECT_METADATA_JSON_FILE_NAME")).reader().readText()
return checkNotNull(parseKotlinSourceSetMetadataFromJson(json))
}
@Test
fun testCompileOnlyDependencyProcessingForMetadataCompilations() = with(transformNativeTestProjectWithPluginDsl("hierarchical-mpp-project-dependency")) {
publishThirdPartyLib(withGranularMetadata = true)
gradleBuildScript("my-lib-foo").appendText("\ndependencies { \"jvmAndJsMainCompileOnly\"(kotlin(\"test-annotations-common\")) }")
projectDir.resolve("my-lib-foo/src/jvmAndJsMain/kotlin/UseCompileOnlyDependency.kt").writeText(
"""
import kotlin.test.Test
class UseCompileOnlyDependency {
@Test
fun myTest() = Unit
}
""".trimIndent()
)
build(":my-lib-foo:compileJvmAndJsMainKotlinMetadata") {
assertSuccessful()
}
}
@Test
fun testHmppDependenciesInJsTests() {
val thirdPartyRepo = publishThirdPartyLib(withGranularMetadata = true).projectDir.parentFile.resolve("repo")
with(Project("hierarchical-mpp-js-test")) {
val taskToExecute = ":jsNodeTest"
build(taskToExecute, "-PthirdPartyRepo=$thirdPartyRepo") {
assertSuccessful()
assertTasksExecuted(taskToExecute)
}
}
}
@Test
fun testProcessingDependencyDeclaredInNonRootSourceSet() {
publishThirdPartyLib(withGranularMetadata = true)
transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, "hierarchical-mpp-published-modules").run {
val intermediateMetadataCompileTask = ":compileJvmAndJsMainKotlinMetadata"
build(intermediateMetadataCompileTask) {
assertSuccessful()
checkNamesOnCompileClasspath(
intermediateMetadataCompileTask,
shouldInclude = listOf(
"third-party-lib" to "commonMain"
)
)
}
}
}
@Test
fun testDependenciesInNonPublishedSourceSets() {
publishThirdPartyLib(withGranularMetadata = true)
transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, "hierarchical-mpp-published-modules").run {
testDependencyTransformations { reports ->
reports.single {
it.sourceSetName == "jvmAndJsMain" && it.scope == "api" && it.groupAndModule.startsWith("com.example")
}.let {
assertEquals(setOf("commonMain"), it.allVisibleSourceSets)
assertEquals(setOf("commonMain"), it.newVisibleSourceSets)
}
}
}
}
@Test
fun testTransitiveDependencyOnSelf() = with(Project("transitive-dep-on-self-hmpp")) {
testDependencyTransformations(subproject = "lib") { reports ->
reports.single {
it.sourceSetName == "commonTest" && it.scope == "implementation" && "libtests" in it.groupAndModule
}.let {
assertEquals(setOf("commonMain", "jvmAndJsMain"), it.allVisibleSourceSets)
}
}
}
@Test
fun testMixedScopesFilesExistKt44845() {
publishThirdPartyLib(withGranularMetadata = true)
transformNativeTestProjectWithPluginDsl("my-lib-foo", gradleVersion, "hierarchical-mpp-published-modules").run {
gradleBuildScript().appendText(
"""
${"\n"}
dependencies {
"jvmAndJsMainImplementation"("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2")
"jvmAndJsMainCompileOnly"("org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1")
}
""".trimIndent()
)
testDependencyTransformations { reports ->
val reportsForJvmAndJsMain = reports.filter { it.sourceSetName == "jvmAndJsMain" }
val thirdPartyLib = reportsForJvmAndJsMain.single {
it.scope == "api" && it.groupAndModule.startsWith("com.example")
}
val coroutinesCore = reportsForJvmAndJsMain.single {
it.scope == "implementation" && it.groupAndModule.contains("kotlinx-coroutines-core")
}
val serialization = reportsForJvmAndJsMain.single {
it.scope == "compileOnly" && it.groupAndModule.contains("kotlinx-serialization-json")
}
listOf(thirdPartyLib, coroutinesCore, serialization).forEach { report ->
assertTrue(report.newVisibleSourceSets.isNotEmpty(), "Expected visible source sets for $report")
assertTrue(report.useFiles.isNotEmpty(), "Expected non-empty useFiles for $report")
report.useFiles.forEach { assertTrue(it.isFile, "Expected $it to exist for $report") }
}
}
}
}
private fun Project.testDependencyTransformations(
subproject: String? = null,
check: CompiledProject.(reports: Iterable<DependencyTransformationReport>) -> Unit
) {
setupWorkingDir()
val buildGradleKts = gradleBuildScript(subproject)
assert(buildGradleKts.extension == "kts") { "Only Kotlin scripts are supported." }
val testTaskName = "reportDependencyTransformationsForTest"
if (testTaskName !in buildGradleKts.readText()) {
buildGradleKts.modify {
"import ${DefaultKotlinSourceSet::class.qualifiedName}\n" + it + "\n" + """
val $testTaskName by tasks.creating {
doFirst {
for (scope in listOf("api", "implementation", "compileOnly", "runtimeOnly")) {
println("========\n${'$'}scope\n")
kotlin.sourceSets.withType<DefaultKotlinSourceSet>().forEach { sourceSet ->
println("--------\n${'$'}{sourceSet.name}")
sourceSet
.getDependenciesTransformation(
"${'$'}{sourceSet.name}${'$'}{scope.capitalize()}DependenciesMetadata"
).forEach {
val line = listOf(
"${DependencyTransformationReport.TEST_OUTPUT_MARKER}",
sourceSet.name,
scope,
it.groupId + ":" + it.moduleName,
it.allVisibleSourceSets.joinToString(","),
it.useFilesForSourceSets.keys.joinToString(","),
it.useFilesForSourceSets.values.flatten().joinToString(",")
)
println(" " + line.joinToString(" :: "))
}
println()
}
println()
}
}
}
""".trimIndent()
}
}
build(":${subproject?.plus(":").orEmpty()}$testTaskName") {
assertSuccessful()
val reports = output.lines()
.filter { DependencyTransformationReport.TEST_OUTPUT_MARKER in it }
.map { DependencyTransformationReport.parseTestOutputLine(it) }
check(this, reports)
}
}
private data class DependencyTransformationReport(
val sourceSetName: String,
val scope: String,
val groupAndModule: String,
val allVisibleSourceSets: Set<String>,
val newVisibleSourceSets: Set<String>, // those which the dependsOn parents don't see
val useFiles: List<File>
) {
val isExcluded: Boolean get() = allVisibleSourceSets.isEmpty()
companion object {
const val TEST_OUTPUT_MARKER = "###transformation"
const val TEST_OUTPUT_COMPONENT_SEPARATOR = " :: "
const val TEST_OUTPUT_ITEMS_SEPARATOR = ","
private operator fun <T> List<T>.component6() = this[5]
fun parseTestOutputLine(line: String): DependencyTransformationReport {
val tail = line.substringAfter(TEST_OUTPUT_MARKER + TEST_OUTPUT_COMPONENT_SEPARATOR)
val (sourceSetName, scope, groupAndModule, allVisibleSourceSets, newVisibleSourceSets, useFiles) =
tail.split(TEST_OUTPUT_COMPONENT_SEPARATOR)
return DependencyTransformationReport(
sourceSetName, scope, groupAndModule,
allVisibleSourceSets.split(TEST_OUTPUT_ITEMS_SEPARATOR).filter { it.isNotEmpty() }.toSet(),
newVisibleSourceSets.split(TEST_OUTPUT_ITEMS_SEPARATOR).filter { it.isNotEmpty() }.toSet(),
useFiles.split(TEST_OUTPUT_ITEMS_SEPARATOR).map { File(it) }
)
}
}
}
}
| kotlin | 35 | 0.57847 | 157 | 42.088608 | 711 | starcoderdata |
package uk.gov.justice.hmpps.prison.repository.sql
enum class MovementsRepositorySql(val sql: String) {
GET_RECENT_MOVEMENTS_BY_DATE_FOR_BATCH(
"""
SELECT OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OEM.MOVEMENT_DATE,
OEM.MOVEMENT_TIME,
OEM.CREATE_DATETIME AS CREATE_DATE_TIME,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
OEM.MOVEMENT_TYPE,
OEM.DIRECTION_CODE
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
WHERE OEM.MOVEMENT_DATE = :movementDate
AND OEM.CREATE_DATETIME >= :fromDateTime
AND OEM.MOVEMENT_TYPE IN (:movementTypes)
AND OEM.MOVEMENT_SEQ = (SELECT MAX(OEM2.MOVEMENT_SEQ) FROM OFFENDER_EXTERNAL_MOVEMENTS OEM2
WHERE OEM2.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID)
AND OB.AGY_LOC_ID <> 'ZZGHI'
"""
),
GET_MOVEMENT_BY_BOOKING_AND_SEQUENCE(
"""
SELECT OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OEM.CREATE_DATETIME AS CREATE_DATE_TIME,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
OEM.MOVEMENT_DATE,
OEM.MOVEMENT_TIME,
OEM.MOVEMENT_TYPE,
OEM.DIRECTION_CODE,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
RC1.DESCRIPTION AS MOVEMENT_TYPE_DESCRIPTION,
RC2.DESCRIPTION AS MOVEMENT_REASON,
RC3.DESCRIPTION AS FROM_CITY,
RC4.DESCRIPTION AS TO_CITY
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON OEM.FROM_AGY_LOC_ID = AL1.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON OEM.TO_AGY_LOC_ID = AL2.AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC1 ON RC1.CODE = OEM.MOVEMENT_TYPE AND RC1.DOMAIN = 'MOVE_TYPE'
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = OEM.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OEM.FROM_CITY AND RC3.DOMAIN = 'CITY'
LEFT JOIN REFERENCE_CODES RC4 ON RC4.CODE = OEM.TO_CITY AND RC4.DOMAIN = 'CITY'
WHERE OEM.MOVEMENT_SEQ = :sequenceNumber
AND OEM.OFFENDER_BOOK_ID = :bookingId
"""
),
GET_MOVEMENTS_BY_OFFENDERS_AND_MOVEMENT_TYPES(
"""
SELECT OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OEM.CREATE_DATETIME AS CREATE_DATE_TIME,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
OEM.MOVEMENT_DATE,
OEM.MOVEMENT_TIME,
OEM.MOVEMENT_TYPE,
OEM.DIRECTION_CODE,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
RC1.DESCRIPTION AS MOVEMENT_TYPE_DESCRIPTION,
RC2.DESCRIPTION AS MOVEMENT_REASON,
RC3.DESCRIPTION AS FROM_CITY,
RC4.DESCRIPTION AS TO_CITY
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID %s
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON OEM.FROM_AGY_LOC_ID = AL1.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON OEM.TO_AGY_LOC_ID = AL2.AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC1 ON RC1.CODE = OEM.MOVEMENT_TYPE AND RC1.DOMAIN = 'MOVE_TYPE'
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = OEM.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OEM.FROM_CITY AND RC3.DOMAIN = 'CITY'
LEFT JOIN REFERENCE_CODES RC4 ON RC4.CODE = OEM.TO_CITY AND RC4.DOMAIN = 'CITY'
WHERE (:latestOnly = 0 OR
OEM.MOVEMENT_SEQ = (SELECT MAX(OEM2.MOVEMENT_SEQ) FROM OFFENDER_EXTERNAL_MOVEMENTS OEM2
WHERE OEM2.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID
AND OEM2.MOVEMENT_TYPE IN (:movementTypes)))
AND OB.AGY_LOC_ID <> 'ZZGHI'
AND OFFENDERS.OFFENDER_ID_DISPLAY in (:offenderNumbers)
AND OEM.MOVEMENT_TYPE IN (:movementTypes)
"""
),
GET_MOVEMENTS_BY_OFFENDERS(
"""
SELECT OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OEM.CREATE_DATETIME AS CREATE_DATE_TIME,
OEM.MOVEMENT_TYPE,
OEM.MOVEMENT_DATE,
OEM.MOVEMENT_TIME,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
OEM.DIRECTION_CODE,
OEM.COMMENT_TEXT,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
RC1.DESCRIPTION AS MOVEMENT_TYPE_DESCRIPTION,
RC2.DESCRIPTION AS MOVEMENT_REASON,
RC3.DESCRIPTION AS FROM_CITY,
RC4.DESCRIPTION AS TO_CITY
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID %s
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON OEM.FROM_AGY_LOC_ID = AL1.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON OEM.TO_AGY_LOC_ID = AL2.AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC1 ON RC1.CODE = OEM.MOVEMENT_TYPE AND RC1.DOMAIN = 'MOVE_TYPE'
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = OEM.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OEM.FROM_CITY AND RC3.DOMAIN = 'CITY'
LEFT JOIN REFERENCE_CODES RC4 ON RC4.CODE = OEM.TO_CITY AND RC4.DOMAIN = 'CITY'
WHERE (:latestOnly = 0 OR
OEM.MOVEMENT_SEQ = (SELECT MAX(OEM2.MOVEMENT_SEQ) FROM OFFENDER_EXTERNAL_MOVEMENTS OEM2
WHERE OEM2.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID))
AND OB.AGY_LOC_ID <> 'ZZGHI'
AND OFFENDERS.OFFENDER_ID_DISPLAY in (:offenderNumbers)
"""
),
GET_ROLLCOUNT_MOVEMENTS(
"""
SELECT
DIRECTION_CODE, MOVEMENT_TYPE,
FROM_AGY_LOC_ID AS FROM_AGENCY,
TO_AGY_LOC_ID AS TO_AGENCY,
OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
WHERE MOVEMENT_DATE = :movementDate
"""
),
GET_ENROUTE_OFFENDER_COUNT(
"""
SELECT count(*)
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
WHERE
OEM.MOVEMENT_SEQ = (SELECT MAX(OEM2.MOVEMENT_SEQ) FROM OFFENDER_EXTERNAL_MOVEMENTS OEM2
WHERE OEM2.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID
AND OEM2.MOVEMENT_TYPE ='TRN')
AND OB.AGY_LOC_ID = 'TRN'
AND OB.ACTIVE_FLAG = 'N'
AND OEM.TO_AGY_LOC_ID = :agencyId
AND OEM.MOVEMENT_TYPE = 'TRN'
AND OEM.DIRECTION_CODE ='OUT'
AND OEM.ACTIVE_FLAG ='Y'
"""
),
GET_ENROUTE_OFFENDER_MOVEMENTS(
"""
SELECT
O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OB.OFFENDER_BOOK_ID AS BOOKING_ID,
O.FIRST_NAME FIRST_NAME,
CONCAT (O.MIDDLE_NAME, CASE WHEN MIDDLE_NAME_2 IS NOT NULL THEN CONCAT (' ', O.MIDDLE_NAME_2) ELSE '' END) MIDDLE_NAMES,
O.LAST_NAME LAST_NAME,
O.BIRTH_DATE DATE_OF_BIRTH,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
OEM.MOVEMENT_TYPE,
OEM.DIRECTION_CODE,
OEM.MOVEMENT_TIME,
OEM.MOVEMENT_DATE,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
RC1.DESCRIPTION AS MOVEMENT_TYPE_DESCRIPTION,
OEM.MOVEMENT_REASON_CODE AS MOVEMENT_REASON,
RC2.DESCRIPTION AS MOVEMENT_REASON_DESCRIPTION
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON OEM.FROM_AGY_LOC_ID = AL1.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON OEM.TO_AGY_LOC_ID = AL2.AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC1 ON RC1.CODE = OEM.MOVEMENT_TYPE AND RC1.DOMAIN = 'MOVE_TYPE'
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = OEM.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
WHERE
OEM.MOVEMENT_SEQ = (SELECT MAX(OEM2.MOVEMENT_SEQ) FROM OFFENDER_EXTERNAL_MOVEMENTS OEM2
WHERE OEM2.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID
AND OEM2.MOVEMENT_TYPE ='TRN')
AND OB.AGY_LOC_ID = 'TRN'
AND OB.ACTIVE_FLAG = 'N'
AND OEM.TO_AGY_LOC_ID = :agencyId
AND OEM.MOVEMENT_TYPE = 'TRN'
AND OEM.DIRECTION_CODE ='OUT'
AND OEM.ACTIVE_FLAG ='Y'
"""
),
GET_OFFENDER_MOVEMENTS_IN(
"""
SELECT /*+ index(OEM, OFFENDER_EXT_MOVEMENTS_X01) */
O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
O.FIRST_NAME AS FIRST_NAME,
CONCAT (O.MIDDLE_NAME, CASE WHEN MIDDLE_NAME_2 IS NOT NULL THEN CONCAT (' ', O.MIDDLE_NAME_2) ELSE '' END) AS MIDDLE_NAMES,
O.LAST_NAME AS LAST_NAME,
O.BIRTH_DATE AS DATE_OF_BIRTH,
OB.OFFENDER_BOOK_ID AS BOOKING_ID,
OEM.MOVEMENT_TIME AS MOVEMENT_DATE_TIME,
OEM.MOVEMENT_TIME AS MOVEMENT_TIME,
AL.AGY_LOC_ID AS FROM_AGENCY_ID,
AL.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
AL1.AGY_LOC_ID AS TO_AGENCY_ID,
AL1.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
COALESCE(AIL.USER_DESC, AIL.DESCRIPTION) AS LOCATION,
RC3.DESCRIPTION AS FROM_CITY,
RC4.DESCRIPTION AS TO_CITY
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT OUTER JOIN AGENCY_LOCATIONS AL ON OEM.FROM_AGY_LOC_ID = AL.AGY_LOC_ID
LEFT OUTER JOIN AGENCY_LOCATIONS AL1 ON OEM.TO_AGY_LOC_ID = AL1.AGY_LOC_ID
LEFT OUTER JOIN AGENCY_INTERNAL_LOCATIONS AIL ON OB.LIVING_UNIT_ID = AIL.INTERNAL_LOCATION_ID
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OEM.FROM_CITY AND RC3.DOMAIN = 'CITY'
LEFT JOIN REFERENCE_CODES RC4 ON RC4.CODE = OEM.TO_CITY AND RC4.DOMAIN = 'CITY'
WHERE
OEM.TO_AGY_LOC_ID = :agencyId
AND OEM.DIRECTION_CODE ='IN'
AND OEM.MOVEMENT_DATE = :movementDate
"""
),
GET_ROLL_COUNT(
"""
SELECT
AIL.INTERNAL_LOCATION_ID AS LIVING_UNIT_ID,
COALESCE(AIL.USER_DESC, AIL.INTERNAL_LOCATION_CODE) AS LIVING_UNIT_DESC,
VR.BEDS_IN_USE,
VR.CURRENTLY_IN_CELL,
VR.OUT_OF_LIVING_UNITS,
VR.CURRENTLY_OUT,
AIL.OPERATION_CAPACITY AS OPERATIONAL_CAPACITY,
AIL.OPERATION_CAPACITY - VR.BEDS_IN_USE AS NET_VACANCIES,
AIL.CAPACITY AS MAXIMUM_CAPACITY,
AIL.CAPACITY - VR.BEDS_IN_USE AS AVAILABLE_PHYSICAL,
(SELECT COUNT(*)
FROM AGENCY_INTERNAL_LOCATIONS AIL2
INNER JOIN LIVING_UNITS_MV LU2 ON AIL2.INTERNAL_LOCATION_ID = LU2.LIVING_UNIT_ID
WHERE AIL2.AGY_LOC_ID = VR.AGY_LOC_ID
AND LU2.ROOT_LIVING_UNIT_ID = AIL.INTERNAL_LOCATION_ID
AND (
AIL2.DEACTIVATE_REASON_CODE IS NULL OR
AIL2.DEACTIVATE_REASON_CODE NOT IN (:deactivateReasonCodes)
)
AND :currentDateTime BETWEEN DEACTIVATE_DATE AND COALESCE(REACTIVATE_DATE,:currentDateTime)) AS OUT_OF_ORDER
FROM
(SELECT
LU.AGY_LOC_ID,
LU.ROOT_LIVING_UNIT_ID,
SUM(DECODE(OB.LIVING_UNIT_ID, NULL, 0, 1)) AS BEDS_IN_USE,
SUM(DECODE(OB.AGENCY_IML_ID, NULL, DECODE (OB.IN_OUT_STATUS, 'IN', 1, 0), 0)) AS CURRENTLY_IN_CELL,
SUM(DECODE(OB.AGENCY_IML_ID, NULL, 0, DECODE (OB.IN_OUT_STATUS, 'IN', 1, 0))) AS OUT_OF_LIVING_UNITS,
SUM(DECODE(OB.IN_OUT_STATUS, 'OUT', 1, 0)) AS CURRENTLY_OUT
FROM LIVING_UNITS_MV LU
LEFT JOIN OFFENDER_BOOKINGS OB ON LU.LIVING_UNIT_ID = OB.LIVING_UNIT_ID AND LU.AGY_LOC_ID = OB.AGY_LOC_ID
GROUP BY LU.AGY_LOC_ID, LU.ROOT_LIVING_UNIT_ID
) VR
INNER JOIN AGENCY_INTERNAL_LOCATIONS AIL ON AIL.INTERNAL_LOCATION_ID = VR.ROOT_LIVING_UNIT_ID
WHERE AIL.CERTIFIED_FLAG = :certifiedFlag
AND AIL.UNIT_TYPE IS NOT NULL
AND AIL.AGY_LOC_ID = :agencyId
AND AIL.ACTIVE_FLAG = 'Y'
AND ((AIL.PARENT_INTERNAL_LOCATION_ID IS NULL AND :livingUnitId IS NULL) OR AIL.PARENT_INTERNAL_LOCATION_ID = :livingUnitId)
ORDER BY LIVING_UNIT_DESC
"""
),
GET_OFFENDERS_OUT_TODAY(
"""
SELECT /*+ index(OEM, OFFENDER_EXT_MOVEMENTS_X01) */
DIRECTION_CODE,
MOVEMENT_DATE,
FROM_AGY_LOC_ID AS FROM_AGENCY,
OFFENDERS.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OFFENDERS.FIRST_NAME,
OFFENDERS.LAST_NAME,
OFFENDERS.BIRTH_DATE AS DATE_OF_BIRTH,
RC2.DESCRIPTION AS MOVEMENT_REASON_DESCRIPTION,
OEM.MOVEMENT_TIME
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS ON OFFENDERS.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = OEM.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
WHERE
OEM.MOVEMENT_TYPE = COALESCE(:movementType, OEM.MOVEMENT_TYPE) AND
OEM.MOVEMENT_DATE = :movementDate AND
OEM.DIRECTION_CODE = 'OUT' AND
OEM.FROM_AGY_LOC_ID = :agencyId
"""
),
GET_OFFENDERS_IN_RECEPTION(
"""
SELECT
VR.OFFENDER_NO,
VR.FIRST_NAME,
VR.LAST_NAME,
VR.DATE_OF_BIRTH,
VR.BOOKING_ID
FROM
(SELECT
LU.AGY_LOC_ID,
LU.ROOT_LIVING_UNIT_ID,
O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
O.FIRST_NAME AS FIRST_NAME,
O.LAST_NAME AS LAST_NAME,
O.BIRTH_DATE AS DATE_OF_BIRTH,
DECODE(OB.AGENCY_IML_ID, NULL, DECODE (OB.IN_OUT_STATUS, 'IN', 1, 0), 0) AS STATUS_IN,
OB.OFFENDER_BOOK_ID AS BOOKING_ID
FROM LIVING_UNITS_MV LU
INNER JOIN OFFENDER_BOOKINGS OB ON LU.LIVING_UNIT_ID = OB.LIVING_UNIT_ID AND LU.AGY_LOC_ID = OB.AGY_LOC_ID
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
) VR
INNER JOIN AGENCY_INTERNAL_LOCATIONS AIL4 ON AIL4.INTERNAL_LOCATION_ID = VR.ROOT_LIVING_UNIT_ID
WHERE AIL4.CERTIFIED_FLAG = 'N'
AND AIL4.UNIT_TYPE IS NOT NULL
AND AIL4.AGY_LOC_ID = :agencyId
AND STATUS_IN = 1
AND AIL4.PARENT_INTERNAL_LOCATION_ID IS NULL
AND AIL4.ACTIVE_FLAG = 'Y'
"""
),
GET_OFFENDERS_CURRENTLY_OUT_OF_LIVING_UNIT(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OB.OFFENDER_BOOK_ID AS BOOKING_ID,
O.FIRST_NAME,
O.LAST_NAME,
O.BIRTH_DATE AS DATE_OF_BIRTH,
COALESCE(AIL.USER_DESC, AIL.DESCRIPTION) AS LOCATION
FROM LIVING_UNITS_MV LU
JOIN OFFENDER_BOOKINGS OB ON LU.LIVING_UNIT_ID = OB.LIVING_UNIT_ID AND
LU.AGY_LOC_ID = OB.AGY_LOC_ID
JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT OUTER JOIN AGENCY_INTERNAL_LOCATIONS AIL ON LU.LIVING_UNIT_ID = AIL.INTERNAL_LOCATION_ID
WHERE OB.BOOKING_SEQ = :bookingSeq
AND OB.IN_OUT_STATUS = :inOutStatus
AND LU.ROOT_LIVING_UNIT_ID = :livingUnitId
"""
),
GET_OFFENDERS_CURRENTLY_OUT_OF_AGENCY(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OB.OFFENDER_BOOK_ID AS BOOKING_ID,
O.FIRST_NAME,
O.LAST_NAME,
O.BIRTH_DATE AS DATE_OF_BIRTH,
COALESCE(AIL2.USER_DESC, AIL2.DESCRIPTION) AS LOCATION
FROM LIVING_UNITS_MV LU
JOIN OFFENDER_BOOKINGS OB ON LU.LIVING_UNIT_ID = OB.LIVING_UNIT_ID AND
lu.AGY_LOC_ID = ob.AGY_LOC_ID
JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
JOIN AGENCY_INTERNAL_LOCATIONS AIL ON LU.ROOT_LIVING_UNIT_ID = AIL.INTERNAL_LOCATION_ID
LEFT OUTER JOIN AGENCY_INTERNAL_LOCATIONS AIL2 ON LU.LIVING_UNIT_ID = AIL2.INTERNAL_LOCATION_ID
WHERE OB.BOOKING_SEQ = :bookingSeq
AND OB.IN_OUT_STATUS = :inOutStatus
and lu.AGY_LOC_ID = :agencyId
and ail.CERTIFIED_FLAG = :certifiedFlag
and ail.ACTIVE_FLAG = :activeFlag
and ail.PARENT_INTERNAL_LOCATION_ID IS NULL
"""
),
GET_MOVEMENTS_BY_AGENCY_AND_TIME_PERIOD(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OEM.CREATE_DATETIME AS CREATE_DATE_TIME,
OEM.EVENT_ID AS EVENT_ID,
OEM.FROM_AGY_LOC_ID AS FROM_AGENCY,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
OEM.TO_AGY_LOC_ID AS TO_AGENCY,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
OEM.MOVEMENT_TIME AS MOVEMENT_TIME,
OEM.MOVEMENT_TYPE AS MOVEMENT_TYPE,
RC1.DESCRIPTION AS MOVEMENT_TYPE_DESCRIPTION,
OEM.MOVEMENT_REASON_CODE AS MOVEMENT_REASON_CODE,
RC2.DESCRIPTION AS MOVEMENT_REASON,
OEM.DIRECTION_CODE AS DIRECTION_CODE,
RC3.DESCRIPTION AS FROM_CITY,
RC4.DESCRIPTION AS TO_CITY
FROM OFFENDER_EXTERNAL_MOVEMENTS OEM
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OEM.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON OEM.FROM_AGY_LOC_ID = AL1.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON OEM.TO_AGY_LOC_ID = AL2.AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC1 ON RC1.CODE = OEM.MOVEMENT_TYPE AND RC1.DOMAIN = 'MOVE_TYPE'
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = OEM.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OEM.FROM_CITY AND RC3.DOMAIN = 'CITY'
LEFT JOIN REFERENCE_CODES RC4 ON RC4.CODE = OEM.TO_CITY AND RC4.DOMAIN = 'CITY'
WHERE
OEM.MOVEMENT_TIME BETWEEN :fromDateTime AND :toDateTime
AND (OEM.FROM_AGY_LOC_ID IN (:agencyListFrom) OR OEM.TO_AGY_LOC_ID IN (:agencyListTo))
ORDER BY OEM.MOVEMENT_TIME
"""
),
GET_COURT_EVENTS_BY_AGENCY_AND_TIME_PERIOD(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
CE.CREATE_DATETIME AS CREATE_DATE_TIME,
CE.EVENT_ID AS EVENT_ID,
OB.AGY_LOC_ID AS FROM_AGENCY,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
CE.AGY_LOC_ID AS TO_AGENCY,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
CE.EVENT_DATE AS EVENT_DATE,
CE.START_TIME AS START_TIME,
CE.END_TIME AS END_TIME,
DECODE (OB.in_out_status,
'IN', DECODE (OB.active_flag, 'Y', 'EXT_MOV', 'COMM'),
'OUT', DECODE (OB.active_flag, 'Y', 'EXT_MOV', 'COMM'), 'COMM')
AS EVENT_CLASS,
'CRT' AS EVENT_TYPE,
ce.COURT_EVENT_TYPE AS EVENT_SUB_TYPE,
DECODE (ce.event_status,
NULL, 'SCH',
ce.event_status) AS EVENT_STATUS,
CE.JUDGE_NAME AS JUDGE_NAME,
CE.DIRECTION_CODE AS DIRECTION_CODE,
CE.COMMENT_TEXT AS COMMENT_TEXT,
DECODE(OB.ACTIVE_FLAG, 'Y', 1, 0) AS BOOKING_ACTIVE_FLAG,
OB.IN_OUT_STATUS AS BOOKING_IN_OUT_STATUS
FROM COURT_EVENTS CE
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = CE.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON AL1.AGY_LOC_ID = OB.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON AL2.AGY_LOC_ID = CE.AGY_LOC_ID
WHERE CE.HOLD_FLAG <> 'Y'
AND CE.START_TIME BETWEEN :fromDateTime AND :toDateTime
AND (OB.AGY_LOC_ID IN (:agencyListFrom) OR CE.AGY_LOC_ID IN (:agencyListTo))
"""
),
GET_OFFENDER_TRANSFERS_BY_AGENCY_AND_TIME_PERIOD(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OIS.CREATE_DATETIME AS CREATE_DATE_TIME,
OIS.EVENT_ID AS EVENT_ID,
OIS.AGY_LOC_ID AS FROM_AGENCY,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
OIS.TO_AGY_LOC_ID AS TO_AGENCY,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
RC3.DESCRIPTION AS TO_CITY,
OIS.EVENT_STATUS AS EVENT_STATUS,
OIS.EVENT_CLASS AS EVENT_CLASS,
OIS.EVENT_TYPE AS EVENT_TYPE,
OIS.EVENT_SUB_TYPE AS EVENT_SUB_TYPE,
OIS.EVENT_DATE AS EVENT_DATE,
OIS.START_TIME AS START_TIME,
OIS.END_TIME AS END_TIME,
OIS.OUTCOME_REASON_CODE AS OUTCOME_REASON_CODE,
OIS.JUDGE_NAME AS JUDGE_NAME,
OIS.ENGAGEMENT_CODE AS ENGAGEMENT_CODE,
OIS.ESCORT_CODE AS ESCORT_CODE,
OIS.PERFORMANCE_CODE AS PERFORMANCE_CODE,
OIS.DIRECTION_CODE AS DIRECTION_CODE,
DECODE(OB.ACTIVE_FLAG, 'Y', 1, 0) AS BOOKING_ACTIVE_FLAG,
OB.IN_OUT_STATUS AS BOOKING_IN_OUT_STATUS
FROM OFFENDER_IND_SCHEDULES OIS
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OIS.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON AL1.AGY_LOC_ID = OIS.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON AL2.AGY_LOC_ID = OIS.TO_AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OIS.TO_CITY_CODE AND RC3.DOMAIN = 'CITY'
WHERE OIS.EVENT_STATUS <> 'DEL'
AND OIS.EVENT_CLASS = 'EXT_MOV'
AND OIS.START_TIME BETWEEN :fromDateTime AND :toDateTime
AND (OIS.AGY_LOC_ID IN (:agencyListFrom) OR OIS.TO_AGY_LOC_ID IN (:agencyListTo))
"""
),
GET_OFFENDER_INDIVIDUAL_SCHEDULES_BY_DATE(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
OIS.CREATE_DATETIME AS CREATE_DATE_TIME,
OIS.EVENT_ID AS EVENT_ID,
OIS.AGY_LOC_ID AS FROM_AGENCY,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
OIS.TO_AGY_LOC_ID AS TO_AGENCY,
AL2.DESCRIPTION AS TO_AGENCY_DESCRIPTION,
RC3.DESCRIPTION AS TO_CITY,
OIS.EVENT_STATUS AS EVENT_STATUS,
OIS.EVENT_CLASS AS EVENT_CLASS,
OIS.EVENT_TYPE AS EVENT_TYPE,
OIS.EVENT_SUB_TYPE AS EVENT_SUB_TYPE,
OIS.EVENT_DATE AS EVENT_DATE,
OIS.START_TIME AS START_TIME,
OIS.END_TIME AS END_TIME,
OIS.OUTCOME_REASON_CODE AS OUTCOME_REASON_CODE,
OIS.JUDGE_NAME AS JUDGE_NAME,
OIS.ENGAGEMENT_CODE AS ENGAGEMENT_CODE,
OIS.ESCORT_CODE AS ESCORT_CODE,
OIS.PERFORMANCE_CODE AS PERFORMANCE_CODE,
OIS.DIRECTION_CODE AS DIRECTION_CODE,
DECODE(OB.ACTIVE_FLAG, 'Y', 1, 0) AS BOOKING_ACTIVE_FLAG,
OB.IN_OUT_STATUS AS BOOKING_IN_OUT_STATUS
FROM OFFENDER_IND_SCHEDULES OIS
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = OIS.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON AL1.AGY_LOC_ID = OIS.AGY_LOC_ID
LEFT JOIN AGENCY_LOCATIONS AL2 ON AL2.AGY_LOC_ID = OIS.TO_AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC3 ON RC3.CODE = OIS.TO_CITY_CODE AND RC3.DOMAIN = 'CITY'
WHERE OIS.EVENT_DATE = :date
"""
),
GET_OFFENDER_RELEASES_BY_AGENCY_AND_DATE(
"""
SELECT O.OFFENDER_ID_DISPLAY AS OFFENDER_NO,
ORD.CREATE_DATETIME AS CREATE_DATE_TIME,
ORD.EVENT_ID AS EVENT_ID,
OB.AGY_LOC_ID AS FROM_AGENCY,
AL1.DESCRIPTION AS FROM_AGENCY_DESCRIPTION,
ORD.RELEASE_DATE AS RELEASE_DATE,
ORD.APPROVED_RELEASE_DATE AS APPROVED_RELEASE_DATE,
'EXT_MOV' AS EVENT_CLASS,
ORD.EVENT_STATUS AS EVENT_STATUS,
ORD.MOVEMENT_TYPE AS MOVEMENT_TYPE_CODE,
RC1.DESCRIPTION AS MOVEMENT_TYPE_DESCRIPTION,
ORD.MOVEMENT_REASON_CODE AS MOVEMENT_REASON_CODE,
RC2.DESCRIPTION AS MOVEMENT_REASON_DESCRIPTION,
ORD.COMMENT_TEXT AS COMMENT_TEXT,
DECODE(OB.ACTIVE_FLAG, 'Y', 1, 0) AS BOOKING_ACTIVE_FLAG,
OB.IN_OUT_STATUS AS BOOKING_IN_OUT_STATUS
FROM OFFENDER_RELEASE_DETAILS ORD
INNER JOIN OFFENDER_BOOKINGS OB ON OB.OFFENDER_BOOK_ID = ORD.OFFENDER_BOOK_ID AND OB.BOOKING_SEQ = 1
INNER JOIN OFFENDERS O ON O.OFFENDER_ID = OB.OFFENDER_ID
LEFT JOIN AGENCY_LOCATIONS AL1 ON AL1.AGY_LOC_ID = OB.AGY_LOC_ID
LEFT JOIN REFERENCE_CODES RC1 ON RC1.CODE = ORD.MOVEMENT_TYPE AND RC1.DOMAIN = 'MOVE_TYPE'
LEFT JOIN REFERENCE_CODES RC2 ON RC2.CODE = ORD.MOVEMENT_REASON_CODE AND RC2.DOMAIN = 'MOVE_RSN'
WHERE ORD.RELEASE_DATE BETWEEN :fromDate AND :toDate
AND OB.AGY_LOC_ID IN (:agencyListFrom)
"""
)
}
| kotlin | 6 | 0.59991 | 132 | 47.729927 | 548 | starcoderdata |
<reponame>sergio11/MovieAddicts
package sanchez.sanchez.sergio.feature_main.persistence.api.tv
import sanchez.sanchez.sergio.feature_main.domain.model.Tv
import sanchez.sanchez.sergio.feature_main.persistence.network.repository.tv.IDiscoverTvNetworkRepository
import sanchez.sanchez.sergio.movie_addicts.core.domain.model.PageData
import sanchez.sanchez.sergio.movie_addicts.core.persistence.api.RepoErrorException
import sanchez.sanchez.sergio.movie_addicts.core.persistence.db.repository.IDBRepository
import java.lang.Exception
/**
* Discover Tv Repository Impl
* @param discoverTvNetworkRepository
* @param discoverTvDBRepository
*/
class DiscoverTvRepositoryImpl(
private val discoverTvNetworkRepository: IDiscoverTvNetworkRepository,
private val discoverTvDBRepository: IDBRepository<Tv>
): IDiscoverTvRepository {
/**
* Fetch Discover Tv
* @param page
*/
override suspend fun fetchDiscoverTv(page: Long): PageData<Tv> = try {
discoverTvNetworkRepository.fetchDiscoverTv(page).also {
discoverTvDBRepository.save(it.data)
}
} catch (ex: Exception) {
try {
PageData(page = 1, data = discoverTvDBRepository.getAll(), isLast = true)
} catch (ex: Exception) {
throw RepoErrorException(ex)
}
}
} | kotlin | 19 | 0.746393 | 105 | 35.611111 | 36 | starcoderdata |
package com.adamkobus.compose.navigation.demo.ui
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import com.adamkobus.compose.navigation.demo.ui.theme.DemoTheme
@Composable
fun PreviewComponent(content: @Composable () -> Unit) {
DemoTheme {
Surface(color = MaterialTheme.colors.background, content = content)
}
}
| kotlin | 16 | 0.789855 | 75 | 30.846154 | 13 | starcoderdata |
package net.lachlanmckee.bookmark.service.persistence.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import kotlinx.coroutines.flow.Flow
import net.lachlanmckee.bookmark.service.persistence.entity.BookmarkEntity
import net.lachlanmckee.bookmark.service.persistence.entity.BookmarkMetadataCrossRef
import net.lachlanmckee.bookmark.service.persistence.entity.BookmarkWithMetadata
@Dao
abstract class BookmarkDao {
@Query("SELECT * FROM bookmark WHERE folderId is NULL")
abstract fun getTopLevelBookmarks(): Flow<List<BookmarkWithMetadata>>
@Query("SELECT * FROM bookmark WHERE folderId = :folderId")
abstract fun getBookmarksWithinFolder(folderId: Long): Flow<List<BookmarkWithMetadata>>
@Transaction
open suspend fun insert(bookmarkEntity: BookmarkEntity, vararg metadataIds: Long) {
val bookmarkId = insert(bookmarkEntity)
insertAll(
*metadataIds
.map { metadataId ->
BookmarkMetadataCrossRef(
bookmarkId = bookmarkId,
metadataId = metadataId
)
}
.toTypedArray()
)
}
@Insert
abstract suspend fun insert(bookmarkEntity: BookmarkEntity): Long
@Insert
abstract suspend fun insertAll(vararg crossRef: BookmarkMetadataCrossRef)
@Query("DELETE FROM bookmark WHERE bookmarkId IN (:bookmarkIds)")
abstract suspend fun deleteByIds(bookmarkIds: LongArray)
@Query("DELETE FROM bookmark")
abstract suspend fun deleteAll()
}
| kotlin | 22 | 0.762284 | 89 | 31.73913 | 46 | starcoderdata |
<gh_stars>1-10
package com.ripple.crypto.ecdsa
import com.ripple.core.coretypes.AccountID
import com.ripple.core.coretypes.STObject
import com.ripple.core.types.known.tx.Transaction
import com.ripple.crypto.Seed
import com.ripple.crypto.ed25519.EDKeyPair
import com.ripple.encodings.common.B16
import org.intellij.lang.annotations.Language
import org.json.JSONObject
import org.junit.Test
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
class EDKeyPairTest {
@Language("JSON")
private val fixturesJson = """{
"tx_json": {
"Account": "<KEY>",
"Amount": "1000",
"Destination": "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh",
"Fee": "10",
"Flags": 2147483648,
"Sequence": 1,
"SigningPubKey": "EDD3993CDC6647896C455F136648B7750723B011475547AF60691AA3D7438E021D",
"TransactionType": "Payment"
},
"expected_sig": "C3646313B08EED6AF4392261A31B961F10C66CB733DB7F6CD9EAB079857834C8B0334270A2C037E63CDCCC1932E0832882B7B7066ECD2FAEDEB4A83DF8AE6303"
}"""
private var edKeyPair: EDKeyPair
private val fixtures = JSONObject(fixturesJson)
private val expectedSig = fixtures.getString("expected_sig")
private val txJson = fixtures.getJSONObject("tx_json")
private val tx = STObject.fromJSONObject(txJson) as Transaction
private val message = tx.signingData()
init {
val seedBytes = Seed.passPhraseToSeedBytes("niq")
edKeyPair = EDKeyPair.from128Seed(seedBytes)
}
@Test
fun testAccountIDGeneration() {
assertEquals("rJZdUusLDtY9NEsGea7ijqhVrXv98rYBYN",
AccountID.fromKeyPair(edKeyPair).toString())
}
@Test
fun testSigning() {
val bytes = edKeyPair.signMessage(message)
assertEquals(fixtures.getString("expected_sig"),
B16.encode(bytes))
}
@Test
fun testVerifying() {
assertTrue(edKeyPair.verify(message, B16.decode(expectedSig)))
}
} | kotlin | 18 | 0.706566 | 152 | 30.951613 | 62 | starcoderdata |
<reponame>AurityLab/graphql-kotlin-toolkit
package com.auritylab.graphql.kotlin.toolkit.common.directive
import com.auritylab.graphql.kotlin.toolkit.common.directive.exception.DirectiveValidationException
import graphql.Scalars
import graphql.introspection.Introspection
import graphql.schema.GraphQLArgument
import graphql.schema.GraphQLDirective
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertThrows
internal class AbstractDirectiveTest {
@Nested
inner class ValidateDefinition {
@Test
fun shouldThrowExceptionOnMissingArgument() {
assertThrows<DirectiveValidationException> {
// _directiveOne defines exactly one argument which is expected to be not available on _directiveEmpty,
// because it does not define any argument.
toInternal(_directiveOne).validateDefinition(_directiveEmpty)
}
}
@Test
fun shouldIgnoreTooManyArguments() {
assertDoesNotThrow {
// As a reference we have a directive with no arguments. We validate against a directive which defines
// exactly one argument. Because additional directives do not matter here, we just assert that it does
// not throw.
toInternal(_directiveEmpty).validateDefinition(_directiveOne)
}
}
@Test
fun shouldThrowExceptionOnMissingLocation() {
assertThrows<DirectiveValidationException> {
// _directiveTwo defines one valid location which is expected to be not available on _directiveEmpty.
// Therefore, we assert that an exception will be thrown.
toInternal(_directiveTwo).validateDefinition(_directiveEmpty)
}
}
@Test
fun shouldIgnoreTooManyLocations() {
assertDoesNotThrow {
// As a reference we have a directive with no valid locations. We validate against a directive which
// defines exactly one valid location. Because additional locations do not matter here, we assert that
// it does not throw any exception.
toInternal(_directiveEmpty).validateDefinition(_directiveTwo)
}
}
@Test
fun shouldThrowExceptionOnDifferingArgumentTypes () {
assertThrows<DirectiveValidationException> {
// As a reference we have a directive with exactly one argument named 'name' of type 'String'. We try
// to validate against a directive which also defines exactly one argument named 'name' but with a
// differing type 'boolean'. Because those types differ we assert that an exception will be thrown.
toInternal(_directiveOne).validateDefinition(_directiveThree)
}
}
}
private val _directiveEmpty = GraphQLDirective.newDirective()
.name("DirectiveEmpty").build()
private val _directiveOne = GraphQLDirective.newDirective()
.name("Directive")
.argument(
GraphQLArgument.newArgument()
.name("name")
.type(Scalars.GraphQLString)
).build()
private val _directiveTwo = GraphQLDirective.newDirective()
.name("DirectiveTwo")
.validLocations(Introspection.DirectiveLocation.FIELD)
.build()
private val _directiveThree = GraphQLDirective.newDirective()
.name("DirectiveThree")
.argument(GraphQLArgument.newArgument().name("name").type(Scalars.GraphQLBoolean))
.build()
/**
* Creates a new [AbstractDirective] based on the given input parameters. The [input] will be used
* as [AbstractDirective.reference]. All other parameters are optional and define default values.
*/
private fun toInternal(
input: GraphQLDirective,
name: String = "Test",
required: Boolean = false
): AbstractDirective {
return object : AbstractDirective(name) {
override val reference: GraphQLDirective = input
}
}
}
| kotlin | 19 | 0.660638 | 119 | 41.02 | 100 | starcoderdata |
/* The MIT License (MIT)
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.examples.kotlin
import org.neuroph.core.NeuralNetwork
import org.neuroph.core.learning.SupervisedTrainingElement
import org.neuroph.core.learning.TrainingSet
import org.neuroph.nnet.CompetitiveNetwork
import org.neuroph.nnet.learning.BackPropagation
import java.io.*
import java.util.*
object TestCompetitive {
@JvmStatic
var inputSize = 8
@JvmStatic
var outputSize = 1
@JvmStatic
var network: NeuralNetwork? = null
@JvmStatic
var trainingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var testingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var layers = arrayOf(8, 8, 1)
@JvmStatic
fun loadNetwork() {
network = NeuralNetwork.load("D:/GitHub/Neuroph-Intellij-Plugin/TestCompetitive.nnet")
}
@JvmStatic
fun trainNetwork() {
val list = ArrayList<Int>()
for (layer in layers) {
list.add(layer)
}
network = CompetitiveNetwork(inputSize, outputSize)
trainingSet = TrainingSet<SupervisedTrainingElement>(inputSize, outputSize)
trainingSet = TrainingSet.createFromFile("D:/GitHub/NeuralNetworkTest/Classroom Occupation Data.csv", inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val learningRule = BackPropagation()
(network as NeuralNetwork).learningRule = learningRule
(network as NeuralNetwork).learn(trainingSet)
(network as NeuralNetwork).save("D:/GitHub/Neuroph-Intellij-Plugin/TestCompetitive.nnet")
}
@JvmStatic
fun testNetwork() {
var input = ""
val fromKeyboard = BufferedReader(InputStreamReader(System.`in`))
val testValues = ArrayList<Double>()
var testValuesDouble: DoubleArray
do {
try {
println("Enter test values or \"\": ")
input = fromKeyboard.readLine()
if (input == "") {
break
}
input = input.replace(" ", "")
val stringVals = input.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
testValues.clear()
for (`val` in stringVals) {
testValues.add(java.lang.Double.parseDouble(`val`))
}
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
} catch (nfe: NumberFormatException) {
nfe.printStackTrace(System.err)
}
testValuesDouble = DoubleArray(testValues.size)
for (t in testValuesDouble.indices) {
testValuesDouble[t] = testValues[t].toDouble()
}
network?.setInput(*testValuesDouble)
network?.calculate()
} while (input != "")
}
@JvmStatic
fun testNetworkAuto(setPath: String) {
var total: Double = 0.0
val list = ArrayList<Int>()
val outputLine = ArrayList<String>()
for (layer in layers) {
list.add(layer)
}
testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val count: Int = testingSet?.elements()?.size!!
var averageDeviance = 0.0
var resultString = ""
try {
val file = File("Results " + setPath)
val fw = FileWriter(file)
val bw = BufferedWriter(fw)
for (i in 0..testingSet?.elements()?.size!! - 1) {
val expected: Double
val calculated: Double
network?.setInput(*testingSet?.elementAt(i)!!.input)
network?.calculate()
calculated = network?.output!![0]
expected = testingSet?.elementAt(i)?.idealArray!![0]
println("Calculated Output: " + calculated)
println("Expected Output: " + expected)
println("Deviance: " + (calculated - expected))
averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected))
total += network?.output!![0]
resultString = ""
for (cols in 0..testingSet?.elementAt(i)?.inputArray?.size!! - 1) {
resultString += testingSet?.elementAt(i)?.inputArray!![cols].toString() + ", "
}
for (t in 0..network?.output!!.size - 1) {
resultString += network?.output!![t].toString() + ", "
}
resultString = resultString.substring(0, resultString.length - 2)
resultString += ""
bw.write(resultString)
bw.flush()
println()
println("Average: " + (total / count).toString())
println("Average Deviance % : " + (averageDeviance / count * 100).toString())
bw.flush()
bw.close()
}
} catch (ex: IOException) {
ex.printStackTrace()
}
}
}
| kotlin | 25 | 0.712386 | 174 | 32.528662 | 157 | starcoderdata |
<reponame>Azure/communication-ui-library-android
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.calling.redux.action
internal sealed class LifecycleAction : Action {
class EnterForegroundTriggered : LifecycleAction()
class EnterBackgroundTriggered : LifecycleAction()
class EnterForegroundSucceeded : LifecycleAction()
class EnterBackgroundSucceeded : LifecycleAction()
}
| kotlin | 9 | 0.799172 | 63 | 36.153846 | 13 | starcoderdata |
<gh_stars>1000+
/*
* Copyright (c) 2018 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.global
import org.junit.Assert.*
import org.junit.Test
class HashUtilitiesTest {
@Test
fun whenSha1HashCalledOnStringThenResultIsCorrect() {
val result = helloWorldText.sha1
assertEquals(helloWorldSha1, result)
}
@Test
fun whenSha256HashCalledOnBytesThenResultIsCorrect() {
val result = helloWorldText.toByteArray().sha256
assertEquals(helloWorldSha256, result)
}
@Test
fun whenSha256HashCalledOnStringThenResultIsCorrect() {
val result = helloWorldText.sha256
assertEquals(helloWorldSha256, result)
}
@Test
fun whenCorrectSha256HashUsedThenVerifyIsTrue() {
assertTrue(helloWorldText.toByteArray().verifySha256(helloWorldSha256))
}
@Test
fun whenIncorrectByteSha256HashUsedThenVerifyIsFalse() {
assertFalse(helloWorldText.toByteArray().verifySha256(otherSha256))
}
companion object {
const val helloWorldText = "Hello World!"
const val helloWorldSha256 = "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069"
const val helloWorldSha1 = "2ef7bde608ce5404e97d5f042f95f89f1c232871"
const val otherSha256 = "f97e9da0e3b879f0a9df979ae260a5f7e1371edb127c1862d4f861981166cdc1"
}
}
| kotlin | 15 | 0.736454 | 103 | 31.220339 | 59 | starcoderdata |
package net.sourcebot.module.cryptography
import net.sourcebot.api.module.SourceModule
import net.sourcebot.module.cryptography.commands.*
class Cryptography : SourceModule() {
override fun enable() {
registerCommands(
Base64Command(),
OngCommand(),
MD2Command(),
MD5Command(),
SHACommand(),
SHA224Command(),
SHA256Command(),
SHA384Command(),
SHA512Command()
)
}
} | kotlin | 13 | 0.576305 | 51 | 23.95 | 20 | starcoderdata |
package world.gregs.voidps.world.activity.skill
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import world.gregs.voidps.engine.entity.character.contain.inventory
import world.gregs.voidps.engine.entity.character.player.skill.Skill
import world.gregs.voidps.engine.entity.definition.data.FishingCatch
import world.gregs.voidps.engine.map.Tile
import world.gregs.voidps.world.script.WorldMock
import world.gregs.voidps.world.script.mockItemExtras
import world.gregs.voidps.world.script.mockStackableItem
import world.gregs.voidps.world.script.npcOption
internal class FishingTest : WorldMock() {
@Test
fun `Fishing gives fish and removes bait`() = runBlocking(Dispatchers.Default) {
mockItemExtras(335, mapOf("fishing" to FishingCatch(15)))// raw_trout
mockItemExtras(331, mapOf("fishing" to FishingCatch(10)))// raw_salmon
mockItemExtras(10138, mapOf("fishing" to FishingCatch(25)))// raw_rainbow_fish
mockStackableItem(314) // feather
val player = createPlayer("fisher")
player.levels.setOffset(Skill.Fishing, 20)
val fishingSpot = createNPC("fishing_spot_lure_bait", Tile(100, 101))
player.inventory.add("fly_fishing_rod")
player.inventory.add("feather", 100)
player.npcOption(fishingSpot, "Lure")
tickIf { player.inventory.spaces >= 26 }
assertTrue(player.inventory.getCount("feather") < 100)
assertTrue(player.inventory.contains("raw_trout"))
assertTrue(player.experience.get(Skill.Fishing) > 0)
}
} | kotlin | 23 | 0.744539 | 86 | 41.282051 | 39 | starcoderdata |
<reponame>mirusu400/kw-notice<filename>kw-notice-android/app/src/main/java/dev/yjyoon/kwnotice/data/remote/model/SwCentralNotice.kt
package dev.yjyoon.kwnotice.data.remote.model
import com.google.gson.annotations.SerializedName
data class SwCentralNotice(
val id: Long,
val title: String,
@SerializedName("posted_date") val postedDate: String,
val url: String,
val type: String,
@SerializedName("crawled_time") val crawledTime: String
)
| kotlin | 14 | 0.76129 | 131 | 34.769231 | 13 | starcoderdata |
<filename>inbox/src/main/java/com/fightpandemics/inbox/dagger/InboxViewModelModule.kt<gh_stars>10-100
package com.fightpandemics.inbox.dagger
import androidx.lifecycle.ViewModel
import com.fightpandemics.core.utils.ViewModelKey
import com.fightpandemics.inbox.ui.InboxViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
@Module
abstract class InboxViewModelModule {
@Binds
@IntoMap
@ViewModelKey(InboxViewModel::class)
abstract fun bindInboxViewModel(inboxViewModel: InboxViewModel): ViewModel
}
| kotlin | 12 | 0.829091 | 101 | 29.555556 | 18 | starcoderdata |
package com.github.kerubistan.kerub.planner.steps
import com.github.kerubistan.kerub.planner.OperationalState
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.mockito.Mockito
class StepFactoryCollectionTest {
private val factory1 = mock<AbstractOperationalStepFactory<*>>()
private val factory2 = mock<AbstractOperationalStepFactory<*>>()
private val step1 = mock<AbstractOperationalStep>()
private val step2 = mock<AbstractOperationalStep>()
@Test
fun produceEmpty() {
assertTrue(StepFactoryCollection(listOf()).produce(OperationalState.fromLists()).isEmpty())
}
@Test
fun produce() {
whenever(factory1.produce(
Mockito.any(OperationalState::class.java)?: OperationalState.fromLists() )).thenReturn(listOf(step1))
whenever(factory2.produce(
Mockito.any(OperationalState::class.java)?: OperationalState.fromLists() )).thenReturn(listOf(step2))
val steps = StepFactoryCollection(listOf(factory1, factory2)).produce(OperationalState.fromLists())
assertEquals(2, steps.size)
assertTrue(steps.contains(step1))
assertTrue(steps.contains(step2))
}
@Test
fun produceWithDisabledFeature() {
whenever(factory1.produce(
Mockito.any(OperationalState::class.java) ?: OperationalState.fromLists())).thenReturn(listOf(step1))
whenever(factory2.produce(
Mockito.any(OperationalState::class.java) ?: OperationalState.fromLists())).thenReturn(listOf(step2))
val steps = StepFactoryCollection(listOf(factory1, factory2)) { false }.produce(OperationalState.fromLists())
assertEquals(steps, listOf<AbstractOperationalStep>())
}
} | kotlin | 23 | 0.784795 | 111 | 34.645833 | 48 | starcoderdata |
<filename>shell/src/test/kotlin/app/graviton/shell/TestWithFakeJRE.kt
package app.graviton.shell
import app.graviton.shell.TestWithFakeJRE.FileOrDirectory.DIRECTORY
import app.graviton.shell.TestWithFakeJRE.FileOrDirectory.FILE
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import java.nio.file.FileSystem
import java.nio.file.Files
import java.nio.file.Path
import java.security.KeyStore
import java.security.PublicKey
open class TestWithFakeJRE {
// Shared file system that is left alone between tests.
private val fs: FileSystem = Jimfs.newFileSystem(
Configuration.unix().toBuilder().setAttributeViews("basic", "posix").build()
)
protected val root: Path = fs.rootDirectories.first()
// fakeMacJreDir is the directory produced by javapackager, before version mangling.
val fakeMacJreDir = root / "fake-jre-mac"
val fakeLinuxJreDir = root / "fake-jre-linux"
// We have to load a pre-generated private key and cert because the Java crypto API is incomplete. There's no
// API for building a certificate. We could probably do it with Bouncy Castle but I don't have that on the plane.
private val testKeyStore = javaClass.getResourceAsStream("/test.pks").use {
val ks = KeyStore.getInstance("PKCS12")
ks.load(it, "testtest".toCharArray())
ks
}
val priv1 = testKeyStore.getEntry("mykey", KeyStore.PasswordProtection("testtest".toCharArray())) as KeyStore.PrivateKeyEntry
val pub1: PublicKey = priv1.certificate.publicKey
val testUpdateMac = RuntimeUpdate(javaClass.getResource("/test-update-mac.jar").toPath(), pub1)
val testUpdateLinux = RuntimeUpdate(javaClass.getResource("/test-update-linux.jar").toPath(), pub1)
enum class FileOrDirectory { FILE, DIRECTORY }
init {
// The fake images aren't that realistic, but it has roughly the right structure.
createFakeJREImage("/example-runtime-files-mac.txt", fakeMacJreDir)
createFakeJREImage("/example-runtime-files-linux.txt", fakeLinuxJreDir)
}
private fun createFakeJREImage(layoutResourcePath: String, destinationPath: Path) {
RuntimeUpdateTest::class.java.getResourceAsStream(layoutResourcePath).bufferedReader().useLines { lines ->
// Use a heuristic to figure out if each line is supposed to be a file or directory.
val types = LinkedHashMap<Path, FileOrDirectory>()
for (line in lines) {
val path = destinationPath / line
// Assume a file unless we see a following entry that is underneath it.
types[path] = FILE
if (path.toString().endsWith("/") || path.parent?.let { types[it] } == FILE) {
types[path.parent] = DIRECTORY
}
}
for ((path, type) in types) {
when (type) {
DIRECTORY -> Files.createDirectories(path)
FILE -> Files.write(path, ByteArray(1))
}
}
}
}
/* - requires java 9+ for the JarSigner API, run manually and the result checked into git.
TODO: Once we're upgraded to Java 11 uncomment this and generate it each time.
fun createFrom(from: Path, signingKey: KeyStore.PrivateKeyEntry, outputPath: Path): RuntimeUpdate {
val tempZip = Files.createTempFile("graviton-runtimeupdate-test", ".zip")
try {
// Step 1. Create the unsigned zip. Unfortunately the JarSigner API is quite old and wants to
// write to a different file to the input, even though it could be modified in place.
ZipOutputStream(Files.newOutputStream(tempZip).buffered()).use { zos ->
Files.walk(from).use { walk ->
for (path in walk) {
val isDir = Files.isDirectory(path)
if (path == from) continue
val s = from.relativize(path).toString()
val pathStr = s + if (isDir && !s.endsWith("/")) "/" else ""
zos.putNextEntry(ZipEntry(pathStr))
if (!isDir)
Files.newInputStream(path).use { it.copyTo(zos) }
zos.closeEntry()
}
}
}
// Step 2. Copy the temp zip and sign it along the way.
Files.newOutputStream(outputPath, StandardOpenOption.CREATE_NEW).buffered().use { stream ->
JarSigner.Builder(signingKey).build().sign(ZipFile(tempZip.toFile()), stream)
}
return RuntimeUpdate(outputPath, signingKey.certificate.publicKey)
} finally {
Files.deleteIfExists(tempZip)
}
} */
}
| kotlin | 25 | 0.632589 | 129 | 48.412371 | 97 | starcoderdata |
@file:Suppress("SpellCheckingInspection")
package com.imn.iicnma
import org.intellij.lang.annotations.Language
@Language("JSON")
val movieDetailJson = """{
"adult": false,
"backdrop_path": "/5UkzNSOK561c2QRy2Zr4AkADzLT.jpg",
"belongs_to_collection": null,
"budget": 0,
"genres": [
{
"id": 878,
"name": "Science Fiction"
},
{
"id": 53,
"name": "Thriller"
},
{
"id": 18,
"name": "Drama"
}
],
"homepage": "http://screen.nsw.gov.au/project/2067",
"id": 528085,
"imdb_id": "tt1918734",
"original_language": "en",
"original_title": "2067",
"overview": "A lowly utility worker is called to the future by a mysterious radio signal, he must leave his dying wife to embark on a journey that will force him to face his deepest fears in an attempt to change the fabric of reality and save humankind from its greatest environmental crisis yet.",
"popularity": 1545.946,
"poster_path": "/7D430eqZj8y3oVkLFfsWXGRcpEG.jpg",
"production_companies": [
{
"id": 22369,
"logo_path": null,
"name": "Arcadia",
"origin_country": "AU"
},
{
"id": 105250,
"logo_path": null,
"name": "KOJO Entertainment",
"origin_country": "AU"
},
{
"id": 142069,
"logo_path": null,
"name": "Elevate Production Finance",
"origin_country": "AU"
},
{
"id": 107909,
"logo_path": null,
"name": "<NAME>",
"origin_country": "US"
},
{
"id": 142070,
"logo_path": null,
"name": "Rocketboy",
"origin_country": "AU"
}
],
"production_countries": [
{
"iso_3166_1": "AU",
"name": "Australia"
}
],
"release_date": "2020-10-01",
"revenue": 0,
"runtime": 114,
"spoken_languages": [
{
"english_name": "English",
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "The fight for the future has begun.",
"title": "2067",
"video": false,
"vote_average": 4.8,
"vote_count": 357
}
""".trimIndent()
@Language("JSON")
val pagedListJson = """{
"total_results": 10000,
"page": 1,
"total_pages": 500,
"results": [
{
"release_date": "2020-10-01",
"adult": false,
"backdrop_path": "/5UkzNSOK561c2QRy2Zr4AkADzLT.jpg",
"vote_count": 356,
"genre_ids": [
878,
53,
18
],
"id": 528085,
"original_language": "en",
"original_title": "2067",
"poster_path": "/7D430eqZj8y3oVkLFfsWXGRcpEG.jpg",
"title": "2067",
"video": false,
"vote_average": 4.8,
"popularity": 1545.946,
"overview": "A lowly utility worker is called to the future by a mysterious radio signal, he must leave his dying wife to embark on a journey that will force him to face his deepest fears in an attempt to change the fabric of reality and save humankind from its greatest environmental crisis yet."
},
{
"release_date": "2020-10-23",
"adult": false,
"backdrop_path": "/86L8wqGMDbwURPni2t7FQ0nDjsH.jpg",
"id": 724989,
"genre_ids": [
28,
53
],
"overview": "The work of billionaire tech CEO <NAME> is so valuable that he hires mercenaries to protect it, and a terrorist group kidnaps his daughter just to get it.",
"original_language": "en",
"original_title": "Hard Kill",
"poster_path": "/ugZW8ocsrfgI95pnQ7wrmKDxIe.jpg",
"title": "Hard Kill",
"video": false,
"vote_average": 5,
"popularity": 1316.819,
"vote_count": 163
},
{
"release_date": "2020-08-14",
"adult": false,
"backdrop_path": "/wu1uilmhM4TdluKi2ytfz8gidHf.jpg",
"genre_ids": [
16,
14,
12,
35,
10751
],
"id": 400160,
"overview": "When his best friend Gary is suddenly snatched away, SpongeBob takes Patrick on a madcap mission far beyond Bikini Bottom to save their pink-shelled pal.",
"original_language": "en",
"original_title": "The SpongeBob Movie: Sponge on the Run",
"poster_path": "/jlJ8nDhMhCYJuzOw3f52CP1W8MW.jpg",
"title": "The SpongeBob Movie: Sponge on the Run",
"video": false,
"vote_average": 8,
"popularity": 1190.392,
"vote_count": 1505
},
{
"release_date": "2020-07-29",
"adult": false,
"backdrop_path": "/2Fk3AB8E9dYIBc2ywJkxk8BTyhc.jpg",
"genre_ids": [
28,
53
],
"id": 524047,
"overview": "<NAME>, his estranged wife and their young son embark on a perilous journey to find sanctuary as a planet-killing comet hurtles toward Earth. Amid terrifying accounts of cities getting levelled, the Garrity's experience the best and worst in humanity. As the countdown to the global apocalypse approaches zero, their incredible trek culminates in a desperate and last-minute flight to a possible safe haven.",
"original_language": "en",
"original_title": "Greenland",
"poster_path": "/bNo2mcvSwIvnx8K6y1euAc1TLVq.jpg",
"title": "Greenland",
"video": false,
"vote_average": 7.1,
"popularity": 1081.895,
"vote_count": 612
}
]
}
""".trimIndent() | kotlin | 7 | 0.586509 | 428 | 28.161111 | 180 | starcoderdata |
package com.revolgenx.anilib.ui.viewmodel.character
import com.revolgenx.anilib.data.field.character.CharacterVoiceActorField
import com.revolgenx.anilib.infrastructure.service.character.CharacterService
import com.revolgenx.anilib.infrastructure.source.CharacterActorSource
import com.revolgenx.anilib.ui.viewmodel.SourceViewModel
class CharacterActorViewModel(private val characterService: CharacterService) :
SourceViewModel<CharacterActorSource, CharacterVoiceActorField>() {
override var field: CharacterVoiceActorField = CharacterVoiceActorField()
override fun createSource(): CharacterActorSource {
source = CharacterActorSource(field, characterService, compositeDisposable)
return source!!
}
}
| kotlin | 11 | 0.824087 | 83 | 40.055556 | 18 | starcoderdata |
package it.codingjam.github.ui.repo
import android.view.ViewGroup
import it.codingjam.github.core.Contributor
import it.codingjam.github.ui.common.DataBoundViewHolder
import it.codingjam.github.ui.repo.databinding.ContributorItemBinding
class ContributorViewHolder(parent: ViewGroup, private val viewModel: RepoViewModel) :
DataBoundViewHolder<Contributor, ContributorItemBinding>(parent, ContributorItemBinding::inflate) {
init {
binding.viewHolder = this
}
override fun bind(t: Contributor) {
binding.contributor = t
}
fun openUserDetail() = viewModel.openUserDetail(item.login)
}
| kotlin | 11 | 0.767773 | 107 | 29.142857 | 21 | starcoderdata |
<filename>game/src/main/kotlin/ds/tetris/game/PaintStyle.kt
/*
* © 2017 <NAME>
*/
package ds.tetris.game
enum class PaintStyle {
STROKE, FILL
} | kotlin | 9 | 0.695364 | 59 | 14.2 | 10 | starcoderdata |
<reponame>cfuerst/aws-doc-sdk-examples
//snippet-sourcedescription:[DeleteNamedQueryExample.kt demonstrates how to delete a named query by using the named query Id value.]
//snippet-keyword:[AWS SDK for Kotlin]
//snippet-keyword:[Code Sample]
//snippet-keyword:[Amazon Athena]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[07/14/2021]
//snippet-sourceauthor:[scmacdon - aws]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.athena
//snippet-start:[athena.kotlin.DeleteNamedQueryExample.import]
import aws.sdk.kotlin.runtime.AwsServiceException
import aws.sdk.kotlin.services.athena.AthenaClient
import aws.sdk.kotlin.services.athena.model.DeleteNamedQueryRequest
import kotlin.system.exitProcess
//snippet-end:[athena.kotlin.DeleteNamedQueryExample.import]
/**
To run this Kotlin code example, ensure that you have setup your development environment,
including your credentials.
For information, see this documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args:Array<String>) {
val usage = """
Usage:
<queryId>
Where:
queryId - the id of the Amazon Athena query (for example, b34e7780-903b-4842-9d2c-6c99bebc82aa).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val queryId = args[0]
val athenaClient = AthenaClient { region = "us-west-2" }
deleteQueryName(athenaClient,queryId)
athenaClient.close()
}
//snippet-start:[athena.kotlin.DeleteNamedQueryExample.main]
suspend fun deleteQueryName(athenaClient: AthenaClient, sampleNamedQueryId: String?) {
try {
val deleteNamedQueryRequest = DeleteNamedQueryRequest {
namedQueryId = sampleNamedQueryId
}
athenaClient.deleteNamedQuery(deleteNamedQueryRequest)
println("$sampleNamedQueryId was deleted!")
} catch (ex: AwsServiceException) {
println(ex.message)
athenaClient.close()
exitProcess(0)
}
}
//snippet-end:[athena.kotlin.DeleteNamedQueryExample.main]
| kotlin | 14 | 0.70575 | 132 | 29.814286 | 70 | starcoderdata |
<filename>Architecture/UnidirectionalKotlinCats/core/src/main/kotlin/com/odai/architecturedemo/event/Status.kt
package com.odai.architecturedemo.event
enum class Status {
LOADING,
IDLE,
ERROR
}
| kotlin | 12 | 0.78744 | 110 | 24.875 | 8 | starcoderdata |
<gh_stars>100-1000
fun <T> getT(): T = null!!
class Test<in I, out O> {
private var i: I = getT()
private val j: I
init {
j = getT()
i = getT()
this.i = getT()
}
fun test() {
i = getT()
this.i = getT()
with(Test<I, O>()) {
i = getT() // resolved to this@Test.i
this.i = getT()
this@with.i = getT()
this@Test.i = getT()
}
}
fun <I, O> test(t: Test<I, O>) {
t.i = getT()
}
companion object {
fun <I, O> test(t: Test<I, O>) {
t.i = getT()
}
}
}
fun <I, O> test(t: Test<I, O>) {
t.<!INAPPLICABLE_CANDIDATE!>i<!> = getT()
}
| kotlin | 16 | 0.402817 | 49 | 17.684211 | 38 | starcoderdata |
/*
* Copyright (c) 2005-2021 <NAME>. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.radiance.demo.component.ktx.group
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.swing.Swing
import org.pushingpixels.radiance.demo.component.ktx.svg.Format_text_bold
import org.pushingpixels.radiance.demo.component.ktx.svg.Format_text_italic
import org.pushingpixels.radiance.demo.component.ktx.svg.Format_text_strikethrough
import org.pushingpixels.radiance.demo.component.ktx.svg.Format_text_underline
import org.pushingpixels.radiance.component.api.common.model.CommandStripPresentationModel
import org.pushingpixels.radiance.swing.ktx.swing.CharacterStyleType
import org.pushingpixels.radiance.swing.ktx.swing.hasStyleInSelection
import org.pushingpixels.radiance.swing.ktx.swing.toggleStyleInSelection
import org.pushingpixels.radiance.component.ktx.command
import org.pushingpixels.radiance.component.ktx.commandButtonStrip
import org.pushingpixels.radiance.theming.api.RadianceThemingCortex
import org.pushingpixels.radiance.theming.api.skin.GeminiSkin
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.FlowLayout
import java.awt.image.BufferedImage
import java.util.*
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.JTextPane
import javax.swing.WindowConstants
import javax.swing.border.EmptyBorder
import javax.swing.text.DefaultCaret
fun main() {
GlobalScope.launch(Dispatchers.Swing) {
RadianceThemingCortex.GlobalScope.setSkin(
GeminiSkin()
)
val frame = JFrame("Text styling demo")
frame.layout = BorderLayout()
// Configure and populate "Lorem ipsum" multiline content
val textPane = JTextPane()
textPane.text =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
textPane.isEditable = false
textPane.border = EmptyBorder(12, 12, 12, 12)
// force the display of text selection even when the focus has been lost
textPane.caret = object : DefaultCaret() {
override fun setSelectionVisible(visible: Boolean) {
super.setSelectionVisible(true)
}
}
frame.add(textPane, BorderLayout.CENTER)
val styleButtonPanel = JPanel(FlowLayout())
frame.add(styleButtonPanel, BorderLayout.LINE_END)
val resourceBundle = ResourceBundle
.getBundle("org.pushingpixels.radiance.demo.component.ktx.resources.Resources", Locale.getDefault())
val commandBold = command {
iconFactory = Format_text_bold.factory()
action = {
textPane.toggleStyleInSelection(CharacterStyleType.STYLE_BOLD)
isToggleSelected = textPane.hasStyleInSelection(CharacterStyleType.STYLE_BOLD)
}
isToggle = true
isActionEnabled = false
actionRichTooltip {
title = resourceBundle.getString("FontBold.tooltip.textActionTitle")
description = resourceBundle.getString("FontBold.tooltip.textActionParagraph1")
}
}
val commandItalic = command {
iconFactory = Format_text_italic.factory()
action = {
textPane.toggleStyleInSelection(CharacterStyleType.STYLE_ITALIC)
isToggleSelected = textPane.hasStyleInSelection(CharacterStyleType.STYLE_ITALIC)
}
isToggle = true
isActionEnabled = false
actionRichTooltip {
title = resourceBundle.getString("FontItalic.tooltip.textActionTitle")
description = resourceBundle.getString("FontItalic.tooltip.textActionParagraph1")
}
}
val commandUnderline = command {
iconFactory = Format_text_underline.factory()
action = {
textPane.toggleStyleInSelection(CharacterStyleType.STYLE_UNDERLINE)
isToggleSelected = textPane.hasStyleInSelection(CharacterStyleType.STYLE_UNDERLINE)
}
isToggle = true
isActionEnabled = false
actionRichTooltip {
title = resourceBundle.getString("FontUnderline.tooltip.textActionTitle")
description = resourceBundle.getString("FontUnderline.tooltip.textActionParagraph1")
}
}
val commandStrikethrough = command {
iconFactory = Format_text_strikethrough.factory()
action = {
textPane.toggleStyleInSelection(CharacterStyleType.STYLE_STRIKETHROUGH)
isToggleSelected = textPane.hasStyleInSelection(CharacterStyleType.STYLE_STRIKETHROUGH)
}
isToggle = true
isActionEnabled = false
actionRichTooltip {
title = resourceBundle.getString("FontStrikethrough.tooltip.textActionTitle")
description = resourceBundle.getString("FontStrikethrough.tooltip.textActionParagraph1")
}
}
// Create a button strip to change the text styling in our text pane.
val commandStyleStrip = commandButtonStrip {
+commandBold
+commandItalic
+commandUnderline
+commandStrikethrough
presentation {
orientation = CommandStripPresentationModel.StripOrientation.VERTICAL
horizontalGapScaleFactor = 0.8
verticalGapScaleFactor = 1.4
}
}
styleButtonPanel.add(commandStyleStrip.toJavaButtonStrip())
textPane.addCaretListener {
// Compute selection presence
val hasSelection = (textPane.selectionEnd - textPane.selectionStart) > 0
// Enable or disable the style commands based on that
commandBold.isActionEnabled = hasSelection
commandItalic.isActionEnabled = hasSelection
commandUnderline.isActionEnabled = hasSelection
commandStrikethrough.isActionEnabled = hasSelection
// For each command, determine if its toggle selection is on based on
// the presence of the matching style in the text pane selection
commandBold.isToggleSelected = textPane.hasStyleInSelection(
CharacterStyleType.STYLE_BOLD)
commandItalic.isToggleSelected = textPane.hasStyleInSelection(
CharacterStyleType.STYLE_ITALIC)
commandUnderline.isToggleSelected = textPane.hasStyleInSelection(
CharacterStyleType.STYLE_UNDERLINE)
commandStrikethrough.isToggleSelected = textPane.hasStyleInSelection(
CharacterStyleType.STYLE_STRIKETHROUGH)
}
// Show our frame in the center of the screen
frame.iconImage = BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR)
frame.size = Dimension(600, 300)
frame.setLocationRelativeTo(null)
frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
frame.isVisible = true
}
}
| kotlin | 25 | 0.700942 | 463 | 46.251309 | 191 | starcoderdata |
package com.soywiz.korim.annotation
@RequiresOptIn
annotation class KorimInternal
object KorimInternalObject
| kotlin | 5 | 0.873874 | 35 | 17.5 | 6 | starcoderdata |
// TARGET_BACKEND: JVM
// WITH_RUNTIME
class MyCollection<T>(val delegate: Collection<T>): Collection<T> by delegate
fun box(): String {
val collection = MyCollection(listOf(2, 3, 9)) as java.util.Collection<*>
val array1 = collection.toArray()
val array2 = collection.toArray(arrayOfNulls<Int>(3) as Array<Int>)
if (!array1.isArrayOf<Any>()) return (array1 as Object).getClass().toString()
if (!array2.isArrayOf<Int>()) return (array2 as Object).getClass().toString()
val s1 = array1.contentToString()
val s2 = array2.contentToString()
if (s1 != "[2, 3, 9]") return "s1 = $s1"
if (s2 != "[2, 3, 9]") return "s2 = $s2"
return "OK"
}
| kotlin | 15 | 0.643172 | 81 | 28.608696 | 23 | starcoderdata |
package com.example.hellodatapersistence8
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
@Entity(tableName = "programmers",
foreignKeys=[ForeignKey(entity=CryptoCurrency::class, parentColumns = ["id"], childColumns = ["cryptocurrency_id"], onDelete=ForeignKey.CASCADE)])
data class Programmer(
@PrimaryKey(autoGenerate = true)
var id: Int,
var name: String,
var cryptocurrency_id: Int
) | kotlin | 14 | 0.752174 | 154 | 26.117647 | 17 | starcoderdata |
package com.baeldung.aggregate
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertEquals
@ExperimentalUnsignedTypes
class AggregateOperationsUnitTest {
private val classUnderTest: AggregateOperations = AggregateOperations()
@Test
fun whenCountOfList_thenReturnsValue() {
assertEquals(4, classUnderTest.countList())
}
@Test
fun whenSumOfList_thenReturnsTotalValue() {
assertEquals(27, classUnderTest.sumList())
}
@Test
fun whenSumOf_thenShouldSumAndPreserveType() {
val employees = listOf(Employee("A", 3500, 23u), Employee("B", 2000, 30u))
assertEquals(5500, employees.sumOf { it.salary })
assertEquals(53u, employees.sumOf { it.age })
}
@Test
fun whenAverageOfList_thenReturnsValue() {
assertEquals(6.75, classUnderTest.averageList())
}
@Test
fun whenMaximumOfList_thenReturnsMaximumValue() {
assertEquals(15, classUnderTest.maximumInList())
}
@Test
fun whenMinimumOfList_thenReturnsMinimumValue() {
assertEquals(1, classUnderTest.minimumInList())
}
@Test
fun whenMaxByList_thenReturnsLargestValue() {
assertEquals(3, classUnderTest.maximumByList())
}
@Test
fun whenMinByList_thenReturnsSmallestValue() {
assertEquals(15, classUnderTest.minimumByList())
}
@Test
fun whenMaxWithList_thenReturnsLargestValue(){
assertEquals("Kolkata", classUnderTest.maximumWithList())
}
@Test
fun whenMinWithList_thenReturnsSmallestValue(){
assertEquals("Barcelona", classUnderTest.minimumWithList())
}
@Test
fun whenSumByList_thenReturnsIntegerValue(){
assertEquals(135, classUnderTest.sumByList())
}
@Test
fun whenSumByDoubleList_thenReturnsDoubleValue(){
assertEquals(3.375, classUnderTest.sumByDoubleList())
}
@Test
fun whenFoldList_thenReturnsValue(){
assertEquals(73, classUnderTest.foldList())
}
@Test
fun whenFoldRightList_thenReturnsValue(){
assertEquals(73, classUnderTest.foldRightList())
}
@Test
fun whenFoldIndexedList_thenReturnsValue(){
assertEquals(89, classUnderTest.foldIndexedList())
}
@Test
fun whenFoldRightIndexedList_thenReturnsValue(){
assertEquals(89, classUnderTest.foldRightIndexedList())
}
@Test
fun whenReduceList_thenReturnsValue(){
assertEquals(-25, classUnderTest.reduceList())
}
@Test
fun whenReduceRightList_thenReturnsValue(){
assertEquals(-11, classUnderTest.reduceRightList())
}
@Test
fun whenReduceIndexedList_thenReturnsValue(){
assertEquals(-10, classUnderTest.reduceIndexedList())
}
@Test
fun whenReduceRightIndexedList_thenReturnsValue(){
assertEquals(5, classUnderTest.reduceRightIndexedList())
}
@Test
fun whenRunningFold_shouldReturnAllTheIntermediateResults() {
val numbers = listOf(1, 2, 3, 4, 5)
assertEquals(listOf(0, 1, 3, 6, 10, 15), numbers.runningFold(0) {total, it -> total + it})
}
@Test
fun whenRunningReduce_shouldReturnAllTheIntermediateResults() {
val numbers = listOf(1, 2, 3, 4, 5)
assertEquals(listOf(1, 3, 6, 10, 15), numbers.runningReduce { total, it -> total + it })
}
} | kotlin | 17 | 0.682196 | 98 | 25.753968 | 126 | starcoderdata |
<reponame>Mu-L/kotlin
// !CHECK_TYPE
object Outer {
private var x
get() = object : CharSequence {
override val length: Int
get() = 0
override fun get(index: Int): Char {
checkSubtype<CharSequence>(<!DEBUG_INFO_MISSING_UNRESOLVED, TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM!>x<!>)
return ' '
}
override fun subSequence(startIndex: Int, endIndex: Int) = ""
fun bar() {
}
}
set(q) {
checkSubtype<CharSequence>(x)
y = q
x = q
}
private var y = <!DEBUG_INFO_LEAKING_THIS!>x<!>
fun foo() {
x = y
checkSubtype<CharSequence>(x)
checkSubtype<CharSequence>(y)
x.bar()
y.bar()
}
}
| kotlin | 16 | 0.482339 | 125 | 21.805556 | 36 | starcoderdata |
// COMPARE_WITH_LIGHT_TREE
package h
class Square() {
var size : Double =
<!UNRESOLVED_REFERENCE!>set<!>(<!UNRESOLVED_REFERENCE!>value<!>) {
//in LT this LAMBDA_EXPRESSION get parsed lazyly, but doesn't got anywhere in FIR tree (as property doesn't have place for it)
<!SYNTAX{PSI}!>$area<!> <!SYNTAX{PSI}!>= size * size<!>
}
<!MUST_BE_INITIALIZED_OR_BE_ABSTRACT!>var area : Double<!>
private set
}
fun main() {
val s = Square()
s.size = 2.0
}
| kotlin | 14 | 0.642553 | 130 | 23.736842 | 19 | starcoderdata |
package test
fun test(f: () -> Unit) {
try {
f()
}
catch (e: MyException) {
f()
}
}
| kotlin | 10 | 0.384615 | 28 | 10.7 | 10 | starcoderdata |
// EXPECTED_REACHABLE_NODES: 1253
// MODULE: lib
// FILE: lib.kt
interface II {
companion object : DDD by error("OK")
}
interface DDD {
fun bar(d: String = error("FAIL4")): String
}
// MODULE: main(lib)
// FILE: main.kt
fun box() : String {
try {
return II.bar()
} catch (e: IllegalStateException) {
return e.message ?: "FAIL 2"
}
return "FAIL"
} | kotlin | 10 | 0.586118 | 47 | 16.727273 | 22 | starcoderdata |
<filename>app/src/main/java/com/example/feedme/models/NonNullMutableLiveData.kt
package com.example.feedme.models
import androidx.lifecycle.MutableLiveData
class NonNullMutableLiveData<T: Any>(initValue: T): MutableLiveData<T>() {
init {
value = initValue
}
override fun getValue(): T = super.getValue() as T
override fun setValue(value: T) = super.setValue(value)
override fun postValue(value: T) = super.postValue(value)
} | kotlin | 10 | 0.732456 | 79 | 29.466667 | 15 | starcoderdata |
<filename>kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/fns.kt
package io.kotest.property.arbitrary
import io.kotest.property.Arb
import io.kotest.property.RandomSource
/**
* Returns an [Arb] where each value is generated from the given function.
*/
fun <A> Arb.Companion.create(edgeCases: List<A>, fn: (RandomSource) -> A): Arb<A> = arb(edgeCases) { rs ->
sequence {
while (true) {
yield(fn(rs))
}
}
}
fun <A> Arb.Companion.create(fn: (RandomSource) -> A): Arb<A> = arb { rs ->
sequence {
while (true) {
yield(fn(rs))
}
}
}
| kotlin | 24 | 0.635914 | 106 | 22.346154 | 26 | starcoderdata |
/*
* Copyright 2018-2019 OAAT's author : <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package com.oaat.services
import org.commonmark.ext.autolink.AutolinkExtension
import org.commonmark.parser.Parser
import org.commonmark.renderer.html.HtmlRenderer
import org.springframework.stereotype.Service
@Service
class MarkdownConverter : (String?) -> String {
private val parser = Parser.builder().extensions(listOf(AutolinkExtension.create())).build()
private val renderer = HtmlRenderer.builder().build()
override fun invoke(input: String?): String {
if (input == null || input == "") {
return ""
}
return renderer.render(parser.parse(input))
}
}
| kotlin | 17 | 0.70274 | 109 | 29.416667 | 24 | starcoderdata |
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.psi2ir.generators
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
open class GeneratorExtensions {
open val externalDeclarationOrigin: ((DeclarationDescriptor) -> IrDeclarationOrigin)?
get() = null
open val samConversion: SamConversion
get() = SamConversion
open class SamConversion {
// Returns null if descriptor is not a SAM adapter
open fun getOriginalForSamAdapter(descriptor: CallableDescriptor): CallableDescriptor? = null
open fun isSamConstructor(descriptor: CallableDescriptor): Boolean = false
open fun isSamType(type: KotlinType): Boolean = false
open fun getSubstitutedFunctionTypeForSamType(samType: KotlinType): KotlinType =
throw UnsupportedOperationException("SAM conversion is not supported in this configuration (samType=$samType)")
companion object Instance : SamConversion()
}
}
| kotlin | 13 | 0.770745 | 123 | 39.628571 | 35 | starcoderdata |
<reponame>enlh/WanAndroid
package com.cxz.wanandroid.ui.fragment
import android.app.DatePickerDialog
import android.os.Bundle
import android.view.View
import com.cxz.wanandroid.R
import com.cxz.wanandroid.base.BaseMvpFragment
import com.cxz.wanandroid.constant.Constant
import com.cxz.wanandroid.event.RefreshTodoEvent
import com.cxz.wanandroid.ext.formatCurrentDate
import com.cxz.wanandroid.ext.showToast
import com.cxz.wanandroid.ext.stringToCalendar
import com.cxz.wanandroid.mvp.contract.AddTodoContract
import com.cxz.wanandroid.mvp.model.bean.TodoBean
import com.cxz.wanandroid.mvp.presenter.AddTodoPresenter
import com.cxz.wanandroid.utils.DialogUtil
import kotlinx.android.synthetic.main.fragment_add_todo.*
import org.greenrobot.eventbus.EventBus
import java.util.*
/**
* Created by chenxz on 2018/8/11.
*/
class AddTodoFragment : BaseMvpFragment<AddTodoContract.View, AddTodoContract.Presenter>(),
AddTodoContract.View {
companion object {
fun getInstance(bundle: Bundle): AddTodoFragment {
val fragment = AddTodoFragment()
fragment.arguments = bundle
return fragment
}
}
override fun createPresenter(): AddTodoContract.Presenter = AddTodoPresenter()
/**
* Date
*/
private var mCurrentDate = formatCurrentDate()
/**
* 类型
*/
private var mType: Int = 0
private var mTodoBean: TodoBean? = null
/**
* 新增,编辑,查看 三种状态
*/
private var mTypeKey = ""
/**
* id
*/
private var mId: Int? = 0
/**
* 优先级 重要(1),一般(0)
*/
private var mPriority = 0
private val mDialog by lazy {
DialogUtil.getWaitDialog(activity!!, getString(R.string.save_ing))
}
override fun showLoading() {
mDialog.show()
}
override fun hideLoading() {
mDialog.dismiss()
}
override fun attachLayoutRes(): Int = R.layout.fragment_add_todo
override fun getType(): Int = mType
override fun getCurrentDate(): String = tv_date.text.toString()
override fun getTitle(): String = et_title.text.toString()
override fun getContent(): String = et_content.text.toString()
override fun getStatus(): Int = mTodoBean?.status ?: 0
override fun getItemId(): Int = mTodoBean?.id ?: 0
override fun getPriority(): String = mPriority.toString()
override fun initView(view: View) {
super.initView(view)
mType = arguments?.getInt(Constant.TODO_TYPE) ?: 0
mTypeKey = arguments?.getString(Constant.TYPE_KEY) ?: Constant.Type.ADD_TODO_TYPE_KEY
when (mTypeKey) {
Constant.Type.ADD_TODO_TYPE_KEY -> {
tv_date.text = formatCurrentDate()
}
Constant.Type.EDIT_TODO_TYPE_KEY -> {
mTodoBean = arguments?.getSerializable(Constant.TODO_BEAN) as TodoBean ?: null
et_title.setText(mTodoBean?.title)
et_content.setText(mTodoBean?.content)
tv_date.text = mTodoBean?.dateStr
mPriority = mTodoBean?.priority ?: 0
if (mTodoBean?.priority == 0) {
rb0.isChecked = true
rb1.isChecked = false
} else if (mTodoBean?.priority == 1) {
rb0.isChecked = false
rb1.isChecked = true
}
}
Constant.Type.SEE_TODO_TYPE_KEY -> {
mTodoBean = arguments?.getSerializable(Constant.TODO_BEAN) as TodoBean ?: null
et_title.setText(mTodoBean?.title)
et_content.setText(mTodoBean?.content)
tv_date.text = mTodoBean?.dateStr
et_title.isEnabled = false
et_content.isEnabled = false
ll_date.isEnabled = false
btn_save.visibility = View.GONE
iv_arrow_right.visibility = View.GONE
ll_priority.isEnabled = false
if (mTodoBean?.priority == 0) {
rb0.isChecked = true
rb1.isChecked = false
rb1.visibility = View.GONE
} else if (mTodoBean?.priority == 1) {
rb0.isChecked = false
rb1.isChecked = true
rb0.visibility = View.GONE
} else {
ll_priority.visibility = View.GONE
}
}
}
ll_date.setOnClickListener {
var now = Calendar.getInstance()
if (mTypeKey == Constant.Type.EDIT_TODO_TYPE_KEY) {
mTodoBean?.dateStr?.let {
now = it.stringToCalendar()
}
}
val dpd = android.app.DatePickerDialog(
activity,
DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
mCurrentDate = "$year-${month + 1}-$dayOfMonth"
tv_date.text = mCurrentDate
},
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
)
dpd.show()
}
btn_save.setOnClickListener {
when (mTypeKey) {
Constant.Type.ADD_TODO_TYPE_KEY -> {
mPresenter?.addTodo()
}
Constant.Type.EDIT_TODO_TYPE_KEY -> {
mPresenter?.updateTodo(getItemId())
}
}
}
rg_priority.setOnCheckedChangeListener { group, checkedId ->
if (checkedId == R.id.rb0) {
mPriority = 0
rb0.isChecked = true
rb1.isChecked = false
} else if (checkedId == R.id.rb1) {
mPriority = 1
rb0.isChecked = false
rb1.isChecked = true
}
}
}
override fun lazyLoad() {
}
override fun showAddTodo(success: Boolean) {
if (success) {
showToast(getString(R.string.save_success))
EventBus.getDefault().post(RefreshTodoEvent(true, mType))
activity?.finish()
}
}
override fun showUpdateTodo(success: Boolean) {
if (success) {
showToast(getString(R.string.save_success))
EventBus.getDefault().post(RefreshTodoEvent(true, mType))
activity?.finish()
}
}
} | kotlin | 28 | 0.561112 | 94 | 31.2 | 200 | starcoderdata |
/*
* Copyright 2020 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.platform
import androidx.compose.runtime.Composable
import androidx.compose.ui.ComposeScene
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.InternalComposeUiApi
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.mouse.MouseScrollEvent
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.node.RootForTest
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import org.jetbrains.skia.Surface
import org.jetbrains.skiko.FrameDispatcher
import java.awt.Component
import kotlin.coroutines.CoroutineContext
/**
* A virtual window for testing purposes.
*
* After [setContent] it composes content immediately and draws it on a virtual [surface].
*
* It doesn't dispatch frames by default. If frame dispatching is needed, pass appropriate
* dispatcher as coroutineContext (for example, Dispatchers.Swing)
*/
@OptIn(ExperimentalComposeUiApi::class)
class TestComposeWindow(
val width: Int,
val height: Int,
val density: Density = Density(1f, 1f),
private val nanoTime: () -> Long = System::nanoTime,
coroutineContext: CoroutineContext = EmptyDispatcher
) {
/**
* Virtual surface on which the content will be drawn
*/
val surface = Surface.makeRasterN32Premul(width, height)
private val canvas = surface.canvas
private val coroutineScope = CoroutineScope(coroutineContext + Job())
private val frameDispatcher: FrameDispatcher = FrameDispatcher(
onFrame = { onFrame() },
context = coroutineScope.coroutineContext
)
private fun onFrame() {
canvas.clear(Color.Transparent.toArgb())
scene.render(canvas, nanoTime())
}
private val scene = ComposeScene(
coroutineScope.coroutineContext,
density,
invalidate = frameDispatcher::scheduleFrame
).apply {
constraints = Constraints(maxWidth = width, maxHeight = height)
}
/**
* All currently registered [RootForTest]s
*/
@OptIn(InternalComposeUiApi::class)
val roots: Set<RootForTest> get() = scene.roots
/**
* Clear-up all acquired resources and stop all pending work
*/
fun dispose() {
scene.dispose()
coroutineScope.cancel()
}
/**
* Returns true if there are pending work scheduled by this window
*/
fun hasInvalidations(): Boolean = scene.hasInvalidations()
/**
* Compose [content] immediately and draw it on a [surface]
*/
fun setContent(content: @Composable () -> Unit) {
scene.constraints = Constraints(maxWidth = width, maxHeight = height)
scene.setContent(content = content)
scene.render(canvas, nanoTime = nanoTime())
}
fun render() {
scene.render(canvas, nanoTime = nanoTime())
}
/**
* Process mouse scroll event
*/
@OptIn(ExperimentalComposeUiApi::class)
fun onMouseScroll(x: Int, y: Int, event: MouseScrollEvent) {
scene.sendPointerScrollEvent(
position = Offset(x.toFloat(), y.toFloat()),
delta = event.delta,
orientation = event.orientation
)
}
/**
* Process mouse move event
*/
fun onMouseMoved(x: Int, y: Int) {
scene.sendPointerEvent(
eventType = PointerEventType.Move,
position = Offset(x.toFloat(), y.toFloat())
)
}
/**
* Process mouse enter event
*/
fun onMouseEntered(x: Int, y: Int) {
scene.sendPointerEvent(
eventType = PointerEventType.Enter,
position = Offset(x.toFloat(), y.toFloat())
)
}
/**
* Process mouse exit event
*/
fun onMouseExited() {
scene.sendPointerEvent(
eventType = PointerEventType.Exit,
position = Offset(-1f, -1f)
)
}
companion object {
private val EventComponent = object : Component() {}
}
} | kotlin | 17 | 0.678817 | 90 | 29.392405 | 158 | starcoderdata |
<reponame>Red350/alarm-app<filename>app/src/main/java/red/padraig/alarmapp/alarm/AlarmBroadcastReceiver.kt
package red.padraig.alarmapp.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.PowerManager
import android.util.Log
import red.padraig.alarmapp.ui.activities.AlarmRingingActivity
import java.text.DateFormat
import java.util.*
class AlarmBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// Acquire a wake lock to allow the alarm to wake the phone
val powerManager = context?.getSystemService(Context.POWER_SERVICE) as PowerManager
val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "AlarmWakelock")
wakeLock.acquire(5000)
Log.d("AlarmBroadcastReceiver", "Received broadcast at ${DateFormat.getDateTimeInstance().format(Date())}")
val newIntent = Intent(context, AlarmRingingActivity::class.java)
context.startActivity(newIntent)
wakeLock.release()
}
} | kotlin | 25 | 0.771149 | 134 | 40.62963 | 27 | starcoderdata |
<reponame>cyberquarks/xodus
/**
* Copyright 2010 - 2020 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.gc
import jetbrains.exodus.bindings.StringBinding
import jetbrains.exodus.env.EnvironmentTestsBase
import jetbrains.exodus.env.StoreConfig
import org.junit.Assert
import org.junit.Test
open class GarbageCollectorInterleavingTest : EnvironmentTestsBase() {
protected open val storeConfig: StoreConfig
get() = StoreConfig.WITHOUT_DUPLICATES
protected open val recordsNumber: Int
get() = 37
@Test
@Throws(InterruptedException::class)
fun testSimple() {
set1KbFileWithoutGC()
val log = env.log
val fileSize = log.fileLengthBound
fill("updateSameKey")
Assert.assertEquals(1L, log.numberOfFiles)
fill("updateSameKey")
Assert.assertEquals(2L, log.numberOfFiles) // but ends in second one
fill("another")
Assert.assertEquals(3L, log.numberOfFiles) // make cleaning of second file possible
env.gc.doCleanFile(fileSize) // clean second file
Thread.sleep(300)
env.gc.testDeletePendingFiles()
Assert.assertEquals(3L, log.numberOfFiles) // half of tree written out from second file
env.gc.doCleanFile(0) // clean first file
Thread.sleep(300)
env.gc.testDeletePendingFiles()
Assert.assertEquals(2L, log.numberOfFiles) // first file contained only garbage
check("updateSameKey")
check("another")
}
private fun fill(table: String) {
val val0 = StringBinding.stringToEntry("val0")
env.executeInTransaction { txn ->
val store = env.openStore(table, storeConfig, txn)
for (i in 0 until recordsNumber) {
val key = StringBinding.stringToEntry("key $i")
store.put(txn, key, val0)
}
}
}
private fun check(table: String) {
val val0 = StringBinding.stringToEntry("val0")
env.executeInReadonlyTransaction { txn ->
val store = env.openStore(table, storeConfig, txn)
for (i in 0 until recordsNumber) {
val key = StringBinding.stringToEntry("key $i")
Assert.assertTrue(store.exists(txn, key, val0))
}
}
}
}
| kotlin | 22 | 0.663036 | 95 | 30.622222 | 90 | starcoderdata |
<filename>collect_app/src/main/java/org/odk/collect/android/external/FormUriActivity.kt
package org.odk.collect.android.external
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import org.odk.collect.analytics.Analytics
import org.odk.collect.android.R
import org.odk.collect.android.activities.FormEntryActivity
import org.odk.collect.android.analytics.AnalyticsEvents
import org.odk.collect.android.injection.DaggerUtils
import org.odk.collect.android.projects.CurrentProjectProvider
import org.odk.collect.android.utilities.ApplicationConstants
import org.odk.collect.projects.ProjectsRepository
import javax.inject.Inject
class FormUriActivity : Activity() {
@Inject
lateinit var currentProjectProvider: CurrentProjectProvider
@Inject
lateinit var projectsRepository: ProjectsRepository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerUtils.getComponent(this).inject(this)
val firstProject = projectsRepository.getAll().first()
val uri = intent.data
val uriProjectId = uri?.getQueryParameter("projectId")
val projectId = uriProjectId ?: firstProject.uuid
logAnalytics(uriProjectId)
if (projectId == currentProjectProvider.getCurrentProject().uuid) {
startActivity(
Intent(this, FormEntryActivity::class.java).also {
it.data = uri
intent.extras?.let { sourceExtras -> it.putExtras(sourceExtras) }
}
)
} else {
AlertDialog.Builder(this)
.setMessage(R.string.wrong_project_selected_for_form)
.setPositiveButton(R.string.ok) { _, _ -> finish() }
.create()
.show()
}
}
private fun logAnalytics(uriProjectId: String?) {
if (uriProjectId != null) {
Analytics.log(AnalyticsEvents.FORM_ACTION_WITH_PROJECT_ID)
} else {
Analytics.log(AnalyticsEvents.FORM_ACTION_WITHOUT_PROJECT_ID)
}
if (intent.getStringExtra(ApplicationConstants.BundleKeys.FORM_MODE) != null) {
Analytics.log(AnalyticsEvents.FORM_ACTION_WITH_FORM_MODE_EXTRA)
}
}
}
| kotlin | 27 | 0.68548 | 87 | 35.265625 | 64 | starcoderdata |
package com.chrynan.sitetheme.templates
import kotlinx.html.TagConsumer
interface Template<VM> {
fun <T> TagConsumer<T>.layout(viewModel: VM): T
} | kotlin | 8 | 0.75817 | 51 | 18.25 | 8 | starcoderdata |
<gh_stars>0
package id.yanuar.weather.util
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.RecordedRequest
import okio.Okio
import java.io.IOException
import java.nio.charset.StandardCharsets
/**
* Created by <NAME>
* <EMAIL>
*/
class ServerDispatcher : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse? {
val path: String
path = if (request.method == "GET") {
val queryIndex = request.path.lastIndexOf("?")
request.path.substring(0, queryIndex)
} else {
request.path
}
val inputStream = javaClass.classLoader
.getResourceAsStream("api/$path")
val source = Okio.buffer(Okio.source(inputStream))
var response: MockResponse? = null
try {
response = MockResponse().setBody(source.readString(StandardCharsets.UTF_8))
} catch (io: IOException) {
io.printStackTrace()
}
return response
}
} | kotlin | 19 | 0.646445 | 88 | 26.076923 | 39 | starcoderdata |
<reponame>vimalpsojan/MyNote<filename>Home/src/androidMain/kotlin/com/vimal/home/ui/HomeScreen.kt
package com.vimal.home.ui
import android.content.res.Configuration
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.systemBarsPadding
import com.vimal.home.R
import com.vimal.uiutils.ui.theme.MyNoteTheme
import com.vimal.uiutils.ui.utils.InsetAwareTopAppBar
import com.vimal.uiutils.ui.utils.isScrolled
@Composable
fun HomeScreen(
viewModel: AndroidHomeViewModel,
scaffoldState: ScaffoldState = rememberScaffoldState()
) {
val notes by viewModel.notes.collectAsState()
HomeScreen(
notes = notes,
onSelectNote = viewModel.onSelectNote,
scaffoldState = scaffoldState
)
}
@Composable
fun HomeScreen(
notes: List<HomeViewModel.Note>?,
onSelectNote: (HomeViewModel.Note) -> Unit,
scaffoldState: ScaffoldState
) {
val scrollState = rememberLazyListState()
Scaffold(
scaffoldState = scaffoldState,
snackbarHost = { SnackbarHost(hostState = it, modifier = Modifier.systemBarsPadding()) },
topBar = {
val title = stringResource(id = R.string.app_name)
InsetAwareTopAppBar(
title = {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxSize()
.padding(bottom = 4.dp, top = 10.dp)
) {
Icon(
painter = painterResource(R.drawable.ic_notes),
contentDescription = title,
tint = MaterialTheme.colors.onBackground,
modifier = Modifier
)
Text(
text = title,
textAlign = TextAlign.Center,
modifier = Modifier
)
}
},
elevation = if (!scrollState.isScrolled) 0.dp else 4.dp
)
}
) { innerPadding ->
val modifier = Modifier.padding(innerPadding)
notes?.let { notes ->
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
modifier = modifier.fillMaxSize()
) {
items(items = notes, itemContent = { note ->
NoteItem(note = note, Modifier.clickable {
onSelectNote(note)
})
})
}
}
}
}
@Composable
fun NoteItem(note: HomeViewModel.Note, modifier: Modifier = Modifier) {
Card(
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 8.dp)
.fillMaxWidth(),
elevation = 2.dp,
shape = RoundedCornerShape(corner = CornerSize(16.dp))
) {
Column(
modifier = modifier
.padding(16.dp)
.fillMaxWidth()
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
Text(text = note.heading ?: "", style = MaterialTheme.typography.h6)
Text(text = note.lastEditedOn ?: "", style = MaterialTheme.typography.overline)
}
Text(
text = note.description ?: "",
style = MaterialTheme.typography.caption,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
}
}
@Preview("Home Screen")
@Preview("Home Screen (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Preview("Home Screen (big font)", fontScale = 1.5f)
@Preview("Home Screen (large screen)", device = Devices.PIXEL_C)
@Composable
fun PreviewSplashScreen() {
MyNoteTheme {
val notes = listOf(
HomeViewModel.Note(
heading = "Note 1",
description = "description 1",
lastEditedOn = "Yesterday 12:55 PM"
),
HomeViewModel.Note(
heading = "Note 2",
description = "description 2",
lastEditedOn = "Today 1:03 AM"
),
HomeViewModel.Note(
heading = "Note 3",
description = "description 3",
lastEditedOn = "1 Hour Ago"
)
)
HomeScreen(notes = notes, onSelectNote = {}, scaffoldState = rememberScaffoldState())
}
} | kotlin | 38 | 0.582707 | 97 | 34.814103 | 156 | starcoderdata |
package eu.kanade.tachiyomi.ui.reader
import android.os.Build
import android.os.Bundle
import android.widget.CompoundButton
import android.widget.Spinner
import androidx.annotation.ArrayRes
import androidx.core.widget.NestedScrollView
import com.f2prateek.rx.preferences.Preference as RxPreference
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.tfcporciuncula.flow.Preference
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.ui.reader.viewer.pager.PagerViewer
import eu.kanade.tachiyomi.ui.reader.viewer.webtoon.WebtoonViewer
import eu.kanade.tachiyomi.util.view.invisible
import eu.kanade.tachiyomi.util.view.visible
import eu.kanade.tachiyomi.widget.IgnoreFirstSpinnerListener
import kotlinx.android.synthetic.main.reader_settings_sheet.always_show_chapter_transition
import kotlinx.android.synthetic.main.reader_settings_sheet.background_color
import kotlinx.android.synthetic.main.reader_settings_sheet.crop_borders
import kotlinx.android.synthetic.main.reader_settings_sheet.crop_borders_webtoon
import kotlinx.android.synthetic.main.reader_settings_sheet.cutout_short
import kotlinx.android.synthetic.main.reader_settings_sheet.fullscreen
import kotlinx.android.synthetic.main.reader_settings_sheet.keepscreen
import kotlinx.android.synthetic.main.reader_settings_sheet.long_tap
import kotlinx.android.synthetic.main.reader_settings_sheet.page_transitions
import kotlinx.android.synthetic.main.reader_settings_sheet.pager_prefs_group
import kotlinx.android.synthetic.main.reader_settings_sheet.rotation_mode
import kotlinx.android.synthetic.main.reader_settings_sheet.scale_type
import kotlinx.android.synthetic.main.reader_settings_sheet.show_page_number
import kotlinx.android.synthetic.main.reader_settings_sheet.viewer
import kotlinx.android.synthetic.main.reader_settings_sheet.webtoon_prefs_group
import kotlinx.android.synthetic.main.reader_settings_sheet.webtoon_side_padding
import kotlinx.android.synthetic.main.reader_settings_sheet.zoom_start
import uy.kohesive.injekt.injectLazy
/**
* Sheet to show reader and viewer preferences.
*/
class ReaderSettingsSheet(private val activity: ReaderActivity) : BottomSheetDialog(activity) {
private val preferences by injectLazy<PreferencesHelper>()
init {
// Use activity theme for this layout
val view = activity.layoutInflater.inflate(R.layout.reader_settings_sheet, null)
val scroll = NestedScrollView(activity)
scroll.addView(view)
setContentView(scroll)
}
/**
* Called when the sheet is created. It initializes the listeners and values of the preferences.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initGeneralPreferences()
when (activity.viewer) {
is PagerViewer -> initPagerPreferences()
is WebtoonViewer -> initWebtoonPreferences()
}
}
/**
* Init general reader preferences.
*/
private fun initGeneralPreferences() {
viewer.onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
activity.presenter.setMangaViewer(position)
val mangaViewer = activity.presenter.getMangaViewer()
if (mangaViewer == ReaderActivity.WEBTOON || mangaViewer == ReaderActivity.VERTICAL_PLUS) {
initWebtoonPreferences()
} else {
initPagerPreferences()
}
}
viewer.setSelection(activity.presenter.manga?.viewer ?: 0, false)
rotation_mode.bindToPreference(preferences.rotation(), 1)
background_color.bindToPreference(preferences.readerTheme())
show_page_number.bindToPreference(preferences.showPageNumber())
fullscreen.bindToPreference(preferences.fullscreen())
val hasDisplayCutout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
activity.window?.decorView?.rootWindowInsets?.displayCutout != null
if (hasDisplayCutout) {
cutout_short.visible()
cutout_short.bindToPreference(preferences.cutoutShort())
}
keepscreen.bindToPreference(preferences.keepScreenOn())
long_tap.bindToPreference(preferences.readWithLongTap())
always_show_chapter_transition.bindToPreference(preferences.alwaysShowChapterTransition())
}
/**
* Init the preferences for the pager reader.
*/
private fun initPagerPreferences() {
webtoon_prefs_group.invisible()
pager_prefs_group.visible()
scale_type.bindToPreference(preferences.imageScaleType(), 1)
zoom_start.bindToPreference(preferences.zoomStart(), 1)
crop_borders.bindToPreference(preferences.cropBorders())
page_transitions.bindToPreference(preferences.pageTransitions())
}
/**
* Init the preferences for the webtoon reader.
*/
private fun initWebtoonPreferences() {
pager_prefs_group.invisible()
webtoon_prefs_group.visible()
crop_borders_webtoon.bindToPreference(preferences.cropBordersWebtoon())
webtoon_side_padding.bindToIntPreference(preferences.webtoonSidePadding(), R.array.webtoon_side_padding_values)
}
/**
* Binds a checkbox or switch view with a boolean preference.
*/
private fun CompoundButton.bindToPreference(pref: Preference<Boolean>) {
isChecked = pref.get()
setOnCheckedChangeListener { _, isChecked -> pref.set(isChecked) }
}
/**
* Binds a spinner to an int preference with an optional offset for the value.
*/
private fun Spinner.bindToPreference(pref: RxPreference<Int>, offset: Int = 0) {
onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
pref.set(position + offset)
}
setSelection(pref.getOrDefault() - offset, false)
}
/**
* Binds a spinner to an int preference with an optional offset for the value.
*/
private fun Spinner.bindToPreference(pref: Preference<Int>, offset: Int = 0) {
onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
pref.set(position + offset)
}
setSelection(pref.get() - offset, false)
}
/**
* Binds a spinner to an int preference. The position of the spinner item must
* correlate with the [intValues] resource item (in arrays.xml), which is a <string-array>
* of int values that will be parsed here and applied to the preference.
*/
private fun Spinner.bindToIntPreference(pref: Preference<Int>, @ArrayRes intValuesResource: Int) {
val intValues = resources.getStringArray(intValuesResource).map { it.toIntOrNull() }
onItemSelectedListener = IgnoreFirstSpinnerListener { position ->
pref.set(intValues[position]!!)
}
setSelection(intValues.indexOf(pref.get()), false)
}
}
| kotlin | 19 | 0.730147 | 119 | 41.357576 | 165 | starcoderdata |
<reponame>Namnodorel/data2viz
/*
* Copyright (c) 2018-2019. data2viz sàrl.
*
* 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.data2viz.color
import io.data2viz.math.*
import kotlin.math.*
/**
* Conversion references values
*/
internal const val Kn = 18f
internal const val Xn = 0.950470f // D65 standard referent
internal const val Yn = 1f
internal const val Zn = 1.088830f
internal const val t0 = 4f / 29f
internal const val t1 = 6f / 29f
internal const val t2 = 3f * t1 * t1
internal const val t3 = t1 * t1 * t1
internal const val deg60toRad = 1.047198
internal const val deg240toRad = 4.18879
internal val angle120deg = 120.deg
internal fun RgbColor.toLaba(): LabColor {
val labB = rgb2xyz(r)
val labA = rgb2xyz(g)
val labL = rgb2xyz(b)
val x = xyz2lab((0.4124564f * labB + 0.3575761f * labA + 0.1804375f * labL) / Xn)
val y = xyz2lab((0.2126729f * labB + 0.7151522f * labA + 0.0721750f * labL) / Yn)
val z = xyz2lab((0.0193339f * labB + 0.1191920f * labA + 0.9503041f * labL) / Zn)
return Colors.lab((116.0 * y - 16).pct, 500.0 * (x - y), 200.0 * (y - z), alpha)
}
internal fun RgbColor.toHsla(): HslColor {
val rPercent = r / 255.0
val gPercent = g / 255.0
val bPercent = b / 255.0
val minPercent = minOf(rPercent, gPercent, bPercent)
val maxPercent = maxOf(rPercent, gPercent, bPercent)
var h = .0
var s = maxPercent - minPercent
val l = (maxPercent + minPercent) / 2f
if (s != .0) {
h = when {
(rPercent == maxPercent) -> if (gPercent < bPercent) ((gPercent - bPercent) / s) + 6f else ((gPercent - bPercent) / s)
(gPercent == maxPercent) -> (bPercent - rPercent) / s + 2f
else -> (rPercent - gPercent) / s + 4f
}
s /= if (l < 0.5f) maxPercent + minPercent else 2 - maxPercent - minPercent
h *= 60.0
} else {
s = if (l > 0 && l < 1) .0 else h
}
return Colors.hsl(h.deg, Percent(s), Percent(l), alpha)
}
internal fun LabColor.toRgba(): RgbColor {
// map CIE LAB to CIE XYZ
var y = ((labL.value * 100.0) + 16) / 116f
var x = y + (labA / 500f)
var z = y - (labB / 200f)
y = Yn * lab2xyz(y)
x = Xn * lab2xyz(x)
z = Zn * lab2xyz(z)
// map CIE XYZ to RGB
return Colors.rgb(
xyz2rgb(3.2404542f * x - 1.5371385f * y - 0.4985314f * z),
xyz2rgb(-0.9692660f * x + 1.8760108f * y + 0.0415560f * z),
xyz2rgb(0.0556434f * x - 0.2040259f * y + 1.0572252f * z),
alpha
)
}
// TODO : use rad (faster)
internal fun HslColor.toRgba(): RgbColor =
if (isAchromatic()) // achromatic
Colors.rgb(
(l.value * 255).roundToInt(),
(l.value * 255).roundToInt(),
(l.value * 255).roundToInt(),
alpha
)
else {
val q = if (l < 50.pct) l * (100.pct + s) else l + s - l * s
val p = Percent(2 * l.value - q.value)
Colors.rgb(
(hue2rgb(p.value, q.value, h + angle120deg) * 255).roundToInt(),
(hue2rgb(p.value, q.value, h) * 255).roundToInt(),
(hue2rgb(p.value, q.value, h - angle120deg) * 255).roundToInt(),
alpha
)
}
internal fun HclColor.toLaba() = Colors.lab(l, (h.cos * c), (h.sin * c), alpha)
internal fun LabColor.toHcla(): HclColor {
val hue = Angle(atan2(labB, labA)).normalize()
val c = sqrt(labA * labA + labB * labB)
return Colors.hcl(hue, c, labL, alpha)
}
// TODO use rad (faster)
private fun hue2rgb(p: Double, q: Double, hue: Angle): Double {
val hd = hue.normalize()
return when {
hd.rad < deg60toRad -> (p + (q - p) * (hd.rad / deg60toRad))
hd.rad < kotlin.math.PI -> q
hd.rad < deg240toRad -> (p + (q - p) * ((deg240toRad - hd.rad) / deg60toRad))
else -> p
}
}
internal fun RgbColor.toLuminance(): Percent {
fun Int.chan2Lumi(): Double {
val x = this / 255.0
return if (x <= 0.03928) x / 12.92
else ((x+0.055)/1.055).pow(2.4)
}
return Percent(0.2126 * r.chan2Lumi() + 0.7152 * g.chan2Lumi() + 0.0722 * b.chan2Lumi()).coerceToDefault()
}
private fun xyz2lab(value: Float): Float =
if (value > t3)
value.pow(1 / 3f)
else
(value / t2 + t0)
private fun rgb2xyz(value: Int): Float {
val percent = value.toFloat() / 255f
return if (percent <= 0.04045f) (percent / 12.92f) else ((percent + 0.055f) / 1.055f).pow(2.4f)
}
private fun lab2xyz(value: Double): Double =
if (value > t1)
(value * value * value)
else
(t2 * (value - t0))
private fun xyz2rgb(value: Double): Int =
if (value <= 0.0031308f)
round(12.92f * value * 255).toInt()
else
round(255 * (1.055 * value.pow(1 / 2.4) - 0.055)).toInt()
| kotlin | 21 | 0.587936 | 130 | 30.766467 | 167 | starcoderdata |
<filename>app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuApi.kt<gh_stars>0
package eu.kanade.tachiyomi.data.track.kitsu
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import eu.kanade.tachiyomi.network.POST
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
import okhttp3.FormBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Headers
import retrofit2.http.PATCH
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
class KitsuApi(private val client: OkHttpClient, interceptor: KitsuInterceptor) {
private val authClient = client.newBuilder().addInterceptor(interceptor).build()
private val rest = Retrofit.Builder()
.baseUrl(baseUrl)
.client(authClient)
.addConverterFactory(jsonConverter)
.build()
.create(Rest::class.java)
private val searchRest = Retrofit.Builder()
.baseUrl(algoliaKeyUrl)
.client(authClient)
.addConverterFactory(jsonConverter)
.build()
.create(SearchKeyRest::class.java)
private val algoliaRest = Retrofit.Builder()
.baseUrl(algoliaUrl)
.client(client)
.addConverterFactory(jsonConverter)
.build()
.create(AgoliaSearchRest::class.java)
suspend fun addLibManga(track: Track, userId: String): Track {
val data = buildJsonObject {
putJsonObject("data") {
put("type", "libraryEntries")
putJsonObject("attributes") {
put("status", track.toKitsuStatus())
put("progress", track.last_chapter_read)
}
putJsonObject("relationships") {
putJsonObject("user") {
putJsonObject("data") {
put("id", userId)
put("type", "users")
}
}
putJsonObject("media") {
putJsonObject("data") {
put("id", track.media_id)
put("type", "manga")
}
}
}
}
}
val json = rest.addLibManga(data)
track.media_id = json["data"]!!.jsonObject["id"]!!.jsonPrimitive.int
return track
}
suspend fun updateLibManga(track: Track): Track {
val data = buildJsonObject {
putJsonObject("data") {
put("type", "libraryEntries")
put("id", track.media_id)
putJsonObject("attributes") {
put("status", track.toKitsuStatus())
put("progress", track.last_chapter_read)
put("ratingTwenty", track.toKitsuScore())
}
}
}
rest.updateLibManga(track.media_id, data)
return track
}
suspend fun search(query: String): List<TrackSearch> {
val json = searchRest.getKey()
val key = json["media"]!!.jsonObject["key"]!!.jsonPrimitive.content
return algoliaSearch(key, query)
}
private suspend fun algoliaSearch(key: String, query: String): List<TrackSearch> {
val jsonObject = buildJsonObject {
put("params", "query=$query$algoliaFilter")
}
val json = algoliaRest.getSearchQuery(algoliaAppId, key, jsonObject)
val data = json["hits"]!!.jsonArray
return data.map { KitsuSearchManga(it.jsonObject) }
.filter { it.subType != "novel" }
.map { it.toTrack() }
}
suspend fun findLibManga(track: Track, userId: String): Track? {
val json = rest.findLibManga(track.media_id, userId)
val data = json["data"]!!.jsonArray
return if (data.size > 0) {
val manga = json["included"]!!.jsonArray[0].jsonObject
KitsuLibManga(data[0].jsonObject, manga).toTrack()
} else {
null
}
}
suspend fun getLibManga(track: Track): Track {
val json = rest.getLibManga(track.media_id)
val data = json["data"]!!.jsonArray
return if (data.size > 0) {
val manga = json["included"]!!.jsonArray[0].jsonObject
KitsuLibManga(data[0].jsonObject, manga).toTrack()
} else {
throw Exception("Could not find manga")
}
}
suspend fun login(username: String, password: String): OAuth {
return Retrofit.Builder()
.baseUrl(loginUrl)
.client(client)
.addConverterFactory(jsonConverter)
.build()
.create(LoginRest::class.java)
.requestAccessToken(username, password)
}
suspend fun getCurrentUser(): String {
return rest.getCurrentUser()["data"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content
}
private interface Rest {
@Headers("Content-Type: application/vnd.api+json")
@POST("library-entries")
suspend fun addLibManga(
@Body data: JsonObject
): JsonObject
@Headers("Content-Type: application/vnd.api+json")
@PATCH("library-entries/{id}")
suspend fun updateLibManga(
@Path("id") remoteId: Int,
@Body data: JsonObject
): JsonObject
@GET("library-entries")
suspend fun findLibManga(
@Query("filter[manga_id]", encoded = true) remoteId: Int,
@Query("filter[user_id]", encoded = true) userId: String,
@Query("include") includes: String = "manga"
): JsonObject
@GET("library-entries")
suspend fun getLibManga(
@Query("filter[id]", encoded = true) remoteId: Int,
@Query("include") includes: String = "manga"
): JsonObject
@GET("users")
suspend fun getCurrentUser(
@Query("filter[self]", encoded = true) self: Boolean = true
): JsonObject
}
private interface SearchKeyRest {
@GET("media/")
suspend fun getKey(): JsonObject
}
private interface AgoliaSearchRest {
@POST("query/")
suspend fun getSearchQuery(@Header("X-Algolia-Application-Id") appid: String, @Header("X-Algolia-API-Key") key: String, @Body json: JsonObject): JsonObject
}
private interface LoginRest {
@FormUrlEncoded
@POST("oauth/token")
suspend fun requestAccessToken(
@Field("username") username: String,
@Field("password") password: String,
@Field("grant_type") grantType: String = "password",
@Field("client_id") client_id: String = clientId,
@Field("client_secret") client_secret: String = clientSecret
): OAuth
}
companion object {
private const val clientId = "dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd"
private const val clientSecret = "54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151"
private const val baseUrl = "https://kitsu.io/api/edge/"
private const val loginUrl = "https://kitsu.io/api/"
private const val baseMangaUrl = "https://kitsu.io/manga/"
private const val algoliaKeyUrl = "https://kitsu.io/api/edge/algolia-keys/"
private const val algoliaUrl = "https://AWQO5J657S-dsn.algolia.net/1/indexes/production_media/"
private const val algoliaAppId = "AWQO5J657S"
private const val algoliaFilter = "&facetFilters=%5B%22kind%3Amanga%22%5D&attributesToRetrieve=%5B%22synopsis%22%2C%22canonicalTitle%22%2C%22chapterCount%22%2C%22posterImage%22%2C%22startDate%22%2C%22subtype%22%2C%22endDate%22%2C%20%22id%22%5D"
private val jsonConverter = Json { ignoreUnknownKeys = true }.asConverterFactory("application/json".toMediaType())
fun mangaUrl(remoteId: Int): String {
return baseMangaUrl + remoteId
}
fun refreshTokenRequest(token: String) = POST(
"${loginUrl}oauth/token",
body = FormBody.Builder()
.add("grant_type", "refresh_token")
.add("client_id", clientId)
.add("client_secret", clientSecret)
.add("refresh_token", token)
.build()
)
}
}
| kotlin | 38 | 0.611322 | 252 | 36.236515 | 241 | starcoderdata |
<reponame>Asmewill/JetpackMvvm
package com.example.wapp.demo.viewmodel
import com.example.oapp.base.BaseViewModel
/**
* Created by jsxiaoshui on 2021-11-15
*/
class ToDoViewModel:BaseViewModel() {
} | kotlin | 6 | 0.782178 | 42 | 19.3 | 10 | starcoderdata |
@file:JvmName("TimeSpanHumanizer")
package org.humanizer.jvm
@JvmOverloads
fun Int.milliSecondsToTimeSpan(milliSecondPrecision: Boolean = false): String =
this.toLong().milliSecondsToTimeSpan(milliSecondPrecision)
// Honestly stolen from here http://stackoverflow.com/a/2795991
@JvmOverloads
fun Long.milliSecondsToTimeSpan(milliSecondPrecision: Boolean = false): String {
val buffer = StringBuffer()
val diffInSeconds = this / 1000
val milliseconds = this % 1000
val seconds = if (diffInSeconds >= 60) diffInSeconds % 60 else diffInSeconds
val minutes = if ((diffInSeconds / 60) >= 60) (diffInSeconds / 60) % (60) else diffInSeconds / 60
val hours = if ((diffInSeconds / 3600) >= 24) (diffInSeconds / 3600) % (24) else diffInSeconds / 3600
val days = diffInSeconds / 60 / 60 / 24
if (days > 0) {
with(buffer) {
append("day".toQuantity(days))
append(" and ")
}
}
if (hours > 0 || days > 0) {
with(buffer) {
append("hour".toQuantity(hours))
append(" and ")
}
}
if (minutes > 0 || hours > 0 || days > 0) {
with(buffer) {
append("minute".toQuantity(minutes))
append(" and ")
}
}
buffer.append("second".toQuantity(seconds))
if (milliSecondPrecision) {
with(buffer) {
append(" and ")
append("millisecond".toQuantity(milliseconds))
}
}
return buffer.toString()
} | kotlin | 20 | 0.595661 | 105 | 28.843137 | 51 | starcoderdata |
<gh_stars>0
package nerd.tuxmobil.fahrplan.congress.repositories
interface OnShiftsLoadingDoneCallback {
fun onShiftsLoadingDone(isSuccess: Boolean)
}
| kotlin | 7 | 0.816456 | 52 | 18.75 | 8 | starcoderdata |
/*
* Copyright (c) 2017-2020. Nitrite author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dizitart.kno2
import org.dizitart.kno2.filters.text
import org.dizitart.no2.common.NullOrder
import org.dizitart.no2.common.SortOrder
import org.dizitart.no2.exceptions.UniqueConstraintException
import org.dizitart.no2.index.IndexOptions
import org.dizitart.no2.index.IndexType
import org.dizitart.no2.repository.annotations.Id
import org.dizitart.no2.repository.annotations.Index
import org.dizitart.no2.repository.annotations.Indices
import org.dizitart.no2.repository.annotations.InheritIndices
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
/**
*
* @author <NAME>
*/
class NitriteTest : BaseTest() {
@Before
fun before() {
db = nitrite {
loadModule(mvStore {
path = fileName
})
}
}
@Test
fun testGetCollection() {
db?.getCollection("test") {
assertTrue(isOpen)
close()
assertFalse(isOpen)
}
}
@Test
fun testGetRepository() {
db?.getRepository<TestData> {
assertTrue(isOpen)
close()
assertFalse(isOpen)
}
}
@Test
fun testGetRepositoryWithKey() {
db?.getRepository<TestData>("tag") {
assertTrue(isOpen)
close()
assertFalse(isOpen)
}
}
@Test
fun testIndexOption() {
db?.getCollection("test") {
createIndex("id", option(IndexType.Unique, true))
assertTrue(hasIndex("id"))
assertFalse(hasIndex("name"))
}
}
@Test
fun testFindOption() {
db?.getCollection("test") {
insert(documentOf("a" to 1),
documentOf("a" to 2),
documentOf("a" to 3),
documentOf("a" to 4),
documentOf("a" to 5))
var cursor = find().skipLimit(0, 2)
assertEquals(cursor.size(), 2)
cursor = find().sort("a", SortOrder.Descending, NullOrder.First)
assertEquals(cursor.size(), 5)
assertEquals(cursor.last()["a"], 1)
cursor = find().sort("a", SortOrder.Descending).skipLimit(0, 2)
assertEquals(cursor.size(), 2)
assertEquals(cursor.last()["a"], 4)
}
}
@Test
fun testIssue54() {
val repository = db?.getRepository<SomeAbsClass>()!!
assertTrue(repository.hasIndex("id"))
assertTrue(repository.hasIndex("name"))
val item = MyClass(UUID.randomUUID(), "xyz", true)
var writeResult = repository.insert(item)
assertEquals(writeResult.affectedCount, 1)
var cursor = repository.find()
assertEquals(cursor.size(), 1)
val item2 = MyClass2(UUID.randomUUID(), "123", true, 3)
writeResult = repository.insert(item2)
assertEquals(writeResult.affectedCount, 1)
cursor = repository.find()
assertEquals(cursor.size(), 2)
}
@Test
fun testIssue55() {
val repository = db?.getRepository<CaObject>()!!
val uuid = UUID.randomUUID()
val executor = Executors.newFixedThreadPool(10)
val latch = CountDownLatch(200)
for (i in 0..100) {
val item = CaObject(uuid, "1234")
executor.submit {
try {
repository.update(item, true)
} catch (e: UniqueConstraintException) {
fail("Synchronization failed on update")
} finally {
latch.countDown()
}
}
executor.submit {
try {
repository.insert(item)
} finally {
latch.countDown()
}
}
}
latch.await()
val cursor = repository.find()
println(cursor.toList())
assertEquals(cursor.size(), 1)
}
@Test
fun testIssue59() {
val repository = db?.getRepository<ClassWithLocalDateTime>()!!
repository.insert(ClassWithLocalDateTime("test", LocalDateTime.now()))
assertNotNull(repository.find())
}
@Test
fun testIssue222() {
val first = NestedObjects("value1", "1", listOf(TempObject("name-1", 42, LevelUnder("street", 12))))
val repository = db?.getRepository<NestedObjects>()!!
repository.insert(first)
repository.createIndex("ob1", IndexOptions.indexOptions(IndexType.Fulltext));
var found = repository.find("ob1" text "value1")
assertFalse(found.isEmpty)
first.ob1 = "value2"
repository.update(first)
found = repository.find("ob1" text "value2")
assertFalse(found.isEmpty)
found = repository.find("ob1" text "value1")
assertTrue(found.isEmpty)
}
}
interface MyInterface {
val id: UUID
}
@Indices(value = [(Index(value = "name", type = IndexType.NonUnique))])
abstract class SomeAbsClass(
@Id override val id: UUID = UUID.randomUUID(),
open val name: String = "abcd"
) : MyInterface {
abstract val checked: Boolean
}
@InheritIndices
class MyClass(
override val id: UUID,
override val name: String,
override val checked: Boolean) : SomeAbsClass(id, name)
@InheritIndices
class MyClass2(
override val id: UUID,
override val name: String,
override val checked: Boolean,
val importance: Int
) : SomeAbsClass(id, name)
data class CaObject(
@Id val localId: UUID,
val name: String
)
@Indices(value = [(Index(value = "time", type = IndexType.Unique))])
data class ClassWithLocalDateTime(
val name: String,
val time: LocalDateTime
)
data class NestedObjects(var ob1: String, @Id val id: String, val list: List<TempObject>)
data class TempObject(val name: String, val aga: Int, val add: LevelUnder)
data class LevelUnder(val street: String, val number: Int) | kotlin | 23 | 0.61031 | 108 | 28.317181 | 227 | starcoderdata |
<filename>zircon.core/jvm/src/test/kotlin/org/hexworks/zircon/internal/component/impl/NoOpGenericRenderer.kt
package org.hexworks.zircon.internal.component.impl
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.renderer.ComponentRenderContext
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.graphics.impl.SubTileGraphics
class NoOpGenericRenderer<T : Component> : ComponentRenderer<T> {
override fun render(tileGraphics: SubTileGraphics, context: ComponentRenderContext<T>) {
}
}
| kotlin | 15 | 0.832192 | 108 | 43.923077 | 13 | starcoderdata |
package net.plshark.usererror.server.role
import kotlinx.coroutines.flow.Flow
import net.plshark.usererror.role.Role
/**
* Repository for group-role associations
*/
interface GroupRolesRepository {
/**
* Find roles belonging to a group
* @param groupId the ID of the group
* @returns a [Flow] emitting all roles belonging to the group
*/
fun findRolesForGroup(groupId: Long): Flow<Role>
/**
* Add a new group-role association
* @param groupId the group ID
* @param roleId the role ID
*/
suspend fun insert(groupId: Long, roleId: Long)
/**
* Remove a group-role association
* @param groupId the group ID
* @param roleId the role ID
*/
suspend fun deleteById(groupId: Long, roleId: Long)
/**
* Remove all associations for a group
* @param groupId the group ID
*/
suspend fun deleteByGroupId(groupId: Long)
/**
* Remove all associations for a role
* @param roleId the role ID
*/
suspend fun deleteByRoleId(roleId: Long)
}
| kotlin | 8 | 0.651229 | 66 | 23.604651 | 43 | starcoderdata |
package com.example.coolweather
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.text.LoginFilter
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
import com.example.coolweather.db.City
import com.example.coolweather.db.County
import com.example.coolweather.db.Province
import com.example.coolweather.util.HttpUtil
import com.example.coolweather.util.Utility
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.choose_area.*
import org.litepal.crud.DataSupport
import java.io.IOException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import kotlin.math.log
/**
* Created by lenovo on 2018/3/30.
*/
class ChooseAreaFragment : Fragment() {
lateinit var adapterItem:ArrayAdapter<String>
private val dataList=ArrayList<String>()
companion object {
val LEVEL_PROVINCE=0
val LEVEL_CITY=1
val LEVEL_COUNTY=2
}
/**
* 省列表
*/
lateinit var provinceList:List<Province>
/**
* 市列表
*/
lateinit var cityList:List<City>
/**
* 县列表
*/
lateinit var countyList:List<County>
lateinit var selectedProvince:Province
lateinit var selectedCity:City
var currentLeve:Int=0
lateinit var listView:ListView
lateinit var progressDialog:AlertDialog
val URL="http://guolin.tech/api/china/"
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view=inflater!!.inflate(R.layout.choose_area, container, false)
adapterItem=ArrayAdapter(context,android.R.layout.simple_list_item_1,dataList)
listView=view.findViewById(R.id.listView)
listView.adapter=adapterItem
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
listView.setOnItemClickListener { parent, view, position, id ->
if (currentLeve== LEVEL_PROVINCE){
selectedProvince=provinceList[position]
queryCities()
}else if (currentLeve== LEVEL_CITY){
selectedCity= cityList[position]
queryCounties()
}else if (currentLeve== LEVEL_COUNTY){
val weatherId= countyList[position].weatherId
if (activity is MainActivity){
val inte=Intent(activity,WeatherActivity::class.java)
inte.putExtra("weather_id",weatherId)
startActivity(inte)
activity.finish()
}else if (activity is WeatherActivity){
val activityWeat=activity as WeatherActivity
activityWeat.drawerLayout.closeDrawers()
activityWeat.swipe_refresh.isRefreshing=false
activityWeat.requestWeather(weatherId)
}
}
}
backBtn.setOnClickListener {
if (currentLeve== LEVEL_COUNTY){
queryCities()
}else if (currentLeve== LEVEL_CITY){
queryProvinces()
}
}
queryProvinces()
}
/**
* 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private fun queryCounties() {
title_text.text=selectedCity.cityName
backBtn.visibility=View.VISIBLE
countyList=DataSupport.where("cityid=?",selectedCity.id.toString()).find(County::class.java)
if (countyList.isNotEmpty()){
dataList.clear()
for (county in countyList){
dataList.add(county.countyName)
}
adapterItem.notifyDataSetChanged()
listView.setSelection(0)
currentLeve= LEVEL_COUNTY
}else {
val provinceCode=selectedProvince.provinceCode
val cityCode=selectedCity.cityCode
val address= "$URL$provinceCode/$cityCode"
queryFromServer(address,"county")
}
}
/**
* 查询选择省内所有的市,优先从数据库查询,如果没有查询到再去服务器查询
*/
private fun queryCities() {
title_text.text=selectedProvince.provinceName
backBtn.visibility=View.VISIBLE
cityList=DataSupport.where("provinceid = ?", selectedProvince.id.toString()).find(City::class.java)
if(cityList.isNotEmpty()){
dataList.clear()
for (city in cityList){
dataList.add(city.cityName)
}
adapterItem.notifyDataSetChanged()
listView.setSelection(0)
currentLeve= LEVEL_CITY
}else {
val provinceCode=selectedProvince.provinceCode
val address = URL+provinceCode
queryFromServer(address,"city")
}
}
/**
* 根据选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private fun queryFromServer(address: String, type: String) {
showProgressDialog()
HttpUtil.sendOkHttpRequest(address, object : Callback {
override fun onFailure(call: Call, e: IOException) {
activity.runOnUiThread({
closeProgressDialog()
Toast.makeText(activity,"加载失败",Toast.LENGTH_SHORT).show()
})
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val responseText=response.body().string()
Log.e("att",responseText)
closeProgressDialog()
var result=false
when {
"province" == type -> result=Utility.handleProvinceResponse(responseText)
"city"==(type) -> result=Utility.handleCityResponse(responseText,selectedProvince.id)
"county"==(type) -> result=Utility.handleCountyResponse(responseText,selectedCity.id)
}
if (result){
activity.runOnUiThread({
when {
"province" == type -> queryProvinces()
"city"==(type) -> queryCities()
"county"==(type) ->queryCounties()
}
})
}
}
})
}
private fun queryProvinces() {
title_text.text="中国"
backBtn.visibility=View.GONE
provinceList=DataSupport.findAll(Province::class.java)
if (provinceList.isNotEmpty()){
dataList.clear()
for (province in provinceList){
dataList.add(province.provinceName)
}
adapterItem.notifyDataSetChanged()
listView.setSelection(0)
currentLeve= LEVEL_PROVINCE
}else{
val address=URL
queryFromServer(address,"province")
}
}
private fun showProgressDialog() {
progressDialog= AlertDialog.Builder(activity).create()
progressDialog.setMessage("正在加载...")
progressDialog.setCancelable(false)
progressDialog.show()
}
fun closeProgressDialog(){
if(progressDialog!=null){
progressDialog.dismiss()
}
}
}
| kotlin | 30 | 0.604116 | 117 | 32.486486 | 222 | starcoderdata |
package network.o3.o3wallet.Wallet.SendV2
import android.content.Intent
import android.content.res.Resources
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.google.zxing.integration.android.IntentIntegrator
import neoutils.Neoutils
import neoutils.Neoutils.parseNEP9URI
import network.o3.o3wallet.API.O3Platform.O3PlatformClient
import network.o3.o3wallet.PersistentStore
import network.o3.o3wallet.R
import network.o3.o3wallet.Wallet.toastUntilCancel
import java.math.BigDecimal
class SendV2Activity : AppCompatActivity() {
var sendViewModel: SendViewModel = SendViewModel()
var sendingToast: Toast? = null
fun resetBestNode() {
if (PersistentStore.getNetworkType() == "Private") {
PersistentStore.setNodeURL(PersistentStore.getNodeURL())
return
}
O3PlatformClient().getChainNetworks {
if (it.first == null) {
return@getChainNetworks
} else {
PersistentStore.setOntologyNodeURL(it.first!!.ontology.best)
PersistentStore.setNodeURL(it.first!!.neo.best)
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.send_v2_activity)
resetBestNode()
if (intent.extras != null) {
val uri = intent.getStringExtra("uri")
val assetID = intent.getStringExtra("assetID")
if (uri != "") {
parseQRPayload(uri)
//give sometime to load eveything up
}
if(assetID != "") {
parseQRPayload("", assetID)
}
}
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setCustomView(R.layout.actionbar_layout)
}
fun setWithAssetId(assetId: String) {
runOnUiThread {
sendViewModel.getOwnedAssets(false).observe ( this, Observer { ownedAssets ->
if (assetId == "neo" || assetId == "gas") {
val nativeAsset = ownedAssets?.find { it.symbol.toUpperCase() == assetId.toUpperCase() }
if (nativeAsset != null) {
sendViewModel.setSelectedAsset(nativeAsset)
}
} else {
val tokenAsset = ownedAssets?.find { it.id == assetId }
if (tokenAsset != null) {
sendViewModel.setSelectedAsset(tokenAsset)
}
}
})
}
}
fun parseQRPayload(payload: String, assetId: String? = null) {
if (assetId != null) {
setWithAssetId(assetId)
}
if (Neoutils.validateNEOAddress(payload)) {
sendViewModel.setSelectedAddress(payload)
return
} else try {
val uri = parseNEP9URI(payload)
val toAddress = uri.to
val amount = uri.amount
val assetID = uri.asset
if (toAddress != "") {
sendViewModel.setSelectedAddress(toAddress)
}
if (amount != 0.0) {
sendViewModel.setSelectedSendAmount(BigDecimal(amount))
}
if(assetID != "") {
runOnUiThread {
sendViewModel.getOwnedAssets(false).observe ( this, Observer { ownedAssets ->
if (assetID == "neo" || assetID == "gas") {
val nativeAsset = ownedAssets?.find { it.symbol.toUpperCase() == assetID.toUpperCase() }
if (nativeAsset != null) {
sendViewModel.setSelectedAsset(nativeAsset)
}
} else {
val tokenAsset = ownedAssets?.find { it.id == assetID }
if (tokenAsset != null) {
sendViewModel.setSelectedAsset(tokenAsset)
}
}
})
}
}
Thread.sleep(2000)
} catch (e: Exception) {
Thread.sleep(2000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == -1) {
runOnUiThread {
sendingToast = baseContext.toastUntilCancel(resources.getString(R.string.SEND_sending_in_progress))
sendingToast?.show()
}
sendViewModel.send()
return
} else if (requestCode == 1 && resultCode == 0) {
Toast.makeText(this, resources.getString(R.string.ALERT_cancelled), Toast.LENGTH_LONG).show()
return
}
if (result == null || result.contents == null) {
return
} else {
parseQRPayload(result.contents)
//give sometime to load eveything up
Thread.sleep(2000)
return
}
}
override fun onBackPressed() {
if (sendViewModel.txID != "") {
finish()
} else {
super.onBackPressed()
}
}
override fun getTheme(): Resources.Theme {
val theme = super.getTheme()
if (PersistentStore.getTheme() == "Dark") {
theme.applyStyle(R.style.AppTheme_Dark, true)
} else {
theme.applyStyle(R.style.AppTheme_White, true)
}
return theme
}
}
| kotlin | 40 | 0.550336 | 116 | 35.093168 | 161 | starcoderdata |
<reponame>Julia-Chekulaeva/kotlin
fun foo(c : Collection<String>) = {
c.filter{
val s : String? = bar()
if (s == null) false // here!
zoo(<!ARGUMENT_TYPE_MISMATCH!>s<!>)
}
}
fun bar() : String? = null
fun zoo(s : String) : Boolean = true | kotlin | 14 | 0.562963 | 43 | 23.636364 | 11 | starcoderdata |
<filename>app/src/main/java/me/texy/treeviewdemo/data/constrains/Constants.kt
package me.texy.treeviewdemo.data.constrains
object Constants {
const val API_KEY = "<KEY>"
} | kotlin | 11 | 0.772727 | 77 | 28.5 | 6 | starcoderdata |
package com.cosic.chessview
import com.cosic.chessview.models.Move
interface OnMoveListener {
fun onMove(moves: List<Move?>?)
fun onMovingFinished()
} | kotlin | 12 | 0.75625 | 38 | 19.125 | 8 | starcoderdata |
package com.zawzaww.padc.mmnewskotlin.views.pods
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import com.zawzaww.padc.mmnewskotlin.delegates.BeforeLoginDelegate
import kotlinx.android.synthetic.main.view_pod_account_control.view.*
import kotlinx.android.synthetic.main.view_pod_before_login.view.*
/**
* Created by zawzaw on 22/07/2018.
*/
class BeforeLoginViewPod : RelativeLayout {
lateinit var mDelegate: BeforeLoginDelegate
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
btnRegister.setOnClickListener {
mDelegate.onTapRegister()
}
btnLogin.setOnClickListener {
mDelegate.onTapLogin()
}
}
fun setDelegate(beforeLoginDelegate: BeforeLoginDelegate) {
mDelegate = beforeLoginDelegate
}
fun displayLoginUser() {
vpLoginUser.visibility = View.VISIBLE
vpBeforeLogin.visibility = View.GONE
}
fun displayBeforeLogin() {
vpLoginUser.visibility = View.GONE
vpBeforeLogin.visibility = View.VISIBLE
}
}
| kotlin | 14 | 0.717063 | 113 | 26.235294 | 51 | starcoderdata |
/*
* Copyright 2018-2020 Guthix
*
* 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.guthix.oldscape.server.follow
import io.guthix.oldscape.server.event.PlayerClickEvent
import io.guthix.oldscape.server.pathing.DestinationTile
import io.guthix.oldscape.server.pathing.breadthFirstSearch
import io.guthix.oldscape.server.pathing.simplePathSearch
import io.guthix.oldscape.server.task.NormalTask
on(PlayerClickEvent::class).where { contextMenuEntry == "Follow" }.then {
val followed = clickedPlayer
val dest = DestinationTile(followed.followPosition)
player.path = breadthFirstSearch(player.pos, dest, player.size, true, world.map)
player.turnToLock(followed)
val currentTarget = player.followPosition
player.cancelTasks(NormalTask)
player.addTask(NormalTask) {
while (true) {
if (dest.reached(player.pos.x, player.pos.y, player.size)) break
if (currentTarget != followed.followPosition) {
player.path = breadthFirstSearch(player.pos, dest, player.size, true, world.map)
}
wait(ticks = 1)
}
while (true) {
wait { currentTarget != followed.followPosition }
player.path = simplePathSearch(player.pos, DestinationTile(followed.followPosition), player.size, world.map)
}
}.onCancel {
player.turnToLock(null)
}
} | kotlin | 27 | 0.712698 | 120 | 40.108696 | 46 | starcoderdata |
<filename>web/src/main/kotlin/components/moments.kt
package components
import com.mirego.nwad.viewmodels.home.MomentViewModel
import com.mirego.trikot.viewmodels.declarative.components.VMDListViewModel
import com.mirego.trikot.viewmodels.declarative.properties.VMDImageDescriptor
import movetotrikot.viewModelComponent
import react.dom.div
import react.dom.img
import react.router.dom.Link
val momentsComponent = viewModelComponent<VMDListViewModel<MomentViewModel>> { moments ->
div(classes = "container grid grid-flow-row auto-rows-max") {
for (moment in moments.elements) {
Link {
attrs.to = "/moments/${moment.identifier}"
attrs.replace = true
div(classes = "pb-4") {
+moment.title.text
div(classes = "relative border-2 rounded p-1") {
img(
classes = "rounded",
src = (moment.image.image as VMDImageDescriptor.Remote).url
) {}
}
}
}
}
}
}
| kotlin | 40 | 0.590383 | 89 | 34.09375 | 32 | starcoderdata |
package no.nav.medlemskap.services.udi
import no.nav.medlemskap.clients.udi.UdiClient
import no.nav.medlemskap.domene.Oppholdstillatelse
class UdiService(private val udiClient: UdiClient) {
suspend fun hentOppholdstillatelseer(fnr: String): Oppholdstillatelse? {
return udiClient.hentOppholdstatusResultat(fnr = fnr)?.let { UdiMapper.mapTilOppholdstillatelse(it) }
}
}
| kotlin | 16 | 0.78866 | 109 | 34.272727 | 11 | starcoderdata |
<reponame>sporreking/DivisionEngine<gh_stars>0
package ecs
import com.curiouscreature.kotlin.math.Float3
data class Transform(
/** The position of this transform. */
val position: Float3 = Float3(),
/** The scale of this transform. */
val scale: Float3 = Float3(1.0f, 1.0f, 1.0f),
/** The rotation of this transform. */
val rotation: Float3 = Float3()
) : Component() {
inline var px: Float get() = position.x; set(x) { position.x = x }
inline var py: Float get() = position.y; set(y) { position.y = y }
inline var pz: Float get() = position.z; set(z) { position.z = z }
inline var sx: Float get() = scale.x; set(x) { scale.x = x }
inline var sy: Float get() = scale.y; set(y) { scale.y = y }
inline var sz: Float get() = scale.z; set(z) { scale.z = z }
inline var rx: Float get() = rotation.x; set(x) { rotation.x = x }
inline var ry: Float get() = rotation.y; set(y) { rotation.y = y }
inline var rz: Float get() = rotation.z; set(z) { rotation.z = z }
} | kotlin | 9 | 0.613503 | 70 | 36.888889 | 27 | starcoderdata |
/*
* Copyright 2020 Expedia, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graphql.plugin.generator.types
import com.expediagroup.graphql.plugin.generator.verifyGraphQLClientGeneration
import org.junit.jupiter.api.Test
class GenerateGraphQLInputObjectTypeSpecIT {
@Test
fun `verify we can generate valid input object type spec`() {
val expected = """
package com.expediagroup.graphql.plugin.generator.integration
import com.expediagroup.graphql.client.GraphQLClient
import com.expediagroup.graphql.client.GraphQLResult
import kotlin.Boolean
import kotlin.String
const val INPUT_OBJECT_TEST_QUERY: String =
"query InputObjectTestQuery {\n inputObjectQuery(criteria: { min: 1.0, max: 5.0 } )\n}"
class InputObjectTestQuery(
private val graphQLClient: GraphQLClient<*>
) {
suspend fun execute(): GraphQLResult<InputObjectTestQuery.Result> =
graphQLClient.execute(INPUT_OBJECT_TEST_QUERY, "InputObjectTestQuery", null)
data class Result(
/**
* Query that accepts some input arguments
*/
val inputObjectQuery: Boolean
)
}
""".trimIndent()
val query = """
query InputObjectTestQuery {
inputObjectQuery(criteria: { min: 1.0, max: 5.0 } )
}
""".trimIndent()
verifyGraphQLClientGeneration(query, expected)
}
@Test
fun `verify we can generate objects using aliases`() {
val expected = """
package com.expediagroup.graphql.plugin.generator.integration
import com.expediagroup.graphql.client.GraphQLClient
import com.expediagroup.graphql.client.GraphQLResult
import kotlin.Boolean
import kotlin.String
const val ALIAS_TEST_QUERY: String =
"query AliasTestQuery {\n first: inputObjectQuery(criteria: { min: 1.0, max: 5.0 } )\n second: inputObjectQuery(criteria: { min: 5.0, max: 10.0 } )\n}"
class AliasTestQuery(
private val graphQLClient: GraphQLClient<*>
) {
suspend fun execute(): GraphQLResult<AliasTestQuery.Result> =
graphQLClient.execute(ALIAS_TEST_QUERY, "AliasTestQuery", null)
data class Result(
/**
* Query that accepts some input arguments
*/
val first: Boolean,
/**
* Query that accepts some input arguments
*/
val second: Boolean
)
}
""".trimIndent()
val query = """
query AliasTestQuery {
first: inputObjectQuery(criteria: { min: 1.0, max: 5.0 } )
second: inputObjectQuery(criteria: { min: 5.0, max: 10.0 } )
}
""".trimIndent()
verifyGraphQLClientGeneration(query, expected)
}
}
| kotlin | 10 | 0.596699 | 169 | 35.35 | 100 | starcoderdata |
<reponame>abhinavraj23/oppia-android
package org.oppia.util.networking
import android.content.Context
import android.net.ConnectivityManager
import androidx.annotation.VisibleForTesting
import javax.inject.Inject
import javax.inject.Singleton
/** Utility to get the current connection status of the device. */
@Singleton
class NetworkConnectionUtil @Inject constructor(private val context: Context) {
/** Enum to distinguish different connection statuses for the device. */
enum class ConnectionStatus {
/** Connected to WIFI or Ethernet. */
LOCAL,
/** Connected to Mobile or WiMax. */
CELLULAR,
/** Not connected to a network. */
NONE
}
private var testConnectionStatus: ConnectionStatus? = null
fun getCurrentConnectionStatus(): ConnectionStatus {
testConnectionStatus?.let {
return it
}
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connectivityManager.activeNetworkInfo?.let { activeNetwork ->
val isConnected = activeNetwork.isConnected
val isLocal = activeNetwork.type == ConnectivityManager.TYPE_WIFI || activeNetwork.type == ConnectivityManager.TYPE_ETHERNET
val isCellular = activeNetwork.type == ConnectivityManager.TYPE_MOBILE || activeNetwork.type == ConnectivityManager.TYPE_WIMAX
return@let when {
isConnected && isLocal -> ConnectionStatus.LOCAL
isConnected && isCellular -> ConnectionStatus.CELLULAR
else -> ConnectionStatus.NONE
}
} ?: ConnectionStatus.NONE
}
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun setCurrentConnectionStatus(status: ConnectionStatus) {
testConnectionStatus = status
}
}
| kotlin | 19 | 0.751163 | 132 | 37.222222 | 45 | starcoderdata |
<filename>src/main/java/io/github/lcriadof/atrevete/kotlin/capitulo8/oracle2.kt
/*
Atrévete con Kotlin:
ISBN: 9798792407336 [tapa dura, tipo encuadernación Hardcover (Case Laminate)]
ISBN: 9798596367164 [tapa blanda]
ambas ediciones son idénticas en contenido
Autor: http://luis.criado.online/index.html
Más información sobre el libro: http://luis.criado.online/cv/obra_ackotlin.html
*/
package io.github.lcriadof.atrevete.kotlin.capitulo8
fun main() {
var sql = oracle("test","secret")
var url: String
var insert: String
var crearTabla:String
url = "jdbc:oracle:thin:@192.168.0.20:15210:xe" // this.connectionURL="jdbc:oracle:thin:@"+ipmaquina+":"+puerto+":"+instancia;
sql.conectar(url)
// identificamos la estructura de la tabla
sql.campos("continentes2")
sql.campos.forEach { println("nombre de campo: "+it) // visualizamos
println( "tipo de campo: "+sql.items.get(it)+"\n" )
}
// añadimos información a la tabla
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(1, 'Norteamérica')"
sql.escribir(insert)
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(2, 'Sudamérica')"
sql.escribir(insert)
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(3, 'Asia')"
sql.escribir(insert)
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(4, 'Europa')"
sql.escribir(insert)
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(5, 'África')"
sql.escribir(insert)
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(6, 'Oceanía')"
sql.escribir(insert)
insert="INSERT INTO TEST.CONTINENTES2 (ID, CONTINENTE) VALUES(7, 'Antártida')"
sql.escribir(insert)
insert="COMMIT;"
sql.escribir(insert)
println(sql.leer("test.continentes2",simboloFinal = ""))
sql.desconectar()
} | kotlin | 19 | 0.704619 | 132 | 35.529412 | 51 | starcoderdata |
package apps.jizzu.simpletodo.data.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import apps.jizzu.simpletodo.data.models.Task
import apps.jizzu.simpletodo.utils.PreferenceHelper
@Database(entities = [Task::class], version = 3)
abstract class TasksDatabase : RoomDatabase() {
abstract fun taskDAO(): TaskDao
companion object {
private var mInstance: TasksDatabase? = null
private const val DATABASE_NAME = "simpletodo_database"
private const val TASKS_TABLE = "tasks_table"
private const val TEMP_TABLE = "temp_table"
private const val TASK_ID_COLUMN = "_id"
private const val TASK_TITLE_COLUMN = "task_title"
private const val TASK_NOTE_COLUMN = "task_note"
private const val TASK_DATE_COLUMN = "task_date"
private const val TASK_POSITION_COLUMN = "task_position"
private const val TASK_TIME_STAMP_COLUMN = "task_time_stamp"
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE $TEMP_TABLE ($TASK_ID_COLUMN INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, $TASK_TITLE_COLUMN TEXT NOT NULL, " +
"$TASK_DATE_COLUMN INTEGER NOT NULL, $TASK_POSITION_COLUMN INTEGER NOT NULL, $TASK_TIME_STAMP_COLUMN INTEGER NOT NULL);")
database.execSQL("INSERT INTO $TEMP_TABLE ($TASK_ID_COLUMN, $TASK_TITLE_COLUMN, $TASK_DATE_COLUMN, $TASK_POSITION_COLUMN, $TASK_TIME_STAMP_COLUMN) " +
"SELECT $TASK_ID_COLUMN, $TASK_TITLE_COLUMN, $TASK_DATE_COLUMN, $TASK_POSITION_COLUMN, $TASK_TIME_STAMP_COLUMN FROM $TASKS_TABLE")
database.execSQL("DROP TABLE $TASKS_TABLE")
database.execSQL("ALTER TABLE $TEMP_TABLE RENAME TO $TASKS_TABLE;")
val preferenceHelper = PreferenceHelper.getInstance()
if (!preferenceHelper.getBoolean(PreferenceHelper.IS_AFTER_DATABASE_MIGRATION)) {
preferenceHelper.putBoolean(PreferenceHelper.IS_AFTER_DATABASE_MIGRATION, true)
}
}
}
private val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE $TASKS_TABLE ADD COLUMN $TASK_NOTE_COLUMN TEXT DEFAULT '' NOT NULL")
}
}
fun getInstance(context: Context): TasksDatabase {
synchronized(TasksDatabase::class.java) {
if (mInstance == null) {
mInstance = Room.databaseBuilder(context,
TasksDatabase::class.java, DATABASE_NAME)
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.build()
}
}
return mInstance!!
}
}
} | kotlin | 27 | 0.623077 | 166 | 45.30303 | 66 | starcoderdata |
<reponame>viettranhoang/Gapo-News-Demo<gh_stars>0
package com.vietth.gapo.data.news.cache.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.vietth.gapo.data.news.cache.database.NewsConverter
import com.vietth.gapo.domain.news.model.Content
import com.vietth.gapo.domain.news.model.News
import com.vietth.gapo.domain.news.model.NewsType
import com.vietth.gapo.domain.news.model.Publisher
import java.util.*
@Entity(tableName = "news")
@TypeConverters(NewsConverter::class)
data class NewsEntity(
@PrimaryKey
@ColumnInfo(name = "id") val id: String,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "description") val description: String?,
@ColumnInfo(name = "type") val type: NewsType?,
@ColumnInfo(name = "published_date") val publishedDate: Date?,
@ColumnInfo(name = "images") val images: List<String>,
@ColumnInfo(name = "content") val content: Content?,
@ColumnInfo(name = "publisher") val publisher: Publisher?,
@ColumnInfo(name = "thumb") val thumb: String?,
)
fun NewsEntity.mapToDomain() =
News(
id, title, description, type, publishedDate, images, content, publisher, thumb
)
fun List<NewsEntity>.mapToDomain() = map { it.mapToDomain() }
fun News.mapToEntity() =
NewsEntity(
id,
title,
description,
type,
publishedDate,
images,
content,
publisher,
thumb
)
fun List<News>.mapToEntity() = map { it.mapToEntity() }
| kotlin | 11 | 0.700762 | 86 | 30.48 | 50 | starcoderdata |
/*
* Copyright 2021. Explore in HMS. All rights reserved.
*
* 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.hms.referenceapp.workouts.repo
import android.util.EventLog
import com.hms.referenceapp.workouts.model.dbmodels.EventDetail
import com.hms.referenceapp.workouts.model.dbmodels.EventList
import com.hms.referenceapp.workouts.model.dbmodels.WorkoutDetail
import com.hms.referenceapp.workouts.model.dbmodels.WorkoutList
import com.hms.referenceapp.workouts.services.CloudDbService
import com.hms.referenceapp.workouts.ui.main.events.EEventType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.ArrayList
class CloudDbUseCase(private val cloudDbService: CloudDbService) {
init {
cloudDbService.createObjectType()
CoroutineScope(Dispatchers.Main).launch {
cloudDbService.openCloudDBZoneV2()
}
}
fun openDbZone() {
return cloudDbService.openCloudDBZone()
}
fun createObject() {
return cloudDbService.createObjectType()
}
fun closeDbZone() {
return cloudDbService.closeCloudDBZone()
}
suspend fun openZoneV2() {
return cloudDbService.openCloudDBZoneV2()
}
fun deleteDbZone() {
return cloudDbService.deleteCloudDBZone()
}
suspend fun getAllWorkoutList(): List<WorkoutList> {
return cloudDbService.queryAllWorkoutList()
}
suspend fun getAllWorkoutDetail(param: Int): List<WorkoutDetail> {
return cloudDbService.queryAllWorkoutDetails(value = param)
}
suspend fun getEventCategoryList(): ArrayList<EventDetail> {
return cloudDbService.getEventCategoryList()
}
suspend fun getEventList(): ArrayList<EventList> {
return cloudDbService.getEventList()
}
suspend fun getEventList(date: Long): ArrayList<EventList> {
val calendar = Calendar.getInstance()
calendar.timeInMillis = date
calendar.set(Calendar.HOUR_OF_DAY, 0)
calendar.set(Calendar.MINUTE, 0)
val startDate = calendar.timeInMillis
calendar.set(Calendar.HOUR_OF_DAY, 23)
calendar.set(Calendar.MINUTE, 59)
val endDate = calendar.timeInMillis
return cloudDbService.getEventList(startDate, endDate)
}
suspend fun getEventList(userId: String, eventType: EEventType): ArrayList<EventList> {
return cloudDbService.getEventList(userId, eventType)
}
suspend fun getEvent(id: Int): EventList {
return cloudDbService.getEvent(id)
}
suspend fun getEventCount(userId: String): Long {
return cloudDbService.getEventCount(userId)
}
fun deleteEvent(param: List<EventList>) {
return cloudDbService.deleteEventInfos(eventInfoList = param)
}
suspend fun upsertEvent(param: EventList): String {
return cloudDbService.upsertEventInfos(eventInfo = param)
}
} | kotlin | 13 | 0.723594 | 91 | 31.268519 | 108 | starcoderdata |
import java.net.URI
import java.util.*
plugins {
id("com.driver733.gradle-kotlin-setup-plugin") version "1.1.3"
`maven-publish`
signing
id("io.codearte.nexus-staging") version "0.21.2"
id("de.marcphilipp.nexus-publish") version "0.4.0"
}
allprojects {
repositories {
mavenCentral()
}
group = "com.driver733.infix-fun-generator"
version = rootProject.version
apply<de.marcphilipp.gradle.nexus.NexusPublishPlugin>()
nexusPublishing {
repositories {
packageGroup.set("com.driver733")
sonatype {
if (extra.has("ossSonatypeUsername")) {
username.set(extra["ossSonatypeUsername"] as String)
}
if (extra.has("ossSonatypePassword")) {
password.set(extra["ossSonatypePassword"] as String)
}
}
}
}
}
nexusStaging {
packageGroup = "com.driver733"
numberOfRetries = 100
delayBetweenRetriesInMillis = 6000
if (extra.has("ossSonatypeUsername")) {
username = extra["ossSonatypeUsername"] as String
}
if (extra.has("ossSonatypePassword")) {
password = extra["ossSonatypePassword"] as String
}
}
subprojects.filter { it.name != "example" }.onEach {
with(it) {
apply<SigningPlugin>()
apply<MavenPublishPlugin>()
apply<JavaPlugin>()
tasks.withType(Javadoc::class) {
setExcludes(setOf("**/*.kt"))
options.encoding = "UTF-8"
}
configure<JavaPluginExtension> {
withSourcesJar()
withJavadocJar()
}
configure<PublishingExtension> {
publications {
create<MavenPublication>(name) {
from(components["java"])
pom {
name.set("Infix functions generator")
description.set("Generation of infix functions for instance methods using annotations")
url.set("https://github.com/driver733/infix-functions-generator")
licenses {
license {
name.set("The MIT License")
url.set("http://www.opensource.org/licenses/mit-license.php")
distribution.set("repo")
}
}
issueManagement {
system.set("Github")
url.set("https://github.com/driver733/infix-functions-generator/issues")
}
developers {
developer {
id.set("driver733")
name.set("<NAME>")
email.set("<EMAIL>")
}
}
scm {
connection.set("scm:git:git@github.com/driver733/infix-functions-generator.git")
developerConnection.set("scm:git:git@github.com/driver733/infix-functions-generator.git")
url.set("https://github.com/driver733/infix-functions-generator")
}
}
}
}
repositories {
maven {
credentials {
if (extra.has("ossSonatypeUsername")) {
username = extra["ossSonatypeUsername"] as String
}
if (extra.has("ossSonatypePassword")) {
password = extra["oss<PASSWORD>Password"] as String
}
}
val snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots/"
val releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
url = URI(if (version.toString().endsWith("-SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl)
}
}
}
signing {
if (extra.has("signing.password")) {
extra["signing.password"] = extra["signing.password"]
.let { s -> s as String }
.let { s -> Base64.getDecoder().decode(s) }
.toString(Charsets.UTF_8)
}
extra["signing.secretKeyRingFile"] = rootProject
.projectDir
.toPath()
.resolve("secrets/secring.gpg")
.toAbsolutePath()
.toString()
sign(publishing.publications[name])
}
tasks.javadoc {
if (JavaVersion.current().isJava9Compatible) {
(options as StandardJavadocDocletOptions).addBooleanOption("html5", true)
}
}
}
}.take(1).forEach { subproject ->
tasks.getByPath(":${subproject.name}:publishToSonatype").apply {
finalizedBy(
":closeRepository",
":releaseRepository"
)
}
tasks.getByPath(":closeRepository").apply {
mustRunAfter(subprojects.map { ":${it.name}:publishToSonatype" })
}
tasks.getByPath(":releaseRepository").apply {
mustRunAfter(":closeRepository")
}
}
| kotlin | 40 | 0.486002 | 117 | 33.15625 | 160 | starcoderdata |
<gh_stars>0
package tasks
import contributors.MockGithubService
import contributors.expectedResults
import contributors.testRequestData
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert
import org.junit.Test
class Request4SuspendKtTest {
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testSuspend() = runBlockingTest {
val startTime = System.currentTimeMillis()
val result = loadContributorsSuspend(MockGithubService, testRequestData)
Assert.assertEquals("Wrong result for 'loadContributorsSuspend'", expectedResults.users, result)
val totalTime = System.currentTimeMillis() - startTime
// TODO: uncomment this assertion
/*Assert.assertEquals(
"The calls run consequently, so the total virtual time should be 4000 ms: " +
"1000 for repos request plus (1000 + 1200 + 800) = 3000 for sequential contributors requests)",
expectedResults.timeFromStart, totalTime
)*/
Assert.assertTrue(
"The calls run consequently, so the total time should be around 4000 ms: " +
"1000 for repos request plus (1000 + 1200 + 800) = 3000 for sequential contributors requests)",
totalTime in expectedResults.timeFromStart..(expectedResults.timeFromStart + 500)
)
}
} | kotlin | 20 | 0.714286 | 115 | 42.515152 | 33 | starcoderdata |
<gh_stars>0
package io.github.droidkaigi.confsched2020.announcement.ui.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import com.squareup.inject.assisted.AssistedInject
import io.github.droidkaigi.confsched2020.ext.combine
import io.github.droidkaigi.confsched2020.ext.dropWhileIndexed
import io.github.droidkaigi.confsched2020.ext.toAppError
import io.github.droidkaigi.confsched2020.ext.toLoadingState
import io.github.droidkaigi.confsched2020.model.Announcement
import io.github.droidkaigi.confsched2020.model.AppError
import io.github.droidkaigi.confsched2020.model.LoadState
import io.github.droidkaigi.confsched2020.model.defaultLang
import io.github.droidkaigi.confsched2020.model.repository.AnnouncementRepository
import timber.log.Timber
import timber.log.debug
class AnnouncementViewModel @AssistedInject constructor(
private val announcementRepository: AnnouncementRepository
) : ViewModel() {
data class UiModel(
val isLoading: Boolean,
val error: AppError?,
val announcements: List<Announcement>,
val isEmpty: Boolean
) {
companion object {
val EMPTY = UiModel(false, null, listOf(), false)
}
}
private val languageLiveData = MutableLiveData(defaultLang())
private val announcementLoadStateLiveData = languageLiveData
.distinctUntilChanged()
.switchMap {
liveData<LoadState<List<Announcement>>> {
emitSource(
announcementRepository.announcements()
// Because the empty list is returned
// when the initial refresh is not finished yet.
.dropWhileIndexed { index, value ->
index == 0 && value.isEmpty()
}
.toLoadingState()
.asLiveData()
)
try {
announcementRepository.refresh()
} catch (e: Exception) {
// We can show announcements with cache
Timber.debug(e) { "Fail announcementRepository.refresh()" }
}
}
}
val uiModel = combine(
initialValue = UiModel.EMPTY,
liveData1 = announcementLoadStateLiveData
) { _, loadState ->
val announcements = (loadState as? LoadState.Loaded)?.value.orEmpty()
UiModel(
isLoading = loadState.isLoading,
error = loadState.getErrorIfExists().toAppError(),
announcements = announcements,
isEmpty = !loadState.isLoading && announcements.isEmpty()
)
}
fun loadLanguageSetting() {
languageLiveData.value = defaultLang()
}
@AssistedInject.Factory
interface Factory {
fun create(): AnnouncementViewModel
}
}
| kotlin | 31 | 0.655071 | 81 | 35.710843 | 83 | starcoderdata |
package ai.promoted.metrics
import ai.promoted.NetworkConnection
import ai.promoted.PromotedApiRequest
import ai.promoted.metrics.usecases.FinalizeLogsUseCase
import ai.promoted.telemetry.Telemetry
import ai.promoted.xray.Xray
import com.google.protobuf.Message
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* Allows you to log [Message]s in a batch fashion, making use of the provided flush interval to
* determine when to flush the batch of logs.
*
* Logs will be sent using [PromotedApiRequest] + [NetworkConnection], and that request will be
* executed using Kotlin coroutines, on the IO dispatcher.
*
* This class should be retained as a singleton to ensure all log messages are being placed onto
* a single batch.
*/
internal class MetricsLogger(
flushIntervalMillis: Long,
private val networkConnection: NetworkConnection,
private val finalizeLogsUseCase: FinalizeLogsUseCase,
private val xray: Xray,
private val telemetry: Telemetry
) {
private val networkConnectionScope = CoroutineScope(context = Dispatchers.IO)
private val scheduler = OperationScheduler(
intervalMillis = flushIntervalMillis,
operation = this::sendCurrentMessages
)
private var logMessages = mutableListOf<Message>()
/**
* Enqueue this message. If there is not a current batch scheduled to be sent, this will start
* a new one. Otherwise, it will be added to the batch and be sent when the flush interval is
* reached.
*/
fun enqueueMessage(message: Message) {
logMessages.add(message)
scheduler.maybeSchedule()
}
/**
* Cancel the batch that is scheduled to be sent and discard the log messages from that batch.
*/
fun cancelAndDiscardPendingQueue() {
scheduler.cancel()
logMessages.clear()
}
/**
* Cancel the scheduled send operation and instead send the batch right now.
*/
fun cancelAndSendPendingQueue() {
scheduler.cancel()
sendCurrentMessages()
}
private fun sendCurrentMessages() {
val logMessagesCopy = logMessages
logMessages = mutableListOf()
val request = finalizeLogsUseCase.finalizeLogs(logMessagesCopy)
trySend(logMessagesCopy, request)
}
@Suppress("TooGenericExceptionCaught")
private fun trySend(
// For telemetry
originalMessages: List<Message>,
request: PromotedApiRequest
) {
networkConnectionScope.launch {
try {
xray.monitoredSuspend { networkConnection.send(request) }
telemetry.onMetricsSent(originalMessages.size, request.bodyData.size)
} catch (error: Throwable) {
// Swallow the exception because Xray will have reported it via Telemetry
// if Telemetry is being used
error.printStackTrace()
}
}
}
}
| kotlin | 22 | 0.692927 | 98 | 31.78022 | 91 | starcoderdata |
<filename>wetrade/src/main/java/com/fjoglar/composechallenge/wetrade/ui/screens/home/HomeScreen.kt
package com.fjoglar.composechallenge.wetrade.ui.screens.home
import android.content.res.Configuration
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.BottomSheetScaffold
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.material.rememberBottomSheetScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.fjoglar.composechallenge.wetrade.data.Repository
import com.fjoglar.composechallenge.wetrade.ui.components.WeTradeTemplate
import com.fjoglar.composechallenge.wetrade.ui.screens.home.components.Stocks
import com.fjoglar.composechallenge.wetrade.ui.screens.home.model.HomeScreenTab
import com.google.accompanist.systemuicontroller.SystemUiController
@ExperimentalMaterialApi
@Composable
fun HomeScreen(
tabs: List<HomeScreenTab>,
systemUiController: SystemUiController? = null
) {
val scaffoldState = rememberBottomSheetScaffoldState()
val bottomSheetState by remember {
mutableStateOf(scaffoldState.bottomSheetState)
}
if (!isSystemInDarkTheme()) {
systemUiController?.setStatusBarColor(
color = Color.Transparent,
darkIcons = bottomSheetState.isExpanded
)
}
BottomSheetScaffold(
scaffoldState = scaffoldState,
sheetContent = { Stocks(stocks = Repository.stocks) },
sheetPeekHeight = 64.dp,
sheetShape = RectangleShape,
sheetElevation = 0.dp
) { paddingValues ->
var selectedTab by remember { mutableStateOf(0) }
Column(
modifier = Modifier
.padding(paddingValues)
.statusBarsPadding()
) {
TabRow(
selectedTabIndex = selectedTab,
backgroundColor = MaterialTheme.colors.background,
indicator = { },
divider = { },
) {
tabs.forEachIndexed { index, tab ->
Tab(
text = {
Text(
text = stringResource(id = tab.titleResId).uppercase(),
style = MaterialTheme.typography.button.copy(fontSize = 12.sp)
)
},
selected = selectedTab == index,
onClick = { selectedTab = index }
)
}
}
tabs[selectedTab].content()
}
}
}
@ExperimentalMaterialApi
@Preview(
name = "Day Mode",
widthDp = 360,
heightDp = 640,
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Preview(
name = "Night Mode",
widthDp = 360,
heightDp = 640,
uiMode = Configuration.UI_MODE_NIGHT_YES,
)
@Composable
private fun WelcomeScreenPreview() {
WeTradeTemplate {
val tabs = listOf(
HomeScreenTab.Account,
HomeScreenTab.Watchlist,
HomeScreenTab.Profile,
)
HomeScreen(tabs = tabs)
}
} | kotlin | 40 | 0.672634 | 98 | 32.715517 | 116 | starcoderdata |
<filename>app/src/main/java/org/stepik/android/data/submission/source/SubmissionRemoteDataSource.kt
package org.stepik.android.data.submission.source
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.filter.model.SubmissionsFilterQuery
import org.stepik.android.model.Submission
interface SubmissionRemoteDataSource {
fun createSubmission(submission: Submission): Single<Submission>
fun getSubmissionsForAttempt(attemptId: Long): Single<List<Submission>>
fun getSubmissionsForStep(stepId: Long, submissionsFilterQuery: SubmissionsFilterQuery, page: Int): Single<PagedList<Submission>>
} | kotlin | 12 | 0.83589 | 133 | 49.230769 | 13 | starcoderdata |
<reponame>geniusmaster33/network-map-service<filename>src/main/kotlin/io/cordite/networkmap/utils/NMSOptions.kt
/**
* Copyright 2018, Cordite 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.
*/
package io.cordite.networkmap.utils
import io.cordite.networkmap.service.CertificateManager
import io.cordite.networkmap.service.InMemoryUser
import io.cordite.networkmap.storage.mongo.MongoStorage
import net.corda.core.identity.CordaX500Name
import net.corda.nodeapi.internal.DEV_ROOT_CA
import java.io.File
import java.time.Duration
class NMSOptions : Options() {
private val portOpt = addOption("port", "8080", "web port")
private val dbDirectoryOpt = addOption("db", ".db", "database directory for this service")
private val cacheTimeoutOpt = addOption("cache-timeout", "2S", "http cache timeout for this service in ISO 8601 duration format")
private val paramUpdateDelayOpt = addOption("param-update-delay", "10S", "schedule duration for a parameter update")
private val networkMapUpdateDelayOpt = addOption("network-map-delay", "1S", "queue time for the network map to update for addition of nodes")
private val usernameOpt = addOption("auth-username", "sa", "system admin username")
private val passwordOpt = addOption("auth-password", "<PASSWORD>", "<PASSWORD>")
private val tlsOpt = addOption("tls", "false", "whether TLS is enabled or not")
private val certPathOpt = addOption("tls-cert-path", "", "path to cert if TLS is turned on")
private val keyPathOpt = addOption("tls-key-path", "", "path to key if TLS turned on")
private val hostNameOpt = addOption("hostname", "0.0.0.0", "interface to bind the service to")
private val doormanOpt = addOption("doorman", "true", "enable Corda doorman protocol")
private val certmanOpt = addOption("certman", "true", "enable Cordite certman protocol so that nodes can authenticate using a signed TLS cert")
private val certManpkixOpt = addOption("certman-pkix", "false", "enables certman's pkix validation against JDK default truststore")
private val certmanTruststoreOpt = addOption("certman-truststore", "", "specified a custom truststore instead of the default JRE cacerts")
private val certmanTruststorePasswordOpt = addOption("certman-truststore-password", "", "truststore password")
private val certmanStrictEV = addOption("certman-strict-ev", "false", "enables strict constraint for EV certs only in certman")
private val rootX509Name = addOption("root-ca-name", "CN=\"<replace me>\", OU=Cordite Foundation Network, O=Cordite Foundation, L=London, ST=London, C=GB", "the name for the root ca. If doorman and certman are turned off this will automatically default to Corda dev root ca")
private val webRootOpt = addOption("web-root", "/", "for remapping the root url for all requests")
private val mongoConnectionOpt = addOption("mongo-connection-string", "embed", "MongoDB connection string. If set to `embed` will start its own mongo instance")
private val mongodLocationOpt = addOption("mongod-location", "", "optional location of pre-existing mongod server")
private val mongodDatabaseOpt = addOption("mongod-database", MongoStorage.DEFAULT_DATABASE, "name for mongo database")
val port get() = portOpt.intValue
val dbDirectory get() = dbDirectoryOpt.stringValue.toFile()
val cacheTimeout get() = Duration.parse("PT${cacheTimeoutOpt.stringValue}")
val paramUpdateDelay get() = Duration.parse("PT${paramUpdateDelayOpt.stringValue}")
val networkMapUpdateDelay get() = Duration.parse("PT${networkMapUpdateDelayOpt.stringValue}")
val tls get() = tlsOpt.booleanValue
val certPath get() = certPathOpt.stringValue
val keyPath get() = keyPathOpt.stringValue
val hostname get() = hostNameOpt.stringValue
val user get() = InMemoryUser.createUser("System Admin", usernameOpt.stringValue, passwordOpt.stringValue)
val enableDoorman get() = doormanOpt.booleanValue
val enableCertman get() = certmanOpt.booleanValue
val pkix get() = certManpkixOpt.booleanValue
val truststore = if (certmanTruststoreOpt.stringValue.isNotEmpty()) File(certmanTruststoreOpt.stringValue) else null
val trustStorePassword get() = if (certmanTruststorePasswordOpt.stringValue.isNotEmpty()) certmanTruststorePasswordOpt.stringValue else null
val strictEV get() = certmanStrictEV.booleanValue
val root
get() = if (!enableDoorman && !enableCertman) {
DEV_ROOT_CA
} else {
CertificateManager.createSelfSignedCertificateAndKeyPair(CordaX500Name.parse(rootX509Name.stringValue))
}
val webRoot get() = webRootOpt.stringValue
val mongoConnectionString get() = mongoConnectionOpt.stringValue
val mongodLocation get() = mongodLocationOpt.stringValue
val mongodDatabase get() = mongodDatabaseOpt.stringValue
} | kotlin | 18 | 0.763023 | 277 | 67.571429 | 77 | starcoderdata |
package io.github.theindifferent.gameoflife.visualizer
interface GameOfLifeModelListener {
fun fireModelUpdate()
}
| kotlin | 5 | 0.825 | 54 | 23 | 5 | starcoderdata |
package br.giovanni.kotlin.sampleservice.controllers
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.concurrent.atomic.AtomicLong
import br.giovanni.kotlin.sampleservice.models.Greeting
@RestController
class GreetingController {
val counter = AtomicLong()
@GetMapping("/greeting")
fun greeting(@RequestParam(value = "name", defaultValue = "World") name: String) =
Greeting(counter.incrementAndGet(), "Hello, $name")
@GetMapping("/sayCiao")
fun sayCiao(@RequestParam(value = "name", defaultValue = "World") name: String) =
Greeting(counter.incrementAndGet(), "Ciao, $name!")
} | kotlin | 12 | 0.777778 | 84 | 34.619048 | 21 | starcoderdata |
package biz.lermitage.sub.model
enum class Category(val label: String) {
ADOPT_OPEN_JDK("AdoptOpenJDK"),
ADOPTIUM("Adoptium"),
DATABASE("Database"),
GO("Go"),
GRADLE("Gradle"),
INKSCAPE("Inkscape"),
JAVA("Java"),
JDK("JDK"),
CODECS("Codecs"),
LIBRARY("Library"),
MARIADB("MariaDB"),
MAVEN("Maven"),
NODEJS("NodeJS"),
OS("Operating System"),
PODCAST("Podcast"),
POSTGRESQL("PostgreSQL"),
PYTHON("Python"),
RHEL("Red Hat Enterprise Linux"),
SPRING_FRAMEWORK("Spring Framework"),
SVG_EDITOR("SVG editor"),
VIDEO_PLAYER("Video player"),
VERACRYPT("VeraCrypt"),
REDIST("Redistributable Runtimes"),
VLC("VLC"),
MS_WINDOWS("MS Windows"),
}
| kotlin | 6 | 0.613605 | 41 | 23.5 | 30 | starcoderdata |
package astminer.cli
import astminer.common.getNormalizedToken
import astminer.common.model.ElementNode
import astminer.common.model.MethodInfo
import astminer.common.model.MethodNode
import astminer.common.model.ParseResult
import astminer.parse.antlr.SimpleNode
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
internal class LabelExtractorTest {
companion object {
private const val PATH_STRING = "random/folder/file.txt"
private const val FOLDER = "folder"
private const val FILENAME = "file.txt"
private const val METHOD_NAME = "method"
private val DUMMY_ROOT = SimpleNode("", null, null)
}
@Test
fun testEmptyFilePathExtractor() {
val labelExtractor = FilePathExtractor()
val emptyParseResult = ParseResult(null, PATH_STRING)
val labeledParseResults = labelExtractor.toLabeledData(emptyParseResult)
assertTrue { labeledParseResults.isEmpty() }
}
@Test
fun testNonEmptyFilePathExtractor() {
val labelExtractor = FilePathExtractor()
val nonEmptyParseResult = ParseResult(DUMMY_ROOT, PATH_STRING)
val labeledParseResults = labelExtractor.toLabeledData(nonEmptyParseResult)
assertEquals(1, labeledParseResults.size)
val (root, label) = labeledParseResults[0]
assertEquals(DUMMY_ROOT, root)
assertEquals(PATH_STRING, label)
}
@Test
fun testEmptyFolderExtractor() {
val labelExtractor = FolderExtractor()
val emptyParseResult = ParseResult(null, PATH_STRING)
val labeledParseResults = labelExtractor.toLabeledData(emptyParseResult)
assertTrue { labeledParseResults.isEmpty() }
}
@Test
fun testNonEmptyFolderExtractor() {
val labelExtractor = FolderExtractor()
val nonEmptyParseResult = ParseResult(DUMMY_ROOT, PATH_STRING)
val labeledParseResults = labelExtractor.toLabeledData(nonEmptyParseResult)
assertEquals(1, labeledParseResults.size)
val (root, label) = labeledParseResults[0]
assertEquals(DUMMY_ROOT, root)
assertEquals(FOLDER, label)
}
@Test
fun testMethodNameExtractor() {
val nameNode = SimpleNode("", DUMMY_ROOT, METHOD_NAME)
val methodInfo = MethodInfo<SimpleNode>(
MethodNode(DUMMY_ROOT, null, nameNode),
ElementNode(null, null),
emptyList()
)
processNodeToken(nameNode, false)
val methodNameExtractor = MethodNameExtractor(false)
val label = methodNameExtractor.extractLabel(methodInfo, PATH_STRING)
assertEquals(METHOD_NAME, label)
assertEquals(METHOD_NAME, nameNode.getNormalizedToken())
}
@Test
fun testMethodNameExtractorHide() {
val nameNode = SimpleNode("", DUMMY_ROOT, METHOD_NAME)
val methodInfo = MethodInfo<SimpleNode>(
MethodNode(DUMMY_ROOT, null, nameNode),
ElementNode(null, null),
emptyList()
)
processNodeToken(nameNode, false)
val methodNameExtractor = MethodNameExtractor(true)
val label = methodNameExtractor.extractLabel(methodInfo, PATH_STRING)
assertEquals(METHOD_NAME, label)
assertEquals("METHOD_NAME", nameNode.getNormalizedToken())
}
}
| kotlin | 15 | 0.687425 | 83 | 36.111111 | 90 | starcoderdata |
<filename>neo/src/main/java/com/mrhabibi/neo/validator/DiscreteValidator.kt
package com.mrhabibi.neo.validator
/**
* Created by mrhabibi on 5/9/17.
*/
class DiscreteValidator : NeoValidator<Any>() {
override fun <U> isFulfilled(value: U, phrase: String): Boolean = phrase.equals(value.toString(), ignoreCase = true)
}
| kotlin | 12 | 0.734756 | 120 | 26.333333 | 12 | starcoderdata |
<gh_stars>1-10
package eu.kanade.tachiyomi.data.database.mappers
import android.database.Cursor
import androidx.core.content.contentValuesOf
import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping
import com.pushtorefresh.storio.sqlite.operations.delete.DefaultDeleteResolver
import com.pushtorefresh.storio.sqlite.operations.get.DefaultGetResolver
import com.pushtorefresh.storio.sqlite.operations.put.DefaultPutResolver
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery
import com.pushtorefresh.storio.sqlite.queries.InsertQuery
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import eu.kanade.tachiyomi.data.database.models.Episode
import eu.kanade.tachiyomi.data.database.models.EpisodeImpl
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_ANIME_ID
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_BOOKMARK
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_DATE_FETCH
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_DATE_UPLOAD
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_EPISODE_NUMBER
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_ID
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_LAST_SECOND_SEEN
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_NAME
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_SCANLATOR
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_SEEN
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_SOURCE_ORDER
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_TOTAL_SECONDS
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.COL_URL
import eu.kanade.tachiyomi.data.database.tables.EpisodeTable.TABLE
class EpisodeTypeMapping : SQLiteTypeMapping<Episode>(
EpisodePutResolver(),
EpisodeGetResolver(),
EpisodeDeleteResolver()
)
class EpisodePutResolver : DefaultPutResolver<Episode>() {
override fun mapToInsertQuery(obj: Episode) = InsertQuery.builder()
.table(TABLE)
.build()
override fun mapToUpdateQuery(obj: Episode) = UpdateQuery.builder()
.table(TABLE)
.where("$COL_ID = ?")
.whereArgs(obj.id)
.build()
override fun mapToContentValues(obj: Episode) =
contentValuesOf(
COL_ID to obj.id,
COL_ANIME_ID to obj.anime_id,
COL_URL to obj.url,
COL_NAME to obj.name,
COL_SEEN to obj.seen,
COL_SCANLATOR to obj.scanlator,
COL_BOOKMARK to obj.bookmark,
COL_DATE_FETCH to obj.date_fetch,
COL_DATE_UPLOAD to obj.date_upload,
COL_LAST_SECOND_SEEN to obj.last_second_seen,
COL_TOTAL_SECONDS to obj.total_seconds,
COL_EPISODE_NUMBER to obj.episode_number,
COL_SOURCE_ORDER to obj.source_order
)
}
class EpisodeGetResolver : DefaultGetResolver<Episode>() {
override fun mapFromCursor(cursor: Cursor): Episode = EpisodeImpl().apply {
id = cursor.getLong(cursor.getColumnIndex(COL_ID))
anime_id = cursor.getLong(cursor.getColumnIndex(COL_ANIME_ID))
url = cursor.getString(cursor.getColumnIndex(COL_URL))
name = cursor.getString(cursor.getColumnIndex(COL_NAME))
scanlator = cursor.getString(cursor.getColumnIndex(COL_SCANLATOR))
seen = cursor.getInt(cursor.getColumnIndex(COL_SEEN)) == 1
bookmark = cursor.getInt(cursor.getColumnIndex(COL_BOOKMARK)) == 1
date_fetch = cursor.getLong(cursor.getColumnIndex(COL_DATE_FETCH))
date_upload = cursor.getLong(cursor.getColumnIndex(COL_DATE_UPLOAD))
last_second_seen = cursor.getLong(cursor.getColumnIndex(COL_LAST_SECOND_SEEN))
total_seconds = cursor.getLong(cursor.getColumnIndex(COL_TOTAL_SECONDS))
episode_number = cursor.getFloat(cursor.getColumnIndex(COL_EPISODE_NUMBER))
source_order = cursor.getInt(cursor.getColumnIndex(COL_SOURCE_ORDER))
}
}
class EpisodeDeleteResolver : DefaultDeleteResolver<Episode>() {
override fun mapToDeleteQuery(obj: Episode) = DeleteQuery.builder()
.table(TABLE)
.where("$COL_ID = ?")
.whereArgs(obj.id)
.build()
}
| kotlin | 20 | 0.743444 | 86 | 45.01087 | 92 | starcoderdata |
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.notifications
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.ScriptBuildStep
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script
import jetbrains.buildServer.configs.kotlin.v2019_2.ui.insert
import projects.kibanaConfiguration
fun BuildFeatures.junit(dirs: String = "target/**/TEST-*.xml") {
feature {
type = "xml-report-plugin"
param("xmlReportParsing.reportType", "junit")
param("xmlReportParsing.reportDirs", dirs)
}
}
fun ProjectFeatures.kibanaAgent(init: ProjectFeature.() -> Unit) {
feature {
type = "CloudImage"
param("network", kibanaConfiguration.agentNetwork)
param("subnet", kibanaConfiguration.agentSubnet)
param("growingId", "true")
param("agent_pool_id", "-2")
param("preemptible", "false")
param("sourceProject", "elastic-images-prod")
param("sourceImageFamily", "elastic-kibana-ci-ubuntu-1804-lts")
param("zone", "us-central1-a")
param("profileId", "kibana")
param("diskType", "pd-ssd")
param("machineCustom", "false")
param("maxInstances", "200")
param("imageType", "ImageFamily")
param("diskSizeGb", "75") // TODO
init()
}
}
fun ProjectFeatures.kibanaAgent(size: String, init: ProjectFeature.() -> Unit = {}) {
kibanaAgent {
id = "KIBANA_STANDARD_$size"
param("source-id", "kibana-standard-$size-")
param("machineType", "n2-standard-$size")
init()
}
}
fun BuildType.kibanaAgent(size: String) {
requirements {
startsWith("teamcity.agent.name", "kibana-standard-$size-", "RQ_AGENT_NAME")
}
}
fun BuildType.kibanaAgent(size: Int) {
kibanaAgent(size.toString())
}
val testArtifactRules = """
target/kibana-*
target/test-metrics/*
target/kibana-security-solution/**/*.png
target/junit/**/*
target/test-suites-ci-plan.json
test/**/screenshots/session/*.png
test/**/screenshots/failure/*.png
test/**/screenshots/diff/*.png
test/functional/failure_debug/html/*.html
x-pack/test/**/screenshots/session/*.png
x-pack/test/**/screenshots/failure/*.png
x-pack/test/**/screenshots/diff/*.png
x-pack/test/functional/failure_debug/html/*.html
x-pack/test/functional/apps/reporting/reports/session/*.pdf
""".trimIndent()
fun BuildType.addTestSettings() {
artifactRules += "\n" + testArtifactRules
steps {
failedTestReporter()
}
features {
junit()
}
}
fun BuildType.addSlackNotifications(to: String = "#kibana-teamcity-testing") {
params {
param("elastic.slack.enabled", "true")
param("elastic.slack.channels", to)
}
}
fun BuildType.dependsOn(buildType: BuildType, init: SnapshotDependency.() -> Unit = {}) {
dependencies {
snapshot(buildType) {
reuseBuilds = ReuseBuilds.SUCCESSFUL
onDependencyCancel = FailureAction.ADD_PROBLEM
onDependencyFailure = FailureAction.ADD_PROBLEM
synchronizeRevisions = true
init()
}
}
}
fun BuildType.dependsOn(vararg buildTypes: BuildType, init: SnapshotDependency.() -> Unit = {}) {
buildTypes.forEach { dependsOn(it, init) }
}
fun BuildSteps.failedTestReporter(init: ScriptBuildStep.() -> Unit = {}) {
script {
name = "Failed Test Reporter"
scriptContent =
"""
#!/bin/bash
node scripts/report_failed_tests
""".trimIndent()
executionMode = BuildStep.ExecutionMode.RUN_ON_FAILURE
init()
}
}
// Note: This is currently only used for tests and has a retry in it for flaky tests.
// The retry should be refactored if runbld is ever needed for other tasks.
fun BuildSteps.runbld(stepName: String, script: String) {
script {
name = stepName
// The indentation for this string is like this to ensure 100% that the RUNBLD-SCRIPT heredoc termination will not have spaces at the beginning
scriptContent =
"""#!/bin/bash
set -euo pipefail
source .ci/teamcity/util.sh
branchName="${'$'}GIT_BRANCH"
branchName="${'$'}{branchName#refs\/heads\/}"
if [[ "${'$'}{GITHUB_PR_NUMBER-}" ]]; then
branchName=pull-request
fi
project=kibana
if [[ "${'$'}{ES_SNAPSHOT_MANIFEST-}" ]]; then
project=kibana-es-snapshot-verify
fi
# These parameters are only for runbld reporting
export JENKINS_HOME="${'$'}HOME"
export BUILD_URL="%teamcity.serverUrl%/build/%teamcity.build.id%"
export branch_specifier=${'$'}branchName
export NODE_LABELS='teamcity'
export BUILD_NUMBER="%build.number%"
export EXECUTOR_NUMBER=''
export NODE_NAME=''
export OLD_PATH="${'$'}PATH"
file=${'$'}(mktemp)
(
cat <<RUNBLD-SCRIPT
#!/bin/bash
export PATH="${'$'}OLD_PATH"
$script
RUNBLD-SCRIPT
) > ${'$'}file
tc_retry /usr/local/bin/runbld -d "${'$'}(pwd)" --job-name="elastic+${'$'}project+${'$'}branchName" ${'$'}file
"""
}
}
| kotlin | 17 | 0.685363 | 147 | 27.378698 | 169 | starcoderdata |
<filename>app/src/main/java/com/pavelrekun/rekado/screens/payload_fragment/PayloadsFragment.kt
package com.pavelrekun.rekado.screens.payload_fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pavelrekun.rekado.R
import com.pavelrekun.rekado.base.BaseActivity
import com.pavelrekun.rekado.services.eventbus.Events
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class PayloadsFragment : androidx.fragment.app.Fragment() {
private lateinit var mvpView: PayloadsContract.View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_payloads, container, false)
val activity = activity as BaseActivity
mvpView = PayloadsView(activity, this)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mvpView.initViews()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
mvpView.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEvent(eventPayloads: Events.UpdatePayloadsListEvent) {
mvpView.updateList()
}
override fun onResume() {
super.onResume()
mvpView.onResume()
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
} | kotlin | 14 | 0.736517 | 119 | 31.381818 | 55 | starcoderdata |
<reponame>Lamartio/kosmos
package io.lamart.kostore.car
import io.lamart.kostore.FilteredReducer
import io.lamart.kostore.Reducer
import io.lamart.kostore.filter
data class Seat(val id: Position, val seatBeltLocked: Boolean = false)
sealed class SeatAction(open val seatId: Position) {
data class Lock(override val seatId: Position) : SeatAction(seatId)
data class Unlock(override val seatId: Position) : SeatAction(seatId)
}
val seatReducer: Reducer<Seat> = filter { seat, action: SeatAction ->
when (action) {
is SeatAction.Lock -> seat.copy(seatBeltLocked = true)
is SeatAction.Unlock -> seat.copy(seatBeltLocked = true)
}
} | kotlin | 15 | 0.742081 | 73 | 32.2 | 20 | starcoderdata |
/*
* Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
*
* A copy of the MIT License is included in this file.
*
*
* Terms of the MIT License:
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.devops.store.service.atom.impl
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.tencent.devops.common.api.constant.CommonMessageCode
import com.tencent.devops.common.api.enums.FrontendTypeEnum
import com.tencent.devops.common.api.exception.ErrorCodeException
import com.tencent.devops.common.api.pojo.Result
import com.tencent.devops.common.api.util.JsonUtil
import com.tencent.devops.common.api.util.timestampmilli
import com.tencent.devops.common.redis.RedisOperation
import com.tencent.devops.common.service.utils.MessageCodeUtil
import com.tencent.devops.store.constant.StoreMessageCode
import com.tencent.devops.store.dao.atom.AtomDao
import com.tencent.devops.store.dao.atom.MarketAtomDao
import com.tencent.devops.store.dao.atom.MarketAtomEnvInfoDao
import com.tencent.devops.store.dao.common.StoreProjectRelDao
import com.tencent.devops.store.pojo.atom.AtomEnv
import com.tencent.devops.store.pojo.atom.AtomEnvRequest
import com.tencent.devops.store.pojo.atom.AtomPostInfo
import com.tencent.devops.store.pojo.atom.AtomRunInfo
import com.tencent.devops.store.pojo.atom.enums.AtomStatusEnum
import com.tencent.devops.store.pojo.atom.enums.JobTypeEnum
import com.tencent.devops.store.pojo.common.ATOM_POST_CONDITION
import com.tencent.devops.store.pojo.common.ATOM_POST_ENTRY_PARAM
import com.tencent.devops.store.pojo.common.ATOM_POST_FLAG
import com.tencent.devops.store.pojo.common.ATOM_POST_NORMAL_PROJECT_FLAG_KEY_PREFIX
import com.tencent.devops.store.pojo.common.ATOM_POST_VERSION_TEST_FLAG_KEY_PREFIX
import com.tencent.devops.store.pojo.common.KEY_CREATE_TIME
import com.tencent.devops.store.pojo.common.KEY_UPDATE_TIME
import com.tencent.devops.store.pojo.common.StoreVersion
import com.tencent.devops.store.pojo.common.enums.StoreTypeEnum
import com.tencent.devops.store.service.atom.AtomService
import com.tencent.devops.store.service.atom.MarketAtomCommonService
import com.tencent.devops.store.service.atom.MarketAtomEnvService
import com.tencent.devops.store.utils.StoreUtils
import com.tencent.devops.store.utils.VersionUtils
import org.jooq.DSLContext
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils
import java.time.LocalDateTime
import java.util.Optional
import java.util.concurrent.TimeUnit
/**
* 插件执行环境逻辑类
*
* since: 2019-01-04
*/
@Suppress("ALL")
@Service
class MarketAtomEnvServiceImpl @Autowired constructor(
private val dslContext: DSLContext,
private val marketAtomEnvInfoDao: MarketAtomEnvInfoDao,
private val storeProjectRelDao: StoreProjectRelDao,
private val atomDao: AtomDao,
private val marketAtomDao: MarketAtomDao,
private val atomService: AtomService,
private val marketAtomCommonService: MarketAtomCommonService,
private val redisOperation: RedisOperation
) : MarketAtomEnvService {
private val logger = LoggerFactory.getLogger(MarketAtomEnvServiceImpl::class.java)
private val cache = CacheBuilder.newBuilder().maximumSize(10)
.expireAfterWrite(1, TimeUnit.MINUTES)
.build(object : CacheLoader<String, Optional<Boolean>>() {
override fun load(key: String): Optional<Boolean> {
val value = redisOperation.get(key)
return if (value != null) {
Optional.of(value.toBoolean())
} else {
Optional.empty()
}
}
})
override fun batchGetAtomRunInfos(
projectCode: String,
atomVersions: Set<StoreVersion>
): Result<Map<String, AtomRunInfo>?> {
logger.info("batchGetAtomRunInfos projectCode:$projectCode,atomVersions:$atomVersions")
// 1、校验插件在项目下是否可用
val storePublicFlagKey = StoreUtils.getStorePublicFlagKey(StoreTypeEnum.ATOM.name)
// 获取从db查询默认插件开关,开关打开则实时从db查
val queryDefaultAtomSwitchOptional = cache.get("queryDefaultAtomSwitch")
val queryDefaultAtomSwitch = if (queryDefaultAtomSwitchOptional.isPresent) {
queryDefaultAtomSwitchOptional.get()
} else false
val filterAtomVersions = mutableSetOf<StoreVersion>()
val validateAtomCodeList = mutableListOf<String>()
if (queryDefaultAtomSwitch || !redisOperation.hasKey(storePublicFlagKey)) {
logger.info("$storePublicFlagKey is not exist!")
if (queryDefaultAtomSwitch && redisOperation.hasKey(storePublicFlagKey)) {
redisOperation.delete(storePublicFlagKey)
}
// 从db去查查默认插件
val defaultAtomCodeRecords = atomDao.batchGetDefaultAtomCode(dslContext)
val defaultAtomCodeList = defaultAtomCodeRecords.map { it.value1() }
if (!queryDefaultAtomSwitch) {
redisOperation.sadd(storePublicFlagKey, *defaultAtomCodeList.toTypedArray())
}
handleAtomVersions(
atomVersions = atomVersions,
storePublicFlagKey = storePublicFlagKey,
validateAtomCodeList = validateAtomCodeList,
filterAtomVersions = filterAtomVersions,
defaultAtomCodeList = defaultAtomCodeList
)
} else {
handleAtomVersions(
atomVersions = atomVersions,
storePublicFlagKey = storePublicFlagKey,
validateAtomCodeList = validateAtomCodeList,
filterAtomVersions = filterAtomVersions
)
}
val atomCodeMap = mutableMapOf<String, String>()
val atomCodeList = mutableListOf<String>()
filterAtomVersions.forEach { atomVersion ->
val storeCode = atomVersion.storeCode
atomCodeMap[storeCode] = atomVersion.storeName
atomCodeList.add(storeCode)
}
if (validateAtomCodeList.isNotEmpty()) {
val validAtomCodeList = storeProjectRelDao.getValidStoreCodesByProject(
dslContext = dslContext,
projectCode = projectCode,
storeCodes = validateAtomCodeList,
storeType = StoreTypeEnum.ATOM
)?.map { it.value1() } ?: emptyList()
// 判断是否存在不可用插件
validateAtomCodeList.removeAll(validAtomCodeList)
}
if (validateAtomCodeList.isNotEmpty()) {
// 存在不可用插件,给出错误提示
val inValidAtomNameList = mutableListOf<String>()
validateAtomCodeList.forEach { atomCode ->
inValidAtomNameList.add(atomCodeMap[atomCode] ?: atomCode)
}
val params = arrayOf(projectCode, JsonUtil.toJson(inValidAtomNameList))
throw ErrorCodeException(
errorCode = StoreMessageCode.USER_ATOM_IS_NOT_ALLOW_USE_IN_PROJECT,
params = params,
defaultMessage = MessageCodeUtil.getCodeMessage(
messageCode = StoreMessageCode.USER_ATOM_IS_NOT_ALLOW_USE_IN_PROJECT,
params = params
)
)
}
// 2、根据插件代码和版本号查找插件运行时信息
// 判断当前项目是否是插件的调试项目
val testAtomCodes = storeProjectRelDao.getTestStoreCodes(
dslContext = dslContext,
projectCode = projectCode,
storeType = StoreTypeEnum.ATOM,
storeCodeList = atomCodeList
)?.map { it.value1() }
val atomRunInfoMap = mutableMapOf<String, AtomRunInfo>()
filterAtomVersions.forEach { atomVersion ->
val atomCode = atomVersion.storeCode
val atomName = atomVersion.storeName
val version = atomVersion.version
// 获取当前大版本内是否有测试中的版本
val atomVersionTestFlag = redisOperation.hget(
key = "$ATOM_POST_VERSION_TEST_FLAG_KEY_PREFIX:$atomCode",
hashKey = VersionUtils.convertLatestVersion(version)
)
val testAtomFlag = testAtomCodes?.contains(atomCode) == true
val testFlag = testAtomFlag && (atomVersionTestFlag == null || atomVersionTestFlag.toBoolean())
logger.info("batchGetAtomRunInfos atomCode:$atomCode,version:$version,testFlag:$testFlag")
// 如果当前的项目属于插件的调试项目且插件当前大版本有测试中的版本则实时去db查
val atomRunInfoName = "$atomCode:$version"
if (testFlag) {
atomRunInfoMap[atomRunInfoName] = queryAtomRunInfoFromDb(
projectCode = projectCode,
atomCode = atomCode,
atomName = atomName,
version = version,
testFlag = testFlag
)
} else {
// 去缓存中获取插件运行时信息
val atomRunInfoKey = StoreUtils.getStoreRunInfoKey(StoreTypeEnum.ATOM.name, atomCode)
val atomRunInfoJson = redisOperation.hget(atomRunInfoKey, version)
if (!atomRunInfoJson.isNullOrEmpty()) {
val atomRunInfo = JsonUtil.to(atomRunInfoJson, AtomRunInfo::class.java)
atomRunInfoMap[atomRunInfoName] = atomRunInfo
} else {
atomRunInfoMap[atomRunInfoName] = queryAtomRunInfoFromDb(
projectCode = projectCode,
atomCode = atomCode,
atomName = atomName,
version = version,
testFlag = testFlag
)
}
}
}
return Result(atomRunInfoMap)
}
private fun handleAtomVersions(
atomVersions: Set<StoreVersion>,
storePublicFlagKey: String,
validateAtomCodeList: MutableList<String>,
filterAtomVersions: MutableSet<StoreVersion>,
defaultAtomCodeList: MutableList<String>? = null
) {
atomVersions.forEach { atomVersion ->
val atomCode = atomVersion.storeCode
val historyFlag = atomVersion.historyFlag
val defaultAtomFlag =
defaultAtomCodeList?.contains(atomCode) ?: redisOperation.isMember(storePublicFlagKey, atomCode)
if (!(defaultAtomFlag || historyFlag)) {
// 默认插件和内置插件无需校验可见范围
validateAtomCodeList.add(atomCode)
}
if (!(!defaultAtomFlag && historyFlag)) {
// 过滤调那些没有存在db中的内置插件
filterAtomVersions.add(atomVersion)
}
}
}
private fun queryAtomRunInfoFromDb(
projectCode: String,
atomCode: String,
atomName: String,
version: String,
testFlag: Boolean
): AtomRunInfo {
val atomEnvResult = getMarketAtomEnvInfo(projectCode, atomCode, version)
if (atomEnvResult.isNotOk()) {
val params = arrayOf(projectCode, atomName)
throw ErrorCodeException(
errorCode = StoreMessageCode.USER_ATOM_IS_NOT_ALLOW_USE_IN_PROJECT,
params = params,
defaultMessage = MessageCodeUtil.getCodeMessage(
messageCode = StoreMessageCode.USER_ATOM_IS_NOT_ALLOW_USE_IN_PROJECT,
params = params
)
)
}
// 查不到当前插件信息则中断流程
val atomEnv = atomEnvResult.data ?: throw ErrorCodeException(
errorCode = StoreMessageCode.USER_ATOM_IS_NOT_ALLOW_USE_IN_PROJECT,
params = arrayOf(projectCode, atomName),
defaultMessage = MessageCodeUtil.getCodeMessage(
messageCode = StoreMessageCode.USER_ATOM_IS_NOT_ALLOW_USE_IN_PROJECT,
params = arrayOf(projectCode, atomName)
)
)
val atomRunInfo = AtomRunInfo(
atomCode = atomCode,
atomName = atomEnv.atomName,
version = atomEnv.version,
initProjectCode = atomEnv.projectCode ?: "",
jobType = atomEnv.jobType,
buildLessRunFlag = atomEnv.buildLessRunFlag,
inputTypeInfos = marketAtomCommonService.generateInputTypeInfos(atomEnv.props)
)
if (!testFlag) {
// 将db中的环境信息写入缓存
val atomRunInfoKey = StoreUtils.getStoreRunInfoKey(StoreTypeEnum.ATOM.name, atomCode)
redisOperation.hset(atomRunInfoKey, version, JsonUtil.toJson(atomRunInfo))
}
return atomRunInfo
}
/**
* 根据插件代码和版本号查看插件执行环境信息
*/
override fun getMarketAtomEnvInfo(
projectCode: String,
atomCode: String,
version: String,
atomStatus: Byte?
): Result<AtomEnv?> {
logger.info("getMarketAtomEnvInfo $projectCode,$atomCode,$version,$atomStatus")
// 判断插件查看的权限
val atomResult = atomService.getPipelineAtom(
projectCode = projectCode,
atomCode = atomCode,
version = version,
atomStatus = atomStatus
)
if (atomResult.isNotOk()) {
return Result(atomResult.status, atomResult.message ?: "")
}
val atom = atomResult.data ?: return Result(data = null)
if (atom.htmlTemplateVersion == FrontendTypeEnum.HISTORY.typeVersion) {
// 如果是历史老插件则直接返回环境信息
return Result(
AtomEnv(
atomId = atom.id,
atomCode = atom.atomCode,
atomName = atom.name,
atomStatus = atom.atomStatus,
creator = atom.creator,
version = atom.version,
publicFlag = atom.defaultFlag ?: false,
summary = atom.summary,
docsLink = atom.docsLink,
props = if (atom.props != null) JsonUtil.toJson(atom.props!!) else null,
buildLessRunFlag = atom.buildLessRunFlag,
createTime = atom.createTime,
updateTime = atom.updateTime
)
)
}
val initProjectCode = storeProjectRelDao.getInitProjectCodeByStoreCode(
dslContext = dslContext,
storeCode = atomCode,
storeType = StoreTypeEnum.ATOM.type.toByte()
)
logger.info("the initProjectCode is :$initProjectCode")
// 普通项目的查已发布、下架中和已下架(需要兼容那些还在使用已下架插件插件的项目)的插件
val normalStatusList = listOf(
AtomStatusEnum.RELEASED.status.toByte(),
AtomStatusEnum.UNDERCARRIAGING.status.toByte(),
AtomStatusEnum.UNDERCARRIAGED.status.toByte()
)
val atomStatusList = getAtomStatusList(
atomStatus = atomStatus,
version = version,
normalStatusList = normalStatusList,
atomCode = atomCode,
projectCode = projectCode
)
val atomDefaultFlag = atom.defaultFlag == true
val atomEnvInfoRecord = marketAtomEnvInfoDao.getProjectMarketAtomEnvInfo(
dslContext = dslContext,
projectCode = projectCode,
atomCode = atomCode,
version = version,
atomDefaultFlag = atomDefaultFlag,
atomStatusList = atomStatusList
)
return Result(
if (atomEnvInfoRecord == null) {
null
} else {
val status = atomEnvInfoRecord["atomStatus"] as Byte
val createTime = atomEnvInfoRecord[KEY_CREATE_TIME] as LocalDateTime
val updateTime = atomEnvInfoRecord[KEY_UPDATE_TIME] as LocalDateTime
val postEntryParam = atomEnvInfoRecord[ATOM_POST_ENTRY_PARAM] as? String
val postCondition = atomEnvInfoRecord[ATOM_POST_CONDITION] as? String
var postFlag = true
val atomPostInfo = if (!StringUtils.isEmpty(postEntryParam) && !StringUtils.isEmpty(postEntryParam)) {
AtomPostInfo(
atomCode = atomCode,
version = version,
postEntryParam = postEntryParam!!,
postCondition = postCondition!!
)
} else {
postFlag = false
null
}
val atomPostMap = mapOf(
ATOM_POST_FLAG to postFlag,
ATOM_POST_ENTRY_PARAM to postEntryParam,
ATOM_POST_CONDITION to postCondition
)
if (status in normalStatusList) {
val normalProjectPostKey = "$ATOM_POST_NORMAL_PROJECT_FLAG_KEY_PREFIX:$atomCode"
if (redisOperation.hget(normalProjectPostKey, version) == null) {
redisOperation.hset(
key = normalProjectPostKey,
hashKey = version,
values = JsonUtil.toJson(atomPostMap)
)
}
}
val jobType = atomEnvInfoRecord["jobType"] as? String
AtomEnv(
atomId = atomEnvInfoRecord["atomId"] as String,
atomCode = atomEnvInfoRecord["atomCode"] as String,
atomName = atomEnvInfoRecord["atomName"] as String,
atomStatus = AtomStatusEnum.getAtomStatus(status.toInt()),
creator = atomEnvInfoRecord["creator"] as String,
version = atomEnvInfoRecord["version"] as String,
publicFlag = atomEnvInfoRecord["defaultFlag"] as Boolean,
summary = atomEnvInfoRecord["summary"] as? String,
docsLink = atomEnvInfoRecord["docsLink"] as? String,
props = atomEnvInfoRecord["props"] as? String,
buildLessRunFlag = atomEnvInfoRecord["buildLessRunFlag"] as? Boolean,
createTime = createTime.timestampmilli(),
updateTime = updateTime.timestampmilli(),
projectCode = initProjectCode,
pkgPath = atomEnvInfoRecord["pkgPath"] as String,
language = atomEnvInfoRecord["language"] as? String,
minVersion = atomEnvInfoRecord["minVersion"] as? String,
target = atomEnvInfoRecord["target"] as String,
shaContent = atomEnvInfoRecord["shaContent"] as? String,
preCmd = atomEnvInfoRecord["preCmd"] as? String,
jobType = if (jobType == null) null else JobTypeEnum.valueOf(jobType),
atomPostInfo = atomPostInfo
)
}
)
}
private fun getAtomStatusList(
atomStatus: Byte?,
version: String,
normalStatusList: List<Byte>,
atomCode: String,
projectCode: String
): List<Byte>? {
var atomStatusList: List<Byte>? = null
if (atomStatus != null) {
mutableListOf(atomStatus)
} else {
if (version.contains("*")) {
atomStatusList = normalStatusList.toMutableList()
val releaseCount = marketAtomDao.countReleaseAtomByCode(dslContext, atomCode, version)
if (releaseCount > 0) {
// 如果当前大版本内还有已发布的版本,则xx.latest只对应最新已发布的版本
atomStatusList = mutableListOf(AtomStatusEnum.RELEASED.status.toByte())
}
val flag =
storeProjectRelDao.isTestProjectCode(dslContext, atomCode, StoreTypeEnum.ATOM, projectCode)
logger.info("isInitTestProjectCode flag is :$flag")
if (flag) {
// 原生项目或者调试项目有权查处于测试中、审核中的插件
atomStatusList.addAll(
listOf(
AtomStatusEnum.TESTING.status.toByte(),
AtomStatusEnum.AUDITING.status.toByte()
)
)
}
}
}
return atomStatusList
}
/**
* 更新插件执行环境信息
*/
override fun updateMarketAtomEnvInfo(
projectCode: String,
atomCode: String,
version: String,
atomEnvRequest: AtomEnvRequest
): Result<Boolean> {
val atomResult = atomService.getPipelineAtom(projectCode, atomCode, version) // 判断插件查看的权限
val status = atomResult.status
if (0 != status) {
return Result(atomResult.status, atomResult.message ?: "", false)
}
val atomRecord = atomDao.getPipelineAtom(dslContext, atomCode, version)
return if (null != atomRecord) {
marketAtomEnvInfoDao.updateMarketAtomEnvInfo(dslContext, atomRecord.id, atomEnvRequest)
Result(true)
} else {
MessageCodeUtil.generateResponseDataObject(
messageCode = CommonMessageCode.PARAMETER_IS_INVALID,
params = arrayOf("$atomCode+$version"),
data = false
)
}
}
}
| kotlin | 28 | 0.615625 | 118 | 44.305051 | 495 | starcoderdata |
package io.canvas.alta.ui.common
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import io.canvas.alta.AppExecutors
import io.canvas.alta.MainViewModel
import io.canvas.alta.R
class TestAdapter() {
/*
appExecutors: AppExecutors,
private val viewModel: MainViewModel
) : DataBoundListAdapter<Repo, ItemRepoBinding>(
appExecutors = appExecutors,
diffCallback = object : DiffUtil.ItemCallback<Repo>() {
override fun areItemsTheSame(oldItem: Repo, newItem: Repo): Boolean {
return oldItem.owner == newItem.owner
&& oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: Repo, newItem: Repo): Boolean {
return oldItem.description == newItem.description
&& oldItem.stars == newItem.stars
}
}
) {
override fun createBinding(parent: ViewGroup): ItemRepoBinding {
return DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.item_repo,
parent,
false
)
}
override fun bind(binding: ItemRepoBinding, item: Repo) {
binding.item = item
binding.viewModel = viewModel
}
*/
} | kotlin | 4 | 0.664643 | 80 | 28.311111 | 45 | starcoderdata |