content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* TransitRegion.kt
*
* Copyright 2019 Google
*
* 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 au.id.micolous.metrodroid.transit
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.multi.StringResource
import au.id.micolous.metrodroid.util.iso3166AlphaToName
import au.id.micolous.metrodroid.util.Collator
import au.id.micolous.metrodroid.util.Preferences
sealed class TransitRegion {
abstract val translatedName: String
open val sortingKey: Pair<Int, String>
get() = Pair(SECTION_MAIN, translatedName)
data class Iso (val code: String): TransitRegion () {
override val translatedName: String
get() = iso3166AlphaToName(code) ?: code
override val sortingKey: Pair<Int, String>
get() = Pair(
if (code == deviceRegion) SECTION_NEARBY else SECTION_MAIN,
translatedName)
}
object Crimea : TransitRegion () {
override val translatedName: String
get() = Localizer.localizeString(R.string.location_crimea)
override val sortingKey
get() = Pair(
if (deviceRegion in listOf("RU", "UA")) SECTION_NEARBY else SECTION_MAIN,
translatedName)
}
data class SectionItem(val res: StringResource,
val section: Int): TransitRegion () {
override val translatedName: String
get() = Localizer.localizeString(res)
override val sortingKey
get() = Pair(section, translatedName)
}
object RegionComparator : Comparator<TransitRegion> {
val collator = Collator.collator
override fun compare(a: TransitRegion, b: TransitRegion): Int {
val ak = a.sortingKey
val bk = b.sortingKey
if (ak.first != bk.first) {
return ak.first.compareTo(bk.first)
}
return collator.compare(ak.second, bk.second)
}
}
companion object {
// On very top put cards tha are most likely to be relevant to the user
const val SECTION_NEARBY = -2
// Then put "Worldwide" cards like EMV and Amiibo
const val SECTION_WORLDWIDE = -1
// Then goes the rest
const val SECTION_MAIN = 0
private val deviceRegion = Preferences.region
val AUSTRALIA = Iso("AU")
val BELGIUM = Iso("BE")
val BRAZIL = Iso("BR")
val CANADA = Iso("CA")
val CHILE = Iso("CL")
val CHINA = Iso("CN")
val CRIMEA = Crimea
val DENMARK = Iso("DK")
val ESTONIA = Iso("EE")
val FINLAND = Iso("FI")
val FRANCE = Iso("FR")
val GEORGIA = Iso("GE")
val GERMANY = Iso("DE")
val HONG_KONG = Iso("HK")
val INDONESIA = Iso("ID")
val IRELAND = Iso("IE")
val ISRAEL = Iso("IL")
val ITALY = Iso("IT")
val JAPAN = Iso("JP")
val MALAYSIA = Iso("MY")
val NETHERLANDS = Iso("NL")
val NEW_ZEALAND = Iso("NZ")
val POLAND = Iso("PL")
val PORTUGAL = Iso("PT")
val RUSSIA = Iso("RU")
val SINGAPORE = Iso("SG")
val SOUTH_AFRICA = Iso("ZA")
val SOUTH_KOREA = Iso("KR")
val SPAIN = Iso("ES")
val SWEDEN = Iso("SE")
val SWITZERLAND = Iso("CH")
val TAIPEI = Iso("TW")
val TURKEY = Iso("TR")
val UAE = Iso("AE")
val UK = Iso("GB")
val UKRAINE = Iso("UA")
val USA = Iso("US")
val WORLDWIDE = SectionItem(R.string.location_worldwide,
SECTION_WORLDWIDE)
}
}
| src/commonMain/kotlin/au/id/micolous/metrodroid/transit/TransitRegion.kt | 3658463460 |
package rs.emulate.common.config.location
import io.netty.buffer.ByteBuf
import rs.emulate.common.config.Config
import rs.emulate.common.config.ConfigDecoder
import rs.emulate.common.config.npc.MorphismSet
import rs.emulate.util.readAsciiString
object LocationDefinitionDecoder : ConfigDecoder<LocationDefinition> {
override fun decode(id: Int, buffer: ByteBuf): LocationDefinition {
val definition = LocationDefinition(id)
var opcode = buffer.readUnsignedByte().toInt()
while (opcode != Config.DEFINITION_TERMINATOR) {
definition.decode(buffer, opcode)
opcode = buffer.readUnsignedByte().toInt()
}
definition.apply {
if (interactive == -1) {
interactive = if (actions.isNotEmpty()) {
1
} else if (models.isNotEmpty() && (modelTypes.isEmpty() || modelTypes.first() == 10)) {
1
} else {
0
}
}
if (hollow) {
solid = false
impenetrable = false
}
if (supportsItems == -1) {
supportsItems = if (solid) 1 else 0
}
}
return definition
}
private fun LocationDefinition.decode(buffer: ByteBuf, opcode: Int) {
when (opcode) {
1 -> {
val count = buffer.readUnsignedByte().toInt()
models = IntArray(count)
modelTypes = IntArray(count)
repeat(count) { index ->
models[index] = buffer.readUnsignedShort()
modelTypes[index] = buffer.readUnsignedByte().toInt()
}
}
2 -> name = buffer.readAsciiString()
3 -> description = buffer.readAsciiString()
5 -> {
val count = buffer.readUnsignedByte().toInt()
models = IntArray(count) { buffer.readUnsignedShort() }
}
14 -> width = buffer.readUnsignedByte().toInt()
15 -> length = buffer.readUnsignedByte().toInt()
17 -> solid = false
18 -> impenetrable = false
19 -> interactive = buffer.readUnsignedByte().toInt()
21 -> contourGround = true
22 -> delayShading = true
23 -> occludes = true
24 -> sequenceId = buffer.readUnsignedShort().let { if (it == 65535) -1 else it }
28 -> decorDisplacement = buffer.readUnsignedByte().toInt()
29 -> brightness = buffer.readByte().toInt()
in 30 until 39 -> actions[opcode - 30] = buffer.readAsciiString().let { if (it == "hidden") null else it }
39 -> diffusion = buffer.readByte().toInt()
40 -> {
val count = buffer.readUnsignedByte().toInt()
repeat(count) {
val original = buffer.readUnsignedShort()
val replacement = buffer.readUnsignedShort()
colours[original] = replacement
}
}
60 -> minimapFunction = buffer.readUnsignedShort()
62 -> inverted = true
64 -> castShadow = false
65 -> scaleX = buffer.readUnsignedShort()
66 -> scaleY = buffer.readUnsignedShort()
67 -> scaleZ = buffer.readUnsignedShort()
68 -> mapsceneId = buffer.readUnsignedShort()
69 -> surroundings = buffer.readUnsignedByte().toInt()
70 -> translateX = buffer.readShort().toInt()
71 -> translateY = buffer.readShort().toInt()
72 -> translateZ = buffer.readShort().toInt()
73 -> obstructsGround = true
74 -> hollow = true
75 -> supportsItems = buffer.readUnsignedByte().toInt()
77 -> morphisms = MorphismSet.decode(buffer)
}
}
}
| common/src/main/kotlin/rs/emulate/common/config/location/LocationDefinitionDecoder.kt | 3166353948 |
package siarhei.luskanau.iot.doorbell.ui.imagedetails.slide
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.Lifecycle
import androidx.test.espresso.Espresso
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import com.karumi.shot.ScreenshotTest
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
import siarhei.luskanau.iot.doorbell.data.model.ImageData
import siarhei.luskanau.iot.doorbell.ui.imagedetails.R
import kotlin.test.Test
import siarhei.luskanau.iot.doorbell.ui.common.R as CommonR
class ImageDetailsSlideFragmentTest : ScreenshotTest {
private fun createFragment(state: ImageDetailsSlideState) = ImageDetailsSlideFragment {
mockk(relaxed = true, relaxUnitFun = true) {
every { getImageDetailsSlideStateFlow() } returns flowOf(state)
}
}
@Test
fun testNormalState() {
val expectedImageData = ImageData(
imageId = "expectedImageId",
imageUri = "expectedImageUri",
timestampString = "timestampString"
)
val scenario = launchFragmentInContainer(themeResId = CommonR.style.AppTheme) {
createFragment(state = NormalImageDetailsSlideState(imageData = expectedImageData))
}
scenario.moveToState(Lifecycle.State.RESUMED)
// normal view is displayed
Espresso.onView(ViewMatchers.withId(R.id.imageView))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
// error view does not exist
Espresso.onView(ViewMatchers.withId(CommonR.id.error_message))
.check(ViewAssertions.doesNotExist())
scenario.onFragment {
compareScreenshot(
fragment = it,
name = javaClass.simpleName + ".normal"
)
}
}
@Test
fun testErrorState() {
val expectedErrorMessage = "Test Exception"
val scenario = launchFragmentInContainer(themeResId = CommonR.style.AppTheme) {
createFragment(
state = ErrorImageDetailsSlideState(error = RuntimeException(expectedErrorMessage))
)
}
scenario.moveToState(Lifecycle.State.RESUMED)
// error view is displayed
Espresso.onView(ViewMatchers.withId(CommonR.id.error_message))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
Espresso.onView(ViewMatchers.withText(expectedErrorMessage))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
// normal view does not exist
Espresso.onView(ViewMatchers.withId(R.id.imageView))
.check(ViewAssertions.doesNotExist())
scenario.onFragment {
compareScreenshot(
fragment = it,
name = javaClass.simpleName + ".empty"
)
}
}
}
| ui/ui_image_details/src/androidTest/kotlin/siarhei/luskanau/iot/doorbell/ui/imagedetails/slide/ImageDetailsSlideFragmentTest.kt | 921469554 |
package com.kiwiandroiddev.sc2buildassistant.feature.settings.domain.datainterface
import io.reactivex.Completable
interface ClearDatabaseAgent {
fun clear(): Completable
} | app/src/main/java/com/kiwiandroiddev/sc2buildassistant/feature/settings/domain/datainterface/ClearDatabaseAgent.kt | 4234427136 |
package com.eden.orchid.github.wiki
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.annotations.Validate
import com.eden.orchid.api.resources.resource.FileResource
import com.eden.orchid.api.resources.resource.StringResource
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.api.util.GitFacade
import com.eden.orchid.api.util.GitRepoFacade
import com.eden.orchid.utilities.OrchidUtils
import com.eden.orchid.utilities.SuppressedWarnings
import com.eden.orchid.wiki.adapter.WikiAdapter
import com.eden.orchid.wiki.model.WikiSection
import com.eden.orchid.wiki.pages.WikiPage
import com.eden.orchid.wiki.pages.WikiSummaryPage
import com.eden.orchid.wiki.utils.WikiUtils
import org.apache.commons.io.FilenameUtils
import java.io.File
import javax.inject.Inject
import javax.validation.constraints.NotBlank
@Validate
@Suppress(SuppressedWarnings.UNUSED_PARAMETER)
class GithubWikiAdapter
@Inject
constructor(
val context: OrchidContext,
val git: GitFacade
) : WikiAdapter {
@Option
@Description("The repository to push to, as [username/repo].")
@NotBlank(message = "Must set the GitHub repository.")
lateinit var repo: String
@Option
@StringDefault("github.com")
@Description("The URL for a self-hosted Github Enterprise installation.")
@NotBlank
lateinit var githubUrl: String
@Option
@StringDefault("master")
lateinit var branch: String
override fun getType(): String = "github"
override fun loadWikiPages(section: WikiSection): Pair<WikiSummaryPage, List<WikiPage>>? {
val repo = git.clone(remoteUrl, displayedRemoteUrl, branch, false)
var sidebarFile: File? = null
var footerFile: File? = null // ignored for now
val wikiPageFiles = mutableListOf<File>()
repo.repoDir.toFile()
.walk()
.filter { it.isFile }
.filter { it.exists() }
.filter { !OrchidUtils.normalizePath(it.absolutePath).contains("/.git/") }
.forEach { currentFile ->
if (currentFile.nameWithoutExtension == "_Sidebar") {
sidebarFile = currentFile
} else if (currentFile.nameWithoutExtension == "_Footer") {
footerFile = currentFile
} else {
wikiPageFiles.add(currentFile)
}
}
val wikiContent = if (sidebarFile != null) {
createSummaryFileFromSidebar(repo, section, sidebarFile!!, wikiPageFiles)
} else {
createSummaryFileFromPages(repo, section, wikiPageFiles)
}
if(footerFile != null) {
addFooterComponent(wikiContent.second, footerFile!!)
}
return wikiContent
}
// Cloning Wiki
//----------------------------------------------------------------------------------------------------------------------
private val displayedRemoteUrl: String
get() = "https://$githubUrl/$repo.wiki.git"
private val remoteUrl: String
get() = "https://$githubUrl/$repo.wiki.git"
// Formatting Wiki files to Orchid's wiki format
//----------------------------------------------------------------------------------------------------------------------
private fun createSummaryFileFromSidebar(
repo: GitRepoFacade,
section: WikiSection,
sidebarFile: File,
wikiPages: MutableList<File>
): Pair<WikiSummaryPage, List<WikiPage>> {
val summary = FileResource(
OrchidReference(
context,
FileResource.pathFromFile(sidebarFile, repo.repoDir.toFile())
),
sidebarFile
)
return WikiUtils.createWikiFromSummaryFile(context, section, summary) { linkName, linkTarget, _ ->
val referencedFile = wikiPages.firstOrNull {
val filePath = FilenameUtils.removeExtension(it.relativeTo(repo.repoDir.toFile()).path)
filePath == linkTarget
}
if(referencedFile == null) {
Clog.w("Page referenced in Github Wiki $repo, $linkTarget does not exist")
StringResource(OrchidReference(context, "wiki/${section.key}/$linkTarget/index.md"), linkName)
}
else {
FileResource(
OrchidReference(
context,
FileResource.pathFromFile(referencedFile, repo.repoDir.toFile())
),
referencedFile
)
}
}
}
private fun createSummaryFileFromPages(
repo: GitRepoFacade,
section: WikiSection,
wikiPageFiles: MutableList<File>
): Pair<WikiSummaryPage, List<WikiPage>> {
val wikiPages = wikiPageFiles.map {
FileResource(
OrchidReference(
context,
FileResource.pathFromFile(it, repo.repoDir.toFile())
),
it
)
}
return WikiUtils.createWikiFromResources(context, section, wikiPages)
}
private fun addFooterComponent(wikiPages: List<WikiPage>, footerFile: File) {
// wikiPages.forEach {
// it.components.add(
// JSONObject().apply {
// put("type", "template")
//
// }
// )
// }
}
}
| integrations/OrchidGithub/src/main/kotlin/com/eden/orchid/github/wiki/GithubWikiAdapter.kt | 1869016610 |
fun main() {
if (true)
} | grammar/testData/grammar/ifExpression/emptyControlStructureBody/onlyIfWithoutSemicolon.kt | 336237918 |
// WITH_STDLIB
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
private fun unzip(zip: ZipFile) {
var errorUnpacking = false
try {
zip.let { zipFile ->
val entries: Enumeration<*> = zipFile.entries()
while (entries.hasMoreElements()) {
val nextElement = entries.nextElement()
nextElement as ZipEntry
}
}
errorUnpacking = false
}
finally {
if (<weak_warning descr="Value of 'errorUnpacking' is always false">errorUnpacking</weak_warning>) {
}
}
}
| plugins/kotlin/idea/tests/testData/inspections/dfa/TryFinally.kt | 1161476172 |
// 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.execution.target
import com.intellij.execution.CommandLineUtil
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.ExecutionException
import com.intellij.execution.target.value.TargetValue
import com.intellij.util.execution.ParametersListUtil
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.collectResults
import java.nio.charset.Charset
import java.util.concurrent.TimeoutException
/**
* Command line that can be executed on any [TargetEnvironment].
*
*
* Exe-path, working-directory and other properties are initialized in a lazy way,
* that allows to create a command line before creating a target where it should be run.
*
* @see TargetedCommandLineBuilder
*/
class TargetedCommandLine internal constructor(private val exePath: TargetValue<String>,
private val _workingDirectory: TargetValue<String>,
private val _inputFilePath: TargetValue<String>,
val charset: Charset,
private val parameters: List<TargetValue<String>>,
private val environment: Map<String, TargetValue<String>>,
val isRedirectErrorStream: Boolean,
val ptyOptions: PtyOptions?) {
/**
* [com.intellij.execution.configurations.GeneralCommandLine.getPreparedCommandLine]
*/
@Throws(ExecutionException::class)
fun getCommandPresentation(target: TargetEnvironment): String {
val exePath = exePath.targetValue.resolve("exe path")
?: throw ExecutionException(ExecutionBundle.message("targeted.command.line.exe.path.not.set"))
val parameters = parameters.map { it.targetValue.resolve("parameter") }
val targetPlatform = target.targetPlatform.platform
return CommandLineUtil.toCommandLine(ParametersListUtil.escape(exePath), parameters, targetPlatform).joinToString(separator = " ")
}
@Throws(ExecutionException::class)
fun collectCommandsSynchronously(): List<String> =
try {
collectCommands().blockingGet(0)!!
}
catch (e: java.util.concurrent.ExecutionException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.collector.failed"), e)
}
catch (e: TimeoutException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.collector.failed"), e)
}
fun collectCommands(): Promise<List<String>> {
val promises: MutableList<Promise<String>> = ArrayList(parameters.size + 1)
promises.add(exePath.targetValue.then { command: String? ->
checkNotNull(command) { "Resolved value for exe path is null" }
command
})
for (parameter in parameters) {
promises.add(parameter.targetValue)
}
return promises.collectResults()
}
@get:Throws(ExecutionException::class)
val workingDirectory: String?
get() = _workingDirectory.targetValue.resolve("working directory")
@get:Throws(ExecutionException::class)
val inputFilePath: String?
get() = _inputFilePath.targetValue.resolve("input file path")
@get:Throws(ExecutionException::class)
val environmentVariables: Map<String, String>
get() = environment.mapValues { (name, value) ->
value.targetValue.resolve("environment variable $name")
?: throw ExecutionException(ExecutionBundle.message("targeted.command.line.resolved.env.value.is.null", name))
}
override fun toString(): String =
listOf(exePath).plus(parameters).joinToString(
separator = " ",
prefix = super.toString() + ": ",
transform = { promise ->
runCatching { promise.targetValue.blockingGet(0) }.getOrElse { if (it is TimeoutException) "..." else "<ERROR>" } ?: ""
}
)
companion object {
@Throws(ExecutionException::class)
private fun Promise<String>.resolve(debugName: String): String? =
try {
blockingGet(0)
}
catch (e: java.util.concurrent.ExecutionException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.resolver.failed.for", debugName), e)
}
catch (e: TimeoutException) {
throw ExecutionException(ExecutionBundle.message("targeted.command.line.resolver.failed.for", debugName), e)
}
}
} | platform/execution/src/com/intellij/execution/target/TargetedCommandLine.kt | 2038690816 |
fun a() {
val array = Byte<caret>Array(10)
}
// REF: (<local>) (size: Int) | plugins/kotlin/navigation/tests/testData/navigationToLibrarySourcePolicy/resolveToStdlib/constructors/byteArrayPrimaryConstructorCall.kt | 1379576115 |
// 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.nj2k.conversions
import com.intellij.psi.PsiMember
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.*
import org.jetbrains.kotlin.nj2k.tree.Visibility.*
class InternalDeclarationConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKVisibilityOwner || element !is JKModalityOwner) return recurse(element)
if (element.visibility != INTERNAL) return recurse(element)
val containingClass = element.parentOfType<JKClass>()
val containingClassKind = containingClass?.classKind ?: element.psi<PsiMember>()?.containingClass?.classKind?.toJk()
val containingClassVisibility = containingClass?.visibility
?: element.psi<PsiMember>()
?.containingClass
?.visibility(context.converter.oldConverterServices.referenceSearcher, null)
?.visibility
val defaultVisibility = if (context.converter.settings.publicByDefault) PUBLIC else INTERNAL
element.visibility = when {
containingClassKind == INTERFACE || containingClassKind == ANNOTATION ->
PUBLIC
containingClassKind == ENUM && element is JKConstructor ->
PRIVATE
element is JKClass && element.isLocalClass() ->
PUBLIC
element is JKConstructor && containingClassVisibility != INTERNAL ->
defaultVisibility
element is JKField || element is JKMethod ->
PUBLIC
else -> defaultVisibility
}
return recurse(element)
}
} | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InternalDeclarationConversion.kt | 2454426975 |
package by.bkug.data
import by.bkug.data.model.Article
import by.bkug.data.model.HtmlMarkup
import by.bkug.data.model.localDate
import org.intellij.lang.annotations.Language
@Language("html")
private val body = HtmlMarkup("""
<p>Приглашаем вас на митап Belarus Kotlin User Group по Kotlin, который пройдет в 19.00, 24 марта в <a href="http://eventspace.by">Space</a>.</p>
<p>На митапе выступят Антон Руткевич и Руслан Ибрагимов. Данное событие откроет серию митапов про Kotlin и будет особенно полезен тем, кто только начинает смотреть на данный язык.</p>
<h2>Программа:</h2>
<ul>
<li>19:00 - 20:00 – <strong>Антон Руткевич</strong> сделает введение в язык и расскажет об основных особенностях языка.</li>
<li>20:00 - 21:00 – <strong>Руслан Ибрагимов</strong> расскажет, как использовать Котлин на бэкенеде на примере Spring приложения, а также рассмотрит стандартную библиотеку Котлин.</li>
</ul>
<p>Встреча организованна при поддержке сообщества <a href="http://jprof.by/">Java Professionals By</a>.</p>
<p>Для участия во встрече необходима предварительная <a href="https://docs.google.com/forms/d/1GdS3ALbh1lwOWpEeAA4VY6DExQjo5dIIOrfmvKzhqlM/viewform?c=0&w=1">регистрация</a> (это поможет нам подготовить необходимое количество печенек :) )</p>
<p><strong>Дата проведения</strong>: 24 марта</p>
<p><strong>Время</strong>: 19:00–21:00</p>
<p><strong>Место проведения</strong>: ул. Октябрьская, 16А – EventSpace. Парковка и вход через ул. Октябрьскую, 10б.</p>
<p><em>Еще больше докладов и общения на тему Kotlin-разработки!</em></p>
$eventSpaceMap
""".trimIndent())
val meetup1 = Article(
title = "Анонс: BKUG #1",
slug = "anons-bkug-1",
category = announcements,
date = localDate("2016-03-17"),
body = body
)
| data/src/main/kotlin/by/bkug/data/Meetup1.kt | 1987747471 |
/*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.fragments
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import android.view.View.OnClickListener
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.squareup.picasso.Picasso
import okhttp3.ResponseBody
import org.apache.commons.lang3.StringUtils
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.entities.DVBViewerPreferences
import org.dvbviewer.controller.data.entities.EpgEntry
import org.dvbviewer.controller.data.entities.IEPG
import org.dvbviewer.controller.data.entities.Timer
import org.dvbviewer.controller.data.epg.ChannelEpgViewModel
import org.dvbviewer.controller.data.epg.EPGRepository
import org.dvbviewer.controller.data.epg.EpgViewModelFactory
import org.dvbviewer.controller.data.remote.RemoteRepository
import org.dvbviewer.controller.data.timer.TimerRepository
import org.dvbviewer.controller.ui.base.BaseListFragment
import org.dvbviewer.controller.ui.phone.IEpgDetailsActivity
import org.dvbviewer.controller.ui.phone.TimerDetailsActivity
import org.dvbviewer.controller.utils.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* The Class ChannelEpg.
*
* @author RayBa
*/
class ChannelEpg : BaseListFragment(), OnItemClickListener, OnClickListener, PopupMenu.OnMenuItemClickListener {
private var mAdapter: ChannelEPGAdapter? = null
private var clickListener: IEpgDetailsActivity.OnIEPGClickListener? = null
private var channel: String? = null
private var channelId: Long = 0
private var epgId: Long = 0
private var logoUrl: String? = null
private var channelPos: Int = 0
private var favPos: Int = 0
private var selectedPosition: Int = 0
private var channelLogo: ImageView? = null
private var channelName: TextView? = null
private var dayIndicator: TextView? = null
private var mDateInfo: EpgDateInfo? = null
private var lastRefresh: Date? = null
private var header: View? = null
private lateinit var timerRepository: TimerRepository
private lateinit var remoteRepository: RemoteRepository
private lateinit var epgRepository: EPGRepository
private lateinit var epgViewModel: ChannelEpgViewModel
override val layoutRessource: Int
get() = R.layout.fragment_channel_epg
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is EpgDateInfo) {
mDateInfo = context
}
if (context is IEpgDetailsActivity.OnIEPGClickListener) {
clickListener = context
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
timerRepository = TimerRepository(getDmsInterface())
remoteRepository = RemoteRepository(getDmsInterface())
epgRepository = EPGRepository(getDmsInterface())
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
fillFromBundle(arguments!!)
mAdapter = ChannelEPGAdapter()
listAdapter = mAdapter
setListShown(false)
listView!!.onItemClickListener = this
if (header != null && channel != null) {
channelLogo!!.setImageBitmap(null)
val url = ServerConsts.REC_SERVICE_URL + "/" + logoUrl
Picasso.get()
.load(url)
.into(channelLogo)
channelName!!.text = channel
if (DateUtils.isToday(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.today)
} else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.tomorrow)
} else {
dayIndicator!!.text = DateUtils.formatDateTime(activity, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY)
}
}
setEmptyText(resources.getString(R.string.no_epg))
val epgObserver = Observer<List<EpgEntry>> { response -> onEpgChanged(response!!) }
val epgViewModelFactory = EpgViewModelFactory(epgRepository)
epgViewModel = ViewModelProvider(this, epgViewModelFactory)
.get(ChannelEpgViewModel::class.java)
val now = Date(mDateInfo!!.epgDate)
val tommorrow = DateUtils.addDay(now)
epgViewModel.getChannelEPG(epgId, now, tommorrow).observe(this, epgObserver)
}
private fun onEpgChanged(response: List<EpgEntry>) {
mAdapter = ChannelEPGAdapter()
listView?.adapter = mAdapter
mAdapter!!.items = response
mAdapter!!.notifyDataSetChanged()
setSelection(0)
val dateText: String
if (DateUtils.isToday(mDateInfo!!.epgDate)) {
dateText = getString(R.string.today)
} else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) {
dateText = getString(R.string.tomorrow)
} else {
dateText = DateUtils.formatDateTime(context, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY)
}
if (header != null) {
if (DateUtils.isToday(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.today)
} else if (DateUtils.isTomorrow(mDateInfo!!.epgDate)) {
dayIndicator!!.setText(R.string.tomorrow)
} else {
dayIndicator!!.text = DateUtils.formatDateTime(activity, mDateInfo!!.epgDate, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY)
}
dayIndicator!!.text = dateText
} else {
val activity = activity as AppCompatActivity?
activity!!.supportActionBar!!.subtitle = dateText
}
lastRefresh = Date(mDateInfo!!.epgDate)
setListShown(true)
}
private fun fillFromBundle(savedInstanceState: Bundle) {
channel = savedInstanceState.getString(KEY_CHANNEL_NAME)
channelId = savedInstanceState.getLong(KEY_CHANNEL_ID)
epgId = savedInstanceState.getLong(KEY_EPG_ID)
logoUrl = savedInstanceState.getString(KEY_CHANNEL_LOGO)
channelPos = savedInstanceState.getInt(KEY_CHANNEL_POS)
favPos = savedInstanceState.getInt(KEY_FAV_POS)
}
/* (non-Javadoc)
* @see org.dvbviewer.controller.ui.base.BaseListFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = super.onCreateView(inflater, container, savedInstanceState)
if (v != null) {
header = v.findViewById(R.id.epg_header)
channelLogo = v.findViewById(R.id.icon)
channelName = v.findViewById(R.id.title)
dayIndicator = v.findViewById(R.id.dayIndicator)
}
return v
}
/**
* The Class ViewHolder.
*
* @author RayBa
*/
private class ViewHolder {
internal var startTime: TextView? = null
internal var title: TextView? = null
internal var description: TextView? = null
internal var contextMenu: ImageView? = null
}
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val entry = mAdapter!!.getItem(position)
if (clickListener != null) {
clickListener!!.onIEPGClick(entry)
return
}
val i = Intent(context, IEpgDetailsActivity::class.java)
i.putExtra(IEPG::class.java.simpleName, entry)
startActivity(i)
}
/**
* The Class ChannelEPGAdapter.
*
* @author RayBa
*/
inner class ChannelEPGAdapter
/**
* Instantiates a new channel epg adapter.
*/
: ArrayListAdapter<EpgEntry>() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var convertView = convertView
val holder: ViewHolder
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_row_epg, parent, false)
holder = ViewHolder()
holder.startTime = convertView.findViewById(R.id.startTime)
holder.title = convertView.findViewById(R.id.title)
holder.description = convertView.findViewById(R.id.description)
holder.contextMenu = convertView.findViewById(R.id.contextMenu)
holder.contextMenu!!.setOnClickListener(this@ChannelEpg)
convertView.tag = holder
} else {
holder = convertView.tag as ViewHolder
}
val epgEntry = getItem(position)
holder.contextMenu!!.tag = position
val flags = DateUtils.FORMAT_SHOW_TIME
val date = DateUtils.formatDateTime(context, epgEntry.start.time, flags)
holder.startTime!!.text = date
holder.title!!.text = epgEntry.title
val subTitle = epgEntry.subTitle
val desc = epgEntry.description
holder.description!!.text = if (TextUtils.isEmpty(subTitle)) desc else subTitle
holder.description!!.visibility = if (TextUtils.isEmpty(holder.description!!.text)) View.GONE else View.VISIBLE
return convertView!!
}
}
/**
* Refreshs the data
*
*/
fun refresh() {
setListShown(false)
val start = Date(mDateInfo!!.epgDate)
val end = DateUtils.addDay(start)
epgViewModel.getChannelEPG(epgId, start, end, true)
}
/**
* Refresh date.
*
*/
private fun refreshDate() {
if (lastRefresh != null && lastRefresh!!.time != mDateInfo!!.epgDate) {
refresh()
}
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onSaveInstanceState(android.os.Bundle)
*/
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_CHANNEL_NAME, channel)
outState.putLong(KEY_CHANNEL_ID, channelId)
outState.putLong(KEY_EPG_ID, epgId)
outState.putString(KEY_CHANNEL_LOGO, logoUrl)
outState.putInt(KEY_CHANNEL_POS, channelPos)
outState.putInt(KEY_FAV_POS, favPos)
outState.putLong(KEY_EPG_DAY, mDateInfo!!.epgDate)
}
/* (non-Javadoc)
* @see com.actionbarsherlock.app.SherlockFragment#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
*/
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.channel_epg, menu)
menu.findItem(R.id.menuPrev).isEnabled = !DateUtils.isToday(mDateInfo!!.epgDate)
}
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
override fun onClick(v: View) {
when (v.id) {
R.id.contextMenu -> {
selectedPosition = v.tag as Int
val popup = PopupMenu(context!!, v)
popup.menuInflater.inflate(R.menu.context_menu_epg, popup.menu)
popup.setOnMenuItemClickListener(this)
popup.show()
}
else -> {
}
}
}
override fun onMenuItemClick(item: MenuItem): Boolean {
val c = mAdapter!!.getItem(selectedPosition)
val timer: Timer
when (item.itemId) {
R.id.menuRecord -> {
timer = cursorToTimer(c)
val call = timerRepository.saveTimer(timer)
call.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
sendMessage(R.string.timer_saved)
logEvent(EVENT_TIMER_CREATED)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
sendMessage(R.string.error_common)
}
})
return true
}
R.id.menuTimer -> {
timer = cursorToTimer(c)
if (UIUtils.isTablet(context!!)) {
val timerdetails = TimerDetails.newInstance()
val args = TimerDetails.buildBundle(timer)
timerdetails.arguments = args
timerdetails.show(activity!!.supportFragmentManager, TimerDetails::class.java.name)
} else {
val timerIntent = Intent(context, TimerDetailsActivity::class.java)
val extras = TimerDetails.buildBundle(timer)
timerIntent.putExtras(extras)
startActivity(timerIntent)
}
return true
}
R.id.menuDetails -> {
val details = Intent(context, IEpgDetailsActivity::class.java)
details.putExtra(IEPG::class.java.simpleName, c)
startActivity(details)
return true
}
R.id.menuSwitch -> {
val prefs = DVBViewerPreferences(context!!)
val target = prefs.getString(DVBViewerPreferences.KEY_SELECTED_CLIENT)
remoteRepository.switchChannel(target, channelId.toString()).enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
sendMessage(R.string.channel_switched)
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
sendMessage(R.string.error_common)
}
})
return true
}
else -> {
}
}
return false
}
/**
* The Interface EpgDateInfo.
*
* @author RayBa
*/
interface EpgDateInfo {
var epgDate: Long
}
/**
* Cursor to timer.
*
* @param c the c
* @return the timer©
*/
private fun cursorToTimer(c: EpgEntry): Timer {
val epgTitle = if (StringUtils.isNotBlank(c.title)) c.title else channel
val prefs = DVBViewerPreferences(context!!)
val epgBefore = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_TIME_BEFORE, DVBViewerPreferences.DEFAULT_TIMER_TIME_BEFORE)
val epgAfter = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_TIME_AFTER, DVBViewerPreferences.DEFAULT_TIMER_TIME_AFTER)
val timer = Timer()
timer.title = epgTitle
timer.channelId = channelId
timer.channelName = channel
timer.start = c.start
timer.end = c.end
timer.pre = epgBefore
timer.post = epgAfter
timer.eventId = c.eventId
timer.pdc = c.pdc
timer.timerAction = prefs.prefs.getInt(DVBViewerPreferences.KEY_TIMER_DEF_AFTER_RECORD, 0)
return timer
}
companion object {
val KEY_CHANNEL_NAME = ChannelEpg::class.java.name + "KEY_CHANNEL_NAME"
val KEY_CHANNEL_ID = ChannelEpg::class.java.name + "KEY_CHANNEL_ID"
val KEY_CHANNEL_LOGO = ChannelEpg::class.java.name + "KEY_CHANNEL_LOGO"
val KEY_CHANNEL_POS = ChannelEpg::class.java.name + "KEY_CHANNEL_POS"
val KEY_FAV_POS = ChannelEpg::class.java.name + "KEY_FAV_POS"
val KEY_EPG_ID = ChannelEpg::class.java.name + "KEY_EPG_ID"
val KEY_EPG_DAY = ChannelEpg::class.java.name + "EPG_DAY"
}
}
| dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/ChannelEpg.kt | 3495040540 |
package lt.markmerkk
/**
* @author mariusmerkevicius
* @since 2016-08-14
*/
object GAStatics {
val CATEGORY_BUTTON = "BUTTON"
val CATEGORY_GENERIC = "GENERIC"
val ACTION_ENTER = "ENTER_TIME"
val ACTION_SYNC_MAIN = "SYNC_MAIN"
val ACTION_SYNC_SETTINGS = "SYNC_SETTINGS"
val ACTION_SEARCH_REFRESH = "SEARCH_REFRESH"
val ACTION_START = "START"
val VIEW_DAY = "VIEW_DAY"
val VIEW_DAY_SIMPLE = "VIEW_SIMPLE_DAY"
val VIEW_WEEK = "VIEW_SIMPLE_WEEK"
val VIEW_CALENDAR_DAY = "VIEW_CALENDAR_DAY"
val VIEW_CALENDAR_WEEK = "VIEW_CALENDAR_WEEK"
val VIEW_GRAPH = "VIEW_GRAPH"
val VIEW_SETTINGS = "VIEW_SETTINGS"
} | app/src/main/java/lt/markmerkk/GAStatics.kt | 1552099301 |
/*
* The MIT License
*
* Copyright (c) 2015 Misakura.
*
* 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 jp.gr.java_conf.kgd.library.buckets.libgdx.util.assets
import com.badlogic.gdx.assets.AssetManager
import jp.gr.java_conf.kgd.library.buckets.libgdx.util.files.FileHandleResolverProvider
object AssetManagerProviderSingleton : AssetManagerProvider
by SimpleAssetManagerProvider(AssetManager(FileHandleResolverProvider.getFileHandleResolver())) | libgdx/util/util/src/main/kotlin/jp/gr/java_conf/kgd/library/buckets/libgdx/util/assets/AssetManagerProviderSingleton.kt | 3371136768 |
package github.jk1.smtpidea.server.pop3
import java.net.ServerSocket
import javax.mail.internet.MimeMessage
import javax.mail.Session
import java.util.Properties
import javax.mail.internet.InternetAddress
import javax.mail.Message.RecipientType
import org.junit.Assert.*
import javax.mail.Message
public trait TestUtils{
public fun findFreePort(): Int {
val socket = ServerSocket(0)
val port = socket.getLocalPort()
socket.close()
return port
}
public fun assertMailEquals(expected: Message, actual: Message) {
assertEquals(expected.getSubject(), actual.getSubject())
assertArrayEquals(expected.getFrom(), actual.getFrom())
assertEquals(expected.getContent().toString().trim(), actual.getContent().toString().trim())
assertArrayEquals(expected.getAllRecipients(), actual.getAllRecipients())
}
public fun createMimeMessage(content: String): MimeMessage
= createMimeMessage("[email protected]", "[email protected]", content)
public fun createMimeMessage(to: String, from: String, content: String): MimeMessage =
createMimeMessage(to, from, "subject", content)
public fun createMimeMessage(to: String, from: String, subject: String, content: String): MimeMessage {
val message = MimeMessage(Session.getInstance(Properties()))
message.setFrom(InternetAddress(from))
message.setRecipient(RecipientType.TO, InternetAddress(to))
message.setSubject(subject)
message.setText(content)
message.saveChanges()
return message
}
}
| src/test/kotlin/github/jk1/smtpidea/TestUtils.kt | 4159107625 |
package vn.eazy.base.mvp.example.mvp.model
import io.reactivex.Flowable
import vn.eazy.base.mvp.architect.BaseModel
import vn.eazy.base.mvp.di.scope.ActivityScope
import vn.eazy.base.mvp.example.mvp.contract.UserContract
import vn.eazy.base.mvp.example.mvp.model.api.service.UserService
import vn.eazy.base.mvp.example.mvp.model.entity.User
import vn.eazy.base.mvp.intergration.IRepositoryManager
import javax.inject.Inject
/**
* Created by harryle on 6/11/17.
*/
@ActivityScope
class UserModel : BaseModel, UserContract.Model {
@Inject
constructor(repositoryManager: IRepositoryManager) : super(repositoryManager)
companion object {
val USER_PER_PAGE: Int = 10
}
override fun getUsers(): Flowable<List<User>> {
val users: Flowable<List<User>> =
mRepositoryManager.obtainRetrofitServices(UserService::class.java).getUsers()
return users
}
} | code/app/src/main/java/vn/eazy/base/mvp/example/mvp/model/UserModel.kt | 2748343620 |
package xyz.javecs.tools.text2expr.rules
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import xyz.javecs.tools.text2expr.parser.Text2ExprBaseVisitor
import xyz.javecs.tools.text2expr.parser.Text2ExprLexer
import xyz.javecs.tools.text2expr.parser.Text2ExprParser
internal data class Field(var key: String = "",
var value: MutableList<String> = ArrayList(),
var isOptional: Boolean = false,
var optionalValue: Double = Double.NaN)
internal class Word(var fields: MutableList<Field> = ArrayList(), val id: String = "") {
fun isOptional() = fields.find { it.isOptional } != null
fun optionalValue(): Double? = fields.find { it.isOptional }?.optionalValue
}
internal fun parser(source: String): Text2ExprParser {
val charStream = CharStreams.fromString(source)
val lexer = Text2ExprLexer(charStream)
val tokens = CommonTokenStream(lexer)
return Text2ExprParser(tokens)
}
internal class RuleParser : Text2ExprBaseVisitor<Unit>() {
var expr = StringBuffer()
var rule = ArrayList<Word>()
override fun visitWordDefine(ctx: Text2ExprParser.WordDefineContext) {
rule.add(Word())
super.visitWordDefine(ctx)
}
override fun visitWordAssign(ctx: Text2ExprParser.WordAssignContext) {
rule.add(Word(id = ctx.ID().text))
super.visitWordAssign(ctx)
}
override fun visitField(ctx: Text2ExprParser.FieldContext) {
val field = Field()
if (ctx.op.text == "?") field.isOptional = true
field.key = ctx.PREFIX().text
field.value = ArrayList()
rule.last().fields.add(field)
visit(ctx.value())
}
override fun visitValue(ctx: Text2ExprParser.ValueContext) {
val field = rule.last().fields.last()
if (ctx.JAPANESE() != null) field.value.add(ctx.JAPANESE().text)
if (ctx.SYMBOL() != null) field.value.add(ctx.SYMBOL().text.replace("\"", ""))
if (ctx.optionalValue() != null) field.optionalValue = ctx.optionalValue().NUMBER().text.toDouble()
ctx.value().forEach { visit(it) }
}
override fun visitExpr(ctx: Text2ExprParser.ExprContext) {
expr.append(ctx.text)
}
} | src/main/kotlin/xyz/javecs/tools/text2expr/rules/RuleParser.kt | 3743355627 |
package org.thoughtcrime.securesms.mediaoverview
import android.graphics.Rect
import android.view.View
import androidx.annotation.Px
import androidx.recyclerview.widget.RecyclerView
import org.thoughtcrime.securesms.util.ViewUtil
internal class MediaGridDividerDecoration(
private val spanCount: Int,
@Px private val space: Int,
private val adapter: MediaGalleryAllAdapter
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val holder = parent.getChildViewHolder(view)
val adapterPosition = holder.adapterPosition
val section = adapter.getAdapterPositionSection(adapterPosition)
val itemSectionOffset = adapter.getItemSectionOffset(section, adapterPosition)
if (itemSectionOffset == -1) {
return
}
val sectionItemViewType = adapter.getSectionItemViewType(section, itemSectionOffset)
if (sectionItemViewType != MediaGalleryAllAdapter.GALLERY) {
return
}
val column = itemSectionOffset % spanCount
val isRtl = ViewUtil.isRtl(view)
val distanceFromEnd = spanCount - 1 - column
val spaceStart = (column / spanCount.toFloat()) * space
val spaceEnd = (distanceFromEnd / spanCount.toFloat()) * space
outRect.setStart(spaceStart.toInt(), isRtl)
outRect.setEnd(spaceEnd.toInt(), isRtl)
outRect.bottom = space
}
private fun Rect.setEnd(end: Int, isRtl: Boolean) {
if (isRtl) {
left = end
} else {
right = end
}
}
private fun Rect.setStart(start: Int, isRtl: Boolean) {
if (isRtl) {
right = start
} else {
left = start
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/mediaoverview/MediaGridDividerDecoration.kt | 1697078737 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.tracker.importer.internal
import java.net.HttpURLConnection
import org.hisp.dhis.android.core.arch.api.executors.internal.APICallErrorCatcher
import org.hisp.dhis.android.core.maintenance.D2ErrorCode
import retrofit2.Response
internal class JobQueryErrorCatcher : APICallErrorCatcher {
override fun mustBeStored(): Boolean = false
override fun catchError(response: Response<*>, errorBody: String): D2ErrorCode? {
return if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) {
D2ErrorCode.JOB_REPORT_NOT_AVAILABLE
} else {
null
}
}
}
| core/src/main/java/org/hisp/dhis/android/core/tracker/importer/internal/JobQueryErrorCatcher.kt | 1688588643 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.enrollment
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.reactivex.Single
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore
import org.hisp.dhis.android.core.arch.helpers.AccessHelper
import org.hisp.dhis.android.core.arch.helpers.DateUtils
import org.hisp.dhis.android.core.common.Access
import org.hisp.dhis.android.core.common.DataAccess
import org.hisp.dhis.android.core.enrollment.internal.EnrollmentServiceImpl
import org.hisp.dhis.android.core.event.Event
import org.hisp.dhis.android.core.event.EventCollectionRepository
import org.hisp.dhis.android.core.organisationunit.OrganisationUnit
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitCollectionRepository
import org.hisp.dhis.android.core.program.AccessLevel
import org.hisp.dhis.android.core.program.Program
import org.hisp.dhis.android.core.program.ProgramCollectionRepository
import org.hisp.dhis.android.core.program.ProgramStage
import org.hisp.dhis.android.core.program.ProgramStageCollectionRepository
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceCollectionRepository
import org.hisp.dhis.android.core.trackedentity.ownership.ProgramTempOwner
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
class EnrollmentServiceShould {
private val enrollmentUid: String = "enrollmentUid"
private val trackedEntityInstanceUid: String = "trackedEntityInstanceUid"
private val programUid: String = "programUid"
private val organisationUnitId: String = "organisationUnitId"
private val enrollment: Enrollment = mock()
private val trackedEntityInstance: TrackedEntityInstance = mock()
private val program: Program = mock()
private val programTempOwner: ProgramTempOwner = mock()
private val enrollmentRepository: EnrollmentCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val trackedEntityInstanceRepository: TrackedEntityInstanceCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programRepository: ProgramCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val organisationUnitRepository: OrganisationUnitCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val eventCollectionRepository: EventCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programStageCollectionRepository: ProgramStageCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programTempOwnerStore: ObjectWithoutUidStore<ProgramTempOwner> = mock()
private lateinit var enrollmentService: EnrollmentService
@Before
fun setUp() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn enrollment
whenever(
trackedEntityInstanceRepository
.uid(trackedEntityInstanceUid).blockingGet()
) doReturn trackedEntityInstance
whenever(programRepository.uid(programUid).blockingGet()) doReturn program
whenever(enrollment.uid()) doReturn enrollmentUid
whenever(trackedEntityInstance.organisationUnit()) doReturn organisationUnitId
enrollmentService = EnrollmentServiceImpl(
enrollmentRepository,
trackedEntityInstanceRepository,
programRepository,
organisationUnitRepository,
eventCollectionRepository,
programStageCollectionRepository,
programTempOwnerStore
)
}
@Test
fun `IsOpen should return true if enrollment is not found`() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn null
assertTrue(enrollmentService.blockingIsOpen(enrollmentUid))
}
@Test
fun `IsOpen should return false if enrollment is not active`() {
whenever(enrollment.status()) doReturn EnrollmentStatus.COMPLETED
assertFalse(enrollmentService.blockingIsOpen(enrollmentUid))
whenever(enrollment.status()) doReturn null
assertFalse(enrollmentService.blockingIsOpen(enrollmentUid))
}
@Test
fun `IsOpen should return true if enrollment is active`() {
whenever(enrollment.status()) doReturn EnrollmentStatus.ACTIVE
assertTrue(enrollmentService.blockingIsOpen(enrollmentUid))
}
@Test
fun `GetEnrollmentAccess should return no access if program not found`() {
whenever(programRepository.uid("other uid").blockingGet()) doReturn null
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, "other uid")
assert(access == EnrollmentAccess.NO_ACCESS)
}
@Test
fun `GetEnrollmentAccess should return data access if program is open`() {
whenever(program.accessLevel()) doReturn AccessLevel.OPEN
whenever(program.access()) doReturn AccessHelper.createForDataWrite(false)
val accessRead = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(accessRead == EnrollmentAccess.READ_ACCESS)
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
val accessWrite = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(accessWrite == EnrollmentAccess.WRITE_ACCESS)
}
@Test
fun `GetEnrollmentAccess should return data access if protected program in capture scope`() {
whenever(program.accessLevel()) doReturn AccessLevel.PROTECTED
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
whenever(
organisationUnitRepository
.byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
.uid(organisationUnitId)
.blockingExists()
) doReturn true
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(access == EnrollmentAccess.WRITE_ACCESS)
}
@Test
fun `GetEnrollmentAccess should return access denied if protected program not in capture scope`() {
whenever(program.accessLevel()) doReturn AccessLevel.PROTECTED
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
whenever(
organisationUnitRepository
.byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
.uid(organisationUnitId)
.blockingExists()
) doReturn false
whenever(programTempOwnerStore.selectWhere(any())) doReturn listOf(programTempOwner)
whenever(programTempOwner.validUntil()) doReturn DateUtils.DATE_FORMAT.parse("1999-01-01T00:00:00.000")
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(access == EnrollmentAccess.PROTECTED_PROGRAM_DENIED)
}
@Test
fun `GetEnrollmentAccess should return data access if protected program has broken glass`() {
whenever(program.accessLevel()) doReturn AccessLevel.PROTECTED
whenever(program.access()) doReturn AccessHelper.createForDataWrite(true)
whenever(
organisationUnitRepository
.byOrganisationUnitScope(OrganisationUnit.Scope.SCOPE_DATA_CAPTURE)
.uid(organisationUnitId)
.blockingExists()
) doReturn false
whenever(programTempOwnerStore.selectWhere(any())) doReturn listOf(programTempOwner)
whenever(programTempOwner.validUntil()) doReturn DateUtils.DATE_FORMAT.parse("2999-01-01T00:00:00.000")
val access = enrollmentService.blockingGetEnrollmentAccess(trackedEntityInstanceUid, programUid)
assert(access == EnrollmentAccess.WRITE_ACCESS)
}
@Test
fun `Enrollment has any events that allows events creation`() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn enrollment
whenever(enrollment.program()) doReturn programUid
whenever(
programStageCollectionRepository.byProgramUid().eq(programUid)
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.byAccessDataWrite().isTrue
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.get()
) doReturn Single.just(getProgramStages())
whenever(
eventCollectionRepository.byEnrollmentUid().eq(enrollmentUid)
) doReturn eventCollectionRepository
whenever(
eventCollectionRepository.byDeleted().isFalse
) doReturn eventCollectionRepository
whenever(eventCollectionRepository.get()) doReturn Single.just(getEventList())
assertTrue(enrollmentService.blockingGetAllowEventCreation(enrollmentUid, listOf("1")))
}
@Test
fun `Enrollment has not any events that allows events creation`() {
whenever(enrollmentRepository.uid(enrollmentUid).blockingGet()) doReturn enrollment
whenever(enrollment.program()) doReturn programUid
whenever(
programStageCollectionRepository.byProgramUid().eq(programUid)
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.byAccessDataWrite().isTrue
) doReturn programStageCollectionRepository
whenever(
programStageCollectionRepository.get()
) doReturn Single.just(getProgramStages())
whenever(
eventCollectionRepository.byEnrollmentUid().eq(enrollmentUid)
) doReturn eventCollectionRepository
whenever(
eventCollectionRepository.byDeleted().isFalse
) doReturn eventCollectionRepository
whenever(eventCollectionRepository.get()) doReturn Single.just(getEventList())
assertFalse(enrollmentService.blockingGetAllowEventCreation(enrollmentUid, listOf("1", "2")))
}
private fun getEventList() = listOf(
Event.builder()
.uid("eventUid1")
.programStage("1")
.build(),
Event.builder()
.uid("eventUid2")
.programStage("2")
.build()
)
private fun getProgramStages() = listOf(
ProgramStage.builder()
.access(Access.create(true, true, DataAccess.create(true, true)))
.uid("1")
.repeatable(true)
.build(),
ProgramStage.builder()
.access(Access.create(true, true, DataAccess.create(true, true)))
.uid("2")
.repeatable(true)
.build()
)
}
| core/src/test/java/org/hisp/dhis/android/core/enrollment/EnrollmentServiceShould.kt | 774623824 |
// 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.refactoring.move.moveDeclarations
import com.intellij.ide.IdeDeprecatedMessagesBundle
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler
import com.intellij.refactoring.rename.RenameUtil
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.usageView.UsageViewUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.HashingStrategy
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.base.util.projectScope
import org.jetbrains.kotlin.idea.base.util.restrictByFileType
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.deleteSingle
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.keysToMap
import kotlin.math.max
import kotlin.math.min
interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration {
object Default : Mover {
override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration {
return when (targetContainer) {
is KtFile -> {
val declarationContainer: KtElement =
if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer
declarationContainer.add(originalElement) as KtNamedDeclaration
}
is KtClassOrObject -> targetContainer.addDeclaration(originalElement)
else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}")
}.apply {
val container = originalElement.containingClassOrObject
if (container is KtObjectDeclaration &&
container.isCompanion() &&
container.declarations.singleOrNull() == originalElement &&
KotlinFindUsagesHandlerFactory(container.project).createFindUsagesHandler(container, false)
.findReferencesToHighlight(container, LocalSearchScope(container.containingFile)).isEmpty()
) {
container.deleteSingle()
} else {
originalElement.deleteSingle()
}
}
}
}
}
sealed class MoveSource {
abstract val elementsToMove: Collection<KtNamedDeclaration>
class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource()
class File(val file: KtFile) : MoveSource() {
override val elementsToMove: Collection<KtNamedDeclaration>
get() = file.declarations.filterIsInstance<KtNamedDeclaration>()
}
}
fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration))
fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations)
fun MoveSource(file: KtFile) = MoveSource.File(file)
class MoveDeclarationsDescriptor @JvmOverloads constructor(
val project: Project,
val moveSource: MoveSource,
val moveTarget: KotlinMoveTarget,
val delegate: MoveDeclarationsDelegate,
val searchInCommentsAndStrings: Boolean = true,
val searchInNonCode: Boolean = true,
val deleteSourceFiles: Boolean = false,
val moveCallback: MoveCallback? = null,
val openInEditor: Boolean = false,
val allElementsToMove: List<PsiElement>? = null,
val analyzeConflicts: Boolean = true,
val searchReferences: Boolean = true
)
class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element)
private object ElementHashingStrategy : HashingStrategy<PsiElement> {
override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean {
if (e1 === e2) return true
// Name should be enough to distinguish different light elements based on the same original declaration
if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) {
return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name
}
return false
}
override fun hashCode(e: PsiElement?): Int {
return when (e) {
null -> 0
is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0)
else -> e.hashCode()
}
}
}
class MoveKotlinDeclarationsProcessor(
val descriptor: MoveDeclarationsDescriptor,
val mover: Mover = Mover.Default,
private val throwOnConflicts: Boolean = false
) : BaseRefactoringProcessor(descriptor.project) {
companion object {
const val REFACTORING_ID = "move.kotlin.declarations"
}
val project get() = descriptor.project
private var nonCodeUsages: Array<NonCodeUsageInfo>? = null
private val moveEntireFile = descriptor.moveSource is MoveSource.File
private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e ->
e.parent != descriptor.moveTarget.getTargetPsiIfExists(e)
}
private val kotlinToLightElementsBySourceFile = elementsToMove
.groupBy { it.containingKtFile }
.mapValues { it.value.keysToMap { declaration -> declaration.toLightElements().ifEmpty { listOf(declaration) } } }
private val conflicts = MultiMap<PsiElement, String>()
override fun getRefactoringId() = REFACTORING_ID
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let {
if (it.isRoot) IdeDeprecatedMessagesBundle.message("default.package.presentable.name") else it.asString()
} ?: IdeDeprecatedMessagesBundle.message("default.package.presentable.name")
return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName)
}
fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) }
public override fun findUsages(): Array<UsageInfo> {
if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY
val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: ""
fun getSearchScope(element: PsiElement): GlobalSearchScope? {
val projectScope = project.projectScope()
val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope
if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope
val moveTarget = descriptor.moveTarget
val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget)
val targetModule = moveTarget.getTargetModule(project) ?: return projectScope
if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope
// Check if facade class may change
if (newContainer is ContainerInfo.Package) {
val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE)
val currentFile = ktDeclaration.containingKtFile
val newFile = when (moveTarget) {
is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null
is KotlinMoveTargetForDeferredFile -> return javaScope
else -> return null
}
val currentFacade = currentFile.findFacadeClass()
val newFacade = newFile.findFacadeClass()
return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null
}
return null
}
fun UsageInfo.intersectsWith(usage: UsageInfo): Boolean {
if (element?.containingFile != usage.element?.containingFile) return false
val firstSegment = segment ?: return false
val secondSegment = usage.segment ?: return false
return max(firstSegment.startOffset, secondSegment.startOffset) <= min(firstSegment.endOffset, secondSegment.endOffset)
}
fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) {
kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement ->
val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList()
val elementName = lightElement.name ?: return@flatMapTo emptyList()
val newFqName = StringUtil.getQualifiedName(newContainerName, elementName)
val foundReferences = HashSet<PsiReference>()
val results = ReferencesSearch
.search(lightElement, searchScope)
.mapNotNullTo(ArrayList()) { ref ->
if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element) }) {
createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false)
} else null
}
val name = lightElement.kotlinFqName?.quoteIfNeeded()?.asString()
if (name != null) {
fun searchForKotlinNameUsages(results: ArrayList<UsageInfo>) {
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
name,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqName).quoteIfNeeded().asString(),
results
)
}
val facadeContainer = lightElement.parent as? KtLightClassForFacade
if (facadeContainer != null) {
val oldFqNameWithFacade = StringUtil.getQualifiedName(facadeContainer.qualifiedName, elementName)
val newFqNameWithFacade = StringUtil.getQualifiedName(
StringUtil.getQualifiedName(newContainerName, facadeContainer.name),
elementName
)
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
searchScope,
oldFqNameWithFacade,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqNameWithFacade).quoteIfNeeded().asString(),
results
)
ArrayList<UsageInfo>().also { searchForKotlinNameUsages(it) }.forEach { kotlinNonCodeUsage ->
if (results.none { it.intersectsWith(kotlinNonCodeUsage) }) {
results.add(kotlinNonCodeUsage)
}
}
} else {
searchForKotlinNameUsages(results)
}
}
MoveClassHandler.EP_NAME.extensions.filter { it !is MoveKotlinClassHandler }.forEach { handler ->
handler.preprocessUsages(results)
}
results
}
}
val usages = ArrayList<UsageInfo>()
val conflictChecker = MoveConflictChecker(
project,
elementsToMove,
descriptor.moveTarget,
elementsToMove.first(),
allElementsToMove = descriptor.allElementsToMove
)
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
val internalUsages = LinkedHashSet<UsageInfo>()
val externalUsages = LinkedHashSet<UsageInfo>()
if (moveEntireFile) {
val changeInfo = ContainerChangeInfo(
ContainerInfo.Package(sourceFile.packageFqName),
descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage
)
internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
} else {
kotlinToLightElements.keys.forEach {
val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget)
internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo)
}
}
internalUsages += descriptor.delegate.findInternalUsages(descriptor)
collectUsages(kotlinToLightElements, externalUsages)
if (descriptor.analyzeConflicts) {
conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts)
descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts)
}
usages += internalUsages
usages += externalUsages
}
return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray())
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
return showConflicts(conflicts, refUsages.get())
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList())
internal fun doPerformRefactoring(usages: List<UsageInfo>) {
fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration {
val targetContainer = moveTarget.getOrCreateTargetPsi(declaration)
descriptor.delegate.preprocessDeclaration(descriptor, declaration)
if (moveEntireFile) return declaration
return mover(declaration, targetContainer).apply {
addToBeShortenedDescendantsToWaitingSet()
}
}
val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal }
val newInternalUsages = ArrayList<UsageInfo>()
markInternalUsages(oldInternalUsages)
val usagesToProcess = ArrayList(externalUsages)
try {
descriptor.delegate.preprocessUsages(descriptor, usages)
val oldToNewElementsMapping = CollectionFactory.createCustomHashingStrategyMap<PsiElement, PsiElement>(ElementHashingStrategy)
val newDeclarations = ArrayList<KtNamedDeclaration>()
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
for ((oldDeclaration, oldLightElements) in kotlinToLightElements) {
val elementListener = transaction?.getElementListener(oldDeclaration)
val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget)
newDeclarations += newDeclaration
oldToNewElementsMapping[oldDeclaration] = newDeclaration
oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile
elementListener?.elementMoved(newDeclaration)
for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) {
oldToNewElementsMapping[oldElement] = newElement
}
if (descriptor.openInEditor) {
EditorHelper.openInEditor(newDeclaration)
}
}
if (descriptor.deleteSourceFiles && sourceFile.declarations.isEmpty()) {
sourceFile.delete()
}
}
val internalUsageScopes: List<KtElement> = if (moveEntireFile) {
newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList()
} else {
newDeclarations
}
internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) }
usagesToProcess += newInternalUsages
nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray()
performDelayedRefactoringRequests(project)
} catch (e: IncorrectOperationException) {
nonCodeUsages = null
RefactoringUIUtil.processIncorrectOperation(myProject, e)
} finally {
cleanUpInternalUsages(newInternalUsages + oldInternalUsages)
}
}
override fun performPsiSpoilingRefactoring() {
nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) }
descriptor.moveCallback?.refactoringCompleted()
}
fun execute(usages: List<UsageInfo>) {
execute(usages.toTypedArray())
}
override fun doRun() {
try {
super.doRun()
} finally {
broadcastRefactoringExit(myProject, refactoringId)
}
}
override fun getCommandName(): String = KotlinBundle.message("command.move.declarations")
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt | 1034900555 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.common
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.getPossiblePsiSourceTypes
import org.jetbrains.uast.toUElementOfExpectedTypes
import org.junit.Assert
interface PossibleSourceTypesTestBase {
private fun PsiFile.getPsiSourcesByPlainVisitor(psiPredicate: (PsiElement) -> Boolean = { true },
vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val sources = mutableSetOf<PsiElement>()
accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (psiPredicate(element)) {
element.toUElementOfExpectedTypes(*uastTypes)?.let {
sources += element
}
}
super.visitElement(element)
}
})
return sources
}
private fun PsiFile.getPsiSourcesByLanguageAwareVisitor(vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val possibleSourceTypes = getPossiblePsiSourceTypes(language, *uastTypes)
return getPsiSourcesByPlainVisitor(psiPredicate = { it.javaClass in possibleSourceTypes }, uastTypes = *uastTypes)
}
private fun PsiFile.getPsiSourcesByLanguageUnawareVisitor(vararg uastTypes: Class<out UElement>): Set<PsiElement> {
val possibleSourceTypes = UastFacade.getPossiblePsiSourceTypes(*uastTypes)
return getPsiSourcesByPlainVisitor(psiPredicate = { it.javaClass in possibleSourceTypes }, uastTypes = *uastTypes)
}
fun checkConsistencyWithRequiredTypes(psiFile: PsiFile, vararg uastTypes: Class<out UElement>) {
val byPlain = psiFile.getPsiSourcesByPlainVisitor(uastTypes = uastTypes)
val byLanguageAware = psiFile.getPsiSourcesByLanguageAwareVisitor(uastTypes = uastTypes)
val byLanguageUnaware = psiFile.getPsiSourcesByLanguageUnawareVisitor(uastTypes = uastTypes)
Assert.assertEquals(
"Filtering PSI elements with getPossiblePsiSourceTypes(${listOf(*uastTypes)}) should not lost or add any conversions",
byPlain,
byLanguageUnaware)
Assert.assertEquals(
"UastFacade implementation(${listOf(*uastTypes)}) should be in sync with language UastLanguagePlugin's one",
byLanguageAware,
byLanguageUnaware)
}
} | uast/uast-tests/src/org/jetbrains/uast/test/common/PossibleSourceTypesTestBase.kt | 1173207755 |
// WITH_STDLIB
fun test() {
val array = intArrayOf(1, 2, 3)
val result = java.util.Arrays.<caret>copyOf(array, 3)
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/collections/qualified.kt | 892418183 |
/*
* Copyright 2000-2017 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.debugger
import com.intellij.util.Url
import org.jetbrains.concurrency.Promise
import java.util.*
interface BreakpointManager {
enum class MUTE_MODE {
ALL,
ONE,
NONE
}
val breakpoints: Iterable<Breakpoint>
val regExpBreakpointSupported: Boolean
get() = false
fun setBreakpoint(target: BreakpointTarget,
line: Int,
column: Int = Breakpoint.EMPTY_VALUE,
url: Url? = null,
condition: String? = null,
ignoreCount: Int = Breakpoint.EMPTY_VALUE): SetBreakpointResult
fun remove(breakpoint: Breakpoint): Promise<*>
/**
* Supports targets that refer to function text in form of function-returning
* JavaScript expression.
* E.g. you can set a breakpoint on the 5th line of user method addressed as
* 'PropertiesDialog.prototype.loadData'.
* Expression is calculated immediately and never recalculated again.
*/
val functionSupport: ((expression: String) -> BreakpointTarget)?
get() = null
// Could be called multiple times for breakpoint
fun addBreakpointListener(listener: BreakpointListener)
fun removeAll(): Promise<*>
fun getMuteMode(): MUTE_MODE = BreakpointManager.MUTE_MODE.ONE
/**
* Flushes the breakpoint parameter changes (set* methods) into the browser
* and returns a promise of an updated breakpoint. This method must
* be called for the set* method invocations to take effect.
*/
fun flush(breakpoint: Breakpoint): Promise<out Breakpoint>
/**
* Asynchronously enables or disables all breakpoints on remote. 'Enabled' means that
* breakpoints behave as normal, 'disabled' means that VM doesn't stop on breakpoints.
* It doesn't update individual properties of [Breakpoint]s. Method call
* with a null value and not null callback simply returns current value.
*/
fun enableBreakpoints(enabled: Boolean): Promise<*>
fun setBreakOnFirstStatement()
fun isBreakOnFirstStatement(context: SuspendContext<*>): Boolean
interface SetBreakpointResult
data class BreakpointExist(val existingBreakpoint: Breakpoint) : SetBreakpointResult
data class BreakpointCreated(val breakpoint: Breakpoint, val isRegistered: Promise<out Breakpoint>) : SetBreakpointResult
}
interface BreakpointListener : EventListener {
fun resolved(breakpoint: Breakpoint)
fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?)
fun nonProvisionalBreakpointRemoved(breakpoint: Breakpoint) {
}
} | platform/script-debugger/backend/src/debugger/BreakpointManager.kt | 3561797831 |
package tripleklay.ui.util
import klay.scene.Pointer
import euklid.f.IPoint
import euklid.f.MathUtil
import euklid.f.Point
import react.Signal
import kotlin.math.sign
/**
* Translates pointer input on a layer into an x, y offset. With a sufficiently large drag delta,
* calculates a velocity, applies it to the position over time and diminishes its value by
* friction. For smaller drag deltas, dispatches the pointer end event on the [.clicked]
* signal.
*
* **NOTE:**Clients of this class must call [.update], so that friction and
* other calculations can be applied. This is normally done within the client's own update method
* and followed by some usage of the [.position] method. For example:
* <pre>`XYFlicker flicker = new XYFlicker();
* Layer layer = ...;
* { layer.addListener(flicker); }
* void update (int delta) {
* flicker.update(delta);
* layer.setTranslation(flicker.position().x(), flicker.position().y());
* }
`</pre> *
* TODO: figure out how to implement with two Flickers. could require some changes therein since
* you probably don't want them to have differing states, plus 2x clicked signals is wasteful
*/
class XYFlicker : Pointer.Listener {
/** Signal dispatched when a pointer usage did not end up being a flick. */
var clicked = Signal<klay.core.Pointer.Event>()
/**
* Gets the current position.
*/
fun position(): IPoint {
return _position
}
override fun onStart(iact: Pointer.Interaction) {
_vel.set(0f, 0f)
_maxDeltaSq = 0f
_origPos.set(_position)
getPosition(iact.event!!, _start)
_prev.set(_start)
_cur.set(_start)
_prevStamp = 0.0
_curStamp = iact.event!!.time
}
override fun onDrag(iact: Pointer.Interaction) {
_prev.set(_cur)
_prevStamp = _curStamp
getPosition(iact.event!!, _cur)
_curStamp = iact.event!!.time
var dx = _cur.x - _start.x
var dy = _cur.y - _start.y
setPosition(_origPos.x + dx, _origPos.y + dy)
_maxDeltaSq = maxOf(dx * dx + dy * dy, _maxDeltaSq)
// for the purposes of capturing the event stream, dx and dy are capped by their ranges
dx = _position.x - _origPos.x
dy = _position.y - _origPos.y
if (dx * dx + dy * dy >= maxClickDeltaSq()) iact.capture()
}
override fun onEnd(iact: Pointer.Interaction) {
// just dispatch a click if the pointer didn't move very far
if (_maxDeltaSq < maxClickDeltaSq()) {
clicked.emit(iact.event!!)
return
}
// if not, maybe impart some velocity
val dragTime = (_curStamp - _prevStamp).toFloat()
val delta = Point(_cur.x - _prev.x, _cur.y - _prev.y)
val dragVel = delta.mult(1 / dragTime)
var dragSpeed = dragVel.distance(0f, 0f)
if (dragSpeed > flickSpeedThresh() && delta.distance(0f, 0f) > minFlickDelta()) {
if (dragSpeed > maxFlickSpeed()) {
dragVel.multLocal(maxFlickSpeed() / dragSpeed)
dragSpeed = maxFlickSpeed()
}
_vel.set(dragVel)
_vel.multLocal(flickXfer())
val sx = _vel.x.sign
val sy = _vel.y.sign
_accel.x = -sx * friction()
_accel.y = -sy * friction()
}
}
override fun onCancel(iact: Pointer.Interaction?) {
_vel.set(0f, 0f)
_accel.set(0f, 0f)
}
fun update(delta: Float) {
if (_vel.x == 0f && _vel.y == 0f) return
_prev.set(_position)
// apply x and y velocity
val x = MathUtil.clamp(_position.x + _vel.x * delta, _min.x, _max.x)
val y = MathUtil.clamp(_position.y + _vel.y * delta, _min.y, _max.y)
// stop when we hit the edges
if (x == _position.x) _vel.x = 0f
if (y == _position.y) _vel.y = 0f
_position.set(x, y)
// apply x and y acceleration
_vel.x = applyAccelertion(_vel.x, _accel.x, delta)
_vel.y = applyAccelertion(_vel.y, _accel.y, delta)
}
/**
* Resets the flicker to the given maximum values.
*/
fun reset(maxX: Float, maxY: Float) {
_max.set(maxX, maxY)
// reclamp the position
setPosition(_position.x, _position.y)
}
/**
* Sets the flicker position, in the case of a programmatic change.
*/
fun positionChanged(x: Float, y: Float) {
setPosition(x, y)
}
/** Translates a pointer event into a position. */
private fun getPosition(event: klay.core.Pointer.Event, dest: Point) {
dest.set(-event.x, -event.y)
}
/** Sets the current position, clamping the values between min and max. */
private fun setPosition(x: Float, y: Float) {
_position.set(MathUtil.clamp(x, _min.x, _max.x), MathUtil.clamp(y, _min.y, _max.y))
}
/** Returns the minimum distance (in pixels) the pointer must have moved to register as a
* flick. */
private fun minFlickDelta(): Float {
return 10f
}
/** Returns the deceleration (in pixels per ms per ms) applied to non-zero velocity. */
private fun friction(): Float {
return 0.0015f
}
/** Returns the minimum (positive) speed (in pixels per millisecond) at time of touch release
* required to initiate a flick (i.e. transfer the flick velocity to the entity). */
private fun flickSpeedThresh(): Float {
return 0.5f
}
/** Returns the fraction of flick speed that is transfered to the entity (a value between 0
* and 1). */
private fun flickXfer(): Float {
return 0.95f
}
/** Returns the maximum flick speed that will be transfered to the entity; limits the actual
* flick speed at time of release. This value is not adjusted by [.flickXfer]. */
private fun maxFlickSpeed(): Float {
return 1.4f // pixels/ms
}
/** Returns the square of the maximum distance (in pixels) the pointer is allowed to travel
* while pressed and still register as a click. */
private fun maxClickDeltaSq(): Float {
return 225f
}
private var _maxDeltaSq: Float = 0.toFloat()
private val _position = Point()
private val _vel = Point()
private val _accel = Point()
private val _origPos = Point()
private val _start = Point()
private val _cur = Point()
private val _prev = Point()
private val _max = Point()
private val _min = Point()
private var _prevStamp: Double = 0.toDouble()
private var _curStamp: Double = 0.toDouble()
companion object {
private fun applyAccelertion(v: Float, a: Float, dt: Float): Float {
var v = v
val prev = v
v += a * dt
// if we decelerate past zero velocity, stop
return if (prev.sign == v.sign) v else 0f
}
}
}
| tripleklay/src/main/kotlin/tripleklay/ui/util/XYFlicker.kt | 4072138476 |
// 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.intentions.loopToCallChain.result
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.*
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.FilterTransformationBase
import org.jetbrains.kotlin.psi.*
class CountTransformation(
loop: KtForExpression,
private val inputVariable: KtCallableDeclaration,
initialization: VariableInitialization,
private val filter: KtExpression?
) : AssignToVariableResultTransformation(loop, initialization) {
override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): ResultTransformation? {
if (previousTransformation !is FilterTransformationBase) return null
if (previousTransformation.indexVariable != null) return null
val newFilter = if (filter == null)
previousTransformation.effectiveCondition.asExpression(reformat)
else
KtPsiFactory(filter).createExpressionByPattern(
"$0 && $1", previousTransformation.effectiveCondition.asExpression(reformat), filter,
reformat = reformat
)
return CountTransformation(loop, previousTransformation.inputVariable, initialization, newFilter)
}
override val presentation: String
get() = "count" + (if (filter != null) "{}" else "()")
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val reformat = chainedCallGenerator.reformat
val call = if (filter != null) {
val lambda = generateLambda(inputVariable, filter, reformat)
chainedCallGenerator.generate("count $0:'{}'", lambda)
} else {
chainedCallGenerator.generate("count()")
}
return if (initialization.initializer.isZeroConstant()) {
call
} else {
KtPsiFactory(call).createExpressionByPattern("$0 + $1", initialization.initializer, call, reformat = reformat)
}
}
/**
* Matches:
* val variable = 0
* for (...) {
* ...
* variable++ (or ++variable)
* }
*/
object Matcher : TransformationMatcher {
override val indexVariableAllowed: Boolean
get() = false
override val shouldUseInputVariables: Boolean
get() = false
override fun match(state: MatchingState): TransformationMatch.Result? {
val operand = state.statements.singleOrNull()?.isPlusPlusOf() ?: return null
val initialization =
operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null
// this should be the only usage of this variable inside the loop
if (initialization.variable.countUsages(state.outerLoop) != 1) return null
val variableType = initialization.variable.resolveToDescriptorIfAny()?.type ?: return null
if (!KotlinBuiltIns.isInt(variableType)) return null
val transformation = CountTransformation(state.outerLoop, state.inputVariable, initialization, null)
return TransformationMatch.Result(transformation)
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt | 3320897702 |
package org.moire.ultrasonic.api.subsonic.response
import com.fasterxml.jackson.annotation.JsonProperty
import org.moire.ultrasonic.api.subsonic.SubsonicAPIVersions
import org.moire.ultrasonic.api.subsonic.SubsonicError
import org.moire.ultrasonic.api.subsonic.models.MusicDirectory
class GetMusicDirectoryResponse(
status: Status,
version: SubsonicAPIVersions,
error: SubsonicError?,
@JsonProperty("directory")
val musicDirectory: MusicDirectory = MusicDirectory()
) : SubsonicResponse(status, version, error)
| core/subsonic-api/src/main/kotlin/org/moire/ultrasonic/api/subsonic/response/GetMusicDirectoryResponse.kt | 1434390948 |
// 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.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.execution.process.ProcessIOExecutorService
import com.intellij.ide.IdeBundle
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerConfigurable
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.advertiser.PluginData
import com.intellij.ide.plugins.marketplace.MarketplaceRequests
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.PlainTextLikeFileType
import com.intellij.openapi.fileTypes.impl.DetectedByContentFileType
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import com.intellij.ui.EditorNotifications
import com.intellij.ui.HyperlinkLabel
import org.jetbrains.annotations.VisibleForTesting
import java.awt.BorderLayout
import java.util.function.Function
import javax.swing.JComponent
import javax.swing.JLabel
class PluginAdvertiserEditorNotificationProvider : EditorNotificationProvider,
DumbAware {
override fun collectNotificationData(
project: Project,
file: VirtualFile,
): Function<in FileEditor, out JComponent?> {
val suggestionData = getSuggestionData(project, ApplicationInfo.getInstance().build.productCode, file.name, file.fileType)
if (suggestionData == null) {
ProcessIOExecutorService.INSTANCE.execute {
val marketplaceRequests = MarketplaceRequests.getInstance()
marketplaceRequests.loadJetBrainsPluginsIds()
marketplaceRequests.loadExtensionsForIdes()
val extensionsStateService = PluginAdvertiserExtensionsStateService.instance
var shouldUpdateNotifications = extensionsStateService.updateCache(file.name)
val fullExtension = PluginAdvertiserExtensionsStateService.getFullExtension(file.name)
if (fullExtension != null) {
shouldUpdateNotifications = extensionsStateService.updateCache(fullExtension) || shouldUpdateNotifications
}
if (shouldUpdateNotifications) {
ApplicationManager.getApplication().invokeLater(
{ EditorNotifications.getInstance(project).updateNotifications(file) },
project.disposed
)
}
LOG.debug("Tried to update extensions cache for file '${file.name}'. shouldUpdateNotifications=$shouldUpdateNotifications")
}
return EditorNotificationProvider.CONST_NULL
}
return suggestionData
}
class AdvertiserSuggestion(
private val project: Project,
private val extensionOrFileName: String,
dataSet: Set<PluginData>,
jbPluginsIds: Set<String>,
val suggestedIdes: List<SuggestedIde>,
) : Function<FileEditor, EditorNotificationPanel?> {
private var installedPlugin: IdeaPluginDescriptor? = null
private val jbProduced = mutableSetOf<PluginData>()
@VisibleForTesting
val thirdParty = mutableSetOf<PluginData>()
init {
val descriptorsById = PluginManagerCore.buildPluginIdMap()
for (data in dataSet) {
val pluginId = data.pluginId
if (pluginId in descriptorsById) {
installedPlugin = descriptorsById[pluginId]
}
else if (!data.isBundled) {
(if (jbPluginsIds.contains(pluginId.idString)) jbProduced else thirdParty) += data
}
}
}
override fun apply(fileEditor: FileEditor): EditorNotificationPanel? {
lateinit var label: JLabel
val panel = object : EditorNotificationPanel(fileEditor) {
init {
label = myLabel
}
}
val pluginAdvertiserExtensionsState = PluginAdvertiserExtensionsStateService.instance.createExtensionDataProvider(project)
panel.text = IdeBundle.message("plugins.advertiser.plugins.found", extensionOrFileName)
fun createInstallActionLabel(plugins: Set<PluginData>) {
val labelText = plugins.singleOrNull()?.nullablePluginName?.let {
IdeBundle.message("plugins.advertiser.action.install.plugin.name", it)
} ?: IdeBundle.message("plugins.advertiser.action.install.plugins")
panel.createActionLabel(labelText) {
FUSEventSource.EDITOR.logInstallPlugins(plugins.map { it.pluginIdString })
installAndEnable(project, plugins.mapTo(HashSet()) { it.pluginId }, true) {
pluginAdvertiserExtensionsState.addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
updateAllNotifications(project)
}
}
}
val installedPlugin = installedPlugin
if (installedPlugin != null) {
if (!installedPlugin.isEnabled) {
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.enable.plugin", installedPlugin.name)) {
pluginAdvertiserExtensionsState.addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
updateAllNotifications(project)
FUSEventSource.EDITOR.logEnablePlugins(listOf(installedPlugin.pluginId.idString), project)
PluginManagerConfigurable.showPluginConfigurableAndEnable(project, setOf(installedPlugin))
}
}
else {
// Plugin supporting the pattern is installed and enabled but the current file is reassigned to a different
// file type
return null
}
}
else if (jbProduced.isNotEmpty()) {
createInstallActionLabel(jbProduced)
}
else if (suggestedIdes.isNotEmpty()) {
if (suggestedIdes.size > 1) {
val parentPanel = label.parent
parentPanel.remove(label)
val hyperlinkLabel = HyperlinkLabel().apply {
setTextWithHyperlink(IdeBundle.message("plugins.advertiser.extensions.supported.in.ides", extensionOrFileName))
addHyperlinkListener { FUSEventSource.EDITOR.learnMoreAndLog(project) }
}
parentPanel.add(hyperlinkLabel, BorderLayout.CENTER)
}
else {
panel.text = IdeBundle.message("plugins.advertiser.extensions.supported.in.ultimate", extensionOrFileName,
suggestedIdes.single().name)
}
for (suggestedIde in suggestedIdes) {
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.try.ultimate", suggestedIde.name)) {
pluginAdvertiserExtensionsState.addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
FUSEventSource.EDITOR.openDownloadPageAndLog(project, suggestedIde.downloadUrl)
}
}
if (suggestedIdes.size == 1) {
panel.createActionLabel(IdeBundle.message("plugins.advertiser.learn.more")) {
FUSEventSource.EDITOR.learnMoreAndLog(project)
}
}
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.ignore.ultimate")) {
FUSEventSource.EDITOR.doIgnoreUltimateAndLog(project)
updateAllNotifications(project)
}
return panel // Don't show the "Ignore extension" label
}
else if (thirdParty.isNotEmpty()) {
createInstallActionLabel(thirdParty)
}
else {
return null
}
panel.createActionLabel(IdeBundle.message("plugins.advertiser.action.ignore.extension")) {
FUSEventSource.EDITOR.logIgnoreExtension(project)
pluginAdvertiserExtensionsState.ignoreExtensionOrFileNameAndInvalidateCache(extensionOrFileName)
updateAllNotifications(project)
}
return panel
}
}
data class SuggestedIde(val name: String, val downloadUrl: String)
companion object {
private val LOG = logger<PluginAdvertiserEditorNotificationProvider>()
@VisibleForTesting
fun getSuggestionData(
project: Project,
activeProductCode: String,
fileName: String,
fileType: FileType,
): AdvertiserSuggestion? {
return PluginAdvertiserExtensionsStateService.instance
.createExtensionDataProvider(project)
.requestExtensionData(fileName, fileType)?.let {
getSuggestionData(project, it, activeProductCode, fileType)
}
}
private fun getSuggestionData(
project: Project,
extensionsData: PluginAdvertiserExtensionsData,
activeProductCode: String,
fileType: FileType,
): AdvertiserSuggestion? {
val marketplaceRequests = MarketplaceRequests.getInstance()
val jbPluginsIds = marketplaceRequests.jetBrainsPluginsIds ?: return null
val ideExtensions = marketplaceRequests.extensionsForIdes ?: return null
val extensionOrFileName = extensionsData.extensionOrFileName
val dataSet = extensionsData.plugins
val hasBundledPlugin = getBundledPluginToInstall(dataSet).isNotEmpty()
val suggestedIdes = if (fileType is PlainTextLikeFileType || fileType is DetectedByContentFileType) {
getSuggestedIdes(activeProductCode, extensionOrFileName, ideExtensions).ifEmpty {
if (hasBundledPlugin && !isIgnoreIdeSuggestion) listOf(ideaUltimate) else emptyList()
}
}
else
emptyList()
return AdvertiserSuggestion(project, extensionOrFileName, dataSet, jbPluginsIds, suggestedIdes)
}
private fun getSuggestedIdes(activeProductCode: String, extensionOrFileName: String, ideExtensions: Map<String, List<String>>): List<SuggestedIde> {
if (isIgnoreIdeSuggestion) {
return emptyList()
}
val productCodes = ideExtensions[extensionOrFileName]
if (productCodes.isNullOrEmpty()) {
return emptyList()
}
val suggestedIde = ides.entries.firstOrNull { it.key in productCodes }
val commercialVersionCode = when (activeProductCode) {
"IC", "IE" -> "IU"
"PC", "PE" -> "PY"
else -> null
}
if (commercialVersionCode != null && suggestedIde != null && suggestedIde.key != commercialVersionCode) {
return listOf(suggestedIde.value, ides[commercialVersionCode]!!)
}
else {
return suggestedIde?.value?.let { listOf(it) } ?: emptyList()
}
}
private fun updateAllNotifications(project: Project) {
EditorNotifications.getInstance(project).updateAllNotifications()
}
val ideaUltimate = SuggestedIde("IntelliJ IDEA Ultimate", "https://www.jetbrains.com/idea/download/")
val pyCharmProfessional = SuggestedIde("PyCharm Professional", "https://www.jetbrains.com/pycharm/download/")
private val ides = linkedMapOf(
"WS" to SuggestedIde("WebStorm", "https://www.jetbrains.com/webstorm/download/"),
"RM" to SuggestedIde("RubyMine", "https://www.jetbrains.com/ruby/download/"),
"PY" to pyCharmProfessional,
"PS" to SuggestedIde("PhpStorm", "https://www.jetbrains.com/phpstorm/download/"),
"GO" to SuggestedIde("GoLand", "https://www.jetbrains.com/go/download/"),
"CL" to SuggestedIde("CLion", "https://www.jetbrains.com/clion/download/"),
"RD" to SuggestedIde("Rider", "https://www.jetbrains.com/rider/download/"),
"OC" to SuggestedIde("AppCode", "https://www.jetbrains.com/objc/download/"),
"IU" to ideaUltimate
)
}
} | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.kt | 3148664318 |
fun <X, Y> gener<caret>ic1(p: X, f: (X) -> Y): Y = f(p)
fun usage() {
val a = generic1("abc") { x -> x.length }
val b = generic1("abc", { x -> x.length })
val c = generic1("abc") { it.length }
val d = generic1("abc", { it.length })
} | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/lambdaArgumentInDiffirentPosition.kt | 4081087930 |
/*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.epm
import jclp.io.extName
import jclp.setting.Settings
import jclp.text.or
import jem.Book
import java.io.File
data class ParserParam(val path: String, val format: String = "", val arguments: Settings? = null) {
val epmName inline get() = format or { extName(File(path).canonicalPath) }
override fun toString(): String =
"ParserParam(path='$path', format='$format', epmName='$epmName', arguments=$arguments)"
}
data class MakerParam(val book: Book, val path: String, val format: String = "", val arguments: Settings? = null) {
val epmName inline get() = format or { extName(File(path).canonicalPath) }
var actualPath: String = path
internal set
override fun toString(): String =
"MakerParam(book=$book, path='$path', format='$format', epmName='$epmName', arguments=$arguments)"
}
| jem-core/src/main/kotlin/jem/epm/Params.kt | 3571369196 |
package com.example.foxy.kotlinmanylayout
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
}
| Anko/KotlinManyLayout/app/src/main/java/com/example/foxy/kotlinmanylayout/Main2Activity.kt | 1727190121 |
package com.seancheey.gui
import com.seancheey.game.Config
import com.seancheey.game.Game
import com.seancheey.game.GameDirector
import com.seancheey.game.model.GuiNode
import com.seancheey.game.model.Node
import com.seancheey.game.model.RobotModel
import com.seancheey.game.model.RobotNode
import javafx.scene.canvas.Canvas
import javafx.scene.input.KeyCode
import javafx.scene.input.MouseButton
import javafx.scene.layout.AnchorPane
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.transform.Affine
/**
* Created by Seancheey on 01/06/2017.
* GitHub: https://github.com/Seancheey
*/
class BattleInspectPane(val battleCanvas: BattleCanvas) : AnchorPane(), GameInspector by battleCanvas {
constructor(game: Game, clipWidth: Double, clipHeight: Double) : this(BattleCanvas(game, clipWidth, clipHeight))
init {
AnchorPane.setLeftAnchor(battleCanvas, 0.0)
AnchorPane.setTopAnchor(battleCanvas, 0.0)
children.add(battleCanvas)
clip = Rectangle((battleCanvas.guiWidth - battleCanvas.clipWidth) / 2, (battleCanvas.guiHeight - battleCanvas.clipHeight) / 2, battleCanvas.clipWidth, battleCanvas.clipHeight)
battleCanvas.drawGuiNode = { a, b -> drawGuiNode(a, b) }
battleCanvas.clearGuiNode = { clearGuiNodes() }
}
fun drawGuiNode(node: GuiNode, parentNode: Node) {
val parentX = parentNode.x * cameraScale - (battleCanvas.guiWidth * cameraScale - width) / 2 + cameraTransX
val parentY = parentNode.y * cameraScale - (battleCanvas.guiHeight * cameraScale - height) / 2 + cameraTransY
if (node.gui !in children) {
children.add(node.gui)
}
AnchorPane.setLeftAnchor(node.gui, node.leftX + parentX)
AnchorPane.setTopAnchor(node.gui, node.upperY + parentY)
}
fun clearGuiNodes() {
val guiNodes = arrayListOf<GuiNode>()
gameDirector.nodes.forEach {
guiNodes.addAll(it.children.filterIsInstance<GuiNode>())
}
val guis = guiNodes.map { it.gui }
val toRemove = children.filter { it !in guis && it != battleCanvas }
children.removeAll(toRemove)
}
class BattleCanvas(override val game: Game, val clipWidth: Double, val clipHeight: Double) : Canvas(game.field.width, game.field.height), GameInspector {
override fun clickRobot(model: RobotModel) {
if (!model.empty) {
battlefield.nodeAddQueue.add(RobotNode(model, battlefield, battlefield.width / 2, battlefield.height / 2, game.playerMap[Config.player]!!))
}
}
override var cameraTransX: Double = 0.0
set(value) {
field = value
translateX = value
clipCanvas()
}
override var cameraTransY: Double = 0.0
set(value) {
field = value
translateY = value
clipCanvas()
}
override var cameraScale: Double = 1.0
set(value) {
scaleX = value
scaleY = value
scaleZ = value
field = value
clipCanvas()
}
override val guiWidth: Double
get() = width
override val guiHeight: Double
get() = height
override val gameDirector: GameDirector = GameDirector(game, { nodes, lag ->
graphicsContext2D.restore()
graphicsContext2D.fill = Color.LIGHTGRAY
graphicsContext2D.fillRect(0.0, 0.0, this.width, this.height)
graphicsContext2D.save()
graphicsContext2D.fill = Color.ALICEBLUE
graphicsContext2D.scale(cameraScale, cameraScale)
nodes.forEach {
drawNode(it)
}
// request focus to handle key event
requestFocus()
cameraTransX += vx
cameraTransY += vy
// clear Gui Nodes
clearGuiNode()
})
private var vx: Double = 0.0
private var vy: Double = 0.0
var drawGuiNode: (GuiNode, Node) -> Unit = { _, _ -> }
var clearGuiNode: () -> Unit = {}
init {
clipCanvas()
fullMapScale()
setOnMouseClicked { event ->
if (event.button == MouseButton.PRIMARY) {
selectRobotBeside(event.x, event.y)
}
if (event.button == MouseButton.SECONDARY) {
moveFocusedRobotsTo(event.x, event.y)
}
if (event.button == MouseButton.MIDDLE) {
val nodes = gameDirector.nodes.filter { it.containsPoint(event.x, event.y) }.filterIsInstance<RobotModel>()
if (nodes.isNotEmpty()) {
val firstNode: RobotModel = nodes[0]
selectAllRobotsWithSameType(firstNode)
}
}
}
setOnScroll { event ->
if (event.deltaY > 0) {
cameraScale *= 1 - Config.scrollSpeedDelta
} else if (event.deltaY < 0) {
cameraScale *= 1 + Config.scrollSpeedDelta
}
}
setOnKeyPressed { event ->
when (event.code) {
KeyCode.W ->
vy = 1.0
KeyCode.S ->
vy = -1.0
KeyCode.A ->
vx = 1.0
KeyCode.D ->
vx = -1.0
else -> return@setOnKeyPressed
}
}
setOnKeyReleased { event ->
when (event.code) {
KeyCode.A, KeyCode.D ->
vx = 0.0
KeyCode.W, KeyCode.S ->
vy = 0.0
else -> return@setOnKeyReleased
}
}
start()
}
fun fullMapScale() {
cameraScale = minOf(clipWidth / width, clipHeight / height)
}
fun start() {
gameDirector.start()
}
fun stop() {
gameDirector.stop = true
}
fun clipOffsetX() = (width - clipWidth / cameraScale) / 2 - translateX / cameraScale
fun clipOffsetY() = (height - clipHeight / cameraScale) / 2 - translateY / cameraScale
/**
* ensure the canvas doesn't come out
*/
private fun clipCanvas() {
val clipRect = Rectangle(clipOffsetX(), clipOffsetY(), clipWidth / cameraScale, clipHeight / cameraScale)
clip = clipRect
}
private fun nodeTranslation(node: Node): Affine {
return Affine(Affine.translate(node.leftX, node.upperY))
}
private fun nodeRotation(node: Node): Affine {
if (node is RobotNode) {
return Affine(Affine.rotate(node.degreeOrientation + 90.0, node.width / 2, node.height / 2))
} else {
return Affine(Affine.rotate(node.degreeOrientation, node.width / 2, node.height / 2))
}
}
private fun drawNode(node: Node, transform: Affine = Affine()) {
val originalTrans = graphicsContext2D.transform
val newTrans: Affine = transform
newTrans.append(nodeTranslation(node))
newTrans.append(nodeRotation(node))
graphicsContext2D.transform = newTrans
graphicsContext2D.drawImage(node.image, 0.0, 0.0, node.width, node.height)
// draw focus if apply
if (node.focusedByPlayer) {
drawFocus(node)
}
// recursively draw its children, assign a copy to prevent concurrency problem
val children = node.immutableChildren
children.forEach {
if (it is GuiNode) {
drawGuiNode(it, node)
} else {
drawNode(it, newTrans.clone())
}
}
graphicsContext2D.transform = originalTrans
}
private fun drawFocus(node: Node) {
graphicsContext2D.transform = Affine()
graphicsContext2D.strokeOval(node.leftX, node.upperY, node.width, node.height)
}
}
} | src/com/seancheey/gui/BattleInspectPane.kt | 1537393496 |
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.sqs
import aws.sdk.kotlin.services.comprehend.ComprehendClient
import aws.sdk.kotlin.services.comprehend.model.DetectDominantLanguageRequest
import aws.sdk.kotlin.services.sqs.SqsClient
import aws.sdk.kotlin.services.sqs.model.GetQueueUrlRequest
import aws.sdk.kotlin.services.sqs.model.MessageAttributeValue
import aws.sdk.kotlin.services.sqs.model.PurgeQueueRequest
import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest
import aws.sdk.kotlin.services.sqs.model.SendMessageRequest
import org.springframework.stereotype.Component
@Component
class SendReceiveMessages {
private val queueNameVal = "Message.fifo"
// Purges the queue.
suspend fun purgeMyQueue() {
var queueUrlVal: String
val getQueueRequest = GetQueueUrlRequest {
queueName = queueNameVal
}
SqsClient { region = "us-west-2" }.use { sqsClient ->
queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl.toString()
val queueRequest = PurgeQueueRequest {
queueUrl = queueUrlVal
}
sqsClient.purgeQueue(queueRequest)
}
}
// Retrieves messages from the FIFO queue.
suspend fun getMessages(): List<MessageData>? {
val attr: MutableList<String> = ArrayList()
attr.add("Name")
val getQueueRequest = GetQueueUrlRequest {
queueName = queueNameVal
}
SqsClient { region = "us-west-2" }.use { sqsClient ->
val queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl
val receiveRequest = ReceiveMessageRequest {
queueUrl = queueUrlVal
maxNumberOfMessages = 10
waitTimeSeconds = 20
messageAttributeNames = attr
}
val messages = sqsClient.receiveMessage(receiveRequest).messages
var myMessage: MessageData
val allMessages = mutableListOf<MessageData>()
// Push the messages to a list.
if (messages != null) {
for (m in messages) {
myMessage = MessageData()
myMessage.body = m.body
myMessage.id = m.messageId
val map = m.messageAttributes
val `val` = map?.get("Name")
if (`val` != null) {
myMessage.name = `val`.stringValue
}
allMessages.add(myMessage)
}
}
return allMessages
}
}
// Adds a new message to the FIFO queue.
suspend fun processMessage(msg: MessageData) {
val attributeValue = MessageAttributeValue {
stringValue = msg.name
dataType = "String"
}
val myMap: MutableMap<String, MessageAttributeValue> = HashMap()
myMap["Name"] = attributeValue
val getQueueRequest = GetQueueUrlRequest {
queueName = queueNameVal
}
// Get the language code of the incoming message.
var lanCode = ""
val request = DetectDominantLanguageRequest {
text = msg.body
}
ComprehendClient { region = "us-west-2" }.use { comClient ->
val resp = comClient.detectDominantLanguage(request)
val allLanList = resp.languages
if (allLanList != null) {
for (lang in allLanList) {
println("Language is " + lang.languageCode)
lanCode = lang.languageCode.toString()
}
}
}
// Send the message to the FIFO queue.
SqsClient { region = "us-west-2" }.use { sqsClient ->
val queueUrlVal: String? = sqsClient.getQueueUrl(getQueueRequest).queueUrl
val sendMsgRequest = SendMessageRequest {
queueUrl = queueUrlVal
messageAttributes = myMap
messageGroupId = "GroupA_$lanCode"
messageDeduplicationId = msg.id
messageBody = msg.body
}
sqsClient.sendMessage(sendMsgRequest)
}
}
}
| kotlin/usecases/creating_message_application/src/main/kotlin/com/example/sqs/SendReceiveMessages.kt | 63913419 |
// 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 org.jetbrains.plugins.github.pullrequest.ui.details
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.GithubIcons
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestsBusyStateTracker
import org.jetbrains.plugins.github.pullrequest.data.service.GithubPullRequestsSecurityService
import org.jetbrains.plugins.github.pullrequest.data.service.GithubPullRequestsStateService
import org.jetbrains.plugins.github.util.GithubUtil.Delegates.equalVetoingObservable
import java.awt.FlowLayout
import java.awt.event.ActionEvent
import javax.swing.*
internal class GithubPullRequestStatePanel(private val model: GithubPullRequestDetailsModel,
private val securityService: GithubPullRequestsSecurityService,
private val busyStateTracker: GithubPullRequestsBusyStateTracker,
private val stateService: GithubPullRequestsStateService)
: NonOpaquePanel(VerticalFlowLayout(0, 0)), Disposable {
private val stateLabel = JLabel().apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0)
}
private val accessDeniedPanel = JLabel("Repository write access required to merge pull requests").apply {
foreground = UIUtil.getContextHelpForeground()
}
private val closeAction = object : AbstractAction("Close") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.close(number) }
}
}
private val closeButton = JButton(closeAction)
private val reopenAction = object : AbstractAction("Reopen") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.reopen(number) }
}
}
private val reopenButton = JButton(reopenAction)
private val mergeAction = object : AbstractAction("Merge...") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.merge(number) }
}
}
private val rebaseMergeAction = object : AbstractAction("Rebase and Merge") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.rebaseMerge(number) }
}
}
private val squashMergeAction = object : AbstractAction("Squash and Merge...") {
override fun actionPerformed(e: ActionEvent?) {
state?.run { stateService.squashMerge(number) }
}
}
private val mergeButton = JBOptionButton(null, null)
private val browseButton = LinkLabel.create("Open on GitHub") {
model.details?.run { BrowserUtil.browse(htmlUrl) }
}.apply {
icon = AllIcons.Ide.External_link_arrow
setHorizontalTextPosition(SwingConstants.LEFT)
}
private val buttonsPanel = NonOpaquePanel(FlowLayout(FlowLayout.LEADING, 0, 0)).apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, 0)
if (Registry.`is`("github.action.pullrequest.state.useapi")) {
add(mergeButton)
add(closeButton)
add(reopenButton)
}
else {
add(browseButton)
}
}
init {
isOpaque = false
add(stateLabel)
add(accessDeniedPanel)
add(buttonsPanel)
model.addDetailsChangedListener(this) {
state = model.details?.let {
GithubPullRequestStatePanel.State(it.number, it.state, it.merged, it.mergeable, it.rebaseable,
securityService.isCurrentUserWithPushAccess(), securityService.isCurrentUser(it.user),
securityService.isMergeAllowed(),
securityService.isRebaseMergeAllowed(),
securityService.isSquashMergeAllowed(),
securityService.isMergeForbiddenForProject(),
busyStateTracker.isBusy(it.number))
}
}
busyStateTracker.addPullRequestBusyStateListener(this) {
if (it == state?.number)
state = state?.copy(busy = busyStateTracker.isBusy(it))
}
}
private var state: GithubPullRequestStatePanel.State? by equalVetoingObservable<GithubPullRequestStatePanel.State?>(null) {
updateText(it)
updateActions(it)
}
private fun updateText(state: GithubPullRequestStatePanel.State?) {
if (state == null) {
stateLabel.text = ""
stateLabel.icon = null
accessDeniedPanel.isVisible = false
}
else {
if (state.state == GithubIssueState.closed) {
if (state.merged) {
stateLabel.icon = GithubIcons.PullRequestClosed
stateLabel.text = "Pull request is merged"
}
else {
stateLabel.icon = GithubIcons.PullRequestClosed
stateLabel.text = "Pull request is closed"
}
accessDeniedPanel.isVisible = false
}
else {
val mergeable = state.mergeable
if (mergeable == null) {
stateLabel.icon = AllIcons.RunConfigurations.TestNotRan
stateLabel.text = "Checking for ability to merge automatically..."
}
else {
if (mergeable) {
stateLabel.icon = AllIcons.RunConfigurations.TestPassed
stateLabel.text = "Branch has no conflicts with base branch"
}
else {
stateLabel.icon = AllIcons.RunConfigurations.TestFailed
stateLabel.text = "Branch has conflicts that must be resolved"
}
}
accessDeniedPanel.isVisible = !state.editAllowed
}
}
}
private fun updateActions(state: GithubPullRequestStatePanel.State?) {
if (state == null) {
reopenAction.isEnabled = false
reopenButton.isVisible = false
closeAction.isEnabled = false
closeButton.isVisible = false
mergeAction.isEnabled = false
rebaseMergeAction.isEnabled = false
squashMergeAction.isEnabled = false
mergeButton.action = null
mergeButton.options = emptyArray()
mergeButton.isVisible = false
browseButton.isVisible = false
}
else {
reopenButton.isVisible = (state.editAllowed || state.currentUserIsAuthor) && state.state == GithubIssueState.closed && !state.merged
reopenAction.isEnabled = reopenButton.isVisible && !state.busy
closeButton.isVisible = (state.editAllowed || state.currentUserIsAuthor) && state.state == GithubIssueState.open
closeAction.isEnabled = closeButton.isVisible && !state.busy
mergeButton.isVisible = state.editAllowed && state.state == GithubIssueState.open && !state.merged
mergeAction.isEnabled = mergeButton.isVisible && (state.mergeable ?: false) && !state.busy && !state.mergeForbidden
rebaseMergeAction.isEnabled = mergeButton.isVisible && (state.rebaseable ?: false) && !state.busy && !state.mergeForbidden
squashMergeAction.isEnabled = mergeButton.isVisible && (state.mergeable ?: false) && !state.busy && !state.mergeForbidden
mergeButton.optionTooltipText = if (state.mergeForbidden) "Merge actions are disabled for this project" else null
val allowedActions = mutableListOf<Action>()
if (state.mergeAllowed) allowedActions.add(mergeAction)
if (state.rebaseMergeAllowed) allowedActions.add(rebaseMergeAction)
if (state.squashMergeAllowed) allowedActions.add(squashMergeAction)
val action = allowedActions.firstOrNull()
val actions = if (allowedActions.size > 1) Array(allowedActions.size - 1) { allowedActions[it + 1] } else emptyArray()
mergeButton.action = action
mergeButton.options = actions
browseButton.isVisible = true
}
}
override fun dispose() {}
private data class State(val number: Long,
val state: GithubIssueState,
val merged: Boolean,
val mergeable: Boolean?,
val rebaseable: Boolean?,
val editAllowed: Boolean,
val currentUserIsAuthor: Boolean,
val mergeAllowed: Boolean,
val rebaseMergeAllowed: Boolean,
val squashMergeAllowed: Boolean,
val mergeForbidden: Boolean,
val busy: Boolean)
} | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GithubPullRequestStatePanel.kt | 820998176 |
package com.virtlink.paplj.intellij
import com.intellij.openapi.fileTypes.LanguageFileType
import javax.swing.Icon
object PapljFileType : LanguageFileType(PapljLanguage) {
const val EXTENSION = "pj"
override fun getName(): String {
return "PAPLJ"
}
override fun getDefaultExtension(): String {
return EXTENSION
}
override fun getDescription(): String {
return "PAPLJ file"
}
override fun getIcon(): Icon? {
return PapljIcons.FILE
}
}
| paplj-intellij/src/main/kotlin/com/virtlink/paplj/intellij/PapljFileType.kt | 4180304956 |
package com.igorini.kotlin.android.app
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.igorini.kotlin.android.app", appContext.packageName)
}
}
| app/src/androidTest/java/com/igorini/kotlin/android/app/ExampleInstrumentedTest.kt | 614396287 |
// 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.debugger.core.breakpoints
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.PositionUtil
import com.intellij.debugger.requests.Requestor
import com.intellij.debugger.ui.breakpoints.BreakpointCategory
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter
import com.intellij.debugger.ui.breakpoints.FieldBreakpoint
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.Method
import com.sun.jdi.ReferenceType
import com.sun.jdi.event.*
import com.sun.jdi.request.EventRequest
import com.sun.jdi.request.MethodEntryRequest
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.symbols.KtKotlinPropertySymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.debugger.base.util.safeAllLineLocations
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.*
import javax.swing.Icon
class KotlinFieldBreakpoint(
project: Project,
breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties>
) : BreakpointWithHighlighter<KotlinPropertyBreakpointProperties>(project, breakpoint) {
companion object {
private val LOG = Logger.getInstance(KotlinFieldBreakpoint::class.java)
private val CATEGORY: Key<FieldBreakpoint> = BreakpointCategory.lookup("field_breakpoints")
}
private enum class BreakpointType {
FIELD,
METHOD
}
private var breakpointType: BreakpointType = BreakpointType.FIELD
override fun isValid(): Boolean {
return super.isValid() && evaluationElement != null
}
override fun reload() {
super.reload()
val callable = evaluationElement ?: return
val callableName = callable.name ?: return
setFieldName(callableName)
if (callable is KtProperty && callable.isTopLevel) {
properties.myClassName = JvmFileClassUtil.getFileClassInfoNoResolve(callable.getContainingKtFile()).fileClassFqName.asString()
} else {
val ktClass: KtClassOrObject? = PsiTreeUtil.getParentOfType(callable, KtClassOrObject::class.java)
if (ktClass is KtClassOrObject) {
val fqName = ktClass.fqName
if (fqName != null) {
properties.myClassName = fqName.asString()
}
}
}
isInstanceFiltersEnabled = false
}
override fun createRequestForPreparedClass(debugProcess: DebugProcessImpl?, refType: ReferenceType?) {
if (debugProcess == null || refType == null) return
breakpointType = evaluationElement?.let(::computeBreakpointType) ?: return
val vm = debugProcess.virtualMachineProxy
try {
if (properties.watchInitialization) {
val sourcePosition = sourcePosition
if (sourcePosition != null) {
debugProcess.positionManager
.locationsOfLine(refType, sourcePosition)
.filter { it.method().isConstructor || it.method().isStaticInitializer }
.forEach {
val request = debugProcess.requestsManager.createBreakpointRequest(this, it)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
}
}
}
when (breakpointType) {
BreakpointType.FIELD -> {
val field = refType.fieldByName(getFieldName())
if (field != null) {
val manager = debugProcess.requestsManager
if (properties.watchModification && vm.canWatchFieldModification()) {
val request = manager.createModificationWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Modification request added")
}
}
if (properties.watchAccess && vm.canWatchFieldAccess()) {
val request = manager.createAccessWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Field access request added (field = ${field.name()}; refType = ${refType.name()})")
}
}
}
}
BreakpointType.METHOD -> {
val fieldName = getFieldName()
if (properties.watchAccess) {
val getter = refType.methodsByName(JvmAbi.getterName(fieldName)).firstOrNull()
if (getter != null) {
createMethodBreakpoint(debugProcess, refType, getter)
}
}
if (properties.watchModification) {
val setter = refType.methodsByName(JvmAbi.setterName(fieldName)).firstOrNull()
if (setter != null) {
createMethodBreakpoint(debugProcess, refType, setter)
}
}
}
}
} catch (ex: Exception) {
LOG.debug(ex)
}
}
private fun computeBreakpointType(property: KtCallableDeclaration): BreakpointType {
return runReadAction {
analyze(property) {
val hasBackingField = when (val symbol = property.getSymbol()) {
is KtValueParameterSymbol -> symbol.generatedPrimaryConstructorProperty?.hasBackingField ?: false
is KtKotlinPropertySymbol -> symbol.hasBackingField
else -> false
}
if (hasBackingField) BreakpointType.FIELD else BreakpointType.METHOD
}
}
}
private fun createMethodBreakpoint(debugProcess: DebugProcessImpl, refType: ReferenceType, accessor: Method) {
val manager = debugProcess.requestsManager
val line = accessor.safeAllLineLocations().firstOrNull()
if (line != null) {
val request = manager.createBreakpointRequest(this, line)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
} else {
var entryRequest: MethodEntryRequest? = findRequest(debugProcess, MethodEntryRequest::class.java, this)
if (entryRequest == null) {
entryRequest = manager.createMethodEntryRequest(this)!!
if (LOG.isDebugEnabled) {
LOG.debug("Method entry request added (method = ${accessor.name()}; refType = ${refType.name()})")
}
} else {
entryRequest.disable()
}
entryRequest.addClassFilter(refType)
manager.enableRequest(entryRequest)
}
}
private inline fun <reified T : EventRequest> findRequest(
debugProcess: DebugProcessImpl,
requestClass: Class<T>,
requestor: Requestor
): T? {
val requests = debugProcess.requestsManager.findRequests(requestor)
for (eventRequest in requests) {
if (eventRequest::class.java == requestClass) {
return eventRequest as T
}
}
return null
}
override fun evaluateCondition(context: EvaluationContextImpl, event: LocatableEvent): Boolean {
if (breakpointType == BreakpointType.METHOD && !matchesEvent(event)) {
return false
}
return super.evaluateCondition(context, event)
}
private fun matchesEvent(event: LocatableEvent): Boolean {
val method = event.location()?.method()
// TODO check property type
return method != null && method.name() in getMethodsName()
}
private fun getMethodsName(): List<String> {
val fieldName = getFieldName()
return listOf(JvmAbi.getterName(fieldName), JvmAbi.setterName(fieldName))
}
override fun getEventMessage(event: LocatableEvent): String {
val location = event.location()!!
val locationQName = location.declaringType().name() + "." + location.method().name()
val locationFileName = try {
location.sourceName()
} catch (e: AbsentInformationException) {
fileName
} catch (e: InternalError) {
fileName
}
val locationLine = location.lineNumber()
when (event) {
is ModificationWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is AccessWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is MethodEntryEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.entry.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
is MethodExitEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.exit.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
}
return JavaDebuggerBundle.message(
"status.line.breakpoint.reached",
locationQName,
locationFileName,
locationLine
)
}
fun setFieldName(fieldName: String) {
properties.myFieldName = fieldName
}
@TestOnly
fun setWatchAccess(value: Boolean) {
properties.watchAccess = value
}
@TestOnly
fun setWatchModification(value: Boolean) {
properties.watchModification = value
}
@TestOnly
fun setWatchInitialization(value: Boolean) {
properties.watchInitialization = value
}
override fun getDisabledIcon(isMuted: Boolean): Icon {
val master = DebuggerManagerEx.getInstanceEx(myProject).breakpointManager.findMasterBreakpoint(this)
return when {
isMuted && master == null -> AllIcons.Debugger.Db_muted_disabled_field_breakpoint
isMuted && master != null -> AllIcons.Debugger.Db_muted_dep_field_breakpoint
master != null -> AllIcons.Debugger.Db_dep_field_breakpoint
else -> AllIcons.Debugger.Db_disabled_field_breakpoint
}
}
override fun getSetIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_field_breakpoint
}
}
override fun getVerifiedIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_verified_field_breakpoint
}
}
override fun getVerifiedWarningsIcon(isMuted: Boolean): Icon = AllIcons.Debugger.Db_exception_breakpoint
override fun getCategory() = CATEGORY
override fun getDisplayName(): String {
if (!isValid) {
return JavaDebuggerBundle.message("status.breakpoint.invalid")
}
val className = className
@Suppress("HardCodedStringLiteral")
return if (!className.isNullOrEmpty()) className + "." + getFieldName() else getFieldName()
}
private fun getFieldName(): String {
return runReadAction {
evaluationElement?.name ?: "unknown"
}
}
override fun getEvaluationElement(): KtCallableDeclaration? {
return when (val callable = PositionUtil.getPsiElementAt(project, KtValVarKeywordOwner::class.java, sourcePosition)) {
is KtProperty -> callable
is KtParameter -> callable
else -> null
}
}
}
| plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/KotlinFieldBreakpoint.kt | 1441882877 |
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apollographql.apollo3.api.json
import com.apollographql.apollo3.api.json.internal.JsonScope
import com.apollographql.apollo3.exception.JsonDataException
import com.apollographql.apollo3.exception.JsonEncodingException
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
import okio.ByteString.Companion.encodeUtf8
import okio.EOFException
import okio.IOException
/**
* A [JsonWriter] that reads json from an okio [BufferedSource]
*
* The base implementation was taken from Moshi and ported to Kotlin multiplatform with some tweaks to make it better suited for GraphQL
* (see [JsonReader]).
*
* To read from a [Map], see also [MapJsonReader]
*/
class BufferedSourceJsonReader(private val source: BufferedSource) : JsonReader {
private val buffer: Buffer = source.buffer
private var peeked = PEEKED_NONE
/**
* A peeked value that was composed entirely of digits with an optional leading dash. Positive values may not have a leading 0.
*/
private var peekedLong: Long = 0
/**
* The number of characters in a peeked number literal. Increment 'pos' by this after reading a number.
*/
private var peekedNumberLength = 0
/**
* A peeked string that should be parsed on the next double, long or string.
* This is populated before a numeric value is parsed and used if that parsing fails.
*/
private var peekedString: String? = null
/**
* The nesting stack. Using a manual array rather than an ArrayList saves 20%.
* This stack permits up to MAX_STACK_SIZE levels of nesting including the top-level document.
* Deeper nesting is prone to trigger StackOverflowErrors.
*/
private val stack = IntArray(MAX_STACK_SIZE).apply {
this[0] = JsonScope.EMPTY_DOCUMENT
}
private var stackSize = 1
private val pathNames = arrayOfNulls<String>(MAX_STACK_SIZE)
private val pathIndices = IntArray(MAX_STACK_SIZE)
private var lenient = false
private val indexStack = IntArray(MAX_STACK_SIZE).apply {
this[0] = 0
}
private var indexStackSize = 1
override fun beginArray(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_BEGIN_ARRAY) {
push(JsonScope.EMPTY_ARRAY)
pathIndices[stackSize - 1] = 0
peeked = PEEKED_NONE
} else {
throw JsonDataException("Expected BEGIN_ARRAY but was ${peek()} at path ${getPath()}")
}
}
override fun endArray(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_END_ARRAY) {
stackSize--
pathIndices[stackSize - 1]++
peeked = PEEKED_NONE
} else {
throw JsonDataException("Expected END_ARRAY but was ${peek()} at path ${getPath()}")
}
}
override fun beginObject(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_BEGIN_OBJECT) {
push(JsonScope.EMPTY_OBJECT)
peeked = PEEKED_NONE
indexStackSize++
indexStack[indexStackSize - 1] = 0
} else {
throw JsonDataException("Expected BEGIN_OBJECT but was ${peek()} at path ${getPath()}")
}
}
override fun endObject(): JsonReader = apply {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
if (p == PEEKED_END_OBJECT) {
stackSize--
pathNames[stackSize] = null // Free the last path name so that it can be garbage collected!
pathIndices[stackSize - 1]++
peeked = PEEKED_NONE
indexStackSize--
} else {
throw JsonDataException("Expected END_OBJECT but was ${peek()} at path ${getPath()}")
}
}
override fun hasNext(): Boolean {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
return p != PEEKED_END_OBJECT && p != PEEKED_END_ARRAY
}
override fun peek(): JsonReader.Token {
return when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_BEGIN_OBJECT -> JsonReader.Token.BEGIN_OBJECT
PEEKED_END_OBJECT -> JsonReader.Token.END_OBJECT
PEEKED_BEGIN_ARRAY -> JsonReader.Token.BEGIN_ARRAY
PEEKED_END_ARRAY -> JsonReader.Token.END_ARRAY
PEEKED_SINGLE_QUOTED_NAME, PEEKED_DOUBLE_QUOTED_NAME, PEEKED_UNQUOTED_NAME -> JsonReader.Token.NAME
PEEKED_TRUE, PEEKED_FALSE -> JsonReader.Token.BOOLEAN
PEEKED_NULL -> JsonReader.Token.NULL
PEEKED_SINGLE_QUOTED, PEEKED_DOUBLE_QUOTED, PEEKED_UNQUOTED, PEEKED_BUFFERED -> JsonReader.Token.STRING
PEEKED_LONG -> JsonReader.Token.LONG
PEEKED_NUMBER -> JsonReader.Token.NUMBER
PEEKED_EOF -> JsonReader.Token.END_DOCUMENT
else -> throw AssertionError()
}
}
private fun doPeek(): Int {
val peekStack = stack[stackSize - 1]
when (peekStack) {
JsonScope.EMPTY_ARRAY -> {
stack[stackSize - 1] = JsonScope.NONEMPTY_ARRAY
}
JsonScope.NONEMPTY_ARRAY -> {
// Look for a comma before the next element.
val c = nextNonWhitespace(true)
buffer.readByte() // consume ']' or ','.
when (c.toChar()) {
']' -> return PEEKED_END_ARRAY.also { peeked = it }
';' -> checkLenient() // fall-through
',' -> Unit
else -> throw syntaxError("Unterminated array")
}
}
JsonScope.EMPTY_OBJECT, JsonScope.NONEMPTY_OBJECT -> {
stack[stackSize - 1] = JsonScope.DANGLING_NAME
// Look for a comma before the next element.
if (peekStack == JsonScope.NONEMPTY_OBJECT) {
val c = nextNonWhitespace(true)
buffer.readByte() // Consume '}' or ','.
when (c.toChar()) {
'}' -> return PEEKED_END_OBJECT.also { peeked = it }
';' -> checkLenient() // fall-through
',' -> Unit
else -> throw syntaxError("Unterminated object")
}
}
val c = nextNonWhitespace(true)
return when (c.toChar()) {
'"' -> {
buffer.readByte() // consume the '\"'.
PEEKED_DOUBLE_QUOTED_NAME.also { peeked = it }
}
'\'' -> {
buffer.readByte() // consume the '\''.
checkLenient()
PEEKED_SINGLE_QUOTED_NAME.also { peeked = it }
}
'}' -> if (peekStack != JsonScope.NONEMPTY_OBJECT) {
buffer.readByte() // consume the '}'.
PEEKED_END_OBJECT.also { peeked = it }
} else {
throw syntaxError("Expected name")
}
else -> {
checkLenient()
if (isLiteral(c.toChar())) {
PEEKED_UNQUOTED_NAME.also { peeked = it }
} else {
throw syntaxError("Expected name")
}
}
}
}
JsonScope.DANGLING_NAME -> {
stack[stackSize - 1] = JsonScope.NONEMPTY_OBJECT
// Look for a colon before the value.
val c = nextNonWhitespace(true)
buffer.readByte() // Consume ':'.
when (c.toChar()) {
':' -> {
}
'=' -> {
checkLenient()
if (source.request(1) && buffer[0] == '>'.code.toByte()) {
buffer.readByte() // Consume '>'.
}
}
else -> throw syntaxError("Expected ':'")
}
}
JsonScope.EMPTY_DOCUMENT -> {
stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT
}
JsonScope.NONEMPTY_DOCUMENT -> {
val c = nextNonWhitespace(false)
if (c == -1) {
return PEEKED_EOF.also { peeked = it }
} else {
checkLenient()
}
}
else -> check(peekStack != JsonScope.CLOSED) { "JsonReader is closed" }
}
val c = nextNonWhitespace(true)
when (c.toChar()) {
']' -> {
if (peekStack == JsonScope.EMPTY_ARRAY) {
buffer.readByte() // Consume ']'.
return PEEKED_END_ARRAY.also { peeked = it }
}
// In lenient mode, a 0-length literal in an array means 'null'.
return if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) {
checkLenient()
PEEKED_NULL.also { peeked = it }
} else {
throw syntaxError("Unexpected value")
}
}
';', ',' -> return if (peekStack == JsonScope.EMPTY_ARRAY || peekStack == JsonScope.NONEMPTY_ARRAY) {
checkLenient()
PEEKED_NULL.also { peeked = it }
} else {
throw syntaxError("Unexpected value")
}
'\'' -> {
checkLenient()
buffer.readByte() // Consume '\''.
return PEEKED_SINGLE_QUOTED.also { peeked = it }
}
'"' -> {
buffer.readByte() // Consume '\"'.
return PEEKED_DOUBLE_QUOTED.also { peeked = it }
}
'[' -> {
buffer.readByte() // Consume '['.
return PEEKED_BEGIN_ARRAY.also { peeked = it }
}
'{' -> {
buffer.readByte() // Consume '{'.
return PEEKED_BEGIN_OBJECT.also { peeked = it }
}
}
var result = peekKeyword()
if (result != PEEKED_NONE) {
return result
}
result = peekNumber()
if (result != PEEKED_NONE) {
return result
}
if (!isLiteral(buffer[0].toInt().toChar())) {
throw syntaxError("Expected value")
}
checkLenient()
return PEEKED_UNQUOTED.also { peeked = it }
}
private fun peekKeyword(): Int { // Figure out which keyword we're matching against by its first character.
val keyword: String
val keywordUpper: String
val peeking: Int
when (buffer[0]) {
't'.code.toByte(), 'T'.code.toByte() -> {
keyword = "true"
keywordUpper = "TRUE"
peeking = PEEKED_TRUE
}
'f'.code.toByte(), 'F'.code.toByte() -> {
keyword = "false"
keywordUpper = "FALSE"
peeking = PEEKED_FALSE
}
'n'.code.toByte(), 'N'.code.toByte() -> {
keyword = "null"
keywordUpper = "NULL"
peeking = PEEKED_NULL
}
else -> return PEEKED_NONE
}
// Confirm that chars [1..length) match the keyword.
val length = keyword.length
for (i in 1 until length) {
if (!source.request(i + 1.toLong())) {
return PEEKED_NONE
}
val c = buffer[i.toLong()]
if (c != keyword[i].code.toByte() && c != keywordUpper[i].code.toByte()) {
return PEEKED_NONE
}
}
if (source.request(length + 1.toLong()) && isLiteral(buffer[length.toLong()].toInt().toChar())) {
return PEEKED_NONE // Don't match trues, falsey or nullsoft!
}
// We've found the keyword followed either by EOF or by a non-literal character.
buffer.skip(length.toLong())
return peeking.also { peeked = it }
}
private fun peekNumber(): Int {
var value: Long = 0 // Negative to accommodate Long.MIN_VALUE more easily.
var negative = false
var fitsInLong = true
var last = NUMBER_CHAR_NONE
var i = 0
loop@ while (source.request(i + 1.toLong())) {
val c = buffer[i.toLong()]
when (c.toInt().toChar()) {
'-' -> {
when (last) {
NUMBER_CHAR_NONE -> {
negative = true
last = NUMBER_CHAR_SIGN
}
NUMBER_CHAR_EXP_E -> {
last = NUMBER_CHAR_EXP_SIGN
}
else -> {
return PEEKED_NONE
}
}
}
'+' -> {
if (last == NUMBER_CHAR_EXP_E) {
last = NUMBER_CHAR_EXP_SIGN
} else {
return PEEKED_NONE
}
}
'e', 'E' -> {
if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {
last = NUMBER_CHAR_EXP_E
} else {
return PEEKED_NONE
}
}
'.' -> {
if (last == NUMBER_CHAR_DIGIT) {
last = NUMBER_CHAR_DECIMAL
} else {
return PEEKED_NONE
}
}
else -> {
if (c < '0'.code.toByte() || c > '9'.code.toByte()) {
if (!isLiteral(c.toInt().toChar())) {
break@loop
} else {
return PEEKED_NONE
}
}
when (last) {
NUMBER_CHAR_SIGN, NUMBER_CHAR_NONE -> {
value = -(c - '0'.code.toByte()).toLong()
last = NUMBER_CHAR_DIGIT
}
NUMBER_CHAR_DIGIT -> {
if (value == 0L) {
return PEEKED_NONE // Leading '0' prefix is not allowed (since it could be octal).
}
val newValue = value * 10 - (c - '0'.code.toByte())
fitsInLong = fitsInLong and (value > MIN_INCOMPLETE_INTEGER) || value == MIN_INCOMPLETE_INTEGER && newValue < value
value = newValue
}
NUMBER_CHAR_DECIMAL -> {
last = NUMBER_CHAR_FRACTION_DIGIT
}
NUMBER_CHAR_EXP_E, NUMBER_CHAR_EXP_SIGN -> {
last = NUMBER_CHAR_EXP_DIGIT
}
}
}
}
i++
}
// We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
return if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
peekedLong = if (negative) value else -value
buffer.skip(i.toLong())
PEEKED_LONG.also { peeked = it }
} else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) {
peekedNumberLength = i
PEEKED_NUMBER.also { peeked = it }
} else {
PEEKED_NONE
}
}
private fun isLiteral(c: Char): Boolean {
return when (c) {
'/', '\\', ';', '#', '=' -> {
checkLenient() // fall-through
false
}
'{', '}', '[', ']', ':', ',', ' ', '\t', '\r', '\n' -> false
else -> true
}
}
override fun nextName(): String {
val result = when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_UNQUOTED_NAME -> nextUnquotedValue()
PEEKED_DOUBLE_QUOTED_NAME -> nextQuotedValue(DOUBLE_QUOTE_OR_SLASH)
PEEKED_SINGLE_QUOTED_NAME -> nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
else -> throw JsonDataException("Expected a name but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_NONE
pathNames[stackSize - 1] = result
return result
}
override fun nextString(): String? {
val result = when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_UNQUOTED -> nextUnquotedValue()
PEEKED_DOUBLE_QUOTED -> nextQuotedValue(DOUBLE_QUOTE_OR_SLASH)
PEEKED_SINGLE_QUOTED -> nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
PEEKED_BUFFERED -> peekedString?.also { peekedString = null }
PEEKED_LONG -> peekedLong.toString()
PEEKED_NUMBER -> buffer.readUtf8(peekedNumberLength.toLong())
else -> throw JsonDataException("Expected a string but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun nextBoolean(): Boolean {
return when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_TRUE -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
true
}
PEEKED_FALSE -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
false
}
else -> throw JsonDataException("Expected a boolean but was ${peek()} at path ${getPath()}")
}
}
override fun nextNull(): Nothing? {
return when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_NULL -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
null
}
else -> throw JsonDataException("Expected null but was ${peek()} at path ${getPath()}")
}
}
override fun nextDouble(): Double {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
when {
p == PEEKED_LONG -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return peekedLong.toDouble()
}
p == PEEKED_NUMBER -> {
peekedString = buffer.readUtf8(peekedNumberLength.toLong())
}
p == PEEKED_DOUBLE_QUOTED -> {
peekedString = nextQuotedValue(DOUBLE_QUOTE_OR_SLASH)
}
p == PEEKED_SINGLE_QUOTED -> {
peekedString = nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
}
p == PEEKED_UNQUOTED -> {
peekedString = nextUnquotedValue()
}
p != PEEKED_BUFFERED -> throw JsonDataException("Expected a double but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_BUFFERED
val result = try {
peekedString!!.toDouble()
} catch (e: NumberFormatException) {
throw JsonDataException("Expected a double but was $peekedString at path ${getPath()}")
}
if (!lenient && (result.isNaN() || result.isInfinite())) {
throw JsonEncodingException("JSON forbids NaN and infinities: $result at path ${getPath()}")
}
peekedString = null
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun nextLong(): Long {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
when {
p == PEEKED_LONG -> {
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return peekedLong
}
p == PEEKED_NUMBER -> {
peekedString = buffer.readUtf8(peekedNumberLength.toLong())
}
p == PEEKED_DOUBLE_QUOTED || p == PEEKED_SINGLE_QUOTED -> {
peekedString = if (p == PEEKED_DOUBLE_QUOTED) nextQuotedValue(DOUBLE_QUOTE_OR_SLASH) else nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
try {
val result = peekedString!!.toLong()
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
} catch (ignored: NumberFormatException) { // Fall back to parse as a double below.
}
}
p != PEEKED_BUFFERED -> throw JsonDataException("Expected a long but was ${peek()} at path ${getPath()}")
}
peeked = PEEKED_BUFFERED
val asDouble: Double = try {
peekedString!!.toDouble()
} catch (e: NumberFormatException) {
throw JsonDataException("Expected a long but was $peekedString at path ${getPath()}")
}
val result = asDouble.toLong()
if (result.toDouble() != asDouble) { // Make sure no precision was lost casting to 'long'.
throw JsonDataException("Expected a long but was $peekedString at path ${getPath()}")
}
peekedString = null
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun nextNumber(): JsonNumber {
return JsonNumber(nextString()!!)
}
/**
* Returns the string up to but not including `quote`, unescaping any character escape
* sequences encountered along the way. The opening quote should have already been read. This
* consumes the closing quote, but does not include it in the returned string.
*
* @throws okio.IOException if any unicode escape sequences are malformed.
*/
private fun nextQuotedValue(runTerminator: ByteString): String {
var builder: StringBuilder? = null
while (true) {
val index = source.indexOfElement(runTerminator)
if (index == -1L) throw syntaxError("Unterminated string")
// If we've got an escape character, we're going to need a string builder.
if (buffer[index] == '\\'.code.toByte()) {
if (builder == null) builder = StringBuilder()
builder.append(buffer.readUtf8(index))
buffer.readByte() // '\'
builder.append(readEscapeCharacter())
continue
}
// If it isn't the escape character, it's the quote. Return the string.
return if (builder == null) {
val result = buffer.readUtf8(index)
buffer.readByte() // Consume the quote character.
result
} else {
builder.append(buffer.readUtf8(index))
buffer.readByte() // Consume the quote character.
builder.toString()
}
}
}
/** Returns an unquoted value as a string. */
private fun nextUnquotedValue(): String {
val i = source.indexOfElement(UNQUOTED_STRING_TERMINALS)
return if (i != -1L) buffer.readUtf8(i) else buffer.readUtf8()
}
private fun skipQuotedValue(runTerminator: ByteString) {
while (true) {
val index = source.indexOfElement(runTerminator)
if (index == -1L) throw syntaxError("Unterminated string")
if (buffer[index] == '\\'.code.toByte()) {
buffer.skip(index + 1)
readEscapeCharacter()
} else {
buffer.skip(index + 1)
return
}
}
}
private fun skipUnquotedValue() {
val i = source.indexOfElement(UNQUOTED_STRING_TERMINALS)
buffer.skip(if (i != -1L) i else buffer.size)
}
override fun nextInt(): Int {
val p = peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()
when {
p == PEEKED_LONG -> {
val result = peekedLong.toInt()
if (peekedLong != result.toLong()) { // Make sure no precision was lost casting to 'int'.
throw JsonDataException("Expected an int but was " + peekedLong
+ " at path " + getPath())
}
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
p == PEEKED_NUMBER -> {
peekedString = buffer.readUtf8(peekedNumberLength.toLong())
}
p == PEEKED_DOUBLE_QUOTED || p == PEEKED_SINGLE_QUOTED -> {
peekedString = if (p == PEEKED_DOUBLE_QUOTED) nextQuotedValue(DOUBLE_QUOTE_OR_SLASH) else nextQuotedValue(SINGLE_QUOTE_OR_SLASH)
try {
val result = peekedString!!.toInt()
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
} catch (ignored: NumberFormatException) { // Fall back to parse as a double below.
}
}
p != PEEKED_BUFFERED -> {
throw JsonDataException("Expected an int but was ${peek()} at path ${getPath()}")
}
}
peeked = PEEKED_BUFFERED
val asDouble: Double = try {
peekedString!!.toDouble()
} catch (e: NumberFormatException) {
throw JsonDataException("Expected an int but was $peekedString at path ${getPath()}")
}
val result = asDouble.toInt()
if (result.toDouble() != asDouble) { // Make sure no precision was lost casting to 'int'.
throw JsonDataException("Expected an int but was $peekedString at path ${getPath()}")
}
peekedString = null
peeked = PEEKED_NONE
pathIndices[stackSize - 1]++
return result
}
override fun close() {
peeked = PEEKED_NONE
stack[0] = JsonScope.CLOSED
stackSize = 1
buffer.clear()
source.close()
}
override fun skipValue() {
var count = 0
do {
when (peeked.takeUnless { it == PEEKED_NONE } ?: doPeek()) {
PEEKED_BEGIN_ARRAY -> {
push(JsonScope.EMPTY_ARRAY)
count++
}
PEEKED_BEGIN_OBJECT -> {
push(JsonScope.EMPTY_OBJECT)
count++
}
PEEKED_END_ARRAY -> {
stackSize--
count--
}
PEEKED_END_OBJECT -> {
stackSize--
count--
}
PEEKED_UNQUOTED_NAME, PEEKED_UNQUOTED -> {
skipUnquotedValue()
}
PEEKED_DOUBLE_QUOTED, PEEKED_DOUBLE_QUOTED_NAME -> {
skipQuotedValue(DOUBLE_QUOTE_OR_SLASH)
}
PEEKED_SINGLE_QUOTED, PEEKED_SINGLE_QUOTED_NAME -> {
skipQuotedValue(SINGLE_QUOTE_OR_SLASH)
}
PEEKED_NUMBER -> {
buffer.skip(peekedNumberLength.toLong())
}
}
peeked = PEEKED_NONE
} while (count != 0)
pathIndices[stackSize - 1]++
pathNames[stackSize - 1] = "null"
}
override fun selectName(names: List<String>): Int {
if (names.isEmpty()) {
return -1
}
while (hasNext()) {
val name = nextName()
val expectedIndex = indexStack[indexStackSize - 1]
if (names[expectedIndex] == name) {
return expectedIndex.also {
indexStack[indexStackSize - 1] = expectedIndex + 1
if (indexStack[indexStackSize - 1] == names.size) {
indexStack[indexStackSize - 1] = 0
}
}
} else {
// guess failed, fallback to full search
var index = expectedIndex
while (true) {
index++
if (index == names.size) {
index = 0
}
if (index == expectedIndex) {
break
}
if (names[index] == name) {
return index.also {
indexStack[indexStackSize - 1] = index + 1
if (indexStack[indexStackSize - 1] == names.size) {
indexStack[indexStackSize - 1] = 0
}
}
}
}
skipValue()
}
}
return -1
}
private fun push(newTop: Int) {
if (stackSize == stack.size) throw JsonDataException("Nesting too deep at " + getPath())
stack[stackSize++] = newTop
}
/**
* Returns the next character in the stream that is neither whitespace nor a part of a comment.
* When this returns, the returned character is always at `buffer[pos-1]`; this means the caller can always push back the returned
* character by decrementing `pos`.
*/
private fun nextNonWhitespace(throwOnEof: Boolean): Int {
/**
* This code uses ugly local variables 'p' and 'l' representing the 'pos' and 'limit' fields respectively. Using locals rather than
* fields saves a few field reads for each whitespace character in a pretty-printed document, resulting in a 5% speedup.
* We need to flush 'p' to its field before any (potentially indirect) call to fillBuffer() and reread both 'p' and 'l' after any
* (potentially indirect) call to the same method.
*/
var p = 0
loop@ while (source.request(p + 1.toLong())) {
val c = buffer[p++.toLong()].toInt()
if (c == '\n'.code || c == ' '.code || c == '\r'.code || c == '\t'.code) {
continue
}
buffer.skip(p - 1.toLong())
if (c == '/'.code) {
if (!source.request(2)) {
return c
}
checkLenient()
val peek = buffer[1]
return when (peek.toInt().toChar()) {
'*' -> {
// skip a /* c-style comment */
buffer.readByte() // '/'
buffer.readByte() // '*'
if (!skipTo("*/")) {
throw syntaxError("Unterminated comment")
}
buffer.readByte() // '*'
buffer.readByte() // '/'
p = 0
continue@loop
}
'/' -> {
// skip a // end-of-line comment
buffer.readByte() // '/'
buffer.readByte() // '/'
skipToEndOfLine()
p = 0
continue@loop
}
else -> c
}
} else if (c == '#'.code) { // Skip a # hash end-of-line comment. The JSON RFC doesn't specify this behaviour, but it's
// required to parse existing documents.
checkLenient()
skipToEndOfLine()
p = 0
} else {
return c
}
}
return if (throwOnEof) {
throw EOFException("End of input")
} else {
-1
}
}
private fun checkLenient() {
if (!lenient) throw syntaxError("Use JsonReader.setLenient(true) to accept malformed JSON")
}
/**
* Advances the position until after the next newline character. If the line
* is terminated by "\r\n", the '\n' must be consumed as whitespace by the
* caller.
*/
private fun skipToEndOfLine() {
val index = source.indexOfElement(LINEFEED_OR_CARRIAGE_RETURN)
buffer.skip(if (index != -1L) index + 1 else buffer.size)
}
/**
* @param toFind a string to search for. Must not contain a newline.
*/
private fun skipTo(toFind: String): Boolean {
outer@ while (source.request(toFind.length.toLong())) {
for (c in toFind.indices) {
if (buffer[c.toLong()] != toFind[c].code.toByte()) {
buffer.readByte()
continue@outer
}
}
return true
}
return false
}
private fun getPath(): String = JsonScope.getPath(stackSize, stack, pathNames, pathIndices)
/**
* Unescapes the character identified by the character or characters that immediately follow a backslash. The backslash '\' should have
* already been read. This supports both unicode escapes "u000A" and two-character escapes "\n".
*
* @throws okio.IOException if any unicode escape sequences are malformed.
*/
private fun readEscapeCharacter(): Char {
if (!source.request(1)) throw syntaxError("Unterminated escape sequence")
return when (val escaped = buffer.readByte().toInt().toChar()) {
'u' -> {
if (!source.request(4)) {
throw EOFException("Unterminated escape sequence at path " + getPath())
}
// Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16);
var result = 0.toChar()
var i = 0
val end = i + 4
while (i < end) {
val c = buffer[i.toLong()]
result = (result.code shl 4).toChar()
result += when {
c >= '0'.code.toByte() && c <= '9'.code.toByte() -> (c - '0'.code.toByte())
c >= 'a'.code.toByte() && c <= 'f'.code.toByte() -> (c - 'a'.code.toByte() + 10)
c >= 'A'.code.toByte() && c <= 'F'.code.toByte() -> (c - 'A'.code.toByte() + 10)
else -> throw syntaxError("\\u" + buffer.readUtf8(4))
}
i++
}
buffer.skip(4)
result
}
't' -> '\t'
'b' -> '\b'
'n' -> '\n'
'r' -> '\r'
'f' -> '\u000C'
'\n', '\'', '"', '\\', '/' -> escaped
else -> {
if (!lenient) throw syntaxError("Invalid escape sequence: \\$escaped")
escaped
}
}
}
override fun rewind() {
error("BufferedSourceJsonReader cannot rewind.")
}
/**
* Returns a new exception with the given message and a context snippet with this reader's content.
*/
private fun syntaxError(message: String): JsonEncodingException =
JsonEncodingException(message + " at path " + getPath())
companion object {
private const val MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10
private val SINGLE_QUOTE_OR_SLASH = "'\\".encodeUtf8()
private val DOUBLE_QUOTE_OR_SLASH = "\"\\".encodeUtf8()
private val UNQUOTED_STRING_TERMINALS = "{}[]:, \n\t\r/\\;#=".encodeUtf8()
private val LINEFEED_OR_CARRIAGE_RETURN = "\n\r".encodeUtf8()
private const val PEEKED_NONE = 0
private const val PEEKED_BEGIN_OBJECT = 1
private const val PEEKED_END_OBJECT = 2
private const val PEEKED_BEGIN_ARRAY = 3
private const val PEEKED_END_ARRAY = 4
private const val PEEKED_TRUE = 5
private const val PEEKED_FALSE = 6
private const val PEEKED_NULL = 7
private const val PEEKED_SINGLE_QUOTED = 8
private const val PEEKED_DOUBLE_QUOTED = 9
private const val PEEKED_UNQUOTED = 10
/** When this is returned, the string value is stored in peekedString. */
private const val PEEKED_BUFFERED = 11
private const val PEEKED_SINGLE_QUOTED_NAME = 12
private const val PEEKED_DOUBLE_QUOTED_NAME = 13
private const val PEEKED_UNQUOTED_NAME = 14
/** When this is returned, the integer value is stored in peekedLong. */
private const val PEEKED_LONG = 15
private const val PEEKED_NUMBER = 16
private const val PEEKED_EOF = 17
/* State machine when parsing numbers */
private const val NUMBER_CHAR_NONE = 0
private const val NUMBER_CHAR_SIGN = 1
private const val NUMBER_CHAR_DIGIT = 2
private const val NUMBER_CHAR_DECIMAL = 3
private const val NUMBER_CHAR_FRACTION_DIGIT = 4
private const val NUMBER_CHAR_EXP_E = 5
private const val NUMBER_CHAR_EXP_SIGN = 6
private const val NUMBER_CHAR_EXP_DIGIT = 7
internal const val MAX_STACK_SIZE = 256
}
}
| apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/json/BufferedSourceJsonReader.kt | 3600200071 |
package jp.hitting.firebasesampleforandroid
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
class ExampleUnitTest {
@Test
@Throws(Exception::class)
fun addition_isCorrect() {
assertEquals(4, (2 + 2).toLong())
}
} | FirebaseSampleForAndroid/app/src/test/kotlin/jp/hitting/firebasesampleforandroid/ExampleUnitTest.kt | 1035572353 |
// 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.workspaceModel.codegen
import com.intellij.openapi.util.registry.Registry
import com.intellij.workspaceModel.codegen.classes.*
import com.intellij.workspaceModel.codegen.deft.meta.ObjClass
import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty
import com.intellij.workspaceModel.codegen.deft.meta.OwnProperty
import com.intellij.workspaceModel.codegen.deft.meta.ValueType
import com.intellij.workspaceModel.codegen.engine.GenerationProblem
import com.intellij.workspaceModel.codegen.engine.ProblemLocation
import com.intellij.workspaceModel.codegen.engine.impl.ProblemReporter
import com.intellij.workspaceModel.codegen.fields.javaMutableType
import com.intellij.workspaceModel.codegen.fields.javaType
import com.intellij.workspaceModel.codegen.fields.wsCode
import com.intellij.workspaceModel.codegen.utils.fqn
import com.intellij.workspaceModel.codegen.utils.fqn7
import com.intellij.workspaceModel.codegen.utils.lines
import com.intellij.workspaceModel.codegen.writer.*
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
val SKIPPED_TYPES: Set<String> = setOfNotNull(WorkspaceEntity::class.simpleName,
WorkspaceEntity.Builder::class.simpleName,
WorkspaceEntityWithSymbolicId::class.simpleName)
fun ObjClass<*>.generateBuilderCode(reporter: ProblemReporter): String = lines {
checkSuperTypes(this@generateBuilderCode, reporter)
line("@${GeneratedCodeApiVersion::class.fqn}(${CodeGeneratorVersions.API_VERSION})")
val (typeParameter, typeDeclaration) =
if (openness.extendable) "T" to "<T: $javaFullName>" else javaFullName to ""
val superBuilders = superTypes.filterIsInstance<ObjClass<*>>().filter { !it.isStandardInterface }.joinToString {
", ${it.name}.Builder<$typeParameter>"
}
val header = "interface Builder$typeDeclaration: $javaFullName$superBuilders, ${WorkspaceEntity.Builder::class.fqn}<$typeParameter>, ${ObjBuilder::class.fqn}<$typeParameter>"
section(header) {
list(allFields.noSymbolicId()) {
checkProperty(this, reporter)
wsBuilderApi
}
}
}
fun checkSuperTypes(objClass: ObjClass<*>, reporter: ProblemReporter) {
objClass.superTypes.filterIsInstance<ObjClass<*>>().forEach {superClass ->
if (!superClass.openness.extendable) {
reporter.reportProblem(GenerationProblem("Class '${superClass.name}' cannot be extended", GenerationProblem.Level.ERROR,
ProblemLocation.Class(objClass)))
}
else if (!superClass.openness.openHierarchy && superClass.module != objClass.module) {
reporter.reportProblem(GenerationProblem("Class '${superClass.name}' cannot be extended from other modules",
GenerationProblem.Level.ERROR, ProblemLocation.Class(objClass)))
}
}
}
private fun checkProperty(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) {
checkInheritance(objProperty, reporter)
checkPropertyType(objProperty, reporter)
}
fun checkInheritance(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) {
objProperty.receiver.allSuperClasses.mapNotNull { it.fieldsByName[objProperty.name] }.forEach { overriddenField ->
if (!overriddenField.open) {
reporter.reportProblem(
GenerationProblem("Property '${overriddenField.receiver.name}::${overriddenField.name}' cannot be overriden",
GenerationProblem.Level.ERROR, ProblemLocation.Property(objProperty)))
}
}
}
private fun checkPropertyType(objProperty: ObjProperty<*, *>, reporter: ProblemReporter) {
val errorMessage = when (val type = objProperty.valueType) {
is ValueType.ObjRef<*> -> {
if (type.child) "Child references should always be nullable"
else null
}
else -> checkType(type)
}
if (errorMessage != null) {
reporter.reportProblem(GenerationProblem(errorMessage, GenerationProblem.Level.ERROR, ProblemLocation.Property(objProperty)))
}
}
private fun checkType(type: ValueType<*>): String? = when (type) {
is ValueType.Optional -> when (type.type) {
is ValueType.List<*> -> "Optional lists aren't supported"
is ValueType.Set<*> -> "Optional sets aren't supported"
else -> checkType(type.type)
}
is ValueType.Set<*> -> {
if (type.elementType.isRefType()) {
"Set of references isn't supported"
}
else checkType(type.elementType)
}
is ValueType.Map<*, *> -> {
checkType(type.keyType) ?: checkType(type.valueType)
}
is ValueType.Blob<*> -> {
if (!keepUnknownFields && type.javaClassName !in knownInterfaces) {
"Unsupported type '${type.javaClassName}'"
}
else null
}
else -> null
}
private val keepUnknownFields: Boolean
get() = Registry.`is`("workspace.model.generator.keep.unknown.fields")
private val knownInterfaces = setOf(
VirtualFileUrl::class.qualifiedName!!,
EntitySource::class.qualifiedName!!,
SymbolicEntityId::class.qualifiedName!!,
)
fun ObjClass<*>.generateCompanionObject(): String = lines {
val builderGeneric = if (openness.extendable) "<$javaFullName>" else ""
val companionObjectHeader = buildString {
append("companion object: ${Type::class.fqn}<$javaFullName, Builder$builderGeneric>(")
val base = superTypes.filterIsInstance<ObjClass<*>>().firstOrNull()
if (base != null && base.name !in SKIPPED_TYPES)
append(base.javaFullName)
append(")")
}
val mandatoryFields = allFields.mandatoryFields()
if (mandatoryFields.isNotEmpty()) {
val fields = mandatoryFields.joinToString { "${it.name}: ${it.valueType.javaType}" }
section(companionObjectHeader) {
line("@${JvmOverloads::class.fqn}")
line("@${JvmStatic::class.fqn}")
line("@${JvmName::class.fqn}(\"create\")")
section("operator fun invoke($fields, init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") {
line("val builder = builder()")
list(mandatoryFields) {
if (this.valueType is ValueType.Set<*> && !this.valueType.isRefType()) {
"builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceSet)}()"
} else if (this.valueType is ValueType.List<*> && !this.valueType.isRefType()) {
"builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceList)}()"
} else {
"builder.$name = $name"
}
}
line("init?.invoke(builder)")
line("return builder")
}
}
}
else {
section(companionObjectHeader) {
line("@${JvmOverloads::class.fqn}")
line("@${JvmStatic::class.fqn}")
line("@${JvmName::class.fqn}(\"create\")")
section("operator fun invoke(init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") {
line("val builder = builder()")
line("init?.invoke(builder)")
line("return builder")
}
}
}
}
fun List<OwnProperty<*, *>>.mandatoryFields(): List<ObjProperty<*, *>> {
var fields = this.noRefs().noOptional().noSymbolicId().noDefaultValue()
if (fields.isNotEmpty()) {
fields = fields.noEntitySource() + fields.single { it.name == "entitySource" }
}
return fields
}
fun ObjClass<*>.generateExtensionCode(): String? {
val fields = module.extensions.filter { it.receiver == this || it.receiver.module != module && it.valueType.isRefType() && it.valueType.getRefType().target == this }
if (openness.extendable && fields.isEmpty()) return null
return lines {
if (!openness.extendable) {
line("fun ${MutableEntityStorage::class.fqn}.modifyEntity(entity: $name, modification: $name.Builder.() -> Unit) = modifyEntity($name.Builder::class.java, entity, modification)")
}
fields.sortedWith(compareBy({ it.receiver.name }, { it.name })).forEach { line(it.wsCode) }
}
}
val ObjProperty<*, *>.wsBuilderApi: String
get() {
val returnType = if (valueType is ValueType.Collection<*, *> && !valueType.isRefType()) valueType.javaMutableType else valueType.javaType
return "override var $javaName: $returnType"
}
| platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/apiCode.kt | 3311823929 |
package de.theunknownxy.mcdocs.gui.document
import de.theunknownxy.mcdocs.docs.DocumentationBackend
import de.theunknownxy.mcdocs.docs.DocumentationNodeRef
trait Action {
fun run(backend: DocumentationBackend)
}
class NavigateAction(val ref: DocumentationNodeRef) : Action {
override fun run(backend: DocumentationBackend) {
backend.navigate(ref)
}
}
| src/main/kotlin/de/theunknownxy/mcdocs/gui/document/Action.kt | 2846295949 |
/*
* Copyright 2000-2017 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 com.intellij.testGuiFramework.util
enum class Key {
ENTER,
BACK_SPACE,
TAB,
CANCEL,
CLEAR,
PAUSE,
CAPS_LOCK,
ESCAPE,
SPACE,
PAGE_UP,
PAGE_DOWN,
END,
HOME,
LEFT,
UP,
RIGHT,
DOWN,
COMMA,
MINUS,
PERIOD,
SLASH,
d0,
d1,
d2,
d3,
d4,
d5,
d6,
d7,
d8,
d9,
SEMICOLON,
EQUALS,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
OPEN_BRACKET,
BACK_SLASH,
CLOSE_BRACKET,
NUMPAD0,
NUMPAD1,
NUMPAD2,
NUMPAD3,
NUMPAD4,
NUMPAD5,
NUMPAD6,
NUMPAD7,
NUMPAD8,
NUMPAD9,
MULTIPLY,
ADD,
SEPARATER,
SEPARATOR,
SUBTRACT,
DECIMAL,
DIVIDE,
DELETE,
NUM_LOCK,
SCROLL_LOCK,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
PRINTSCREEN,
INSERT,
HELP,
BACK_QUOTE,
QUOTE,
KP_UP,
KP_DOWN,
KP_LEFT,
KP_RIGHT,
DEAD_GRAVE,
DEAD_ACUTE,
DEAD_CIRCUMFLEX,
DEAD_TILDE,
DEAD_MACRON,
DEAD_BREVE,
DEAD_ABOVEDOT,
DEAD_DIAERESIS,
DEAD_ABOVERING,
DEAD_DOUBLEACUTE,
DEAD_CARON,
DEAD_CEDILLA,
DEAD_OGONEK,
DEAD_IOTA,
DEAD_VOICED,
DEAD_SEMIVOICED,
AMPERSAND,
ASTERISK,
QUOTEDBL,
LESS,
GREATER,
BRACELEFT,
BRACERIGHT,
AT,
COLON,
CIRCUMFLEX,
DOLLAR,
EURO_SIGN,
EXCLAMATION_MARK,
INVERTED_EXCLAMATION,
LEFT_PARENTHESIS,
NUMBER_SIGN,
PLUS,
RIGHT_PARENTHESIS,
UNDERSCORE,
WINDOWS,
CONTEXT_MENU,
FINAL,
CONVERT,
NONCONVERT,
ACCEPT,
MODECHANGE,
KANA,
KANJI,
ALPHANUMERIC,
KATAKANA,
HIRAGANA,
FULL_WIDTH,
HALF_WIDTH,
ROMAN_CHARACTERS,
ALL_CANDIDATES,
PREVIOUS_CANDIDATE,
CODE_INPUT,
JAPANESE_KATAKANA,
JAPANESE_HIRAGANA,
JAPANESE_ROMAN,
KANA_LOCK,
INPUT_METHOD,
CUT,
COPY,
PASTE,
UNDO,
AGAIN,
FIND,
PROPS,
STOP,
COMPOSE,
BEGIN,
UNDEFINED
}
enum class Modifier {
SHIFT,
CONTROL,
ALT,
META,
ALT_GR
}
class Shortcut(var modifiers: HashSet<Modifier> = HashSet(), var key: Key? = null) {
fun getKeystroke(): String {
val mods = modifiers.toList().sorted().joinToString(" ") { it.name.toLowerCase() }
if (key == null) return ""
val cleanKeyName = (if (key!!.name.startsWith("d")) key!!.name.substring(1) else key!!.name).toLowerCase()
return if (mods.isNotEmpty()) "$mods $cleanKeyName" else cleanKeyName
}
override fun toString(): String = getKeystroke()
}
operator fun Modifier.plus(modifier: Modifier): Shortcut {
return Shortcut(hashSetOf(this, modifier), null)
}
operator fun Modifier.plus(key: Key): Shortcut {
return Shortcut(hashSetOf(this), key)
}
operator fun Shortcut.plus(modifier: Modifier): Shortcut {
return Shortcut(hashSetOf(*this.modifiers.toTypedArray(), modifier), null)
}
operator fun Shortcut.plus(key: Key): Shortcut {
if (this.key != null) throw Exception("Unable to merge shortcut with key ${this.key!!.name} and ${key.name}")
return Shortcut(this.modifiers, key)
}
operator fun Modifier.plus(shortcut: Shortcut): Shortcut {
val unionOfModifier = hashSetOf<Modifier>(this)
unionOfModifier.addAll(shortcut.modifiers)
return Shortcut(unionOfModifier, shortcut.key)
}
operator fun Shortcut.plus(shortcut: Shortcut): Shortcut {
if (this.key != null && shortcut.key != null) throw Exception(
"Unable to merge shortcut with key ${this.key!!.name} and ${shortcut.key!!.name}")
val unionOfModifier = hashSetOf<Modifier>()
unionOfModifier.addAll(this.modifiers)
unionOfModifier.addAll(shortcut.modifiers)
val newKey = if (this.key != null) this.key else shortcut.key
return Shortcut(unionOfModifier, newKey)
}
fun resolveKey(inputString: String): Key {
return if (Regex("\\d]").matches(inputString)) Key.valueOf("d$inputString")
else Key.valueOf(inputString)
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/util/Keys.kt | 915000900 |
package wenhui.com.shimmerimageview
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("wenhui.com.shimmerimageview", appContext.packageName)
}
}
| example/src/androidTest/java/wenhui/com/shimmerimageview/ExampleInstrumentedTest.kt | 426995025 |
package net.kivitro.kittycat.presenter
import com.mikepenz.aboutlibraries.Libs
import com.mikepenz.aboutlibraries.LibsBuilder
import net.kivitro.kittycat.R
import net.kivitro.kittycat.view.SettingsView
import timber.log.Timber
/**
* Created by Max on 04.08.2016.
*/
class SettingsPresenter : Presenter<SettingsView>() {
fun onAboutClicked() {
Timber.d("onAboutClicked")
view?.let {
LibsBuilder()
.withActivityTitle(it.activity.getString(R.string.title_activity_about))
.withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
.start(it.activity)
}
}
} | app/src/main/kotlin/net/kivitro/kittycat/presenter/SettingsPresenter.kt | 2481162415 |
/*
* Copyright (C) 2019 Veli Tasalı
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.activity
import android.os.Bundle
import android.view.MenuItem
import dagger.hilt.android.AndroidEntryPoint
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.app.Activity
@AndroidEntryPoint
class SharingActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sharing)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp)
navController(R.id.nav_host_fragment).addOnDestinationChangedListener { _, destination, _ ->
title = destination.label
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
return true
}
return super.onOptionsItemSelected(item)
}
}
| app/src/main/java/org/monora/uprotocol/client/android/activity/SharingActivity.kt | 365126476 |
/*
* Copyright 2015 Yann Le Moigne
*
* 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 fr.javatic.reactkt.core.utils
object KeyCode {
val ENTER = 13;
val ESCAPE = 27;
} | subprojects/core/src/main/kotlin/fr/javatic/reactkt/core/utils/KeyCode.kt | 3563688475 |
@file:JvmName("InitU")
package hope.base.utils
import android.app.Application
import hope.base.AppConstant
import hope.base.log.ZLog
import hope.base.ui.widget.fresco.FrescoHelper
fun init(app: Application, debug: Boolean) {
AppConstant.init(app)
ZLog.init(debug)
FrescoHelper.init(app)
DateTimeUtils.init(app)
}
| base/src/main/java/hope/base/utils/InitU.kt | 3776899706 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.flow
import benchmarks.flow.scrabble.flow
import io.reactivex.*
import io.reactivex.functions.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.Callable
@Warmup(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 7, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
open class NumbersBenchmark {
companion object {
private const val primes = 100
private const val natural = 1000L
}
private fun numbers(limit: Long = Long.MAX_VALUE) = flow {
for (i in 2L..limit) emit(i)
}
private fun primesFlow(): Flow<Long> = flow {
var source = numbers()
while (true) {
val next = source.take(1).single()
emit(next)
source = source.filter { it % next != 0L }
}
}
private fun rxNumbers() =
Flowable.generate(Callable { 1L }, BiFunction<Long, Emitter<Long>, Long> { state, emitter ->
val newState = state + 1
emitter.onNext(newState)
newState
})
private fun generateRxPrimes(): Flowable<Long> = Flowable.generate(Callable { rxNumbers() },
BiFunction<Flowable<Long>, Emitter<Long>, Flowable<Long>> { state, emitter ->
// Not the most fair comparison, but here we go
val prime = state.firstElement().blockingGet()
emitter.onNext(prime)
state.filter { it % prime != 0L }
})
@Benchmark
fun primes() = runBlocking {
primesFlow().take(primes).count()
}
@Benchmark
fun primesRx() = generateRxPrimes().take(primes.toLong()).count().blockingGet()
@Benchmark
fun zip() = runBlocking {
val numbers = numbers(natural)
val first = numbers
.filter { it % 2L != 0L }
.map { it * it }
val second = numbers
.filter { it % 2L == 0L }
.map { it * it }
first.zip(second) { v1, v2 -> v1 + v2 }.filter { it % 3 == 0L }.count()
}
@Benchmark
fun zipRx() {
val numbers = rxNumbers().take(natural)
val first = numbers
.filter { it % 2L != 0L }
.map { it * it }
val second = numbers
.filter { it % 2L == 0L }
.map { it * it }
first.zipWith(second, { v1, v2 -> v1 + v2 }).filter { it % 3 == 0L }.count()
.blockingGet()
}
@Benchmark
fun transformations(): Int = runBlocking {
numbers(natural)
.filter { it % 2L != 0L }
.map { it * it }
.filter { (it + 1) % 3 == 0L }.count()
}
@Benchmark
fun transformationsRx(): Long {
return rxNumbers().take(natural)
.filter { it % 2L != 0L }
.map { it * it }
.filter { (it + 1) % 3 == 0L }.count()
.blockingGet()
}
}
| benchmarks/src/jmh/kotlin/benchmarks/flow/NumbersBenchmark.kt | 355028944 |
package org.livingdoc.results.examples.decisiontables
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.livingdoc.results.Status
import java.lang.reflect.Method
internal class FieldResultBuilderTest {
private val checkMethod: Method = (FixtureClass::class.java).methods[0]
@Test
fun `test successful field result`() {
val result = FieldResult.Builder()
.withValue("a")
.withCheckMethod(this.checkMethod)
.withStatus(Status.Executed)
.build()
assertThat(result.value).isEqualTo("a")
assertThat(result.method).isEqualTo(this.checkMethod)
assertThat(result.status).isEqualTo(Status.Executed)
}
@Test
fun `test field result with missing value`() {
val builder = FieldResult.Builder()
.withCheckMethod(this.checkMethod)
.withStatus(Status.Executed)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test field result with missing status`() {
val builder = FieldResult.Builder()
.withValue("a")
.withCheckMethod(this.checkMethod)
assertThrows<IllegalStateException> {
builder.build()
}
}
@Test
fun `test field result with missing method`() {
val result = FieldResult.Builder()
.withValue("a")
.withStatus(Status.Executed)
.build()
assertThat(result.method).isEqualTo(null)
}
@Test
fun `test finalized builder`() {
val builder = FieldResult.Builder()
.withValue("a")
.withCheckMethod(this.checkMethod)
.withStatus(Status.Executed)
builder.build()
assertThrows<IllegalStateException> {
builder.withStatus(Status.Manual)
}
}
class FixtureClass {
fun fixtureMethod() {}
}
}
| livingdoc-results/src/test/kotlin/org/livingdoc/results/examples/decisiontables/FieldResultBuilderTest.kt | 400759705 |
package szewek.fl.kotlin
import net.minecraft.nbt.*
inline operator fun NBTTagCompound.get(s: String): NBTBase = getTag(s)
inline operator fun NBTTagCompound.set(s: String, tag: NBTBase) = setTag(s, tag)
inline operator fun NBTTagCompound.contains(s: String) = hasKey(s)
inline operator fun NBTTagList.plusAssign(tag: NBTBase) = appendTag(tag)
inline val NBTBase.asBoolean
get() = if (this is NBTPrimitive) this.byte != (0).toByte() else false
inline val NBTBase.asByte
get() = (this as? NBTPrimitive)?.byte ?: (0).toByte()
inline val NBTBase.asShort
get() = (this as? NBTPrimitive)?.short ?: (0).toShort()
inline val NBTBase.asInt
get() = (this as? NBTPrimitive)?.int ?: 0
inline val NBTBase.asLong
get() = (this as? NBTPrimitive)?.long ?: 0L
inline val NBTBase.asFloat
get() = (this as? NBTPrimitive)?.float ?: 0F
inline val NBTBase.asDouble
get() = (this as? NBTPrimitive)?.double ?: 0.0
inline val NBTBase.asString
get() = (this as? NBTTagString)?.string ?: ""
inline val NBTBase.asByteArray
get() = (this as? NBTTagByteArray)?.byteArray
inline val NBTBase.asIntArray
get() = (this as? NBTTagIntArray)?.intArray
inline val NBTBase.asCompound
get() = this as? NBTTagCompound
inline val NBTBase.asList
get() = this as? NBTTagList | src/main/java/szewek/fl/kotlin/NBTX.kt | 3489278375 |
package pl.brightinventions.patchy
import org.springframework.beans.BeanWrapperImpl
fun PatchyRequest.applyChangesTo(target: Any) {
val targetBean = BeanWrapperImpl(target)
declaredChanges.forEach { change ->
if (targetBean.isWritableProperty(change.key)) {
targetBean.setPropertyValue(change.key, targetBean.convertForProperty(change.value, change.key))
}
}
} | src/main/kotlin/pl/brightinventions/patchy/_ApplyChanges.kt | 8893834 |
// 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.ui.views
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.guessCurrentProject
import com.intellij.openapi.wm.impl.welcomeScreen.learnIde.HeightLimitedPane
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.IconUtil
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import icons.FeaturesTrainerIcons
import org.jetbrains.annotations.NotNull
import training.learn.CourseManager
import training.learn.LearnBundle
import training.learn.course.IftModule
import training.learn.course.Lesson
import training.learn.lesson.LessonManager
import training.ui.UISettings
import training.util.createBalloon
import training.util.learningProgressString
import training.util.rigid
import training.util.scaledRigid
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*
import javax.swing.border.EmptyBorder
private val HOVER_COLOR: Color get() = JBColor.namedColor("Plugins.hoverBackground", JBColor(0xEDF6FE, 0x464A4D))
class LearningItems : JPanel() {
var modules: List<IftModule> = emptyList()
private val expanded: MutableSet<IftModule> = mutableSetOf()
init {
name = "learningItems"
layout = BoxLayout(this, BoxLayout.Y_AXIS)
isOpaque = false
isFocusable = false
}
fun updateItems(showModule: IftModule? = null) {
if (showModule != null) expanded.add(showModule)
removeAll()
for (module in modules) {
if (module.lessons.isEmpty()) continue
add(createModuleItem(module))
if (expanded.contains(module)) {
for (lesson in module.lessons) {
add(createLessonItem(lesson))
}
}
}
revalidate()
repaint()
}
private fun createLessonItem(lesson: Lesson): JPanel {
val result = JPanel()
result.isOpaque = false
result.layout = BoxLayout(result, BoxLayout.X_AXIS)
result.alignmentX = LEFT_ALIGNMENT
result.border = EmptyBorder(JBUI.scale(7), JBUI.scale(7), JBUI.scale(6), JBUI.scale(7))
val checkmarkIconLabel = createLabelIcon(if (lesson.passed) FeaturesTrainerIcons.Img.GreenCheckmark else EmptyIcon.ICON_16)
result.add(createLabelIcon(EmptyIcon.ICON_16))
result.add(scaledRigid(UISettings.instance.expandAndModuleGap, 0))
result.add(checkmarkIconLabel)
val name = LinkLabel<Any>(lesson.name, null)
name.setListener(
{ _, _ ->
val project = guessCurrentProject(this)
val cantBeOpenedInDumb = DumbService.getInstance(project).isDumb && !lesson.properties.canStartInDumbMode
if (cantBeOpenedInDumb && !LessonManager.instance.lessonShouldBeOpenedCompleted(lesson)) {
val balloon = createBalloon(LearnBundle.message("indexing.message"))
balloon.showInCenterOf(name)
return@setListener
}
CourseManager.instance.openLesson(project, lesson)
}, null)
result.add(rigid(4, 0))
result.add(name)
return result
}
private fun createModuleItem(module: IftModule): JPanel {
val modulePanel = JPanel()
modulePanel.isOpaque = false
modulePanel.layout = BoxLayout(modulePanel, BoxLayout.Y_AXIS)
modulePanel.alignmentY = TOP_ALIGNMENT
modulePanel.background = Color(0, 0, 0, 0)
val result = object : JPanel() {
private var onInstall = true
override fun paint(g: Graphics?) {
if (onInstall && mouseAlreadyInside(this)) {
setCorrectBackgroundOnInstall(this)
onInstall = false
}
super.paint(g)
}
}
result.isOpaque = true
result.background = UISettings.instance.backgroundColor
result.layout = BoxLayout(result, BoxLayout.X_AXIS)
result.border = EmptyBorder(JBUI.scale(8), JBUI.scale(7), JBUI.scale(10), JBUI.scale(7))
result.alignmentX = LEFT_ALIGNMENT
val mouseAdapter = object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) {
if (!result.visibleRect.contains(e.point)) return
if (expanded.contains(module)) {
expanded.remove(module)
}
else {
expanded.clear()
expanded.add(module)
}
updateItems()
}
override fun mouseEntered(e: MouseEvent) {
setCorrectBackgroundOnInstall(result)
result.revalidate()
result.repaint()
}
override fun mouseExited(e: MouseEvent) {
result.background = UISettings.instance.backgroundColor
result.cursor = Cursor.getDefaultCursor()
result.revalidate()
result.repaint()
}
}
val expandPanel = JPanel().also {
it.layout = BoxLayout(it, BoxLayout.Y_AXIS)
it.isOpaque = false
it.background = Color(0, 0, 0, 0)
it.alignmentY = TOP_ALIGNMENT
//it.add(Box.createVerticalStrut(JBUI.scale(1)))
it.add(rigid(0, 1))
val rawIcon = if (expanded.contains(module)) UIUtil.getTreeExpandedIcon() else UIUtil.getTreeCollapsedIcon()
it.add(createLabelIcon(rawIcon))
}
result.add(expandPanel)
val name = JLabel(module.name)
name.font = UISettings.instance.modulesFont
modulePanel.add(name)
scaledRigid(UISettings.instance.progressModuleGap, 0)
modulePanel.add(scaledRigid(0, UISettings.instance.progressModuleGap))
if (expanded.contains(module)) {
modulePanel.add(HeightLimitedPane(module.description ?: "", -1, UIUtil.getLabelForeground() as JBColor).also {
it.addMouseListener(mouseAdapter)
})
}
else {
modulePanel.add(createModuleProgressLabel(module))
}
result.add(scaledRigid(UISettings.instance.expandAndModuleGap, 0))
result.add(modulePanel)
result.add(Box.createHorizontalGlue())
result.addMouseListener(mouseAdapter)
return result
}
private fun createLabelIcon(rawIcon: @NotNull Icon): JLabel = JLabel(IconUtil.toSize(rawIcon, JBUI.scale(16), JBUI.scale(16)))
private fun createModuleProgressLabel(module: IftModule): JBLabel {
val progressStr = learningProgressString(module.lessons)
val progressLabel = JBLabel(progressStr)
progressLabel.name = "progressLabel"
val hasNotPassedLesson = module.lessons.any { !it.passed }
progressLabel.foreground = if (hasNotPassedLesson) UISettings.instance.moduleProgressColor else UISettings.instance.completedColor
progressLabel.font = UISettings.instance.getFont(-1)
progressLabel.alignmentX = LEFT_ALIGNMENT
return progressLabel
}
private fun setCorrectBackgroundOnInstall(component: Component) {
component.background = HOVER_COLOR
component.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
}
private fun mouseAlreadyInside(c: Component): Boolean {
val mousePos: Point = MouseInfo.getPointerInfo()?.location ?: return false
val bounds: Rectangle = c.bounds
bounds.location = c.locationOnScreen
return bounds.contains(mousePos)
}
}
| plugins/ide-features-trainer/src/training/ui/views/LearningItems.kt | 1069149532 |
package com.dbflow5.query.list
import com.dbflow5.BaseUnitTest
import com.dbflow5.config.databaseForTable
import com.dbflow5.models.SimpleModel
import com.dbflow5.query.select
import com.dbflow5.structure.save
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Description:
*/
class FlowCursorListTest : BaseUnitTest() {
@Test
fun validateCursorPassed() {
databaseForTable<SimpleModel> { db ->
val cursor = (select from SimpleModel::class).cursor(db)
val list = FlowCursorList.Builder(select from SimpleModel::class, db)
.cursor(cursor)
.build()
assertEquals(cursor, list.cursor)
}
}
@Test
fun validateModelQueriable() {
databaseForTable<SimpleModel> { db ->
val modelQueriable = (select from SimpleModel::class)
val list = FlowCursorList.Builder(modelQueriable, db)
.build()
assertEquals(modelQueriable, list.modelQueriable)
}
}
@Test
fun validateGetAll() {
databaseForTable<SimpleModel> { db ->
(0..9).forEach {
SimpleModel("$it").save(db)
}
val list = (select from SimpleModel::class).cursorList(db)
val all = list.all
assertEquals(list.count, all.size.toLong())
}
}
@Test
fun validateCursorChange() {
databaseForTable<SimpleModel> { db ->
(0..9).forEach {
SimpleModel("$it").save(db)
}
val list = (select from SimpleModel::class).cursorList(db)
var cursorListFound: FlowCursorList<SimpleModel>? = null
var count = 0
val listener: (FlowCursorList<SimpleModel>) -> Unit = { loadedList ->
cursorListFound = loadedList
count++
}
list.addOnCursorRefreshListener(listener)
assertEquals(10, list.count)
SimpleModel("10").save(db)
list.refresh()
assertEquals(11, list.count)
assertEquals(list, cursorListFound)
list.removeOnCursorRefreshListener(listener)
list.refresh()
assertEquals(1, count)
}
}
}
| tests/src/androidTest/java/com/dbflow5/query/list/FlowCursorListTest.kt | 4205230020 |
// 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 org.jetbrains.plugins.github.api.data
import org.jetbrains.plugins.github.api.GHRepositoryPath
class GHRepositoryPermission(id: String,
val owner: GHRepositoryOwnerName,
nameWithOwner: String,
val viewerPermission: GHRepositoryPermissionLevel?,
val mergeCommitAllowed: Boolean,
val squashMergeAllowed: Boolean,
val rebaseMergeAllowed: Boolean)
: GHNode(id) {
val path: GHRepositoryPath
init {
val split = nameWithOwner.split('/')
path = GHRepositoryPath(split[0], split[1])
}
} | plugins/github/src/org/jetbrains/plugins/github/api/data/GHRepositoryPermission.kt | 3622138472 |
package test.common
import org.json.simple.JSONObject
import org.junit.Assert
import org.junit.Test
import slatekit.common.DateTime
import slatekit.requests.InputArgs
import slatekit.common.utils.Random
import slatekit.common.crypto.EncDouble
import slatekit.common.crypto.EncInt
import slatekit.common.crypto.EncLong
import slatekit.common.crypto.EncString
import test.setup.Movie
import org.threeten.bp.*
import slatekit.apis.core.Transformer
import slatekit.common.DateTimes
import slatekit.requests.CommonRequest
import slatekit.common.Source
import slatekit.requests.Request
import slatekit.meta.*
import slatekit.serialization.deserializer.Deserializer
import test.setup.MyEncryptor
import test.setup.StatusEnum
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KType
class DeserializerTests {
fun test_basic_types(tstr:String, tbool:Boolean, tshort:Short, tint:Int, tlong:Long, tdoub:Double):Unit {}
@Test fun can_parse_basictypes(){
val test = """{ "tstr": "abc", "tbool": false, "tshort": 1, "tint": 12, "tlong": 123, "tdoub": 123.45 }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val results = deserializer.deserialize(this::test_basic_types.parameters, test)
Assert.assertTrue(results[0] == "abc")
Assert.assertTrue(results[1] == false)
Assert.assertTrue(results[2] == 1.toShort())
Assert.assertTrue(results[3] == 12)
Assert.assertTrue(results[4] == 123L)
Assert.assertTrue(results[5] == 123.45)
}
fun test_dates(tdate: LocalDate, ttime: LocalTime, tlocaldatetime: LocalDateTime, tdatetime: DateTime):Unit{}
@Test fun can_parse_dates(){
val test = """{ "tdate": "2017-07-06", "ttime": "10:30:45", "tlocaldatetime": "2017-07-06T10:30:45", "tdatetime": "201707061030" }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val results = deserializer.deserialize(this::test_dates.parameters, test)
Assert.assertTrue(results[0] == LocalDate.of(2017, 7, 6))
Assert.assertTrue(results[1] == LocalTime.of(10,30,45))
Assert.assertTrue(results[2] == LocalDateTime.of(2017,7,6, 10,30, 45))
Assert.assertTrue(results[3] == DateTimes.of(2017,7,6, 10,30))
}
fun test_uuid(uid: UUID) {}
@Test fun can_parse_uuids(){
val uuid = Random.uuid()
val test = """{ "uid": "$uuid" }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val results = deserializer.deserialize(this::test_uuid.parameters, test)
Assert.assertTrue(results[0] == UUID.fromString(uuid))
}
fun test_enum(status: StatusEnum) {}
@Test fun can_parse_enum(){
val enumVal = StatusEnum.Active
val test = """{ "status": ${enumVal.value} }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val results = deserializer.deserialize(this::test_enum.parameters, test)
Assert.assertTrue(results[0] == enumVal)
}
fun test_decrypted(decString: EncString, decInt: EncInt, decLong: EncLong, decDouble: EncDouble):Unit {}
@Test fun can_parse_decrypted(){
val decStr = MyEncryptor.encrypt("abc123")
val decInt = MyEncryptor.encrypt("123")
val decLong = MyEncryptor.encrypt("12345")
val decDoub = MyEncryptor.encrypt("12345.67")
val test = """{ "decString": "$decStr", "decInt": "$decInt", "decLong": "$decLong", "decDouble": "$decDoub" }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()), MyEncryptor)
val results = deserializer.deserialize(this::test_decrypted.parameters, test)
Assert.assertTrue((results[0] as EncString).value == "abc123")
Assert.assertTrue((results[1] as EncInt).value == 123)
Assert.assertTrue((results[2] as EncLong).value == 12345L)
Assert.assertTrue((results[3] as EncDouble).value == 12345.67)
}
fun test_arrays(strings: List<String>, bools:List<Boolean>, ints:List<Int>, longs:List<Long>, doubles:List<Double>):Unit {}
@Test fun can_parse_arrays(){
val test = """{ "strings": ["a", "b", "c"], "bools": [true, false, true], "ints": [1,2,3], "longs": [100,200,300], "doubles": [1.2,3.4,5.6] }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()), MyEncryptor)
val results = deserializer.deserialize(this::test_arrays.parameters, test)
Assert.assertTrue((results[0] as List<String>)[0] == "a")
Assert.assertTrue((results[0] as List<String>)[1] == "b")
Assert.assertTrue((results[0] as List<String>)[2] == "c")
Assert.assertTrue((results[1] as List<Boolean>)[0] == true)
Assert.assertTrue((results[1] as List<Boolean>)[1] == false)
Assert.assertTrue((results[1] as List<Boolean>)[2] == true)
Assert.assertTrue((results[2] as List<Int>)[0] == 1)
Assert.assertTrue((results[2] as List<Int>)[1] == 2)
Assert.assertTrue((results[2] as List<Int>)[2] == 3)
Assert.assertTrue((results[3] as List<Long>)[0] == 100L)
Assert.assertTrue((results[3] as List<Long>)[1] == 200L)
Assert.assertTrue((results[3] as List<Long>)[2] == 300L)
Assert.assertTrue((results[4] as List<Double>)[0] == 1.2)
Assert.assertTrue((results[4] as List<Double>)[1] == 3.4)
Assert.assertTrue((results[4] as List<Double>)[2] == 5.6)
}
data class SampleObject1(val tstr:String, val tbool:Boolean, val tshort:Short, val tint:Int, val tlong:Long, val tdoub:Double)
fun test_object(sample1: SampleObject1):Unit{}
@Test fun can_parse_object(){
val test = """{ "sample1": { "tstr": "abc", "tbool": false, "tshort": 1, "tint": 12, "tlong": 123, "tdoub": 123.45 } }"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val results = deserializer.deserialize(this::test_object.parameters, test)
Assert.assertTrue(results[0] == DeserializerTests.SampleObject1("abc", false, 1, 12, 123, 123.45))
}
fun test_object_list(items:List<SampleObject1>):Unit{}
@Test fun can_parse_object_lists(){
val test = """{ "items":
[
{ "tstr": "abc", "tbool": false, "tshort": 1, "tint": 12, "tlong": 123, "tdoub": 123.45 },
{ "tstr": "def", "tbool": true , "tshort": 2, "tint": 34, "tlong": 456, "tdoub": 678.91 }
]}"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val inputs = deserializer.deserialize(this::test_object_list.parameters, test)
val results = inputs.get(0) as ArrayList<*>
println(results)
Assert.assertTrue(results[0] == DeserializerTests.SampleObject1("abc", false, 1, 12, 123, 123.45))
Assert.assertTrue(results[1] == DeserializerTests.SampleObject1("def", true, 2, 34, 456, 678.91))
}
data class NestedObject1(val name:String, val items:List<SampleObject1>)
fun test_nested_object_list(str:String, item: NestedObject1):Unit{}
@Test fun can_parse_object_lists_nested(){
val test = """{
"str" : "abc",
"item":
{
"name": "nested_objects",
"items":
[
{ "tstr": "abc", "tbool": false, "tshort": 1, "tint": 12, "tlong": 123, "tdoub": 123.45 },
{ "tstr": "def", "tbool": true , "tshort": 2, "tint": 34, "tlong": 456, "tdoub": 678.91 }
]
}
}"""
val deserializer = Deserializer(CommonRequest.cli("a", "b", "c", "post", mapOf(), mapOf()))
val results = deserializer.deserialize(this::test_nested_object_list.parameters, test)
val item = results[1] as NestedObject1
Assert.assertTrue(results[0] == "abc")
Assert.assertTrue(item.items[0] == DeserializerTests.SampleObject1("abc", false, 1, 12, 123, 123.45))
Assert.assertTrue(item.items[1] == DeserializerTests.SampleObject1("def", true, 2, 34, 456, 678.91))
}
fun test_custom_converter(tstr:String, tbool:Boolean, movie: Movie):Unit {}
@Test fun can_parse_custom_types_using_lambda_decoder(){
val test = """{
"tstr": "abc",
"tbool": false,
"movie": {
"id": 123,
"title": "dark knight",
"category": "action",
"playing": false,
"cost": 15,
"rating": 4.5,
"released": "2012-07-04T18:00:00Z"
}
}""".trimIndent()
val req = CommonRequest("a.b.c", listOf("a", "b", "c"), Source.CLI, "post",
InputArgs(mapOf()), InputArgs(mapOf(Pair("movie", "batman"))))
val decoder = Transformer(Movie::class.java, null) { _, _ ->
Movie(0L, "batman", cost = 0, rating = 4.0, released = DateTime.now())
}
val deserializer = Deserializer(req, null, mapOf(Pair(Movie::class.qualifiedName!!, decoder)))
val results = deserializer.deserialize(this::test_custom_converter.parameters, test)
Assert.assertTrue(results[0] == "abc")
Assert.assertTrue(results[1] == false)
Assert.assertTrue(results[2] is Movie )
Assert.assertTrue((results[2] as Movie ).title == "batman")
}
@Test fun can_parse_custom_types_using_simple_decoder(){
val test = """{
"tstr": "abc",
"tbool": false,
"movie": {
"id": 123,
"title": "dark knight",
"category": "action",
"playing": false,
"cost": 15,
"rating": 4.5,
"released": "2012-07-04T18:00:00Z"
}
}""".trimIndent()
val req = CommonRequest("a.b.c", listOf("a", "b", "c"), Source.CLI, "post",
InputArgs(mapOf()), InputArgs(mapOf(Pair("movie", "batman"))))
val deserializer = Deserializer(req, null, mapOf(Pair(Movie::class.qualifiedName!!, MovieDecoder())))
val results = deserializer.deserialize(this::test_custom_converter.parameters, test)
Assert.assertTrue(results[0] == "abc")
Assert.assertTrue(results[1] == false)
Assert.assertTrue(results[2] is Movie )
Assert.assertTrue((results[2] as Movie ).title == "dark knight")
Assert.assertTrue((results[2] as Movie ).category == "action")
Assert.assertTrue(!(results[2] as Movie ).playing)
Assert.assertTrue((results[2] as Movie ).cost == 15)
Assert.assertTrue((results[2] as Movie ).rating == 4.5)
}
class MovieDecoder : Transformer<Movie>(Movie::class.java) {
override fun restore(output: JSONObject?): Movie? {
return output?.let {
val doc = output
val inputs = InputsJSON(doc, null, doc)
val movie = Movie(
id = inputs.getLong("id"),
title = inputs.getString("title"),
category = inputs.getString("category"),
playing = inputs.getBool("playing"),
cost = inputs.getInt("cost"),
rating = inputs.getDouble("rating"),
released = inputs.getDateTime("released")
)
movie
}
}
}
fun test_context_converter(actor:Self, tstr:String, tbool:Boolean):Unit {}
@Test fun can_parse_custom_types_using_context(){
val test = """{
"tstr": "abc",
"tbool": false
}""".trimIndent()
val req = CommonRequest("a.b.c", listOf("a", "b", "c"), Source.CLI, "post",
InputArgs(mapOf(Pair("movie", "batman"))), InputArgs(mapOf("Authorization" to "a.user123.c")))
val deserializer = Deserializer(req, null, mapOf(Pair(Self::class.qualifiedName!!, JWTSelfDecoder())))
val results = deserializer.deserialize(this::test_context_converter.parameters, test)
Assert.assertTrue(results[0] == Self("user123"))
Assert.assertTrue(results[1] == "abc")
Assert.assertTrue(results[2] == false )
}
@Test fun can_parse_custom_types_using_context_with_override(){
val test = """{
"tstr": "abc",
"tbool": false,
"actor": "user999"
}""".trimIndent()
val req = CommonRequest("a.b.c", listOf("a", "b", "c"), Source.CLI, "post",
InputArgs(mapOf(Pair("movie", "batman"))), InputArgs(mapOf("Authorization" to "a.user123.c")))
val deserializer = Deserializer(req, null, mapOf(Pair(Self::class.qualifiedName!!, JWTSelfDecoder())))
val results = deserializer.deserialize(this::test_context_converter.parameters, test)
Assert.assertTrue(results[0] == Self("user999"))
Assert.assertTrue(results[1] == "abc")
Assert.assertTrue(results[2] == false )
}
@Test fun can_parse_custom_types_using_context_with_override_using_JSON(){
val test = """{
"tstr": "abc",
"tbool": false,
"actor": "user901"
}""".trimIndent()
val json = InputsJSON.of(test)
val req = CommonRequest("a.b.c", listOf("a", "b", "c"), Source.CLI, "post",
json, InputArgs(mapOf("Authorization" to "a.user123.c")))
val deserializer = Deserializer(req, null, mapOf(Pair(Self::class.qualifiedName!!, JWTSelfDecoder())))
val results = deserializer.deserialize(this::test_context_converter.parameters)
Assert.assertTrue(results[0] == Self("user901"))
Assert.assertTrue(results[1] == "abc")
Assert.assertTrue(results[2] == false )
}
data class Self(val uuid:String)
class JWTSelfDecoder : Transformer<Self>(Self::class.java), JSONRestoreWithContext<Self>{
override fun <T> restore(ctx: T, model: JSONObject?, key:String): Self? {
if(!(ctx is Request)) throw Exception("Request not available")
if(!ctx.meta.containsKey("Authorization")) throw Exception("JWT Not found")
// Simple extractor of uuid from JWT for test purpose.
val token = ctx.meta.getString("Authorization")
val parts = token.split(".")
val uuidFromToken = parts[1]
val exists = model?.containsKey(key) ?: false
val tokenFinal = when(exists) {
true -> model?.get(key) as String
false -> uuidFromToken
}
return Self(tokenFinal)
}
}
@Test fun can_check_types(){
val params = this::test_arrays.parameters
val first = params[0]
println(first.type)
val tpe = first.type
val listCls = tpe.classifier as KClass<*>
println(listCls == List::class)
val paramType: KType = tpe.arguments[0].type!!
val cls = tpe.classifier as KClass<*>
println(cls.toString())
println(cls.qualifiedName)
}
fun printInfo(item:Any?):Unit {
println(item)
}
}
| src/lib/kotlin/slatekit-tests/src/test/kotlin/test/common/DeserializerTests.kt | 2421523235 |
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.render
import android.content.ContentResolver
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.exifinterface.media.ExifInterface
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.nurik.roman.muzei.androidclientcommon.BuildConfig
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import kotlin.math.max
fun InputStream.isValidImage(): Boolean {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
inPreferredConfig = Bitmap.Config.ARGB_8888
}
BitmapFactory.decodeStream(this, null, options)
return with(options) {
outWidth != 0 && outHeight != 0 &&
(Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
outConfig == Bitmap.Config.ARGB_8888)
}
}
/**
* Base class for loading images with the correct rotation
*/
sealed class ImageLoader {
companion object {
private const val TAG = "ImageLoader"
suspend fun decode(
contentResolver: ContentResolver,
uri: Uri,
targetWidth: Int = 0,
targetHeight: Int = targetWidth
) = withContext(Dispatchers.IO) {
ContentUriImageLoader(contentResolver, uri)
.decode(targetWidth, targetHeight)
}
}
fun getSize(): Pair<Int, Int> {
return try {
val (originalWidth, originalHeight) = openInputStream()?.use { input ->
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(input, null, options)
options.outWidth to options.outHeight
} ?: return 0 to 0
val rotation = getRotation()
val width = if (rotation == 90 || rotation == 270) originalHeight else originalWidth
val height = if (rotation == 90 || rotation == 270) originalWidth else originalHeight
return width to height
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Error decoding ${toString()}: ${e.message}")
}
0 to 0
}
}
fun decode(
targetWidth: Int = 0,
targetHeight: Int = targetWidth
) : Bitmap? {
return try {
val (originalWidth, originalHeight) = openInputStream()?.use { input ->
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(input, null, options)
Pair(options.outWidth, options.outHeight)
} ?: return null
val rotation = getRotation()
val width = if (rotation == 90 || rotation == 270) originalHeight else originalWidth
val height = if (rotation == 90 || rotation == 270) originalWidth else originalHeight
openInputStream()?.use { input ->
BitmapFactory.decodeStream(input, null,
BitmapFactory.Options().apply {
inPreferredConfig = Bitmap.Config.ARGB_8888
if (targetWidth != 0) {
inSampleSize = max(
width.sampleSize(targetWidth),
height.sampleSize(targetHeight))
}
})
}?.run {
when (rotation) {
0 -> this
else -> {
val rotateMatrix = Matrix().apply {
postRotate(rotation.toFloat())
}
Bitmap.createBitmap(
this, 0, 0,
this.width, this.height,
rotateMatrix, true).also { rotatedBitmap ->
if (rotatedBitmap != this) {
recycle()
}
}
}
}
}
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Error decoding ${toString()}: ${e.message}")
}
null
}
}
fun getRotation(): Int = try {
openInputStream()?.use { input ->
val exifInterface = ExifInterface(input)
when (exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL)) {
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
} ?: 0
} catch (e: Exception) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Couldn't open EXIF interface for ${toString()}", e)
}
0
}
abstract fun openInputStream() : InputStream?
}
/**
* An [ImageLoader] capable of loading images from a [ContentResolver]
*/
class ContentUriImageLoader constructor(
private val contentResolver: ContentResolver,
private val uri: Uri
) : ImageLoader() {
@Throws(FileNotFoundException::class)
override fun openInputStream(): InputStream? =
contentResolver.openInputStream(uri)
override fun toString(): String {
return uri.toString()
}
}
/**
* An [ImageLoader] capable of loading images from [AssetManager]
*/
class AssetImageLoader constructor(
private val assetManager: AssetManager,
private val fileName: String
) : ImageLoader() {
@Throws(IOException::class)
override fun openInputStream(): InputStream =
assetManager.open(fileName)
override fun toString(): String {
return fileName
}
} | android-client-common/src/main/java/com/google/android/apps/muzei/render/ImageLoader.kt | 2852033410 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// FILE: JavaClass.java
public class JavaClass {
public static String test() {
return MainKt.bar(MainKt.foo());
}
}
// FILE: main.kt
class Pair<out X, out Y>(val x: X, val y: Y)
class Inv<T>(val x: T)
fun foo(): Inv<Pair<CharSequence, CharSequence>> = Inv(Pair("O", "K"))
fun bar(inv: Inv<Pair<CharSequence, CharSequence>>) = inv.x.x.toString() + inv.x.y
fun box(): String {
return JavaClass.test();
}
| backend.native/tests/external/codegen/box/javaInterop/generics/invariantArgumentsNoWildcard.kt | 744010444 |
// TARGET_BACKEND: JVM
// FILE: 1.kt
// LANGUAGE_VERSION: 1.2
// SKIP_INLINE_CHECK_IN: inlineFun$default
//WITH_RUNTIME
package test
inline fun <reified T> inlineFun(lambda: () -> String = { { T::class.java.simpleName } () }): String {
return lambda()
}
// FILE: 2.kt
//NO_CHECK_LAMBDA_INLINING
import test.*
class OK
fun box(): String {
return inlineFun<OK>()
}
| backend.native/tests/external/codegen/boxInline/reified/defaultLambda/nestedStatic.kt | 1541476612 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
import kotlin.reflect.KClass
fun check(clazz: Class<*>?, expected: String) {
assert (clazz!!.canonicalName == expected) {
"clazz name: ${clazz.canonicalName}"
}
}
fun check(kClass: KClass<*>, expected: String) {
check(kClass.javaPrimitiveType, expected)
}
fun checkNull(clazz: Class<*>?) {
assert (clazz == null) {
"clazz should be null: ${clazz!!.canonicalName}"
}
}
fun checkNull(kClass: KClass<*>) {
checkNull(kClass.javaPrimitiveType)
}
fun box(): String {
check(Boolean::class.javaPrimitiveType, "boolean")
check(Boolean::class, "boolean")
check(Char::class.javaPrimitiveType, "char")
check(Char::class, "char")
check(Byte::class.javaPrimitiveType, "byte")
check(Byte::class, "byte")
check(Short::class.javaPrimitiveType, "short")
check(Short::class, "short")
check(Int::class.javaPrimitiveType, "int")
check(Int::class, "int")
check(Float::class.javaPrimitiveType, "float")
check(Float::class, "float")
check(Long::class.javaPrimitiveType, "long")
check(Long::class, "long")
check(Double::class.javaPrimitiveType, "double")
check(Double::class, "double")
checkNull(String::class.javaPrimitiveType)
checkNull(String::class)
checkNull(Nothing::class.javaPrimitiveType)
checkNull(Nothing::class)
checkNull(Void::class.javaPrimitiveType)
checkNull(Void::class)
return "OK"
}
| backend.native/tests/external/codegen/box/classLiteral/java/javaPrimitiveType.kt | 165853043 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
inline fun <reified T : Any> check(expected: String) {
val clazz = T::class.javaObjectType!!
assert (clazz.canonicalName == "java.lang.$expected") {
"clazz name: ${clazz.canonicalName}"
}
}
fun box(): String {
check<Boolean>("Boolean")
check<Char>("Character")
check<Byte>("Byte")
check<Short>("Short")
check<Int>("Integer")
check<Float>("Float")
check<Long>("Long")
check<Double>("Double")
check<String>("String")
check<Void>("Void")
return "OK"
}
| backend.native/tests/external/codegen/box/classLiteral/java/javaObjectTypeReified.kt | 2840497878 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
annotation class Ann(val value: String)
@Ann("OK")
val property: String
get() = ""
fun box(): String {
return (::property.annotations.single() as Ann).value
}
| backend.native/tests/external/codegen/box/reflection/annotations/propertyWithoutBackingField.kt | 1249263321 |
data class A(var string: String)
fun box(): String {
val a = A("Fail")
a.string = "OK"
val (result) = a
return result
}
| backend.native/tests/external/codegen/box/dataClasses/changingVarParam.kt | 1178426767 |
/*
* 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.compose.compiler.plugins.kotlin
import androidx.compose.compiler.plugins.kotlin.analysis.ComposeWritableSlices
import androidx.compose.compiler.plugins.kotlin.inference.ErrorReporter
import androidx.compose.compiler.plugins.kotlin.inference.TypeAdapter
import androidx.compose.compiler.plugins.kotlin.inference.ApplierInferencer
import androidx.compose.compiler.plugins.kotlin.inference.Item
import androidx.compose.compiler.plugins.kotlin.inference.LazyScheme
import androidx.compose.compiler.plugins.kotlin.inference.LazySchemeStorage
import androidx.compose.compiler.plugins.kotlin.inference.NodeAdapter
import androidx.compose.compiler.plugins.kotlin.inference.NodeKind
import androidx.compose.compiler.plugins.kotlin.inference.Open
import androidx.compose.compiler.plugins.kotlin.inference.Scheme
import androidx.compose.compiler.plugins.kotlin.inference.Token
import androidx.compose.compiler.plugins.kotlin.inference.deserializeScheme
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.backend.jvm.ir.psiElement
import org.jetbrains.kotlin.builtins.isFunctionType
import org.jetbrains.kotlin.codegen.kotlinType
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.findClassAcrossModuleDependencies
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.types.KotlinType
private sealed class InferenceNode(val element: PsiElement) {
open val kind: NodeKind get() = when (element) {
is KtLambdaExpression, is KtFunctionLiteral -> NodeKind.Lambda
is KtFunction -> NodeKind.Function
else -> NodeKind.Expression
}
abstract val type: InferenceNodeType
}
private sealed class InferenceNodeType {
abstract fun toScheme(callContext: CallCheckerContext): Scheme
abstract fun isTypeFor(descriptor: CallableDescriptor): Boolean
}
private class InferenceDescriptorType(val descriptor: CallableDescriptor) : InferenceNodeType() {
override fun toScheme(callContext: CallCheckerContext): Scheme =
descriptor.toScheme(callContext)
override fun isTypeFor(descriptor: CallableDescriptor) = this.descriptor == descriptor
override fun hashCode(): Int = 31 * descriptor.original.hashCode()
override fun equals(other: Any?): Boolean =
other is InferenceDescriptorType && other.descriptor.original == descriptor.original
}
private class InferenceKotlinType(val type: KotlinType) : InferenceNodeType() {
override fun toScheme(callContext: CallCheckerContext): Scheme = type.toScheme()
override fun isTypeFor(descriptor: CallableDescriptor): Boolean = false
override fun hashCode(): Int = 31 * type.hashCode()
override fun equals(other: Any?): Boolean =
other is InferenceKotlinType && other.type == type
}
private class InferenceUnknownType : InferenceNodeType() {
override fun toScheme(callContext: CallCheckerContext): Scheme = Scheme(Open(-1))
override fun isTypeFor(descriptor: CallableDescriptor): Boolean = false
override fun hashCode(): Int = System.identityHashCode(this)
override fun equals(other: Any?): Boolean = other === this
}
private class PsiElementNode(
element: PsiElement,
val bindingContext: BindingContext
) : InferenceNode(element) {
override val type: InferenceNodeType = when (element) {
is KtLambdaExpression -> descriptorTypeOf(element.functionLiteral)
is KtFunctionLiteral, is KtFunction -> descriptorTypeOf(element)
is KtProperty -> kotlinTypeOf(element)
is KtPropertyAccessor -> kotlinTypeOf(element)
is KtExpression -> kotlinTypeOf(element)
else -> descriptorTypeOf(element)
}
private fun descriptorTypeOf(element: PsiElement): InferenceNodeType =
bindingContext[BindingContext.FUNCTION, element]?.let {
InferenceDescriptorType(it)
} ?: InferenceUnknownType()
private fun kotlinTypeOf(element: KtExpression) = element.kotlinType(bindingContext)?.let {
InferenceKotlinType(it)
} ?: InferenceUnknownType()
}
private class ResolvedPsiElementNode(
element: PsiElement,
override val type: InferenceNodeType,
) : InferenceNode(element) {
override val kind: NodeKind get() = NodeKind.Function
}
private class ResolvedPsiParameterReference(
element: PsiElement,
override val type: InferenceNodeType,
val index: Int,
val container: PsiElement
) : InferenceNode(element) {
override val kind: NodeKind get() = NodeKind.ParameterReference
}
class ComposableTargetChecker : CallChecker, StorageComponentContainerContributor {
private lateinit var callContext: CallCheckerContext
private fun containerOf(element: PsiElement): PsiElement? {
var current: PsiElement? = element.parent
while (current != null) {
when (current) {
is KtLambdaExpression, is KtFunction, is KtProperty, is KtPropertyAccessor ->
return current
is KtClass, is KtFile -> break
}
current = current.parent as? KtElement
}
return null
}
private fun containerNodeOf(element: PsiElement) =
containerOf(element)?.let {
PsiElementNode(it, callContext.trace.bindingContext)
}
// Create an InferApplier instance with adapters for the Psi front-end
private val infer = ApplierInferencer(
typeAdapter = object : TypeAdapter<InferenceNodeType> {
override fun declaredSchemaOf(type: InferenceNodeType): Scheme =
type.toScheme(callContext)
override fun currentInferredSchemeOf(type: InferenceNodeType): Scheme? = null
override fun updatedInferredScheme(type: InferenceNodeType, scheme: Scheme) { }
},
nodeAdapter = object : NodeAdapter<InferenceNodeType, InferenceNode> {
override fun containerOf(node: InferenceNode): InferenceNode =
containerNodeOf(node.element) ?: node
override fun kindOf(node: InferenceNode) = node.kind
override fun schemeParameterIndexOf(
node: InferenceNode,
container: InferenceNode
): Int = (node as? ResolvedPsiParameterReference)?.let {
if (it.container == container.element) it.index else -1
} ?: -1
override fun typeOf(node: InferenceNode): InferenceNodeType = node.type
override fun referencedContainerOf(node: InferenceNode): InferenceNode? {
return null
}
},
errorReporter = object : ErrorReporter<InferenceNode> {
/**
* Find the `description` value from ComposableTargetMarker if the token refers to an
* annotation with the marker or just return [token] if it cannot be found.
*/
private fun descriptionFrom(token: String): String {
val fqName = FqName(token)
val cls = callContext.moduleDescriptor.findClassAcrossModuleDependencies(
ClassId.topLevel(fqName)
)
return cls?.let {
it.annotations.findAnnotation(
ComposeFqNames.ComposableTargetMarker
)?.let { marker ->
marker.allValueArguments.firstNotNullOfOrNull { entry ->
val name = entry.key
if (
!name.isSpecial &&
name.identifier == ComposeFqNames.ComposableTargetMarkerDescription
) {
(entry.value as? StringValue)?.value
} else null
}
}
} ?: token
}
override fun reportCallError(node: InferenceNode, expected: String, received: String) {
if (expected != received) {
val expectedDescription = descriptionFrom(expected)
val receivedDescription = descriptionFrom(received)
callContext.trace.report(
ComposeErrors.COMPOSE_APPLIER_CALL_MISMATCH.on(
node.element,
expectedDescription,
receivedDescription
)
)
}
}
override fun reportParameterError(
node: InferenceNode,
index: Int,
expected: String,
received: String
) {
if (expected != received) {
val expectedDescription = descriptionFrom(expected)
val receivedDescription = descriptionFrom(received)
callContext.trace.report(
ComposeErrors.COMPOSE_APPLIER_PARAMETER_MISMATCH.on(
node.element,
expectedDescription,
receivedDescription
)
)
}
}
override fun log(node: InferenceNode?, message: String) {
// ignore log messages in the front-end
}
},
lazySchemeStorage = object : LazySchemeStorage<InferenceNode> {
override fun getLazyScheme(node: InferenceNode): LazyScheme? =
callContext.trace.bindingContext.get(
ComposeWritableSlices.COMPOSE_LAZY_SCHEME,
node.type
)
override fun storeLazyScheme(node: InferenceNode, value: LazyScheme) {
callContext.trace.record(
ComposeWritableSlices.COMPOSE_LAZY_SCHEME,
node.type,
value
)
}
}
)
override fun registerModuleComponents(
container: StorageComponentContainer,
platform: TargetPlatform,
moduleDescriptor: ModuleDescriptor
) {
container.useInstance(this)
}
override fun check(
resolvedCall: ResolvedCall<*>,
reportOn: PsiElement,
context: CallCheckerContext
) {
if (!resolvedCall.isComposableInvocation()) return
callContext = context
val bindingContext = callContext.trace.bindingContext
val parameters = resolvedCall.candidateDescriptor.valueParameters.filter {
(it.type.isFunctionType && it.type.hasComposableAnnotation()) || it.isSamComposable()
}
val arguments = parameters.map {
val argument = resolvedCall.valueArguments.entries.firstOrNull { entry ->
entry.key.original == it
}?.value
if (argument is ExpressionValueArgument) {
argumentToInferenceNode(it, argument.valueArgument?.asElement() ?: reportOn)
} else {
// Generate a node that is ignored
PsiElementNode(reportOn, bindingContext)
}
}
infer.visitCall(
call = PsiElementNode(reportOn, bindingContext),
target = resolvedCallToInferenceNode(resolvedCall),
arguments = arguments
)
}
private fun resolvedCallToInferenceNode(resolvedCall: ResolvedCall<*>) =
when (resolvedCall) {
is VariableAsFunctionResolvedCall ->
descriptorToInferenceNode(
resolvedCall.variableCall.candidateDescriptor,
resolvedCall.call.callElement
)
else -> {
val receiver = resolvedCall.dispatchReceiver
val expression = (receiver as? ExpressionReceiver)?.expression
val referenceExpression = expression as? KtReferenceExpression
val candidate = referenceExpression?.let { r ->
val callableReference =
callContext.trace[BindingContext.REFERENCE_TARGET, r] as?
CallableDescriptor
callableReference?.let { reference ->
descriptorToInferenceNode(reference, resolvedCall.call.callElement)
}
}
candidate ?: descriptorToInferenceNode(
resolvedCall.resultingDescriptor,
resolvedCall.call.callElement
)
}
}
private fun argumentToInferenceNode(
descriptor: ValueParameterDescriptor,
element: PsiElement
): InferenceNode {
val bindingContext = callContext.trace.bindingContext
val lambda = lambdaOrNull(element)
if (lambda != null) return PsiElementNode(lambda, bindingContext)
val parameter = findParameterReferenceOrNull(descriptor, element)
if (parameter != null) return parameter
return PsiElementNode(element, bindingContext)
}
private fun lambdaOrNull(element: PsiElement): KtFunctionLiteral? {
var container = (element as? KtLambdaArgument)?.children?.singleOrNull()
while (true) {
container = when (container) {
null -> return null
is KtLabeledExpression -> container.lastChild
is KtFunctionLiteral -> return container
is KtLambdaExpression -> container.children.single()
else -> throw Error("Unknown type: ${container.javaClass}")
}
}
}
private fun descriptorToInferenceNode(
descriptor: CallableDescriptor,
element: PsiElement
): InferenceNode = when (descriptor) {
is ValueParameterDescriptor -> parameterDescriptorToInferenceNode(descriptor, element)
else -> {
// If this is a call to the accessor of the variable find the original descriptor
val original = descriptor.original
if (original is ValueParameterDescriptor)
parameterDescriptorToInferenceNode(original, element)
else ResolvedPsiElementNode(element, InferenceDescriptorType(descriptor))
}
}
private fun parameterDescriptorToInferenceNode(
descriptor: ValueParameterDescriptor,
element: PsiElement
): InferenceNode {
val parameter = findParameterReferenceOrNull(descriptor, element)
return parameter ?: PsiElementNode(element, callContext.trace.bindingContext)
}
private fun findParameterReferenceOrNull(
descriptor: ValueParameterDescriptor,
element: PsiElement
): InferenceNode? {
val bindingContext = callContext.trace.bindingContext
val declaration = descriptor.containingDeclaration
var currentContainer: InferenceNode? = containerNodeOf(element)
while (currentContainer != null) {
val type = currentContainer.type
if (type.isTypeFor(declaration)) {
val index =
declaration.valueParameters.filter {
it.isComposableCallable(bindingContext) ||
it.isSamComposable()
}.indexOf(descriptor)
return ResolvedPsiParameterReference(
element,
InferenceDescriptorType(descriptor),
index,
currentContainer.element
)
}
currentContainer = containerNodeOf(currentContainer.element)
}
return null
}
}
private fun Annotated.schemeItem(): Item {
val explicitTarget = compositionTarget()
val explicitOpen = if (explicitTarget == null) compositionOpenTarget() else null
return when {
explicitTarget != null -> Token(explicitTarget)
explicitOpen != null -> Open(explicitOpen)
else -> Open(-1, isUnspecified = true)
}
}
private fun Annotated.scheme(): Scheme? = compositionScheme()?.let { deserializeScheme(it) }
internal fun CallableDescriptor.toScheme(callContext: CallCheckerContext?): Scheme =
scheme()
?: Scheme(
target = schemeItem().let {
// The item is unspecified see if the containing has an annotation we can use
if (it.isUnspecified) {
val target = callContext?.let { context -> fileScopeTarget(context) }
if (target != null) return@let target
}
it
},
parameters = valueParameters.filter {
it.type.hasComposableAnnotation() || it.isSamComposable()
}.map {
it.samComposableOrNull()?.toScheme(callContext) ?: it.type.toScheme()
}
).mergeWith(overriddenDescriptors.map { it.toScheme(null) })
private fun CallableDescriptor.fileScopeTarget(callContext: CallCheckerContext): Item? =
(psiElement?.containingFile as? KtFile)?.let {
for (entry in it.annotationEntries) {
val annotationDescriptor =
callContext.trace.bindingContext[BindingContext.ANNOTATION, entry]
annotationDescriptor?.compositionTarget()?.let { token ->
return Token(token)
}
}
null
}
private fun KotlinType.toScheme(): Scheme = Scheme(
target = schemeItem(),
parameters = arguments.filter { it.type.hasComposableAnnotation() }.map { it.type.toScheme() }
)
private fun ValueParameterDescriptor.samComposableOrNull() =
(type.constructor.declarationDescriptor as? ClassDescriptor)?.let {
getSingleAbstractMethodOrNull(it)
}
private fun ValueParameterDescriptor.isSamComposable() =
samComposableOrNull()?.hasComposableAnnotation() == true
internal fun Scheme.mergeWith(schemes: List<Scheme>): Scheme {
if (schemes.isEmpty()) return this
val lazyScheme = LazyScheme(this)
val bindings = lazyScheme.bindings
fun unifySchemes(a: LazyScheme, b: LazyScheme) {
bindings.unify(a.target, b.target)
for ((ap, bp) in a.parameters.zip(b.parameters)) {
unifySchemes(ap, bp)
}
}
schemes.forEach {
val overrideScheme = LazyScheme(it, bindings = lazyScheme.bindings)
unifySchemes(lazyScheme, overrideScheme)
}
return lazyScheme.toScheme()
} | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/ComposableTargetChecker.kt | 3328573030 |
package com.xenoage.zong.core.music.direction
import com.xenoage.zong.core.music.TextElement
import com.xenoage.zong.core.text.Text
/**
* Direction words, that are not interpreted by this program.
*/
class Words(
override var text: Text
) : Direction(), TextElement
| core/src/com/xenoage/zong/core/music/direction/Words.kt | 577183188 |
fun foo(p: () -> Unit){}
fun bar() {
foo(::<caret>)
}
fun f(){}
// ELEMENT: f | plugins/kotlin/completion/tests/testData/handlers/smart/CallableReference3.kt | 1412910982 |
// 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.internal.statistic.collectors.fus.settings
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventId1
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.util.net.HttpConfigurable
import java.util.HashSet
private class ProxyTypeCollector : ApplicationUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(): MutableSet<MetricEvent> {
val result = HashSet<MetricEvent>()
val httpConfigurable = HttpConfigurable.getInstance()
// HttpProxySettingsUi holds JBRadioButtons for proxy types in ButtonGroups
// That handles HttpConfigurable flags in sync so we only need to check them one by one to determine currently chosen proxy type
if (httpConfigurable != null && (httpConfigurable.USE_PROXY_PAC || httpConfigurable.USE_HTTP_PROXY)) {
val type = when {
httpConfigurable.USE_PROXY_PAC -> ProxyType.Auto
/*httpConfigurable.USE_HTTP_PROXY && */httpConfigurable.PROXY_TYPE_IS_SOCKS -> ProxyType.Socks
/*httpConfigurable.USE_HTTP_PROXY && !httpConfigurable.PROXY_TYPE_IS_SOCKS*/else -> ProxyType.Http
}
result.add(TYPE.metric(type.name))
}
return result
}
companion object {
private val GROUP: EventLogGroup = EventLogGroup("proxy.settings", 1)
private val TYPE: EventId1<String?> = GROUP.registerEvent(
"proxy.type", EventFields.String("name", ProxyType.values().map { type -> type.name }))
enum class ProxyType { Auto, Socks, Http }
}
} | platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/settings/ProxyTypeCollector.kt | 957311659 |
// 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.ui.dsl.gridLayout
import com.intellij.ui.dsl.checkNonNegative
import com.intellij.ui.dsl.checkPositive
import com.intellij.ui.dsl.gridLayout.impl.GridImpl
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
enum class HorizontalAlign {
LEFT,
CENTER,
RIGHT,
FILL
}
enum class VerticalAlign {
TOP,
CENTER,
BOTTOM,
FILL
}
data class Constraints(
/**
* Grid destination
*/
val grid: Grid,
/**
* Cell x coordinate in [grid]
*/
val x: Int,
/**
* Cell y coordinate in [grid]
*/
val y: Int,
/**
* Columns number occupied by the cell
*/
val width: Int = 1,
/**
* Rows number occupied by the cell
*/
val height: Int = 1,
/**
* Horizontal alignment of content inside the cell
*/
val horizontalAlign: HorizontalAlign = HorizontalAlign.LEFT,
/**
* Vertical alignment of content inside the cell
*/
val verticalAlign: VerticalAlign = VerticalAlign.CENTER,
/**
* If true then vertical align is done by baseline:
*
* 1. All cells in the same grid row with [baselineAlign] true, [height] equals 1 and with the same [verticalAlign]
* (except [VerticalAlign.FILL], which doesn't support baseline) are aligned by baseline together
* 2. Sub grids (see [GridImpl.registerSubGrid]) with only one row and that contain cells only with [VerticalAlign.FILL] and another
* specific [VerticalAlign] (at least one cell without fill align) have own baseline and can be aligned by baseline in parent grid
*/
val baselineAlign: Boolean = false,
/**
* Gaps between grid cell bounds and components visual bounds (visual bounds is component bounds minus [visualPaddings])
*/
val gaps: Gaps = Gaps.EMPTY,
/**
* Gaps between component bounds and its visual bounds. Can be used when component has focus ring outside of
* its usual size. In such case components size is increased on focus size (so focus ring is not clipped)
* and [visualPaddings] should be set to maintain right alignments
*
* 1. Layout manager aligns components by their visual bounds
* 2. Cell size with gaps is calculated as component.bounds + [gaps] - [visualPaddings]
*/
var visualPaddings: Gaps = Gaps.EMPTY,
/**
* Component helper for custom behaviour
*/
@ApiStatus.Experimental
val componentHelper: ComponentHelper? = null
) {
init {
checkNonNegative("x", x)
checkNonNegative("y", y)
checkPositive("width", width)
checkPositive("height", height)
}
}
/**
* A helper for custom behaviour for components in cells
*/
@ApiStatus.Experimental
interface ComponentHelper {
/**
* Returns custom baseline or null if default baseline calculation should be used
*
* @see JComponent.getBaseline
*/
fun getBaseline(width: Int, height: Int): Int?
}
| platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/Constraints.kt | 1921358176 |
fun some(x: Any) {
when (x) {
is Number -> 0
else -> 1
}
when {
}
when {
}
when {
}
when (true) {
}
when (true) {
}
when
(true) {
}
when
(true) {
}
when {
}
}
val a = when {
true && true && true -> {
}
else -> {
}
}
// SET_FALSE: ALIGN_IN_COLUMNS_CASE_BRANCH
| plugins/kotlin/idea/tests/testData/formatter/When.after.kt | 1722575327 |
package test
fun main(args: Array<String>) {
// SMART_STEP_INTO_BY_INDEX: 2
//Breakpoint!
f1 {
test()
}
}
inline fun f1(f1Param: () -> Unit) {
f1Param()
}
fun test() {
println("Hello")
}
| plugins/kotlin/jvm-debugger/test/testData/stepping/custom/ktij12731.kt | 1043264004 |
class Outer {
interface Inner1 {
fun f() { }
}
interface Inner2 {
fun g() { }
}
}
class X : Outer.Inner1, Outer.Inner2 {
<caret>
} | plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/qualifySuperType.kt | 3711829083 |
// 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.inspections
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.highlighter.AbstractKotlinHighlightVisitor
import org.jetbrains.kotlin.idea.quickfix.CleanupFix
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.ReplaceObsoleteLabelSyntaxFix
import org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
class KotlinCleanupInspection : LocalInspectionTool(), CleanupLocalInspectionTool {
// required to simplify the inspection registration in tests
override fun getDisplayName(): String = KotlinBundle.message("usage.of.redundant.or.deprecated.syntax.or.deprecated.symbols")
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? {
if (isOnTheFly || file !is KtFile || !ProjectRootsUtil.isInProjectSource(file)) {
return null
}
val analysisResult = file.analyzeWithAllCompilerChecks()
if (analysisResult.isError()) {
return null
}
val diagnostics = analysisResult.bindingContext.diagnostics
val problemDescriptors = arrayListOf<ProblemDescriptor>()
val importsToRemove = DeprecatedSymbolUsageFix.importDirectivesToBeRemoved(file)
for (import in importsToRemove) {
val removeImportFix = RemoveImportFix(import)
val problemDescriptor = createProblemDescriptor(import, removeImportFix.text, listOf(removeImportFix), manager)
problemDescriptors.add(problemDescriptor)
}
file.forEachDescendantOfType<PsiElement> { element ->
for (diagnostic in diagnostics.forElement(element)) {
if (diagnostic.isCleanup()) {
val fixes = diagnostic.toCleanupFixes()
if (fixes.isNotEmpty()) {
problemDescriptors.add(diagnostic.toProblemDescriptor(fixes, file, manager))
}
}
}
}
return problemDescriptors.toTypedArray()
}
private fun Diagnostic.isCleanup() = factory in cleanupDiagnosticsFactories || isObsoleteLabel()
private val cleanupDiagnosticsFactories = setOf(
Errors.MISSING_CONSTRUCTOR_KEYWORD,
Errors.UNNECESSARY_NOT_NULL_ASSERTION,
Errors.UNNECESSARY_SAFE_CALL,
Errors.USELESS_CAST,
Errors.USELESS_ELVIS,
ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION,
Errors.DEPRECATION,
Errors.DEPRECATION_ERROR,
Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION,
Errors.OPERATOR_MODIFIER_REQUIRED,
Errors.INFIX_MODIFIER_REQUIRED,
Errors.DEPRECATED_TYPE_PARAMETER_SYNTAX,
Errors.MISPLACED_TYPE_PARAMETER_CONSTRAINTS,
Errors.COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT,
ErrorsJs.WRONG_EXTERNAL_DECLARATION,
Errors.YIELD_IS_RESERVED,
Errors.DEPRECATED_MODIFIER_FOR_TARGET,
Errors.DEPRECATED_MODIFIER
)
private fun Diagnostic.isObsoleteLabel(): Boolean {
val annotationEntry = psiElement.getNonStrictParentOfType<KtAnnotationEntry>() ?: return false
return ReplaceObsoleteLabelSyntaxFix.looksLikeObsoleteLabel(annotationEntry)
}
private fun Diagnostic.toCleanupFixes(): Collection<CleanupFix> {
return AbstractKotlinHighlightVisitor.createQuickFixes(this).filterIsInstance<CleanupFix>()
}
private class Wrapper(val intention: IntentionAction) : IntentionWrapper(intention) {
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (intention.isAvailable(
project,
editor,
file
)
) { // we should check isAvailable here because some elements may get invalidated (or other conditions may change)
super.invoke(project, editor, file)
}
}
}
private fun Diagnostic.toProblemDescriptor(fixes: Collection<CleanupFix>, file: KtFile, manager: InspectionManager): ProblemDescriptor {
// TODO: i18n DefaultErrorMessages.render
@NlsSafe val message = DefaultErrorMessages.render(this)
return createProblemDescriptor(psiElement, message, fixes, manager)
}
private fun createProblemDescriptor(
element: PsiElement,
@Nls message: String,
fixes: Collection<CleanupFix>,
manager: InspectionManager
): ProblemDescriptor {
return manager.createProblemDescriptor(
element,
message,
false,
fixes.map { Wrapper(it) }.toTypedArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
private class RemoveImportFix(import: KtImportDirective) : KotlinQuickFixAction<KtImportDirective>(import), CleanupFix {
override fun getFamilyName() = KotlinBundle.message("remove.deprecated.symbol.import")
@Nls
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
element?.delete()
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt | 3260974477 |
// "Wrap with '?.let { ... }' call" "true"
// WITH_STDLIB
interface Foo {
val bar: ((Int) -> Unit)?
}
fun test(foo: Foo) {
foo.bar<caret>(1)
}
| plugins/kotlin/idea/tests/testData/quickfix/wrapWithSafeLetCall/invokeFunctionType.kt | 2041078663 |
val b: Boolean = true
val c: String = "true"
val d: Int = 1
val e: Long = 1L
val f: Boolean = true
fun foo(): Boolean
fun test(): Int {
return <caret>
}
//ORDER: test, d | plugins/kotlin/completion/tests/testData/weighers/basic/expectedType/returnFromFunction.kt | 625391012 |
package de.fabmax.kool.util
import de.fabmax.kool.lock
object UniqueId {
private var nextId = 1L
private val idLock = Any()
fun nextId(): Long = lock(idLock) { ++nextId }
} | kool-core/src/commonMain/kotlin/de/fabmax/kool/util/UniqueId.kt | 2364262626 |
/*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.events
import com.mbrlabs.mundus.commons.Scene
/**
* @author Marcus Brummer
* @version 21-01-2016
*/
class SceneAddedEvent(var scene: Scene?) {
interface SceneAddedListener {
@Subscribe
fun onSceneAdded(event: SceneAddedEvent)
}
}
| editor/src/main/com/mbrlabs/mundus/editor/events/SceneAddedEvent.kt | 133343759 |
/*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.sources
import com.github.javaparser.ast.Node
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.body.TypeDeclaration
import com.github.javaparser.ast.visitor.VoidVisitorAdapter
import org.jetbrains.android.anko.getJavaClassName
public class SourceManager(private val provider: SourceProvider) {
public fun getArgumentNames(classFqName: String, methodName: String, argumentJavaTypes: List<String>): List<String>? {
val parsed = provider.parse(classFqName) ?: return null
val className = getJavaClassName(classFqName)
val argumentNames = arrayListOf<String>()
var done = false
object : VoidVisitorAdapter<Any>() {
override fun visit(method: MethodDeclaration, arg: Any?) {
if (done) return
if (methodName != method.getName() || argumentJavaTypes.size() != method.getParameters().size()) return
if (method.getParentClassName() != className) return
val parameters = method.getParameters()
for ((argumentFqType, param) in argumentJavaTypes.zip(parameters)) {
if (argumentFqType.substringAfterLast('.') != param.getType().toString()) return
}
parameters.forEach { argumentNames.add(it.getId().getName()) }
done = true
}
}.visit(parsed, null)
return if (done) argumentNames else null
}
private fun Node.getParentClassName(): String {
val parent = getParentNode()
return if (parent is TypeDeclaration) {
val outerName = parent.getParentClassName()
if (outerName.isNotEmpty()) "$outerName.${parent.getName()}" else parent.getName()
} else ""
}
} | dsl/src/org/jetbrains/android/anko/sources/SourceManager.kt | 3769033161 |
// 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.
@file:JvmName("ExternalSystemJdkComboBoxUtil")
package com.intellij.openapi.externalSystem.service.ui
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkException
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil.USE_PROJECT_JDK
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.roots.ui.configuration.SdkComboBox
import com.intellij.openapi.roots.ui.configuration.SdkListItem
import org.jetbrains.annotations.TestOnly
fun SdkComboBox.getSelectedJdkReference() = resolveJdkReference(selectedItem)
private fun resolveJdkReference(item: SdkListItem?): String? {
return when (item) {
is SdkListItem.ProjectSdkItem -> USE_PROJECT_JDK
is SdkListItem.SdkItem -> item.sdk.name
is SdkListItem.InvalidSdkItem -> item.sdkName
else -> null
}
}
fun SdkComboBox.setSelectedJdkReference(jdkReference: String?) {
selectedItem = resolveSdkItem(jdkReference)
}
private fun SdkComboBox.resolveSdkItem(jdkReference: String?): SdkListItem {
if (jdkReference == null) return showNoneSdkItem()
if (jdkReference == USE_PROJECT_JDK) return showProjectSdkItem()
try {
val selectedJdk = ExternalSystemJdkUtil.resolveJdkName(null, jdkReference)
if (selectedJdk == null) return showInvalidSdkItem(jdkReference)
return findSdkItem(selectedJdk) ?: addAndGetSdkItem(selectedJdk)
}
catch (ex: ExternalSystemJdkException) {
return showInvalidSdkItem(jdkReference)
}
}
private fun SdkComboBox.addAndGetSdkItem(sdk: Sdk): SdkListItem {
SdkConfigurationUtil.addSdk(sdk)
model.sdksModel.addSdk(sdk)
reloadModel()
return findSdkItem(sdk) ?: showInvalidSdkItem(sdk.name)
}
private fun SdkComboBox.findSdkItem(sdk: Sdk): SdkListItem? {
return model.listModel.findSdkItem(sdk)
}
@TestOnly
fun resolveJdkReferenceInTests(item: SdkListItem?) = resolveJdkReference(item)
| platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalSystemJdkComboBoxUtil.kt | 3243216798 |
package pl.ches.citybikes.data.repo
import pl.ches.citybikes.data.disk.entity.Area
import pl.ches.citybikes.data.disk.enums.SourceApi
import rx.Observable
/**
* @author Michał Seroczyński <[email protected]>
*/
interface AreaRepository {
fun get(sourceApi: SourceApi, forceRefresh: Boolean): Observable<List<Area>>
} | app/src/main/kotlin/pl/ches/citybikes/data/repo/AreaRepository.kt | 1598922867 |
// "Replace with 'newFun()'" "true"
// WITH_RUNTIME
class C {
@Deprecated("", ReplaceWith("newFun()"))
fun oldFun(): Int {
return newFun()
}
}
fun newFun(): Int = 0
fun foo(): Int? {
return getC()?.<caret>oldFun()
}
fun getC(): C? = null
| plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/argumentSideEffects/complexExpressionNotUsedSafeCall2Runtime.kt | 585931836 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testIntegration
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.testframework.TestIconMapper
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo.Magnitude.ERROR_INDEX
import com.intellij.execution.testframework.sm.runner.states.TestStateInfo.Magnitude.FAILED_INDEX
import com.intellij.icons.AllIcons
import com.intellij.openapi.vfs.VirtualFileManager
import java.util.*
import javax.swing.Icon
interface RecentTestsPopupEntry {
val icon: Icon?
val presentation: String
val runDate: Date
val failed: Boolean
fun accept(visitor: TestEntryVisitor)
}
abstract class TestEntryVisitor {
open fun visitTest(test: SingleTestEntry) = Unit
open fun visitSuite(suite: SuiteEntry) = Unit
open fun visitRunConfiguration(configuration: RunConfigurationEntry) = Unit
}
private fun String.toClassName(allowedDots: Int): String {
val fqn = VirtualFileManager.extractPath(this)
var dots = 0
return fqn.takeLastWhile {
if (it == '.') dots++
dots <= allowedDots
}
}
class SingleTestEntry(val url: String,
override val runDate: Date,
val runConfiguration: RunnerAndConfigurationSettings,
magnitude: TestStateInfo.Magnitude) : RecentTestsPopupEntry
{
override val presentation = url.toClassName(1)
override val icon = TestIconMapper.getIcon(magnitude)
override val failed = magnitude == ERROR_INDEX || magnitude == FAILED_INDEX
var suite: SuiteEntry? = null
override fun accept(visitor: TestEntryVisitor) {
visitor.visitTest(this)
}
}
class SuiteEntry(val suiteUrl: String,
override val runDate: Date,
var runConfiguration: RunnerAndConfigurationSettings) : RecentTestsPopupEntry {
val tests = hashSetOf<SingleTestEntry>()
val suiteName = VirtualFileManager.extractPath(suiteUrl)
var runConfigurationEntry: RunConfigurationEntry? = null
override val presentation = suiteUrl.toClassName(0)
override val icon: Icon? = AllIcons.RunConfigurations.Junit
override val failed: Boolean
get() {
return tests.find { it.failed } != null
}
fun addTest(test: SingleTestEntry) {
tests.add(test)
test.suite = this
}
override fun accept(visitor: TestEntryVisitor) {
visitor.visitSuite(this)
}
}
class RunConfigurationEntry(val runSettings: RunnerAndConfigurationSettings) : RecentTestsPopupEntry {
val suites = arrayListOf<SuiteEntry>()
override val runDate: Date
get() {
return suites.minBy { it.runDate }!!.runDate
}
override val failed: Boolean
get() {
return suites.find { it.failed } != null
}
fun addSuite(suite: SuiteEntry) {
suites.add(suite)
suite.runConfigurationEntry = this
}
override val presentation: String = runSettings.name
override val icon: Icon? = AllIcons.RunConfigurations.Junit
override fun accept(visitor: TestEntryVisitor) {
visitor.visitRunConfiguration(this)
}
} | java/execution/impl/src/com/intellij/testIntegration/RunConfigurationEntry.kt | 1874027017 |
// WITH_RUNTIME
fun foo() {
val t = java.lang.Float.<caret>compare(5.0, 6.0)
}
| plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/compare/float.kt | 4034464411 |
// 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.groovy.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.configuration.MigrationInfo
import org.jetbrains.kotlin.idea.configuration.getWholeModuleGroup
import org.jetbrains.kotlin.idea.configuration.isLanguageVersionUpdate
import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
import org.jetbrains.kotlin.idea.inspections.ReplaceStringInDocumentFix
import org.jetbrains.kotlin.idea.inspections.gradle.KotlinGradleInspectionVisitor
import org.jetbrains.kotlin.idea.inspections.migration.DEPRECATED_COROUTINES_LIBRARIES_INFORMATION
import org.jetbrains.kotlin.idea.inspections.migration.DeprecatedForKotlinLibInfo
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix
import org.jetbrains.kotlin.idea.versions.LibInfo
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
private val LibInfo.gradleMarker get() = "$groupId:$name:"
@Suppress("SpellCheckingInspection")
class GradleKotlinxCoroutinesDeprecationInspection : BaseInspection(), CleanupLocalInspectionTool, MigrationFix {
override fun isApplicable(migrationInfo: MigrationInfo): Boolean {
return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_2, LanguageVersion.KOTLIN_1_3)
}
override fun buildVisitor(): BaseInspectionVisitor = DependencyFinder()
private open class DependencyFinder : KotlinGradleInspectionVisitor() {
override fun visitClosure(closure: GrClosableBlock) {
super.visitClosure(closure)
val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return
if (dependenciesCall.invokedExpression.text != "dependencies") return
val dependencyEntries = GradleHeuristicHelper.findStatementWithPrefixes(closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS)
for (dependencyStatement in dependencyEntries) {
for (outdatedInfo in DEPRECATED_COROUTINES_LIBRARIES_INFORMATION) {
val dependencyText = dependencyStatement.text
val libMarker = outdatedInfo.lib.gradleMarker
if (!dependencyText.contains(libMarker)) continue
if (!checkKotlinVersion(dependencyStatement.containingFile, outdatedInfo.sinceKotlinLanguageVersion)) {
// Same result will be for all invocations in this file, so exit
return
}
val libVersion =
DifferentStdlibGradleVersionInspection.getResolvedLibVersion(
dependencyStatement.containingFile, outdatedInfo.lib.groupId, listOf(outdatedInfo.lib.name)
) ?: DeprecatedGradleDependencyInspection.libraryVersionFromOrderEntry(
dependencyStatement.containingFile,
outdatedInfo.lib.name
) ?: continue
val updatedVersion = outdatedInfo.versionUpdater.updateVersion(libVersion)
if (libVersion == updatedVersion) {
continue
}
if (dependencyText.contains(updatedVersion)) {
continue
}
val reportOnElement = reportOnElement(dependencyStatement, outdatedInfo)
val fix = if (dependencyText.contains(libVersion)) {
ReplaceStringInDocumentFix(reportOnElement, libVersion, updatedVersion)
} else {
null
}
registerError(
reportOnElement, outdatedInfo.message,
if (fix != null) arrayOf(fix) else emptyArray(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
break
}
}
}
private fun reportOnElement(classpathEntry: GrCallExpression, deprecatedForKotlinInfo: DeprecatedForKotlinLibInfo): PsiElement {
val indexOf = classpathEntry.text.indexOf(deprecatedForKotlinInfo.lib.name)
if (indexOf < 0) return classpathEntry
return classpathEntry.findElementAt(indexOf) ?: classpathEntry
}
private fun checkKotlinVersion(file: PsiFile, languageVersion: LanguageVersion): Boolean {
val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return false
val moduleGroup = module.getWholeModuleGroup()
return moduleGroup.sourceRootModules.any { moduleInGroup ->
moduleInGroup.languageVersionSettings.languageVersion >= languageVersion
}
}
}
} | plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/GradleKotlinxCoroutinesDeprecationInspection.kt | 1638632461 |
// 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 com.intellij.codeInsight.navigation.actions
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.codeInsight.navigation.impl.*
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiFile
import com.intellij.ui.list.createTargetPopup
internal object GotoDeclarationOnlyHandler2 : CodeInsightActionHandler {
override fun startInWriteAction(): Boolean = false
private fun gotoDeclaration(project: Project, editor: Editor, file: PsiFile, offset: Int): GTDActionData? {
return fromGTDProviders(project, editor, offset)
?: gotoDeclaration(file, offset)
}
fun getCtrlMouseInfo(editor: Editor, file: PsiFile, offset: Int): CtrlMouseInfo? {
return gotoDeclaration(file.project, editor, file, offset)?.ctrlMouseInfo()
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.declaration.only")
if (navigateToLookupItem(project, editor, file)) {
return
}
if (EditorUtil.isCaretInVirtualSpace(editor)) {
return
}
val offset = editor.caretModel.offset
val actionResult: GTDActionResult? = try {
underModalProgress(project, CodeInsightBundle.message("progress.title.resolving.reference")) {
gotoDeclaration(project, editor, file, offset)?.result()
}
}
catch (e: IndexNotReadyException) {
DumbService.getInstance(project).showDumbModeNotification(
CodeInsightBundle.message("popup.content.navigation.not.available.during.index.update"))
return
}
if (actionResult == null) {
notifyNowhereToGo(project, editor, file, offset)
}
else {
gotoDeclaration(editor, file, actionResult)
}
}
internal fun gotoDeclaration(editor: Editor, file: PsiFile, actionResult: GTDActionResult) {
when (actionResult) {
is GTDActionResult.SingleTarget -> {
recordAndNavigate(
editor, file, actionResult.navigatable(),
GotoDeclarationAction.getCurrentEventData(), actionResult.navigationProvider
)
}
is GTDActionResult.MultipleTargets -> {
// obtain event data before showing the popup,
// because showing the popup will finish the GotoDeclarationAction#actionPerformed and clear the data
val eventData: List<EventPair<*>> = GotoDeclarationAction.getCurrentEventData()
val popup = createTargetPopup(
CodeInsightBundle.message("declaration.navigation.title"),
actionResult.targets, GTDTarget::presentation
) { (navigatable, _, navigationProvider) ->
recordAndNavigate(editor, file, navigatable(), eventData, navigationProvider)
}
popup.showInBestPositionFor(editor)
}
}
}
private fun recordAndNavigate(
editor: Editor,
file: PsiFile,
navigatable: Navigatable,
eventData: List<EventPair<*>>,
navigationProvider: Any?
) {
if (navigationProvider != null) {
GTDUCollector.recordNavigated(eventData, navigationProvider.javaClass)
}
gotoTarget(editor, file, navigatable)
}
}
| platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationOnlyHandler2.kt | 2809484982 |
fun test(x: Int) {
val f: Function<Int> = <caret>if (x == 0) {
{ 0 }
} else if (x == 1) {
{ 1 }
} else {
{ 2 }
}
} | plugins/kotlin/idea/tests/testData/intentions/branched/ifWhen/ifToWhen/lambdaExpression.kt | 208283036 |
class <caret>
// EXIST: { lookupString: "TopLevelClassName1", itemText: "TopLevelClassName1" } | plugins/kotlin/completion/tests/testData/basic/common/TopLevelClassName1.kt | 3722244085 |
package com.github.kerubistan.kerub.utils
import com.github.kerubistan.kerub.data.EventListener
import com.github.kerubistan.kerub.model.messages.Message
import org.springframework.jms.core.JmsTemplate
class JmsEventListener(val template: JmsTemplate) : EventListener {
override fun send(message: Message) {
template.send { it?.createObjectMessage(message) }
}
} | src/main/kotlin/com/github/kerubistan/kerub/utils/JmsEventListener.kt | 2142176503 |
package com.github.kerubistan.kerub.planner.steps.storage.lvm.pool.create
import com.github.kerubistan.kerub.model.LvmStorageCapability
import com.github.kerubistan.kerub.model.OperatingSystem
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.model.config.HostConfiguration
import com.github.kerubistan.kerub.model.dynamic.CompositeStorageDeviceDynamic
import com.github.kerubistan.kerub.model.dynamic.HostDynamic
import com.github.kerubistan.kerub.model.dynamic.HostStatus
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.steps.AbstractFactoryVerifications
import com.github.kerubistan.kerub.testHost
import com.github.kerubistan.kerub.testHostCapabilities
import com.github.kerubistan.kerub.utils.junix.common.Centos
import io.github.kerubistan.kroki.size.GB
import io.github.kerubistan.kroki.size.TB
import org.junit.Test
import java.util.UUID
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class CreateLvmPoolFactoryTest : AbstractFactoryVerifications(CreateLvmPoolFactory) {
@Test
fun produce() {
assertTrue("when there is no free space on the vg, produce nothing") {
val storageId = UUID.randomUUID()
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
os = OperatingSystem.Linux,
storageCapabilities = listOf(
LvmStorageCapability(
id = storageId,
size = 4.TB,
physicalVolumes = mapOf("/dev/sda" to 2.TB, "/dev/sdb" to 2.TB),
volumeGroupName = "test-vg-1"
)
)
)
)
CreateLvmPoolFactory.produce(
OperationalState.fromLists(
hosts = listOf(host),
hostDyns = listOf(
HostDynamic(
id = host.id,
status = HostStatus.Up,
storageStatus = listOf(
CompositeStorageDeviceDynamic(
id = storageId,
reportedFreeCapacity = 0.TB
)
)
)
),
hostCfgs = listOf(
HostConfiguration(
id = host.id,
storageConfiguration = listOf()
)
)
)
).isEmpty()
}
assertTrue("Actually anything less then 16 GB is considered too small") {
val storageId = UUID.randomUUID()
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
os = OperatingSystem.Linux,
storageCapabilities = listOf(
LvmStorageCapability(
id = storageId,
size = 4.TB,
physicalVolumes = mapOf("/dev/sda" to 2.TB, "/dev/sdb" to 2.TB),
volumeGroupName = "test-vg-1"
)
)
)
)
CreateLvmPoolFactory.produce(
OperationalState.fromLists(
hosts = listOf(host),
hostDyns = listOf(
HostDynamic(
id = host.id,
status = HostStatus.Up,
storageStatus = listOf(
CompositeStorageDeviceDynamic(
id = storageId,
reportedFreeCapacity = 15.GB
)
)
)
),
hostCfgs = listOf(
HostConfiguration(
id = host.id,
storageConfiguration = listOf()
)
)
)
).isEmpty()
}
assertTrue {
val storageId = UUID.randomUUID()
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
os = OperatingSystem.Linux,
distribution = SoftwarePackage.pack(Centos, "7.0"),
installedSoftware = listOf(
SoftwarePackage.pack("lvm2","1.2.3"),
SoftwarePackage.pack("device-mapper-persistent-data","1.2.3")
),
storageCapabilities = listOf(
LvmStorageCapability(
id = storageId,
size = 4.TB,
physicalVolumes = mapOf("/dev/sda" to 2.TB, "/dev/sdb" to 2.TB),
volumeGroupName = "test-vg-1"
)
)
)
)
CreateLvmPoolFactory.produce(
OperationalState.fromLists(
hosts = listOf(host),
hostDyns = listOf(
HostDynamic(
id = host.id,
status = HostStatus.Up,
storageStatus = listOf(
CompositeStorageDeviceDynamic(
id = storageId,
reportedFreeCapacity = 3.TB
)
)
)
),
hostCfgs = listOf(
HostConfiguration(
id = host.id,
storageConfiguration = listOf(
)
)
)
)
).isNotEmpty()
}
assertFalse("") {
val storageId = UUID.randomUUID()
val host = testHost.copy(
capabilities = testHostCapabilities.copy(
os = OperatingSystem.Linux,
storageCapabilities = listOf(
LvmStorageCapability(
id = storageId,
size = 4.TB,
physicalVolumes = mapOf("/dev/sda" to 2.TB, "/dev/sdb" to 2.TB),
volumeGroupName = "test-vg-1"
)
)
)
)
CreateLvmPoolFactory.produce(
OperationalState.fromLists(
hosts = listOf(host),
hostDyns = listOf(
HostDynamic(
id = host.id,
status = HostStatus.Up,
storageStatus = listOf(
CompositeStorageDeviceDynamic(
id = storageId,
reportedFreeCapacity = 3.TB
)
)
)
),
hostCfgs = listOf(
HostConfiguration(
id = host.id,
storageConfiguration = listOf(
)
)
)
)
).isNotEmpty()
}
}
} | src/test/kotlin/com/github/kerubistan/kerub/planner/steps/storage/lvm/pool/create/CreateLvmPoolFactoryTest.kt | 1449082226 |
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.database
import kotlin.js.Promise
import org.jetbrains.elastic.*
import org.jetbrains.utils.*
import org.jetbrains.report.json.*
import org.jetbrains.report.*
fun <T> Iterable<T>.isEmpty() = count() == 0
fun <T> Iterable<T>.isNotEmpty() = !isEmpty()
inline fun <T: Any> T?.str(block: (T) -> String): String =
if (this != null) block(this)
else ""
// Dispatcher to create and control benchmarks indexes separated by some feature.
// Feature can be choosen as often used as filtering entity in case there is no need in separate indexes.
// Default behaviour of dispatcher is working with one index (case when separating isn't needed).
class BenchmarksIndexesDispatcher(connector: ElasticSearchConnector, val feature: String,
featureValues: Iterable<String> = emptyList()) {
// Becnhmarks indexes to work with in case of existing feature values.
private val benchmarksIndexes =
if (featureValues.isNotEmpty())
featureValues.map { it to BenchmarksIndex("benchmarks_${it.replace(" ", "_").toLowerCase()}", connector) }
.toMap()
else emptyMap()
// Single benchmark index.
private val benchmarksSingleInstance =
if (featureValues.isEmpty()) BenchmarksIndex("benchmarks", connector) else null
// Get right index in ES.
private fun getIndex(featureValue: String = "") =
benchmarksSingleInstance ?: benchmarksIndexes[featureValue]
?: error("Used wrong feature value $featureValue. Indexes are separated using next values: ${benchmarksIndexes.keys}")
// Used filter to get data with needed feature value.
var featureFilter: ((String) -> String)? = null
// Get benchmark reports corresponding to needed build number.
fun getBenchmarksReports(buildNumber: String, featureValue: String): Promise<List<String>> {
val queryDescription = """
{
"size": 1000,
"query": {
"bool": {
"must": [
{ "match": { "buildNumber": "$buildNumber" } }
]
}
}
}
"""
return getIndex(featureValue).search(queryDescription, listOf("hits.hits._source")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits")?.let { results ->
results.map {
val element = it as JsonObject
element.getObject("_source").toString()
}
} ?: emptyList()
}
}
// Get benchmarkes names corresponding to needed build number.
fun getBenchmarksList(buildNumber: String, featureValue: String): Promise<List<String>> {
return getBenchmarksReports(buildNumber, featureValue).then { reports ->
reports.map {
val dbResponse = JsonTreeParser.parse(it).jsonObject
parseBenchmarksArray(dbResponse.getArray("benchmarks"))
.map { it.name }
}.flatten()
}
}
// Delete benchmarks from database.
fun deleteBenchmarks(featureValue: String, buildNumber: String? = null): Promise<String> {
// Delete all or for choosen build number.
val matchQuery = buildNumber?.let {
""""match": { "buildNumber": "$it" }"""
} ?: """"match_all": {}"""
val queryDescription = """
{
"query": {
$matchQuery
}
}
""".trimIndent()
return getIndex(featureValue).delete(queryDescription)
}
// Get benchmarks values of needed metric for choosen build number.
fun getSamples(metricName: String, featureValue: String = "", samples: List<String>, buildsCountToShow: Int,
buildNumbers: Iterable<String>? = null,
normalize: Boolean = false): Promise<List<Pair<String, Array<Double?>>>> {
val queryDescription = """
{
"_source": ["buildNumber"],
"size": ${samples.size * buildsCountToShow},
"query": {
"bool": {
"must": [
${buildNumbers.str { builds ->
"""
{ "terms" : { "buildNumber" : [${builds.map { "\"$it\"" }.joinToString()}] } },""" }
}
${featureFilter.str { "${it(featureValue)}," } }
{"nested" : {
"path" : "benchmarks",
"query" : {
"bool": {
"must": [
{ "match": { "benchmarks.metric": "$metricName" } },
{ "terms": { "benchmarks.name": [${samples.map { "\"${it.toLowerCase()}\"" }.joinToString()}] }}
]
}
}, "inner_hits": {
"size": ${samples.size},
"_source": ["benchmarks.name",
"benchmarks.${if (normalize) "normalizedScore" else "score"}"]
}
}
}
]
}
}
}"""
return getIndex(featureValue).search(queryDescription, listOf("hits.hits._source", "hits.hits.inner_hits"))
.then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val results = dbResponse.getObjectOrNull("hits")?.getArrayOrNull("hits")
?: error("Wrong response:\n$responseString")
// Get indexes for provided samples.
val indexesMap = samples.mapIndexed { index, it -> it to index }.toMap()
val valuesMap = buildNumbers?.map {
it to arrayOfNulls<Double?>(samples.size)
}?.toMap()?.toMutableMap() ?: mutableMapOf<String, Array<Double?>>()
// Parse and save values in requested order.
results.forEach {
val element = it as JsonObject
val build = element.getObject("_source").getPrimitive("buildNumber").content
buildNumbers?.let { valuesMap.getOrPut(build) { arrayOfNulls<Double?>(samples.size) } }
element
.getObject("inner_hits")
.getObject("benchmarks")
.getObject("hits")
.getArray("hits").forEach {
val source = (it as JsonObject).getObject("_source")
valuesMap[build]!![indexesMap[source.getPrimitive("name").content]!!] =
source.getPrimitive(if (normalize) "normalizedScore" else "score").double
}
}
valuesMap.toList()
}
}
fun insert(data: JsonSerializable, featureValue: String = "") =
getIndex(featureValue).insert(data)
fun delete(data: String, featureValue: String = "") =
getIndex(featureValue).delete(data)
// Get failures number happned during build.
fun getFailuresNumber(featureValue: String = "", buildNumbers: Iterable<String>? = null): Promise<Map<String, Int>> {
val queryDescription = """
{
"_source": false,
${featureFilter.str {
"""
"query": {
"bool": {
"must": [ ${it(featureValue)} ]
}
}, """
} }
${buildNumbers.str { builds ->
"""
"aggs" : {
"builds": {
"filters" : {
"filters": {
${builds.map { "\"$it\": { \"match\" : { \"buildNumber\" : \"$it\" }}" }
.joinToString(",\n")}
}
},"""
} }
"aggs" : {
"metric_build" : {
"nested" : {
"path" : "benchmarks"
},
"aggs" : {
"metric_samples": {
"filters" : {
"filters": { "samples": { "match": { "benchmarks.status": "FAILED" } } }
},
"aggs" : {
"failed_count": {
"value_count": {
"field" : "benchmarks.score"
}
}
}
}
}
${buildNumbers.str {
""" }
}"""
} }
}
}
}
"""
return getIndex(featureValue).search(queryDescription, listOf("aggregations")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val aggregations = dbResponse.getObjectOrNull("aggregations") ?: error("Wrong response:\n$responseString")
buildNumbers?.let {
// Get failed number for each provided build.
val buckets = aggregations
.getObjectOrNull("builds")
?.getObjectOrNull("buckets")
?: error("Wrong response:\n$responseString")
buildNumbers.map {
it to buckets
.getObject(it)
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObject("failed_count")
.getPrimitive("value")
.int
}.toMap()
} ?: listOf("golden" to aggregations
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObject("failed_count")
.getPrimitive("value")
.int
).toMap()
}
}
// Get geometric mean for benchmarks values of needed metric.
fun getGeometricMean(metricName: String, featureValue: String = "",
buildNumbers: Iterable<String>? = null, normalize: Boolean = false,
excludeNames: List<String> = emptyList()): Promise<List<Pair<String, List<Double?>>>> {
// Filter only with metric or also with names.
val filterBenchmarks = if (excludeNames.isEmpty())
"""
"match": { "benchmarks.metric": "$metricName" }
"""
else """
"bool": {
"must": { "match": { "benchmarks.metric": "$metricName" } },
"must_not": [ ${excludeNames.map { """{ "match_phrase" : { "benchmarks.name" : "$it" } }"""}.joinToString() } ]
}
""".trimIndent()
val queryDescription = """
{
"_source": false,
${featureFilter.str {
"""
"query": {
"bool": {
"must": [ ${it(featureValue)} ]
}
}, """
} }
${buildNumbers.str { builds ->
"""
"aggs" : {
"builds": {
"filters" : {
"filters": {
${builds.map { "\"$it\": { \"match\" : { \"buildNumber\" : \"$it\" }}" }
.joinToString(",\n")}
}
},"""
} }
"aggs" : {
"metric_build" : {
"nested" : {
"path" : "benchmarks"
},
"aggs" : {
"metric_samples": {
"filters" : {
"filters": { "samples": { $filterBenchmarks } }
},
"aggs" : {
"sum_log_x": {
"sum": {
"field" : "benchmarks.${if (normalize) "normalizedScore" else "score"}",
"script" : {
"source": "if (_value == 0) { 0.0 } else { Math.log(_value) }"
}
}
},
"geom_mean": {
"bucket_script": {
"buckets_path": {
"sum_log_x": "sum_log_x",
"x_cnt": "_count"
},
"script": "Math.exp(params.sum_log_x/params.x_cnt)"
}
}
}
}
}
${buildNumbers.str {
""" }
}"""
} }
}
}
}
"""
return getIndex(featureValue).search(queryDescription, listOf("aggregations")).then { responseString ->
val dbResponse = JsonTreeParser.parse(responseString).jsonObject
val aggregations = dbResponse.getObjectOrNull("aggregations") ?: error("Wrong response:\n$responseString")
buildNumbers?.let {
val buckets = aggregations
.getObjectOrNull("builds")
?.getObjectOrNull("buckets")
?: error("Wrong response:\n$responseString")
buildNumbers.map {
it to listOf(buckets
.getObject(it)
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObjectOrNull("geom_mean")
?.getPrimitive("value")
?.double
)
}
} ?: listOf("golden" to listOf(aggregations
.getObject("metric_build")
.getObject("metric_samples")
.getObject("buckets")
.getObject("samples")
.getObjectOrNull("geom_mean")
?.getPrimitive("value")
?.double
)
)
}
}
} | tools/performance-server/src/main/kotlin/database/BenchmarksIndexesDispatcher.kt | 740900350 |
package com.github.kerubistan.kerub.model.dynamic
import com.github.kerubistan.kerub.model.AbstractDataRepresentationTest
import io.github.kerubistan.kroki.size.TB
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import java.util.UUID.randomUUID
class SimpleStorageDeviceDynamicTest : AbstractDataRepresentationTest<SimpleStorageDeviceDynamic>(){
override val testInstances = listOf(
SimpleStorageDeviceDynamic(
id = randomUUID(),
freeCapacity = 4.TB
)
)
override val clazz = SimpleStorageDeviceDynamic::class.java
@Test
fun validations() {
assertThrows<IllegalStateException>("invalid freeCapacity") {
SimpleStorageDeviceDynamic(
id = randomUUID(),
freeCapacity = (-1).toBigInteger()
)
}
}
} | src/test/kotlin/com/github/kerubistan/kerub/model/dynamic/SimpleStorageDeviceDynamicTest.kt | 31042249 |
/**
* Useless one
*/
enum class SomeEnum<caret>
//INFO: <div class='definition'><pre><span style="color:#000080;font-weight:bold;">public</span> <span style="color:#000080;font-weight:bold;">final</span> <span style="color:#000080;font-weight:bold;">enum class</span> <span style="color:#000000;">SomeEnum</span></pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Useless one</p></div><table class='sections'></table><div class='bottom'><icon src="/org/jetbrains/kotlin/idea/icons/kotlin_file.svg"/> OnEnumDeclaration.kt<br/></div>
| plugins/kotlin/idea/tests/testData/editor/quickDoc/OnEnumDeclaration.kt | 3315843242 |
// 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.intellij.plugins.markdown.lang.references.paths
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceOwner
import org.intellij.plugins.markdown.lang.psi.MarkdownElementVisitor
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkDestination
import org.intellij.plugins.markdown.lang.references.paths.github.GithubWikiLocalFileReference
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class MarkdownUnresolvedFileReferenceInspection: LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object: MarkdownElementVisitor() {
override fun visitLinkDestination(linkDestination: MarkdownLinkDestination) {
checkReference(linkDestination, holder)
}
}
}
private fun checkReference(element: PsiElement, holder: ProblemsHolder) {
val references = element.references.asSequence()
val fileReferences = references.filter { it is FileReferenceOwner }
val unresolvedReferences = fileReferences.filter { !shouldSkip(it) && isValidRange(it) && it.resolve() == null }
for (reference in unresolvedReferences) {
holder.registerProblem(
reference,
ProblemsHolder.unresolvedReferenceMessage(reference),
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
)
}
}
private fun isValidRange(reference: PsiReference): Boolean {
val elementRange = reference.element.textRange
return reference.rangeInElement.endOffset <= elementRange.endOffset - elementRange.startOffset
}
/**
* Since we resolve any username and any repository github wiki reference,
* even if the file is not present in this repository,
* the link may still refer to an existing file, so there must not be a warning.
*
* See [GithubWikiLocalFileReferenceProvider.linkPattern].
*/
private fun shouldSkip(reference: PsiReference): Boolean {
return reference is GithubWikiLocalFileReference
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/lang/references/paths/MarkdownUnresolvedFileReferenceInspection.kt | 533895036 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.ui.CollectionComboBoxModel
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
internal class GHAccountsComboBoxModel(accounts: Set<GithubAccount>, selection: GithubAccount?) :
CollectionComboBoxModel<GithubAccount>(accounts.toMutableList(), selection),
GHAccountsHost {
override fun addAccount(server: GithubServerPath, login: String, token: String) {
val account = GithubAuthenticationManager.getInstance().registerAccount(login, server, token)
add(account)
selectedItem = account
}
override fun isAccountUnique(login: String, server: GithubServerPath): Boolean =
GithubAuthenticationManager.getInstance().isAccountUnique(login, server)
} | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GHAccountsComboBoxModel.kt | 3367804681 |
// 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.vcs.log.ui.table
import com.intellij.ui.hover.TableHoverListener
import com.intellij.ui.popup.list.SelectablePanel
import com.intellij.ui.popup.list.SelectablePanel.Companion.wrap
import com.intellij.ui.popup.list.SelectablePanel.SelectionArcCorners
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.annotations.ApiStatus
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JTable
import javax.swing.table.TableCellRenderer
@ApiStatus.Internal
internal class VcsLogNewUiTableCellRenderer(val delegate: TableCellRenderer) : TableCellRenderer, VcsLogCellRenderer {
private var isRight = false
private var isLeft = false
private var cachedRenderer: JComponent? = null
private lateinit var selectablePanel: SelectablePanel
override fun getTableCellRendererComponent(table: JTable,
value: Any,
isSelected: Boolean,
hasFocus: Boolean,
row: Int,
column: Int): Component {
val columnRenderer = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) as JComponent
// +1 – root column selection is not supported right now
val isLeftColumn = column == ROOT_COLUMN_INDEX + 1
val isRightColumn = column == table.columnCount - 1
updateSelectablePanelIfNeeded(isRightColumn, isLeftColumn, columnRenderer)
selectablePanel.apply {
background = getUnselectedBackground(table, row, column, isSelected, hasFocus)
selectionColor = if (isSelected) VcsLogGraphTable.getSelectionBackground(table.hasFocus()) else null
selectionArc = 0
selectionArcCorners = SelectionArcCorners.ALL
if (isSelected && (isLeft || isRight)) {
getSelectedRowType(table, row).tune(selectablePanel, isLeft, isRight)
}
}
return selectablePanel
}
private fun updateSelectablePanelIfNeeded(isRightColumn: Boolean, isLeftColumn: Boolean, columnRenderer: JComponent) {
if (isRight != isRightColumn || isLeft != isLeftColumn || cachedRenderer !== columnRenderer) {
cachedRenderer = columnRenderer
isLeft = isLeftColumn
isRight = isRightColumn
selectablePanel = wrap(createWrappablePanel(columnRenderer, isLeft, isRight))
}
}
private fun createWrappablePanel(renderer: JComponent, isLeft: Boolean = false, isRight: Boolean = false): BorderLayoutPanel {
val panel = BorderLayoutPanel().addToCenter(renderer).andTransparent()
if (isLeft) {
panel.addToLeft(createEmptyPanel())
}
if (isRight) {
panel.addToRight(createEmptyPanel())
}
return panel
}
override fun getCellController(): VcsLogCellController? {
if (cachedRenderer != null && cachedRenderer is VcsLogCellRenderer) {
return (cachedRenderer as VcsLogCellRenderer).cellController
}
return null
}
private fun getUnselectedBackground(table: JTable, row: Int, column: Int, isSelected: Boolean, hasFocus: Boolean): Color? {
val hovered = if (isSelected) false else row == TableHoverListener.getHoveredRow(table)
return (table as VcsLogGraphTable)
.getStyle(row, column, hasFocus, false, hovered)
.background
}
private fun getSelectedRowType(table: JTable, row: Int): SelectedRowType {
val selection = table.selectionModel
val max = selection.maxSelectionIndex
val min = selection.minSelectionIndex
if (max == min) return SelectedRowType.SINGLE
val isTopRowSelected = selection.isSelectedIndex(row - 1)
val isBottomRowSelected = selection.isSelectedIndex(row + 1)
return when {
isTopRowSelected && isBottomRowSelected -> SelectedRowType.MIDDLE
isTopRowSelected -> SelectedRowType.BOTTOM
isBottomRowSelected -> SelectedRowType.TOP
else -> SelectedRowType.SINGLE
}
}
companion object {
private val INSETS
get() = 4
private val ARC
get() = JBUI.CurrentTheme.Popup.Selection.ARC.get()
private fun createEmptyPanel(): JPanel = object : JPanel(null) {
init {
isOpaque = false
}
override fun getPreferredSize(): Dimension = JBDimension(8, 0)
}
private const val ROOT_COLUMN_INDEX = 0
}
private enum class SelectedRowType {
SINGLE {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = ARC
selectionArcCorners = when {
isLeft && isRight -> SelectionArcCorners.ALL
isLeft -> SelectionArcCorners.LEFT
isRight -> SelectionArcCorners.RIGHT
else -> SelectionArcCorners.ALL
}
}
},
TOP {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = ARC
selectionArcCorners = when {
isLeft && isRight -> SelectionArcCorners.TOP
isLeft -> SelectionArcCorners.TOP_LEFT
isRight -> SelectionArcCorners.TOP_RIGHT
else -> SelectionArcCorners.ALL
}
}
},
MIDDLE {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = 0
}
},
BOTTOM {
override fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean) {
selectionArc = ARC
selectionArcCorners = when {
isLeft && isRight -> SelectionArcCorners.BOTTOM
isLeft -> SelectionArcCorners.BOTTOM_LEFT
isRight -> SelectionArcCorners.BOTTOM_RIGHT
else -> SelectionArcCorners.ALL
}
}
};
fun tune(selectablePanel: SelectablePanel, isLeft: Boolean, isRight: Boolean) {
selectablePanel.selectionInsets = JBUI.insets(0, if (isLeft) INSETS else 0, 0, if (isRight) INSETS else 0)
selectablePanel.tuneArcAndCorners(isLeft, isRight)
}
protected abstract fun SelectablePanel.tuneArcAndCorners(isLeft: Boolean, isRight: Boolean)
}
} | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/VcsLogNewUiTableCellRenderer.kt | 1411109363 |
/*
* 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.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object FilterChipTokens {
val ContainerHeight = 32.0.dp
val ContainerShape = ShapeKeyTokens.CornerSmall
val ContainerSurfaceTintLayerColor = ColorSchemeKeyTokens.SurfaceTint
val DisabledLabelTextColor = ColorSchemeKeyTokens.OnSurface
const val DisabledLabelTextOpacity = 0.38f
val DraggedContainerElevation = ElevationTokens.Level4
val ElevatedContainerElevation = ElevationTokens.Level1
val ElevatedDisabledContainerColor = ColorSchemeKeyTokens.OnSurface
val ElevatedDisabledContainerElevation = ElevationTokens.Level0
const val ElevatedDisabledContainerOpacity = 0.12f
val ElevatedFocusContainerElevation = ElevationTokens.Level1
val ElevatedHoverContainerElevation = ElevationTokens.Level2
val ElevatedPressedContainerElevation = ElevationTokens.Level1
val ElevatedSelectedContainerColor = ColorSchemeKeyTokens.SecondaryContainer
val ElevatedUnselectedContainerColor = ColorSchemeKeyTokens.Surface
val FlatContainerElevation = ElevationTokens.Level0
val FlatDisabledSelectedContainerColor = ColorSchemeKeyTokens.OnSurface
const val FlatDisabledSelectedContainerOpacity = 0.12f
val FlatDisabledUnselectedOutlineColor = ColorSchemeKeyTokens.OnSurface
const val FlatDisabledUnselectedOutlineOpacity = 0.12f
val FlatSelectedContainerColor = ColorSchemeKeyTokens.SecondaryContainer
val FlatSelectedFocusContainerElevation = ElevationTokens.Level0
val FlatSelectedHoverContainerElevation = ElevationTokens.Level1
val FlatSelectedOutlineWidth = 0.0.dp
val FlatSelectedPressedContainerElevation = ElevationTokens.Level0
val FlatUnselectedFocusContainerElevation = ElevationTokens.Level0
val FlatUnselectedFocusOutlineColor = ColorSchemeKeyTokens.OnSurfaceVariant
val FlatUnselectedHoverContainerElevation = ElevationTokens.Level0
val FlatUnselectedOutlineColor = ColorSchemeKeyTokens.Outline
val FlatUnselectedOutlineWidth = 1.0.dp
val FlatUnselectedPressedContainerElevation = ElevationTokens.Level0
val LabelTextFont = TypographyKeyTokens.LabelLarge
val SelectedDraggedLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedFocusLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedHoverLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedPressedLabelTextColor = ColorSchemeKeyTokens.OnSecondaryContainer
val UnselectedDraggedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedFocusLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedHoverLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedPressedLabelTextColor = ColorSchemeKeyTokens.OnSurfaceVariant
val DisabledIconColor = ColorSchemeKeyTokens.OnSurface
const val DisabledIconOpacity = 0.38f
val IconSize = 18.0.dp
val SelectedDraggedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedFocusIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedHoverIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val SelectedPressedIconColor = ColorSchemeKeyTokens.OnSecondaryContainer
val UnselectedDraggedIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedFocusIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedHoverIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
val UnselectedPressedIconColor = ColorSchemeKeyTokens.OnSurfaceVariant
} | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/FilterChipTokens.kt | 1813291048 |
/*
* 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.tv.foundation.lazy.list
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.layout.IntervalList
import androidx.compose.foundation.lazy.layout.LazyLayoutIntervalContent
import androidx.compose.foundation.lazy.layout.MutableIntervalList
import androidx.compose.runtime.Composable
import androidx.tv.foundation.ExperimentalTvFoundationApi
@Suppress("IllegalExperimentalApiUsage") // TODO (b/233188423): Address before moving to beta
@OptIn(ExperimentalFoundationApi::class)
internal class TvLazyListScopeImpl : TvLazyListScope {
private val _intervals = MutableIntervalList<LazyListIntervalContent>()
val intervals: IntervalList<LazyListIntervalContent> = _intervals
private var _headerIndexes: MutableList<Int>? = null
val headerIndexes: List<Int> get() = _headerIndexes ?: emptyList()
override fun items(
count: Int,
key: ((index: Int) -> Any)?,
contentType: (index: Int) -> Any?,
itemContent: @Composable TvLazyListItemScope.(index: Int) -> Unit
) {
_intervals.addInterval(
count,
LazyListIntervalContent(
key = key,
type = contentType,
item = itemContent
)
)
}
override fun item(
key: Any?,
contentType: Any?,
content: @Composable TvLazyListItemScope.() -> Unit
) {
_intervals.addInterval(
1,
LazyListIntervalContent(
key = if (key != null) { _: Int -> key } else null,
type = { contentType },
item = { content() }
)
)
}
@ExperimentalTvFoundationApi
override fun stickyHeader(
key: Any?,
contentType: Any?,
content: @Composable TvLazyListItemScope.() -> Unit
) {
val headersIndexes = _headerIndexes ?: mutableListOf<Int>().also {
_headerIndexes = it
}
headersIndexes.add(_intervals.size)
item(key, contentType, content)
}
}
@OptIn(ExperimentalFoundationApi::class)
internal class LazyListIntervalContent(
override val key: ((index: Int) -> Any)?,
override val type: ((index: Int) -> Any?),
val item: @Composable TvLazyListItemScope.(index: Int) -> Unit
) : LazyLayoutIntervalContent
| tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/list/TvLazyListScopeImpl.kt | 2159282883 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.vo
import androidx.room.compiler.processing.XMethodElement
import androidx.room.solver.shortcut.binder.DeleteOrUpdateMethodBinder
/**
* Base class for shortcut methods in @DAO.
*/
abstract class DeleteOrUpdateShortcutMethod(
val element: XMethodElement,
val entities: Map<String, ShortcutEntity>,
val parameters: List<ShortcutQueryParameter>,
val methodBinder: DeleteOrUpdateMethodBinder?
)
| room/room-compiler/src/main/kotlin/androidx/room/vo/DeleteOrUpdateShortcutMethod.kt | 2649869256 |
// 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.jetbrains.python.sdk.flavors
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.File
class MayaSdkFlavor private constructor() : CPythonSdkFlavor<PyFlavorData.Empty>() {
override fun getFlavorDataClass(): Class<PyFlavorData.Empty> = PyFlavorData.Empty::class.java
override fun isValidSdkHome(path: String): Boolean {
val file = File(path)
return file.isFile && isValidSdkPath(file) || isMayaFolder(file)
}
override fun isValidSdkPath(file: File): Boolean {
val name = FileUtil.getNameWithoutExtension(file).toLowerCase()
return name.startsWith("mayapy")
}
override fun getSdkPath(path: VirtualFile): VirtualFile? {
if (isMayaFolder(File(path.path))) {
return path.findFileByRelativePath("Contents/bin/mayapy")
}
return path
}
companion object {
val INSTANCE: MayaSdkFlavor = MayaSdkFlavor()
private fun isMayaFolder(file: File): Boolean {
return file.isDirectory && file.name == "Maya.app"
}
}
}
class MayaFlavorProvider: PythonFlavorProvider {
override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE
}
| python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt | 3858245930 |
// FIR_IDENTICAL
class `A$B` {
class `$$$` {
class `$`
}
}
object `$$$$B$C`
fun f() {
fun g() {
class `A$B` {
inner class `C$D`
}
}
}
| plugins/kotlin/idea/tests/testData/checker/regression/DollarsInName.kt | 3249663732 |
package io.github.sdsstudios.ScoreKeeper.Game
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import io.github.sdsstudios.ScoreKeeper.Database.Dao.GameDao
import io.github.sdsstudios.ScoreKeeper.TimeLimit.Companion.DEFAULT_TIME
import java.util.*
import kotlin.coroutines.experimental.buildSequence
/**
* Created by sethsch1 on 29/10/17.
*/
@Entity(tableName = GameDao.TABLE_NAME)
open class Game(@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Long = 0,
@ColumnInfo(name = GameDao.KEY_CREATION_DATE)
var creationDate: Date = Date(),
@ColumnInfo(name = GameDao.KEY_LAST_PLAYED_DATE)
var lastPlayedDate: Date = creationDate,
@ColumnInfo(name = GameDao.KEY_WINNING_SCORE)
var scoreToWin: Int? = null,
@ColumnInfo(name = GameDao.KEY_SCORE_INTERVAL)
var scoreInterval: Int = 1,
@ColumnInfo(name = GameDao.KEY_SCORE_DIFF_TO_WIN)
var scoreDiffToWin: Int? = null,
@ColumnInfo(name = GameDao.KEY_NUM_SETS_CHOSEN)
var numSetsChosen: Int = 1,
@ColumnInfo(name = GameDao.KEY_NUM_SETS_PLAYED)
var numSetsPlayed: Int = 1,
@ColumnInfo(name = GameDao.KEY_STARTING_SCORE)
var startingScore: Int = 0,
@ColumnInfo(name = GameDao.KEY_COMPLETED)
var completed: Boolean = false,
@ColumnInfo(name = GameDao.KEY_REVERSE_SCORING)
var reverseScoring: Boolean = false,
@ColumnInfo(name = GameDao.KEY_USE_STOPWATCH)
var useStopwatch: Boolean = false,
@ColumnInfo(name = GameDao.KEY_NOTES)
var notes: String = "",
@ColumnInfo(name = GameDao.KEY_DURATION)
var duration: String = DEFAULT_TIME,
@ColumnInfo(name = GameDao.KEY_TITLE)
var title: String = "The Game With No Name",
@ColumnInfo(name = GameDao.KEY_TIME_LIMIT)
var timeLimit: String = DEFAULT_TIME
) : Comparable<Game> {
open fun createSetsForPlayers(playerIds: List<Long>): Array<Scores> = buildSequence {
playerIds.forEach { id ->
yield(Scores(
playerId = id,
gameId = [email protected],
scores = mutableListOf(startingScore.toLong())
))
}
}.toList().toTypedArray()
fun newTimeLimit(timeLimitString: String) {
timeLimit = timeLimitString
completed = false
}
fun haveAllSetsBeenPlayed() = numSetsPlayed == numSetsChosen
fun usesSets() = numSetsChosen > 1
override fun compareTo(other: Game): Int =
other.lastPlayedDate.compareTo(this.lastPlayedDate)
} | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Game/Game.kt | 3939478255 |
// 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.codeInsight.hints
import com.intellij.configurationStore.deserializeInto
import com.intellij.configurationStore.serialize
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.messages.Topic
import org.jdom.Element
import java.util.*
@State(name = "InlayHintsSettings", storages = [Storage("editor.xml")], category = SettingsCategory.CODE)
class InlayHintsSettings : PersistentStateComponent<InlayHintsSettings.State> {
companion object {
@JvmStatic
fun instance(): InlayHintsSettings {
return ApplicationManager.getApplication().getService(InlayHintsSettings::class.java)
}
/**
* Inlay hints settings changed.
*/
@Topic.AppLevel
@JvmStatic
val INLAY_SETTINGS_CHANGED: Topic<SettingsListener> = Topic(SettingsListener::class.java, Topic.BroadcastDirection.TO_DIRECT_CHILDREN)
}
private val listener: SettingsListener
get() = ApplicationManager.getApplication().messageBus.syncPublisher(INLAY_SETTINGS_CHANGED)
private var myState = State()
private val lock = Any()
class State {
// explicitly enabled languages (because of enabled by default setting, we can't say that everything which is not disabled is enabled)
var enabledHintProviderIds: TreeSet<String> = sortedSetOf()
var disabledHintProviderIds: TreeSet<String> = sortedSetOf()
// We can't store Map<String, Any> directly, because values deserialized as Object
var settingsMapElement: Element = Element("settingsMapElement")
var lastViewedProviderKeyId: String? = null
var isEnabled: Boolean = true
var disabledLanguages: TreeSet<String> = sortedSetOf()
}
// protected by lock
private val myCachedSettingsMap: MutableMap<String, Any> = hashMapOf()
// protected by lock
private val isEnabledByDefaultIdsCache: MutableMap<String, Boolean> = hashMapOf()
init {
InlayHintsProviderExtension.inlayProviderName.addChangeListener(Runnable {
synchronized(lock) {
isEnabledByDefaultIdsCache.clear()
}
}, null)
}
fun changeHintTypeStatus(key: SettingsKey<*>, language: Language, enable: Boolean) {
synchronized(lock) {
val id = key.getFullId(language)
if (enable) {
if (!isEnabledByDefault(key, language)) {
myState.enabledHintProviderIds.add(id)
}
myState.disabledHintProviderIds.remove(id)
}
else {
myState.enabledHintProviderIds.remove(id)
myState.disabledHintProviderIds.add(id)
}
}
listener.settingsChanged()
}
fun setHintsEnabledForLanguage(language: Language, enabled: Boolean) {
val settingsChanged = synchronized(lock) {
val id = language.id
if (enabled) {
myState.disabledLanguages.remove(id)
}
else {
myState.disabledLanguages.add(id)
}
}
if (settingsChanged) {
listener.languageStatusChanged()
listener.settingsChanged()
}
}
fun saveLastViewedProviderId(providerId: String): Unit = synchronized(lock) {
myState.lastViewedProviderKeyId = providerId
}
fun getLastViewedProviderId() : String? {
return myState.lastViewedProviderKeyId
}
fun setEnabledGlobally(enabled: Boolean) {
val settingsChanged = synchronized(lock) {
if (myState.isEnabled != enabled) {
myState.isEnabled = enabled
listener.globalEnabledStatusChanged(enabled)
true
} else {
false
}
}
if (settingsChanged) {
listener.settingsChanged()
}
}
fun hintsEnabledGlobally() : Boolean = synchronized(lock) {
return myState.isEnabled
}
/**
* @param createSettings is a setting, that was obtained from createSettings method of provider
*/
fun <T: Any> findSettings(key: SettingsKey<T>, language: Language, createSettings: ()->T): T = synchronized(lock) {
val fullId = key.getFullId(language)
return getSettingCached(fullId, createSettings)
}
fun <T: Any> storeSettings(key: SettingsKey<T>, language: Language, value: T) {
synchronized(lock){
val fullId = key.getFullId(language)
myCachedSettingsMap[fullId] = value as Any
val element = myState.settingsMapElement.clone()
element.removeChild(fullId)
val serialized = serialize(value)
if (serialized == null) {
myState.settingsMapElement = element
}
else {
val storeElement = Element(fullId)
val wrappedSettingsElement = storeElement.addContent(serialized)
myState.settingsMapElement = element.addContent(wrappedSettingsElement)
element.sortAttributes(compareBy { it.name })
}
}
listener.settingsChanged()
}
fun hintsEnabled(language: Language) : Boolean = synchronized(lock) {
return language.id !in myState.disabledLanguages
}
fun hintsShouldBeShown(language: Language) : Boolean = synchronized(lock) {
if (!hintsEnabledGlobally()) return false
return hintsEnabled(language)
}
fun hintsEnabled(key: SettingsKey<*>, language: Language) : Boolean {
synchronized(lock) {
if (explicitlyDisabled(language, key)) {
return false
}
if (isEnabledByDefault(key, language)) {
return true
}
return key.getFullId(language) in state.enabledHintProviderIds
}
}
private fun explicitlyDisabled(language: Language, key: SettingsKey<*>): Boolean {
var lang: Language? = language
while (lang != null) {
if (key.getFullId(lang) in myState.disabledHintProviderIds) {
return true
}
lang = lang.baseLanguage
}
return false
}
fun hintsShouldBeShown(key: SettingsKey<*>, language: Language): Boolean = synchronized(lock) {
return hintsEnabledGlobally() &&
hintsEnabled(language) &&
hintsEnabled(key, language)
}
override fun getState(): State = synchronized(lock) {
return myState
}
override fun loadState(state: State): Unit = synchronized(lock) {
val elementChanged = myState.settingsMapElement != state.settingsMapElement
if (elementChanged) {
myCachedSettingsMap.clear()
}
myState = state
}
// may return parameter settings object or cached object
private fun <T : Any> getSettingCached(id: String, settings: ()->T): T {
synchronized(lock) {
@Suppress("UNCHECKED_CAST")
val cachedValue = myCachedSettingsMap[id] as T?
if (cachedValue != null) return cachedValue
val notCachedSettings = getSettingNotCached(id, settings())
myCachedSettingsMap[id] = notCachedSettings
return notCachedSettings
}
}
private fun <T : Any> getSettingNotCached(id: String, settings: T): T {
val state = myState.settingsMapElement
val settingsElement = state.getChild(id)
if (settingsElement == null) return settings
val settingsElementChildren= settingsElement.children
if (settingsElementChildren.isEmpty()) return settings
settingsElementChildren.first().deserializeInto(settings)
return settings
}
// must be called under lock
private fun isEnabledByDefault(key: SettingsKey<*>, language: Language) : Boolean {
return isEnabledByDefaultIdsCache.computeIfAbsent(key.getFullId(language)) { computeIsEnabledByDefault(it) }
}
private fun computeIsEnabledByDefault(id: String) : Boolean {
val bean = InlayHintsProviderExtension.inlayProviderName.extensionList
.firstOrNull {
val keyId = it.settingsKeyId ?: return@firstOrNull false
SettingsKey.getFullId(it.language!!, keyId) == id
} ?: return true
return bean.isEnabledByDefault
}
interface SettingsListener {
/**
* @param newEnabled whether inlay hints are globally switched on or off now
*/
fun globalEnabledStatusChanged(newEnabled: Boolean) {}
/**
* Called, when hints are enabled/disabled for some language
*/
fun languageStatusChanged() {}
/**
* Called when any settings in inlay hints were changed
*/
fun settingsChanged() {}
}
}
| platform/lang-api/src/com/intellij/codeInsight/hints/InlayHintsSettings.kt | 2592738553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.