content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package top.zbeboy.isy.web.vo.internship.regulate
import java.sql.Date
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-29 .
**/
open class InternshipRegulateVo {
var internshipRegulateId: String? = null
@NotNull
@Size(max = 30)
var studentName: String? = null
@NotNull
@Size(max = 20)
var studentNumber: String? = null
@NotNull
@Size(max = 15)
var studentTel: String? = null
@NotNull
@Size(max = 200)
var internshipContent: String? = null
@NotNull
@Size(max = 200)
var internshipProgress: String? = null
@NotNull
@Size(max = 20)
var reportWay: String? = null
@NotNull
var reportDate: Date? = null
var schoolGuidanceTeacher: String? = null
var tliy = "无"
@NotNull
var studentId: Int? = null
@NotNull
@Size(max = 64)
var internshipReleaseId: String? = null
@NotNull
var staffId: Int? = null
} | src/main/java/top/zbeboy/isy/web/vo/internship/regulate/InternshipRegulateVo.kt | 3630952898 |
package simyukkuri.gameobject.yukkuri.event.action.actions
import simyukkuri.gameobject.yukkuri.event.IndividualEvent
import simyukkuri.gameobject.yukkuri.event.action.Posture
import simyukkuri.gameobject.yukkuri.event.action.SingleAction
/** 吹っ飛んでいる状態. */
class FlyAway(override val posture: Posture) : SingleAction() {
override fun execute() = Unit
override fun interrupt() = Unit
override fun isTheSameAs(other: IndividualEvent): Boolean {
if (other !is FlyAway) return false
return posture == other.posture
}
} | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/event/action/actions/FlyAway.kt | 2046547176 |
package io.georocket.index.generic
import io.georocket.constants.ConfigConstants
import io.georocket.index.DatabaseIndex
import io.georocket.index.Indexer
import io.georocket.index.IndexerFactory
import io.georocket.index.geojson.GeoJsonBoundingBoxIndexer
import io.georocket.index.xml.XMLBoundingBoxIndexer
import io.georocket.query.GeoIntersects
import io.georocket.query.IndexQuery
import io.georocket.query.QueryCompiler.MatchPriority
import io.georocket.query.QueryPart
import io.georocket.query.StringQueryPart
import io.georocket.util.CoordinateTransformer
import io.georocket.util.JsonStreamEvent
import io.georocket.util.StreamEvent
import io.georocket.util.XMLStreamEvent
import io.vertx.core.Vertx
import io.vertx.kotlin.core.json.jsonArrayOf
import io.vertx.kotlin.core.json.jsonObjectOf
import org.geotools.referencing.CRS
/**
* Base class for factories creating indexers that manage bounding boxes
* @author Michel Kraemer
*/
class BoundingBoxIndexerFactory : IndexerFactory {
companion object {
private const val FLOAT_REGEX = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"
private const val COMMA_REGEX = "\\s*,\\s*"
private const val CODE_PREFIX = "([a-zA-Z]+:\\d+:)?"
private val BBOX_REGEX = (CODE_PREFIX + FLOAT_REGEX + COMMA_REGEX +
FLOAT_REGEX + COMMA_REGEX + FLOAT_REGEX + COMMA_REGEX + FLOAT_REGEX).toRegex()
}
val defaultCrs: String?
/**
* Default constructor
*/
constructor() {
defaultCrs = Vertx.currentContext()
?.config()
?.getString(ConfigConstants.QUERY_DEFAULT_CRS)
}
/**
* Construct a new instance with an explicit defaultCrs
*/
constructor(defaultCrs: String?) {
this.defaultCrs = defaultCrs
}
@Suppress("UNCHECKED_CAST")
override fun <T : StreamEvent> createIndexer(eventType: Class<T>): Indexer<T>? {
if (eventType.isAssignableFrom(XMLStreamEvent::class.java)) {
return XMLBoundingBoxIndexer() as Indexer<T>
} else if (eventType.isAssignableFrom(JsonStreamEvent::class.java)) {
return GeoJsonBoundingBoxIndexer() as Indexer<T>
}
return null
}
override fun getQueryPriority(queryPart: QueryPart): MatchPriority {
return when (queryPart) {
is StringQueryPart -> if (BBOX_REGEX.matches(queryPart.value)) {
MatchPriority.ONLY
} else {
MatchPriority.NONE
}
else -> MatchPriority.NONE
}
}
override fun compileQuery(queryPart: QueryPart): IndexQuery? {
if (queryPart !is StringQueryPart) {
return null
}
val index = queryPart.value.lastIndexOf(':')
val (crsCode, co) = if (index > 0) {
queryPart.value.substring(0, index) to queryPart.value.substring(index + 1)
} else {
null to queryPart.value
}
val crs = if (crsCode != null) {
CRS.decode(crsCode)
} else if (defaultCrs != null) {
CoordinateTransformer.decode(defaultCrs)
} else {
null
}
var points = co.split(",").map { it.trim().toDouble() }.toDoubleArray()
if (crs != null) {
val transformer = CoordinateTransformer(crs)
points = transformer.transform(points, 2)!!
}
val minX = points[0]
val minY = points[1]
val maxX = points[2]
val maxY = points[3]
return GeoIntersects(
"bbox", jsonObjectOf(
"type" to "Polygon",
"coordinates" to jsonArrayOf(
jsonArrayOf(
jsonArrayOf(minX, minY),
jsonArrayOf(maxX, minY),
jsonArrayOf(maxX, maxY),
jsonArrayOf(minX, maxY),
jsonArrayOf(minX, minY)
)
)
)
)
}
override fun getDatabaseIndexes(indexedFields: List<String>): List<DatabaseIndex> = listOf(
DatabaseIndex.Geo("bbox", "bbox_geo")
)
}
| src/main/kotlin/io/georocket/index/generic/BoundingBoxIndexerFactory.kt | 1998560755 |
// Copyright 2000-2018 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.codeInsight.hints
import com.intellij.codeInsight.hints.filtering.MatcherConstructor
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.text.StringUtil
import java.util.*
import java.util.stream.Collectors
fun getHintProviders(): List<Pair<Language, InlayParameterHintsProvider>> {
val name = ExtensionPointName<LanguageExtensionPoint<InlayParameterHintsProvider>>("com.intellij.codeInsight.parameterNameHints")
val languages = name.extensionList.map { it.language }
return languages
.mapNotNull { Language.findLanguageByID(it) }
.map { it to InlayParameterHintsExtension.forLanguage(it) }
}
fun getBlackListInvalidLineNumbers(text: String): List<Int> {
val rules = StringUtil.split(text, "\n", true, false)
return rules
.mapIndexedNotNull { index, s -> index to s }
.filter { it.second.isNotEmpty() }
.map { it.first to MatcherConstructor.createMatcher(it.second) }
.filter { it.second == null }
.map { it.first }
}
fun getLanguageForSettingKey(language: Language): Language {
val supportedLanguages = getBaseLanguagesWithProviders()
var languageForSettings: Language? = language
while (languageForSettings != null && !supportedLanguages.contains(languageForSettings)) {
languageForSettings = languageForSettings.baseLanguage
}
if (languageForSettings == null) languageForSettings = language
return languageForSettings
}
fun getBaseLanguagesWithProviders(): List<Language> {
return getHintProviders()
.stream()
.map { (first) -> first }
.sorted(Comparator.comparing<Language, String> { l -> l.displayName })
.collect(Collectors.toList())
} | platform/lang-impl/src/com/intellij/codeInsight/hints/HintUtils.kt | 3706168624 |
package com.esafirm.androidplayground.kotlin
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.Controller
import com.esafirm.androidplayground.libs.Logger
class KotlinTypeController : Controller() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View =
Logger.getLogView(container.context)
override fun onAttach(view: View) {
super.onAttach(view)
Logger.log("Assert that ${Unit is Nothing}")
}
}
| app/src/main/java/com/esafirm/androidplayground/kotlin/KotlinTypeController.kt | 1793667279 |
package io.georocket.output.xml
import io.georocket.storage.XmlChunkMeta
import io.georocket.util.XMLStartElement
import io.vertx.core.buffer.Buffer
import io.vertx.core.streams.WriteStream
/**
* Abstract base class for XML merge strategies
* @author Michel Kraemer
*/
abstract class AbstractMergeStrategy : MergeStrategy {
companion object {
/**
* The default XML header written by the merger
*/
const val XMLHEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
}
override var parents: List<XMLStartElement>? = null
protected var isHeaderWritten = false
private set
/**
* Merge the parent elements of a given [chunkMetadata] into the current
* parent elements. Perform no checks.
*/
protected abstract fun mergeParents(chunkMetadata: XmlChunkMeta)
override fun init(chunkMetadata: XmlChunkMeta) {
if (!canMerge(chunkMetadata)) {
throw IllegalArgumentException("Chunk cannot be merged with this strategy")
}
mergeParents(chunkMetadata)
}
/**
* Write the XML header and the parent elements
* @param out the output stream to write to
*/
private fun writeHeader(out: WriteStream<Buffer>) {
out.write(Buffer.buffer(XMLHEADER))
parents!!.forEach { e -> out.write(Buffer.buffer(e.toString())) }
}
override suspend fun merge(
chunk: Buffer, chunkMetadata: XmlChunkMeta,
outputStream: WriteStream<Buffer>
) {
if (!canMerge(chunkMetadata)) {
throw IllegalStateException("Chunk cannot be merged with this strategy")
}
if (!isHeaderWritten) {
writeHeader(outputStream)
isHeaderWritten = true
}
outputStream.write(chunk)
}
override fun finish(outputStream: WriteStream<Buffer>) {
// close all parent elements
for (e in parents!!.reversed()) {
outputStream.write(Buffer.buffer("</" + e.name + ">"))
}
}
}
| src/main/kotlin/io/georocket/output/xml/AbstractMergeStrategy.kt | 1095085436 |
package com.nikhilparanjape.radiocontrol.receivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.nikhilparanjape.radiocontrol.utilities.AlarmSchedulers
/**
* Created by Nikhil Paranjape on 12/16/2015.
*
* @author Nikhil Paranjape
*
*
*/
class WakeupReceiver : BroadcastReceiver() {
private var alarmUtil = AlarmSchedulers()
override fun onReceive(context: Context, intent: Intent) {
alarmUtil.scheduleAlarm(context)
val pref = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context)
val editor = pref.edit()
editor.putBoolean("isNoDisturbEnabled", false)
editor.apply()
}
companion object {
const val REQUEST_CODE = 12345
}
}
| RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/receivers/WakeupReceiver.kt | 2014428977 |
// WITH_STDLIB
fun test(list: List<Int>) {
list.<caret>filter { it > 1 }.runningFold(0) { acc, i -> acc + i }
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/runningFold.kt | 1614946404 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.findParentOfType
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.util.getParentResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentForExpression
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import java.util.*
class ChangeFunctionLiteralReturnTypeFix(
functionLiteralExpression: KtLambdaExpression,
type: KotlinType
) : KotlinQuickFixAction<KtLambdaExpression>(functionLiteralExpression) {
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type)
private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type)
private val functionLiteralReturnTypeRef: KtTypeReference?
get() = element?.functionLiteral?.typeReference
private val appropriateQuickFix = createAppropriateQuickFix(functionLiteralExpression, type)
private fun createAppropriateQuickFix(functionLiteralExpression: KtLambdaExpression, type: KotlinType): IntentionAction? {
val context = functionLiteralExpression.analyze()
val functionLiteralType = context.getType(functionLiteralExpression) ?: return null
val builtIns = functionLiteralType.constructor.builtIns
val functionClass = builtIns.getFunction(functionLiteralType.arguments.size - 1)
val functionClassTypeParameters = LinkedList<KotlinType>()
for (typeProjection in functionLiteralType.arguments) {
functionClassTypeParameters.add(typeProjection.type)
}
// Replacing return type:
functionClassTypeParameters.removeAt(functionClassTypeParameters.size - 1)
functionClassTypeParameters.add(type)
val eventualFunctionLiteralType = TypeUtils.substituteParameters(functionClass, functionClassTypeParameters)
val correspondingProperty = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtProperty::class.java)
if (correspondingProperty != null &&
correspondingProperty.delegate == null &&
correspondingProperty.initializer?.let { QuickFixBranchUtil.canEvaluateTo(it, functionLiteralExpression) } != false
) {
val correspondingPropertyTypeRef = correspondingProperty.typeReference
val propertyType = context.get(BindingContext.TYPE, correspondingPropertyTypeRef)
return if (propertyType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, propertyType))
ChangeVariableTypeFix(correspondingProperty, eventualFunctionLiteralType)
else
null
}
val resolvedCall = functionLiteralExpression.getParentResolvedCall(context, true)
if (resolvedCall != null) {
val valueArgument = resolvedCall.call.getValueArgumentForExpression(functionLiteralExpression)
val correspondingParameter = resolvedCall.getParameterForArgument(valueArgument)
if (correspondingParameter != null && correspondingParameter.overriddenDescriptors.size <= 1) {
val project = functionLiteralExpression.project
val correspondingParameterDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, correspondingParameter)
if (correspondingParameterDeclaration is KtParameter) {
val correspondingParameterTypeRef = correspondingParameterDeclaration.typeReference
val parameterType = context.get(BindingContext.TYPE, correspondingParameterTypeRef)
return if (parameterType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, parameterType))
ChangeParameterTypeFix(correspondingParameterDeclaration, eventualFunctionLiteralType)
else
null
}
}
}
val parentFunction = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtFunction::class.java, true)
return if (parentFunction != null && QuickFixBranchUtil.canFunctionOrGetterReturnExpression(parentFunction, functionLiteralExpression)) {
val parentFunctionReturnTypeRef = parentFunction.typeReference
val parentFunctionReturnType = context.get(BindingContext.TYPE, parentFunctionReturnTypeRef)
if (parentFunctionReturnType != null && !KotlinTypeChecker.DEFAULT
.isSubtypeOf(eventualFunctionLiteralType, parentFunctionReturnType)
)
ChangeCallableReturnTypeFix.ForEnclosing(parentFunction, eventualFunctionLiteralType)
else
null
} else
null
}
override fun getText() = appropriateQuickFix?.text ?: KotlinBundle.message("fix.change.return.type.lambda", typePresentation)
override fun getFamilyName() = KotlinBundle.message("fix.change.return.type.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean =
functionLiteralReturnTypeRef != null || appropriateQuickFix != null && appropriateQuickFix.isAvailable(
project,
editor!!,
file
)
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
ApplicationManager.getApplication().runWriteAction {
functionLiteralReturnTypeRef?.let {
val newTypeRef = it.replace(KtPsiFactory(project).createType(typeSourceCode)) as KtTypeReference
ShortenReferences.DEFAULT.process(newTypeRef)
}
}
if (appropriateQuickFix != null && appropriateQuickFix.isAvailable(project, editor!!, file)) {
appropriateQuickFix.invoke(project, editor, file)
}
}
override fun startInWriteAction(): Boolean {
return appropriateQuickFix == null || appropriateQuickFix.startInWriteAction()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val functionLiteralExpression = diagnostic.psiElement.findParentOfType<KtLambdaExpression>(strict = false) ?: return null
return ChangeFunctionLiteralReturnTypeFix(functionLiteralExpression, functionLiteralExpression.builtIns.unitType)
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt | 1747851458 |
package assimp
import glm_.b
import glm_.c
import glm_.mat4x4.Mat4
import java.io.DataInputStream
import java.io.InputStream
import java.nio.ByteBuffer
/**
* Created by elect on 15/11/2016.
*/
var ByteBuffer.pos
get() = position()
set(value) {
position(value)
}
fun String.trimNUL(): String {
val nulIdx = indexOf(NUL)
return if (nulIdx != -1) substring(0, nulIdx)
else this
}
fun ByteBuffer.skipSpaces(): Boolean {
var value = this[position()]
while (value == SP.b || value == HT.b) {
get()
value = this[position()]
}
return !value.isLineEnd
}
fun ByteBuffer.skipLine(): Boolean {
var value = this[position()]
while (value != CR.b && value != LF.b && value != NUL.b) {
get()
value = this[position()]
}
// files are opened in binary mode. Ergo there are both NL and CR
while (value == CR.b || value == LF.b) {
get()
value = this[position()]
}
return value != 0.b
}
fun ByteBuffer.skipSpacesAndLineEnd(): Boolean {
var value = this[position()]
while (value == SP.b || value == HT.b || value == CR.b || value == LF.b) {
get()
// check if we are at the end of file, e.g: ply
if (remaining() > 0) value = this[position()]
else return true
}
return value != 0.b
}
fun ByteBuffer.nextWord(): String {
skipSpaces()
val bytes = ArrayList<Byte>()
while (!this[position()].isSpaceOrNewLine) bytes.add(get())
return String(bytes.toByteArray())
}
fun ByteBuffer.restOfLine(): String {
val bytes = ArrayList<Byte>()
while (!this[position()].isLineEnd) bytes.add(get())
return String(bytes.toByteArray())
}
fun ByteBuffer.consumeNUL() {
while (get(pos).c == NUL) get()
}
val Byte.isLineEnd get() = this == CR.b || this == LF.b || this == NUL.b || this == FF.b
val Char.isLineEnd get () = this == CR || this == LF || this == NUL || this == FF
val Byte.isSpaceOrNewLine get() = isSpace || isLineEnd
val Char.isSpaceOrNewLine get() = isSpace || isLineEnd
val Char.isNewLine get() = this == LF
val Byte.isSpace get() = this == SP.b || this == HT.b
val Char.isSpace get() = this == SP || this == HT
infix fun ByteBuffer.startsWith(string: String) = string.all { get() == it.b }
val Char.isNumeric get() = if (isDigit()) true else (this == '-' || this == '+')
// http://www.aivosto.com/vbtips/control-characters.html
/** Null */
val NUL = '\u0000'
/** Start of Heading — TC1 Transmission control character 1 */
val SOH = '\u0001'
/** Start of Text — TC2 Transmission control character 2 */
val STX = '\u0002'
/** End of Text — TC3 Transmission control character 3 */
val ETX = '\u0003'
/** End of Transmission — TC4 Transmission control character 4 */
val EOT = '\u0004'
/** Enquiry — TC5 Transmission control character 5 */
val ENQ = '\u0005'
/** Acknowledge — TC6 Transmission control character 6 */
val ACK = '\u0006'
/** Bell */
val BEL = '\u0007'
/** Backspace — FE0 Format effector 0 */
val BS = '\u0008'
/** Horizontal Tabulation — FE1 Format effector 1 (Character Tabulation) */
val HT = '\u0009'
/** Line Feed — FE2 Format effector 2 */
val LF = '\u000A'
/** Vertical Tabulation — FE3 Format effector 3 (Line Tabulation) */
val VT = '\u000B'
/** Form Feed — FE4 Format effector 4 */
val FF = '\u000C'
/** Carriage Return — FE5 Format effector 5 */
val CR = '\u000D'
/** Shift Out — LS1 Locking-Shift One */
val SO = '\u000E'
/** Shift In — LS0 Locking-Shift Zero */
val SI = '\u000D'
/** Data Link Escape — TC7 Transmission control character 7 */
val DLE = '\u0010'
/** Device Control 1 — XON */
val DC1 = '\u0011'
/** Device Control 2 */
val DC2 = '\u0012'
/** Device Control 3 — XOFF */
val DC3 = '\u0013'
/** Device Control 4 (Stop) */
val DC4 = '\u0014'
/** Negative Acknowledge — TC8 Transmission control character 8 */
val NAK = '\u0015'
/** Synchronous Idle — TC9 Transmission control character 9 */
val SYN = '\u0016'
/** End of Transmission Block — TC10 Transmission control character 10 */
val ETB = '\u0017'
/** Cancel */
val CAN = '\u0018'
/** End of Medium */
val EM = '\u0019'
/** Substitute */
val SUB = '\u001A'
/** Escape */
val ESC = '\u001B'
/** File Separator — IS4 Information separator 4 */
val FS = '\u001C'
/** Group Separator — IS3 Information separator 3 */
val GS = '\u001D'
/** Record Separator — IS2 Information separator 2 */
val RS = '\u001E'
/** Unit Separator — IS1 Information separator 1 */
val US = '\u001F'
/** Space */
val SP = '\u0020'
/** Delete */
val DEL = '\u007F' | src/main/kotlin/assimp/ParsingUtils.kt | 47441228 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.gridLayout
/**
* Grid representation of [GridLayout] root container or cells sub-grids
*/
interface Grid {
/**
* Set of columns that fill available extra space in container
*/
val resizableColumns: MutableSet<Int>
/**
* Set of rows that fill available extra space in container
*/
val resizableRows: MutableSet<Int>
/**
* Gaps around columns. Used only when column is visible
*/
val columnsGaps: MutableList<HorizontalGaps>
/**
* Gaps around rows. Used only when row is visible
*/
val rowsGaps: MutableList<VerticalGaps>
}
| platform/platform-api/src/com/intellij/ui/dsl/gridLayout/Grid.kt | 1690279488 |
package com.intellij.configurationStore
import com.intellij.codeInsight.template.impl.TemplateSettings
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.testFramework.ProjectRule
import com.intellij.util.io.readText
import com.intellij.util.io.write
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class TemplateSchemeTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
// https://youtrack.jetbrains.com/issue/IDEA-155623#comment=27-1721029
@Test fun `do not remove unknown context`() {
val schemeFile = fsRule.fs.getPath("templates/Groovy.xml")
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val schemeData = """
<templateSet group="Groovy">
<template name="serr" value="System.err.println("$\END$")dwed" description="Prints a string to System.errwefwe" toReformat="true" toShortenFQNames="true" deactivated="true">
<context>
<option name="__DO_NOT_DELETE_ME__" value="true" />
<option name="GROOVY_STATEMENT" value="false" />
</context>
</template>
</templateSet>""".trimIndent()
schemeFile.write(schemeData)
TemplateSettings(schemeManagerFactory)
schemeManagerFactory.save()
assertThat(schemeFile.readText()).isEqualTo(schemeData)
}
} | platform/configuration-store-impl/testSrc/TemplateSchemeTest.kt | 4104383293 |
package br.com.concretesolutions.kappuccino.matchers.drawable
import android.graphics.drawable.Drawable
import android.view.View
import br.com.concretesolutions.kappuccino.utils.getBitmap
import br.com.concretesolutions.kappuccino.utils.getDrawable
import br.com.concretesolutions.kappuccino.utils.getResourceName
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
open class DrawableMatcher(private val drawableId: Int) : TypeSafeMatcher<View>(View::class.java) {
private var resourceName: String? = null
protected var drawable: Drawable? = null
override fun matchesSafely(target: View): Boolean {
if (drawable == null) return drawableId < 0
val currentDrawable = drawable
resourceName = getResourceName(target.context, drawableId)
val expectedDrawable = getDrawable(target.context, drawableId) ?: return false
val currentBitmap = getBitmap(currentDrawable!!)
val expectedBitmap = getBitmap(expectedDrawable)
return currentBitmap.sameAs(expectedBitmap)
}
override fun describeTo(description: Description?) {
description?.appendText("with drawable from resource id: ")
description?.appendValue(drawableId)
if (resourceName != null) {
description?.appendText("[")
description?.appendText(resourceName)
description?.appendText("]")
}
}
}
| kappuccino/src/main/kotlin/br/com/concretesolutions/kappuccino/matchers/drawable/DrawableMatcher.kt | 3957701064 |
// FIR_COMPARISON
// FIR_IDENTICAL
object x {
val b: Boolean = true
val c: String = "true"
val d: Int = 1
val e: Long = 1L
val f: Boolean = true
fun foo(): Boolean = true
}
fun test() {
if(x.<caret>){
}
// ORDER: b, f, foo | plugins/kotlin/completion/testData/weighers/basic/expectedType/ifConditionQualified.kt | 4125291460 |
package org.stepik.android.view.course_list.ui.delegate
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.core.view.isVisible
import kotlinx.android.synthetic.main.item_course.view.*
import kotlinx.android.synthetic.main.layout_course_properties.view.*
import org.stepic.droid.R
import org.stepic.droid.util.TextUtil
import org.stepik.android.domain.course.model.CourseStats
import org.stepik.android.domain.course.model.EnrollmentState
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.user_courses.model.UserCourse
import org.stepik.android.model.Course
import ru.nobird.app.core.model.safeCast
import java.util.Locale
class CoursePropertiesDelegate(
root: View,
private val view: ViewGroup
) {
private val learnersCountImage = view.learnersCountImage
private val learnersCountText = view.learnersCountText
private val courseRatingImage = view.courseRatingImage
private val courseRatingText = view.courseRatingText
private val courseCertificateImage = view.courseCertificateImage
private val courseCertificateText = view.courseCertificateText
private val courseArchiveImage = view.courseArchiveImage
private val courseArchiveText = view.courseArchiveText
private val courseFavoriteImage = root.courseListFavorite
private val courseWishlistImage = root.courseListWishlist
fun setStats(courseListItem: CourseListItem.Data) {
setLearnersCount(courseListItem.course.learnersCount, courseListItem.course.enrollment > 0L)
setRating(courseListItem.courseStats)
setCertificate(courseListItem.course)
setUserCourse(courseListItem.courseStats.enrollmentState.safeCast<EnrollmentState.Enrolled>()?.userCourse)
setWishlist(courseListItem.course.enrollment > 0L, courseListItem.course.isInWishlist)
view.isVisible = view.children.any(View::isVisible)
}
private fun setLearnersCount(learnersCount: Long, isEnrolled: Boolean) {
val needShowLearners = learnersCount > 0 && !isEnrolled
if (needShowLearners) {
learnersCountText.text = TextUtil.formatNumbers(learnersCount)
}
learnersCountImage.isVisible = needShowLearners
learnersCountText.isVisible = needShowLearners
}
private fun setRating(courseStats: CourseStats) {
val needShow = courseStats.review > 0
if (needShow) {
courseRatingText.text = String.format(Locale.ROOT, view.resources.getString(R.string.course_rating_value), courseStats.review)
}
courseRatingImage.isVisible = needShow
courseRatingText.isVisible = needShow
}
private fun setCertificate(course: Course) {
val isEnrolled = course.enrollment > 0L
val needShow = course.withCertificate && !isEnrolled
courseCertificateImage.isVisible = needShow
courseCertificateText.isVisible = needShow
}
private fun setUserCourse(userCourse: UserCourse?) {
courseFavoriteImage.isVisible = userCourse?.isFavorite == true
val isArchived = userCourse?.isArchived == true
courseArchiveImage.isVisible = isArchived
courseArchiveText.isVisible = isArchived
}
private fun setWishlist(isEnrolled: Boolean, isWishlisted: Boolean) {
courseWishlistImage.isVisible = !isEnrolled && isWishlisted
}
} | app/src/main/java/org/stepik/android/view/course_list/ui/delegate/CoursePropertiesDelegate.kt | 2638870001 |
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.internal.HashFunction
import okio.internal.Hmac
import okio.internal.Md5
import okio.internal.Sha1
import okio.internal.Sha256
import okio.internal.Sha512
actual class HashingSink internal constructor(
private val sink: Sink,
private val hashFunction: HashFunction
) : Sink {
override fun write(source: Buffer, byteCount: Long) {
checkOffsetAndCount(source.size, 0, byteCount)
// Hash byteCount bytes from the prefix of source.
var hashedCount = 0L
var s = source.head!!
while (hashedCount < byteCount) {
val toHash = minOf(byteCount - hashedCount, s.limit - s.pos).toInt()
hashFunction.update(s.data, s.pos, toHash)
hashedCount += toHash
s = s.next!!
}
// Write those bytes to the sink.
sink.write(source, byteCount)
}
override fun flush() = sink.flush()
override fun timeout(): Timeout = sink.timeout()
override fun close() = sink.close()
/**
* Returns the hash of the bytes accepted thus far and resets the internal state of this sink.
*
* **Warning:** This method is not idempotent. Each time this method is called its
* internal state is cleared. This starts a new hash with zero bytes accepted.
*/
actual val hash: ByteString
get() {
val result = hashFunction.digest()
return ByteString(result)
}
actual companion object {
/** Returns a sink that uses the obsolete MD5 hash algorithm to produce 128-bit hashes. */
actual fun md5(sink: Sink) = HashingSink(sink, Md5())
/** Returns a sink that uses the obsolete SHA-1 hash algorithm to produce 160-bit hashes. */
actual fun sha1(sink: Sink) = HashingSink(sink, Sha1())
/** Returns a sink that uses the SHA-256 hash algorithm to produce 256-bit hashes. */
actual fun sha256(sink: Sink) = HashingSink(sink, Sha256())
/** Returns a sink that uses the SHA-512 hash algorithm to produce 512-bit hashes. */
actual fun sha512(sink: Sink) = HashingSink(sink, Sha512())
/** Returns a sink that uses the obsolete SHA-1 HMAC algorithm to produce 160-bit hashes. */
actual fun hmacSha1(sink: Sink, key: ByteString) = HashingSink(sink, Hmac.sha1(key))
/** Returns a sink that uses the SHA-256 HMAC algorithm to produce 256-bit hashes. */
actual fun hmacSha256(sink: Sink, key: ByteString) = HashingSink(sink, Hmac.sha256(key))
/** Returns a sink that uses the SHA-512 HMAC algorithm to produce 512-bit hashes. */
actual fun hmacSha512(sink: Sink, key: ByteString) = HashingSink(sink, Hmac.sha512(key))
}
}
| okio/src/nonJvmMain/kotlin/okio/HashingSink.kt | 3305063494 |
package no.skatteetaten.aurora.boober.feature
import org.junit.jupiter.api.Test
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isSuccess
import no.skatteetaten.aurora.boober.model.ApplicationDeploymentRef
import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment
import no.skatteetaten.aurora.boober.utils.AbstractFeatureTest
import no.skatteetaten.aurora.boober.utils.singleApplicationErrorResult
class JavaDeployFeatureTest : AbstractFeatureTest() {
override val feature: Feature
get() = JavaDeployFeature("docker.registry")
@Test
fun `should generate resource for java application`() {
val (adResource, dcResource, serviceResource, isResource) = generateResources(
"""{
"version" : "SNAPSHOT-feature_FOO_1001_FIX_STUPID_STUFF_20190402.113042-26-b1.18.1-wingnut8-1.3.0",
"groupId" : "org.test"
}""",
resource = createEmptyApplicationDeployment(),
createdResources = 3
)
assertThat(adResource).auroraResourceModifiedByThisFeatureWithComment("Added application name and id")
val ad = adResource.resource as ApplicationDeployment
assertThat(ad.spec.applicationId).isEqualTo("665c8f8518c18e8fc6b28a458496ce19bf9e7645")
assertThat(ad.spec.applicationName).isEqualTo("simple")
assertThat(dcResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("dc.json")
assertThat(serviceResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("service.json")
assertThat(isResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("is.json")
}
@Test
fun `should generate resource for java application with adaptions`() {
val (adResource, dcResource, serviceResource, isResource) = generateResources(
"""{
"artifactId" : "simple",
"version" : "1",
"groupId" : "org.test",
"readiness" : {
"path" : "/health"
},
"liveness" : true,
"serviceAccount" : "hero",
"deployStrategy" : {
"type" : "recreate"
},
"prometheus" : false
}""",
resource = createEmptyApplicationDeployment(),
createdResources = 3
)
assertThat(adResource).auroraResourceModifiedByThisFeatureWithComment("Added application name and id")
val ad = adResource.resource as ApplicationDeployment
assertThat(ad.spec.applicationId).isEqualTo("665c8f8518c18e8fc6b28a458496ce19bf9e7645")
assertThat(ad.spec.applicationName).isEqualTo("simple")
assertThat(dcResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("dc-expanded.json")
assertThat(serviceResource).auroraResourceCreatedByThisFeature()
.auroraResourceMatchesFile("service-no-prometheus.json")
assertThat(isResource).auroraResourceCreatedByThisFeature().auroraResourceMatchesFile("is-1.json")
}
@Test
fun `fileName can be long if both artifactId and name exist`() {
assertThat {
createCustomAuroraDeploymentContext(
ApplicationDeploymentRef("utv", "this-name-is-stupid-stupid-stupidly-long-for-no-reason"),
"about.json" to FEATURE_ABOUT,
"this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to """{ "groupId" : "org.test" }""",
"utv/about.json" to "{}",
"utv/this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to
"""{ "name" : "foo", "artifactId" : "foo", "version" : "1" }"""
)
}.isSuccess()
}
@Test
fun `Fails when application name is too long and artifactId blank`() {
assertThat {
createCustomAuroraDeploymentContext(
ApplicationDeploymentRef("utv", "this-name-is-stupid-stupid-stupidly-long-for-no-reason"),
"about.json" to FEATURE_ABOUT,
"this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to """{ "groupId" : "org.test" }""",
"utv/about.json" to "{}",
"utv/this-name-is-stupid-stupid-stupidly-long-for-no-reason.json" to
"""{ "name" : "foo", "version" : "1" }"""
)
}.singleApplicationErrorResult("ArtifactId must be set and be shorter then 50 characters")
}
@Test
fun `Fails when envFile does not start with about`() {
assertThat {
createAuroraDeploymentContext(
"""{
"envFile" : "foo.json"
}"""
)
}.singleApplicationErrorResult("envFile must start with about")
}
}
| src/test/kotlin/no/skatteetaten/aurora/boober/feature/JavaDeployFeatureTest.kt | 627894577 |
package com.squareup.spoon
import com.android.annotations.VisibleForTesting
import com.android.ddmlib.testrunner.ITestRunListener
import com.android.ddmlib.testrunner.TestIdentifier
import com.google.common.collect.ImmutableList
import java.util.LinkedHashSet
/**
* Listens to an instrumentation invocation where `log=true` is set and records information about
* the test suite.
*/
internal class LogRecordingTestRunListener : ITestRunListener {
companion object {
private val parameterRegex = "\\[.*\\]$".toRegex()
@VisibleForTesting
fun stripParametersInClassName(test: TestIdentifier): TestIdentifier {
val className = test.className.replace(parameterRegex, "")
return TestIdentifier(className, test.testName)
}
}
private val activeTests = LinkedHashSet<TestIdentifier>()
private val ignoredTests = LinkedHashSet<TestIdentifier>()
private var runName: String? = null
private var testCount: Int = 0
fun activeTests(): List<TestIdentifier> = ImmutableList.copyOf(activeTests)
fun ignoredTests(): List<TestIdentifier> = ImmutableList.copyOf(ignoredTests)
fun runName() = runName
fun testCount() = testCount
override fun testRunStarted(runName: String, testCount: Int) {
this.runName = runName
this.testCount = testCount
}
override fun testStarted(test: TestIdentifier) {
val newTest = stripParametersInClassName(test)
activeTests.add(newTest)
}
override fun testIgnored(test: TestIdentifier) {
val newTest = stripParametersInClassName(test)
activeTests.remove(newTest)
ignoredTests.add(newTest)
}
override fun testFailed(test: TestIdentifier, trace: String) {}
override fun testAssumptionFailure(test: TestIdentifier, trace: String) {}
override fun testEnded(test: TestIdentifier, testMetrics: Map<String, String>) {}
override fun testRunFailed(errorMessage: String) {}
override fun testRunStopped(elapsedTime: Long) {}
override fun testRunEnded(elapsedTime: Long, runMetrics: Map<String, String>) {}
}
| spoon-runner/src/main/java/com/squareup/spoon/LogRecordingTestRunListener.kt | 3017766427 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.jcef.mermaid
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.ColorUtil
import com.intellij.util.io.DigestUtil
import org.intellij.markdown.ast.ASTNode
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownCodeFenceCacheableProvider
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithExternalFiles
import org.intellij.plugins.markdown.extensions.jcef.MarkdownJCEFPreviewExtension
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import org.intellij.plugins.markdown.ui.preview.html.MarkdownCodeFencePluginCacheCollector
import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil
import java.io.File
import java.nio.file.Paths
internal class MermaidCodeGeneratingProviderExtension(
collector: MarkdownCodeFencePluginCacheCollector? = null
) : MarkdownCodeFenceCacheableProvider(collector),
MarkdownJCEFPreviewExtension,
MarkdownExtensionWithExternalFiles,
ResourceProvider
{
override val scripts: List<String> = listOf(
MAIN_SCRIPT_FILENAME,
THEME_DEFINITION_FILENAME,
"mermaid/bootstrap.js",
)
override val styles: List<String> = listOf("mermaid/mermaid.css")
override val events: Map<String, (String) -> Unit> =
mapOf("storeMermaidFile" to this::storeFileEvent)
override fun isApplicable(language: String) = isEnabled && isAvailable && language == "mermaid"
override fun generateHtml(language: String, raw: String, node: ASTNode): String {
val hash = MarkdownUtil.md5(raw, "") + determineTheme()
val key = getUniqueFile("mermaid", hash, "svg").toFile()
return if (key.exists()) {
"<img src=\"${key.toURI()}\"/>"
} else createRawContentElement(hash, raw)
}
fun store(key: String, content: ByteArray) {
val actualKey = getUniqueFile("mermaid", key, "svg").toFile()
FileUtil.createParentDirs(actualKey)
actualKey.outputStream().buffered().use {
it.write(content)
}
collector?.addAliveCachedFile(this, actualKey)
}
override fun onLAFChanged() = Unit
override val displayName: String =
MarkdownBundle.message("markdown.extensions.mermaid.display.name")
override val id: String = "MermaidLanguageExtension"
override val description: String = MarkdownBundle.message("markdown.extensions.mermaid.description")
override val downloadLink: String = DOWNLOAD_URL
override val downloadFilename: String = "mermaid.js"
private val actualFile
get() = Paths.get(directory.toString(), "mermaid", downloadFilename).toFile()
private fun isDistributionChecksumValid(): Boolean {
val got = StringUtil.toHexString(DigestUtil.md5().digest(actualFile.readBytes()))
return got == CHECKSUM
}
override val isAvailable: Boolean
get() = actualFile.exists() && isDistributionChecksumValid()
override fun afterDownload(): Boolean {
val sourceFile = File(directory, downloadFilename)
sourceFile.copyTo(actualFile, overwrite = true)
return sourceFile.delete()
}
override fun canProvide(resourceName: String): Boolean {
return resourceName in scripts || resourceName in styles
}
private fun determineTheme(): String {
val registryValue = Registry.stringValue("markdown.mermaid.theme")
if (registryValue == "follow-ide") {
val scheme = EditorColorsManager.getInstance().globalScheme
return if (ColorUtil.isDark(scheme.defaultBackground)) "dark" else "default"
}
return registryValue
}
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
return when (resourceName) {
MAIN_SCRIPT_FILENAME -> ResourceProvider.loadExternalResource(File(directory, resourceName))
THEME_DEFINITION_FILENAME -> ResourceProvider.Resource("window.mermaidTheme = '${determineTheme()}';".toByteArray())
else -> ResourceProvider.loadInternalResource(this::class.java, resourceName)
}
}
override val resourceProvider: ResourceProvider = this
private fun escapeContent(content: String): String {
return content.replace("<", "<").replace(">", ">")
}
private fun createRawContentElement(hash: String, content: String): String {
return "<div class=\"mermaid\" cache-id=\"$hash\" id=\"$hash\">${escapeContent(content)}</div>"
}
private fun storeFileEvent(data: String) {
if (data.isEmpty()) {
return
}
val key = data.substring(0, data.indexOf(';'))
val content = data.substring(data.indexOf(';') + 1)
store(key, content.toByteArray())
}
companion object {
private const val MAIN_SCRIPT_FILENAME = "mermaid/mermaid.js"
private const val THEME_DEFINITION_FILENAME = "mermaid/themeDefinition.js"
private const val DOWNLOAD_URL = "https://unpkg.com/[email protected]/dist/mermaid.js"
private const val CHECKSUM = "352791299c7f42ee02e774da58bead4a"
}
}
| plugins/markdown/src/org/intellij/plugins/markdown/extensions/jcef/mermaid/MermaidCodeGeneratingProviderExtension.kt | 682696925 |
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.future
import kotlinx.coroutines.*
import org.junit.Test
import java.util.concurrent.*
import java.util.concurrent.CancellationException
import kotlin.test.*
class AsFutureTest : TestBase() {
@Test
fun testCompletedDeferredAsCompletableFuture() = runTest {
expect(1)
val deferred = async(start = CoroutineStart.UNDISPATCHED) {
expect(2) // completed right away
"OK"
}
expect(3)
val future = deferred.asCompletableFuture()
assertEquals("OK", future.await())
finish(4)
}
@Test
fun testCompletedJobAsCompletableFuture() = runTest {
val job = Job().apply { complete() }
val future = job.asCompletableFuture()
assertEquals(Unit, future.await())
}
@Test
fun testWaitForDeferredAsCompletableFuture() = runTest {
expect(1)
val deferred = async {
expect(3) // will complete later
"OK"
}
expect(2)
val future = deferred.asCompletableFuture()
assertEquals("OK", future.await()) // await yields main thread to deferred coroutine
finish(4)
}
@Test
fun testWaitForJobAsCompletableFuture() = runTest {
val job = Job()
val future = job.asCompletableFuture()
assertTrue(job.isActive)
job.complete()
assertFalse(job.isActive)
assertEquals(Unit, future.await())
}
@Test
fun testAsCompletableFutureThrowable() {
val deferred = GlobalScope.async<Unit> { throw OutOfMemoryError() }
val future = deferred.asCompletableFuture()
try {
expect(1)
future.get()
expectUnreached()
} catch (e: ExecutionException) {
assertTrue(future.isCompletedExceptionally)
assertTrue(e.cause is OutOfMemoryError)
finish(2)
}
}
@Test
fun testJobAsCompletableFutureThrowable() {
val job = Job()
CompletableDeferred<Unit>(parent = job).apply { completeExceptionally(OutOfMemoryError()) }
val future = job.asCompletableFuture()
try {
expect(1)
future.get()
expectUnreached()
} catch (e: ExecutionException) {
assertTrue(future.isCompletedExceptionally)
assertTrue(e.cause is OutOfMemoryError)
finish(2)
}
}
@Test
fun testJobAsCompletableFutureCancellation() {
val job = Job()
val future = job.asCompletableFuture()
job.cancel()
try {
expect(1)
future.get()
expectUnreached()
} catch (e: CancellationException) {
assertTrue(future.isCompletedExceptionally)
finish(2)
}
}
@Test
fun testJobCancellation() {
val job = Job()
val future = job.asCompletableFuture()
future.cancel(true)
assertTrue(job.isCancelled)
assertTrue(job.isCompleted)
assertFalse(job.isActive)
}
@Test
fun testDeferredCancellation() {
val deferred = CompletableDeferred<Int>()
val future = deferred.asCompletableFuture()
future.cancel(true)
assertTrue(deferred.isCancelled)
assertTrue(deferred.isCompleted)
assertFalse(deferred.isActive)
assertTrue(deferred.getCompletionExceptionOrNull() is CancellationException)
}
}
| integration/kotlinx-coroutines-jdk8/test/future/AsFutureTest.kt | 3820430275 |
package org.jetbrains.android.anko.config
enum class ArtifactType(val nameInConfiguration: String) {
COMMONS("commons"), // Anko Commons (does not contain platform-dependent functions)
SQLITE("sqlite"), // Anko SQLite
PLATFORM("platform"), // Anko Layouts for the specific Android SDK version (eg. 15, 19, 21 etc.)
SUPPORT_V4("supportV4"), // Anko Layouts for Android support-v4 library
TOOLKIT("toolkit"), // Anko Layouts for any other Android libraries
SIMPLE_LISTENERS("simpleListeners"), // Old View listeners
COROUTINE_LISTENERS("coroutineListeners") // View listeners with coroutine support
} | anko/library/generator/src/org/jetbrains/android/anko/config/ArtifactType.kt | 1449756455 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.utils
import com.intellij.execution.wsl.WSLCommandLineOptions
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.execution.wsl.WslPath
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.JdkFinder
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.projectRoots.impl.jdkDownloader.JdkInstaller
import com.intellij.openapi.projectRoots.impl.jdkDownloader.JdkListDownloader
import com.intellij.openapi.projectRoots.impl.jdkDownloader.JdkPredicate
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.navigation.Place
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.idea.maven.execution.SyncBundle
import org.jetbrains.idea.maven.project.MavenProjectBundle
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.server.MavenDistributionsCache
import org.jetbrains.idea.maven.server.MavenServerManager
import org.jetbrains.idea.maven.server.WslMavenDistribution
import java.io.File
import java.util.function.Function
import java.util.function.Supplier
import javax.swing.event.HyperlinkEvent
internal object MavenWslUtil : MavenUtil() {
@JvmStatic
fun getPropertiesFromMavenOpts(distribution: WSLDistribution): Map<String, String> {
return parseMavenProperties(distribution.getEnvironmentVariable("MAVEN_OPTS"))
}
@JvmStatic
fun getWslDistribution(project: Project): WSLDistribution {
val basePath = project.basePath ?: throw IllegalArgumentException("Project $project with null base path")
return WslPath.getDistributionByWindowsUncPath(basePath)
?: throw IllegalArgumentException("Distribution for path $basePath not found, check your WSL installation")
}
@JvmStatic
fun tryGetWslDistribution(project: Project): WSLDistribution? {
return project.basePath?.let { WslPath.getDistributionByWindowsUncPath(it) }
}
@JvmStatic
fun tryGetWslDistributionForPath(path: String?): WSLDistribution? {
return path?.let { WslPath.getDistributionByWindowsUncPath(it)}
}
/**
* return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml")
*/
@JvmStatic
fun WSLDistribution.resolveUserSettingsFile(overriddenUserSettingsFile: String?): File {
if (isEmptyOrSpaces(overriddenUserSettingsFile)) {
return File(resolveM2Dir(), SETTINGS_XML)
}
else {
return File(overriddenUserSettingsFile)
}
}
/**
* return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml")
*/
@JvmStatic
fun WSLDistribution.resolveGlobalSettingsFile(overriddenMavenHome: String?): File? {
val directory = this.resolveMavenHomeDirectory(overriddenMavenHome) ?: return null
return File(File(directory, CONF_DIR), SETTINGS_XML)
}
@JvmStatic
fun WSLDistribution.resolveM2Dir(): File {
return this.getWindowsFile(File(this.environment["HOME"], DOT_M2_DIR))!!
}
/**
* return file in windows-style ("\\wsl$\distrib-name\home\user\.m2\settings.xml")
*/
@JvmStatic
fun WSLDistribution.resolveMavenHomeDirectory(overrideMavenHome: String?): File? {
MavenLog.LOG.debug("resolving maven home on WSL with override = \"${overrideMavenHome}\"")
if (overrideMavenHome != null) {
if (overrideMavenHome == MavenServerManager.BUNDLED_MAVEN_3) {
return MavenDistributionsCache.resolveEmbeddedMavenHome().mavenHome
}
val home = File(overrideMavenHome)
if (isValidMavenHome(home)) {
MavenLog.LOG.debug("resolved maven home as ${overrideMavenHome}")
return home
}
else {
MavenLog.LOG.debug("Maven home ${overrideMavenHome} on WSL is invalid")
return null
}
}
val m2home = this.environment[ENV_M2_HOME]
if (m2home != null && !isEmptyOrSpaces(m2home)) {
val homeFromEnv = this.getWindowsPath(m2home)?.let(::File)
if (isValidMavenHome(homeFromEnv)) {
MavenLog.LOG.debug("resolved maven home using \$M2_HOME as ${homeFromEnv}")
return homeFromEnv
}
else {
MavenLog.LOG.debug("Maven home using \$M2_HOME is invalid")
return null
}
}
var home = this.getWindowsPath("/usr/share/maven")?.let(::File)
if (isValidMavenHome(home)) {
MavenLog.LOG.debug("Maven home found at /usr/share/maven")
return home
}
home = this.getWindowsPath("/usr/share/maven2")?.let(::File)
if (isValidMavenHome(home)) {
MavenLog.LOG.debug("Maven home found at /usr/share/maven2")
return home
}
val options = WSLCommandLineOptions()
.setExecuteCommandInLoginShell(true)
.setShellPath(this.shellPath)
val processOutput = this.executeOnWsl(listOf("which", "mvn"), options, 10000, null)
if (processOutput.exitCode == 0) {
val path = processOutput.stdout.lines().find { it.isNotEmpty() }?.let(this::resolveSymlink)?.let(this::getWindowsPath)?.let(::File)
if (path != null) {
return path
}
}
MavenLog.LOG.debug("mvn not found in \$PATH")
MavenLog.LOG.debug("Maven home not found on ${this.presentableName}")
return null
}
/**
* return file in windows style
*/
@JvmStatic
fun WSLDistribution.resolveLocalRepository(overriddenLocalRepository: String?,
overriddenMavenHome: String?,
overriddenUserSettingsFile: String?): File {
if (overriddenLocalRepository != null && !isEmptyOrSpaces(overriddenLocalRepository)) {
return File(overriddenLocalRepository)
}
return doResolveLocalRepository(this.resolveUserSettingsFile(overriddenUserSettingsFile),
this.resolveGlobalSettingsFile(overriddenMavenHome))?.let { this.getWindowsFile(it) }
?: File(this.resolveM2Dir(), REPOSITORY_DIR)
}
@JvmStatic
internal fun WSLDistribution.getDefaultMavenDistribution(overriddenMavenHome: String? = null): WslMavenDistribution? {
val file = this.resolveMavenHomeDirectory(overriddenMavenHome) ?: return null
val wslFile = this.getWslPath(file.path) ?: return null
return WslMavenDistribution(this, wslFile, "default")
}
@JvmStatic
fun getJdkPath(wslDistribution: WSLDistribution): String? {
return wslDistribution.getEnvironmentVariable("JDK_HOME")
}
@JvmStatic
fun WSLDistribution.getWindowsFile(wslFile: File): File? {
return FileUtil.toSystemIndependentName(wslFile.path).let(this::getWindowsPath)?.let(::File)
}
@JvmStatic
fun WSLDistribution.getWslFile(windowsFile: File): File? {
return windowsFile.path.let(this::getWslPath)?.let(::File)
}
@JvmStatic
fun <T> resolveWslAware(project: Project?, ordinary: Supplier<T>, wsl: Function<WSLDistribution, T>): T {
if (project == null && ApplicationManager.getApplication().isUnitTestMode) {
MavenLog.LOG.error("resolveWslAware: Project is null")
}
val wslDistribution = project?.let { tryGetWslDistribution(it) } ?: return ordinary.get()
return wsl.apply(wslDistribution)
}
@JvmStatic
fun useWslMaven(project: Project): Boolean {
val projectWslDistr = tryGetWslDistribution(project) ?: return false
val jdkWslDistr = tryGetWslDistributionForPath(ProjectRootManager.getInstance(project).projectSdk?.homePath) ?: return false
return jdkWslDistr.id == projectWslDistr.id
}
@JvmStatic
fun sameDistributions(first: WSLDistribution?, second: WSLDistribution?): Boolean {
return first?.id == second?.id
}
@JvmStatic
fun restartMavenConnectorsIfJdkIncorrect(project: Project) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
val projectWslDistr = tryGetWslDistribution(project)
var needReset = false
MavenServerManager.getInstance().allConnectors.forEach {
if (it.project == project) {
val jdkWslDistr = tryGetWslDistributionForPath(it.jdk.homePath)
if ((projectWslDistr != null && it.supportType != "WSL") || !sameDistributions(projectWslDistr, jdkWslDistr)) {
needReset = true
it.shutdown(true)
}
}
}
if (!needReset) {
MavenProjectsManager.getInstance(project).embeddersManager.reset()
}
}, SyncBundle.message("maven.sync.restarting"), false, project)
}
@JvmStatic
fun checkWslJdkAndShowNotification(project: Project?) {
val projectWslDistr = tryGetWslDistribution(project!!)
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk == null) return;
val jdkWslDistr = tryGetWslDistributionForPath(sdk.homePath)
val FIX_STR = "FIX"
val OPEN_STR = "OPEN"
if (sameDistributions(projectWslDistr, jdkWslDistr)) return
val listener = object : NotificationListener {
override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) {
if (event.description == OPEN_STR) {
val configurable = ProjectStructureConfigurable.getInstance(
project)
ShowSettingsUtil.getInstance().editConfigurable(project, configurable) {
val place = Place().putPath(
ProjectStructureConfigurable.CATEGORY, configurable.projectConfig)
configurable.navigateTo(place, true)
}
}
else {
if (trySetUpExistingJdk(project, projectWslDistr, notification)) return
ApplicationManager.getApplication().invokeLater {
findOrDownloadNewJdk(project, projectWslDistr, sdk, notification, this)
}
}
}
}
if (projectWslDistr != null && jdkWslDistr == null) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("wsl.windows.jdk.used.for.wsl"),
MavenProjectBundle.message("wsl.windows.jdk.used.for.wsl.descr", OPEN_STR, FIX_STR),
NotificationType.WARNING,
listener), project)
}
else if (projectWslDistr == null && jdkWslDistr != null) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("wsl.wsl.jdk.used.for.windows"),
MavenProjectBundle.message("wsl.wsl.jdk.used.for.windows.descr", OPEN_STR, FIX_STR),
NotificationType.WARNING,
listener), project)
}
else if (projectWslDistr != null && jdkWslDistr != null) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("wsl.different.wsl.jdk.used"),
MavenProjectBundle.message("wsl.different.wsl.jdk.used.descr", OPEN_STR, FIX_STR),
NotificationType.WARNING,
listener), project)
}
}
private fun trySetUpExistingJdk(project: Project, projectWslDistr: WSLDistribution?, notification: Notification): Boolean {
val sdk = service<ProjectJdkTable>().allJdks.filter {
sameDistributions(projectWslDistr, it.homePath?.let(WslPath::getDistributionByWindowsUncPath))
}.maxWithOrNull(compareBy(VersionComparatorUtil.COMPARATOR) { it.versionString })
if (sdk == null) return false;
WriteAction.runAndWait<RuntimeException> {
ProjectRootManagerEx.getInstance(project).projectSdk = sdk
notification.hideBalloon()
}
return true
}
private fun findOrDownloadNewJdk(project: Project, projectWslDistr: WSLDistribution?, sdk: Sdk, notification: Notification, listener: NotificationListener) {
val jdkTask = object : Task.Backgroundable(null, MavenProjectBundle.message("wsl.jdk.searching"), false) {
override fun run(indicator: ProgressIndicator) {
val sdkPath = service<JdkFinder>().suggestHomePaths().filter {
sameDistributions(projectWslDistr, WslPath.getDistributionByWindowsUncPath(it))
}.firstOrNull()
if (sdkPath != null) {
WriteAction.runAndWait<RuntimeException> {
val jdkName = SdkConfigurationUtil.createUniqueSdkName(JavaSdk.getInstance(), sdkPath,
ProjectJdkTable.getInstance().allJdks.toList())
val newJdk = JavaSdk.getInstance().createJdk(jdkName, sdkPath)
ProjectJdkTable.getInstance().addJdk(newJdk)
ProjectRootManagerEx.getInstance(project).projectSdk = newJdk
notification.hideBalloon()
}
return
}
val installer = JdkInstaller.getInstance()
val jdkPredicate = when {
projectWslDistr != null -> JdkPredicate.forWSL()
else -> JdkPredicate.default()
}
val model = JdkListDownloader.getInstance().downloadModelForJdkInstaller(indicator, jdkPredicate)
if (model.isEmpty()) {
Notifications.Bus.notify(Notification(MAVEN_NOTIFICATION_GROUP, MavenProjectBundle.message("maven.wsl.jdk.fix.failed"),
MavenProjectBundle.message("maven.wsl.jdk.fix.failed.descr"),
NotificationType.ERROR, listener), project)
}
else {
val homeDir = installer.defaultInstallDir(model[0], projectWslDistr)
val request = installer.prepareJdkInstallation(model[0], homeDir)
installer.installJdk(request, indicator, project)
notification.hideBalloon()
}
}
}
ProgressManager.getInstance().run(jdkTask)
}
}
| plugins/maven/src/main/java/org/jetbrains/idea/maven/utils/MavenWslUtil.kt | 3032573878 |
package org.http4k.filter.cookie
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.core.cookie.Cookie
import org.junit.Test
import java.time.Duration
import java.time.LocalDateTime
class LocalCookieTest {
val cookie = Cookie("foo", "bar")
@Test
fun `cookie without time attributes does not expire`() {
assertThat(LocalCookie(cookie, LocalDateTime.MAX).isExpired(LocalDateTime.MIN), equalTo(false))
}
@Test
fun `cookie with maxAge zero expires straight away`() {
val created = LocalDateTime.of(2017, 3, 11, 12, 15, 2)
val localCookie = LocalCookie(cookie.maxAge(0), created)
assertThat(localCookie.isExpired(created.plus(Duration.ofMillis(500))), equalTo(true))
}
@Test
fun `expiration for cookie with maxAge only`() {
val created = LocalDateTime.of(2017, 3, 11, 12, 15, 2)
val localCookie = LocalCookie(cookie.maxAge(5), created)
assertThat(localCookie.isExpired(created.plusSeconds(4)), equalTo(false))
assertThat(localCookie.isExpired(created.plusSeconds(5)), equalTo(true))
}
@Test
fun `expiration for cookies with expires only`() {
val created = LocalDateTime.of(2017, 3, 11, 12, 15, 2)
val expires = created.plusSeconds(5)
val localCookie = LocalCookie(cookie.expires(expires), created)
assertThat(localCookie.isExpired(created.plusSeconds(5)), equalTo(false))
assertThat(localCookie.isExpired(created.plusSeconds(6)), equalTo(true))
}
} | http4k-core/src/test/kotlin/org/http4k/filter/cookie/LocalCookieTest.kt | 1371081384 |
// Copyright 2000-2019 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.ui.tabs
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.ui.FileColorManager
import org.jdom.Element
@Service
internal abstract class FileColorModelStorageManager(private val project: Project) : PersistentStateComponent<Element> {
protected abstract val perUser: Boolean
private fun getFileColorManager() = FileColorManager.getInstance(project) as FileColorManagerImpl
override fun getState(): Element {
return getFileColorManager().uninitializedModel.save(!perUser)
}
override fun loadState(state: Element) {
getFileColorManager().uninitializedModel.load(state, !perUser)
}
}
@State(name = "SharedFileColors", storages = [Storage("fileColors.xml")])
internal class PerTeamFileColorModelStorageManager(project: Project) : FileColorModelStorageManager(project) {
override val perUser: Boolean
get() = false
}
@State(name = "FileColors", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)])
internal class PerUserFileColorModelStorageManager(project: Project) : FileColorModelStorageManager(project) {
override val perUser: Boolean
get() = true
} | platform/lang-impl/src/com/intellij/ui/tabs/FileColorModelStorageManager.kt | 3929164451 |
package com.scliang.kquick
import android.content.Context
import android.widget.FrameLayout
/**
* Created by scliang on 2017/6/12.
* KQuick Library UI BaseContainer
*/
class BaseContainer(context: Context) : FrameLayout(context) | core/src/main/kotlin/BaseContainer.kt | 1477957450 |
/*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.timegraph
import android.view.View
import com.jjoe64.graphview.GraphView
import com.vrem.annotation.OpenClass
import com.vrem.wifianalyzer.MainContext
import com.vrem.wifianalyzer.R
import com.vrem.wifianalyzer.settings.Settings
import com.vrem.wifianalyzer.settings.ThemeStyle
import com.vrem.wifianalyzer.wifi.band.WiFiBand
import com.vrem.wifianalyzer.wifi.graphutils.GraphViewBuilder
import com.vrem.wifianalyzer.wifi.graphutils.GraphViewNotifier
import com.vrem.wifianalyzer.wifi.graphutils.GraphViewWrapper
import com.vrem.wifianalyzer.wifi.model.WiFiData
import com.vrem.wifianalyzer.wifi.predicate.Predicate
import com.vrem.wifianalyzer.wifi.predicate.makeOtherPredicate
private const val NUM_X_TIME = 21
internal fun makeGraphView(mainContext: MainContext, graphMaximumY: Int, themeStyle: ThemeStyle): GraphView =
GraphViewBuilder(NUM_X_TIME, graphMaximumY, themeStyle, false)
.setLabelFormatter(TimeAxisLabel())
.setVerticalTitle(mainContext.resources.getString(R.string.graph_axis_y))
.setHorizontalTitle(mainContext.resources.getString(R.string.graph_time_axis_x))
.build(mainContext.context)
internal fun makeGraphViewWrapper(): GraphViewWrapper {
val settings = MainContext.INSTANCE.settings
val themeStyle = settings.themeStyle()
val configuration = MainContext.INSTANCE.configuration
val graphView = makeGraphView(MainContext.INSTANCE, settings.graphMaximumY(), themeStyle)
val graphViewWrapper = GraphViewWrapper(graphView, settings.timeGraphLegend(), themeStyle)
configuration.size = graphViewWrapper.size(graphViewWrapper.calculateGraphType())
graphViewWrapper.setViewport()
return graphViewWrapper
}
@OpenClass
internal class TimeGraphView(private val wiFiBand: WiFiBand,
private val dataManager: DataManager = DataManager(),
private val graphViewWrapper: GraphViewWrapper = makeGraphViewWrapper())
: GraphViewNotifier {
override fun update(wiFiData: WiFiData) {
val predicate = predicate(MainContext.INSTANCE.settings)
val wiFiDetails = wiFiData.wiFiDetails(predicate, MainContext.INSTANCE.settings.sortBy())
val newSeries = dataManager.addSeriesData(graphViewWrapper, wiFiDetails, MainContext.INSTANCE.settings.graphMaximumY())
graphViewWrapper.removeSeries(newSeries)
graphViewWrapper.updateLegend(MainContext.INSTANCE.settings.timeGraphLegend())
graphViewWrapper.visibility(if (selected()) View.VISIBLE else View.GONE)
}
fun predicate(settings: Settings): Predicate = makeOtherPredicate(settings)
private fun selected(): Boolean {
return wiFiBand == MainContext.INSTANCE.settings.wiFiBand()
}
override fun graphView(): GraphView {
return graphViewWrapper.graphView
}
} | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/timegraph/TimeGraphView.kt | 1945337720 |
// 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.vcs.changes.shelf
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.util.registry.Registry
import git4idea.stash.GitShelveChangesSaver
import git4idea.test.*
import org.assertj.core.api.Assertions.assertThat
import java.util.*
class GitStandardShelveTest : GitShelveTest() {
override fun setUp() {
super.setUp()
setBatchShelveOptimization(false)
}
}
class GitBatchShelveTest: GitShelveTest() {
override fun setUp() {
super.setUp()
setBatchShelveOptimization(true)
}
}
abstract class GitShelveTest : GitSingleRepoTest() {
private lateinit var shelveChangesManager : ShelveChangesManager
private lateinit var saver: GitShelveChangesSaver
override fun setUp() {
super.setUp()
shelveChangesManager = ShelveChangesManager.getInstance(project)
saver = GitShelveChangesSaver(project, git, EmptyProgressIndicator(), "test")
git("config core.autocrlf false")
}
protected fun setBatchShelveOptimization(value: Boolean) {
val batchSize = if (value) 100 else -1
Registry.get("git.shelve.load.base.in.batches").setValue(batchSize, testRootDisposable)
}
fun `test modification`() {
val file = file("a.txt")
val initialContent = "initial\n"
file.create(initialContent).addCommit("initial")
file.append("more changes\n")
val newContent = file.read()
refresh()
updateChangeListManager()
saver.saveLocalChanges(listOf(repo.root))
refresh()
updateChangeListManager()
changeListManager.assertNoChanges()
assertEquals("Current file content is incorrect", initialContent, file.read())
val list = `assert single shelvelist`()
assertChanges(list) {
modified("a.txt", initialContent, newContent)
}
}
fun `test two files modification`() {
val aFile = file("a.txt")
val initialContent = "initial\n"
aFile.create(initialContent).addCommit("initial")
aFile.append("more changes\n")
val aNewContent = aFile.read()
val bfile = file("b.txt")
bfile.create(initialContent).addCommit("initial")
bfile.append("more changes from b\n")
val bNewContent = bfile.read()
refresh()
updateChangeListManager()
saver.saveLocalChanges(listOf(repo.root))
refresh()
updateChangeListManager()
changeListManager.assertNoChanges()
assertEquals("Current file content is incorrect", initialContent, aFile.read())
assertEquals("Current file content is incorrect", initialContent, bfile.read())
val list = `assert single shelvelist`()
assertChanges(list) {
modified("a.txt", initialContent, aNewContent)
modified("b.txt", initialContent, bNewContent)
}
}
fun `test addition`() {
val file = file("a.txt")
val initialContent = "initial\n"
file.create(initialContent).add()
refresh()
updateChangeListManager()
saver.saveLocalChanges(listOf(repo.root))
refresh()
updateChangeListManager()
changeListManager.assertNoChanges()
assertFalse("There should be no file a.txt on disk", file.file.exists())
val list = `assert single shelvelist`()
assertChanges(list) {
added("a.txt", initialContent)
}
}
fun `test shelf and load files added in multiple roots`() {
val file = file("a.txt")
val initialContent = "initial\n"
file.create(initialContent).add()
val secondRoot = createRepository(project, projectRoot.createDir("secondRoot").toNioPath(), false)
val file2 = secondRoot.file("b.txt")
file2.create(initialContent).add()
refresh()
updateChangeListManager()
saver.saveLocalChanges(listOf(repo.root, secondRoot.root))
refresh()
updateChangeListManager()
changeListManager.assertNoChanges()
assertThat(file.file).doesNotExist()
assertThat(file2.file).doesNotExist()
val list = `assert single shelvelist`()
assertChanges(list) {
added("a.txt", initialContent)
added("b.txt", initialContent)
}
saver.load()
refresh()
updateChangeListManager()
assertTrue("There should be the file a.txt on the disk", file.file.exists())
assertTrue("There should be the file b.txt on the disk", file2.file.exists())
repo.assertStatus(file.file, 'A')
secondRoot.assertStatus(file2.file, 'A')
}
private fun `assert single shelvelist`(): ShelvedChangeList {
val lists = shelveChangesManager.shelvedChangeLists
assertEquals("Incorrect shelve lists amount", 1, lists.size)
return lists[0]
}
private fun assertChanges(list: ShelvedChangeList, changes: ChangesBuilder.() -> Unit) {
val changesInShelveList = list.changes!!.map { it.change }
val cb = ChangesBuilder()
cb.changes()
val actualChanges = HashSet(changesInShelveList)
for (change in cb.changes) {
val found = actualChanges.find(change.changeMatcher)
assertNotNull("The change [$change] not found\n$changesInShelveList", found)
actualChanges.remove(found)
}
assertEmpty("There are unexpected changes in the shelvelist", actualChanges)
}
} | plugins/git4idea/tests/com/intellij/openapi/vcs/changes/shelf/GitShelveTest.kt | 1423541463 |
package org.http4k.lens
import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import org.http4k.core.Status
import org.http4k.lens.ParamMeta.StringParam
object BiDiLensContract {
val spec = BiDiLensSpec("location", StringParam, LensGet { _: String, str: String ->
if (str.isBlank()) emptyList() else listOf(str)
},
LensSet { _: String, values: List<String>, str: String -> values.fold(str, { memo, next -> memo + next }) })
fun <IN, T> checkContract(spec: BiDiLensSpec<IN, String, T>, tValue: T, validValue: IN, nullValue: IN, invalidValue: IN, s: IN, modifiedValue: IN, listModifiedValue: IN) {
//synonym methods
assertThat(spec.required("hello").extract(validValue), equalTo(tValue))
assertThat(spec.required("hello").inject(tValue, s), equalTo(modifiedValue))
val optionalLens = spec.optional("hello")
assertThat(optionalLens(validValue), equalTo(tValue))
assertThat(optionalLens.extract(validValue), equalTo(tValue))
assertThat((spec.map { it.toString() }.optional("hello"))(validValue), equalTo(tValue.toString()))
assertThat(optionalLens(nullValue), absent())
assertThat({ optionalLens(invalidValue) }, throws(lensFailureWith(optionalLens.invalid())))
assertThat(optionalLens(tValue, s), equalTo(modifiedValue))
val optionalMultiLens = spec.multi.optional("hello")
assertThat(optionalMultiLens(validValue), equalTo(listOf(tValue)))
assertThat((spec.map { it.toString() }.multi.optional("hello"))(validValue), equalTo(listOf(tValue.toString())))
assertThat(optionalMultiLens(nullValue), absent())
assertThat({ optionalMultiLens(invalidValue) }, throws(lensFailureWith(optionalLens.invalid())))
assertThat(optionalMultiLens(listOf(tValue, tValue), s), equalTo(listModifiedValue))
val requiredLens = spec.required("hello")
assertThat(requiredLens(validValue), equalTo(tValue))
assertThat((spec.map { it.toString() }.required("hello"))(validValue), equalTo(tValue.toString()))
assertThat({ requiredLens(nullValue) }, throws(lensFailureWith(requiredLens.missing())))
assertThat({ requiredLens(invalidValue) }, throws(lensFailureWith(requiredLens.invalid())))
assertThat(requiredLens(tValue, s), equalTo(modifiedValue))
val requiredMultiLens = spec.multi.required("hello")
assertThat(requiredMultiLens(validValue), equalTo(listOf(tValue)))
assertThat((spec.map { it.toString() }.multi.required("hello"))(validValue), equalTo(listOf(tValue.toString())))
assertThat({ requiredMultiLens(nullValue) }, throws(lensFailureWith(requiredLens.missing())))
assertThat({ requiredMultiLens(invalidValue) }, throws(lensFailureWith(requiredLens.invalid())))
assertThat(requiredMultiLens(listOf(tValue, tValue), s), equalTo(listModifiedValue))
val defaultedLens = spec.defaulted("hello", tValue)
assertThat(defaultedLens(validValue), equalTo(tValue))
assertThat((spec.map { it.toString() }.defaulted("hello", "world"))(validValue), equalTo(tValue.toString()))
assertThat(defaultedLens(nullValue), equalTo(tValue))
assertThat({ defaultedLens(invalidValue) }, throws(lensFailureWith(defaultedLens.invalid())))
assertThat(defaultedLens(tValue, s), equalTo(modifiedValue))
val defaultedMultiLens = spec.multi.defaulted("hello", listOf(tValue))
assertThat(defaultedMultiLens(validValue), equalTo(listOf(tValue)))
assertThat((spec.map { it.toString() }.multi.defaulted("hello", listOf(tValue.toString())))(validValue), equalTo(listOf(tValue.toString())))
assertThat(defaultedMultiLens(nullValue), equalTo(listOf(tValue)))
assertThat({ defaultedMultiLens(invalidValue) }, throws(lensFailureWith(defaultedMultiLens.invalid())))
assertThat(defaultedMultiLens(listOf(tValue, tValue), s), equalTo(listModifiedValue))
}
}
data class MyCustomBodyType(val value: String)
fun lensFailureWith(vararg failures: Failure, status: Status = Status.BAD_REQUEST) = object : Matcher<LensFailure> {
private val expectedList = failures.toList()
override val description: String = "LensFailure with status $status and failures $expectedList"
override fun invoke(actual: LensFailure): MatchResult =
if (actual.failures != expectedList) {
MatchResult.Mismatch("\n${actual.failures}\ninstead of \n$expectedList")
} else if (actual.status != status) {
MatchResult.Mismatch("${actual.status}\ninstead of $status")
} else
MatchResult.Match
}
| http4k-core/src/test/kotlin/org/http4k/lens/helpers.kt | 3142441966 |
// Copyright 2000-2019 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.vcs.changes.ignore.actions
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsRoot
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionAction
import com.intellij.openapi.vcs.changes.ignore.lang.IgnoreFileType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.vcsUtil.VcsImplUtil
import com.intellij.vcsUtil.VcsUtil
import kotlin.streams.toList
open class IgnoreFileActionGroup(private val ignoreFileType: IgnoreFileType) :
ActionGroup(
message("vcs.add.to.ignore.file.action.group.text", ignoreFileType.ignoreLanguage.filename),
message("vcs.add.to.ignore.file.action.group.description", ignoreFileType.ignoreLanguage.filename),
ignoreFileType.icon
), DumbAware {
private var actions: Collection<AnAction> = emptyList()
override fun update(e: AnActionEvent) {
val selectedFiles = getSelectedFiles(e)
val presentation = e.presentation
val project = e.getData(CommonDataKeys.PROJECT)
if (project == null) {
presentation.isVisible = false
return
}
val unversionedFiles = ScheduleForAdditionAction.getUnversionedFiles(e, project).toList()
if (unversionedFiles.isEmpty()) {
presentation.isVisible = false
return
}
val ignoreFiles =
filterSelectedFiles(project, selectedFiles).map { findSuitableIgnoreFiles(project, it) }.filterNot(Collection<*>::isEmpty)
val resultedIgnoreFiles = ignoreFiles.flatten().toHashSet()
for (files in ignoreFiles) {
resultedIgnoreFiles.retainAll(files) //only take ignore files which is suitable for all selected files
}
val additionalActions = createAdditionalActions(project, selectedFiles, unversionedFiles)
if (resultedIgnoreFiles.isNotEmpty()) {
actions = resultedIgnoreFiles.toActions(project, additionalActions.size)
}
else {
actions = listOfNotNull(createNewIgnoreFileAction(project, selectedFiles))
}
if (additionalActions.isNotEmpty()) {
actions += additionalActions
}
isPopup = actions.size > 1
presentation.isVisible = actions.isNotEmpty()
}
protected open fun createAdditionalActions(project: Project,
selectedFiles: List<VirtualFile>,
unversionedFiles: List<VirtualFile>): List<AnAction> = emptyList()
override fun canBePerformed(context: DataContext) = actions.size == 1
override fun actionPerformed(e: AnActionEvent) {
actions.firstOrNull()?.actionPerformed(e)
}
override fun getChildren(e: AnActionEvent?) = actions.toTypedArray()
private fun filterSelectedFiles(project: Project, files: List<VirtualFile>) =
files.filter { file ->
VcsUtil.isFileUnderVcs(project, VcsUtil.getFilePath(file)) && !ChangeListManager.getInstance(project).isIgnoredFile(file)
}
private fun findSuitableIgnoreFiles(project: Project, file: VirtualFile): Collection<VirtualFile> {
val fileParent = file.parent
return FileTypeIndex.getFiles(ignoreFileType, ProjectScope.getProjectScope(project))
.filter {
fileParent == it.parent || fileParent != null && it.parent != null && VfsUtil.isAncestor(it.parent, fileParent, false)
}
}
private fun Collection<VirtualFile>.toActions(project: Project, additionalActionsSize: Int): Collection<AnAction> {
val projectDir = project.guessProjectDir()
return map { file ->
IgnoreFileAction(file).apply {
templatePresentation.apply {
icon = ignoreFileType.icon
text = file.toTextRepresentation(project, projectDir, [email protected] + additionalActionsSize)
}
}
}
}
private fun createNewIgnoreFileAction(project: Project, selectedFiles: List<VirtualFile>): AnAction? {
val filename = ignoreFileType.ignoreLanguage.filename
val (rootVcs, commonIgnoreFileRoot) = selectedFiles.getCommonIgnoreFileRoot(project) ?: return null
if (rootVcs == null) return null
if (commonIgnoreFileRoot.findChild(filename) != null) return null
val ignoredFileContentProvider = VcsImplUtil.findIgnoredFileContentProvider(rootVcs) ?: return null
if (ignoredFileContentProvider.fileName != filename) return null
return CreateNewIgnoreFileAction(filename, commonIgnoreFileRoot).apply {
templatePresentation.apply {
icon = ignoreFileType.icon
text = message("vcs.add.to.ignore.file.action.group.text", filename)
}
}
}
private fun VirtualFile.toTextRepresentation(project: Project, projectDir: VirtualFile?, size: Int): String {
if (size == 1) return message("vcs.add.to.ignore.file.action.group.text", ignoreFileType.ignoreLanguage.filename)
val projectRootOrVcsRoot = projectDir ?: VcsUtil.getVcsRootFor(project, this) ?: return name
return VfsUtil.getRelativePath(this, projectRootOrVcsRoot) ?: name
}
private fun Collection<VirtualFile>.getCommonIgnoreFileRoot(project: Project): VcsRoot? {
val vcsManager = ProjectLevelVcsManager.getInstance(project)
val first = firstOrNull() ?: return null
val commonVcsRoot = vcsManager.getVcsRootObjectFor(first) ?: return null
if (first == commonVcsRoot.path) return null //trying to ignore vcs root itself
val haveCommonRoot = asSequence().drop(1).all {
it != commonVcsRoot && vcsManager.getVcsRootObjectFor(it) == commonVcsRoot
}
return if (haveCommonRoot) commonVcsRoot else null
}
private operator fun VcsRoot.component1() = vcs
private operator fun VcsRoot.component2() = path
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ignore/actions/IgnoreFileActionGroup.kt | 4161739657 |
@file:Suppress("PropertyName", "ReplaceArrayOfWithLiteral", "LocalVariableName", "FunctionName", "RemoveRedundantBackticks")
package org.redundent.generated
import org.redundent.kotlin.xml.*
open class `MethodName`(nodeName: String) : Node(nodeName)
fun `MethodName`.`type1`(__block__: `Type1`.() -> Unit) {
val `type1` = `Type1`("type1")
`type1`.apply(__block__)
this.addNode(`type1`)
}
fun `MethodName`.`type2`(__block__: `Type2`.() -> Unit) {
val `type2` = `Type2`("type2")
`type2`.apply(__block__)
this.addNode(`type2`)
}
fun `MethodName`.`type3`(__block__: `Type3`.() -> Unit) {
val `type3` = `Type3`("type3")
`type3`.apply(__block__)
this.addNode(`type3`)
}
fun `Method-Name`(__block__: `MethodName`.() -> Unit): `MethodName` {
val `Method-Name` = `MethodName`("Method-Name")
`Method-Name`.apply(__block__)
return `Method-Name`
}
open class `Type1`(nodeName: String) : Node(nodeName)
open class `Type2`(nodeName: String) : Node(nodeName)
open class `Type3`(nodeName: String) : Node(nodeName) | kotlin-xml-dsl-generator/src/test/resources/code/choice.kt | 3533876282 |
// TARGET_BACKEND: JVM
// WITH_RUNTIME
// FILE: test.kt
// LANGUAGE_VERSION: 1.1
import kotlin.test.*
inline fun String.extension() {}
fun box(): String {
J.s().extension() // NB no exception thrown
return "OK"
}
// FILE: J.java
public class J {
public static String s() { return null; }
} | backend.native/tests/external/codegen/box/javaInterop/notNullAssertions/nullabilityAssertionOnInlineFunExtensionReceiver_lv11.kt | 3377785044 |
package com.xenoage.zong.core.text
import com.xenoage.utils.Pt
import com.xenoage.utils.color.Color
import com.xenoage.utils.font.TextMetrics
import com.xenoage.utils.pxToMm_1_1
import com.xenoage.zong.symbols.Symbol
/**
* Musical [Symbol] within a formatted text.
*/
class FormattedTextSymbol(
val symbol: Symbol,
/** The size of the symbol in pt (relative to the ascent
* height defined in the symbol */
val size: Pt,
val color: Color
) : FormattedTextElement {
override val style: FormattedTextStyle = FormattedTextStyle(color = color)
val scaling: Float
/** The horizontal offset of the symbol, which must be added so that
* the symbol is left-aligned). */
val offsetX: Float
/** Measurements, with only ascent and width set. The other values are 0. */
override val metrics: TextMetrics
init {
//compute scaling
this.scaling = computeScaling(symbol, size)
//compute ascent and width
val ascent = symbol.ascentHeight * this.scaling //TODO: right?
val width = (symbol.rightBorder - symbol.leftBorder) * this.scaling
this.metrics = TextMetrics(ascent, 0f, 0f, width)
//horizontal offset: align symbol to the left side
this.offsetX = -symbol.leftBorder * this.scaling
}
override val length: Int
get() = 1
/** Returns the Unicode Object Replacement character, `\ufffc`. */
override val text: String
get() = "\ufffc"
override fun toString(): String =
"[symbol ${symbol.id}]"
companion object {
/**
* Computes and returns the scaling factor that is needed to draw
* the given symbol fitting to the given font size.
*/
private fun computeScaling(symbol: Symbol, size: Pt): Float =
//TODO: 0.65f is a constant that defines that the ascent has 65% of the complete hight
size * pxToMm_1_1 / symbol.ascentHeight * 0.65f
}
}
| core/src/com/xenoage/zong/core/text/FormattedTextSymbol.kt | 98566090 |
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.rule.attribute
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.context.MappingContext
import org.nd4j.samediff.frameworkimport.lookupIndexForArgDescriptor
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
abstract class SizeThresholdIntArrayIntIndexRule<
GRAPH_DEF: GeneratedMessageV3,
OP_DEF_TYPE: GeneratedMessageV3,
NODE_TYPE: GeneratedMessageV3,
ATTR_DEF : GeneratedMessageV3,
ATTR_VALUE_TYPE : GeneratedMessageV3,
TENSOR_TYPE : GeneratedMessageV3, DATA_TYPE>(mappingNamesToPerform: Map<String, String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>):
BaseAttributeExtractionRule<GRAPH_DEF, OP_DEF_TYPE, NODE_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, TENSOR_TYPE, DATA_TYPE>
(name = "sizethresholdarrayint", mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) where DATA_TYPE: ProtocolMessageEnum {
override fun convertAttributes(mappingCtx: MappingContext<GRAPH_DEF, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, ATTR_DEF, ATTR_VALUE_TYPE, DATA_TYPE>): List<OpNamespace.ArgDescriptor> {
val ret = ArrayList<OpNamespace.ArgDescriptor>()
for((k, v) in mappingNamesToPerform()) {
val descriptorForName = transformerArgs[k]
val inputArr = mappingCtx.irAttributeValueForNode(v).listIntValue()
val index = descriptorForName!![0].int32Value
val sizeThreshold = descriptorForName!![1].int64Value
val fallbackIndex = descriptorForName!![2].stringValue
val descriptorBuilder = OpNamespace.ArgDescriptor.newBuilder()
descriptorBuilder.name = v
descriptorBuilder.argType = OpNamespace.ArgDescriptor.ArgType.INT64
if(inputArr.size < sizeThreshold) {
descriptorBuilder.int64Value = inputArr[fallbackIndex.toInt()]
} else {
descriptorBuilder.int64Value = inputArr[index]
}
descriptorBuilder.argIndex = lookupIndexForArgDescriptor(
argDescriptorName = k,
opDescriptorName = mappingCtx.nd4jOpName(),
argDescriptorType = OpNamespace.ArgDescriptor.ArgType.INT64
)
ret.add(descriptorBuilder.build())
}
return ret
}
override fun acceptsInputType(argDescriptorType: AttributeValueType): Boolean {
return argDescriptorType == AttributeValueType.INT ||
argDescriptorType == AttributeValueType.STRING
}
override fun outputsType(argDescriptorType: List<OpNamespace.ArgDescriptor.ArgType>): Boolean {
return argDescriptorType.contains(OpNamespace.ArgDescriptor.ArgType.INT64)
}
} | nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/rule/attribute/SizeThresholdIntArrayIntIndexRule.kt | 1226933501 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.viewfinder
import android.content.Context
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraManager
import android.os.Build
import android.util.Size
import android.view.TextureView
import android.widget.FrameLayout
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import org.junit.After
import org.junit.Assume
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 21)
class TextureViewImplementationTest {
private var parent: FrameLayout? = null
private var implementation: TextureViewImplementation? = null
private var surfaceTexture: SurfaceTexture? = null
private var _surfaceRequest: ViewfinderSurfaceRequest? = null
private val surfaceRequest: ViewfinderSurfaceRequest
get() {
if (_surfaceRequest == null) {
val cameraManager = ApplicationProvider.getApplicationContext<Context>()
.getSystemService(Context.CAMERA_SERVICE
) as CameraManager
val cameraIds = cameraManager.cameraIdList
Assume.assumeTrue("No cameras found on device.", cameraIds.isNotEmpty())
val cameraId = cameraIds[0]
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
_surfaceRequest =
ViewfinderSurfaceRequest(ANY_SIZE, characteristics)
}
return _surfaceRequest!!
}
@Before
fun setUp() {
val mContext = InstrumentationRegistry.getInstrumentation().targetContext
surfaceTexture = SurfaceTexture(0)
parent = FrameLayout(mContext)
implementation = TextureViewImplementation(parent!!, ViewfinderTransformation())
}
@After
fun tearDown() {
if (_surfaceRequest != null) {
_surfaceRequest!!.willNotProvideSurface()
// Ensure all successful requests have their returned future finish.
_surfaceRequest!!.viewfinderSurface.close()
_surfaceRequest = null
}
}
@LargeTest
@Test(expected = TimeoutException::class)
@Throws(
Exception::class
)
fun doNotProvideSurface_ifSurfaceTextureNotAvailableYet() {
val request = surfaceRequest
implementation!!.onSurfaceRequested(request)
request.viewfinderSurface.surface[2, TimeUnit.SECONDS]
}
@Test
@Throws(Exception::class)
fun provideSurface_ifSurfaceTextureAvailable() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
val surfaceListenableFuture = surfaceRequest.viewfinderSurface.surface
implementation!!.mTextureView
?.surfaceTextureListener!!
.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
val surface = surfaceListenableFuture.get()
Truth.assertThat(surface).isNotNull()
}
@Test
@Throws(Exception::class)
fun doNotDestroySurface_whenSurfaceTextureBeingDestroyed_andCameraUsingSurface() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
val surfaceListenableFuture = surfaceRequest.viewfinderSurface.surface
val surfaceTextureListener = implementation!!.mTextureView?.surfaceTextureListener
surfaceTextureListener!!.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
surfaceListenableFuture.get()
Truth.assertThat(implementation!!.mSurfaceReleaseFuture).isNotNull()
Truth.assertThat(
surfaceTextureListener.onSurfaceTextureDestroyed(
surfaceTexture!!
)
).isFalse()
}
@Test
@LargeTest
@Throws(Exception::class)
fun destroySurface_whenSurfaceTextureBeingDestroyed_andCameraNotUsingSurface() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
val deferrableSurface = surfaceRequest.viewfinderSurface
val surfaceListenableFuture = deferrableSurface.surface
val surfaceTextureListener = implementation!!.mTextureView?.surfaceTextureListener
surfaceTextureListener!!.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
surfaceListenableFuture.get()
deferrableSurface.close()
// Wait enough time for surfaceReleaseFuture's listener to be called
Thread.sleep(1000)
Truth.assertThat(implementation!!.mSurfaceReleaseFuture).isNull()
Truth.assertThat(
surfaceTextureListener.onSurfaceTextureDestroyed(
surfaceTexture!!
)
).isTrue()
}
@Test
@LargeTest
@Throws(Exception::class)
fun releaseSurfaceTexture_afterSurfaceTextureDestroyed_andCameraNoLongerUsingSurface() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
val deferrableSurface = surfaceRequest.viewfinderSurface
val surfaceListenableFuture = deferrableSurface.surface
val surfaceTextureListener = implementation!!.mTextureView?.surfaceTextureListener
surfaceTextureListener!!.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
surfaceListenableFuture.get()
surfaceTextureListener.onSurfaceTextureDestroyed(surfaceTexture!!)
deferrableSurface.close()
// Wait enough time for surfaceReleaseFuture's listener to be called
Thread.sleep(1000)
Truth.assertThat(implementation!!.mSurfaceReleaseFuture).isNull()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Truth.assertThat(surfaceTexture!!.isReleased).isTrue()
}
}
@Test
@LargeTest
@Throws(Exception::class)
fun nullSurfaceCompleterAndSurfaceReleaseFuture_whenSurfaceProviderCancelled() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
// Cancel the request from the camera side
surfaceRequest.viewfinderSurface.surface.cancel(true)
// Wait enough time for mCompleter's cancellation listener to be called
Thread.sleep(1000)
Truth.assertThat(implementation!!.mSurfaceRequest).isNull()
Truth.assertThat(implementation!!.mSurfaceReleaseFuture).isNull()
}
@Test
@LargeTest
@Throws(Exception::class)
fun releaseSurface_whenSurfaceTextureDestroyed_andCameraSurfaceRequestIsCancelled() {
implementation!!.onSurfaceRequested(surfaceRequest)
// Cancel the request from the client side
surfaceRequest.willNotProvideSurface()
val surfaceTextureListener = implementation!!.mTextureView?.surfaceTextureListener
surfaceTextureListener!!.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
// Wait enough time for surfaceReleaseFuture's listener to be called.
Thread.sleep(1000)
Truth.assertThat(
surfaceTextureListener.onSurfaceTextureDestroyed(
surfaceTexture!!
)
).isTrue()
Truth.assertThat(implementation!!.mSurfaceTexture).isNull()
}
@Test
fun doNotCreateTextureView_beforeSensorOutputSizeKnown() {
Truth.assertThat(parent!!.childCount).isEqualTo(0)
}
@Test
@Throws(Exception::class)
fun resetSurfaceTextureOnDetachAndAttachWindow() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
val deferrableSurface = surfaceRequest.viewfinderSurface
val surfaceListenableFuture = deferrableSurface.surface
val surfaceTextureListener = implementation!!.mTextureView?.surfaceTextureListener
surfaceTextureListener!!.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
surfaceListenableFuture.get()
surfaceTextureListener.onSurfaceTextureDestroyed(surfaceTexture!!)
Truth.assertThat(implementation!!.mDetachedSurfaceTexture).isNotNull()
implementation!!.onDetachedFromWindow()
implementation!!.onAttachedToWindow()
Truth.assertThat(implementation!!.mDetachedSurfaceTexture).isNull()
Truth.assertThat(implementation!!.mTextureView?.surfaceTexture).isEqualTo(surfaceTexture)
}
@Test
@LargeTest
@Throws(Exception::class)
fun releaseDetachedSurfaceTexture_whenDeferrableSurfaceClose() {
val surfaceRequest = surfaceRequest
implementation!!.onSurfaceRequested(surfaceRequest)
val deferrableSurface = surfaceRequest.viewfinderSurface
val surfaceListenableFuture = deferrableSurface.surface
val surfaceTextureListener = implementation!!.mTextureView?.surfaceTextureListener
surfaceTextureListener!!.onSurfaceTextureAvailable(surfaceTexture!!, ANY_WIDTH, ANY_HEIGHT)
surfaceListenableFuture.get()
surfaceTextureListener.onSurfaceTextureDestroyed(surfaceTexture!!)
Truth.assertThat(implementation!!.mDetachedSurfaceTexture).isNotNull()
deferrableSurface.close()
// Wait enough time for surfaceReleaseFuture's listener to be called
Thread.sleep(1000)
Truth.assertThat(implementation!!.mSurfaceReleaseFuture).isNull()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Truth.assertThat(surfaceTexture!!.isReleased).isTrue()
}
Truth.assertThat(implementation!!.mDetachedSurfaceTexture).isNull()
}
@Test
fun keepOnlyLatestTextureView_whenGetSurfaceProviderCalledMultipleTimes() {
implementation!!.onSurfaceRequested(surfaceRequest)
Truth.assertThat(parent!!.getChildAt(0)).isInstanceOf(TextureView::class.java)
val textureView1 = parent!!.getChildAt(0) as TextureView
implementation!!.onSurfaceRequested(surfaceRequest)
Truth.assertThat(parent!!.getChildAt(0)).isInstanceOf(TextureView::class.java)
val textureView2 = parent!!.getChildAt(0) as TextureView
Truth.assertThat(textureView1).isNotSameInstanceAs(textureView2)
Truth.assertThat(parent!!.childCount).isEqualTo(1)
}
companion object {
private const val ANY_WIDTH = 1600
private const val ANY_HEIGHT = 1200
private val ANY_SIZE: Size by lazy { Size(ANY_WIDTH, ANY_HEIGHT) }
}
} | camera/camera-viewfinder/src/androidTest/java/androidx/camera/viewfinder/TextureViewImplementationTest.kt | 1339325815 |
// 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.roots.ui.configuration
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
interface SdkLookupProvider {
val progressIndicator: ProgressIndicator?
fun newLookupBuilder(): SdkLookupBuilder
fun getSdkInfo(): SdkInfo
fun getSdk(): Sdk?
fun blockingGetSdk(): Sdk?
sealed class SdkInfo {
object Undefined : SdkInfo()
object Unresolved : SdkInfo()
data class Resolving(val name: String, val versionString: String?, val homePath: String?) : SdkInfo()
data class Resolved(val name: String, val versionString: String?, val homePath: String?) : SdkInfo()
}
interface Id
companion object {
@JvmStatic
fun getInstance(project: Project, providerId: Id): SdkLookupProvider {
return SdkLookupProviders.getProvider(project, providerId)
}
}
} | platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SdkLookupProvider.kt | 3683706309 |
// WITH_STDLIB
// PARAM_DESCRIPTOR: value-parameter it: kotlin.Int defined in foo.<anonymous>
// PARAM_TYPES: kotlin.Int
fun foo(a: Int): Int {
a.let {
<selection>if (it > 0) return it else return@foo -it</selection>
}
return 0
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/controlFlow/definiteReturns/labeledAndUnlabeledReturn1.kt | 2818569234 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem
import kotlinx.collections.immutable.toImmutableList
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingDefaultValue
import org.jetbrains.kotlin.tools.projectWizard.core.service.BuildSystemAvailabilityWizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.FileSystemWizardService
import org.jetbrains.kotlin.tools.projectWizard.core.service.ProjectImportingWizardService
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.library.MavenArtifact
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.BuildFilePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.printBuildFile
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.DefaultRepository
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repository
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles
abstract class BuildSystemPlugin(context: Context) : Plugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "buildSystem"
val type by enumSetting<BuildSystemType>(
KotlinNewProjectWizardBundle.message("plugin.buildsystem.setting.type"),
GenerationPhase.FIRST_STEP,
) {
fun Reader.isBuildSystemAvailable(type: BuildSystemType): Boolean =
service<BuildSystemAvailabilityWizardService>().isAvailable(type)
isSavable = true
values = BuildSystemType.ALL_BY_PRIORITY.toImmutableList()
defaultValue = SettingDefaultValue.Dynamic {
values.firstOrNull { isBuildSystemAvailable(it) }
}
filter = { _, type -> isBuildSystemAvailable(type) }
validate { buildSystemType ->
val projectKind = KotlinPlugin.projectKind.notRequiredSettingValue ?: ProjectKind.Multiplatform
if (buildSystemType in projectKind.supportedBuildSystems && isBuildSystemAvailable(buildSystemType)) {
ValidationResult.OK
} else {
ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message(
"plugin.buildsystem.setting.type.error.wrong.project.kind",
projectKind.shortName.capitalize(),
buildSystemType.fullText
)
)
}
}
tooltipText = KotlinNewProjectWizardBundle.message("plugin.buildsystem.setting.type.tooltip")
}
val buildSystemData by property<List<BuildSystemData>>(emptyList())
val buildFiles by listProperty<BuildFileIR>()
val pluginRepositoreis by listProperty<Repository>()
val takeRepositoriesFromDependencies by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(createModules)
runAfter(TemplatesPlugin.postApplyTemplatesToModules)
withAction {
updateBuildFiles { buildFile ->
val dependenciesOfModule = buildList<LibraryDependencyIR> {
buildFile.modules.modules.forEach { module ->
if (module is SingleplatformModuleIR) module.sourcesets.forEach { sourceset ->
+sourceset.irs.filterIsInstance<LibraryDependencyIR>()
}
+module.irs.filterIsInstance<LibraryDependencyIR>()
}
}
val repositoriesToAdd = dependenciesOfModule.mapNotNull { dependency ->
dependency.artifact.safeAs<MavenArtifact>()?.repository?.let(::RepositoryIR)
}
buildFile.withIrs(repositoriesToAdd).asSuccess()
}
}
}
val createModules by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(StructurePlugin.createProjectDir)
withAction {
val fileSystem = service<FileSystemWizardService>()
val data = buildSystemData.propertyValue.first { it.type == buildSystemType }
val buildFileData = data.buildFileData ?: return@withAction UNIT_SUCCESS
buildFiles.propertyValue.mapSequenceIgnore { buildFile ->
fileSystem.createFile(
buildFile.directoryPath / buildFileData.buildFileName,
buildFileData.createPrinter().printBuildFile { buildFile.render(this) }
)
}
}
}
val importProject by pipelineTask(GenerationPhase.PROJECT_IMPORT) {
runAfter(createModules)
withAction {
val data = buildSystemData.propertyValue.first { it.type == buildSystemType }
service<ProjectImportingWizardService> { service -> service.isSuitableFor(data.type) }
.importProject(this, StructurePlugin.projectPath.settingValue, allIRModules, buildSystemType)
}
}
}
override val settings: List<PluginSetting<*, *>> = listOf(
type,
)
override val pipelineTasks: List<PipelineTask> = listOf(
takeRepositoriesFromDependencies,
createModules,
importProject,
)
override val properties: List<Property<*>> = listOf(
buildSystemData,
buildFiles,
pluginRepositoreis
)
}
fun Reader.getPluginRepositoriesWithDefaultOnes(): List<Repository> {
val allRepositories = BuildSystemPlugin.pluginRepositoreis.propertyValue + buildSystemType.getDefaultPluginRepositories()
return allRepositories.filterOutOnlyDefaultPluginRepositories(buildSystemType)
}
private fun List<Repository>.filterOutOnlyDefaultPluginRepositories(buildSystem: BuildSystemType): List<Repository> {
val isAllDefault = all { it.isDefaultPluginRepository(buildSystem) }
return if (isAllDefault) emptyList() else this
}
private fun Repository.isDefaultPluginRepository(buildSystem: BuildSystemType) =
this in buildSystem.getDefaultPluginRepositories()
fun PluginSettingsOwner.addBuildSystemData(data: BuildSystemData) = pipelineTask(GenerationPhase.PREPARE) {
runBefore(BuildSystemPlugin.createModules)
withAction {
BuildSystemPlugin.buildSystemData.addValues(data)
}
}
data class BuildSystemData(
val type: BuildSystemType,
val buildFileData: BuildFileData?
)
data class BuildFileData(
val createPrinter: () -> BuildFilePrinter,
@NonNls val buildFileName: String
)
enum class BuildSystemType(
@Nls override val text: String,
@NonNls val id: String, // used for FUS, should never be changed
val fullText: String = text
) : DisplayableSettingItem {
GradleKotlinDsl(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.gradle.kotlin"),
id = "gradleKotlin"
),
GradleGroovyDsl(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.gradle.groovy"),
id = "gradleGroovy"
),
Jps(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.intellij"),
id = "jps",
fullText = KotlinNewProjectWizardBundle.message("buildsystem.type.intellij.full")
),
Maven(
text = KotlinNewProjectWizardBundle.message("buildsystem.type.maven"),
id = "maven"
);
override val greyText: String?
get() = null
companion object {
val ALL_GRADLE = setOf(GradleKotlinDsl, GradleGroovyDsl)
val ALL_BY_PRIORITY = setOf(GradleKotlinDsl, GradleGroovyDsl, Maven, Jps)
}
}
val BuildSystemType.isGradle
get() = this == BuildSystemType.GradleGroovyDsl
|| this == BuildSystemType.GradleKotlinDsl
val Reader.allIRModules
get() = BuildSystemPlugin.buildFiles.propertyValue.flatMap { buildFile ->
buildFile.modules.modules
}
val Writer.allModulesPaths
get() = BuildSystemPlugin.buildFiles.propertyValue.flatMap { buildFile ->
val paths = when (val structure = buildFile.modules) {
is MultiplatformModulesStructureIR -> listOf(buildFile.directoryPath)
else -> structure.modules.map { it.path }
}
paths.mapNotNull { path ->
projectPath.relativize(path)
.takeIf { it.toString().isNotBlank() }
?.toList()
?.takeIf { it.isNotEmpty() }
}
}
fun BuildSystemType.getDefaultPluginRepositories(): List<DefaultRepository> = when (this) {
BuildSystemType.GradleKotlinDsl, BuildSystemType.GradleGroovyDsl -> listOf(DefaultRepository.GRADLE_PLUGIN_PORTAL)
BuildSystemType.Maven -> listOf(DefaultRepository.MAVEN_CENTRAL)
BuildSystemType.Jps -> emptyList()
}
val Reader.buildSystemType: BuildSystemType
get() = BuildSystemPlugin.type.settingValue
| plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/BuildSystemPlugin.kt | 181532291 |
package defaultImpls;
interface AllAbstract {
val c: Int
fun <T> f(t: T): T
val g: Int
var g2: String
}
interface NonAbstractFun {
fun f() {
}
}
interface NonAbstractFunWithExpressionBody {
fun f() = 3
}
interface NonAbstractProperty {
val c: Int get() = 3
}
interface NonAbstractPropertyWithBody {
val c: Int get() {
return 3
}
} | plugins/kotlin/completion/tests/testData/injava/mockLib/defaultImpls/defaultImpls.kt | 2193967162 |
fun test(s: String?) {
val x: Any = if (s == null) {
""
}
else {
<caret>Unit
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantUnitExpression/redundant4.kt | 1892757722 |
/*
* Copyright 2016-2021 Julien Guerinet
*
* 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.guerinet.room.converter
import kotlinx.datetime.LocalDate
/**
* Converts [LocalDate]s to Strings and vice-versa for Room
* @author Julien Guerinet
* @since 4.0.0
*/
class LocalDateConverter : BaseConverter<LocalDate>() {
override fun objectFromString(value: String): LocalDate? = try {
LocalDate.parse(value)
} catch (e: Exception) {
null
}
}
| room/src/main/java/converter/LocalDateConverter.kt | 311286581 |
package dependency
@Deprecated("", ReplaceWith("dependency.NewAnnotation"))
annotation class OldAnnotation
annotation class NewAnnotation()
@NewAnnotation
class C | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/classUsages/wholeProject/noParenthesesAnnotation.after.Declaration.kt | 1347228346 |
fun test(some: (Int) -> Int) {
}
fun foo() {
test() {
// Some comment
it
}
test() {
// val a = 42
}
test() {
/*
val a = 42
*/
}
test() {
/*
val a = 42
*/
}
test() {
// val a = 42
val b = 44
}
}
val s = Shadow { -> // wdwd
val a = 42
}
val s2 = Shadow { // wdwd
val a = 42
}
val s3 = Shadow(fun() { // wdwd
val a = 42
})
val s4 = Shadow(fun() { /* s */
val a = 42
})
val s5 = Shadow { ->
// wdwd
val a = 42
}
val s6 = Shadow {
// wdwd
val a = 42
}
val s7 = Shadow(fun() {
// wdwd
val a = 42
})
val s8 = Shadow(fun() {
// wdwd
val a = 42
})
val s9 = Shadow { -> /* s */
val a = 42
}
class Shadow(callback: () -> Unit)
| plugins/kotlin/idea/tests/testData/formatter/CommentInFunctionLiteral.kt | 2436634601 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution.test.runner
import com.intellij.execution.JavaRunConfigurationExtensionManager
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.plugins.gradle.execution.test.runner.TestTasksChooser.Companion.contextWithLocationName
import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration
import org.jetbrains.plugins.gradle.util.GradleCommandLine.Companion.parse
import org.jetbrains.plugins.gradle.util.GradleCommandLine.TasksAndArguments
import org.jetbrains.plugins.gradle.util.TasksToRun
import org.jetbrains.plugins.gradle.util.createTestWildcardFilter
import java.util.*
import java.util.function.Consumer
abstract class AbstractGradleTestRunConfigurationProducer<E : PsiElement, Ex : PsiElement> : GradleTestRunConfigurationProducer() {
protected abstract fun getElement(context: ConfigurationContext): E?
protected abstract fun getLocationName(context: ConfigurationContext, element: E): String
protected abstract fun suggestConfigurationName(context: ConfigurationContext, element: E, chosenElements: List<Ex>): String
protected abstract fun chooseSourceElements(context: ConfigurationContext, element: E, onElementsChosen: Consumer<List<Ex>>)
private fun chooseSourceElements(context: ConfigurationContext, element: E, onElementsChosen: (List<Ex>) -> Unit) {
chooseSourceElements(context, element, Consumer { onElementsChosen(it) })
}
protected abstract fun getAllTestsTaskToRun(context: ConfigurationContext, element: E, chosenElements: List<Ex>): List<TestTasksToRun>
private fun getAllTasksAndArguments(context: ConfigurationContext, element: E, chosenElements: List<Ex>): List<TasksAndArguments> {
return getAllTestsTaskToRun(context, element, chosenElements)
.map { it.toTasksAndArguments() }
}
override fun doSetupConfigurationFromContext(
configuration: GradleRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
val project = context.project ?: return false
val module = context.module ?: return false
val externalProjectPath = resolveProjectPath(module) ?: return false
val location = context.location ?: return false
val element = getElement(context) ?: return false
val allTasksAndArguments = getAllTasksAndArguments(context, element, emptyList())
val tasksAndArguments = allTasksAndArguments.firstOrNull() ?: return false
sourceElement.set(element)
configuration.name = suggestConfigurationName(context, element, emptyList())
setUniqueNameIfNeeded(project, configuration)
configuration.settings.externalProjectPath = externalProjectPath
configuration.settings.taskNames = tasksAndArguments.toList()
configuration.settings.scriptParameters = ""
JavaRunConfigurationExtensionManager.instance.extendCreatedConfiguration(configuration, location)
return true
}
override fun doIsConfigurationFromContext(
configuration: GradleRunConfiguration,
context: ConfigurationContext
): Boolean {
val module = context.module ?: return false
val externalProjectPath = resolveProjectPath(module) ?: return false
val element = getElement(context) ?: return false
val allTasksAndArguments = getAllTasksAndArguments(context, element, emptyList())
val tasksAndArguments = configuration.commandLine.tasksAndArguments.toList()
return externalProjectPath == configuration.settings.externalProjectPath &&
tasksAndArguments.isNotEmpty() && allTasksAndArguments.isNotEmpty() &&
isConsistedFrom(tasksAndArguments, allTasksAndArguments.map { it.toList() })
}
override fun onFirstRun(configuration: ConfigurationFromContext, context: ConfigurationContext, startRunnable: Runnable) {
val project = context.project
val element = getElement(context)
if (project == null || element == null) {
LOG.warn("Cannot extract configuration data from context, uses raw run configuration")
super.onFirstRun(configuration, context, startRunnable)
return
}
val runConfiguration = configuration.configuration as GradleRunConfiguration
val dataContext = contextWithLocationName(context.dataContext, getLocationName(context, element))
chooseSourceElements(context, element) { elements ->
val allTestsToRun = getAllTestsTaskToRun(context, element, elements)
.groupBy { it.tasksToRun.testName }
.mapValues { it.value }
testTasksChooser.chooseTestTasks(project, dataContext, allTestsToRun) { chosenTestsToRun ->
val chosenTasksAndArguments = chosenTestsToRun.flatten()
.groupBy { it.tasksToRun }
.mapValues { it.value.map(TestTasksToRun::testFilter).toSet() }
.map { createTasksAndArguments(it.key, it.value) }
runConfiguration.name = suggestConfigurationName(context, element, elements)
setUniqueNameIfNeeded(project, runConfiguration)
runConfiguration.settings.taskNames = chosenTasksAndArguments.flatMap { it.toList() }
runConfiguration.settings.scriptParameters = if (chosenTasksAndArguments.size > 1) "--continue" else ""
super.onFirstRun(configuration, context, startRunnable)
}
}
}
/**
* Checks that [list] can be represented by sequence from all or part of [subLists].
*
* For example:
*
* `[1, 2, 3, 4] is not consisted from [1, 2]`
*
* `[1, 2, 3, 4] is consisted from [1, 2] and [3, 4]`
*
* `[1, 2, 3, 4] is consisted from [1, 2], [3, 4] and [1, 2, 3]`
*
* `[1, 2, 3, 4] is not consisted from [1, 2, 3] and [3, 4]`
*/
private fun isConsistedFrom(list: List<String>, subLists: List<List<String>>): Boolean {
val reducer = ArrayList(list)
val sortedTiles = subLists.sortedByDescending { it.size }
for (tile in sortedTiles) {
val size = tile.size
val index = indexOfSubList(reducer, tile)
if (index >= 0) {
val subReducer = reducer.subList(index, index + size)
subReducer.clear()
subReducer.add(null)
}
}
return ContainerUtil.and(reducer) { it == null }
}
private fun indexOfSubList(list: List<String>, subList: List<String>): Int {
for (i in list.indices) {
if (i + subList.size <= list.size) {
var hasSubList = true
for (j in subList.indices) {
if (list[i + j] != subList[j]) {
hasSubList = false
break
}
}
if (hasSubList) {
return i
}
}
}
return -1
}
private fun createTasksAndArguments(tasksToRun: TasksToRun, testFilters: Collection<String>): TasksAndArguments {
val commandLineBuilder = StringJoiner(" ")
for (task in tasksToRun) {
commandLineBuilder.add(task.escapeIfNeeded())
}
if (createTestWildcardFilter() !in testFilters) {
for (testFilter in testFilters) {
if (StringUtil.isNotEmpty(testFilter)) {
commandLineBuilder.add(testFilter)
}
}
}
val commandLine = commandLineBuilder.toString()
return parse(commandLine).tasksAndArguments
}
fun TestTasksToRun.toTasksAndArguments() = createTasksAndArguments(tasksToRun, listOf(testFilter))
class TestTasksToRun(val tasksToRun: TasksToRun, val testFilter: String)
} | plugins/gradle/java/src/execution/test/runner/AbstractGradleTestRunConfigurationProducer.kt | 2491702186 |
class C{}
fun foo(c: C){}
fun foo(c: C, i: Int){}
fun foo() {
foo(<caret>
}
| plugins/kotlin/completion/tests/testData/handlers/smart/MergeTail1.kt | 3829691726 |
// AFTER-WARNING: Parameter 'initialText' is never used
annotation class Annotation1(val a: Int = 0)
annotation class Annotation2(val a: Int = 0)
annotation class Annotation3(val a: Int = 0)
class TestClass(@Annotation1(42) @Annotation3(42) initialText: String = "LoremIpsum") {
private @Annotation1(42) @field:Annotation2(42) val <caret>text = "dolor sit amet"
} | plugins/kotlin/idea/tests/testData/intentions/movePropertyToConstructor/withoutMatchingParameter.kt | 2074013745 |
package test
open class BaseProtectedConstructor protected constructor()
internal class DerivedSamePackage : BaseProtectedConstructor() | plugins/kotlin/j2k/new/tests/testData/newJ2k/protected/onlyProtectedConstructor.kt | 3022009293 |
// 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.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase
import com.intellij.testFramework.UsefulTestCase.assertEmpty
import com.intellij.testFramework.UsefulTestCase.assertInstanceOf
import com.intellij.workspaceModel.storage.impl.ChangeEntry
import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl
import com.intellij.workspaceModel.storage.impl.assertConsistency
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.junit.Assert.*
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
private fun WorkspaceEntityStorage.singleParent() = entities(ParentEntity::class.java).single()
private fun WorkspaceEntityStorage.singleChild() = entities(ChildEntity::class.java).single()
class ReferencesInStorageTest {
private lateinit var virtualFileManager: VirtualFileUrlManager
@Before
fun setUp() {
//ClassToIntConverter.clear()
virtualFileManager = VirtualFileUrlManagerImpl()
}
@Test
fun `add entity`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity("foo"))
builder.assertConsistency()
assertEquals("foo", child.parent.parentProperty)
assertEquals(child, builder.singleChild())
assertEquals(child.parent, builder.singleParent())
assertEquals(child, child.parent.children.single())
}
@Test
fun `add entity via diff`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity("foo")
val diff = createBuilderFrom(builder.toStorage())
diff.addChildEntity(parentEntity = parentEntity)
builder.addDiff(diff)
builder.assertConsistency()
val child = builder.singleChild()
assertEquals("foo", child.parent.parentProperty)
assertEquals(child, builder.singleChild())
assertEquals(child.parent, builder.singleParent())
assertEquals(child, child.parent.children.single())
}
@Test
fun `add remove reference inside data class`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val parent2 = builder.addParentEntity("parent2")
builder.assertConsistency()
val child = builder.addChildEntity(parent1, "child", DataClass("data", builder.createReference(parent2)))
builder.assertConsistency()
assertEquals(child, parent1.children.single())
assertEquals(emptyList<ChildEntity>(), parent2.children.toList())
assertEquals("parent1", child.parent.parentProperty)
assertEquals("parent2", child.dataClass!!.parent.resolve(builder)?.parentProperty)
assertEquals(setOf(parent1, parent2), builder.entities(ParentEntity::class.java).toSet())
builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = null
}
builder.assertConsistency()
assertEquals(setOf(parent1, parent2), builder.entities(ParentEntity::class.java).toSet())
}
@Test
fun `remove child entity`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.assertConsistency()
val child = builder.addChildEntity(parent)
builder.assertConsistency()
builder.removeEntity(child)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ChildEntity>(), parent.children.toList())
assertEquals(parent, builder.singleParent())
}
@Test
fun `remove parent entity`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
builder.removeEntity(child.parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity via diff`() {
val builder = createEmptyBuilder()
val oldParent = builder.addParentEntity("oldParent")
val oldChild = builder.addChildEntity(oldParent, "oldChild")
val diff = createEmptyBuilder()
val parent = diff.addParentEntity("newParent")
diff.addChildEntity(parent, "newChild")
diff.removeEntity(parent)
diff.assertConsistency()
builder.addDiff(diff)
builder.assertConsistency()
assertEquals(listOf(oldChild), builder.entities(ChildEntity::class.java).toList())
assertEquals(listOf(oldParent), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity with two children`() {
val builder = createEmptyBuilder()
val child1 = builder.addChildEntity(builder.addParentEntity())
builder.addChildEntity(parentEntity = child1.parent)
builder.removeEntity(child1.parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity in DAG`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
val child = builder.addChildEntity(parentEntity = parent)
builder.addChildChildEntity(parent, child)
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
// UNSUPPORTED
/*
@Test
fun `remove parent entity referenced via data class`() {
val builder = PEntityStorageBuilder.create()
val parent1 = builder.addPParentEntity("parent1")
val parent2 = builder.addPParentEntity("parent2")
builder.addPChildEntity(parent1, "child", PDataClass("data", builder.createReference(parent2)))
builder.removeEntity(parent2)
builder.assertConsistency()
assertEquals(emptyList<PChildEntity>(), builder.entities(PChildEntity::class.java).toList())
assertEquals(listOf(parent1), builder.entities(PParentEntity::class.java).toList())
assertEquals(emptyList<PChildEntity>(), parent1.children.toList())
}
*/
@Test
fun `remove parent entity referenced via two paths`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.addChildEntity(parent, "child", DataClass("data", builder.createReference(parent)))
builder.assertConsistency()
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `remove parent entity referenced via two paths via entity ref`() {
val builder = createEmptyBuilder()
val parent = builder.addParentEntity()
builder.addChildEntity(parent, "child", DataClass("data", parent.createReference()))
builder.assertConsistency()
builder.removeEntity(parent)
builder.assertConsistency()
assertEquals(emptyList<ChildEntity>(), builder.entities(ChildEntity::class.java).toList())
assertEquals(emptyList<ParentEntity>(), builder.entities(ParentEntity::class.java).toList())
}
@Test
fun `modify parent property`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newParent = builder.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", newParent.parentProperty)
assertEquals(newParent, builder.singleParent())
assertEquals(newParent, child.parent)
assertEquals(child, newParent.children.single())
assertEquals("parent", oldParent.parentProperty)
}
@Test
fun `modify parent property via diff`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val diff = createBuilderFrom(builder)
diff.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.addDiff(diff)
builder.assertConsistency()
val newParent = builder.singleParent()
assertEquals("changed", newParent.parentProperty)
assertEquals(newParent, builder.singleParent())
assertEquals(newParent, child.parent)
assertEquals(child, newParent.children.single())
assertEquals("parent", oldParent.parentProperty)
}
@Test
fun `modify child property`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
childProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", newChild.childProperty)
assertEquals(oldParent, builder.singleParent())
assertEquals(newChild, builder.singleChild())
assertEquals(oldParent, newChild.parent)
assertEquals(oldParent, child.parent)
assertEquals(newChild, oldParent.children.single())
assertEquals("child", child.childProperty)
}
@Test
fun `modify reference to parent`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val oldParent = child.parent
val newParent = builder.addParentEntity("new")
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
parent = newParent
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals(setOf(oldParent, newParent), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.parent)
assertEquals(newChild, newParent.children.single())
assertEquals(newParent, child.parent)
//assertEquals(oldParent, child.parent) // ProxyBasedStore behaviour
assertEquals(emptyList<ChildEntity>(), oldParent.children.toList())
}
@Test
fun `modify reference to parent via data class`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val oldParent = builder.addParentEntity("parent2")
val child = builder.addChildEntity(parent1, "child", DataClass("data", builder.createReference(oldParent)))
val newParent = builder.addParentEntity("new")
builder.assertConsistency()
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data2", builder.createReference(newParent))
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals("data2", newChild.dataClass!!.stringProperty)
assertEquals(setOf(oldParent, newParent, parent1), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.dataClass.parent.resolve(builder))
assertEquals(oldParent, child.dataClass!!.parent.resolve(builder))
}
@Test
fun `modify reference to parent via data class via entity ref`() {
val builder = createEmptyBuilder()
val parent1 = builder.addParentEntity("parent1")
val oldParent = builder.addParentEntity("parent2")
val child = builder.addChildEntity(parent1, "child", DataClass("data", oldParent.createReference()))
val newParent = builder.addParentEntity("new")
builder.assertConsistency()
val newChild = builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data2", newParent.createReference())
}
builder.assertConsistency()
assertEquals("child", newChild.childProperty)
assertEquals("data2", newChild.dataClass!!.stringProperty)
assertEquals(setOf(oldParent, newParent, parent1), builder.entities(ParentEntity::class.java).toSet())
assertEquals(newChild, builder.singleChild())
assertEquals(newParent, newChild.dataClass.parent.resolve(builder))
assertEquals(oldParent, child.dataClass!!.parent.resolve(builder))
}
@Test
fun `builder from storage`() {
val storage = createEmptyBuilder().apply {
addChildEntity(addParentEntity())
}.toStorage()
storage.assertConsistency()
assertEquals("parent", storage.singleParent().parentProperty)
val builder = createBuilderFrom(storage)
builder.assertConsistency()
val oldParent = builder.singleParent()
assertEquals("parent", oldParent.parentProperty)
val newParent = builder.modifyEntity(ModifiableParentEntity::class.java, oldParent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", builder.singleParent().parentProperty)
assertEquals("parent", storage.singleParent().parentProperty)
assertEquals(newParent, builder.singleChild().parent)
assertEquals("changed", builder.singleChild().parent.parentProperty)
assertEquals("parent", storage.singleChild().parent.parentProperty)
val parent2 = builder.addParentEntity("parent2")
builder.modifyEntity(ModifiableChildEntity::class.java, builder.singleChild()) {
dataClass = DataClass("data", builder.createReference(parent2))
}
builder.assertConsistency()
assertEquals("parent", storage.singleParent().parentProperty)
assertEquals(null, storage.singleChild().dataClass)
assertEquals("data", builder.singleChild().dataClass!!.stringProperty)
assertEquals(parent2, builder.singleChild().dataClass!!.parent.resolve(builder))
assertEquals(setOf(parent2, newParent), builder.entities(ParentEntity::class.java).toSet())
}
@Test
fun `storage from builder`() {
val builder = createEmptyBuilder()
val child = builder.addChildEntity(builder.addParentEntity())
val snapshot = builder.toStorage()
builder.assertConsistency()
builder.modifyEntity(ModifiableParentEntity::class.java, child.parent) {
parentProperty = "changed"
}
builder.assertConsistency()
assertEquals("changed", builder.singleParent().parentProperty)
assertEquals("changed", builder.singleChild().parent.parentProperty)
assertEquals("parent", snapshot.singleParent().parentProperty)
assertEquals("parent", snapshot.singleChild().parent.parentProperty)
val parent2 = builder.addParentEntity("new")
builder.modifyEntity(ModifiableChildEntity::class.java, child) {
dataClass = DataClass("data", builder.createReference(parent2))
}
builder.assertConsistency()
assertEquals("parent", snapshot.singleParent().parentProperty)
assertEquals(null, snapshot.singleChild().dataClass)
assertEquals(parent2, builder.singleChild().dataClass!!.parent.resolve(builder))
}
@Test
fun `modify optional parent property`() {
val builder = createEmptyBuilder()
val child = builder.addChildWithOptionalParentEntity(null)
assertNull(child.optionalParent)
val newParent = builder.addParentEntity()
assertEquals(emptyList<ChildWithOptionalParentEntity>(), newParent.optionalChildren.toList())
val newChild = builder.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, child) {
optionalParent = newParent
}
builder.assertConsistency()
assertEquals(newParent, newChild.optionalParent)
assertEquals(newChild, newParent.optionalChildren.single())
val veryNewChild = builder.modifyEntity(ModifiableChildWithOptionalParentEntity::class.java, newChild) {
optionalParent = null
}
assertNull(veryNewChild.optionalParent)
assertEquals(emptyList<ChildWithOptionalParentEntity>(), newParent.optionalChildren.toList())
}
@Test
fun `removing one to one parent`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.removeEntity(parentEntity)
val parents = builder.entities(OoParentEntity::class.java).toList()
val children = builder.entities(OoChildEntity::class.java).toList()
assertEmpty(parents)
assertEmpty(children)
}
@Test
fun `add one to one entities`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.assertConsistency()
}
@Test
fun `test replace by source one to one nullable ref with parent persistent Id and child without it`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
@Ignore("Skip because of unstable rbs")
fun `test replace by source one to one ref with parent persistent Id and child with persistent Id`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "childOne")
builder.addOoChildAlsoWithPidEntity(parentEntity, "childTwo")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "childOneOne", source = AnotherSource)
newBuilder.addOoChildAlsoWithPidEntity(parentEntity, "childTwo", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val firstChild = builder.entities(OoChildForParentWithPidEntity::class.java).single()
val secondChild = builder.entities(OoChildAlsoWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, firstChild.entitySource)
assertEquals(AnotherSource, secondChild.entitySource)
assertEquals("childOneOne", firstChild.childProperty)
assertEquals(parent, firstChild.parent)
assertEquals("childTwo", secondChild.childProperty)
assertEquals(parent, secondChild.parent)
}
@Test
fun `test replace by source with parent persistent Id and without children`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(MySource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
fun `test replace by source one to one ref with parent persistent Id and child without it and parent entity source intersection`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent", AnotherSource)
builder.addOoChildForParentWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
fun `test replace by source one to one ref with parent persistent Id and child without it and child entity source intersection`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithPidEntity("parent")
builder.addOoChildForParentWithPidEntity(parentEntity, "child", AnotherSource)
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithPidEntity("parent", AnotherSource)
newBuilder.addOoChildForParentWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val parent = builder.entities(OoParentWithPidEntity::class.java).single()
val child = builder.entities(OoChildForParentWithPidEntity::class.java).single()
assertEquals(AnotherSource, parent.entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals(child, parent.childOne)
}
@Test
fun `test replace by source one to one nullable ref with child persistent Id and parent without it`() {
val builder = createEmptyBuilder()
var parentEntity = builder.addOoParentWithoutPidEntity("parent")
builder.addOoChildWithPidEntity(parentEntity, "child")
builder.checkConsistency()
val newBuilder = createEmptyBuilder()
parentEntity = newBuilder.addOoParentWithoutPidEntity("parent", AnotherSource)
newBuilder.addOoChildWithPidEntity(parentEntity, "child", source = AnotherSource)
newBuilder.checkConsistency()
builder.replaceBySource({ it is AnotherSource }, newBuilder)
builder.checkConsistency()
val listOfParent = builder.entities(OoParentWithoutPidEntity::class.java).toList()
val child = builder.entities(OoChildWithPidEntity::class.java).single()
assertEquals(2, listOfParent.size)
assertEquals(MySource, listOfParent[0].entitySource)
assertEquals(AnotherSource, listOfParent[1].entitySource)
assertEquals(AnotherSource, child.entitySource)
assertEquals("child", child.childProperty)
assertEquals(listOfParent[1], child.parent)
}
@Test
fun `add child to a single parent`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildEntity(parentEntity)
builder.addOoChildEntity(parentEntity)
builder.assertConsistency()
// Child has a not-null parent, so we remove it one field replace
val children = builder.entities(OoChildEntity::class.java).toList()
assertEquals(1, children.size)
}
@Test
fun `double child adding`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentEntity()
builder.addOoChildWithNullableParentEntity(parentEntity)
builder.addOoChildWithNullableParentEntity(parentEntity)
builder.assertConsistency()
// Child has a nullable parent. So we just unlink a parent from one of the entities
val children = builder.entities(OoChildWithNullableParentEntity::class.java).toList()
assertEquals(2, children.size)
if (children[0].parent == null) {
assertNotNull(children[1].parent)
}
else {
assertNull(children[1].parent)
}
}
@Test
fun `remove children`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity()
val childEntity = builder.addChildEntity(parentEntity)
builder.changeLog.clear()
builder.modifyEntity(ModifiableParentEntity::class.java, parentEntity) {
this.children = emptyList<ChildEntity>().asSequence()
}
builder.assertConsistency()
assertTrue(builder.entities(ChildEntity::class.java).toList().isEmpty())
assertInstanceOf(builder.changeLog.changeLog[childEntity.id], ChangeEntry.RemoveEntity::class.java)
}
@Test
fun `remove multiple children`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity()
val childEntity1 = builder.addChildEntity(parentEntity)
val childEntity2 = builder.addChildEntity(parentEntity)
builder.changeLog.clear()
builder.modifyEntity(ModifiableParentEntity::class.java, parentEntity) {
this.children = sequenceOf(childEntity2)
}
builder.assertConsistency()
assertEquals(1, builder.entities(ChildEntity::class.java).toList().size)
assertInstanceOf(builder.changeLog.changeLog[childEntity1.id], ChangeEntry.RemoveEntity::class.java)
}
@Test
fun `check store consistency after deserialization`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addParentEntity()
builder.addChildEntity(parentEntity)
builder.addChildEntity(parentEntity)
builder.assertConsistency()
builder.removeEntity(parentEntity.id)
builder.assertConsistency()
val stream = ByteArrayOutputStream()
val serializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
serializer.serializeCache(stream, builder.toStorage())
val byteArray = stream.toByteArray()
// Deserialization won't create collection which consists only from null elements
val deserializer = EntityStorageSerializerImpl(TestEntityTypesResolver(), VirtualFileUrlManagerImpl())
val deserialized = (deserializer.deserializeCache(ByteArrayInputStream(byteArray)) as? WorkspaceEntityStorageBuilderImpl)?.toStorage()
deserialized!!.assertConsistency()
}
@Test
fun `replace one to one connection with adding already existing child`() {
val builder = createEmptyBuilder()
val parentEntity = builder.addOoParentWithPidEntity()
builder.addOoChildForParentWithPidEntity(parentEntity)
val anotherBuilder = createBuilderFrom(builder)
anotherBuilder.addOoChildForParentWithPidEntity(parentEntity, childProperty = "MyProperty")
// Modify initial builder
builder.addOoChildForParentWithPidEntity(parentEntity)
builder.addDiff(anotherBuilder)
builder.assertConsistency()
assertEquals("MyProperty", builder.entities(OoParentWithPidEntity::class.java).single().childOne!!.childProperty)
}
@Test
fun `pull one to one connection into another builder`() {
val builder = createEmptyBuilder()
val anotherBuilder = createBuilderFrom(builder)
val parentEntity = anotherBuilder.addOoParentEntity()
anotherBuilder.addOoChildWithNullableParentEntity(parentEntity)
builder.addDiff(anotherBuilder)
builder.assertConsistency()
UsefulTestCase.assertNotEmpty(builder.entities(OoParentEntity::class.java).toList())
UsefulTestCase.assertNotEmpty(builder.entities(OoChildWithNullableParentEntity::class.java).toList())
}
}
| platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/ReferencesInStorageTest.kt | 1155194252 |
/*
* Copyright 2016-2019 Julien Guerinet
*
* 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.guerinet.suitcase.dialog
import android.content.Context
import androidx.annotation.StringRes
import com.afollestad.materialdialogs.DialogCallback
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.afollestad.materialdialogs.list.listItemsMultiChoice
import com.afollestad.materialdialogs.list.listItemsSingleChoice
/**
* Context extensions relating to dialogs
* @author Julien Guerinet
* @since 2.5.0
*/
/* DIALOGS */
/**
* Displays and returns a dialog with a [title] and a [message]. Takes an [init] block to add any other buttons
*/
fun Context.showDialog(
@StringRes title: Int = 0,
@StringRes message: Int = 0,
init: (MaterialDialog.() -> Unit)? = null
) = MaterialDialog(this).show {
build(title, message)
init?.invoke(this)
}
/**
* Displays and returns a dialog with a [title] and a [message]. Takes an [init] block to add any other buttons
*/
fun Context.showDialog(
@StringRes title: Int = 0,
message: String? = null,
init: (MaterialDialog.() -> Unit)? = null
) = MaterialDialog(this).show {
build(title, message)
init?.invoke(this)
}
/* NEUTRAL */
/**
* Displays and returns a dialog with one button. This dialog can have a [title], a [message],
* a [button] text (defaults to the Android OK), and a button [listener].
*/
fun Context.neutralDialog(
@StringRes title: Int = 0,
@StringRes message: Int = 0,
@StringRes button: Int = android.R.string.ok,
listener: DialogCallback? = null
) = showDialog(title, message) {
positiveButton(button, click = listener)
}
/**
* Displays and returns a dialog with one button. This dialog can have a [title], a [message],
* a [button] text (defaults to the Android OK), and a button [listener]
*/
fun Context.neutralDialog(
@StringRes title: Int = 0,
message: String? = null,
@StringRes button: Int = android.R.string.ok,
listener: DialogCallback? = null
) = showDialog(title, message) {
positiveButton(button, click = listener)
}
/* LISTS DIALOGS */
/**
* Displays and returns a dialog with a single choice list of [choices] to choose from.
* Dialog may have a [title] and may show radio buttons depending on [showRadioButtons].
* A [currentChoice] can be given (-1 if none, defaults to -1). When a choice is selected,
* [onChoiceSelected] is called
*/
fun Context.singleListDialog(
choices: List<String>,
@StringRes title: Int = -1,
currentChoice: Int = -1,
showRadioButtons: Boolean = true,
onChoiceSelected: (position: Int) -> Unit
) = MaterialDialog(this).show {
build(title)
if (showRadioButtons) {
listItemsSingleChoice(items = choices, initialSelection = currentChoice) { _, index, _ ->
onChoiceSelected(index)
}
} else {
listItems(items = choices) { _, index, _ ->
onChoiceSelected(index)
}
}
}
/**
* Displays and returns a dialog with a multiple choice list of [choices] to choose from.
* Dialog may have a [title] and has one [button] (text defaults to the Android OK). A list of
* [selectedItems] can be given (defaults to an empty list). When the user has clicked on the
* button, [onChoicesSelected] is called with the list of selected choices.
*/
fun Context.multiListDialog(
choices: List<String>,
@StringRes title: Int = -1,
@StringRes button: Int = android.R.string.ok,
selectedItems: IntArray = intArrayOf(),
onChoicesSelected: (positions: IntArray) -> Unit
) = MaterialDialog(this).show {
build(title)
listItemsMultiChoice(items = choices, initialSelection = selectedItems) { _, indices, _ ->
onChoicesSelected(indices)
}
positiveButton(button)
}
/**
* Begins the construction of a [MaterialDialog] with an optional [title] and [message]
*/
private fun MaterialDialog.build(
@StringRes title: Int,
@StringRes message: Int = 0
) {
if (title != 0) {
title(title)
}
if (message != 0) {
message(message)
}
}
/**
* Begins the construction of a [MaterialDialog] with an optional [title] and [message]
*/
private fun MaterialDialog.build(
@StringRes title: Int,
message: String?
) {
build(title)
message?.let { message(text = message) }
}
| dialog/src/main/java/ContextExt.kt | 2817070960 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.snapshots.demo2_0_0
import org.apache.causeway.client.kroviz.snapshots.Response
object OBJECT_LAYOUT: Response(){
override val url = "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/object-layout"
override val str = """
{
"row": [
{
"cols": [
{
"col": {
"domainObject": {
"named": null,
"describedAs": null,
"plural": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/element",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object\""
},
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"namedEscaped": null
},
"action": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/actions/clearHints",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "clearHints",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/actions/downloadLayoutXml",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "downloadLayoutXml",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/actions/openRestApi",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "openRestApi",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/actions/rebuildMetamodel",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "rebuildMetamodel",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/actions/downloadMetaModelXml",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "downloadMetaModelXml",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": true,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
},
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Editable",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/string",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "string",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/stringMultiline",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "stringMultiline",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "editable",
"unreferencedActions": null,
"unreferencedProperties": null
},
{
"name": "Readonly",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/stringReadonly",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "stringReadonly",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/stringMultilineReadonly",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "stringMultilineReadonly",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "readonly",
"unreferencedActions": null,
"unreferencedProperties": true
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 6,
"unreferencedActions": null,
"unreferencedCollections": null
}
},
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Description",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.Text/AR-LCAAAAAAAAACFkLEOgkAMhneeorlJB0Xj4nBASIybi9EHOKExF3s9wx0Kby8ERKIkdvrTv_36pzKpDMEDC6ctR2K9XAlAzmyu-RqJ82m_2ApwXnGuyDJGokYnkjiQOzQ2DqAp6XzRTMcKOgGzjHR2A4NzGfbeePBQktekGeMUzFv3u4G7K-ZWbKBtu-UE7QMYY4-ocstUNzmKXg6BLqUHRWSfDjxWHhwSZn4ADquTMQc3_QZPpf1z6pcayLD75QsMtJyWiwEAAA==/properties/description",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "description",
"cssClass": null,
"hidden": null,
"labelPosition": "NONE",
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": "More than one column with 'unreferencedProperties' attribute set",
"id": "description",
"unreferencedActions": null,
"unreferencedProperties": true
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 6,
"unreferencedActions": null,
"unreferencedCollections": true
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
}
"""
}
| incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/OBJECT_LAYOUT.kt | 2659021 |
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_History_Refill @JvmOverloads constructor(
injector: HasAndroidInjector,
from: Long = 0
) : DanaRS_Packet_History_(injector, from) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__REFILL
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__REFILL"
}
} | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Refill.kt | 1375245782 |
package com.astoev.cave.survey.test.helper
import android.content.Context
import androidx.test.core.app.ApplicationProvider.getApplicationContext
import com.astoev.cave.survey.service.ormlite.DatabaseHelper
object Database {
fun clearDatabase() {
val ctx = getApplicationContext<Context>()
ctx!!.deleteDatabase(DatabaseHelper.DATABASE_NAME)
// new DatabaseHelper(ctx);
}
} | src/androidTest/java/com/astoev/cave/survey/test/helper/Database.kt | 4243135560 |
/*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pattonvillecs.pattonvilleapp.service.repository.news
import com.github.magneticflux.rss.createRssPersister
import com.github.magneticflux.rss.namespaces.standard.elements.Rss
import okhttp3.ResponseBody
import org.pattonvillecs.pattonvilleapp.service.model.DataSource
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
/**
* Created by Mitchell Skaggs on 12/14/2017.
*
* @since 1.4.0
*/
object NewsConverterFactory : Converter.Factory() {
override fun responseBodyConverter(type: Type, annotations: Array<out Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? {
return when (type) {
Rss::class.java -> RssConverter
else -> super.responseBodyConverter(type, annotations, retrofit)
}
}
override fun stringConverter(type: Type, annotations: Array<out Annotation>, retrofit: Retrofit): Converter<*, String>? {
return when (type) {
DataSource::class.java -> DataSourceConverter
else -> super.stringConverter(type, annotations, retrofit)
}
}
private val persister = createRssPersister()
object RssConverter : Converter<ResponseBody, Rss> {
override fun convert(value: ResponseBody): Rss {
return value.use {
persister.read(Rss::class.java, it.charStream())
}
}
}
object DataSourceConverter : Converter<DataSource, String> {
override fun convert(value: DataSource): String {
return when (value) {
DataSource.DISTRICT -> "District"
DataSource.HIGH_SCHOOL -> "HighSchool"
DataSource.HEIGHTS_MIDDLE_SCHOOL -> "Heights"
DataSource.HOLMAN_MIDDLE_SCHOOL -> "Holman"
DataSource.REMINGTON_TRADITIONAL_SCHOOL -> "Remington"
DataSource.BRIDGEWAY_ELEMENTARY -> "Bridgeway"
DataSource.DRUMMOND_ELEMENTARY -> "Drummond"
DataSource.ROSE_ACRES_ELEMENTARY -> "RoseAcres"
DataSource.PARKWOOD_ELEMENTARY -> "Parkwood"
DataSource.WILLOW_BROOK_ELEMENTARY -> "WillowBrook"
else -> throw IllegalArgumentException("newsURL must be present to download news feed! Did you filter by DataSources that have newsURLs?")
}
}
}
} | app/src/main/java/org/pattonvillecs/pattonvilleapp/service/repository/news/NewsConverterFactory.kt | 227379354 |
package test
expect class Foo(<caret>n: Int)
fun test() {
Foo(1)
Foo(n = 1)
} | plugins/kotlin/idea/tests/testData/refactoring/safeDeleteMultiModule/byExpectClassPrimaryConstructorParameter/before/Common/src/test/test.kt | 2607045302 |
// Copyright 2000-2019 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.util.indexing
import com.intellij.openapi.util.Computable
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.Processor
import com.intellij.util.indexing.impl.AbstractUpdateData
import com.intellij.util.indexing.snapshot.EmptyValueContainer
import java.lang.UnsupportedOperationException
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
class EmptyUpdatableIndex<Key, Value, Input> : UpdatableIndex<Key, Value, Input> {
private var lock = ReentrantReadWriteLock()
@Throws(StorageException::class)
override fun processAllKeys(processor: Processor<in Key>,
scope: GlobalSearchScope,
idFilter: IdFilter?): Boolean {
return false
}
override fun getLock(): ReadWriteLock = lock
@Throws(StorageException::class)
override fun getIndexedFileData(fileId: Int): Map<Key, Value> = emptyMap()
override fun setIndexedStateForFile(fileId: Int, file: IndexedFile) = Unit
override fun resetIndexedStateForFile(fileId: Int) {}
override fun isIndexedStateForFile(fileId: Int, file: IndexedFile): Boolean = false
override fun getModificationStamp(): Long = 0
override fun removeTransientDataForFile(inputId: Int) = Unit
override fun removeTransientDataForKeys(inputId: Int, keys: Collection<Key>) = Unit
override fun getExtension(): IndexExtension<Key, Value, Input> = throw UnsupportedOperationException()
@Throws(StorageException::class)
override fun updateWithMap(updateData: AbstractUpdateData<Key, Value>) = Unit
override fun setBufferingEnabled(enabled: Boolean) = Unit
override fun cleanupMemoryStorage() = Unit
override fun cleanupForNextTest() = Unit
@Throws(StorageException::class)
override fun getData(key: Key): ValueContainer<Value> {
@Suppress("UNCHECKED_CAST")
return EmptyValueContainer as ValueContainer<Value>
}
override fun update(inputId: Int, content: Input?): Computable<Boolean> = throw UnsupportedOperationException()
@Throws(StorageException::class)
override fun flush() {
}
@Throws(StorageException::class)
override fun clear() {
}
override fun dispose() {}
} | platform/lang-impl/src/com/intellij/util/indexing/EmptyUpdatableIndex.kt | 3182148701 |
fun a() {
when (true)<caret> {
}
} | plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/WhenWithCondition.kt | 995230407 |
// "Replace usages of 'myJavaClass(): Class<T>' in whole project" "true"
// WITH_RUNTIME
@Deprecated("", ReplaceWith("T::class.java"))
inline fun <reified T: Any> myJavaClass(): Class<T> = T::class.java
fun foo() {
val v1 = <caret>myJavaClass<List<*>>()
val v2 = myJavaClass<List<String>>()
val v3 = myJavaClass<Array<String>>()
val v4 = myJavaClass<java.util.Random>()
}
| plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/classLiteralAndTypeArgsRuntime.kt | 1804893276 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.profile
import io.github.feelfreelinux.wykopmobilny.api.profile.ProfileApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.utils.intoComposite
class ProfilePresenter(
val schedulers: Schedulers,
val profileApi: ProfileApi
) : BasePresenter<ProfileView>() {
var userName = "a__s"
fun loadData() {
profileApi.getIndex(userName)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showProfile(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
fun markObserved() {
profileApi.observe(userName)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showButtons(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
fun markUnobserved() {
profileApi.unobserve(userName)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showButtons(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
fun markBlocked() {
profileApi.block(userName)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showButtons(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
fun markUnblocked() {
profileApi.unblock(userName)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showButtons(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
fun getBadges() {
profileApi.getBadges(userName, 0)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe({ view?.showBadges(it) }, { view?.showErrorDialog(it) })
.intoComposite(compositeObservable)
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/ProfilePresenter.kt | 307925210 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.injection
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTreeUtil.getDeepestLast
import com.intellij.util.Consumer
import com.intellij.util.Processor
import org.intellij.plugins.intelliLang.Configuration
import org.intellij.plugins.intelliLang.inject.*
import org.intellij.plugins.intelliLang.inject.config.BaseInjection
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.patterns.KotlinPatterns
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
@NonNls
val KOTLIN_SUPPORT_ID = "kotlin"
class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() {
override fun getId(): String = KOTLIN_SUPPORT_ID
override fun createAddActions(project: Project?, consumer: Consumer<in BaseInjection>?): Array<AnAction> {
return super.createAddActions(project, consumer).apply {
forEach {
it.templatePresentation.icon = KotlinFileType.INSTANCE.icon
}
}
}
override fun getPatternClasses() = arrayOf(KotlinPatterns::class.java)
override fun isApplicableTo(host: PsiLanguageInjectionHost?) = host is KtElement
override fun useDefaultInjector(host: PsiLanguageInjectionHost?): Boolean = false
override fun addInjectionInPlace(language: Language?, host: PsiLanguageInjectionHost?): Boolean {
if (language == null || host == null) return false
val configuration = Configuration.getProjectInstance(host.project).advancedConfiguration
if (!configuration.isSourceModificationAllowed) {
// It's not allowed to modify code without explicit permission. Postpone adding @Inject or comment till it granted.
host.putUserData(InjectLanguageAction.FIX_KEY, Processor { fixHost: PsiLanguageInjectionHost? ->
fixHost != null && addInjectionInstructionInCode(language, fixHost)
})
return false
}
if (!addInjectionInstructionInCode(language, host)) {
return false
}
TemporaryPlacesRegistry.getInstance(host.project).addHostWithUndo(host, InjectedLanguage.create(language.id))
return true
}
override fun removeInjectionInPlace(psiElement: PsiLanguageInjectionHost?): Boolean {
if (psiElement == null || psiElement !is KtElement) return false
val project = psiElement.getProject()
val injectInstructions = listOfNotNull(
findAnnotationInjection(psiElement),
findInjectionComment(psiElement)
)
TemporaryPlacesRegistry.getInstance(project).removeHostWithUndo(project, psiElement)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.remove.injection.in.code.instructions")) {
injectInstructions.forEach(PsiElement::delete)
}
return true
}
override fun findCommentInjection(host: PsiElement, commentRef: Ref<in PsiElement>?): BaseInjection? {
// Do not inject through CommentLanguageInjector, because it injects as simple injection.
// We need to behave special for interpolated strings.
return null
}
fun findCommentInjection(host: KtElement): BaseInjection? {
return InjectorUtils.findCommentInjection(host, "", null)
}
private fun findInjectionComment(host: KtElement): PsiComment? {
val commentRef = Ref.create<PsiElement>(null)
InjectorUtils.findCommentInjection(host, "", commentRef) ?: return null
return commentRef.get() as? PsiComment
}
internal fun findAnnotationInjectionLanguageId(host: KtElement): InjectionInfo? {
val annotationEntry = findAnnotationInjection(host) ?: return null
val extractLanguageFromInjectAnnotation = extractLanguageFromInjectAnnotation(annotationEntry) ?: return null
val prefix = extractStringArgumentByName(annotationEntry, "prefix")
val suffix = extractStringArgumentByName(annotationEntry, "suffix")
return InjectionInfo(extractLanguageFromInjectAnnotation, prefix, suffix)
}
}
private fun extractStringArgumentByName(annotationEntry: KtAnnotationEntry, name: String): String? {
val namedArgument: ValueArgument =
annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name } ?: return null
return extractStringValue(namedArgument)
}
private fun extractLanguageFromInjectAnnotation(annotationEntry: KtAnnotationEntry): String? {
val firstArgument: ValueArgument = annotationEntry.valueArguments.firstOrNull() ?: return null
return extractStringValue(firstArgument)
}
private fun extractStringValue(valueArgument: ValueArgument): String? {
val firstStringArgument = valueArgument.getArgumentExpression() as? KtStringTemplateExpression ?: return null
val firstStringEntry = firstStringArgument.entries.singleOrNull() ?: return null
return firstStringEntry.text
}
private fun findAnnotationInjection(host: KtElement): KtAnnotationEntry? {
val modifierListOwner = findElementToInjectWithAnnotation(host) ?: return null
val modifierList = modifierListOwner.modifierList ?: return null
// Host can't be before annotation
if (host.startOffset < modifierList.endOffset) return null
return modifierListOwner.findAnnotation(FqName(AnnotationUtil.LANGUAGE))
}
private fun canInjectWithAnnotation(host: PsiElement): Boolean {
val module = ModuleUtilCore.findModuleForPsiElement(host) ?: return false
val javaPsiFacade = JavaPsiFacade.getInstance(module.project)
return javaPsiFacade.findClass(AnnotationUtil.LANGUAGE, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) != null
}
private fun findElementToInjectWithAnnotation(host: KtElement): KtModifierListOwner? = PsiTreeUtil.getParentOfType(
host,
KtModifierListOwner::class.java,
false, /* strict */
KtBlockExpression::class.java, KtParameterList::class.java, KtTypeParameterList::class.java /* Stop at */
)
private fun findElementToInjectWithComment(host: KtElement): KtExpression? {
val parentBlockExpression = PsiTreeUtil.getParentOfType(
host,
KtBlockExpression::class.java,
true, /* strict */
KtDeclaration::class.java /* Stop at */
) ?: return null
return parentBlockExpression.statements.firstOrNull { statement ->
PsiTreeUtil.isAncestor(statement, host, false) && checkIsValidPlaceForInjectionWithLineComment(statement, host)
}
}
private fun addInjectionInstructionInCode(language: Language, host: PsiLanguageInjectionHost): Boolean {
val ktHost = host as? KtElement ?: return false
val project = ktHost.project
// Find the place where injection can be stated with annotation or comment
val modifierListOwner = findElementToInjectWithAnnotation(ktHost)
if (modifierListOwner != null && canInjectWithAnnotation(ktHost)) {
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.annotation")) {
modifierListOwner.addAnnotation(FqName(AnnotationUtil.LANGUAGE), "\"${language.id}\"")
}
return true
}
// Find the place where injection can be done with one-line comment
val commentBeforeAnchor: PsiElement =
modifierListOwner?.firstNonCommentChild() ?: findElementToInjectWithComment(ktHost) ?: return false
val psiFactory = KtPsiFactory(project)
val injectComment = psiFactory.createComment("//language=" + language.id)
project.executeWriteCommand(KotlinJvmBundle.message("command.action.add.injection.comment")) {
commentBeforeAnchor.parent.addBefore(injectComment, commentBeforeAnchor)
}
return true
}
// Inspired with InjectorUtils.findCommentInjection()
private fun checkIsValidPlaceForInjectionWithLineComment(statement: KtExpression, host: KtElement): Boolean {
// make sure comment is close enough and ...
val statementStartOffset = statement.startOffset
val hostStart = host.startOffset
if (hostStart < statementStartOffset || hostStart - statementStartOffset > 120) {
return false
}
if (hostStart - statementStartOffset > 2) {
// ... there's no non-empty valid host in between comment and e2
if (prevWalker(host, statement).asSequence().takeWhile { it != null }.any {
it is PsiLanguageInjectionHost && it.isValidHost && !StringUtil.isEmptyOrSpaces(it.text)
}
) return false
}
return true
}
private fun PsiElement.firstNonCommentChild(): PsiElement? =
firstChild.siblings().dropWhile { it is PsiComment || it is PsiWhiteSpace }.firstOrNull()
// Based on InjectorUtils.prevWalker
private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator<PsiElement?> {
return object : Iterator<PsiElement?> {
private var e: PsiElement? = element
override fun hasNext(): Boolean = true
override fun next(): PsiElement? {
val current = e
if (current == null || current === scope) return null
val prev = current.prevSibling
e = if (prev != null) {
getDeepestLast(prev)
} else {
val parent = current.parent
if (parent === scope || parent is PsiFile) null else parent
}
return e
}
}
}
| plugins/kotlin/injection/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt | 2990301095 |
// WITH_RUNTIME
// IS_APPLICABLE: false
class List {
val size = 0
}
fun foo() {
val list = List()
list.size<caret> == 0
} | plugins/kotlin/idea/tests/testData/intentions/replaceSizeZeroCheckWithIsEmpty/sizeCheck.kt | 2969178505 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.common.kotlin
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.test.common.kotlin.UastTestSuffix.TXT
import org.jetbrains.uast.kotlin.internal.KotlinUElementWithComments
import org.jetbrains.uast.visitor.UastVisitor
import java.io.File
interface UastCommentLogTestBase : UastPluginSelection, UastFileComparisonTestBase {
private fun getCommentsFile(filePath: String, suffix: String): File = getTestMetadataFileFromPath(filePath, "comments$suffix")
private fun getIdenticalCommentsFile(filePath: String): File = getCommentsFile(filePath, TXT)
private fun getPluginCommentsFile(filePath: String): File {
val identicalFile = getIdenticalCommentsFile(filePath)
if (identicalFile.exists()) return identicalFile
return getCommentsFile(filePath, "$pluginSuffix$TXT")
}
private fun UComment.testLog(indent: String): String {
return "UComment(${text})".replace("\n", "\n" + indent)
}
fun check(filePath: String, file: UFile) {
val comments = printComments(file)
val commentsFile = getPluginCommentsFile(filePath)
KotlinTestUtils.assertEqualsToFile(commentsFile, comments)
cleanUpIdenticalFile(
commentsFile,
getCommentsFile(filePath, "$counterpartSuffix$TXT"),
getIdenticalCommentsFile(filePath),
kind = "comments"
)
}
private fun printComments(file: UFile): String = buildString {
val indent = " "
file.accept(object : UastVisitor {
private var level = 0
private fun printIndent() {
append(indent.repeat(level))
}
private fun renderComments(comments: List<UComment>) {
comments.forEach { comment ->
printIndent()
appendLine(comment.testLog(indent.repeat(level)))
}
}
private val UElement.nameIfAvailable: String
get() = (javaPsi as? PsiNamedElement)?.name?.takeIf { it.isNotBlank() } ?: "<no name provided>"
override fun visitElement(node: UElement): Boolean {
if (node is UDeclaration || node is UFile) {
printIndent()
appendLine("${node::class.java.simpleName}:${node.nameIfAvailable}(")
level++
if (node is KotlinUElementWithComments) renderComments(node.comments)
}
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
if (node is UDeclaration || node is UFile) {
level--
printIndent()
appendLine(")")
}
}
})
}
}
| plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/UastCommentLogTestBase.kt | 4274957942 |
/*
* Copyright 2010-2018 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 codegen.basics.cast_null
import kotlin.test.*
@Test
fun runTest() {
testCast(null, false)
testCastToNullable(null, true)
testCastToNullable(TestKlass(), true)
testCastToNullable("", false)
testCastNotNullableToNullable(TestKlass(), true)
testCastNotNullableToNullable("", false)
println("Ok")
}
class TestKlass
fun ensure(b: Boolean) {
if (!b) {
println("Error")
}
}
fun testCast(x: Any?, expectSuccess: Boolean) {
try {
x as TestKlass
} catch (e: Throwable) {
ensure(!expectSuccess)
return
}
ensure(expectSuccess)
}
fun testCastToNullable(x: Any?, expectSuccess: Boolean) {
try {
x as TestKlass?
} catch (e: Throwable) {
ensure(!expectSuccess)
return
}
ensure(expectSuccess)
}
fun testCastNotNullableToNullable(x: Any, expectSuccess: Boolean) {
try {
x as TestKlass?
} catch (e: Throwable) {
ensure(!expectSuccess)
return
}
ensure(expectSuccess)
} | backend.native/tests/codegen/basics/cast_null.kt | 431698497 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtNamedFunction
// OPTIONS: usages
// FIND_BY_REF
// WITH_FILE_NAME
package usages
fun test() {
val f = mapOf(Pair("1", "2")).keys.<caret>single({ true })
}
// FIR_COMPARISON | plugins/kotlin/idea/tests/testData/findUsages/stdlibUsages/LibraryMemberFunctionUsagesInStdlib.0.kt | 1881994716 |
package de.stefanmedack.ccctv.repository
import de.stefanmedack.ccctv.model.Resource
import de.stefanmedack.ccctv.util.applySchedulers
import io.reactivex.Flowable
import io.reactivex.Single
abstract class NetworkBoundResource<LocalType, NetworkType> internal constructor() {
val resource: Flowable<Resource<LocalType>>
get() = Flowable.concat(
fetchLocal()
.take(1)
.map<Resource<LocalType>> { Resource.Success(it) }
.applySchedulers()
.filter { !isStale(it) }, // TODO maybe return local even if local data is stale
fetchNetwork()
.toFlowable()
.map { mapNetworkToLocal(it) }
.flatMap {
Flowable.fromCallable {
saveLocal(it)
it
}.applySchedulers()
}
.map<Resource<LocalType>> { Resource.Success(it) }
// .onErrorReturn { Resource.Error("Error") } // TODO better msg
.applySchedulers()
).firstOrError()
.toFlowable()
.startWith(Resource.Loading())
protected abstract fun fetchLocal(): Flowable<LocalType>
protected abstract fun saveLocal(data: LocalType)
protected abstract fun isStale(localResource: Resource<LocalType>): Boolean
protected abstract fun fetchNetwork(): Single<NetworkType>
protected abstract fun mapNetworkToLocal(data: NetworkType): LocalType
}
| app/src/main/java/de/stefanmedack/ccctv/repository/NetworkBoundResource.kt | 1120794421 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. 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.dependency.analyzer
import com.intellij.openapi.actionSystem.AnActionEvent
abstract class AbstractDependencyAnalyzerAction<Data> : DependencyAnalyzerAction() {
abstract fun getSelectedData(e: AnActionEvent): Data?
abstract fun getExternalProjectPath(e: AnActionEvent, selectedData: Data): String?
abstract fun getDependencyData(e: AnActionEvent, selectedData: Data): DependencyAnalyzerDependency.Data?
abstract fun getDependencyScope(e: AnActionEvent, selectedData: Data): DependencyAnalyzerDependency.Scope?
override fun isEnabledAndVisible(e: AnActionEvent): Boolean {
val selectedData = getSelectedData(e) ?: return false
return getExternalProjectPath(e, selectedData) != null
}
override fun setSelectedState(view: DependencyAnalyzerView, e: AnActionEvent) {
val selectedData = getSelectedData(e) ?: return
val externalProjectPath = getExternalProjectPath(e, selectedData) ?: return
val dependencyData = getDependencyData(e, selectedData)
val dependencyScope = getDependencyScope(e, selectedData)
if (dependencyData != null && dependencyScope != null) {
view.setSelectedDependency(externalProjectPath, dependencyData, dependencyScope)
}
else if (dependencyData != null) {
view.setSelectedDependency(externalProjectPath, dependencyData)
}
else {
view.setSelectedExternalProject(externalProjectPath)
}
}
} | platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/AbstractDependencyAnalyzerAction.kt | 1002419281 |
package com.pinkal.todo.utils.views.recyclerview.itemdrag
/**
* Created by Pinkal on 12/6/17.
*/
interface ItemTouchHelperAdapter {
fun onItemMove(fromPosition: Int, toPosition: Int): Boolean
fun onItemDismiss(position: Int)
} | app/src/main/java/com/pinkal/todo/utils/views/recyclerview/itemdrag/ItemTouchHelperAdapter.kt | 925764202 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.metrics.performance
import android.view.FrameMetrics
import android.view.View
import android.view.Window
import androidx.annotation.RequiresApi
@RequiresApi(31)
internal class JankStatsApi31Impl(
jankStats: JankStats,
view: View,
window: Window
) : JankStatsApi26Impl(jankStats, view, window) {
// Reuse the same frameData on every frame to avoid allocating per-frame objects
val frameData = FrameDataApi31(0, 0, 0, 0, 0, false, stateInfo)
override fun getFrameData(
startTime: Long,
expectedDuration: Long,
frameMetrics: FrameMetrics
): FrameDataApi31 {
val uiDuration = frameMetrics.getMetric(FrameMetrics.UNKNOWN_DELAY_DURATION) +
frameMetrics.getMetric(FrameMetrics.INPUT_HANDLING_DURATION) +
frameMetrics.getMetric(FrameMetrics.ANIMATION_DURATION) +
frameMetrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION) +
frameMetrics.getMetric(FrameMetrics.DRAW_DURATION) +
frameMetrics.getMetric(FrameMetrics.SYNC_DURATION)
prevEnd = startTime + uiDuration
metricsStateHolder.state?.getIntervalStates(startTime, prevEnd, stateInfo)
val isJank = uiDuration > expectedDuration
val totalDuration = frameMetrics.getMetric(FrameMetrics.TOTAL_DURATION)
// SWAP is counted for both CPU and GPU metrics, so add it back in after subtracting GPU
val cpuDuration = totalDuration -
frameMetrics.getMetric(FrameMetrics.GPU_DURATION) +
frameMetrics.getMetric(FrameMetrics.SWAP_BUFFERS_DURATION)
val overrun = totalDuration -
frameMetrics.getMetric(FrameMetrics.DEADLINE)
frameData.update(startTime, uiDuration, cpuDuration, totalDuration, overrun, isJank)
return frameData
}
override fun getExpectedFrameDuration(metrics: FrameMetrics): Long {
return metrics.getMetric(FrameMetrics.DEADLINE)
}
} | metrics/metrics-performance/src/main/java/androidx/metrics/performance/JankStatsApi31Impl.kt | 3948029926 |
/*
* 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.
*/
@file:Suppress("PLUGIN_ERROR")
package androidx.compose.runtime
import android.app.Activity
import android.os.Looper
import android.view.Choreographer
import android.view.View
import android.view.ViewGroup
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.platform.LocalContext
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.test.assertTrue
class TestActivity : ComponentActivity()
@Suppress("DEPRECATION")
fun makeTestActivityRule() = androidx.test.rule.ActivityTestRule(TestActivity::class.java)
internal val Activity.root get() = findViewById<ViewGroup>(android.R.id.content)
internal fun Activity.uiThread(block: () -> Unit) {
val latch = CountDownLatch(1)
var throwable: Throwable? = null
runOnUiThread(object : Runnable {
override fun run() {
try {
block()
} catch (e: Throwable) {
throwable = e
} finally {
latch.countDown()
}
}
})
val completed = latch.await(5, TimeUnit.SECONDS)
if (!completed) error("UI thread work did not complete within 5 seconds")
throwable?.let {
throw when (it) {
is AssertionError -> AssertionError(it.localizedMessage, it)
else ->
IllegalStateException(
"UI thread threw an exception: ${it.localizedMessage}",
it
)
}
}
}
internal fun ComponentActivity.show(block: @Composable () -> Unit) {
uiThread {
Snapshot.sendApplyNotifications()
setContent(content = block)
}
}
internal fun Activity.waitForAFrame() {
if (Looper.getMainLooper() == Looper.myLooper()) {
throw Exception("Cannot be run from the main thread")
}
val latch = CountDownLatch(1)
uiThread {
Choreographer.getInstance().postFrameCallback { latch.countDown() }
}
assertTrue(latch.await(1, TimeUnit.HOURS), "Time-out waiting for choreographer frame")
}
abstract class BaseComposeTest {
@Suppress("DEPRECATION")
abstract val activityRule: androidx.test.rule.ActivityTestRule<TestActivity>
val activity get() = activityRule.activity
fun compose(
composable: @Composable () -> Unit
) = ComposeTester(
activity,
composable
)
@Composable
@Suppress("UNUSED_PARAMETER")
fun subCompose(block: @Composable () -> Unit) {
// val reference = rememberCompositionContext()
// remember {
// Composition(
// UiApplier(View(activity)),
// reference
// )
// }.apply {
// setContent {
// block()
// }
// }
}
}
class ComposeTester(val activity: ComponentActivity, val composable: @Composable () -> Unit) {
inner class ActiveTest(val activity: Activity) {
fun then(block: ActiveTest.(activity: Activity) -> Unit): ActiveTest {
activity.waitForAFrame()
activity.uiThread {
block(activity)
}
return this
}
fun done() {
activity.uiThread {
activity.setContentView(View(activity))
}
activity.waitForAFrame()
}
}
private fun initialComposition(composable: @Composable () -> Unit) {
activity.show {
CompositionLocalProvider(
LocalContext provides activity
) {
composable()
}
}
}
fun then(block: ComposeTester.(activity: Activity) -> Unit): ActiveTest {
initialComposition(composable)
activity.waitForAFrame()
activity.uiThread {
block(activity)
}
return ActiveTest(activity)
}
}
fun View.traversal(): Sequence<View> = sequence {
yield(this@traversal)
if (this@traversal is ViewGroup) {
for (i in 0 until childCount) {
yieldAll(getChildAt(i).traversal())
}
}
}
| compose/runtime/runtime/integration-tests/src/androidAndroidTest/kotlin/androidx/compose/runtime/BaseComposeTest.kt | 2350663454 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.fragment
import androidx.fragment.app.DialogFragment
import androidx.navigation.contains
import androidx.navigation.createGraph
import androidx.navigation.get
import androidx.test.annotation.UiThreadTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class DialogFragmentNavigatorDestinationBuilderTest {
@Suppress("DEPRECATION")
@get:Rule
val activityRule = androidx.test.rule.ActivityTestRule<TestActivity>(TestActivity::class.java)
private val fragmentManager get() = activityRule.activity.supportFragmentManager
@Suppress("DEPRECATION")
@UiThreadTest
@Test fun fragment() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ID) {
dialog<BuilderTestDialogFragment>(DESTINATION_ID)
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ID in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ID] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
}
@Suppress("DEPRECATION")
@UiThreadTest
@Test fun fragmentWithBody() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ID) {
dialog<BuilderTestDialogFragment>(DESTINATION_ID) {
label = LABEL
}
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ID in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ID] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
assertWithMessage("DialogFragment should have label set")
.that(graph[DESTINATION_ID].label)
.isEqualTo(LABEL)
}
@UiThreadTest
@Test fun fragmentRoute() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ROUTE) {
dialog<BuilderTestDialogFragment>(DESTINATION_ROUTE)
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ROUTE in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ROUTE] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
}
@UiThreadTest
@Test fun fragmentWithBodyRoute() {
val navHostFragment = NavHostFragment()
fragmentManager.beginTransaction()
.add(android.R.id.content, navHostFragment)
.commitNow()
val graph = navHostFragment.createGraph(startDestination = DESTINATION_ROUTE) {
dialog<BuilderTestDialogFragment>(DESTINATION_ROUTE) {
label = LABEL
}
}
assertWithMessage("Destination should be added to the graph")
.that(DESTINATION_ROUTE in graph)
.isTrue()
assertWithMessage("DialogFragment class should be set to BuilderTestDialogFragment")
.that((graph[DESTINATION_ROUTE] as DialogFragmentNavigator.Destination).className)
.isEqualTo(BuilderTestDialogFragment::class.java.name)
assertWithMessage("DialogFragment should have label set")
.that(graph[DESTINATION_ROUTE].label)
.isEqualTo(LABEL)
}
}
private const val DESTINATION_ID = 1
private const val DESTINATION_ROUTE = "destination"
private const val LABEL = "Test"
class BuilderTestDialogFragment : DialogFragment()
| navigation/navigation-fragment/src/androidTest/java/androidx/navigation/fragment/DialogFragmentNavigatorDestinationBuilderTest.kt | 2014341916 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.core.view
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.widget.Toolbar
import androidx.core.app.TestActivity
import androidx.core.test.R
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.testutils.withActivity
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class MenuHostTest {
private val context = InstrumentationRegistry.getInstrumentation().context
private val menuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.item1 -> true
R.id.item2 -> true
else -> false
}
}
}
@Test
fun onMenuItemSelected() {
with(ActivityScenario.launch(TestActivity::class.java)) {
val toolbar = Toolbar(context)
val menuHost = TestMenuHost(toolbar.menu, withActivity { menuInflater })
menuHost.addMenuProvider(menuProvider)
val menuItem1: MenuItem = toolbar.menu.findItem(R.id.item1)
assertThat(menuHost.onMenuItemSelected(menuItem1)).isTrue()
}
}
}
class TestMenuHost(private val menu: Menu, private val menuInflater: MenuInflater) : MenuHost {
var invalidateCount = 0
private val menuHostHelper = MenuHostHelper {
invalidateMenu()
invalidateCount++
}
fun onPrepareMenu(menu: Menu) {
menuHostHelper.onPrepareMenu(menu)
}
private fun onCreateMenu() {
menuHostHelper.onCreateMenu(menu, menuInflater)
}
fun onMenuItemSelected(item: MenuItem): Boolean {
return menuHostHelper.onMenuItemSelected(item)
}
fun onMenuClosed(menu: Menu) {
menuHostHelper.onMenuClosed(menu)
}
override fun addMenuProvider(provider: MenuProvider) {
menuHostHelper.addMenuProvider(provider)
}
override fun addMenuProvider(provider: MenuProvider, owner: LifecycleOwner) {
menuHostHelper.addMenuProvider(provider, owner)
}
override fun addMenuProvider(
provider: MenuProvider,
owner: LifecycleOwner,
state: Lifecycle.State
) {
menuHostHelper.addMenuProvider(provider, owner, state)
}
override fun removeMenuProvider(provider: MenuProvider) {
menuHostHelper.removeMenuProvider(provider)
}
override fun invalidateMenu() {
menu.clear()
onCreateMenu()
}
} | core/core/src/androidTest/java/androidx/core/view/MenuHostTest.kt | 1985823553 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.collectFunctions
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.util.isValidOperator
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.*
abstract class TypesWithOperatorDetector(
private val name: Name,
private val scope: LexicalScope,
private val indicesHelper: KotlinIndicesHelper?
) {
protected abstract fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor?
private val cache = HashMap<FuzzyType, Pair<FunctionDescriptor, TypeSubstitutor>?>()
val extensionOperators: Collection<FunctionDescriptor> by lazy {
val result = ArrayList<FunctionDescriptor>()
val extensionsFromScope = scope
.collectFunctions(name, NoLookupLocation.FROM_IDE)
.filter { it.extensionReceiverParameter != null }
result.addSuitableOperators(extensionsFromScope)
indicesHelper?.getTopLevelExtensionOperatorsByName(name.asString())?.let { result.addSuitableOperators(it) }
result.distinctBy { it.original }
}
val classesWithMemberOperators: Collection<ClassDescriptor> by lazy {
if (indicesHelper == null) return@lazy emptyList<ClassDescriptor>()
val operators = ArrayList<FunctionDescriptor>().addSuitableOperators(indicesHelper.getMemberOperatorsByName(name.asString()))
operators.map { it.containingDeclaration as ClassDescriptor }.distinct()
}
private fun MutableCollection<FunctionDescriptor>.addSuitableOperators(functions: Collection<FunctionDescriptor>): MutableCollection<FunctionDescriptor> {
for (function in functions) {
if (!function.isValidOperator()) continue
var freeParameters = function.typeParameters
val containingClass = function.containingDeclaration as? ClassDescriptor
if (containingClass != null) {
freeParameters += containingClass.typeConstructor.parameters
}
val substitutor = checkIsSuitableByType(function, freeParameters) ?: continue
addIfNotNull(function.substitute(substitutor))
}
return this
}
fun findOperator(type: FuzzyType): Pair<FunctionDescriptor, TypeSubstitutor>? = if (cache.containsKey(type)) {
cache[type]
} else {
val result = findOperatorNoCache(type)
cache[type] = result
result
}
private fun findOperatorNoCache(type: FuzzyType): Pair<FunctionDescriptor, TypeSubstitutor>? {
if (type.nullability() != TypeNullability.NULLABLE) {
for (memberFunction in type.type.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE)) {
if (memberFunction.isValidOperator()) {
val substitutor = checkIsSuitableByType(memberFunction, type.freeParameters) ?: continue
val substituted = memberFunction.substitute(substitutor) ?: continue
return substituted to substitutor
}
}
}
for (operator in extensionOperators) {
val substitutor = type.checkIsSubtypeOf(operator.fuzzyExtensionReceiverType()!!) ?: continue
val substituted = operator.substitute(substitutor) ?: continue
return substituted to substitutor
}
return null
}
}
class TypesWithContainsDetector(
scope: LexicalScope,
indicesHelper: KotlinIndicesHelper?,
private val argumentType: KotlinType
) : TypesWithOperatorDetector(OperatorNameConventions.CONTAINS, scope, indicesHelper) {
override fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor? {
val parameter = operator.valueParameters.single()
val fuzzyParameterType = parameter.type.toFuzzyType(operator.typeParameters + freeTypeParams)
return fuzzyParameterType.checkIsSuperTypeOf(argumentType)
}
}
class TypesWithGetValueDetector(
scope: LexicalScope,
indicesHelper: KotlinIndicesHelper?,
private val propertyOwnerType: FuzzyType,
private val propertyType: FuzzyType?
) : TypesWithOperatorDetector(OperatorNameConventions.GET_VALUE, scope, indicesHelper) {
override fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor? {
val paramType = operator.valueParameters.first().type.toFuzzyType(freeTypeParams)
val substitutor = paramType.checkIsSuperTypeOf(propertyOwnerType) ?: return null
if (propertyType == null) return substitutor
val fuzzyReturnType = operator.returnType?.toFuzzyType(freeTypeParams) ?: return null
val substitutorFromPropertyType = fuzzyReturnType.checkIsSubtypeOf(propertyType) ?: return null
return substitutor.combineIfNoConflicts(substitutorFromPropertyType, freeTypeParams)
}
}
class TypesWithSetValueDetector(
scope: LexicalScope,
indicesHelper: KotlinIndicesHelper?,
private val propertyOwnerType: FuzzyType
) : TypesWithOperatorDetector(OperatorNameConventions.SET_VALUE, scope, indicesHelper) {
override fun checkIsSuitableByType(
operator: FunctionDescriptor,
freeTypeParams: Collection<TypeParameterDescriptor>
): TypeSubstitutor? {
val paramType = operator.valueParameters.first().type.toFuzzyType(freeTypeParams)
return paramType.checkIsSuperTypeOf(propertyOwnerType)
}
} | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/core/TypesWithOperatorDetector.kt | 4035376933 |
package com.bignerdranch.beatbox.data
/**
* Created by Panel on 18.08.2016.
*/
object BeatBox {
private val TAG = "BeatBox"
private val SOUNDS_FOLDER = "sample_sounds"
} | plugins/kotlin/idea/tests/testData/copyPaste/plainTextConversion/KT13529.expected.kt | 608139210 |
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.buildsystem.model.DeclaredDependency
import com.intellij.buildsystem.model.OperationFailure
import com.intellij.buildsystem.model.OperationItem
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.jetbrains.packagesearch.intellij.plugin.intentions.PackageSearchDependencyUpgradeQuickFix
import com.jetbrains.packagesearch.intellij.plugin.util.asCoroutine
/**
* Extension point that allows to modify the dependencies of a specific project.
*/
@Deprecated(
"Use async version. Either AsyncProjectModuleOperationProvider or CoroutineProjectModuleOperationProvider." +
" Remember to change the extension point type in the xml",
ReplaceWith(
"ProjectAsyncModuleOperationProvider",
"com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectAsyncModuleOperationProvider"
),
DeprecationLevel.WARNING
)
interface ProjectModuleOperationProvider {
companion object {
private val EP_NAME = "com.intellij.packagesearch.projectModuleOperationProvider"
private val extensionPointName
get() = ExtensionPointName.create<ProjectModuleOperationProvider>(EP_NAME)
internal val extensions
get() = extensionPointName.extensions.map { it.asCoroutine() }
}
/**
* Returns whether the implementation of the interface uses the shared "packages update available"
* inspection and quickfix. This is `false` by default; override this property and return `true`
* to opt in to [PackageUpdateInspection].
*
* @return `true` opt in to [PackageUpdateInspection], false otherwise.
* @see PackageUpdateInspection
* @see PackageSearchDependencyUpgradeQuickFix
*/
fun usesSharedPackageUpdateInspection(): Boolean = false
/**
* Checks if current implementation has support in the given [project] for the current [psiFile].
* @return `true` if the [project] and [psiFile] are supported.
*/
fun hasSupportFor(project: Project, psiFile: PsiFile?): Boolean
/**
* Checks if current implementation has support in the given [projectModuleType].
* @return `true` if the [projectModuleType] is supported.
*/
fun hasSupportFor(projectModuleType: ProjectModuleType): Boolean
/**
* Adds a dependency to the given [module] using [operationMetadata].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun addDependencyToModule(
operationMetadata: DependencyOperationMetadata,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Removes a dependency from the given [module] using [operationMetadata].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun removeDependencyFromModule(
operationMetadata: DependencyOperationMetadata,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Modify a dependency in the given [module] using [operationMetadata].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun updateDependencyInModule(
operationMetadata: DependencyOperationMetadata,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Lists all dependencies declared in the given [module]. A declared dependency
* have to be explicitly written in the build file.
* @return A [Collection]<[UnifiedDependency]> found in the project.
*/
fun declaredDependenciesInModule(
module: ProjectModule
): Collection<DeclaredDependency> = emptyList()
/**
* Lists all resolved dependencies in the given [module].
* @return A [Collection]<[UnifiedDependency]> found in the project.
*/
fun resolvedDependenciesInModule(
module: ProjectModule,
scopes: Set<String> = emptySet()
): Collection<UnifiedDependency> = emptyList()
/**
* Adds the [repository] to the given [module].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun addRepositoryToModule(
repository: UnifiedDependencyRepository,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Removes the [repository] from the given [module].
* @return A list containing all failures encountered during the operation. If the list is empty, the operation was successful.
*/
fun removeRepositoryFromModule(
repository: UnifiedDependencyRepository,
module: ProjectModule
): Collection<OperationFailure<out OperationItem>> = emptyList()
/**
* Lists all repositories in the given [module].
* @return A [Collection]<[UnifiedDependencyRepository]> found the project.
*/
fun listRepositoriesInModule(
module: ProjectModule
): Collection<UnifiedDependencyRepository> = emptyList()
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModuleOperationProvider.kt | 3802497121 |
package com.zeke.demo.jetpack.paging
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kingz.base.BaseVMActivity
import com.zeke.demo.R
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
/**
* author: King.Z <br>
* date: 2021/8/22 21:13 <br>
* description: <br>
*/
class PagingDemoActivity : BaseVMActivity() {
lateinit var pagingAdapter: PagingDemoAdapter
override val viewModel: UserInfoViewModel by lazy {
UserInfoViewModel(ReqresApiService.getApiService())
}
override fun getContentLayout(): Int = R.layout.activity_paging_demo
override fun initView(savedInstanceState: Bundle?) {
super.initView(savedInstanceState)
pagingAdapter = PagingDemoAdapter().apply {
// 列表加载时回调
addLoadStateListener {
if (it.refresh == LoadState.Loading) {
// show progress view
} else {
//hide progress view
}
}
//withLoadStateHeaderAndFooter{ }
// .withLoadStateFooter
}
findViewById<RecyclerView>(R.id.content_recycler).apply {
layoutManager = LinearLayoutManager(this@PagingDemoActivity)
adapter = pagingAdapter
}
}
override fun initData(savedInstanceState: Bundle?) {
lifecycleScope.launch {
try {
viewModel.listData.collect {
pagingAdapter.submitData(it)
}
} catch (e: Throwable) {
println("Exception from the flow: $e")
}
}
}
} | module-Demo/src/main/java/com/zeke/demo/jetpack/paging/PagingDemoActivity.kt | 98740269 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.core.entity.settings
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settingValidator
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
abstract class SettingBuilder<V : Any, T : SettingType<V>>(
private val path: String,
private val title: String,
private val neededAtPhase: GenerationPhase
) {
var isAvailable: Reader.() -> Boolean = { true }
open var defaultValue: SettingDefaultValue<V>? = null
var validateOnProjectCreation = true
var isSavable: Boolean = false
var isRequired: Boolean? = null
var description: String? = null
fun value(value: V) = SettingDefaultValue.Value(value)
fun dynamic(getter: Reader.(SettingReference<V, SettingType<V>>) -> V?) =
SettingDefaultValue.Dynamic(getter)
protected var validator =
SettingValidator<V> { ValidationResult.OK }
fun validate(validator: SettingValidator<V>) {
this.validator = this.validator and validator
}
fun validate(validator: Reader.(V) -> ValidationResult) {
this.validator = this.validator and settingValidator(
validator
)
}
abstract val type: T
fun buildInternal() = InternalSetting(
path = path,
title = title,
description = description,
defaultValue = defaultValue,
isAvailable = isAvailable,
isRequired = isRequired ?: (defaultValue == null),
isSavable = isSavable,
neededAtPhase = neededAtPhase,
validator = validator,
validateOnProjectCreation = validateOnProjectCreation,
type = type
)
} | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/settings/SettingBuilder.kt | 2879162947 |
class A()
<caret>
fun
// WITHOUT_CUSTOM_LINE_INDENT_PROVIDER | plugins/kotlin/idea/tests/testData/indentationOnNewline/AfterClassNameBeforeFun.after.kt | 1683598738 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script.configuration
import com.intellij.openapi.extensions.ProjectExtensionPointName
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsCache
import org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangeListener
import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
/**
* Extension point for overriding default Kotlin scripting support.
*
* Implementation should store script configuration internally (in memory and/or fs),
* and provide it inside [collectConfigurations] using the [ScriptClassRootsCache.LightScriptInfo].
* Custom data can be attached to [ScriptClassRootsCache.LightScriptInfo] and retrieved
* by calling [ScriptClassRootsCache.getLightScriptInfo].
*
* [ScriptChangeListener] can be used to listen script changes.
* [CompositeScriptConfigurationManager.updater] should be used to schedule configuration reloading.
*
* [isApplicable] should return true for files that is covered by that support.
*
* [isConfigurationLoadingInProgress] is used to pause analyzing.
*
* [getConfigurationImmediately] is used to get scripting configuration for a supported file
* (for which [isApplicable] returns true) immediately. It may be useful for intensively created files
* if it is expensive to run full update for each file creation and/or update
*
* Long read: [idea/idea-gradle/src/org/jetbrains/kotlin/idea/scripting/gradle/README.md].
*
* @sample GradleBuildRootsManager
*/
interface ScriptingSupport {
fun isApplicable(file: VirtualFile): Boolean
fun isConfigurationLoadingInProgress(file: KtFile): Boolean
fun collectConfigurations(builder: ScriptClassRootsBuilder)
fun afterUpdate()
fun getConfigurationImmediately(file: VirtualFile): ScriptCompilationConfigurationWrapper? = null
companion object {
val EPN: ProjectExtensionPointName<ScriptingSupport> =
ProjectExtensionPointName("org.jetbrains.kotlin.scripting.idea.scriptingSupport")
}
}
| plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/configuration/ScriptingSupport.kt | 4240880465 |
/*
* Copyright 2010-2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.report.json
/**
* Class representing single JSON element.
* Can be [JsonPrimitive], [JsonArray] or [JsonObject].
*
* [JsonElement.toString] properly prints JSON tree as valid JSON, taking into
* account quoted values and primitives
*/
sealed class JsonElement {
/**
* Convenience method to get current element as [JsonPrimitive]
* @throws JsonElementTypeMismatchException is current element is not a [JsonPrimitive]
*/
open val primitive: JsonPrimitive
get() = error("JsonLiteral")
/**
* Convenience method to get current element as [JsonObject]
* @throws JsonElementTypeMismatchException is current element is not a [JsonObject]
*/
open val jsonObject: JsonObject
get() = error("JsonObject")
/**
* Convenience method to get current element as [JsonArray]
* @throws JsonElementTypeMismatchException is current element is not a [JsonArray]
*/
open val jsonArray: JsonArray
get() = error("JsonArray")
/**
* Convenience method to get current element as [JsonNull]
* @throws JsonElementTypeMismatchException is current element is not a [JsonNull]
*/
open val jsonNull: JsonNull
get() = error("JsonPrimitive")
/**
* Checks whether current element is [JsonNull]
*/
val isNull: Boolean
get() = this === JsonNull
private fun error(element: String): Nothing =
throw JsonElementTypeMismatchException(this::class.toString(), element)
}
/**
* Class representing JSON primitive value. Can be either [JsonLiteral] or [JsonNull].
*/
sealed class JsonPrimitive : JsonElement() {
/**
* Content of given element without quotes. For [JsonNull] this methods returns `"null"`
*/
abstract val content: String
/**
* Content of the given element without quotes or `null` if current element is [JsonNull]
*/
abstract val contentOrNull: String?
@Suppress("LeakingThis")
final override val primitive: JsonPrimitive = this
/**
* Returns content of current element as int
* @throws NumberFormatException if current element is not a valid representation of number
*/
val int: Int get() = content.toInt()
/**
* Returns content of current element as int or `null` if current element is not a valid representation of number
**/
val intOrNull: Int? get() = content.toIntOrNull()
/**
* Returns content of current element as long
* @throws NumberFormatException if current element is not a valid representation of number
*/
val long: Long get() = content.toLong()
/**
* Returns content of current element as long or `null` if current element is not a valid representation of number
*/
val longOrNull: Long? get() = content.toLongOrNull()
/**
* Returns content of current element as double
* @throws NumberFormatException if current element is not a valid representation of number
*/
val double: Double get() = content.toDouble()
/**
* Returns content of current element as double or `null` if current element is not a valid representation of number
*/
val doubleOrNull: Double? get() = content.toDoubleOrNull()
/**
* Returns content of current element as float
* @throws NumberFormatException if current element is not a valid representation of number
*/
val float: Float get() = content.toFloat()
/**
* Returns content of current element as float or `null` if current element is not a valid representation of number
*/
val floatOrNull: Float? get() = content.toFloatOrNull()
/**
* Returns content of current element as boolean
* @throws IllegalStateException if current element doesn't represent boolean
*/
val boolean: Boolean get() = content.toBooleanStrict()
/**
* Returns content of current element as boolean or `null` if current element is not a valid representation of boolean
*/
val booleanOrNull: Boolean? get() = content.toBooleanStrictOrNull()
override fun toString() = content
}
/**
* Class representing JSON literals: numbers, booleans and string.
* Strings are always quoted.
*/
data class JsonLiteral internal constructor(
private val body: Any,
private val isString: Boolean
) : JsonPrimitive() {
override val content = body.toString()
override val contentOrNull: String = content
/**
* Creates number literal
*/
constructor(number: Number) : this(number, false)
/**
* Creates boolean literal
*/
constructor(boolean: Boolean) : this(boolean, false)
/**
* Creates quoted string literal
*/
constructor(string: String) : this(string, true)
override fun toString() =
if (isString) buildString { printQuoted(content) }
else content
fun unquoted() = content
}
/**
* Class representing JSON `null` value
*/
object JsonNull : JsonPrimitive() {
override val jsonNull: JsonNull = this
override val content: String = "null"
override val contentOrNull: String? = null
}
/**
* Class representing JSON object, consisting of name-value pairs, where value is arbitrary [JsonElement]
*/
data class JsonObject(val content: Map<String, JsonElement>) : JsonElement(), Map<String, JsonElement> by content {
override val jsonObject: JsonObject = this
/**
* Returns [JsonElement] associated with given [key]
* @throws NoSuchElementException if element is not present
*/
override fun get(key: String): JsonElement = content[key] ?: throw NoSuchElementException("Element $key is missing")
/**
* Returns [JsonElement] associated with given [key] or `null` if element is not present
*/
fun getOrNull(key: String): JsonElement? = content[key]
/**
* Returns [JsonPrimitive] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
fun getPrimitive(key: String): JsonPrimitive = get(key) as? JsonPrimitive
?: unexpectedJson(key, "JsonPrimitive")
/**
* Returns [JsonObject] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
fun getObject(key: String): JsonObject = get(key) as? JsonObject
?: unexpectedJson(key, "JsonObject")
/**
* Returns [JsonArray] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
fun getArray(key: String): JsonArray = get(key) as? JsonArray
?: unexpectedJson(key, "JsonArray")
/**
* Returns [JsonPrimitive] associated with given [key] or `null` if element
* is not present or has different type
*/
fun getPrimitiveOrNull(key: String): JsonPrimitive? = content[key] as? JsonPrimitive
/**
* Returns [JsonObject] associated with given [key] or `null` if element
* is not present or has different type
*/
fun getObjectOrNull(key: String): JsonObject? = content[key] as? JsonObject
/**
* Returns [JsonArray] associated with given [key] or `null` if element
* is not present or has different type
*/
fun getArrayOrNull(key: String): JsonArray? = content[key] as? JsonArray
/**
* Returns [J] associated with given [key]
*
* @throws NoSuchElementException if element is not present
* @throws JsonElementTypeMismatchException if element is present, but has invalid type
*/
inline fun <reified J : JsonElement> getAs(key: String): J = get(key) as? J
?: unexpectedJson(key, J::class.toString())
/**
* Returns [J] associated with given [key] or `null` if element
* is not present or has different type
*/
inline fun <reified J : JsonElement> lookup(key: String): J? = content[key] as? J
override fun toString(): String {
return content.entries.joinToString(
prefix = "{",
postfix = "}",
transform = {(k, v) -> """"$k": $v"""}
)
}
}
data class JsonArray(val content: List<JsonElement>) : JsonElement(), List<JsonElement> by content {
override val jsonArray: JsonArray = this
/**
* Returns [index]-th element of an array as [JsonPrimitive]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
fun getPrimitive(index: Int) = content[index] as? JsonPrimitive
?: unexpectedJson("at $index", "JsonPrimitive")
/**
* Returns [index]-th element of an array as [JsonObject]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
fun getObject(index: Int) = content[index] as? JsonObject
?: unexpectedJson("at $index", "JsonObject")
/**
* Returns [index]-th element of an array as [JsonArray]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
fun getArray(index: Int) = content[index] as? JsonArray
?: unexpectedJson("at $index", "JsonArray")
/**
* Returns [index]-th element of an array as [JsonPrimitive] or `null` if element is missing or has different type
*/
fun getPrimitiveOrNull(index: Int) = content.getOrNull(index) as? JsonPrimitive
/**
* Returns [index]-th element of an array as [JsonObject] or `null` if element is missing or has different type
*/
fun getObjectOrNull(index: Int) = content.getOrNull(index) as? JsonObject
/**
* Returns [index]-th element of an array as [JsonArray] or `null` if element is missing or has different type
*/
fun getArrayOrNull(index: Int) = content.getOrNull(index) as? JsonArray
/**
* Returns [index]-th element of an array as [J]
* @throws JsonElementTypeMismatchException if element has invalid type
*/
inline fun <reified J : JsonElement> getAs(index: Int): J = content[index] as? J
?: unexpectedJson("at $index", J::class.toString())
/**
* Returns [index]-th element of an array as [J] or `null` if element is missing or has different type
*/
inline fun <reified J : JsonElement> getAsOrNull(index: Int): J? = content.getOrNull(index) as? J
override fun toString() = content.joinToString(prefix = "[", postfix = "]")
}
fun unexpectedJson(key: String, expected: String): Nothing =
throw JsonElementTypeMismatchException(key, expected) | tools/benchmarks/shared/src/main/kotlin/report/json/JsonElement.kt | 1864162891 |
package us.nineworlds.serenity.emby.events
import us.nineworlds.serenity.common.Server
data class EmbyServerFoundEvent(val server: Server) | emby-lib/src/main/kotlin/us/nineworlds/serenity/emby/events/EmbyServerFoundEvent.kt | 1003127878 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test.sequence.exec
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.OutputChecker
import com.intellij.debugger.streams.lib.LibrarySupportProvider
import com.intellij.debugger.streams.psi.DebuggerPositionResolver
import com.intellij.debugger.streams.psi.impl.DebuggerPositionResolverImpl
import com.intellij.debugger.streams.trace.*
import com.intellij.debugger.streams.trace.impl.TraceResultInterpreterImpl
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.StreamChainBuilder
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.util.Computable
import com.intellij.xdebugger.XDebugSessionListener
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches
import org.jetbrains.kotlin.idea.debugger.test.KotlinDescriptorTestCaseWithStepping
import org.jetbrains.kotlin.idea.debugger.test.TestFiles
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences
import java.util.concurrent.atomic.AtomicBoolean
abstract class KotlinTraceTestCase : KotlinDescriptorTestCaseWithStepping() {
private companion object {
val DEFAULT_CHAIN_SELECTOR = ChainSelector.byIndex(0)
}
private lateinit var traceChecker: StreamTraceChecker
override fun initOutputChecker(): OutputChecker {
traceChecker = StreamTraceChecker(this)
return super.initOutputChecker()
}
abstract val librarySupportProvider: LibrarySupportProvider
override fun doMultiFileTest(files: TestFiles, preferences: DebuggerPreferences) {
// Sequence expressions are verbose. Disable expression logging for sequence debugger
KotlinDebuggerCaches.LOG_COMPILATIONS = false
val session = debuggerSession.xDebugSession ?: kotlin.test.fail("XDebugSession is null")
assertNotNull(session)
val completed = AtomicBoolean(false)
val positionResolver = getPositionResolver()
val chainBuilder = getChainBuilder()
val resultInterpreter = getResultInterpreter()
val expressionBuilder = getExpressionBuilder()
val chainSelector = DEFAULT_CHAIN_SELECTOR
session.addSessionListener(object : XDebugSessionListener {
override fun sessionPaused() {
if (completed.getAndSet(true)) {
resume()
return
}
try {
sessionPausedImpl()
} catch (t: Throwable) {
println("Exception caught: $t, ${t.message}", ProcessOutputTypes.SYSTEM)
t.printStackTrace()
resume()
}
}
private fun sessionPausedImpl() {
printContext(debugProcess.debuggerContext)
val chain = ApplicationManager.getApplication().runReadAction(
Computable<StreamChain> {
val elementAtBreakpoint = positionResolver.getNearestElementToBreakpoint(session)
val chains = if (elementAtBreakpoint == null) null else chainBuilder.build(elementAtBreakpoint)
if (chains.isNullOrEmpty()) null else chainSelector.select(chains)
})
if (chain == null) {
complete(null, null, null, FailureReason.CHAIN_CONSTRUCTION)
return
}
EvaluateExpressionTracer(session, expressionBuilder, resultInterpreter).trace(chain, object : TracingCallback {
override fun evaluated(result: TracingResult, context: EvaluationContextImpl) {
complete(chain, result, null, null)
}
override fun evaluationFailed(traceExpression: String, message: String) {
complete(chain, null, message, FailureReason.EVALUATION)
}
override fun compilationFailed(traceExpression: String, message: String) {
complete(chain, null, message, FailureReason.COMPILATION)
}
})
}
private fun complete(chain: StreamChain?, result: TracingResult?, error: String?, errorReason: FailureReason?) {
try {
if (error != null) {
assertNotNull(errorReason)
assertNotNull(chain)
throw AssertionError(error)
} else {
assertNull(errorReason)
handleSuccess(chain, result)
}
} catch (t: Throwable) {
println("Exception caught: " + t + ", " + t.message, ProcessOutputTypes.SYSTEM)
} finally {
resume()
}
}
private fun resume() {
ApplicationManager.getApplication().invokeLater { session.resume() }
}
}, testRootDisposable)
}
private fun getPositionResolver(): DebuggerPositionResolver {
return DebuggerPositionResolverImpl()
}
protected fun handleSuccess(chain: StreamChain?, result: TracingResult?) {
kotlin.test.assertNotNull(chain)
kotlin.test.assertNotNull(result)
println(chain.text, ProcessOutputTypes.SYSTEM)
val trace = result.trace
traceChecker.checkChain(trace)
val resolvedTrace = result.resolve(librarySupportProvider.librarySupport.resolverFactory)
traceChecker.checkResolvedChain(resolvedTrace)
}
private fun getResultInterpreter(): TraceResultInterpreter {
return TraceResultInterpreterImpl(librarySupportProvider.librarySupport.interpreterFactory)
}
private fun getChainBuilder(): StreamChainBuilder {
return librarySupportProvider.chainBuilder
}
private fun getExpressionBuilder(): TraceExpressionBuilder {
return librarySupportProvider.getExpressionBuilder(project)
}
protected enum class FailureReason {
COMPILATION, EVALUATION, CHAIN_CONSTRUCTION
}
@FunctionalInterface
protected interface ChainSelector {
fun select(chains: List<StreamChain>): StreamChain
companion object {
fun byIndex(index: Int): ChainSelector {
return object : ChainSelector {
override fun select(chains: List<StreamChain>): StreamChain = chains[index]
}
}
}
}
} | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/exec/KotlinTraceTestCase.kt | 737902591 |
// 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 training.learn.lesson.general.navigation
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManagerImpl
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.openapi.actionSystem.impl.ActionButtonWithText
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.search.EverythingGlobalScope
import com.intellij.psi.search.ProjectScope
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.util.ui.UIUtil
import training.dsl.*
import training.dsl.LessonUtil.adjustPopupPosition
import training.dsl.LessonUtil.restorePopupPosition
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.course.LessonType
import training.util.LessonEndInfo
import training.util.isToStringContains
import java.awt.Point
import java.awt.event.KeyEvent
import javax.swing.JList
abstract class SearchEverywhereLesson : KLesson("Search everywhere", LessonsBundle.message("search.everywhere.lesson.name")) {
abstract override val sampleFilePath: String?
abstract val resultFileName: String
override val lessonType: LessonType = LessonType.PROJECT
private val requiredClassName = "QuadraticEquationsSolver"
private var backupPopupLocation: Point? = null
override val lessonContent: LessonContext.() -> Unit = {
sdkConfigurationTasks()
task("SearchEverywhere") {
triggerAndBorderHighlight().component { ui: ExtendableTextField ->
UIUtil.getParentOfType(SearchEverywhereUI::class.java, ui) != null
}
text(LessonsBundle.message("search.everywhere.invoke.search.everywhere", LessonUtil.actionName(it),
LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT)))
test { actions(it) }
}
task("que") {
before {
if (backupPopupLocation == null) {
backupPopupLocation = adjustPopupPosition(SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY)
}
}
text(LessonsBundle.message("search.everywhere.type.prefixes", strong("quadratic"), strong("equation"), code(it)))
stateCheck { checkWordInSearch(it) }
restoreByUi()
test {
Thread.sleep(500)
type(it)
}
}
task {
triggerAndBorderHighlight().listItem { item ->
if (item is PsiNameIdentifierOwner)
item.name == requiredClassName
else item.isToStringContains(requiredClassName)
}
restoreByUi()
}
task {
text(LessonsBundle.message("search.everywhere.navigate.to.class", code(requiredClassName), LessonUtil.rawEnter()))
stateCheck {
FileEditorManager.getInstance(project).selectedEditor?.file?.name.equals(resultFileName)
}
restoreByUi()
test {
Thread.sleep(500) // wait items loading
val jList = previous.ui as? JList<*> ?: error("No list")
val itemIndex = LessonUtil.findItem(jList) { item ->
if (item is PsiNameIdentifierOwner)
item.name == requiredClassName
else item.isToStringContains(requiredClassName)
} ?: error("No item")
ideFrame {
jListFixture(jList).clickItem(itemIndex)
}
}
}
actionTask("GotoClass") {
LessonsBundle.message("search.everywhere.goto.class", action(it))
}
task("bufre") {
text(LessonsBundle.message("search.everywhere.type.class.name", code(it)))
stateCheck { checkWordInSearch(it) }
restoreAfterStateBecomeFalse { !checkInsideSearchEverywhere() }
test { type(it) }
}
task(EverythingGlobalScope.getNameText()) {
text(LessonsBundle.message("search.everywhere.use.all.places",
strong(ProjectScope.getProjectFilesScopeName()), strong(it)))
triggerAndFullHighlight().component { _: ActionButtonWithText -> true }
triggerUI().component { button: ActionButtonWithText ->
button.accessibleContext.accessibleName == it
}
showWarning(LessonsBundle.message("search.everywhere.class.popup.closed.warning.message", action("GotoClass"))) {
!checkInsideSearchEverywhere() && focusOwner !is JList<*>
}
test {
invokeActionViaShortcut("ALT P")
}
}
task("QuickJavaDoc") {
text(LessonsBundle.message("search.everywhere.quick.documentation", action(it)))
triggerOnQuickDocumentationPopup()
restoreByUi()
test { actions(it) }
}
task {
text(LessonsBundle.message("search.everywhere.close.documentation.popup", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck { previous.ui?.isShowing != true }
test { invokeActionViaShortcut("ENTER") }
}
task {
text(LessonsBundle.message("search.everywhere.finish", action("GotoSymbol"), action("GotoFile")))
}
if (TaskTestContext.inTestMode) task {
stateCheck { focusOwner is EditorComponentImpl }
test {
invokeActionViaShortcut("ESCAPE")
invokeActionViaShortcut("ESCAPE")
}
}
epilogue()
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
restorePopupPosition(project, SearchEverywhereManagerImpl.LOCATION_SETTINGS_KEY, backupPopupLocation)
backupPopupLocation = null
}
open fun LessonContext.epilogue() = Unit
private fun TaskRuntimeContext.checkWordInSearch(expected: String): Boolean =
(focusOwner as? ExtendableTextField)?.text?.equals(expected, ignoreCase = true) == true
private fun TaskRuntimeContext.checkInsideSearchEverywhere(): Boolean {
return UIUtil.getParentOfType(SearchEverywhereUI::class.java, focusOwner) != null
}
override val suitableTips = listOf("SearchEverywhere", "GoToClass", "search_everywhere_general")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("help.search.everywhere"),
LessonUtil.getHelpLink("searching-everywhere.html")),
)
} | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/SearchEverywhereLesson.kt | 4225881514 |
class Collections {
fun test() {
val x: List<String> = mutableListOf("A", "B")
val xx: List<String?> = mutableListOf("A", null)
val y = listOf("C")
val z = setOf("D")
}
} | plugins/kotlin/j2k/new/tests/testData/newJ2k/collections/common.kt | 2830879587 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build
import org.jetbrains.intellij.build.impl.MavenArtifactsBuilder
import org.junit.Assert
import org.junit.Test
class MavenArtifactsBuilderTest {
@Test
fun `maven coordinates`() {
checkCoordinates("intellij.xml", "com.jetbrains.intellij.xml", "xml")
checkCoordinates("intellij.xml.impl", "com.jetbrains.intellij.xml", "xml-impl")
checkCoordinates("intellij.java.debugger", "com.jetbrains.intellij.java", "java-debugger")
checkCoordinates("intellij.platform.util", "com.jetbrains.intellij.platform", "util")
checkCoordinates("intellij.platform.testFramework.common", "com.jetbrains.intellij.platform", "test-framework-common")
checkCoordinates("intellij.platform.testFramework.junit5", "com.jetbrains.intellij.platform", "test-framework-junit5")
checkCoordinates("intellij.platform.testFramework", "com.jetbrains.intellij.platform", "test-framework")
checkCoordinates("intellij.java.compiler.antTasks", "com.jetbrains.intellij.java", "java-compiler-ant-tasks")
checkCoordinates("intellij.platform.vcs.log", "com.jetbrains.intellij.platform", "vcs-log")
checkCoordinates("intellij.spring", "com.jetbrains.intellij.spring", "spring")
checkCoordinates("intellij.spring.boot", "com.jetbrains.intellij.spring", "spring-boot")
checkCoordinates("intellij.junit.v5.rt", "com.jetbrains.intellij.junit", "junit-v5-rt")
}
private fun checkCoordinates(moduleName: String, expectedGroupId: String, expectedArtifactId: String) {
val coordinates = MavenArtifactsBuilder.generateMavenCoordinates(moduleName, "snapshot")
Assert.assertEquals("Incorrect groupId generated for $moduleName", expectedGroupId, coordinates.groupId)
Assert.assertEquals("Incorrect artifactId generated for $moduleName", expectedArtifactId, coordinates.artifactId)
}
} | platform/build-scripts/tests/testSrc/org/jetbrains/intellij/build/MavenArtifactsBuilderTest.kt | 681566827 |
public class A @JvmOverloads constructor<caret>(
public val x: Int = 0,
public val y: Double = 0.0,
public val z: String = "0"
) | plugins/kotlin/idea/tests/testData/refactoring/changeSignature/JvmOverloadedConstructorSwapParamsBefore.kt | 1730371050 |
class Outer {
companion object {
class SomeClass : java.io.Serializable {
companion object CompanionName {
private object SomeObject {
fun String.someFun(p: Int, b: Boolean): String {
fun localFun() {
val v = doIt(fun (x: Int, y: Char) {
<caret>
})
}
}
}
}
}
}
}
| plugins/kotlin/idea/tests/testData/codeInsight/breadcrumbs/Declarations.kt | 967858315 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.test.utils.IgnoreTests
import java.io.File
abstract class AbstractK1IntentionTest : AbstractIntentionTestBase() {
override fun doTestFor(mainFile: File, pathToFiles: Map<String, PsiFile>, intentionAction: IntentionAction, fileText: String) {
IgnoreTests.runTestIfNotDisabledByFileDirective(mainFile.toPath(), IgnoreTests.DIRECTIVES.IGNORE_FE10) {
super.doTestFor(mainFile, pathToFiles, intentionAction, fileText)
}
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/intentions/AbstractK1IntentionTest.kt | 546925700 |
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtObjectDeclaration
// OPTIONS: usages, constructorUsages
// FIND_BY_REF
// WITH_FILE_NAME
package usages
import library.*
fun test() {
val a = A.<caret>Companion
}
// FIR_COMPARISON | plugins/kotlin/idea/tests/testData/findUsages/libraryUsages/kotlinLibrary/LibraryCompanionObjectUsages.0.kt | 253529079 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui
import com.intellij.collaboration.async.collectScoped
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.collaboration.ui.CollaborationToolsUIUtil.isDefault
import com.intellij.collaboration.ui.util.bindDisabled
import com.intellij.collaboration.ui.util.bindVisibility
import com.intellij.collaboration.util.URIUtil
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.content.Content
import git4idea.remote.hosting.ui.RepositoryAndAccountSelectorComponentFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.plugins.gitlab.api.GitLabApiManager
import org.jetbrains.plugins.gitlab.api.GitLabProjectCoordinates
import org.jetbrains.plugins.gitlab.authentication.GitLabLoginUtil
import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager
import org.jetbrains.plugins.gitlab.authentication.ui.GitLabAccountsDetailsProvider
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabToolWindowTabViewModel.NestedViewModel
import org.jetbrains.plugins.gitlab.mergerequest.ui.list.GitLabMergeRequestsPanelFactory
import org.jetbrains.plugins.gitlab.util.GitLabBundle
import org.jetbrains.plugins.gitlab.util.GitLabProjectMapping
import java.awt.BorderLayout
import java.awt.event.ActionEvent
import javax.swing.*
internal class GitLabToolWindowTabController(private val project: Project,
scope: CoroutineScope,
tabVm: GitLabToolWindowTabViewModel,
private val content: Content) {
init {
scope.launch {
tabVm.nestedViewModelState.collectScoped { scope, vm ->
content.displayName = GitLabBundle.message("title.merge.requests")
val component = when (vm) {
is NestedViewModel.Selectors -> createSelectorsComponent(scope, vm)
is NestedViewModel.MergeRequests -> createMergeRequestsComponent(scope, vm)
}
CollaborationToolsUIUtil.setComponentPreservingFocus(content, component)
}
}
}
private fun createSelectorsComponent(scope: CoroutineScope, vm: NestedViewModel.Selectors): JComponent {
val accountsDetailsProvider = GitLabAccountsDetailsProvider(scope) {
// TODO: separate loader
service<GitLabAccountManager>().findCredentials(it)?.let(service<GitLabApiManager>()::getClient)
}
val selectorVm = vm.selectorVm
val selectors = RepositoryAndAccountSelectorComponentFactory(selectorVm).create(
scope = scope,
repoNamer = { mapping ->
val allProjects = vm.selectorVm.repositoriesState.value.map { it.repository }
getProjectDisplayName(allProjects, mapping.repository)
},
detailsProvider = accountsDetailsProvider,
accountsPopupActionsSupplier = { createPopupLoginActions(selectorVm, it) },
credsMissingText = GitLabBundle.message("account.token.missing"),
submitActionText = GitLabBundle.message("view.merge.requests.button"),
loginButtons = createLoginButtons(scope, selectorVm)
)
scope.launch {
selectorVm.loginRequestsFlow.collect { req ->
val account = req.account
if (account == null) {
val (newAccount, token) = GitLabLoginUtil.logInViaToken(project, selectors, req.repo.repository.serverPath) { server, name ->
req.accounts.none { it.server == server || it.name == name }
} ?: return@collect
req.login(newAccount, token)
}
else {
val token = GitLabLoginUtil.updateToken(project, selectors, account) { server, name ->
req.accounts.none { it.server == server || it.name == name }
} ?: return@collect
req.login(account, token)
}
}
}
return JPanel(BorderLayout()).apply {
add(selectors, BorderLayout.NORTH)
}
}
private fun createMergeRequestsComponent(scope: CoroutineScope, vm: NestedViewModel.MergeRequests): JComponent =
GitLabMergeRequestsPanelFactory().create(scope, vm.listVm)
private fun createLoginButtons(scope: CoroutineScope, vm: GitLabRepositoryAndAccountSelectorViewModel)
: List<JButton> {
return listOf(
JButton(CollaborationToolsBundle.message("login.button")).apply {
isDefault = true
isOpaque = false
addActionListener {
vm.requestTokenLogin(false, true)
}
bindDisabled(scope, vm.busyState)
bindVisibility(scope, vm.tokenLoginAvailableState)
}
)
}
private fun createPopupLoginActions(vm: GitLabRepositoryAndAccountSelectorViewModel, mapping: GitLabProjectMapping?): List<Action> {
if (mapping == null) return emptyList()
return listOf(object : AbstractAction(CollaborationToolsBundle.message("login.button")) {
override fun actionPerformed(e: ActionEvent?) {
vm.requestTokenLogin(true, false)
}
})
}
private fun getProjectDisplayName(allProjects: List<GitLabProjectCoordinates>, project: GitLabProjectCoordinates): @NlsSafe String {
val showServer = needToShowServer(allProjects)
val builder = StringBuilder()
if (showServer) builder.append(URIUtil.toStringWithoutScheme(project.serverPath.toURI())).append("/")
builder.append(project.projectPath.owner).append("/")
builder.append(project.projectPath.name)
return builder.toString()
}
private fun needToShowServer(projects: List<GitLabProjectCoordinates>): Boolean {
if (projects.size <= 1) return false
val firstServer = projects.first().serverPath
return projects.any { it.serverPath != firstServer }
}
} | plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/GitLabToolWindowTabController.kt | 1455550628 |
import B.X as XX
fun bar(s: String) {
XX = s
} | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveField/moveFieldToTopLevelClassAndMakePrivate/after/specificImport.kt | 3243135013 |
// WITH_STDLIB
// DISABLE-ERRORS
class FooException : Exception()
class BarException : Exception()
@Throws(exceptionClasses = BarException::class)
fun test() {
<caret>throw FooException()
} | plugins/kotlin/idea/tests/testData/intentions/addThrowsAnnotation/hasThrowsWithDifferentClassArgument2.kt | 4073403931 |
fun foo(a: Int, b: String, c: String) {}
fun foo(a: Int, b: String) {}
fun bar(b: String, a: Int, c: String) {
foo(<caret>)
}
// EXIST: "a, b, c"
// EXIST: "a, b"
| plugins/kotlin/completion/tests/testData/smart/multipleArgsItem/7.kt | 362577193 |
fun foo(p : (String, Char) -> Boolean){}
fun main(args: Array<String>) {
fo<caret>{ x }
}
// ELEMENT: foo
// TAIL_TEXT: " { String, Char -> ... } (p: (String, Char) -> Boolean) (<root>)"
| plugins/kotlin/completion/tests/testData/handlers/basic/highOrderFunctions/WithArgsNonEmptyLambdaAfter.kt | 661772968 |
package biz.dealnote.messenger.model
class PeerUpdate(val accountId: Int, val peerId: Int) {
var readIn: Read? = null
var readOut: Read? = null
var lastMessage: LastMessage? = null
var unread: Unread? = null
var pin: Pin? = null
var title: Title? = null
class Read (val messageId: Int)
class Unread(val count: Int)
class LastMessage(val messageId: Int)
class Pin(val pinned: Message?)
class Title(val title: String?)
} | app/src/main/java/biz/dealnote/messenger/model/PeerUpdate.kt | 2993756065 |
/*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.utils
import android.app.ProgressDialog
import android.content.Context
import android.content.pm.ApplicationInfo
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import com.zwq65.unity.R
import java.io.File
/**
* ================================================
*
* Created by NIRVANA on 2017/01/27
* Contact with <[email protected]>
* ================================================
*/
object CommonUtils {
val imageStorePath: String
get() {
var path: String = if (getSdCardIsEnable()) {
getSdCardPath()
} else {
getDataAbsolutePath()
}
path = path + "Unity" + File.separator + "image" + File.separator
return path
}
fun showLoadingDialog(context: Context): ProgressDialog {
val progressDialog = ProgressDialog(context)
progressDialog.show()
if (progressDialog.window != null) {
progressDialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
}
progressDialog.setContentView(R.layout.progress_dialog)
progressDialog.isIndeterminate = true
progressDialog.setCancelable(false)
progressDialog.setCanceledOnTouchOutside(false)
return progressDialog
}
/**
* 判断当前应用是否是debug状态
*/
fun isApkInDebug(context: Context): Boolean {
return try {
val info = context.applicationInfo
info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
} catch (e: Exception) {
false
}
}
/**
* 用于取得recycleView当前最大的position以判断是否许需要加载
*
* @param lastPositions recycleView底部的position数组
* @return 最大的position
*/
fun findMax(lastPositions: IntArray): Int {
return lastPositions.max() ?: lastPositions[0]
}
}
| app/src/main/java/com/zwq65/unity/utils/CommonUtils.kt | 706339118 |
package ch.rmy.android.http_shortcuts.variables.types
import android.content.Context
import ch.rmy.android.framework.extensions.addOrRemove
import ch.rmy.android.framework.extensions.runFor
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableRepository
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.extensions.showOrElse
import ch.rmy.android.http_shortcuts.utils.ActivityProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.coroutines.resume
class SelectType : BaseVariableType() {
@Inject
lateinit var variablesRepository: VariableRepository
@Inject
lateinit var activityProvider: ActivityProvider
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun resolveValue(context: Context, variable: VariableModel): String {
val value = withContext(Dispatchers.Main) {
suspendCancellableCoroutine<String> { continuation ->
createDialogBuilder(activityProvider.getActivity(), variable, continuation)
.run {
if (isMultiSelect(variable)) {
val selectedOptions = mutableListOf<String>()
runFor(variable.options!!) { option ->
checkBoxItem(name = option.labelOrValue, checked = { option.id in selectedOptions }) { isChecked ->
selectedOptions.addOrRemove(option.id, isChecked)
}
}
.positive(R.string.dialog_ok) {
continuation.resume(
selectedOptions
.mapNotNull { optionId ->
variable.options!!.find { it.id == optionId }
}
.joinToString(getSeparator(variable)) { option ->
option.value
}
)
}
} else {
runFor(variable.options!!) { option ->
item(name = option.labelOrValue) {
continuation.resume(option.value)
}
}
}
}
.showOrElse {
continuation.cancel()
}
}
}
if (variable.rememberValue) {
variablesRepository.setVariableValue(variable.id, value)
}
return value
}
companion object {
const val KEY_MULTI_SELECT = "multi_select"
const val KEY_SEPARATOR = "separator"
fun isMultiSelect(variable: VariableModel) =
variable.dataForType[KEY_MULTI_SELECT]?.toBoolean() ?: false
fun getSeparator(variable: VariableModel) =
variable.dataForType[KEY_SEPARATOR] ?: ","
}
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/variables/types/SelectType.kt | 1314358244 |
package com.dreampany.framework.data.source.api
import com.dreampany.framework.data.enums.State
import com.dreampany.framework.data.enums.Subtype
import com.dreampany.framework.data.enums.Type
import com.dreampany.framework.data.model.Store
import io.reactivex.Maybe
/**
* Created by Roman-372 on 7/12/2019
* Copyright (c) 2019 bjit. All rights reserved.
* [email protected]
* Last modified $file.lastModified
*/
interface StoreDataSource : DataSource<Store> {
fun isExists(id: String, type: Type, subtype: Subtype, state: State): Boolean
fun isExistsRx(id: String, type: Type, subtype: Subtype, state: State): Maybe<Boolean>
fun getCount(id: String, type: Type, subtype: Subtype): Int
fun getCount(id: String, type: Type, subtype: Subtype, state: State): Int
fun getCountRx(id: String, type: Type, subtype: Subtype): Maybe<Int>
fun getCountByType(type: Type, subtype: Subtype, state: State): Int
fun getCountByTypeRx(type: Type, subtype: Subtype, state: State): Maybe<Int>
fun getItem(type: Type, subtype: Subtype, state: State): Store?
fun getRandomItem(type: Type, subtype: Subtype, state: State): Store?
fun getItem(id: String, type: Type, subtype: Subtype, state: State): Store?
fun getItemRx(id: String, type: Type, subtype: Subtype, state: State): Maybe<Store>
fun getItems(type: Type, subtype: Subtype, state: State): List<Store>?
fun getItemsRx(type: Type, subtype: Subtype, state: State): Maybe<List<Store>>
} | frame/src/main/kotlin/com/dreampany/framework/data/source/api/StoreDataSource.kt | 3318516856 |
package com.vicpin.sample.view.adapter
import android.view.View
import com.vicpin.kpresenteradapter.ViewHolder
import com.vicpin.sample.R
import com.vicpin.sample.model.Country
import com.vicpin.sample.view.presenter.HeaderPresenter
import kotlinx.android.synthetic.main.adapter_header.*
/**
* Created by Victor on 25/06/2016.
*/
class HeaderView(itemView: View) : ViewHolder<Country>(itemView), HeaderPresenter.View {
override var presenter = HeaderPresenter()
override fun setNumItems(numItems: Int) {
headerText.text = context.getString(R.string.header, numItems)
}
}
| sample/src/main/java/com/vicpin/sample/view/adapter/HeaderView.kt | 873662729 |
package com.conorodonnell.bus.persistence
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Stop::class], version = 2, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun stops(): StopRepository
}
| app/src/main/java/com/conorodonnell/bus/persistence/AppDatabase.kt | 2065687292 |
/**
* BreadWallet
*
* Created by Mihail Gutan <[email protected]> on 11/28/16.
* Copyright (c) 2016 breadwallet LLC
*
* 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.breadwallet.tools.crypto
import android.text.format.DateUtils
import com.breadwallet.crypto.Coder
import com.breadwallet.crypto.Hasher
import com.breadwallet.crypto.Key
import com.breadwallet.crypto.Signer
import java.nio.ByteBuffer
import java.nio.ByteOrder
@Suppress("TooManyFunctions")
object CryptoHelper {
private const val NONCE_SIZE = 12
private val base58: Coder by lazy {
Coder.createForAlgorithm(Coder.Algorithm.BASE58)
}
private val sha256: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.SHA256)
}
private val sha256_2: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.SHA256_2)
}
private val md5: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.MD5)
}
private val keccak256: Hasher by lazy {
Hasher.createForAlgorithm(Hasher.Algorithm.KECCAK256)
}
private val compact: Signer by lazy {
Signer.createForAlgorithm(Signer.Algorithm.COMPACT)
}
private val jose: Signer by lazy {
Signer.createForAlgorithm(Signer.Algorithm.BASIC_JOSE)
}
private val basicDer: Signer by lazy {
Signer.createForAlgorithm(Signer.Algorithm.BASIC_DER)
}
private val hex: Coder by lazy {
Coder.createForAlgorithm(Coder.Algorithm.HEX)
}
@JvmStatic
fun hexEncode(data: ByteArray): String {
return hex.encode(data).or("")
}
@JvmStatic
fun hexDecode(data: String): ByteArray? {
return hex.decode(data).orNull()
}
fun signCompact(data: ByteArray, key: Key): ByteArray {
return compact.sign(data, key).or(byteArrayOf())
}
fun signJose(data: ByteArray, key: Key): ByteArray {
return jose.sign(data, key).or(byteArrayOf())
}
fun signBasicDer(data: ByteArray, key: Key): ByteArray {
return basicDer.sign(data, key).or(byteArrayOf())
}
fun base58Encode(data: ByteArray): String {
return base58.encode(data).or("")
}
fun base58Decode(data: String): ByteArray {
return base58.decode(data).or(byteArrayOf())
}
@JvmStatic
fun base58ofSha256(toEncode: ByteArray): String {
val sha256First = sha256(toEncode)
return base58.encode(sha256First).or("")
}
@JvmStatic
fun doubleSha256(data: ByteArray): ByteArray? {
return sha256_2.hash(data).orNull()
}
@JvmStatic
fun sha256(data: ByteArray?): ByteArray? {
return sha256.hash(data).orNull()
}
@JvmStatic
fun md5(data: ByteArray): ByteArray? {
return md5.hash(data).orNull()
}
fun keccak256(data: ByteArray): ByteArray? {
return keccak256.hash(data).orNull()
}
/**
* generate a nonce using microseconds-since-epoch
*/
@JvmStatic
@Suppress("MagicNumber")
fun generateRandomNonce(): ByteArray {
val nonce = ByteArray(NONCE_SIZE)
val buffer = ByteBuffer.allocate(8)
val t = System.nanoTime() / DateUtils.SECOND_IN_MILLIS
buffer.order(ByteOrder.LITTLE_ENDIAN)
buffer.putLong(t)
val byteTime = buffer.array()
System.arraycopy(byteTime, 0, nonce, 4, byteTime.size)
return nonce
}
}
| app-core/src/main/java/com/breadwallet/tools/crypto/CryptoHelper.kt | 205466842 |
/*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.interfaze
import android.view.View
/**
* Created by lizhaotailang on 2016/3/18.
*
* OnClickListener for [android.support.v7.widget.RecyclerView] item.
*/
interface OnRecyclerViewItemOnClickListener {
fun onItemClick(v: View, position: Int)
}
| app/src/main/java/com/marktony/zhihudaily/interfaze/OnRecyclerViewItemOnClickListener.kt | 3153913601 |
package org.jetbrains.ide
import com.intellij.testFramework.ProjectRule
import com.intellij.util.Consumer
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.net.NetUtils
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInitializer
import io.netty.util.CharsetUtil
import junit.framework.TestCase
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.io.ChannelExceptionHandler
import org.jetbrains.io.Decoder
import org.jetbrains.io.MessageDecoder
import org.jetbrains.io.NettyUtil
import org.junit.ClassRule
import org.junit.Test
import java.util.*
import java.util.concurrent.TimeUnit
// we don't handle String in efficient way - because we want to test readContent/readChars also
internal class BinaryRequestHandlerTest {
companion object {
@ClassRule val projectRule = ProjectRule()
}
@Test fun test() {
val text = "Hello!"
val result = AsyncPromise<String>()
val bootstrap = NettyUtil.oioClientBootstrap().handler(object : ChannelInitializer<Channel>() {
override fun initChannel(channel: Channel) {
channel.pipeline().addLast(object : Decoder() {
override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) {
val requiredLength = 4 + text.length()
val response = readContent(input, context, requiredLength) { buffer, context, isCumulateBuffer -> buffer.toString(buffer.readerIndex(), requiredLength, CharsetUtil.UTF_8) }
if (response != null) {
result.setResult(response)
}
}
}, ChannelExceptionHandler.getInstance())
}
})
val port = BuiltInServerManager.getInstance().waitForStart().port
val channel = bootstrap.connect(NetUtils.getLoopbackAddress(), port).syncUninterruptibly().channel()
val buffer = channel.alloc().buffer()
buffer.writeByte('C'.toInt())
buffer.writeByte('H'.toInt())
buffer.writeLong(MyBinaryRequestHandler.ID.mostSignificantBits)
buffer.writeLong(MyBinaryRequestHandler.ID.leastSignificantBits)
val message = Unpooled.copiedBuffer(text, CharsetUtil.UTF_8)
buffer.writeShort(message.readableBytes())
channel.write(buffer)
channel.writeAndFlush(message).await(5, TimeUnit.SECONDS)
try {
result.rejected(object : Consumer<Throwable> {
override fun consume(error: Throwable) {
TestCase.fail(error.getMessage())
}
})
if (result.state == Promise.State.PENDING) {
val semaphore = Semaphore()
semaphore.down()
result.processed { semaphore.up() }
if (!semaphore.waitForUnsafe(5000)) {
TestCase.fail("Time limit exceeded")
return
}
}
TestCase.assertEquals("got-" + text, result.get())
}
finally {
channel.close()
}
}
class MyBinaryRequestHandler : BinaryRequestHandler() {
companion object {
val ID = UUID.fromString("E5068DD6-1DB7-437C-A3FC-3CA53B6E1AC9")
}
override fun getId(): UUID {
return ID
}
override fun getInboundHandler(context: ChannelHandlerContext): ChannelHandler {
return MyDecoder()
}
private class MyDecoder : MessageDecoder() {
private var state = State.HEADER
private enum class State {
HEADER,
CONTENT
}
override fun messageReceived(context: ChannelHandlerContext, input: ByteBuf) {
while (true) {
when (state) {
State.HEADER -> {
val buffer = getBufferIfSufficient(input, 2, context) ?: return
contentLength = buffer.readUnsignedShort()
state = State.CONTENT
}
State.CONTENT -> {
val messageText = readChars(input) ?: return
state = State.HEADER
context.writeAndFlush(Unpooled.copiedBuffer("got-" + messageText, CharsetUtil.UTF_8))
}
}
}
}
}
}
} | platform/built-in-server/testSrc/BinaryRequestHandlerTest.kt | 3061997654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.