repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
programmerr47/ganalytics
sample/src/main/java/com/github/programmerr47/ganalyticssample/analytic.kt
1
988
package com.github.programmerr47.ganalyticssample import com.github.programmerr47.ganalytics.core.* interface Analytics { val car: AnalyticsCar val seller: AnalyticsSeller @HasPrefix val customer: AnalyticsCustomer } interface AnalyticsCar { fun isSold() fun type(carType: CarType) fun price(price: Price) } @HasPrefix interface AnalyticsSeller { @NoPrefix fun isFair() fun sellCar(car: Car) @Action("add_car") fun addNewCarToSellList(car: Car) } interface AnalyticsCustomer { fun buyCar(@Label(CustomerCarConverter::class) car: Car) fun startedSearching() fun endedSearching() } //--------------------------------- class Car(val type: CarType, val price: Price) enum class CarType { SEDAN, HATCHBACK, SUV, CROSSOVER } class Price(val amount: Int, val currency: String) object CustomerCarConverter : TypedLabelConverter<Car> { override fun convertTyped(label: Car) = label.run { "$type with price = ${price.amount}" } }
mit
pkleimann/livingdoc2
livingdoc-repository-file/src/main/kotlin/org/livingdoc/repositories/format/HtmlFormat.kt
1
4923
package org.livingdoc.repositories.format import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.select.Elements import org.livingdoc.repositories.DocumentFormat import org.livingdoc.repositories.HtmlDocument import org.livingdoc.repositories.ParseException import org.livingdoc.repositories.model.decisiontable.DecisionTable import org.livingdoc.repositories.model.decisiontable.Field import org.livingdoc.repositories.model.decisiontable.Header import org.livingdoc.repositories.model.decisiontable.Row import org.livingdoc.repositories.model.scenario.Scenario import org.livingdoc.repositories.model.scenario.Step import java.io.InputStream import java.nio.charset.Charset class HtmlFormat : DocumentFormat { private val supportedFileExtensions = setOf("html", "htm") override fun canHandle(fileExtension: String): Boolean { return supportedFileExtensions.contains(fileExtension.toLowerCase()) } override fun parse(stream: InputStream): HtmlDocument { val streamContent = stream.readBytes().toString(Charset.defaultCharset()) val document = Jsoup.parse(streamContent) val elements = parseTables(document) + parseLists(document) // TODO: provide elements in order they occur inside the original source document return HtmlDocument(elements, document) } private fun parseTables(document: Document): List<DecisionTable> { val tableElements = document.getElementsByTag("table") return parseTableElements(tableElements) } private fun parseTableElements(tableElements: Elements): List<DecisionTable> { fun tableHasAtLeastTwoRows(table: Element) = table.getElementsByTag("tr").size > 1 return tableElements .filter(::tableHasAtLeastTwoRows) .map(::parseTableToDecisionTable) } private fun parseTableToDecisionTable(table: Element): DecisionTable { val tableRows = table.getElementsByTag("tr") val headers = extractHeadersFromFirstRow(tableRows) val dataRows = parseDataRow(headers, tableRows) return DecisionTable(headers, dataRows) } private fun extractHeadersFromFirstRow(tableRows: Elements): List<Header> { val firstRowContainingHeaders = tableRows[0] val headers = firstRowContainingHeaders.children() .filter(::isHeaderOrDataCell) .map(Element::text) .map(::Header).toList() if (headers.size != headers.distinct().size) { throw ParseException("Headers must contains only unique values: $headers") } return headers } private fun parseDataRow(headers: List<Header>, tableRows: Elements): List<Row> { val dataRows = mutableListOf<Row>() tableRows.drop(1).forEachIndexed { rowIndex, row -> val dataCells = row.children().filter(::isHeaderOrDataCell) if (headers.size != dataCells.size) { throw ParseException( "Header count must match the data cell count in data row ${rowIndex + 1}. Headers: ${headers.map( Header::name )}, DataCells: $dataCells" ) } val rowData = headers.mapIndexed { headerIndex, headerName -> headerName to Field(dataCells[headerIndex].text()) }.toMap() dataRows.add(Row(rowData)) } return dataRows } private fun isHeaderOrDataCell(it: Element) = it.tagName() == "th" || it.tagName() == "td" private fun parseLists(document: Document): List<Scenario> { val unorderedListElements = document.getElementsByTag("ul") val orderedListElements = document.getElementsByTag("ol") return parseListElements(unorderedListElements) + parseListElements(orderedListElements) } private fun parseListElements(htmlListElements: Elements): List<Scenario> { fun listHasAtLeastTwoItems(htmlList: Element) = htmlList.getElementsByTag("li").size > 1 return htmlListElements .filter(::listHasAtLeastTwoItems) .map(::parseListIntoScenario) } private fun parseListIntoScenario(htmlList: Element): Scenario { verifyZeroNestedLists(htmlList) val listItemElements = htmlList.getElementsByTag("li") return Scenario(parseListItems(listItemElements)) } private fun parseListItems(listItemElements: Elements): List<Step> { return listItemElements.map { Step(it.text()) }.toList() } private fun verifyZeroNestedLists(htmlList: Element) { val innerHtml = htmlList.html() if (innerHtml.contains("<ul") || innerHtml.contains("<ol")) { throw ParseException("Nested lists within unordered or ordered lists are not supported: ${htmlList.html()}") } } }
apache-2.0
dahlstrom-g/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/plugins/ClassLoaderConfiguratorTest.kt
1
6210
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package com.intellij.ide.plugins import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.ide.plugins.cl.PluginClassLoader import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.BuildNumber import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.assertions.Assertions.assertThatThrownBy import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.util.io.directoryStreamIfExists import org.jetbrains.xxh3.Xxh3 import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import java.nio.file.Path import java.util.* import java.util.function.Supplier private val buildNumber = BuildNumber.fromString("2042.0")!! internal class ClassLoaderConfiguratorTest { @Rule @JvmField val name = TestName() @Rule @JvmField val inMemoryFs = InMemoryFsRule() @Test fun `plugin must be after child`() { val pluginId = PluginId.getId("org.jetbrains.kotlin") val emptyPath = Path.of("") val plugins = arrayOf( IdeaPluginDescriptorImpl(RawPluginDescriptor(), emptyPath, isBundled = false, id = pluginId, moduleName = null), IdeaPluginDescriptorImpl(RawPluginDescriptor(), emptyPath, isBundled = false, id = PluginId.getId("org.jetbrains.plugins.gradle"), moduleName = null), IdeaPluginDescriptorImpl(RawPluginDescriptor(), emptyPath, isBundled = false, id = pluginId, moduleName = "kotlin.gradle.gradle-java"), IdeaPluginDescriptorImpl(RawPluginDescriptor(), emptyPath, isBundled = false, id = pluginId, moduleName = "kotlin.compiler-plugins.annotation-based-compiler-support.gradle"), ) sortDependenciesInPlace(plugins) assertThat(plugins.last().moduleName).isNull() } @Test fun packageForOptionalMustBeSpecified() { assertThatThrownBy { loadPlugins(modulePackage = null) }.hasMessageContaining("Package is not specified") .hasMessageContaining("package=null") } @Test fun packageForOptionalMustBeDifferent() { assertThatThrownBy { loadPlugins(modulePackage = "com.example") }.hasMessageContaining("Package prefix com.example is already used") .hasMessageContaining("com.example") } @Test fun packageMustBeUnique() { assertThatThrownBy { loadPlugins(modulePackage = "com.bar") }.hasMessageContaining("Package prefix com.bar is already used") .hasMessageContaining("package=com.bar") } @Test fun regularPluginClassLoaderIsUsedIfPackageSpecified() { val plugin = loadPlugins(modulePackage = "com.example.extraSupportedFeature") .enabledPlugins .get(1) assertThat(plugin.content.modules.get(0).requireDescriptor().pluginClassLoader).isInstanceOf(PluginAwareClassLoader::class.java) } @Test @Suppress("PluginXmlValidity") fun `inject content module if another plugin specifies dependency in old format`() { val rootDir = inMemoryFs.fs.getPath("/") plugin(rootDir, """ <idea-plugin package="com.foo"> <id>1-foo</id> <content> <module name="com.example.sub"/> </content> </idea-plugin> """) module(rootDir, "1-foo", "com.example.sub", """ <idea-plugin package="com.foo.sub"> </idea-plugin> """) plugin(rootDir, """ <idea-plugin> <id>2-bar</id> <depends>1-foo</depends> </idea-plugin> """) val plugins = loadDescriptors(rootDir).enabledPlugins assertThat(plugins).hasSize(2) val barPlugin = plugins.get(1) assertThat(barPlugin.pluginId.idString).isEqualTo("2-bar") val classLoaderConfigurator = ClassLoaderConfigurator(PluginSetBuilder(plugins).createPluginSetWithEnabledModulesMap()) classLoaderConfigurator.configure() assertThat((barPlugin.pluginClassLoader as PluginClassLoader)._getParents().map { it.descriptorPath }) .containsExactly("com.example.sub.xml", null) } @Suppress("PluginXmlValidity") private fun loadPlugins(modulePackage: String?): PluginLoadingResult { val rootDir = inMemoryFs.fs.getPath("/") // toUnsignedLong - avoid `-` symbol val pluginIdSuffix = Integer.toUnsignedLong( Xxh3.hash32(javaClass.name + name.methodName)).toString(36) val dependencyId = "p_dependency_$pluginIdSuffix" plugin(rootDir, """ <idea-plugin package="com.bar"> <id>$dependencyId</id> <extensionPoints> <extensionPoint qualifiedName="bar.barExtension" beanClass="com.intellij.util.KeyedLazyInstanceEP" dynamic="true"/>" </extensionPoints> </idea-plugin> """) val dependentPluginId = "p_dependent_$pluginIdSuffix" plugin(rootDir, """ <idea-plugin package="com.example"> <id>$dependentPluginId</id> <content> <module name="com.example.sub"/> </content> </idea-plugin> """) module(rootDir, dependentPluginId, "com.example.sub", """ <idea-plugin ${modulePackage?.let { """package="$it"""" } ?: ""}> <!-- dependent must not be empty, add some extension --> <extensionPoints> <extensionPoint qualifiedName="bar.barExtension" beanClass="com.intellij.util.KeyedLazyInstanceEP" dynamic="true"/>" </extensionPoints> </idea-plugin> """) val loadResult = loadDescriptors(rootDir) val plugins = loadResult.enabledPlugins assertThat(plugins).hasSize(2) val classLoaderConfigurator = ClassLoaderConfigurator(PluginSetBuilder(plugins).createPluginSetWithEnabledModulesMap()) classLoaderConfigurator.configure() return loadResult } } private fun loadDescriptors(dir: Path): PluginLoadingResult { val result = PluginLoadingResult(brokenPluginVersions = emptyMap(), productBuildNumber = Supplier { buildNumber }) val context = DescriptorListLoadingContext(disabledPlugins = Collections.emptySet(), result = result) // constant order in tests val paths = dir.directoryStreamIfExists { it.sorted() }!! context.use { for (file in paths) { result.add(loadDescriptor(file, context) ?: continue, false) } } return result }
apache-2.0
intellij-solidity/intellij-solidity
src/main/kotlin/me/serce/solidity/ide/folding.kt
1
1883
package me.serce.solidity.ide import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.project.DumbAware import me.serce.solidity.lang.core.SolidityTokenTypes import java.util.* class SolidityFoldingBuilder : FoldingBuilder, DumbAware { override fun buildFoldRegions(node: ASTNode, document: Document): Array<FoldingDescriptor> { val descriptors = ArrayList<FoldingDescriptor>() collectDescriptorsRecursively(node, document, descriptors) return descriptors.toTypedArray() } override fun getPlaceholderText(node: ASTNode): String? { val type = node.elementType return when (type) { SolidityTokenTypes.BLOCK -> "{...}" SolidityTokenTypes.COMMENT -> "/*...*/" SolidityTokenTypes.CONTRACT_DEFINITION -> "${node.text.substringBefore("{")} {...} " else -> "..." } } override fun isCollapsedByDefault(node: ASTNode): Boolean { return false } companion object { private fun collectDescriptorsRecursively( node: ASTNode, document: Document, descriptors: MutableList<FoldingDescriptor> ) { val type = node.elementType if ( type === SolidityTokenTypes.BLOCK && spanMultipleLines(node, document) || type === SolidityTokenTypes.COMMENT || type === SolidityTokenTypes.CONTRACT_DEFINITION) { descriptors.add(FoldingDescriptor(node, node.textRange)) } for (child in node.getChildren(null)) { collectDescriptorsRecursively(child, document, descriptors) } } private fun spanMultipleLines(node: ASTNode, document: Document): Boolean { val range = node.textRange return document.getLineNumber(range.startOffset) < document.getLineNumber(range.endOffset) } } }
mit
dahlstrom-g/intellij-community
plugins/kotlin/completion/tests/testData/handlers/smart/ExclChar.kt
26
75
fun foo(flag: Boolean) { if (<caret>) } // ELEMENT: flag // CHAR: '!'
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/sealedInheritorsInComplexModuleStructure1/main/main.kt
9
235
package foo actual sealed class <!LINE_MARKER("descr='Has expects in common module'")!>SealedWithPlatformActuals<!> <!ACTUAL_WITHOUT_EXPECT!>actual constructor()<!>: <!SEALED_INHERITOR_IN_DIFFERENT_MODULE!>SealedWithSharedActual<!>()
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/expressions/multilineExpressionWithClosure1.kt
13
80
// MOVE: up fun test() { (0..10) .map { it } <caret>println() }
apache-2.0
dahlstrom-g/intellij-community
plugins/kotlin/base/fir/analysis-api-providers/testData/annotationsResolver/priority/star_import_beats_package_import.kt
8
120
package test import dependency.MyAnnotation @MyAnnotation fun test<caret>() {} // ANNOTATION: dependency/MyAnnotation
apache-2.0
tommyli/nem12-manager
fenergy-service/src/main/kotlin/co/firefire/fenergy/shared/domain/LoginNmi.kt
1
2377
// Tommy Li ([email protected]), 2017-07-03 package co.firefire.fenergy.shared.domain import co.firefire.fenergy.nem12.domain.NmiMeterRegister import org.hibernate.annotations.GenericGenerator import org.hibernate.annotations.Parameter import java.util.* import javax.persistence.CascadeType import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.JoinColumn import javax.persistence.ManyToOne import javax.persistence.OneToMany import javax.persistence.OrderBy @Entity data class LoginNmi( @ManyToOne(optional = false) @JoinColumn(name = "login", referencedColumnName = "id", nullable = false) var login: Login = Login(), var nmi: String = "" ) : Comparable<LoginNmi> { @Id @GenericGenerator( name = "LoginNmiIdSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = arrayOf( Parameter(name = "sequence_name", value = "login_nmi_id_seq"), Parameter(name = "initial_value", value = "1000"), Parameter(name = "increment_size", value = "1") ) ) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "LoginNmiIdSeq") var id: Long? = null var label: String? = null @OneToMany(mappedBy = "loginNmi", cascade = arrayOf(CascadeType.ALL), orphanRemoval = true) @OrderBy("meterSerial, registerId, nmiSuffix") var nmiMeterRegisters: SortedSet<NmiMeterRegister> = TreeSet() fun addNmiMeterRegister(nmiMeterRegister: NmiMeterRegister) { nmiMeterRegister.loginNmi = this nmiMeterRegisters.add(nmiMeterRegister) } fun mergeNmiMeterRegister(nmr: NmiMeterRegister) { val existing: NmiMeterRegister? = nmiMeterRegisters.find { it.loginNmi == nmr.loginNmi && it.meterSerial == nmr.meterSerial && it.registerId == nmr.registerId && it.nmiSuffix == nmr.nmiSuffix } if (existing == null) { addNmiMeterRegister(nmr) } else { existing.mergeIntervalDays(nmr.intervalDays.values) } } override fun compareTo(other: LoginNmi) = compareValuesBy(this, other, { it.login }, { it.nmi }) override fun toString() = "LoginNmi(login=$login, nmi='$nmi', id=$id, label=$label)" }
apache-2.0
android/location-samples
SleepSampleKotlin/app/src/main/java/com/android/example/sleepsamplekotlin/data/db/SleepDatabase.kt
2
1997
/* * Copyright (C) 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 com.android.example.sleepsamplekotlin.data.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase private const val DATABASE_NAME = "sleep_segments_database" /** * Stores all sleep segment data. */ @Database( entities = [SleepSegmentEventEntity::class, SleepClassifyEventEntity::class], version = 3, exportSchema = false ) abstract class SleepDatabase : RoomDatabase() { abstract fun sleepSegmentEventDao(): SleepSegmentEventDao abstract fun sleepClassifyEventDao(): SleepClassifyEventDao companion object { // For Singleton instantiation @Volatile private var INSTANCE: SleepDatabase? = null fun getDatabase(context: Context): SleepDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context, SleepDatabase::class.java, DATABASE_NAME ) // Wipes and rebuilds instead of migrating if no Migration object. // Migration is not part of this sample. .fallbackToDestructiveMigration() .build() INSTANCE = instance // return instance instance } } } }
apache-2.0
SpectraLogic/ds3_java_browser
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/factories/PutJobFactory.kt
1
3208
/* * *************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.services.jobService.factories import com.spectralogic.ds3client.Ds3Client import com.spectralogic.dsbrowser.api.services.logging.LoggingService import com.spectralogic.dsbrowser.gui.DeepStorageBrowserPresenter import com.spectralogic.dsbrowser.gui.services.JobWorkers import com.spectralogic.dsbrowser.gui.services.Workers import com.spectralogic.dsbrowser.gui.services.jobService.JobTask import com.spectralogic.dsbrowser.gui.services.jobService.JobTaskElement import com.spectralogic.dsbrowser.gui.services.jobService.PutJob import com.spectralogic.dsbrowser.gui.services.jobService.data.PutJobData import com.spectralogic.dsbrowser.gui.services.jobinterruption.JobInterruptionStore import com.spectralogic.dsbrowser.gui.services.sessionStore.Session import com.spectralogic.dsbrowser.gui.util.treeItem.SafeHandler import com.spectralogic.dsbrowser.util.andThen import org.slf4j.LoggerFactory import java.nio.file.Path import javax.inject.Inject import javax.inject.Singleton @Singleton class PutJobFactory @Inject constructor( private val loggingService: LoggingService, private val jobInterruptionStore: JobInterruptionStore, private val deepStorageBrowserPresenter: DeepStorageBrowserPresenter, private val jobWorkers: JobWorkers, private val workers: Workers, private val jobTaskElementFactory: JobTaskElement.JobTaskElementFactory ) { private companion object { private val LOG = LoggerFactory.getLogger(PutJobFactory::class.java) private const val TYPE: String = "Put" } fun create(session: Session, files: List<Pair<String, Path>>, bucket: String, targetDir: String, client: Ds3Client, refreshBehavior: () -> Unit = {}) { PutJobData(files, targetDir, bucket, jobTaskElementFactory.create(client)) .let { PutJob(it) } .let { JobTask(it, session.sessionName) } .apply { onSucceeded = SafeHandler.logHandle(onSucceeded(TYPE, LOG).andThen(refreshBehavior)) onFailed = SafeHandler.logHandle(onFailed(client, jobInterruptionStore, deepStorageBrowserPresenter, loggingService, workers, TYPE).andThen(refreshBehavior)) onCancelled = SafeHandler.logHandle(onCancelled(client, loggingService, jobInterruptionStore, deepStorageBrowserPresenter).andThen(refreshBehavior)) } .also { jobWorkers.execute(it) } } }
apache-2.0
MGaetan89/ShowsRage
app/src/test/kotlin/com/mgaetan89/showsrage/network/SickRageApi_GetPosterUrlTest.kt
1
10095
package com.mgaetan89.showsrage.network import android.content.SharedPreferences import com.mgaetan89.showsrage.extension.getApiKey import com.mgaetan89.showsrage.extension.getPortNumber import com.mgaetan89.showsrage.extension.getServerAddress import com.mgaetan89.showsrage.extension.getServerPath import com.mgaetan89.showsrage.extension.useHttps import com.mgaetan89.showsrage.model.ImageType import com.mgaetan89.showsrage.model.Indexer import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.Mockito.`when` import org.mockito.Mockito.mock @RunWith(Parameterized::class) class SickRageApi_GetPosterUrlTest( val useHttps: Boolean, val address: String, val port: String, val path: String, val apiKey: String, val indexerId: Int, val indexer: Indexer?, val url: String ) { @Before fun before() { val preferences = mock(SharedPreferences::class.java) `when`(preferences.useHttps()).thenReturn(this.useHttps) `when`(preferences.getServerAddress()).thenReturn(this.address) `when`(preferences.getPortNumber()).thenReturn(this.port) `when`(preferences.getServerPath()).thenReturn(this.path) `when`(preferences.getApiKey()).thenReturn(this.apiKey) SickRageApi.instance.init(preferences) } @Test fun getPosterUrl() { assertThat(SickRageApi.instance.getImageUrl(ImageType.POSTER, this.indexerId, this.indexer)).isEqualTo(this.url) } companion object { @JvmStatic @Parameterized.Parameters(name = "[{6}] {index} - {0}://{1}:{2}/{3}/{4}/") fun data(): Collection<Array<Any?>> { return listOf( arrayOf(false, "", "", "", "", 0, null, "http://127.0.0.1/?cmd=show.getposter"), arrayOf(false, "127.0.0.1", "", "", "", 123, null, "http://127.0.0.1/?cmd=show.getposter"), arrayOf(true, "", "", "", "", 0, null, "http://127.0.0.1/?cmd=show.getposter"), arrayOf(true, "127.0.0.1", "", "", "", 123, null, "https://127.0.0.1/?cmd=show.getposter"), // TVDB arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TVDB, "http://127.0.0.1:8083/?cmd=show.getposter&tvdbid=0"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVDB, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVDB, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TVDB, "https://127.0.0.1:8083/?cmd=show.getposter&tvdbid=0"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVDB, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVDB, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvdbid=123"), // TVRage arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TVRAGE, "http://127.0.0.1:8083/?cmd=show.getposter&tvrageid=0"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVRAGE, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TVRAGE, "https://127.0.0.1:8083/?cmd=show.getposter&tvrageid=0"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvrageid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVRAGE, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvrageid=123"), // TVMaze arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TVMAZE, "http://127.0.0.1:8083/?cmd=show.getposter&tvmazeid=0"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVMAZE, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TVMAZE, "https://127.0.0.1:8083/?cmd=show.getposter&tvmazeid=0"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tvmazeid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TVMAZE, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tvmazeid=123"), // TMDB arrayOf<Any?>(false, "127.0.0.1", "8083", "", "", 0, Indexer.TMDB, "http://127.0.0.1:8083/?cmd=show.getposter&tmdbid=0"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api/", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TMDB, "http://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(false, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TMDB, "http://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "", "", 0, Indexer.TMDB, "https://127.0.0.1:8083/?cmd=show.getposter&tmdbid=0"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api/", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api/", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "/api1/api2/", "", 123, Indexer.TMDB, "https://127.0.0.1:8083/api1/api2/?cmd=show.getposter&tmdbid=123"), arrayOf<Any?>(true, "127.0.0.1", "8083", "api", "apiKey", 123, Indexer.TMDB, "https://127.0.0.1:8083/api/apiKey/?cmd=show.getposter&tmdbid=123") ) } } }
apache-2.0
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/sync/cleanup/MarkedForDeletionCleaner.kt
2
3627
package co.smartreceipts.android.sync.cleanup import co.smartreceipts.analytics.log.Logger import co.smartreceipts.android.model.Receipt import co.smartreceipts.android.persistence.PersistenceManager import co.smartreceipts.android.persistence.database.controllers.impl.ReceiptTableController import co.smartreceipts.android.persistence.database.operations.DatabaseOperationMetadata import co.smartreceipts.android.persistence.database.operations.OperationFamilyType import co.smartreceipts.android.persistence.database.tables.ReceiptsTable import co.smartreceipts.android.sync.provider.SyncProviderStore import co.smartreceipts.core.di.scopes.ApplicationScope import co.smartreceipts.core.sync.provider.SyncProvider import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.schedulers.Schedulers import javax.inject.Inject /** * In situations in which no [SyncProvider.None] is designated as the desired sync provider, we can * potentially enter a situation in which items are marked for deletion on Google Drive but are never * actually deleted (as the delete never syncs to Google Drive). This utility class allows us to * clean up these entities */ @ApplicationScope class MarkedForDeletionCleaner constructor(private val receiptsTable: ReceiptsTable, private val receiptTableController: ReceiptTableController, private val syncProviderStore: SyncProviderStore, private val backgroundScheduler: Scheduler) { @Inject constructor(persistenceManager: PersistenceManager, receiptTableController: ReceiptTableController, syncProviderStore: SyncProviderStore) : this(persistenceManager.database.receiptsTable, receiptTableController, syncProviderStore, Schedulers.io()) /** * In situations in which no [SyncProvider.None] is designated as the desired sync provider, we can * potentially enter a situation in which items are marked for deletion on Google Drive but are never * actually deleted (as the delete never syncs to Google Drive). This utility method allows us to * clean up these entities */ fun safelyDeleteAllOutstandingItems() { Observable.fromCallable { return@fromCallable syncProviderStore.provider } .subscribeOn(backgroundScheduler) .flatMap { if (it == SyncProvider.None) { Logger.info(this, "No sync provider is currently configured. " + "Checking if we should delete outstanding items that are marked for deletion.") return@flatMap receiptsTable.getAllMarkedForDeletionItems(SyncProvider.GoogleDrive) .doOnSuccess { receipts -> Logger.info(this, "Found {} receipts that are marked for deletion", receipts.size) } .flatMapObservable { receipts -> Observable.fromIterable(receipts) } } else { return@flatMap Observable.empty<Receipt>() } } .subscribe ({ receipt -> receiptTableController.delete(receipt, DatabaseOperationMetadata(OperationFamilyType.Sync)) }, { Logger.error(this, "Our deletion stream was interrupted", it) }) } }
agpl-3.0
taumechanica/ml
src/main/kotlin/ml/strong/EncodingForest.kt
1
1160
// Use of this source code is governed by The MIT License // that can be found in the LICENSE file. package taumechanica.ml.strong import taumechanica.ml.data.DataFrame import taumechanica.ml.meta.RandomTree class EncodingForest { val encoders: Array<RandomTree> constructor( frame: DataFrame, complexity: Int, extract: () -> IntArray?, size: Int = 0 ) { encoders = if (size > 0) { val indices = IntArray(frame.features.size, { it }) Array<RandomTree>(size, { RandomTree(frame, indices, complexity) }) } else { var trees = mutableListOf<RandomTree>() var indices = extract() while (indices != null) { trees.add(RandomTree(frame, indices, complexity)) indices = extract() } trees.toTypedArray() } } fun encode(values: DoubleArray, targetIndex: Int) = DoubleArray( encoders.size + 1, { if (it < encoders.size) { encoders[it].encode(values) } else { values[targetIndex] } } ) }
mit
justnero-ru/university
semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/test/parse.kt
1
1849
package bellman.test import com.beust.klaxon.* import java.io.File fun String.getFileFromResources() = File(Thread.currentThread().contextClassLoader.getResource(this).file) fun testSet(fileName: String = "config.json"): TestSet = TestSet(listOf(testTask(fileName))) fun testTask(fileName: String = "config.json"): TestTask = (Parser().parse(fileName.getFileFromResources().path) as JsonObject).testTask() fun JsonObject.testTask() = TestTask( int("iterationCoefficient")!!, generateGraphConfiguration("graph") ) fun JsonObject.generateGraphConfiguration() = GenerateGraphConfiguration( array<Int>("vertexNumber")?.toIntArray()!!, array<Double>("edgeProbability")?.toDoubleArray()!! ) fun JsonObject.generateGraphConfiguration(fieldName: String) = obj(fieldName)!!.generateGraphConfiguration() fun ResultSet.toJson() = json { array( results .mapIndexed { index, testResult -> index.toString() to testResult.toJson() } .map { obj(it) } ) } fun TestResult.toJson() = json { obj( "processNumber" to processNumber, "input" to input.toJson(), "millisecondTime" to millisecondTime.toJson() ) } fun Input.toJson() = json { obj( "iterationNumber" to iterationNumber, "vertexNumber" to vertexNumber, "edgeProbability" to edgeProbability ) } fun ParallelAndSequentialTime.toJson() = json { obj( "parallel" to first, "sequential" to second ) }
mit
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/gui/builder/ActionGroup.kt
1
88
package hamburg.remme.tinygit.gui.builder class ActionGroup(vararg val action: Action)
bsd-3-clause
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/home/HomeNavigator.kt
3
5126
package com.alexstyl.specialdates.home import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import com.alexstyl.specialdates.CrashAndErrorTracker import com.alexstyl.specialdates.ShareAppIntentCreator import com.alexstyl.specialdates.Strings import com.alexstyl.specialdates.addevent.AddEventActivity import com.alexstyl.specialdates.analytics.Analytics import com.alexstyl.specialdates.analytics.Screen import com.alexstyl.specialdates.contact.Contact import com.alexstyl.specialdates.date.Date import com.alexstyl.specialdates.donate.DonateActivity import com.alexstyl.specialdates.events.namedays.activity.NamedaysOnADayActivity import com.alexstyl.specialdates.facebook.FacebookProfileActivity import com.alexstyl.specialdates.facebook.FacebookUserSettings import com.alexstyl.specialdates.facebook.login.FacebookLogInActivity import com.alexstyl.specialdates.permissions.ContactPermissionActivity import com.alexstyl.specialdates.person.PersonActivity import com.alexstyl.specialdates.search.SearchActivity import com.alexstyl.specialdates.theming.AttributeExtractor import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import com.novoda.simplechromecustomtabs.SimpleChromeCustomTabs class HomeNavigator(private val analytics: Analytics, private val strings: Strings, private val facebookUserSettings: FacebookUserSettings, private val tracker: CrashAndErrorTracker, private val attributeExtractor: AttributeExtractor) { fun toDonate(activity: Activity) { if (hasPlayStoreInstalled(activity)) { val intent = DonateActivity.createIntent(activity) activity.startActivity(intent) } else { SimpleChromeCustomTabs.getInstance() .withFallback { navigateToDonateWebsite(activity) } .withIntentCustomizer { simpleChromeCustomTabsIntentBuilder -> val toolbarColor = attributeExtractor.extractPrimaryColorFrom(activity) simpleChromeCustomTabsIntentBuilder.withToolbarColor(toolbarColor) } .navigateTo(SUPPORT_URL, activity) } analytics.trackScreen(Screen.DONATE) } private fun hasPlayStoreInstalled(activity: Activity): Boolean { val googleApiAvailability = GoogleApiAvailability.getInstance() val resultCode = googleApiAvailability.isGooglePlayServicesAvailable(activity) return resultCode == ConnectionResult.SUCCESS } private fun navigateToDonateWebsite(activity: Activity) { try { val intent = Intent(Intent.ACTION_VIEW) intent.data = SUPPORT_URL activity.startActivity(intent) } catch (e: ActivityNotFoundException) { tracker.track(e) } } fun toAddEvent(activity: Activity, code: Int) { val intent = Intent(activity, AddEventActivity::class.java) activity.startActivityForResult(intent, code) } fun toFacebookImport(activity: Activity) { if (facebookUserSettings.isLoggedIn) { val intent = Intent(activity, FacebookProfileActivity::class.java) activity.startActivity(intent) } else { val intent = Intent(activity, FacebookLogInActivity::class.java) activity.startActivity(intent) } } fun toSearch(activity: Activity) { val intent = Intent(activity, SearchActivity::class.java) activity.startActivity(intent) analytics.trackScreen(Screen.SEARCH) } fun toDateDetails(dateSelected: Date, activity: Activity) { val intent = NamedaysOnADayActivity.getStartIntent(activity, dateSelected) activity.startActivity(intent) analytics.trackScreen(Screen.DATE_DETAILS) } fun toAppInvite(activity: Activity) { val intent = ShareAppIntentCreator(strings).buildIntent() val shareTitle = strings.inviteFriend() activity.startActivity(Intent.createChooser(intent, shareTitle)) analytics.trackAppInviteRequested() } fun toGithubPage(activity: Activity) { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("https://github.com/alexstyl/Memento-Calendar") analytics.trackVisitGithub() activity.startActivity(intent) } fun toContactDetails(contact: Contact, activity: Activity) { val intent = PersonActivity.buildIntentFor(activity, contact) activity.startActivity(intent) analytics.trackContactDetailsViewed(contact) } fun toContactPermission(activity: Activity, requestCode: Int) { val intent = Intent(activity, ContactPermissionActivity::class.java) activity.startActivityForResult(intent, requestCode) analytics.trackScreen(Screen.CONTACT_PERMISSION_REQUESTED) } companion object { private val SUPPORT_URL = Uri.parse("https://g3mge.app.goo.gl/jdF1") } }
mit
kohry/gorakgarakANPR
app/src/main/java/com/gorakgarak/anpr/ml/NeuralNetwork.kt
1
2611
package com.gorakgarak.anpr.ml import android.content.Context import com.gorakgarak.anpr.R import com.gorakgarak.anpr.parser.GorakgarakXMLParser import org.opencv.core.Core import org.opencv.core.CvType.CV_32FC1 import org.opencv.core.CvType.CV_32SC1 import org.opencv.core.Mat import org.opencv.core.Scalar import org.opencv.ml.ANN_MLP import org.opencv.ml.Ml.ROW_SAMPLE import java.io.FileInputStream /** * Created by kohry on 2017-10-15. */ object NeuralNetwork { val CHAR_COUNT = 30 val LAYER_COUNT = 10 val strCharacters = arrayOf('0','1','2','3','4','5','6','7','8','9','B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z') val ann: ANN_MLP = ANN_MLP.create() private fun readXML(context: Context): Pair<Mat, Mat> { // val inputStream = context.assets.open(fileName) // val fs = opencv_core.FileStorage() // fs.open(fileName,opencv_core.FileStorage.READ) // // val train = Mat(fs["TrainingDataF15"].mat().address()) // val classes = Mat(fs["classes"].mat().address()) return GorakgarakXMLParser.parse(context.resources.openRawResource(R.raw.ann),"TrainingDataF15") } fun train(context: Context) { if (ann.isTrained) return val data = readXML(context) val trainData = data.first val classes = data.second val layerSizes = Mat(1,3,CV_32SC1) val r = trainData.rows() val c = trainData.cols() layerSizes.put(0, 0, intArrayOf(trainData.cols())) layerSizes.put(0, 1, intArrayOf(LAYER_COUNT)) layerSizes.put(0, 2, intArrayOf(CHAR_COUNT)) ann.layerSizes = layerSizes ann.setActivationFunction(ANN_MLP.SIGMOID_SYM) val trainClasses = Mat() trainClasses.create(trainData.rows(), CHAR_COUNT, CV_32FC1) (0 until trainClasses.rows()).forEach { row -> (0 until trainClasses.cols()).forEach { col -> if (col == classes.get(row, 0).get(0).toInt()) trainClasses.put(row, col, floatArrayOf(1f)) else trainClasses.put(col, row, floatArrayOf(0f)) } } //this part has changed from opencv 2 -> 3. ann class does not need weights anymore. // val weights = Mat(1, trainData.rows(), CV_32FC1, Scalar.all(1.0)) ann.train(trainData, ROW_SAMPLE, trainClasses) } fun classify(f: Mat): Double { val result = -1 val output = Mat(1, CHAR_COUNT, CV_32FC1) ann.predict(f) val minMaxLoc = Core.minMaxLoc(output) return minMaxLoc.maxLoc.x } }
mit
RuneSuite/client
updater-deob/src/main/java/org/runestar/client/updater/deob/common/SortFieldsByModifiers.kt
1
786
package org.runestar.client.updater.deob.common import org.objectweb.asm.Type import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.FieldNode import org.runestar.client.updater.deob.Transformer import java.lang.reflect.Modifier import java.nio.file.Path object SortFieldsByModifiers : Transformer.Tree() { override fun transform(dir: Path, klasses: List<ClassNode>) { klasses.forEach { k -> k.fields = k.fields.sortedWith(FIELD_COMPARATOR) } } private val FIELD_COMPARATOR: Comparator<FieldNode> = compareBy<FieldNode> { !Modifier.isStatic(it.access) } .thenBy { Modifier.toString(it.access and Modifier.fieldModifiers()) } .thenBy { Type.getType(it.desc).className } .thenBy { it.name } }
mit
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/SENewUIHeaderView.kt
1
1863
// 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.ide.actions.searcheverywhere import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.components.JBTabbedPane import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import java.util.function.Function import javax.swing.JComponent import javax.swing.JPanel import javax.swing.border.EmptyBorder internal class SENewUIHeaderView(tabs: List<SearchEverywhereHeader.SETab>, shortcutSupplier: Function<in String?, String?>, toolbar: JComponent) { lateinit var tabbedPane: JBTabbedPane @JvmField val panel: DialogPanel init { panel = panel { row { tabbedPane = tabbedPaneHeader() .customize(Gaps.EMPTY) .applyToComponent { font = JBFont.regular() background = JBUI.CurrentTheme.ComplexPopup.HEADER_BACKGROUND isFocusable = false } .component toolbar.putClientProperty(ActionToolbarImpl.USE_BASELINE_KEY, true) cell(toolbar) .resizableColumn() .align(AlignX.RIGHT) } } val headerInsets = JBUI.CurrentTheme.ComplexPopup.headerInsets() @Suppress("UseDPIAwareBorders") panel.border = JBUI.Borders.compound( JBUI.Borders.customLineBottom(JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground()), EmptyBorder(0, headerInsets.left, 0, headerInsets.right)) for (tab in tabs) { val shortcut = shortcutSupplier.apply(tab.id) tabbedPane.addTab(tab.name, null, JPanel(), shortcut) } } }
apache-2.0
Leifzhang/AndroidRouter
kspCompiler/src/main/java/com/kronos/ksp/compiler/KotlinPoetExe.kt
1
5016
package com.kronos.ksp.compiler import com.google.devtools.ksp.isLocal import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.Dependencies import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.symbol.Variance.CONTRAVARIANT import com.google.devtools.ksp.symbol.Variance.COVARIANT import com.google.devtools.ksp.symbol.Variance.INVARIANT import com.google.devtools.ksp.symbol.Variance.STAR import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import java.io.OutputStreamWriter import java.nio.charset.StandardCharsets.UTF_8 import com.squareup.kotlinpoet.STAR as KpStar /** * * @Author LiABao * @Since 2021/3/8 * */ internal fun KSType.toClassName(): ClassName { val decl = declaration check(decl is KSClassDeclaration) return decl.toClassName() } internal fun KSType.toTypeName(typeParamResolver: TypeParameterResolver): TypeName { val type = when (val decl = declaration) { is KSClassDeclaration -> decl.toTypeName(arguments.map { it.toTypeName(typeParamResolver) }) is KSTypeParameter -> typeParamResolver[decl.name.getShortName()] is KSTypeAlias -> decl.type.resolve().toTypeName(typeParamResolver) else -> error("Unsupported type: $declaration") } return type.copy(nullable = isMarkedNullable) } internal fun KSClassDeclaration.toTypeName(argumentList: List<TypeName> = emptyList()): TypeName { val className = toClassName() return if (argumentList.isNotEmpty()) { className.parameterizedBy(argumentList) } else { className } } internal interface TypeParameterResolver { val parametersMap: Map<String, TypeVariableName> operator fun get(index: String): TypeVariableName } internal fun List<KSTypeParameter>.toTypeParameterResolver( fallback: TypeParameterResolver? = null, sourceType: String? = null, ): TypeParameterResolver { val parametersMap = LinkedHashMap<String, TypeVariableName>() val typeParamResolver = { id: String -> parametersMap[id] ?: fallback?.get(id) ?: throw IllegalStateException("No type argument found for $id! Anaylzing $sourceType") } val resolver = object : TypeParameterResolver { override val parametersMap: Map<String, TypeVariableName> = parametersMap override operator fun get(index: String): TypeVariableName = typeParamResolver(index) } // Fill the parametersMap. Need to do sequentially and allow for referencing previously defined params for (typeVar in this) { // Put the simple typevar in first, then it can be referenced in the full toTypeVariable() // replacement later that may add bounds referencing this. val id = typeVar.name.getShortName() parametersMap[id] = TypeVariableName(id) // Now replace it with the full version. parametersMap[id] = typeVar.toTypeVariableName(resolver) } return resolver } internal fun KSClassDeclaration.toClassName(): ClassName { require(!isLocal()) { "Local/anonymous classes are not supported!" } val pkgName = packageName.asString() val typesString = qualifiedName!!.asString().removePrefix("$pkgName.") val simpleNames = typesString .split(".") return ClassName(pkgName, simpleNames) } internal fun KSTypeParameter.toTypeName(typeParamResolver: TypeParameterResolver): TypeName { if (variance == STAR) return KpStar return toTypeVariableName(typeParamResolver) } internal fun KSTypeParameter.toTypeVariableName( typeParamResolver: TypeParameterResolver, ): TypeVariableName { val typeVarName = name.getShortName() val typeVarBounds = bounds.map { it.toTypeName(typeParamResolver) } val typeVarVariance = when (variance) { COVARIANT -> KModifier.OUT CONTRAVARIANT -> KModifier.IN else -> null } return TypeVariableName( typeVarName, bounds = typeVarBounds.toList(), variance = typeVarVariance ) } internal fun KSTypeArgument.toTypeName(typeParamResolver: TypeParameterResolver): TypeName { val typeName = type?.resolve()?.toTypeName(typeParamResolver) ?: return KpStar return when (variance) { COVARIANT -> WildcardTypeName.producerOf(typeName) CONTRAVARIANT -> WildcardTypeName.consumerOf(typeName) STAR -> KpStar INVARIANT -> typeName } } internal fun KSTypeReference.toTypeName(typeParamResolver: TypeParameterResolver): TypeName { val type = resolve() return type.toTypeName(typeParamResolver) } internal fun FileSpec.writeTo(codeGenerator: CodeGenerator, logger: KSPLogger) { // logger.warn("start dependencies") // logger.error("dependencies:$dependencies") // Don't use writeTo(file) because that tries to handle directories under the hood logger.info("codeGenerator:${codeGenerator.generatedFile}") }
mit
JetBrains/intellij-community
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/tokenizer/PriorityQueue.kt
1
1281
package org.jetbrains.completion.full.line.local.tokenizer // import org.apache.commons.math3.random.MersenneTwister import org.apache.commons.math3.distribution.UniformRealDistribution import java.util.* abstract class BasePriorityQueue<T> { abstract fun push(x: T) abstract fun pop(): T? } class STLQueue<T> : BasePriorityQueue<T>() { private val q = PriorityQueue<T>() override fun push(x: T) { this.q.add(x) } override fun pop(): T? { return this.q.poll() } } class DropoutQueue<T>(var skipProb: Double) : BasePriorityQueue<T>() { // val rnd = MersenneTwister() var dist = UniformRealDistribution(0.0, 1.0) private val q = PriorityQueue<T>() private val skippedElements = ArrayList<T>() override fun push(x: T) { q.add(x) } override fun pop(): T? { assert(skippedElements.isEmpty()) while (true) { if (q.isEmpty()) { skippedElements.forEach { q.add(it) } skippedElements.clear() return null } val temp = q.peek() q.poll() if (dist.sample() < skipProb) { skippedElements.add(temp) } else { skippedElements.forEach { q.add(it) } skippedElements.clear() return temp } } } }
apache-2.0
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/julius/psi/Comment.kt
1
211
package org.jetbrains.yesod.julius.psi /** * @author Leyla H */ import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode class Comment(node: ASTNode) : ASTWrapperPsiElement(node)
apache-2.0
google/iosched
mobile/src/test/java/com/google/samples/apps/iosched/ui/signin/SignInViewModelTest.kt
1
2198
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.signin import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.google.samples.apps.iosched.test.data.MainCoroutineRule import com.google.samples.apps.iosched.test.util.fakes.FakeSignInViewModelDelegate import junit.framework.Assert.assertEquals import org.junit.Rule import org.junit.Test class SignInViewModelTest { // Executes tasks in the Architecture Components in the same thread @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() // Overrides Dispatchers.Main used in Coroutines @get:Rule var coroutineRule = MainCoroutineRule() @Test fun signedInUser_signsOut() { // Given a view model with a signed in user val signInViewModelDelegate = FakeSignInViewModelDelegate().apply { injectIsSignedIn = true } val viewModel = SignInViewModel(signInViewModelDelegate) // When sign out is requested viewModel.onSignOut() // Then a sign out request is emitted assertEquals(1, signInViewModelDelegate.signOutRequestsEmitted) } @Test fun noSignedInUser_signsIn() { // Given a view model with a signed out user val signInViewModelDelegate = FakeSignInViewModelDelegate().apply { injectIsSignedIn = false } val viewModel = SignInViewModel(signInViewModelDelegate) // When sign out is requested viewModel.onSignIn() // Then a sign out request is emitted assertEquals(1, signInViewModelDelegate.signInRequestsEmitted) } }
apache-2.0
allotria/intellij-community
plugins/git4idea/src/git4idea/config/GitVcsPanel.kt
1
21621
// 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 git4idea.config import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.application.options.editor.checkBox import com.intellij.dvcs.branch.DvcsSyncSettings import com.intellij.dvcs.ui.DvcsBundle import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.service import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.changes.onChangeListAvailabilityChanged import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.ui.components.TextComponentEmptyText import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.layout.* import com.intellij.util.Function import com.intellij.util.execution.ParametersListUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.VcsExecutablePathSelector import com.intellij.vcs.commit.CommitModeManager import com.intellij.vcs.log.VcsLogFilterCollection.STRUCTURE_FILTER import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcs.log.ui.filter.StructureFilterPopupComponent import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi import git4idea.GitVcs import git4idea.branch.GitBranchIncomingOutgoingManager import git4idea.i18n.GitBundle import git4idea.i18n.GitBundle.message import git4idea.index.canEnableStagingArea import git4idea.index.enableStagingArea import git4idea.repo.GitRepositoryManager import git4idea.update.GitUpdateProjectInfoLogProperties import git4idea.update.getUpdateMethods import org.jetbrains.annotations.CalledInAny import java.awt.Color import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.JLabel import javax.swing.border.Border private fun gitSharedSettings(project: Project) = GitSharedSettings.getInstance(project) private fun projectSettings(project: Project) = GitVcsSettings.getInstance(project) private val applicationSettings get() = GitVcsApplicationSettings.getInstance() private val gitOptionGroupName get() = message("settings.git.option.group") // @formatter:off private fun cdSyncBranches(project: Project) = CheckboxDescriptor(DvcsBundle.message("sync.setting"), PropertyBinding({ projectSettings(project).syncSetting == DvcsSyncSettings.Value.SYNC }, { projectSettings(project).syncSetting = if (it) DvcsSyncSettings.Value.SYNC else DvcsSyncSettings.Value.DONT_SYNC }), groupName = gitOptionGroupName) private val cdCommitOnCherryPick get() = CheckboxDescriptor(message("settings.commit.automatically.on.cherry.pick"), PropertyBinding(applicationSettings::isAutoCommitOnCherryPick, applicationSettings::setAutoCommitOnCherryPick), groupName = gitOptionGroupName) private fun cdAddCherryPickSuffix(project: Project) = CheckboxDescriptor(message("settings.add.suffix"), PropertyBinding({ projectSettings(project).shouldAddSuffixToCherryPicksOfPublishedCommits() }, { projectSettings(project).setAddSuffixToCherryPicks(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutCrlf(project: Project) = CheckboxDescriptor(message("settings.crlf"), PropertyBinding({ projectSettings(project).warnAboutCrlf() }, { projectSettings(project).setWarnAboutCrlf(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutDetachedHead(project: Project) = CheckboxDescriptor(message("settings.detached.head"), PropertyBinding({ projectSettings(project).warnAboutDetachedHead() }, { projectSettings(project).setWarnAboutDetachedHead(it) }), groupName = gitOptionGroupName) private fun cdAutoUpdateOnPush(project: Project) = CheckboxDescriptor(message("settings.auto.update.on.push.rejected"), PropertyBinding({ projectSettings(project).autoUpdateIfPushRejected() }, { projectSettings(project).setAutoUpdateIfPushRejected(it) }), groupName = gitOptionGroupName) private fun cdShowCommitAndPushDialog(project: Project) = CheckboxDescriptor(message("settings.push.dialog"), PropertyBinding({ projectSettings(project).shouldPreviewPushOnCommitAndPush() }, { projectSettings(project).setPreviewPushOnCommitAndPush(it) }), groupName = gitOptionGroupName) private fun cdHidePushDialogForNonProtectedBranches(project: Project) = CheckboxDescriptor(message("settings.push.dialog.for.protected.branches"), PropertyBinding({ projectSettings(project).isPreviewPushProtectedOnly }, { projectSettings(project).isPreviewPushProtectedOnly = it }), groupName = gitOptionGroupName) private val cdOverrideCredentialHelper get() = CheckboxDescriptor(message("settings.credential.helper"), PropertyBinding({ applicationSettings.isUseCredentialHelper }, { applicationSettings.isUseCredentialHelper = it }), groupName = gitOptionGroupName) private fun synchronizeBranchProtectionRules(project: Project) = CheckboxDescriptor(message("settings.synchronize.branch.protection.rules"), PropertyBinding({gitSharedSettings(project).isSynchronizeBranchProtectionRules}, { gitSharedSettings(project).isSynchronizeBranchProtectionRules = it }), groupName = gitOptionGroupName, comment = message("settings.synchronize.branch.protection.rules.description")) private val cdEnableStagingArea get() = CheckboxDescriptor(message("settings.enable.staging.area"), PropertyBinding({ applicationSettings.isStagingAreaEnabled }, { enableStagingArea(it) }), groupName = gitOptionGroupName, comment = message("settings.enable.staging.area.comment")) // @formatter:on internal fun gitOptionDescriptors(project: Project): List<OptionDescription> { val list = mutableListOf( cdCommitOnCherryPick, cdAutoUpdateOnPush(project), cdWarnAboutCrlf(project), cdWarnAboutDetachedHead(project), cdEnableStagingArea ) val manager = GitRepositoryManager.getInstance(project) if (manager.moreThanOneRoot()) { list += cdSyncBranches(project) } return list.map(CheckboxDescriptor::asOptionDescriptor) } internal class GitVcsPanel(private val project: Project) : BoundConfigurable(GitBundle.message("settings.git.option.group"), "project.propVCSSupport.VCSs.Git"), SearchableConfigurable { private val projectSettings by lazy { GitVcsSettings.getInstance(project) } @Volatile private var versionCheckRequested = false private val currentUpdateInfoFilterProperties = MyLogProperties(project.service<GitUpdateProjectInfoLogProperties>()) private lateinit var branchUpdateInfoRow: Row private lateinit var branchUpdateInfoCommentRow: Row private lateinit var supportedBranchUpLabel: JLabel private val pathSelector: VcsExecutablePathSelector by lazy { VcsExecutablePathSelector(GitVcs.NAME, disposable!!, object : VcsExecutablePathSelector.ExecutableHandler { override fun patchExecutable(executable: String): String? { return GitExecutableDetector.patchExecutablePath(executable) } override fun testExecutable(executable: String) { testGitExecutable(executable) } }) } private fun testGitExecutable(pathToGit: String) { val modalityState = ModalityState.stateForComponent(pathSelector.mainPanel) val errorNotifier = InlineErrorNotifierFromSettings( GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null), modalityState, disposable!! ) object : Task.Modal(project, GitBundle.message("git.executable.version.progress.title"), true) { private lateinit var gitVersion: GitVersion override fun run(indicator: ProgressIndicator) { val executableManager = GitExecutableManager.getInstance() val executable = executableManager.getExecutable(pathToGit) executableManager.dropVersionCache(executable) gitVersion = executableManager.identifyVersion(executable) } override fun onThrowable(error: Throwable) { val problemHandler = findGitExecutableProblemHandler(project) problemHandler.showError(error, errorNotifier) } override fun onSuccess() { if (gitVersion.isSupported) { errorNotifier.showMessage(message("git.executable.version.is", gitVersion.presentation)) } else { showUnsupportedVersionError(project, gitVersion, errorNotifier) } } }.queue() } private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent, private val modalityState: ModalityState, disposable: Disposable) : InlineErrorNotifier(inlineComponent, modalityState, disposable) { @CalledInAny override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) { if (fixOption is ErrorNotifier.FixOption.Configure) { super.showError(text, description, null) } else { super.showError(text, description, fixOption) } } override fun resetGitExecutable() { super.resetGitExecutable() GitExecutableManager.getInstance().getDetectedExecutable(project) // populate cache invokeAndWaitIfNeeded(modalityState) { resetPathSelector() } } } private fun getCurrentExecutablePath(): String? = pathSelector.currentPath?.takeIf { it.isNotBlank() } private fun LayoutBuilder.gitExecutableRow() = row { pathSelector.mainPanel(growX) .onReset { resetPathSelector() } .onIsModified { val projectSettingsPathToGit = projectSettings.pathToGit val currentPath = getCurrentExecutablePath() if (pathSelector.isOverridden) { currentPath != projectSettingsPathToGit } else { currentPath != applicationSettings.savedPathToGit || projectSettingsPathToGit != null } } .onApply { val executablePathOverridden = pathSelector.isOverridden val currentPath = getCurrentExecutablePath() if (executablePathOverridden) { projectSettings.pathToGit = currentPath } else { applicationSettings.setPathToGit(currentPath) projectSettings.pathToGit = null } validateExecutableOnceAfterClose() updateBranchUpdateInfoRow() VcsDirtyScopeManager.getInstance(project).markEverythingDirty() } } private fun resetPathSelector() { val projectSettingsPathToGit = projectSettings.pathToGit val detectedExecutable = try { GitExecutableManager.getInstance().getDetectedExecutable(project) } catch (e: ProcessCanceledException) { GitExecutableDetector.getDefaultExecutable() } pathSelector.reset(applicationSettings.savedPathToGit, projectSettingsPathToGit != null, projectSettingsPathToGit, detectedExecutable) updateBranchUpdateInfoRow() } /** * Special method to check executable after it has been changed through settings */ private fun validateExecutableOnceAfterClose() { if (!versionCheckRequested) { ApplicationManager.getApplication().invokeLater( { object : Task.Backgroundable(project, message("git.executable.version.progress.title"), true) { override fun run(indicator: ProgressIndicator) { GitExecutableManager.getInstance().testGitExecutableVersionValid(project) } }.queue() versionCheckRequested = false }, ModalityState.NON_MODAL) versionCheckRequested = true } } private fun updateBranchUpdateInfoRow() { val branchInfoSupported = GitVersionSpecialty.INCOMING_OUTGOING_BRANCH_INFO.existsIn(project) branchUpdateInfoRow.enabled = Registry.`is`("git.update.incoming.outgoing.info") && branchInfoSupported branchUpdateInfoCommentRow.visible = !branchInfoSupported supportedBranchUpLabel.foreground = if (!branchInfoSupported && projectSettings.incomingCheckStrategy != GitIncomingCheckStrategy.Never) { DialogWrapper.ERROR_FOREGROUND_COLOR } else { UIUtil.getContextHelpForeground() } } private fun LayoutBuilder.branchUpdateInfoRow() { branchUpdateInfoRow = row { supportedBranchUpLabel = JBLabel(message("settings.supported.for.2.9")) cell { label(message("settings.explicitly.check") + " ") comboBox( EnumComboBoxModel(GitIncomingCheckStrategy::class.java), { projectSettings.incomingCheckStrategy }, { selectedStrategy -> projectSettings.incomingCheckStrategy = selectedStrategy as GitIncomingCheckStrategy updateBranchUpdateInfoRow() if (!project.isDefault) { GitBranchIncomingOutgoingManager.getInstance(project).updateIncomingScheduling() } }) } branchUpdateInfoCommentRow = row { supportedBranchUpLabel() } } } override fun getId() = "vcs.${GitVcs.NAME}" override fun createPanel(): DialogPanel = panel { gitExecutableRow() row { checkBox(cdEnableStagingArea) .enableIf(StagingAreaAvailablePredicate(project, disposable!!)) } if (project.isDefault || GitRepositoryManager.getInstance(project).moreThanOneRoot()) { row { checkBox(cdSyncBranches(project)).applyToComponent { toolTipText = DvcsBundle.message("sync.setting.description", GitVcs.DISPLAY_NAME.get()) } } } row { checkBox(cdCommitOnCherryPick) .enableIf(ChangeListsEnabledPredicate(project, disposable!!)) } row { checkBox(cdAddCherryPickSuffix(project)) } row { checkBox(cdWarnAboutCrlf(project)) } row { checkBox(cdWarnAboutDetachedHead(project)) } branchUpdateInfoRow() row { cell { label(message("settings.update.method")) comboBox( CollectionComboBoxModel(getUpdateMethods()), { projectSettings.updateMethod }, { projectSettings.updateMethod = it!! }, renderer = SimpleListCellRenderer.create<UpdateMethod>("", UpdateMethod::getName) ) } } row { cell { label(message("settings.clean.working.tree")) buttonGroup({ projectSettings.saveChangesPolicy }, { projectSettings.saveChangesPolicy = it }) { GitSaveChangesPolicy.values().forEach { saveSetting -> radioButton(saveSetting.text, saveSetting) } } } } row { checkBox(cdAutoUpdateOnPush(project)) } row { val previewPushOnCommitAndPush = checkBox(cdShowCommitAndPushDialog(project)) row { checkBox(cdHidePushDialogForNonProtectedBranches(project)) .enableIf(previewPushOnCommitAndPush.selected) } } row { cell { label(message("settings.protected.branched")) val sharedSettings = gitSharedSettings(project) val protectedBranchesField = ExpandableTextFieldWithReadOnlyText(ParametersListUtil.COLON_LINE_PARSER, ParametersListUtil.COLON_LINE_JOINER) if (sharedSettings.isSynchronizeBranchProtectionRules) { protectedBranchesField.readOnlyText = ParametersListUtil.COLON_LINE_JOINER.`fun`(sharedSettings.additionalProhibitedPatterns) } protectedBranchesField(growX) .withBinding<List<String>>( { ParametersListUtil.COLON_LINE_PARSER.`fun`(it.text) }, { component, value -> component.text = ParametersListUtil.COLON_LINE_JOINER.`fun`(value) }, PropertyBinding( { sharedSettings.forcePushProhibitedPatterns }, { sharedSettings.forcePushProhibitedPatterns = it }) ) } row { checkBox(synchronizeBranchProtectionRules(project)) } } row { checkBox(cdOverrideCredentialHelper) } if (AbstractCommonUpdateAction.showsCustomNotification(listOf(GitVcs.getInstance(project)))) { updateProjectInfoFilter() } } private fun LayoutBuilder.updateProjectInfoFilter() { row { cell { val storedProperties = project.service<GitUpdateProjectInfoLogProperties>() val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(GitVcs.getInstance(project)).toSet() val model = VcsLogClassicFilterUi.FileFilterModel(roots, currentUpdateInfoFilterProperties, null) val component = object : StructureFilterPopupComponent(currentUpdateInfoFilterProperties, model, VcsLogColorManagerImpl(roots)) { override fun shouldDrawLabel(): Boolean = false override fun shouldIndicateHovering(): Boolean = false override fun getDefaultSelectorForeground(): Color = UIUtil.getLabelForeground() override fun createUnfocusedBorder(): Border { return FilledRoundedBorder(JBColor.namedColor("Component.borderColor", Gray.xBF), ARC_SIZE, 1) } }.initUi() label(message("settings.filter.update.info") + " ") component() .onIsModified { storedProperties.getFilterValues(STRUCTURE_FILTER.name) != currentUpdateInfoFilterProperties.structureFilter } .onApply { storedProperties.saveFilterValues(STRUCTURE_FILTER.name, currentUpdateInfoFilterProperties.structureFilter) } .onReset { currentUpdateInfoFilterProperties.structureFilter = storedProperties.getFilterValues(STRUCTURE_FILTER.name) model.updateFilterFromProperties() } } } } private class MyLogProperties(mainProperties: GitUpdateProjectInfoLogProperties) : MainVcsLogUiProperties by mainProperties { var structureFilter: List<String>? = null override fun getFilterValues(filterName: String): List<String>? = structureFilter.takeIf { filterName == STRUCTURE_FILTER.name } override fun saveFilterValues(filterName: String, values: MutableList<String>?) { if (filterName == STRUCTURE_FILTER.name) { structureFilter = values } } } } private typealias ParserFunction = Function<String, List<String>> private typealias JoinerFunction = Function<List<String>, String> internal class ExpandableTextFieldWithReadOnlyText(lineParser: ParserFunction, private val lineJoiner: JoinerFunction) : ExpandableTextField(lineParser, lineJoiner) { var readOnlyText = "" init { addFocusListener(object : FocusAdapter() { override fun focusLost(e: FocusEvent) { val myComponent = this@ExpandableTextFieldWithReadOnlyText if (e.component == myComponent) { val document = myComponent.document val documentText = document.getText(0, document.length) updateReadOnlyText(documentText) } } }) } override fun setText(t: String?) { if (!t.isNullOrBlank() && t != text) { updateReadOnlyText(t) } super.setText(t) } private fun updateReadOnlyText(@NlsSafe text: String) { if (readOnlyText.isBlank()) return val readOnlySuffix = if (text.isBlank()) readOnlyText else lineJoiner.join("", readOnlyText) // NON-NLS with(emptyText as TextComponentEmptyText) { clear() appendText(text, SimpleTextAttributes.REGULAR_ATTRIBUTES) appendText(readOnlySuffix, SimpleTextAttributes.GRAYED_ATTRIBUTES) setTextToTriggerStatus(text) //this will force status text rendering in case if the text field is not empty } } fun JoinerFunction.join(vararg items: String): String = `fun`(items.toList()) } private class StagingAreaAvailablePredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { project.messageBus.connect(disposable).subscribe(CommitModeManager.SETTINGS, object : CommitModeManager.SettingsListener { override fun settingsChanged() { listener(invoke()) } }) } override fun invoke(): Boolean = canEnableStagingArea() } private class ChangeListsEnabledPredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { onChangeListAvailabilityChanged(project, disposable, false) { listener(invoke()) } } override fun invoke(): Boolean = ChangeListManager.getInstance(project).areChangeListsEnabled() }
apache-2.0
ursjoss/sipamato
public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/newstudies/NewStudyListPage.kt
1
9092
package ch.difty.scipamato.publ.web.newstudies import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG import ch.difty.scipamato.common.web.LABEL_TAG import ch.difty.scipamato.publ.entity.NewStudy import ch.difty.scipamato.publ.entity.NewStudyPageLink import ch.difty.scipamato.publ.entity.NewStudyTopic import ch.difty.scipamato.publ.entity.Newsletter import ch.difty.scipamato.publ.persistence.api.NewStudyTopicService import ch.difty.scipamato.publ.web.CommercialFontResourceProvider import ch.difty.scipamato.publ.web.PublicPageParameters import ch.difty.scipamato.publ.web.common.BasePage import ch.difty.scipamato.publ.web.paper.browse.PublicPaperDetailPage import ch.difty.scipamato.publ.web.resources.IcoMoonIconType import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapExternalLink import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapLink import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType import de.agilecoders.wicket.core.markup.html.bootstrap.image.IconType import org.apache.wicket.markup.ComponentTag import org.apache.wicket.markup.head.CssHeaderItem import org.apache.wicket.markup.head.IHeaderResponse import org.apache.wicket.markup.html.basic.Label import org.apache.wicket.markup.html.link.ExternalLink import org.apache.wicket.markup.html.link.Link import org.apache.wicket.markup.html.list.ListItem import org.apache.wicket.markup.html.list.ListView import org.apache.wicket.model.Model import org.apache.wicket.model.PropertyModel import org.apache.wicket.model.StringResourceModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.request.resource.CssResourceReference import org.apache.wicket.spring.injection.annot.SpringBean import org.wicketstuff.annotation.mount.MountPath /** * The page lists 'new studies', i.e. studies that were collected and flagged by the SciPaMaTo-team * as eligible for this page. By default, the newest collection of new studies is presented. * * With the use of page-parameters, an older collection of new studies can be selected instead. * * The page is typically shown in an iframe of a CMS. */ @MountPath("new-studies") @Suppress("SameParameterValue") open class NewStudyListPage(parameters: PageParameters) : BasePage<Void>(parameters) { @SpringBean private lateinit var newStudyTopicService: NewStudyTopicService @SpringBean(name = "simplonFontResourceProvider") private lateinit var simplonFontResourceProvider: CommercialFontResourceProvider @SpringBean(name = "icoMoonFontResourceProvider") private lateinit var icoMoonFontResourceProvider: CommercialFontResourceProvider override fun renderAdditionalCommercialFonts(response: IHeaderResponse) { response.render(CssHeaderItem.forReference(simplonFontResourceProvider.cssResourceReference)) response.render(CssHeaderItem.forReference(icoMoonFontResourceProvider.cssResourceReference)) } override fun renderHead(response: IHeaderResponse) { super.renderHead(response) response.render(CssHeaderItem.forReference(CssResourceReference(NewStudyListPage::class.java, "NewStudyListPage.css"))) } override fun onInitialize() { super.onInitialize() newIntroSection() newNewsletterSection() newExternalLinkSection() newArchiveSectionWithPreviousNewsletters() } /** * Introductory paragraph */ private fun newIntroSection() { queue(newLabel("h1Title")) queue(newLabel("introParagraph")) queue(newDbSearchLink("dbLink", properties.cmsUrlSearchPage)) } private fun newDbSearchLink(id: String, href: String?) = object : ExternalLink( id, href, StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null).string ) { override fun onComponentTag(tag: ComponentTag) { super.onComponentTag(tag) tag.put(TARGET, BLANK) } } /** * The actual newsletter/new study list part with topics and nested studies */ private fun newNewsletterSection() { queue(newNewStudyCollection("topics")) } private fun newNewStudyCollection(id: String): ListView<NewStudyTopic> { val topics = retrieveStudyCollection() paperIdManager.initialize(extractPaperNumbersFrom(topics)) return object : ListView<NewStudyTopic>(id, topics) { override fun populateItem(topic: ListItem<NewStudyTopic>) { topic.add(Label("topicTitle", PropertyModel<Any>(topic.model, "title"))) topic.add(object : ListView<NewStudy>("topicStudies", topic.modelObject.studies) { override fun populateItem(study: ListItem<NewStudy>) { study.add(Label("headline", PropertyModel<Any>(study.model, "headline"))) study.add(Label("description", PropertyModel<Any>(study.model, "description"))) study.add(newLinkToStudy("reference", study)) } }) } } } private fun retrieveStudyCollection(): List<NewStudyTopic> { val issue = pageParameters[PublicPageParameters.ISSUE.parameterName] return if (issue.isNull || issue.isEmpty) newStudyTopicService.findMostRecentNewStudyTopics(languageCode) else newStudyTopicService.findNewStudyTopicsForNewsletterIssue(issue.toString(), languageCode) } private fun extractPaperNumbersFrom(topics: List<NewStudyTopic>): List<Long> = topics.flatMap { it.studies }.map { it.number } /** * Link pointing to the study detail page with the current [study] (with [id]) */ private fun newLinkToStudy(id: String, study: ListItem<NewStudy>): Link<NewStudy> { val pp = PageParameters() pp[PublicPageParameters.NUMBER.parameterName] = study.modelObject.number return object : Link<NewStudy>(id) { override fun onClick() { paperIdManager.setFocusToItem(study.modelObject.number) setResponsePage(PublicPaperDetailPage(pp, pageReference)) } }.apply { add(Label("$id$LABEL_TAG", PropertyModel<String>(study.model, "reference"))) } } /** * Any links configured in database table new_study_page_links will be published in this section. */ private fun newExternalLinkSection() { queue(newLinkList("links")) } private fun newLinkList(id: String): ListView<NewStudyPageLink> { val links = newStudyTopicService.findNewStudyPageLinks(languageCode) return object : ListView<NewStudyPageLink>(id, links) { override fun populateItem(link: ListItem<NewStudyPageLink>) { link.add(newExternalLink("link", link)) } } } private fun newExternalLink(id: String, linkItem: ListItem<NewStudyPageLink>) = object : BootstrapExternalLink( id, Model.of(linkItem.modelObject.url) ) { }.apply { setTarget(BootstrapExternalLink.Target.blank) setIconType(chooseIcon(GlyphIconType.arrowright, IcoMoonIconType.arrow_right)) setLabel(Model.of(linkItem.modelObject.title)) } fun chooseIcon(free: IconType, commercial: IconType): IconType = if (properties.isCommercialFontPresent) commercial else free /** The archive section lists links pointing to previous newsletters with their studies. */ private fun newArchiveSectionWithPreviousNewsletters() { queue(newLabel("h2ArchiveTitle")) queue(newNewsletterArchive("archive")) } private fun newLabel(id: String) = Label( id, StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null) ) private fun newNewsletterArchive(id: String): ListView<Newsletter> { val newsletterCount = properties.numberOfPreviousNewslettersInArchive val newsletters = newStudyTopicService.findArchivedNewsletters(newsletterCount, languageCode) return object : ListView<Newsletter>(id, newsletters) { override fun populateItem(nl: ListItem<Newsletter>) { nl.add(newLinkToArchivedNewsletter("monthName", nl)) } } } private fun newLinkToArchivedNewsletter(id: String, newsletter: ListItem<Newsletter>): Link<Newsletter> { val pp = PageParameters() pp[PublicPageParameters.ISSUE.parameterName] = newsletter.modelObject.issue val monthName = newsletter.modelObject.getMonthName(languageCode) return object : BootstrapLink<Newsletter>(id, Buttons.Type.Link) { override fun onClick() = setResponsePage(NewStudyListPage(pp)) }.apply { setLabel(Model.of(monthName)) setIconType(chooseIcon(GlyphIconType.link, IcoMoonIconType.link)) } } companion object { private const val serialVersionUID = 1L private const val TARGET = "target" private const val BLANK = "_blank" } }
gpl-3.0
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHEditableHtmlPaneHandle.kt
2
2601
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui import com.intellij.CommonBundle import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.scale.JBUIScale import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPreLoadingSubmittableTextFieldModel import org.jetbrains.plugins.github.pullrequest.comment.ui.GHSubmittableTextFieldFactory import org.jetbrains.plugins.github.ui.util.GHUIUtil import org.jetbrains.plugins.github.ui.util.HtmlEditorPane import org.jetbrains.plugins.github.util.successOnEdt import java.util.concurrent.CompletableFuture import javax.swing.JComponent import javax.swing.text.BadLocationException import javax.swing.text.Utilities internal open class GHEditableHtmlPaneHandle(private val editorPane: HtmlEditorPane, private val loadSource: () -> CompletableFuture<String>, private val updateText: (String) -> CompletableFuture<out Any?>) { val panel = NonOpaquePanel(VerticalLayout(JBUIScale.scale(8))).apply { add(wrapEditorPane(editorPane)) } protected open fun wrapEditorPane(editorPane: HtmlEditorPane): JComponent = editorPane private var editor: JComponent? = null fun showAndFocusEditor() { if (editor == null) { val placeHolderText = StringUtil.repeatSymbol('\n', Integer.max(0, getLineCount() - 1)) val model = GHPreLoadingSubmittableTextFieldModel(placeHolderText, loadSource()) { newText -> updateText(newText).successOnEdt { hideEditor() } } editor = GHSubmittableTextFieldFactory(model).create(CommonBundle.message("button.submit"), onCancel = { hideEditor() }) panel.add(editor!!, VerticalLayout.FILL_HORIZONTAL) panel.validate() panel.repaint() } editor?.let { GHUIUtil.focusPanel(it) } } private fun hideEditor() { editor?.let { panel.remove(it) panel.revalidate() panel.repaint() } editor = null } private fun getLineCount(): Int { if (editorPane.document.length == 0) return 0 var lineCount = 0 var offset = 0 while (true) { try { offset = Utilities.getRowEnd(editorPane, offset) + 1 lineCount++ } catch (e: BadLocationException) { break } } return lineCount } }
apache-2.0
LivingDoc/livingdoc
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/LivingDoc.kt
2
5561
package org.livingdoc.engine import org.livingdoc.api.documents.ExecutableDocument import org.livingdoc.api.documents.Group import org.livingdoc.api.tagging.Tag import org.livingdoc.config.ConfigProvider import org.livingdoc.engine.config.TaggingConfig import org.livingdoc.engine.execution.ExecutionException import org.livingdoc.engine.execution.MalformedFixtureException import org.livingdoc.engine.execution.groups.GroupFixture import org.livingdoc.engine.execution.groups.ImplicitGroup import org.livingdoc.reports.ReportsManager import org.livingdoc.repositories.RepositoryManager import org.livingdoc.repositories.config.RepositoryConfiguration import org.livingdoc.results.documents.DocumentResult import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * Executes the given document class and returns the [DocumentResult]. The document's class must be annotated * with [ExecutableDocument]. * * @return the [DocumentResult] of the execution * @throws ExecutionException in case the execution failed in a way that did not produce a viable result * @since 2.0 */ class LivingDoc( private val configProvider: ConfigProvider = ConfigProvider.load(), private val repositoryManager: RepositoryManager = RepositoryManager.from(RepositoryConfiguration.from(configProvider)), private val decisionTableToFixtureMatcher: DecisionTableToFixtureMatcher = DecisionTableToFixtureMatcher(), private val scenarioToFixtureMatcher: ScenarioToFixtureMatcher = ScenarioToFixtureMatcher() ) { companion object { /** * Indicates whether the execution should fail fast due to a specific * thrown exception and not execute any more tests. */ var failFastActivated: Boolean = false /** * Global ExecutorService which uses a WorkStealing(Thread)Pool * for the parallel execution of tasks in the LivingDoc engine */ val executor: ExecutorService = Executors.newWorkStealingPool() } val taggingConfig = TaggingConfig.from(configProvider) /** * Executes the given document classes and returns the list of [DocumentResults][DocumentResult]. The document * classes must be annotated with [ExecutableDocument]. * * @param documentClasses the document classes to execute * @return a list of [DocumentResults][DocumentResult] of the execution * @throws ExecutionException in case the execution failed in a way that did not produce a viable result */ @Throws(ExecutionException::class) fun execute(documentClasses: List<Class<*>>): List<DocumentResult> { // Execute documents val documentResults = documentClasses.filter { val tags = getTags(it) when { taggingConfig.includedTags.isNotEmpty() && tags.none { tag -> taggingConfig.includedTags.contains(tag) } -> false tags.any { tag -> taggingConfig.excludedTags.contains(tag) } -> false else -> true } }.groupBy { documentClass -> extractGroup(documentClass) }.flatMap { (groupClass, documentClasses) -> executeGroup(groupClass, documentClasses) } // Generate reports val reportsManager = ReportsManager.from(configProvider) reportsManager.generateReports(documentResults) // Return results for further processing return documentResults } private fun getTags(documentClass: Class<*>): List<String> { return documentClass.getAnnotationsByType(Tag::class.java).map { it.value } } /** * Executes the given group, which contains the given document classes and returns the list of * [DocumentResults][DocumentResult]. The group class must be annotated with [Group] and the document classes must * be annotated with [ExecutableDocument]. * * @param groupClass the group that contains the documentClasses * @param documentClasses the document classes to execute * @return a list of [DocumentResults][DocumentResult] of the execution * @throws ExecutionException in case the execution failed in a way that did not produce a viable result */ @Throws(ExecutionException::class) private fun executeGroup(groupClass: Class<*>, documentClasses: List<Class<*>>): List<DocumentResult> { return GroupFixture( groupClass, documentClasses, repositoryManager, decisionTableToFixtureMatcher, scenarioToFixtureMatcher ).execute() } private fun extractGroup(documentClass: Class<*>): Class<*> { val declaringGroup = documentClass.declaringClass?.takeIf { declaringClass -> declaringClass.isAnnotationPresent(Group::class.java) } val annotationGroup = documentClass.getAnnotation(ExecutableDocument::class.java).group.java.takeIf { annotationClass -> annotationClass.isAnnotationPresent(Group::class.java) } if (declaringGroup != null && annotationGroup != null && declaringGroup != annotationGroup) throw MalformedFixtureException( documentClass, listOf( "Ambiguous group definition: declared inside ${declaringGroup.name}, " + "annotation specifies ${annotationGroup.name}" ) ) return declaringGroup ?: annotationGroup ?: ImplicitGroup::class.java } }
apache-2.0
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/PathResolverState.kt
1
770
package jetbrains.buildServer.agent.runner import jetbrains.buildServer.agent.Path import jetbrains.buildServer.rx.Observer data class PathResolverState( public val pathToResolve: Path, public val virtualPathObserver: Observer<Path>, public val commandToResolve: Path = Path("")) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PathResolverState if (pathToResolve != other.pathToResolve) return false if (commandToResolve != other.commandToResolve) return false return true } override fun hashCode(): Int { var result = pathToResolve.hashCode() result = 31 * result + commandToResolve.hashCode() return result } }
apache-2.0
Raizlabs/DBFlow
tests/src/androidTest/java/com/dbflow5/sql/language/WhereTest.kt
1
6118
package com.dbflow5.sql.language import com.dbflow5.BaseUnitTest import com.dbflow5.assertEquals import com.dbflow5.config.databaseForTable import com.dbflow5.models.SimpleModel import com.dbflow5.models.SimpleModel_Table.name import com.dbflow5.models.TwoColumnModel import com.dbflow5.models.TwoColumnModel_Table.id import com.dbflow5.query.NameAlias import com.dbflow5.query.OrderBy.Companion.fromNameAlias import com.dbflow5.query.Where import com.dbflow5.query.groupBy import com.dbflow5.query.having import com.dbflow5.query.min import com.dbflow5.query.nameAlias import com.dbflow5.query.or import com.dbflow5.query.property.property import com.dbflow5.query.select import com.dbflow5.query.update import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Test class WhereTest : BaseUnitTest() { @Test fun validateBasicWhere() { val query = select from SimpleModel::class where name.`is`("name") "SELECT * FROM `SimpleModel` WHERE `name`='name'".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateComplexQueryWhere() { val query = select from SimpleModel::class where name.`is`("name") or id.eq(1) and (id.`is`(0) or name.eq("hi")) "SELECT * FROM `SimpleModel` WHERE `name`='name' OR `id`=1 AND (`id`=0 OR `name`='hi')".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateGroupBy() { val query = select from SimpleModel::class where name.`is`("name") groupBy name "SELECT * FROM `SimpleModel` WHERE `name`='name' GROUP BY `name`".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateGroupByNameAlias() { val query = (select from SimpleModel::class where name.`is`("name")).groupBy("name".nameAlias, "id".nameAlias) "SELECT * FROM `SimpleModel` WHERE `name`='name' GROUP BY `name`,`id`".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateGroupByNameProps() { val query = (select from SimpleModel::class where name.`is`("name")).groupBy(name, id) "SELECT * FROM `SimpleModel` WHERE `name`='name' GROUP BY `name`,`id`".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateHaving() { val query = select from SimpleModel::class where name.`is`("name") having name.like("That") "SELECT * FROM `SimpleModel` WHERE `name`='name' HAVING `name` LIKE 'That'".assertEquals(query) assertCanCopyQuery(query) "SELECT * FROM `SimpleModel` GROUP BY exampleValue HAVING MIN(ROWID)>5".assertEquals( (select from SimpleModel::class groupBy NameAlias.rawBuilder("exampleValue").build() having min(NameAlias.rawBuilder("ROWID").build().property).greaterThan(5)) ) } @Test fun validateLimit() { val query = select from SimpleModel::class where name.`is`("name") limit 10 "SELECT * FROM `SimpleModel` WHERE `name`='name' LIMIT 10".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateOffset() { val query = select from SimpleModel::class where name.`is`("name") offset 10 "SELECT * FROM `SimpleModel` WHERE `name`='name' OFFSET 10".assertEquals(query) assertCanCopyQuery(query) } @Test fun validateWhereExists() { val query = (select from SimpleModel::class whereExists (select(name) from SimpleModel::class where name.like("Andrew"))) ("SELECT * FROM `SimpleModel` " + "WHERE EXISTS (SELECT `name` FROM `SimpleModel` WHERE `name` LIKE 'Andrew')").assertEquals(query) assertCanCopyQuery(query) } @Test fun validateOrderByWhere() { val query = (select from SimpleModel::class where name.eq("name")).orderBy(name, true) ("SELECT * FROM `SimpleModel` WHERE `name`='name' ORDER BY `name` ASC").assertEquals(query) assertCanCopyQuery(query) } @Test fun validateOrderByWhereAlias() { val query = (select from SimpleModel::class where name.eq("name")).orderBy("name".nameAlias, true) ("SELECT * FROM `SimpleModel` " + "WHERE `name`='name' ORDER BY `name` ASC").assertEquals(query) assertCanCopyQuery(query) } @Test fun validateOrderBy() { val query = (select from SimpleModel::class where name.eq("name") orderBy fromNameAlias("name".nameAlias).ascending()) ("SELECT * FROM `SimpleModel` " + "WHERE `name`='name' ORDER BY `name` ASC").assertEquals(query) assertCanCopyQuery(query) } private fun <T : Any> assertCanCopyQuery(query: Where<T>) { val actual = query.cloneSelf() query.assertEquals(actual) assertTrue(actual !== query) } @Test fun validateOrderByAll() { val query = (select from TwoColumnModel::class where name.eq("name")) .orderByAll(listOf( fromNameAlias("name".nameAlias).ascending(), fromNameAlias("id".nameAlias).descending())) ("SELECT * FROM `TwoColumnModel` " + "WHERE `name`='name' ORDER BY `name` ASC,`id` DESC").assertEquals(query) assertCanCopyQuery(query) } @Test fun validateNonSelectThrowError() { databaseForTable<SimpleModel> { db -> try { update<SimpleModel>().set(name.`is`("name")).querySingle(db) fail("Non select passed") } catch (i: IllegalArgumentException) { // expected } try { update<SimpleModel>().set(name.`is`("name")).queryList(db) fail("Non select passed") } catch (i: IllegalArgumentException) { // expected } } } @Test fun validate_match_operator() { val query = (select from SimpleModel::class where (name match "%s")) ("SELECT * FROM `SimpleModel` WHERE `name` MATCH '%s'").assertEquals(query) assertCanCopyQuery(query) } }
mit
mtransitapps/mtransit-for-android
src/main/java/org/mtransit/android/ui/type/AgencyTypePagerAdapter.kt
1
1766
package org.mtransit.android.ui.type import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import org.mtransit.android.commons.MTLog import org.mtransit.android.data.IAgencyUIProperties import org.mtransit.android.ui.type.poi.AgencyPOIsFragment import org.mtransit.android.ui.type.rts.RTSAgencyRoutesFragment class AgencyTypePagerAdapter(f: Fragment) : FragmentStateAdapter(f), MTLog.Loggable { companion object { private val LOG_TAG = AgencyTypePagerAdapter::class.java.simpleName } override fun getLogTag(): String = LOG_TAG private var agencies: MutableList<IAgencyUIProperties>? = null fun setAgencies(newAgencies: List<IAgencyUIProperties>?): Boolean { // TODO DiffUtil var changed = false if (!this.agencies.isNullOrEmpty()) { this.agencies?.clear() this.agencies = null // loading changed = true } newAgencies?.let { this.agencies = mutableListOf<IAgencyUIProperties>().apply { changed = addAll(it) } } if (changed) { notifyDataSetChanged() } return changed } fun isReady() = agencies != null override fun getItemCount() = agencies?.size ?: 0 override fun createFragment(position: Int): Fragment { val agency = agencies?.getOrNull(position) ?: throw RuntimeException("Trying to create fragment at $position!") if (agency.isRTS) { return RTSAgencyRoutesFragment.newInstance( agency.authority, agency.colorInt ) } return AgencyPOIsFragment.newInstance( agency.authority, agency.colorInt ) } }
apache-2.0
martinlau/fixture
src/test/kotlin/io/fixture/feature/step/StepDefs.kt
1
5755
/* * #%L * fixture * %% * Copyright (C) 2013 Martin Lau * %% * 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. * #L% */ package io.fixture.feature.step import cucumber.api.java.en.Given import cucumber.api.java.en.Then import cucumber.api.java.en.When import kotlin.test.assertEquals import kotlin.test.assertTrue import org.openqa.selenium.By import org.openqa.selenium.WebDriver import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import kotlin.test.assertNotNull import cucumber.api.PendingException import cucumber.api.DataTable import org.subethamail.wiser.Wiser import java.util.regex.Pattern import java.net.URI import java.net.URL import org.apache.http.impl.client.DefaultHttpClient import org.apache.http.client.methods.HttpGet import org.apache.http.client.HttpClient import org.apache.http.client.methods.HttpHead class StepDefs [Autowired] ( val driver: WebDriver, val httpClient: HttpClient, val wiser: Wiser ) { [Value(value = "#{systemProperties['tomcat.http.port']}")] var tomcatPort: Int? = null [Given(value = """^I open any page""")] fun I_open_any_page() { driver.get("http://localhost:${tomcatPort}/fixture") } [Given(value = """^I select the theme "([^"]*)"$""")] fun I_select_the_theme(theme: String) { driver.get(driver.getCurrentUrl() + "?theme=${theme}") } [When(value = """^I go to the page "([^"]*)"$""")] fun I_go_to_the_page(page: String) { driver.get("http://localhost:${tomcatPort}/fixture${page}") } [When(value = """^I click on the link "([^"]*)"$""")] fun I_click_on_the_link(link: String) { driver.findElement(By.linkText(link))!!.click() } [When(value = """^I log in with the credentials "([^"]*)" and "([^"]*)"$""")] fun I_log_in_with_the_credentials(username: String, password: String) { // HACK: drone.io seems to need some time to load the page - this allows that driver.getCurrentUrl() driver.findElement(By.id("username"))!!.sendKeys(username) driver.findElement(By.id("password"))!!.sendKeys(password) driver.findElement(By.id("submit"))!!.click() } [When(value = """^I fill in the form "([^\"]*)" with:$""")] fun I_fill_in_the_form_with(formId: String, data: DataTable) { val form = driver.findElement(By.id(formId))!! data.asMaps()!!.forEach { val name = it.get("field") val value = it.get("value") val field = form.findElement(By.name(name))!! if (field.getAttribute("type") == "checkbox") { if ("true" == value) field.click() } else { field.sendKeys(value) } } form.submit() } [When(value = """^I click the link in the activation email$""")] fun I_click_the_link_in_the_activation_email() { val message = wiser.getMessages().last!! val pattern = Pattern.compile(""".*(https?://[\da-z\.-]+(:\d+)?[^\s]*).*""", Pattern.DOTALL) val matcher = pattern.matcher(message.toString()!!) if (matcher.matches()) { val url = matcher.group(1) driver.get(url) } } [Then(value = """^the theme should change to "([^"]*)"$""")] fun the_theme_should_change_to(theme: String) { // HACK: drone.io seems to need some time to load the page - this allows that driver.getCurrentUrl() assertTrue(driver.getPageSource().contains("href=\"/fixture/static/bootswatch/2.3.1/${theme}/bootstrap.min.css\"")) } [Then(value = """^I should see the "([^"]*)" link$""")] fun I_should_see_the_link(link: String) { // HACK: drone.io seems to need some time to load the page - this allows that driver.getCurrentUrl() assertNotNull(driver.findElement(By.linkText(link))) } [Then(value = """^I should see the page "([^"]*)"$""")] fun I_should_see_the_page(title: String) { // HACK: drone.io seems to need some time to load the page - this allows that driver.getCurrentUrl() assertEquals(title, driver.getTitle()) } [Then(value = """^I should see the alert "([^"]*)"$""")] fun I_should_see_the_alert(message: String) { // HACK: drone.io seems to need some time to load the page - this allows that driver.getCurrentUrl() assertTrue(driver.findElement(By.className("alert"))!!.getText()!!.contains(message)) } [Then(value = """^all "([^"]*)" tags should have valid "([^"]*)" attributes$""")] fun all_tags_should_have_valid_attributes(tag: String, attribute: String) { val base = driver.getCurrentUrl()!! driver.findElements(By.tagName(tag))?.forEach { val path = it.getAttribute(attribute)!! val uri = URI.create(base).resolve(path) val request = HttpHead(uri) try { val response = httpClient.execute(request)!! assertEquals(200, response.getStatusLine()!!.getStatusCode()) } finally { request.releaseConnection() } } } }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/objects/selfReferenceToCompanionObjectInAnonymousObjectInSuperConstructorCall.kt
4
300
interface IFn { operator fun invoke(): String } abstract class Base(val fn: IFn) class Host { companion object : Base( object : IFn { override fun invoke(): String = Host.ok() } ) { fun ok() = "OK" } } fun box() = Host.Companion.fn()
apache-2.0
blokadaorg/blokada
android5/app/src/main/java/ui/TaskerIntegration.kt
1
2817
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui import android.content.Context import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import com.twofortyfouram.locale.sdk.client.receiver.AbstractPluginSettingReceiver import com.twofortyfouram.locale.sdk.client.ui.activity.AbstractPluginActivity import org.blokada.R import ui.utils.cause import utils.Logger private const val EVENT_KEY_COMMAND = "command" class TaskerActivity : AbstractPluginActivity() { private lateinit var command: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tasker) command = findViewById(R.id.tasker_command) findViewById<Button>(R.id.tasker_done).setOnClickListener { finish() } } override fun onPostCreateWithPreviousResult(previousBundle: Bundle, previousBlurp: String) { when { previousBundle.containsKey(EVENT_KEY_COMMAND) -> { command.setText(previousBundle.getString(EVENT_KEY_COMMAND)) } } } override fun getResultBundle() = Bundle().apply { putString(EVENT_KEY_COMMAND, command.text.toString()) } override fun isBundleValid(bundle: Bundle) = bundle.containsKey(EVENT_KEY_COMMAND) override fun getResultBlurb(bundle: Bundle): String { val command = bundle.getString(EVENT_KEY_COMMAND) return "%s: %s".format("Blokada", command) } } class TaskerReceiver : AbstractPluginSettingReceiver() { private val log = Logger("TaskerReceiver") init { log.v("TaskerReceiver created") } override fun isAsync(): Boolean { return false } override fun firePluginSetting(ctx: Context, bundle: Bundle) { when { bundle.containsKey(EVENT_KEY_COMMAND) -> cmd(ctx, bundle.getString(EVENT_KEY_COMMAND)!!) else -> log.e("unknown app intent") } } private fun cmd(ctx: Context, command: String) { try { log.v("Executing command from Tasker: $command") val intent = getIntentForCommand(command) ctx.startService(intent) Toast.makeText(ctx, "Tasker: Blokada ($command)", Toast.LENGTH_SHORT).show() } catch (ex: Exception) { log.e("Invalid switch app intent".cause(ex)) } } override fun isBundleValid(bundle: Bundle) = bundle.containsKey(EVENT_KEY_COMMAND) }
mpl-2.0
operando/Guild
guild-kotlin/src/main/kotlin/com/os/operando/guild/kt/Quartet.kt
1
829
package com.os.operando.guild.kt import java.io.Serializable /** * A tuple of four elements. * * @param F first element type * @param S second element type * @param T third element type * @param FO fourth element type * @property first First value * @property second Second value * @property third Third value * @property fourth Fourth value */ data class Quartet<out F, out S, out T, out FO>( val first: F, val second: S, val third: T, val fourth: FO) : Serializable { override fun toString(): String = "($first, $second, $third, $fourth)" } infix fun <A, B, C, D, E> Quartet<A, B, C, D>.to(that: E): Quintet<A, B, C, D, E> = Quintet(this.first, this.second, this.third, this.fourth, that) fun <T> Quartet<T, T, T, T>.toList(): List<T> = listOf(first, second, third, fourth)
apache-2.0
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/ProminentObjectProcessor.kt
1
7015
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.objectdetection import android.graphics.RectF import android.util.Log import androidx.annotation.MainThread import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.objects.FirebaseVisionObject import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions import com.google.firebase.ml.md.kotlin.camera.CameraReticleAnimator import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay import com.google.firebase.ml.md.R import com.google.firebase.ml.md.kotlin.camera.WorkflowModel import com.google.firebase.ml.md.kotlin.camera.WorkflowModel.WorkflowState import com.google.firebase.ml.md.kotlin.camera.FrameProcessorBase import com.google.firebase.ml.md.kotlin.settings.PreferenceUtils import java.io.IOException import java.util.ArrayList /** A processor to run object detector in prominent object only mode. */ class ProminentObjectProcessor(graphicOverlay: GraphicOverlay, private val workflowModel: WorkflowModel) : FrameProcessorBase<List<FirebaseVisionObject>>() { private val detector: FirebaseVisionObjectDetector private val confirmationController: ObjectConfirmationController = ObjectConfirmationController(graphicOverlay) private val cameraReticleAnimator: CameraReticleAnimator = CameraReticleAnimator(graphicOverlay) private val reticleOuterRingRadius: Int = graphicOverlay .resources .getDimensionPixelOffset(R.dimen.object_reticle_outer_ring_stroke_radius) init { val optionsBuilder = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) if (PreferenceUtils.isClassificationEnabled(graphicOverlay.context)) { optionsBuilder.enableClassification() } this.detector = FirebaseVision.getInstance().getOnDeviceObjectDetector(optionsBuilder.build()) } override fun stop() { try { detector.close() } catch (e: IOException) { Log.e(TAG, "Failed to close object detector!", e) } } override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionObject>> { return detector.processImage(image) } @MainThread override fun onSuccess( image: FirebaseVisionImage, results: List<FirebaseVisionObject>, graphicOverlay: GraphicOverlay ) { var objects = results if (!workflowModel.isCameraLive) { return } if (PreferenceUtils.isClassificationEnabled(graphicOverlay.context)) { val qualifiedObjects = ArrayList<FirebaseVisionObject>() qualifiedObjects.addAll(objects .filter { it.classificationCategory != FirebaseVisionObject.CATEGORY_UNKNOWN } ) objects = qualifiedObjects } if (objects.isEmpty()) { confirmationController.reset() workflowModel.setWorkflowState(WorkflowState.DETECTING) } else { val objectIndex = 0 val visionObject = objects[objectIndex] if (objectBoxOverlapsConfirmationReticle(graphicOverlay, visionObject)) { // User is confirming the object selection. confirmationController.confirming(visionObject.trackingId) workflowModel.confirmingObject( DetectedObject(visionObject, objectIndex, image), confirmationController.progress ) } else { // Object detected but user doesn't want to pick this one. confirmationController.reset() workflowModel.setWorkflowState(WorkflowState.DETECTED) } } graphicOverlay.clear() if (objects.isEmpty()) { graphicOverlay.add(ObjectReticleGraphic(graphicOverlay, cameraReticleAnimator)) cameraReticleAnimator.start() } else { if (objectBoxOverlapsConfirmationReticle(graphicOverlay, objects[0])) { // User is confirming the object selection. cameraReticleAnimator.cancel() graphicOverlay.add( ObjectGraphicInProminentMode( graphicOverlay, objects[0], confirmationController ) ) if (!confirmationController.isConfirmed && PreferenceUtils.isAutoSearchEnabled(graphicOverlay.context)) { // Shows a loading indicator to visualize the confirming progress if in auto search mode. graphicOverlay.add(ObjectConfirmationGraphic(graphicOverlay, confirmationController)) } } else { // Object is detected but the confirmation reticle is moved off the object box, which // indicates user is not trying to pick this object. graphicOverlay.add( ObjectGraphicInProminentMode( graphicOverlay, objects[0], confirmationController ) ) graphicOverlay.add(ObjectReticleGraphic(graphicOverlay, cameraReticleAnimator)) cameraReticleAnimator.start() } } graphicOverlay.invalidate() } private fun objectBoxOverlapsConfirmationReticle( graphicOverlay: GraphicOverlay, visionObject: FirebaseVisionObject ): Boolean { val boxRect = graphicOverlay.translateRect(visionObject.boundingBox) val reticleCenterX = graphicOverlay.width / 2f val reticleCenterY = graphicOverlay.height / 2f val reticleRect = RectF( reticleCenterX - reticleOuterRingRadius, reticleCenterY - reticleOuterRingRadius, reticleCenterX + reticleOuterRingRadius, reticleCenterY + reticleOuterRingRadius ) return reticleRect.intersect(boxRect) } override fun onFailure(e: Exception) { Log.e(TAG, "Object detection failed!", e) } companion object { private const val TAG = "ProminentObjProcessor" } }
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/typealias/objectLiteralConstructor.kt
5
387
open class LockFreeLinkedListNode(val s: String) private class SendBuffered(s: String) : LockFreeLinkedListNode(s) open class AddLastDesc2<out T : LockFreeLinkedListNode>(val node: T) typealias AddLastDesc<T> = AddLastDesc2<T> fun describeSendBuffered(): AddLastDesc<*> { return object : AddLastDesc<SendBuffered>(SendBuffered("OK")) {} } fun box() = describeSendBuffered().node.s
apache-2.0
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/builtinStubMethods/extendJavaCollections/arrayList.kt
2
366
// KT-6042 java.lang.UnsupportedOperationException with ArrayList // IGNORE_BACKEND: NATIVE class A : ArrayList<String>() fun box(): String { val a = A() val b = A() a.addAll(b) a.addAll(0, b) a.removeAll(b) a.retainAll(b) a.clear() a.add("") a.set(0, "") a.add(0, "") a.removeAt(0) a.remove("") return "OK" }
apache-2.0
JuliusKunze/kotlin-native
performance/src/main/kotlin/org/jetbrains/ring/IntArrayBenchmark.kt
2
3887
/* * Copyright 2010-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.ring open class IntArrayBenchmark { private var _data: IntArray? = null val data: IntArray get() = _data!! fun setup() { val list = IntArray(BENCHMARK_SIZE) var index = 0 for (n in intValues(BENCHMARK_SIZE)) list[index++] = n _data = list } //Benchmark fun copy(): List<Int> { return data.toList() } //Benchmark fun copyManual(): ArrayList<Int> { val list = ArrayList<Int>(data.size) for (item in data) { list.add(item) } return list } //Benchmark fun filterAndCount(): Int { return data.filter { filterLoad(it) }.count() } //Benchmark fun filterSomeAndCount(): Int { return data.filter { filterSome(it) }.count() } //Benchmark fun filterAndMap(): List<String> { return data.filter { filterLoad(it) }.map { mapLoad(it) } } //Benchmark fun filterAndMapManual(): ArrayList<String> { val list = ArrayList<String>() for (it in data) { if (filterLoad(it)) { val value = mapLoad(it) list.add(value) } } return list } //Benchmark fun filter(): List<Int> { return data.filter { filterLoad(it) } } //Benchmark fun filterSome(): List<Int> { return data.filter { filterSome(it) } } //Benchmark fun filterPrime(): List<Int> { return data.filter { filterPrime(it) } } //Benchmark fun filterManual(): ArrayList<Int> { val list = ArrayList<Int>() for (it in data) { if (filterLoad(it)) list.add(it) } return list } //Benchmark fun filterSomeManual(): ArrayList<Int> { val list = ArrayList<Int>() for (it in data) { if (filterSome(it)) list.add(it) } return list } //Benchmark fun countFilteredManual(): Int { var count = 0 for (it in data) { if (filterLoad(it)) count++ } return count } //Benchmark fun countFilteredSomeManual(): Int { var count = 0 for (it in data) { if (filterSome(it)) count++ } return count } //Benchmark fun countFilteredPrimeManual(): Int { var count = 0 for (it in data) { if (filterPrime(it)) count++ } return count } //Benchmark fun countFiltered(): Int { return data.count { filterLoad(it) } } //Benchmark fun countFilteredSome(): Int { return data.count { filterSome(it) } } //Benchmark fun countFilteredPrime(): Int { val res = data.count { filterPrime(it) } //println(res) return res } //Benchmark fun countFilteredLocal(): Int { return data.cnt { filterLoad(it) } } //Benchmark fun countFilteredSomeLocal(): Int { return data.cnt { filterSome(it) } } //Benchmark fun reduce(): Int { return data.fold(0) { acc, it -> if (filterLoad(it)) acc + 1 else acc } } }
apache-2.0
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/relations/MythicRelationManager.kt
1
2179
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.relations import com.tealcube.minecraft.bukkit.mythicdrops.api.choices.Choice import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.Relation import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.RelationManager class MythicRelationManager : RelationManager { private val managedRelations = mutableMapOf<String, Relation>() override fun get(): Set<Relation> = managedRelations.values.toSet() override fun contains(id: String): Boolean = managedRelations.containsKey(id.toLowerCase()) override fun add(toAdd: Relation) { managedRelations[toAdd.name.toLowerCase()] = toAdd } override fun remove(id: String) { managedRelations.remove(id.toLowerCase()) } override fun getById(id: String): Relation? = managedRelations[id.toLowerCase()] override fun clear() { managedRelations.clear() } override fun random(): Relation? = Choice.between(get()).choose() }
mit
Dmedina88/SSB
example/app/src/main/kotlin/com/grayherring/devtalks/data/model/Talk.kt
1
725
package com.grayherring.devtalks.data.model import com.grayherring.devtalks.base.util.notBlank import paperparcel.PaperParcel import paperparcel.PaperParcelable @PaperParcel data class Talk( val presenter: String = "", val title: String = "", val platform: String = "", val description: String = "", val date: String = "", val email: String = "", val slides: String = "", val stream: String = "", val tags: List<String> = ArrayList<String>(), val id: String? ) : PaperParcelable { companion object { @JvmField val CREATOR = PaperParcelTalk.CREATOR } fun isValid(): Boolean { return notBlank(presenter, title, platform, description, date, email, slides, stream) } }
apache-2.0
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/html/render/EmpireRendererHandler.kt
1
3122
package au.com.codeka.warworlds.server.html.render import au.com.codeka.warworlds.common.Log import java.awt.Color import java.awt.color.ColorSpace import java.awt.geom.AffineTransform import java.awt.image.AffineTransformOp import java.awt.image.BufferedImage import java.io.File import java.util.* import javax.imageio.ImageIO /** [RendererHandler] for rendering empire shields. */ class EmpireRendererHandler : RendererHandler() { private val log = Log("EmpireRendererHandler") override fun get() { val empireId = getUrlParameter("empire")!!.toLong() var width = getUrlParameter("width")!!.toInt() var height = getUrlParameter("height")!!.toInt() val bucket = getUrlParameter("bucket") val factor = BUCKET_FACTORS[bucket] if (factor == null) { log.warning("Invalid bucket: %s", request.pathInfo) response.status = 404 return } val cacheFile = File(String.format(Locale.ENGLISH, "data/cache/empire/%d/%dx%d/%s.png", empireId, width, height, bucket)) if (cacheFile.exists()) { serveCachedFile(cacheFile) return } else { cacheFile.parentFile.mkdirs() } width = (width * factor).toInt() height = (height * factor).toInt() // TODO: if they have a custom one, use that //WatchableObject<Empire> empire = EmpireManager.i.getEmpire(empireId); var shieldImage = BufferedImage(128, 128, ColorSpace.TYPE_RGB) val g = shieldImage.createGraphics() g.paint = getShieldColour(empireId) g.fillRect(0, 0, 128, 128) // Merge the shield image with the outline image. shieldImage = mergeShieldImage(shieldImage) // Resize the image if required. if (width != 128 || height != 128) { val w = shieldImage.width val h = shieldImage.height val after = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) val at = AffineTransform() at.scale(width.toFloat() / w.toDouble(), height.toFloat() / h.toDouble()) val scaleOp = AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC) shieldImage = scaleOp.filter(shieldImage, after) } ImageIO.write(shieldImage, "png", cacheFile) serveCachedFile(cacheFile) } private fun getShieldColour(empireID: Long): Color { if (empireID == 0L) { return Color(Color.TRANSLUCENT) } val rand = Random(empireID xor 7438274364563846L) return Color(rand.nextInt(100) + 100, rand.nextInt(100) + 100, rand.nextInt(100) + 100) } private fun mergeShieldImage(shieldImage: BufferedImage): BufferedImage { val finalImage = ImageIO.read(File("data/renderer/empire/shield.png")) val width = finalImage.width val height = finalImage.height val fx = shieldImage.width.toFloat() / width.toFloat() val fy = shieldImage.height.toFloat() / height.toFloat() for (y in 0 until height) { for (x in 0 until width) { var pixel = finalImage.getRGB(x, y) if (pixel and 0xffffff == 0xff00ff) { pixel = shieldImage.getRGB((x * fx).toInt(), (y * fy).toInt()) finalImage.setRGB(x, y, pixel) } } } return finalImage } }
mit
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleBuildFileHighlightingTest.kt
5
3463
// 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.codeInsight.gradle import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.testFramework.runInEdtAndWait import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.Ignore import org.junit.Test abstract class GradleBuildFileHighlightingTest : KotlinGradleImportingTestCase() { class KtsInJsProject2114 : GradleBuildFileHighlightingTest() { @TargetVersions("4.8 <=> 6.0") @Test fun testKtsInJsProject() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProjectUsingSingeModulePerGradleProject() checkHighlighting(buildGradleKts) } } class Simple : GradleBuildFileHighlightingTest() { @TargetVersions("5.3+") @Test fun testSimple() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProjectUsingSingeModulePerGradleProject() checkHighlighting(buildGradleKts) } } class ComplexBuildGradleKts : GradleBuildFileHighlightingTest() { @Ignore @TargetVersions("4.8+") @Test fun testComplexBuildGradleKts() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProjectUsingSingeModulePerGradleProject() checkHighlighting(buildGradleKts) } } class JavaLibraryPlugin14 : GradleBuildFileHighlightingTest() { @Test @TargetVersions("6.0.1+") fun testJavaLibraryPlugin() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProject() checkHighlighting(buildGradleKts) } } protected fun List<VirtualFile>.findBuildGradleKtsFile(): VirtualFile { return singleOrNull { it.name == GradleConstants.KOTLIN_DSL_SCRIPT_NAME } ?: error("Couldn't find any build.gradle.kts file") } protected fun checkHighlighting(file: VirtualFile) { runInEdtAndWait { runReadAction { val psiFile = PsiManager.getInstance(myProject).findFile(file) as? KtFile ?: error("Couldn't find psiFile for virtual file: ${file.canonicalPath}") ScriptConfigurationManager.updateScriptDependenciesSynchronously(psiFile) val bindingContext = psiFile.analyzeWithContent() val diagnostics = bindingContext.diagnostics.filter { it.severity == Severity.ERROR } assert(diagnostics.isEmpty()) { val diagnosticLines = diagnostics.joinToString("\n") { DefaultErrorMessages.render(it) } "Diagnostic list should be empty:\n $diagnosticLines" } } } } override fun testDataDirName() = "highlighting" }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/override/typeMismatchOnOverride/propertyReturnTypeMismatchOnOverride.kt
3
119
// "Change type to 'Int'" "true" interface X { val x: Int } class A : X { override val x: Number<caret> = 42 }
apache-2.0
smmribeiro/intellij-community
platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/LibraryLicensesTester.kt
1
2499
// 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.intellij.build import gnu.trove.THashSet import junit.framework.AssertionFailedError import org.jetbrains.intellij.build.impl.LibraryLicensesListGenerator import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.JpsLibrary import org.jetbrains.jps.model.module.JpsModule import org.junit.rules.ErrorCollector class LibraryLicensesTester(private val project: JpsProject, private val licenses: List<LibraryLicense>) { fun reportMissingLicenses(collector: ErrorCollector) { val nonPublicModules = setOf("intellij.idea.ultimate.build", "intellij.idea.community.build", "buildSrc", "intellij.workspaceModel.performanceTesting") val libraries = HashMap<JpsLibrary, JpsModule>() project.modules.filter { it.name !in nonPublicModules && !it.name.contains("guiTests") && !it.name.startsWith("fleet") && it.name != "intellij.platform.util.immutableKeyValueStore.benchmark" && !it.name.contains("integrationTests", ignoreCase = true)}.forEach { module -> JpsJavaExtensionService.dependencies(module).includedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME).libraries.forEach { libraries[it] = module } } val librariesWithLicenses = licenses.flatMapTo(THashSet()) { it.libraryNames } for ((jpsLibrary, jpsModule) in libraries) { val libraryName = LibraryLicensesListGenerator.getLibraryName(jpsLibrary) if (libraryName !in librariesWithLicenses) { collector.addError(AssertionFailedError(""" |License isn't specified for '$libraryName' library (used in module '${jpsModule.name}' in ${jpsModule.contentRootsList.urls}) |If a library is packaged into IDEA installation information about its license must be added into one of *LibraryLicenses.groovy files |If a library is used in tests only change its scope to 'Test' |If a library is used for compilation only change its scope to 'Provided' """.trimMargin())) } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/variables/unusedVariableWithConstantInitializer.kt
13
76
// "Remove variable 'flag'" "true" fun foo() { val <caret>flag = true }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/project-wizard/core/resources/org/jetbrains/kotlin/tools/projectWizard/templates/ios/dummyFile.kt
6
158
// 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.
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/maxMin/max6.kt
9
330
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'mapIndexed{}.maxOrNull()'" // INTENTION_TEXT_2: "Replace with 'asSequence().mapIndexed{}.maxOrNull()'" fun getMaxLineWidth(list: List<Double>): Double { var max = 0.0 <caret>for ((i, item) in list.withIndex()) { max = Math.max(max, item * i) } return max }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/smart/propertyDelegate/DelegatesDot.kt
13
322
import kotlin.properties.Delegates class C { val v by Delegates.<caret> } // EXIST: { itemText: "notNull", typeText: "ReadWriteProperty<Any?, T>" } // EXIST: { itemText: "observable", typeText: "ReadWriteProperty<Any?, T>" } // EXIST: { itemText: "vetoable", typeText: "ReadWriteProperty<Any?, T>" } // NOTHING_ELSE
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinConventionMethodReferencesSearcher.kt
6
1450
// 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.search.ideaExtensions import com.intellij.openapi.application.QueryExecutorBase import com.intellij.psi.PsiReference import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.util.Processor import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.canBeResolvedWithFrontEnd import org.jetbrains.kotlin.idea.search.usagesSearch.operators.OperatorReferenceSearcher import org.jetbrains.kotlin.idea.util.application.runReadAction class KotlinConventionMethodReferencesSearcher : QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters>() { override fun processQuery(queryParameters: MethodReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { runReadAction { val method = queryParameters.method if (!method.canBeResolvedWithFrontEnd()) return@runReadAction null val operatorSearcher = OperatorReferenceSearcher.create( queryParameters.method, queryParameters.effectiveSearchScope, consumer, queryParameters.optimizer, KotlinReferencesSearchOptions(acceptCallableOverrides = true) ) operatorSearcher }?.run() } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/toCollection/goodReceiver.kt
9
509
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'mapTo(){}'" // IS_APPLICABLE_2: false // AFTER-WARNING: The value 'ArrayList<Int>()' assigned to 'var target: MutableCollection<Int> defined in foo' is never used import java.util.ArrayList fun foo(list: List<MutableCollection<Int>>) { var target: MutableCollection<Int>() target = ArrayList<Int>() <caret>for (collection in list) { target.add(collection.size) } if (target.size > 100) { target = ArrayList<Int>() } }
apache-2.0
smmribeiro/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/ExecutorRunToolbarAction.kt
10
374
// 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.execution.runToolbar interface ExecutorRunToolbarAction : RTBarAction { val process: RunToolbarProcess override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.RIGHT_FLEXIBLE }
apache-2.0
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/CustomizationEquipmentRecyclerViewAdapter.kt
1
6390
package com.habitrpg.android.habitica.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.core.os.bundleOf import com.facebook.drawee.view.SimpleDraweeView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.CustomizationGridItemBinding import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.models.inventory.CustomizationSet import com.habitrpg.android.habitica.models.inventory.Equipment import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.subjects.PublishSubject import java.util.* class CustomizationEquipmentRecyclerViewAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() { var gemBalance: Int = 0 var equipmentList : MutableList<Equipment> = ArrayList() set(value) { field = value notifyDataSetChanged() } var activeEquipment: String? = null set(value) { field = value this.notifyDataSetChanged() } private val selectCustomizationEvents = PublishSubject.create<Equipment>() private val unlockCustomizationEvents = PublishSubject.create<Equipment>() private val unlockSetEvents = PublishSubject.create<CustomizationSet>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder { val viewID: Int = R.layout.customization_grid_item val view = LayoutInflater.from(parent.context).inflate(viewID, parent, false) return EquipmentViewHolder(view) } override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) { (holder as EquipmentViewHolder).bind(equipmentList[position]) } override fun getItemCount(): Int { return equipmentList.size } override fun getItemViewType(position: Int): Int { return if (this.equipmentList[position].javaClass == CustomizationSet::class.java) { 0 } else { 1 } } fun setEquipment(newEquipmentList: List<Equipment>) { this.equipmentList = newEquipmentList.toMutableList() this.notifyDataSetChanged() } fun getSelectCustomizationEvents(): Flowable<Equipment> { return selectCustomizationEvents.toFlowable(BackpressureStrategy.DROP) } fun getUnlockCustomizationEvents(): Flowable<Equipment> { return unlockCustomizationEvents.toFlowable(BackpressureStrategy.DROP) } fun getUnlockSetEvents(): Flowable<CustomizationSet> { return unlockSetEvents.toFlowable(BackpressureStrategy.DROP) } internal inner class EquipmentViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener { private val binding = CustomizationGridItemBinding.bind(itemView) var equipment: Equipment? = null init { itemView.setOnClickListener(this) } fun bind(equipment: Equipment) { this.equipment = equipment DataBindingUtils.loadImage(binding.imageView, "shop_" + this.equipment?.key) if (equipment.owned == true || equipment.value == 0.0) { binding.buyButton.visibility = View.GONE } else { binding.buyButton.visibility = View.VISIBLE binding.priceLabel.currency = "gems" binding.priceLabel.value = if (equipment.gearSet == "animal") { 2.0 } else { equipment.value } } if (activeEquipment == equipment.key) { binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700_brand_border) } else { binding.wrapper.background = itemView.context.getDrawable(R.drawable.layout_rounded_bg_gray_700) } } override fun onClick(v: View) { if (equipment?.owned != true && (equipment?.value ?: 0.0) > 0.0) { val dialogContent = LayoutInflater.from(itemView.context).inflate(R.layout.dialog_purchase_customization, null) as LinearLayout val imageView = dialogContent.findViewById<SimpleDraweeView>(R.id.imageView) DataBindingUtils.loadImage(imageView, "shop_" + this.equipment?.key) val priceLabel = dialogContent.findViewById<TextView>(R.id.priceLabel) priceLabel.text = if (equipment?.gearSet == "animal") { 2.0 } else { equipment?.value ?: 0 }.toString() (dialogContent.findViewById<View>(R.id.gem_icon) as? ImageView)?.setImageBitmap(HabiticaIconsHelper.imageOfGem()) val dialog = HabiticaAlertDialog(itemView.context) dialog.addButton(R.string.purchase_button, true) { _, _ -> if (equipment?.value ?: 0.0 > gemBalance) { MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", false))) return@addButton } equipment?.let { unlockCustomizationEvents.onNext(it) } } dialog.setTitle(R.string.purchase_customization) dialog.setAdditionalContentView(dialogContent) dialog.addButton(R.string.reward_dialog_dismiss, false) dialog.show() return } if (equipment?.key == activeEquipment) { return } equipment?.let { selectCustomizationEvents.onNext(it) } } } }
gpl-3.0
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfAccessor.kt
1
15381
package de.fabmax.kool.modules.gltf import de.fabmax.kool.math.* import de.fabmax.kool.util.DataStream import kotlinx.serialization.Serializable import kotlinx.serialization.Transient /** * A typed view into a bufferView. A bufferView contains raw binary data. An accessor provides a typed view into a * bufferView or a subset of a bufferView similar to how WebGL's vertexAttribPointer() defines an attribute in a * buffer. * * @param bufferView The index of the bufferView. * @param byteOffset The offset relative to the start of the bufferView in bytes. * @param componentType The datatype of components in the attribute. * @param normalized Specifies whether integer data values should be normalized. * @param count The number of attributes referenced by this accessor. * @param type Specifies if the attribute is a scalar, vector, or matrix. * @param max Maximum value of each component in this attribute. * @param min Minimum value of each component in this attribute. */ @Serializable data class GltfAccessor( val bufferView: Int = -1, val byteOffset: Int = 0, val componentType: Int, val normalized: Boolean = false, val count: Int, val type: String, val max: List<Float>? = null, val min: List<Float>? = null, val sparse: Sparse? = null, val name: String? = null ) { @Transient var bufferViewRef: GltfBufferView? = null companion object { const val TYPE_SCALAR = "SCALAR" const val TYPE_VEC2 = "VEC2" const val TYPE_VEC3 = "VEC3" const val TYPE_VEC4 = "VEC4" const val TYPE_MAT2 = "MAT2" const val TYPE_MAT3 = "MAT3" const val TYPE_MAT4 = "MAT4" const val COMP_TYPE_BYTE = 5120 const val COMP_TYPE_UNSIGNED_BYTE = 5121 const val COMP_TYPE_SHORT = 5122 const val COMP_TYPE_UNSIGNED_SHORT = 5123 const val COMP_TYPE_INT = 5124 const val COMP_TYPE_UNSIGNED_INT = 5125 const val COMP_TYPE_FLOAT = 5126 val COMP_INT_TYPES = setOf( COMP_TYPE_BYTE, COMP_TYPE_UNSIGNED_BYTE, COMP_TYPE_SHORT, COMP_TYPE_UNSIGNED_SHORT, COMP_TYPE_INT, COMP_TYPE_UNSIGNED_INT) } @Serializable data class Sparse( val count: Int, val indices: SparseIndices, val values: SparseValues ) @Serializable data class SparseIndices( val bufferView: Int, val byteOffset: Int = 0, val componentType: Int ) { @Transient lateinit var bufferViewRef: GltfBufferView } @Serializable data class SparseValues( val bufferView: Int, val byteOffset: Int = 0 ) { @Transient lateinit var bufferViewRef: GltfBufferView } } abstract class DataStreamAccessor(val accessor: GltfAccessor) { private val elemByteSize: Int private val byteStride: Int private val buffer: GltfBufferView? = accessor.bufferViewRef private val stream: DataStream? private val sparseIndexStream: DataStream? private val sparseValueStream: DataStream? private val sparseIndexType: Int private var nextSparseIndex: Int var index: Int = 0 set(value) { field = value stream?.index = value * byteStride } init { stream = if (buffer != null) { DataStream(buffer.bufferRef.data, accessor.byteOffset + buffer.byteOffset) } else { null } if (accessor.sparse != null) { sparseIndexStream = DataStream(accessor.sparse.indices.bufferViewRef.bufferRef.data, accessor.sparse.indices.bufferViewRef.byteOffset) sparseValueStream = DataStream(accessor.sparse.values.bufferViewRef.bufferRef.data, accessor.sparse.values.bufferViewRef.byteOffset) sparseIndexType = accessor.sparse.indices.componentType nextSparseIndex = sparseIndexStream.nextIntComponent(sparseIndexType) } else { sparseIndexStream = null sparseValueStream = null sparseIndexType = 0 nextSparseIndex = -1 } val compByteSize = when (accessor.componentType) { GltfAccessor.COMP_TYPE_BYTE -> 1 GltfAccessor.COMP_TYPE_UNSIGNED_BYTE -> 1 GltfAccessor.COMP_TYPE_SHORT -> 2 GltfAccessor.COMP_TYPE_UNSIGNED_SHORT -> 2 GltfAccessor.COMP_TYPE_INT -> 4 GltfAccessor.COMP_TYPE_UNSIGNED_INT -> 4 GltfAccessor.COMP_TYPE_FLOAT -> 4 else -> throw IllegalArgumentException("Unknown accessor component type: ${accessor.componentType}") } val numComponents = when(accessor.type) { GltfAccessor.TYPE_SCALAR -> 1 GltfAccessor.TYPE_VEC2 -> 2 GltfAccessor.TYPE_VEC3 -> 3 GltfAccessor.TYPE_VEC4 -> 4 GltfAccessor.TYPE_MAT2 -> 4 GltfAccessor.TYPE_MAT3 -> 9 GltfAccessor.TYPE_MAT4 -> 16 else -> throw IllegalArgumentException("Unsupported accessor type: ${accessor.type}") } // fixme: some mat types require padding (also depending on component type) which is currently not considered elemByteSize = compByteSize * numComponents byteStride = if (buffer != null && buffer.byteStride > 0) { buffer.byteStride } else { elemByteSize } } private fun selectDataStream() = if (index != nextSparseIndex) stream else sparseValueStream protected fun nextInt(): Int { if (index < accessor.count) { return selectDataStream()?.nextIntComponent(accessor.componentType) ?: 0 } else { throw IndexOutOfBoundsException("Accessor overflow") } } protected fun nextFloat(): Float { if (accessor.componentType == GltfAccessor.COMP_TYPE_FLOAT) { if (index < accessor.count) { return selectDataStream()?.readFloat() ?: 0f } else { throw IndexOutOfBoundsException("Accessor overflow") } } else { // implicitly convert int type to normalized float return nextInt() / when (accessor.componentType) { GltfAccessor.COMP_TYPE_BYTE -> 128f GltfAccessor.COMP_TYPE_UNSIGNED_BYTE -> 255f GltfAccessor.COMP_TYPE_SHORT -> 32767f GltfAccessor.COMP_TYPE_UNSIGNED_SHORT -> 65535f GltfAccessor.COMP_TYPE_INT -> 2147483647f GltfAccessor.COMP_TYPE_UNSIGNED_INT -> 4294967296f else -> throw IllegalStateException("Unknown component type: ${accessor.componentType}") } } } protected fun nextDouble() = nextFloat().toDouble() private fun DataStream.nextIntComponent(componentType: Int): Int { return when (componentType) { GltfAccessor.COMP_TYPE_BYTE -> readByte() GltfAccessor.COMP_TYPE_UNSIGNED_BYTE -> readUByte() GltfAccessor.COMP_TYPE_SHORT -> readShort() GltfAccessor.COMP_TYPE_UNSIGNED_SHORT -> readUShort() GltfAccessor.COMP_TYPE_INT -> readInt() GltfAccessor.COMP_TYPE_UNSIGNED_INT -> readUInt() else -> throw IllegalArgumentException("Invalid component type: $componentType") } } protected fun advance() { if (index == nextSparseIndex && sparseIndexStream?.hasRemaining() == true) { nextSparseIndex = sparseIndexStream.nextIntComponent(sparseIndexType) } index++ } } /** * Utility class to retrieve scalar integer values from an accessor. The provided accessor must have a non floating * point component type (byte, short or int either signed or unsigned) and must be of type SCALAR. * * @param accessor [GltfAccessor] to use. */ class IntAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_SCALAR) { throw IllegalArgumentException("IntAccessor requires accessor type ${GltfAccessor.TYPE_SCALAR}, provided was ${accessor.type}") } if (accessor.componentType !in GltfAccessor.COMP_INT_TYPES) { throw IllegalArgumentException("IntAccessor requires a (byte / short / int) component type, provided was ${accessor.componentType}") } } fun next(): Int { if (index < accessor.count) { val i = nextInt() advance() return i } else { throw IndexOutOfBoundsException("Accessor overflow") } } } /** * Utility class to retrieve scalar float values from an accessor. The provided accessor must have a float component * type and must be of type SCALAR. * * @param accessor [GltfAccessor] to use. */ class FloatAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_SCALAR) { throw IllegalArgumentException("Vec2fAccessor requires accessor type ${GltfAccessor.TYPE_SCALAR}, provided was ${accessor.type}") } // if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) { // throw IllegalArgumentException("FloatAccessor requires a float component type, provided was ${accessor.componentType}") // } } fun next(): Float { val f = nextFloat() advance() return f } fun nextD() = next().toDouble() } /** * Utility class to retrieve Vec2 float values from an accessor. The provided accessor must have a float component type * and must be of type VEC2. * * @param accessor [GltfAccessor] to use. */ class Vec2fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_VEC2) { throw IllegalArgumentException("Vec2fAccessor requires accessor type ${GltfAccessor.TYPE_VEC2}, provided was ${accessor.type}") } // if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) { // throw IllegalArgumentException("Vec2fAccessor requires a float component type, provided was ${accessor.componentType}") // } } fun next(): MutableVec2f = next(MutableVec2f()) fun next(result: MutableVec2f): MutableVec2f { result.x = nextFloat() result.y = nextFloat() advance() return result } fun nextD(): MutableVec2d = nextD(MutableVec2d()) fun nextD(result: MutableVec2d): MutableVec2d { result.x = nextDouble() result.y = nextDouble() advance() return result } } /** * Utility class to retrieve Vec3 float values from an accessor. The provided accessor must have a float component type * and must be of type VEC3. * * @param accessor [GltfAccessor] to use. */ class Vec3fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_VEC3) { throw IllegalArgumentException("Vec3fAccessor requires accessor type ${GltfAccessor.TYPE_VEC3}, provided was ${accessor.type}") } // if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) { // throw IllegalArgumentException("Vec3fAccessor requires a float component type, provided was ${accessor.componentType}") // } } fun next(): MutableVec3f = next(MutableVec3f()) fun next(result: MutableVec3f): MutableVec3f { result.x = nextFloat() result.y = nextFloat() result.z = nextFloat() advance() return result } fun nextD(): MutableVec3d = nextD(MutableVec3d()) fun nextD(result: MutableVec3d): MutableVec3d { result.x = nextDouble() result.y = nextDouble() result.z = nextDouble() advance() return result } } /** * Utility class to retrieve Vec4 float values from an accessor. The provided accessor must have a float component type * and must be of type VEC4. * * @param accessor [GltfAccessor] to use. */ class Vec4fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_VEC4) { throw IllegalArgumentException("Vec4fAccessor requires accessor type ${GltfAccessor.TYPE_VEC4}, provided was ${accessor.type}") } // if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) { // throw IllegalArgumentException("Vec4fAccessor requires a float component type, provided was ${accessor.componentType}") // } } fun next(): MutableVec4f = next(MutableVec4f()) fun next(result: MutableVec4f): MutableVec4f { result.x = nextFloat() result.y = nextFloat() result.z = nextFloat() result.w = nextFloat() advance() return result } fun nextD(): MutableVec4d = nextD(MutableVec4d()) fun nextD(result: MutableVec4d): MutableVec4d { result.x = nextDouble() result.y = nextDouble() result.z = nextDouble() result.w = nextDouble() advance() return result } } /** * Utility class to retrieve Vec4 int values from an accessor. The provided accessor must have a non floating * point component type (byte, short or int either signed or unsigned) and must be of type VEC4. * * @param accessor [GltfAccessor] to use. */ class Vec4iAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_VEC4) { throw IllegalArgumentException("Vec4iAccessor requires accessor type ${GltfAccessor.TYPE_VEC4}, provided was ${accessor.type}") } if (accessor.componentType !in GltfAccessor.COMP_INT_TYPES) { throw IllegalArgumentException("Vec4fAccessor requires a (byte / short / int) component type, provided was ${accessor.componentType}") } } fun next(): MutableVec4i = next(MutableVec4i()) fun next(result: MutableVec4i): MutableVec4i { result.x = nextInt() result.y = nextInt() result.z = nextInt() result.w = nextInt() advance() return result } } /** * Utility class to retrieve Mat4 float values from an accessor. The provided accessor must have a float component type * and must be of type MAT4. * * @param accessor [GltfAccessor] to use. */ class Mat4fAccessor(accessor: GltfAccessor) : DataStreamAccessor(accessor) { init { if (accessor.type != GltfAccessor.TYPE_MAT4) { throw IllegalArgumentException("Mat4fAccessor requires accessor type ${GltfAccessor.TYPE_MAT4}, provided was ${accessor.type}") } if (accessor.componentType != GltfAccessor.COMP_TYPE_FLOAT) { throw IllegalArgumentException("Mat4fAccessor requires a float component type, provided was ${accessor.componentType}") } } fun next(): Mat4f = next(Mat4f()) fun next(result: Mat4f): Mat4f { for (i in 0..15) { result.matrix[i] = nextFloat() } advance() return result } fun nextD(): Mat4d = nextD(Mat4d()) fun nextD(result: Mat4d): Mat4d { for (i in 0..15) { result.matrix[i] = nextDouble() } advance() return result } }
apache-2.0
idea4bsd/idea4bsd
java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.kt
4
6016
/* * 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.icons.AllIcons import com.intellij.openapi.keymap.MacKeymapUtil import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.SystemInfo import com.intellij.psi.PsiElement import com.intellij.ui.popup.WizardPopup import com.intellij.ui.popup.list.ListPopupImpl import com.intellij.util.PsiNavigateUtil import java.awt.event.ActionEvent import java.awt.event.KeyEvent import javax.swing.AbstractAction import javax.swing.Icon import javax.swing.KeyStroke class RecentTestsListPopup(popupStep: ListPopupStep<RecentTestsPopupEntry>, private val testRunner: RecentTestRunner, private val locator: TestLocator) : ListPopupImpl(popupStep) { init { shiftReleased() registerActions(this) val shift = if (SystemInfo.isMac) MacKeymapUtil.SHIFT else "Shift" setAdText("Debug with $shift, navigate with F4") } override fun createPopup(parent: WizardPopup?, step: PopupStep<*>?, parentValue: Any?): WizardPopup { val popup = super.createPopup(parent, step, parentValue) registerActions(popup) return popup } private fun registerActions(popup: WizardPopup) { popup.registerAction("alternate", KeyStroke.getKeyStroke("shift pressed SHIFT"), object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { shiftPressed() } }) popup.registerAction("restoreDefault", KeyStroke.getKeyStroke("released SHIFT"), object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { shiftReleased() } }) popup.registerAction("invokeAction", KeyStroke.getKeyStroke("shift ENTER"), object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { handleSelect(true) } }) popup.registerAction("navigate", KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { val values = selectedValues if (values.size == 1) { val entry = values[0] as RecentTestsPopupEntry getElement(entry)?.let { cancel() PsiNavigateUtil.navigate(it) } } } }) } private fun getElement(entry: RecentTestsPopupEntry): PsiElement? { var element: PsiElement? = null entry.accept(object : TestEntryVisitor() { override fun visitTest(test: SingleTestEntry) { element = locator.getLocation(test.url)?.psiElement } override fun visitSuite(suite: SuiteEntry) { element = locator.getLocation(suite.suiteUrl)?.psiElement } override fun visitRunConfiguration(configuration: RunConfigurationEntry) { if (configuration.suites.size == 1) { visitSuite(configuration.suites[0]) } } }) return element } private fun shiftPressed() { setCaption("Debug Recent Tests") testRunner.setMode(RecentTestRunner.Mode.DEBUG) } private fun shiftReleased() { setCaption("Run Recent Tests") testRunner.setMode(RecentTestRunner.Mode.RUN) } } class SelectTestStep(title: String?, tests: List<RecentTestsPopupEntry>, private val runner: RecentTestRunner) : BaseListPopupStep<RecentTestsPopupEntry>(title, tests) { override fun getIconFor(value: RecentTestsPopupEntry): Icon? { if (value is SingleTestEntry) { return AllIcons.RunConfigurations.TestFailed } else { return AllIcons.RunConfigurations.TestPassed } } override fun getTextFor(value: RecentTestsPopupEntry) = value.presentation override fun isSpeedSearchEnabled() = true override fun hasSubstep(selectedValue: RecentTestsPopupEntry) = getConfigurations(selectedValue).isNotEmpty() override fun onChosen(entry: RecentTestsPopupEntry, finalChoice: Boolean): PopupStep<RecentTestsPopupEntry>? { if (finalChoice) { runner.run(entry) return null } val configurations = getConfigurations(entry) return SelectConfigurationStep(configurations, runner) } private fun getConfigurations(entry: RecentTestsPopupEntry): List<RecentTestsPopupEntry> { val collector = TestConfigurationCollector() entry.accept(collector) return collector.getEnclosingConfigurations() } } class SelectConfigurationStep(items: List<RecentTestsPopupEntry>, private val runner: RecentTestRunner) : BaseListPopupStep<RecentTestsPopupEntry>(null, items) { override fun getTextFor(value: RecentTestsPopupEntry): String { var presentation = value.presentation value.accept(object : TestEntryVisitor() { override fun visitSuite(suite: SuiteEntry) { presentation = "[suite] " + presentation } override fun visitRunConfiguration(configuration: RunConfigurationEntry) { presentation = "[configuration] " + presentation } }) return presentation } override fun getIconFor(value: RecentTestsPopupEntry?) = AllIcons.RunConfigurations.Junit override fun onChosen(selectedValue: RecentTestsPopupEntry, finalChoice: Boolean): PopupStep<RecentTestsPopupEntry>? { if (finalChoice) { runner.run(selectedValue) } return null } }
apache-2.0
550609334/Twobbble
app/src/main/java/com/twobbble/view/activity/BucketShotsActivity.kt
1
6485
package com.twobbble.view.activity import android.app.ActivityOptions import android.content.Intent import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import com.twobbble.R import com.twobbble.application.App import com.twobbble.entity.Shot import com.twobbble.presenter.BucketShotsPresenter import com.twobbble.tools.hideErrorImg import com.twobbble.tools.showErrorImg import com.twobbble.tools.toast import com.twobbble.view.adapter.ItemShotAdapter import com.twobbble.view.api.IBucketShotsView import com.twobbble.view.customview.ItemSwipeRemoveCallback import kotlinx.android.synthetic.main.activity_bucket_shots.* import kotlinx.android.synthetic.main.error_layout.* import kotlinx.android.synthetic.main.list.* import org.greenrobot.eventbus.EventBus import org.jetbrains.anko.doAsync class BucketShotsActivity : BaseActivity(), IBucketShotsView { private var mId: Long = 0 private var mTitle: String? = null private val mPresenter: BucketShotsPresenter by lazy { BucketShotsPresenter(this) } private var isLoading: Boolean = false private var mPage: Int = 1 lateinit private var mShots: MutableList<Shot> private var mListAdapter: ItemShotAdapter? = null private var mDelPosition: Int = 0 private lateinit var mDelShot: Shot companion object { val KEY_ID = "id" val KEY_TITLE = "title" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bucket_shots) mId = intent.getLongExtra(KEY_ID, 0) mTitle = intent.getStringExtra(KEY_TITLE) init() getShots() } private fun init() { Toolbar.title = mTitle mRefresh.setColorSchemeResources(R.color.google_red, R.color.google_yellow, R.color.google_green, R.color.google_blue) val layoutManager = LinearLayoutManager(App.instance, LinearLayoutManager.VERTICAL, false) mRecyclerView.layoutManager = layoutManager mRecyclerView.itemAnimator = DefaultItemAnimator() } fun getShots(isLoadMore: Boolean = false) { isLoading = true mPresenter.getBucketShots(id = mId, page = mPage, isLoadMore = isLoadMore) } override fun onStart() { super.onStart() bindEvent() } private fun bindEvent() { Toolbar.setNavigationOnClickListener { finish() } mRefresh.setOnRefreshListener { mPage = 1 getShots(false) } mErrorLayout.setOnClickListener { hideErrorImg(mErrorLayout) getShots(false) } mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { val linearManager = recyclerView?.layoutManager as LinearLayoutManager val position = linearManager.findLastVisibleItemPosition() if (mShots.isNotEmpty() && position == mShots.size) { if (!isLoading) { mPage += 1 getShots(true) } } } }) val itemTouchHelper = ItemTouchHelper(ItemSwipeRemoveCallback { delPosition, _ -> mDelShot = mShots[delPosition] mListAdapter?.deleteItem(delPosition) mDelPosition = delPosition mDialogManager.showOptionDialog( resources.getString(R.string.delete_shot), resources.getString(R.string.whether_to_delete_shot_from_bucket), confirmText = resources.getString(R.string.delete), onConfirm = { mPresenter.removeShotFromBucket(id = mId, shot_id = mDelShot.id) }, onCancel = { mListAdapter?.addItem(delPosition, mDelShot) mRecyclerView.scrollToPosition(delPosition) }) }) itemTouchHelper.attachToRecyclerView(mRecyclerView) } override fun onDestroy() { super.onDestroy() mPresenter.unSubscriber() } override fun showProgress() { if (mListAdapter == null) mRefresh.isRefreshing = true } override fun hideProgress() { mRefresh.isRefreshing = false } override fun showProgressDialog(msg: String?) { mDialogManager.showCircleProgressDialog() } override fun hideProgressDialog() { mDialogManager.dismissAll() } override fun getShotSuccess(shots: MutableList<Shot>?, isLoadMore: Boolean) { isLoading = false if (shots != null && shots.isNotEmpty()) { if (!isLoadMore) { mountList(shots) } else { mListAdapter?.addItems(shots) } } else { if (!isLoadMore) { showErrorImg(mErrorLayout, imgResID = R.mipmap.img_empty_buckets) } else { mListAdapter?.hideProgress() } } } private fun mountList(shots: MutableList<Shot>) { mShots = shots mListAdapter = ItemShotAdapter(mShots, { EventBus.getDefault().postSticky(mShots[it]) startActivity(Intent(this, DetailsActivity::class.java), ActivityOptions.makeSceneTransitionAnimation(this).toBundle()) }, { EventBus.getDefault().postSticky(shots[it].user) startActivity(Intent(applicationContext, UserActivity::class.java)) }) mRecyclerView.adapter = mListAdapter } override fun getShotFailed(msg: String, isLoadMore: Boolean) { isLoading = false toast(msg) if (!isLoadMore) { if (mListAdapter == null) showErrorImg(mErrorLayout, msg, R.mipmap.img_network_error_2) } else { mListAdapter?.loadError { getShots(true) } } } override fun removeShotSuccess() { toast(R.string.delete_success) } override fun removeShotFailed(msg: String) { toast("${resources.getString(R.string.delete_success)}:$msg") mListAdapter?.addItem(mDelPosition, mDelShot) mRecyclerView.scrollToPosition(mDelPosition) } }
apache-2.0
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/pureKotlin/renameFileWithFunctionOverload/foo1.kt
15
30
package foo fun f(a: Any) {}
apache-2.0
lsmaira/gradle
buildSrc/subprojects/buildquality/src/main/kotlin/org/gradle/gradlebuild/buildquality/VerifyBuildEnvironmentPlugin.kt
2
1483
package org.gradle.gradlebuild.buildquality import availableJavaInstallations import org.gradle.api.Plugin import org.gradle.api.Project import java.nio.charset.Charset import org.gradle.api.tasks.compile.AbstractCompile import org.gradle.kotlin.dsl.* open class VerifyBuildEnvironmentPlugin : Plugin<Project> { override fun apply(project: Project): Unit = project.run { validateForProductionEnvironments(project) validateForAllCompileTasks(project) } private fun validateForProductionEnvironments(rootProject: Project) = rootProject.tasks.register("verifyIsProductionBuildEnvironment") { doLast { rootProject.availableJavaInstallations.validateForProductionEnvironment() val systemCharset = Charset.defaultCharset().name() assert(systemCharset == "UTF-8") { "Platform encoding must be UTF-8. Is currently $systemCharset. Set -Dfile.encoding=UTF-8" } } } private fun validateForAllCompileTasks(rootProject: Project) { val verifyBuildEnvironment = rootProject.tasks.register("verifyBuildEnvironment") { doLast { rootProject.availableJavaInstallations.validateForCompilation() } } rootProject.subprojects { tasks.withType<AbstractCompile>().configureEach { dependsOn(verifyBuildEnvironment) } } } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/indentationOnNewline/emptyParameters/EmptyConditionInWhen.after.kt
24
91
fun a() { when ( <caret> ) } // SET_FALSE: ALIGN_MULTILINE_METHOD_BRACKETS
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/bottom-mpp/src/jvmWithJavaiOSMain/kotlin/transitiveStory/midActual/sourceCalls/intemediateCall/SecondModCaller.kt
2
2109
package transitiveStory.midActual.sourceCalls.intemediateCall import transitiveStory.bottomActual.mppBeginning.BottomActualDeclarations import transitiveStory.bottomActual.mppBeginning.regularTLfunInTheBottomActualCommmon // https://youtrack.jetbrains.com/issue/KT-33731 import transitiveStory.bottomActual.intermediateSrc.* class SecondModCaller { // ========= api calls (attempt to) ========== // java val jApiOne = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: JavaApiContainer'")!>JavaApiContainer<!>() // kotlin val kApiOne = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: KotlinApiContainer'")!>KotlinApiContainer<!>() // ========= mpp-bottom-actual calls ========== // common source set val interCallOne = regularTLfunInTheBottomActualCommmon("Some string from `mpp-mid-actual` module") val interCallTwo = BottomActualDeclarations.inTheCompanionOfBottomActualDeclarations val interCallThree = BottomActualDeclarations().simpleVal // https://youtrack.jetbrains.com/issue/KT-33731 // intermediate source set val interCallFour = InBottomActualIntermediate().p val interCallFive = IntermediateMPPClassInBottomActual() // ========= jvm18 source set (attempt to) ========== // java val interCallSix = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: JApiCallerInJVM18'")!>JApiCallerInJVM18<!>() // kotlin val interCallSeven = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: Jvm18KApiInheritor'")!>Jvm18KApiInheritor<!>() val interCallEight = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: Jvm18JApiInheritor'")!>Jvm18JApiInheritor<!>() val interCallNine = IntermediateMPPClassInBottomActual() } // experiments with intermod inheritance class BottomActualCommonInheritor : BottomActualDeclarations() expect class <!LINE_MARKER("descr='Has actuals in Native, JVM'")!>BottomActualMPPInheritor<!> : BottomActualDeclarations
apache-2.0
PeteGabriel/Yamda
app/src/main/java/com/dev/moviedb/mvvm/repository/remote/dto/ResultDTO.kt
1
1924
package com.dev.moviedb.mvvm.repository.remote.dto import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class Result { @SerializedName("poster_path") @Expose var posterPath: Any? = null @SerializedName("popularity") @Expose var popularity: Double? = null @SerializedName("id") @Expose var id: Int? = null @SerializedName("overview") @Expose var overview: String? = null @SerializedName("backdrop_path") @Expose var backdropPath: Any? = null @SerializedName("vote_average") @Expose var voteAverage: Int? = null @SerializedName("media_type") @Expose var mediaType: String? = null @SerializedName("first_air_date") @Expose var firstAirDate: String? = null @SerializedName("origin_country") @Expose var originCountry: List<String>? = null @SerializedName("genre_ids") @Expose var genreIds: List<Int>? = null @SerializedName("original_language") @Expose var originalLanguage: String? = null @SerializedName("vote_count") @Expose var voteCount: Int? = null @SerializedName("name") @Expose var name: String? = null @SerializedName("original_name") @Expose var originalName: String? = null @SerializedName("adult") @Expose var adult: Boolean? = null @SerializedName("release_date") @Expose var releaseDate: String? = null @SerializedName("original_title") @Expose var originalTitle: String? = null @SerializedName("title") @Expose var title: String? = null @SerializedName("video") @Expose var video: Boolean? = null @SerializedName("profile_path") @Expose var profilePath: String? = null @SerializedName("known_for") @Expose var knownFor: List<KnownFor>? = null }
gpl-3.0
siosio/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/TextFieldComponent.kt
1
2108
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.textField import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.JComponent class TextFieldComponent( context: Context, labelText: String? = null, description: String? = null, initialValue: String? = null, validator: SettingValidator<String>? = null, onValueUpdate: (String, isByUser: Boolean) -> Unit = { _, _ -> } ) : UIComponent<String>( context, labelText, validator, onValueUpdate ) { private var isDisabled: Boolean = false private var cachedValueWhenDisabled: String? = null private val textField = textField(initialValue.orEmpty(), ::fireValueUpdated) override val alignTarget: JComponent? get() = textField override val uiComponent = componentWithCommentAtBottom(textField, description) override fun updateUiValue(newValue: String) = safeUpdateUi { textField.text = newValue } fun onUserType(action: () -> Unit) { textField.addKeyListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent?) = action() }) } fun disable(@Nls message: String) { cachedValueWhenDisabled = getUiValue() textField.isEditable = false textField.foreground = UIUtil.getLabelDisabledForeground() isDisabled = true updateUiValue(message) } override fun validate(value: String) { if (isDisabled) return super.validate(value) } override fun getUiValue(): String = cachedValueWhenDisabled ?: textField.text }
apache-2.0
siosio/intellij-community
java/idea-ui/src/com/intellij/ide/projectWizard/generators/JavaBuildSystemType.kt
1
3039
// 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.ide.projectWizard.generators import com.intellij.ide.highlighter.ModuleFileType import com.intellij.ide.util.projectWizard.JavaModuleBuilder import com.intellij.ide.wizard.BuildSystemType import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.UIBundle import com.intellij.ui.layout.* import java.nio.file.Paths abstract class JavaBuildSystemType<P>(override val name: String) : BuildSystemType<JavaSettings, P> { companion object { var EP_NAME = ExtensionPointName<JavaBuildSystemType<*>>("com.intellij.newProjectWizard.buildSystem.java") } } class IntelliJJavaBuildSystemType : JavaBuildSystemType<IntelliJBuildSystemSettings>("IntelliJ") { override var settingsFactory = { IntelliJBuildSystemSettings() } override fun advancedSettings(settings: IntelliJBuildSystemSettings): DialogPanel = panel { hideableRow(UIBundle.message("label.project.wizard.new.project.advanced.settings")) { row { cell { label(UIBundle.message("label.project.wizard.new.project.module.name")) } cell { textField(settings::moduleName) } } row { cell { label(UIBundle.message("label.project.wizard.new.project.content.root")) } cell { textFieldWithBrowseButton(settings::contentRoot, UIBundle.message("label.project.wizard.new.project.content.root"), null, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } } row { cell { label(UIBundle.message("label.project.wizard.new.project.module.file.location")) } cell { textFieldWithBrowseButton(settings::moduleFileLocation, UIBundle.message("label.project.wizard.new.project.module.file.location"), null, FileChooserDescriptorFactory.createSingleFolderDescriptor()) } } }.largeGapAfter() } override fun setupProject(project: Project, languageSettings: JavaSettings, settings: IntelliJBuildSystemSettings) { val builder = JavaModuleBuilder() val moduleFile = Paths.get(settings.moduleFileLocation, settings.moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION) builder.name = settings.moduleName builder.moduleFilePath = FileUtil.toSystemDependentName(moduleFile.toString()) builder.contentEntryPath = FileUtil.toSystemDependentName(settings.contentRoot) builder.moduleJdk = languageSettings.sdk builder.commit(project) } } class IntelliJBuildSystemSettings { var moduleName: String = "" var contentRoot: String = "" var moduleFileLocation: String = "" }
apache-2.0
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/fileActions/export/MarkdownExportProvider.kt
2
1153
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.fileActions.export import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.intellij.plugins.markdown.fileActions.MarkdownFileActionFormat import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import java.io.File import javax.swing.JComponent @ApiStatus.Experimental interface MarkdownExportProvider { val formatDescription: MarkdownFileActionFormat fun exportFile(project: Project, mdFile: VirtualFile, outputFile: String) fun validate(project: Project, file: VirtualFile): @Nls String? fun createSettingsComponent(project: Project, suggestedTargetFile: File): JComponent? = null companion object { private val EP_NAME: ExtensionPointName<MarkdownExportProvider> = ExtensionPointName.create("org.intellij.markdown.markdownExportProvider") val allProviders: List<MarkdownExportProvider> = EP_NAME.extensionList } }
apache-2.0
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/inline/util/rewriters/ReturnReplacingVisitor.kt
3
2723
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.inline.util.rewriters import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.metadata.* import org.jetbrains.kotlin.js.translate.context.Namer import org.jetbrains.kotlin.js.translate.utils.JsAstUtils class ReturnReplacingVisitor( private val resultRef: JsNameRef?, private val breakLabel: JsNameRef?, private val function: JsFunction, private val isSuspend: Boolean ) : JsVisitorWithContextImpl() { /** * Prevents replacing returns in object literal */ override fun visit(x: JsObjectLiteral, ctx: JsContext<JsNode>): Boolean = false /** * Prevents replacing returns in inner function */ override fun visit(x: JsFunction, ctx: JsContext<JsNode>): Boolean = false override fun endVisit(x: JsReturn, ctx: JsContext<JsNode>) { if (x.returnTarget != null && function.functionDescriptor != x.returnTarget) return ctx.removeMe() val returnReplacement = getReturnReplacement(x.expression) if (returnReplacement != null) { ctx.addNext(JsExpressionStatement(returnReplacement).apply { synthetic = true }) } if (breakLabel != null) { ctx.addNext(JsBreak(breakLabel)) } } private fun getReturnReplacement(returnExpression: JsExpression?): JsExpression? { return if (returnExpression != null) { val assignment = resultRef?.let { lhs -> val rhs = processCoroutineResult(returnExpression)!! JsAstUtils.assignment(lhs, rhs).apply { synthetic = true } } assignment ?: processCoroutineResult(returnExpression) } else { processCoroutineResult(null) } } fun processCoroutineResult(expression: JsExpression?): JsExpression? { if (!isSuspend) return expression val lhs = JsNameRef("\$\$coroutineResult\$\$", JsAstUtils.stateMachineReceiver()).apply { coroutineResult = true } return JsAstUtils.assignment(lhs, expression ?: Namer.getUndefinedExpression()) } }
apache-2.0
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/AbstractKotlinUVariable.kt
1
6413
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.elements.KtLightAbstractAnnotation import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable @ApiStatus.Internal abstract class AbstractKotlinUVariable( givenParent: UElement? ) : KotlinAbstractUElement(givenParent), PsiVariable, UVariableEx, UAnchorOwner { override val uastInitializer: UExpression? get() { val psi = psi val initializerExpression = when (psi) { is UastKotlinPsiVariable -> psi.ktInitializer is UastKotlinPsiParameter -> psi.ktDefaultValue is KtLightElement<*, *> -> { val origin = psi.kotlinOrigin?.takeIf { it.canAnalyze() } // EA-137191 when (origin) { is KtVariableDeclaration -> origin.initializer is KtParameter -> origin.defaultValue else -> null } } else -> null } ?: return null return languagePlugin?.convertElement(initializerExpression, this) as? UExpression ?: UastEmptyExpression(null) } protected val delegateExpression: UExpression? by lz { val psi = psi val expression = when (psi) { is KtLightElement<*, *> -> (psi.kotlinOrigin as? KtProperty)?.delegateExpression is UastKotlinPsiVariable -> (psi.ktElement as? KtProperty)?.delegateExpression else -> null } expression?.let { languagePlugin?.convertElement(it, this) as? UExpression } } override fun getNameIdentifier(): PsiIdentifier { val kotlinOrigin = (psi as? KtLightElement<*, *>)?.kotlinOrigin return UastLightIdentifier(psi, kotlinOrigin as? KtDeclaration) } override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile) override val uAnnotations by lz { val sourcePsi = sourcePsi ?: return@lz psi.annotations.map { WrappedUAnnotation(it, this) } val annotations = SmartList<UAnnotation>(KotlinNullabilityUAnnotation(baseResolveProviderService, sourcePsi, this)) if (sourcePsi is KtModifierListOwner) { sourcePsi.annotationEntries .filter { acceptsAnnotationTarget(it.useSiteTarget?.getAnnotationUseSiteTarget()) } .mapTo(annotations) { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) } } annotations } protected abstract fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean override val typeReference: UTypeReferenceExpression? by lz { KotlinUTypeReferenceExpression((sourcePsi as? KtCallableDeclaration)?.typeReference, this) { type } } override val uastAnchor: UIdentifier? get() { val identifierSourcePsi = when (val sourcePsi = sourcePsi) { is KtNamedDeclaration -> sourcePsi.nameIdentifier is KtTypeReference -> sourcePsi.typeElement?.let { // receiver param in extension function (it as? KtUserType)?.referenceExpression?.getIdentifier() ?: it } ?: sourcePsi is KtNameReferenceExpression -> sourcePsi.getReferencedNameElement() is KtBinaryExpression, is KtCallExpression -> null // e.g. `foo("Lorem ipsum") ?: foo("dolor sit amet")` is KtDestructuringDeclaration -> sourcePsi.valOrVarKeyword is KtLambdaExpression -> sourcePsi.functionLiteral.lBrace else -> sourcePsi } ?: return null return KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this) } override fun equals(other: Any?) = other is AbstractKotlinUVariable && psi == other.psi class WrappedUAnnotation( psiAnnotation: PsiAnnotation, override val uastParent: UElement ) : UAnnotation, UAnchorOwner, DelegatedMultiResolve { override val javaPsi: PsiAnnotation = psiAnnotation override val psi: PsiAnnotation = javaPsi override val sourcePsi: PsiElement? = psiAnnotation.safeAs<KtLightAbstractAnnotation>()?.kotlinOrigin override val attributeValues: List<UNamedExpression> by lz { psi.parameterList.attributes.map { WrappedUNamedExpression(it, this) } } override val uastAnchor: UIdentifier by lz { KotlinUIdentifier( { javaPsi.nameReferenceElement?.referenceNameElement }, sourcePsi.safeAs<KtAnnotationEntry>()?.typeReference?.nameElement, this ) } class WrappedUNamedExpression( pair: PsiNameValuePair, override val uastParent: UElement? ) : UNamedExpression { override val name: String? = pair.name override val psi = pair override val javaPsi: PsiElement = psi override val sourcePsi: PsiElement? = null override val uAnnotations: List<UAnnotation> = emptyList() override val expression: UExpression by lz { toUExpression(psi.value) } } override val qualifiedName: String? = psi.qualifiedName override fun findAttributeValue(name: String?): UExpression? = psi.findAttributeValue(name)?.let { toUExpression(it) } override fun findDeclaredAttributeValue(name: String?): UExpression? = psi.findDeclaredAttributeValue(name)?.let { toUExpression(it) } override fun resolve(): PsiClass? = psi.nameReferenceElement?.resolve() as? PsiClass } } private fun toUExpression(psi: PsiElement?): UExpression = psi.toUElementOfType() ?: UastEmptyExpression(null)
apache-2.0
jwren/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/CodeVisionHost.kt
1
21767
// 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.codeVision import com.intellij.codeInsight.codeVision.settings.CodeVisionGroupDefaultSettingModel import com.intellij.codeInsight.codeVision.settings.CodeVisionSettings import com.intellij.codeInsight.codeVision.settings.CodeVisionSettingsLiveModel import com.intellij.codeInsight.codeVision.ui.CodeVisionView import com.intellij.codeInsight.codeVision.ui.model.PlaceholderCodeVisionEntry import com.intellij.codeInsight.codeVision.ui.model.RichTextCodeVisionEntry import com.intellij.codeInsight.codeVision.ui.model.richText.RichText import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.hints.InlayGroup import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable import com.intellij.codeInsight.hints.settings.language.isInlaySettingsEditor import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.lang.Language import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorKind import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.fileEditor.* import com.intellij.openapi.fileEditor.impl.BaseRemoteFileEditor import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.rd.createLifetime import com.intellij.openapi.rd.createNestedDisposable import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.SyntaxTraverser import com.intellij.ui.SimpleTextAttributes import com.intellij.util.Alarm import com.intellij.util.application import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.util.ui.update.Update import com.jetbrains.rd.util.error import com.jetbrains.rd.util.getLogger import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.lifetime.SequentialLifetimes import com.jetbrains.rd.util.lifetime.onTermination import com.jetbrains.rd.util.reactive.Signal import com.jetbrains.rd.util.reactive.whenTrue import com.jetbrains.rd.util.trace import org.jetbrains.annotations.TestOnly import java.util.concurrent.CompletableFuture open class CodeVisionHost(val project: Project) { companion object { private val logger = getLogger<CodeVisionHost>() @JvmStatic fun getInstance(project: Project): CodeVisionHost = project.getService(CodeVisionHost::class.java) const val defaultVisibleLenses = 5 const val settingsLensProviderId = "!Settings" const val moreLensProviderId = "!More" /** * Flag which is enabled when executed test in [com.intellij.java.codeInsight.codeVision.CodeVisionTestCase]. * Code vision can access different files during its work (and it is expected, e.g. references). So it is better to disable * particular implementations of code vision to make sure that other tests' performance is not hurt. */ val isCodeVisionTestKey: Key<Boolean> = Key.create("code.vision.test") private val editorTrackingStart: Key<Long> = Key.create("editor.tracking.start") /** * Returns true iff we are in test in [com.intellij.java.codeInsight.codeVision.CodeVisionTestCase]. */ @JvmStatic fun isCodeLensTest(editor: Editor): Boolean { return editor.project?.getUserData(isCodeVisionTestKey) == true } } protected val codeVisionLifetime = project.createLifetime() /** * Pass empty list to update ALL providers in editor */ data class LensInvalidateSignal(val editor: Editor?, val providerIds: Collection<String> = emptyList()) val invalidateProviderSignal: Signal<LensInvalidateSignal> = Signal() private val defaultSortedProvidersList = mutableListOf<String>() @Suppress("MemberVisibilityCanBePrivate") // Uses in Rider protected val lifeSettingModel = CodeVisionSettingsLiveModel(codeVisionLifetime) var providers: List<CodeVisionProvider<*>> = CodeVisionProviderFactory.createAllProviders(project) init { lifeSettingModel.isRegistryEnabled.whenTrue(codeVisionLifetime) { enableCodeVisionLifetime -> ApplicationManager.getApplication().invokeLater { runReadAction { if (project.isDisposed) return@runReadAction val liveEditorList = ProjectEditorLiveList(enableCodeVisionLifetime, project) liveEditorList.editorList.view(enableCodeVisionLifetime) { editorLifetime, editor -> if (isEditorApplicable(editor)) { subscribeForFrontendEditor(editorLifetime, editor) } } val viewService = project.service<CodeVisionView>() viewService.setPerAnchorLimits( CodeVisionAnchorKind.values().associateWith { (lifeSettingModel.getAnchorLimit(it) ?: defaultVisibleLenses) }) invalidateProviderSignal.advise(enableCodeVisionLifetime) { invalidateSignal -> if (invalidateSignal.editor == null && invalidateSignal.providerIds.isEmpty()) viewService.setPerAnchorLimits( CodeVisionAnchorKind.values().associateWith { (lifeSettingModel.getAnchorLimit(it) ?: defaultVisibleLenses) }) } lifeSettingModel.visibleMetricsAboveDeclarationCount.advise(codeVisionLifetime) { invalidateProviderSignal.fire(LensInvalidateSignal(null, emptyList())) } lifeSettingModel.visibleMetricsNextToDeclarationCount.advise(codeVisionLifetime) { invalidateProviderSignal.fire(LensInvalidateSignal(null, emptyList())) } rearrangeProviders() project.messageBus.connect(enableCodeVisionLifetime.createNestedDisposable()) .subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { private fun recollectAndRearrangeProviders() { providers = CodeVisionProviderFactory.createAllProviders( project) rearrangeProviders() } override fun pluginLoaded(pluginDescriptor: IdeaPluginDescriptor) { recollectAndRearrangeProviders() } override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { recollectAndRearrangeProviders() } }) project.messageBus.connect(enableCodeVisionLifetime.createNestedDisposable()) .subscribe(CodeVisionSettings.CODE_LENS_SETTINGS_CHANGED, object : CodeVisionSettings.CodeVisionSettingsListener { override fun groupPositionChanged(id: String, position: CodeVisionAnchorKind) { } override fun providerAvailabilityChanged(id: String, isEnabled: Boolean) { PsiManager.getInstance(project).dropPsiCaches() DaemonCodeAnalyzer.getInstance(project).restart() } }) } } } } // run in read action fun collectPlaceholders(editor: Editor, psiFile: PsiFile?): List<Pair<TextRange, CodeVisionEntry>> { if (!lifeSettingModel.isEnabledWithRegistry.value) return emptyList() val project = editor.project ?: return emptyList() if (psiFile != null && psiFile.virtualFile != null && !ProjectRootManager.getInstance(project).fileIndex.isInSourceContent(psiFile.virtualFile)) return emptyList() val bypassBasedCollectors = ArrayList<Pair<BypassBasedPlaceholderCollector, CodeVisionProvider<*>>>() val placeholders = ArrayList<Pair<TextRange, CodeVisionEntry>>() val settings = CodeVisionSettings.instance() for (provider in providers) { if (!settings.isProviderEnabled(provider.groupId)) continue if (getAnchorForProvider(provider) != CodeVisionAnchorKind.Top) continue val placeholderCollector: CodeVisionPlaceholderCollector = provider.getPlaceholderCollector(editor, psiFile) ?: continue if (placeholderCollector is BypassBasedPlaceholderCollector) { bypassBasedCollectors.add(placeholderCollector to provider) } else if (placeholderCollector is GenericPlaceholderCollector) { for (placeholderRange in placeholderCollector.collectPlaceholders(editor)) { placeholders.add(placeholderRange to PlaceholderCodeVisionEntry(provider.id)) } } } if (bypassBasedCollectors.isNotEmpty()) { val traverser = SyntaxTraverser.psiTraverser(psiFile) for (element in traverser) { for ((collector, provider) in bypassBasedCollectors) { for (placeholderRange in collector.collectPlaceholders(element, editor)) { placeholders.add(placeholderRange to PlaceholderCodeVisionEntry(provider.id)) } } } } return placeholders } protected fun rearrangeProviders() { val allProviders = collectAllProviders() defaultSortedProvidersList.clear() defaultSortedProvidersList.addAll(allProviders.getTopSortedIdList()) } protected open fun collectAllProviders(): List<Pair<String, CodeVisionProvider<*>>> { return providers.map { it.id to it } } private fun isEditorApplicable(editor: Editor): Boolean { return editor.editorKind == EditorKind.MAIN_EDITOR || editor.editorKind == EditorKind.UNTYPED } fun invalidateProvider(signal: LensInvalidateSignal) { invalidateProviderSignal.fire(signal) } fun getNumber(providerId: String): Int { if (lifeSettingModel.disabledCodeVisionProviderIds.contains(providerId)) return -1 return defaultSortedProvidersList.indexOf(providerId) } open fun handleLensClick(editor: Editor, range: TextRange, entry: CodeVisionEntry) { //todo intellij statistic logger.trace { "Handling click for entry with id: ${entry.providerId}" } if (entry.providerId == settingsLensProviderId) { openCodeVisionSettings() return } val frontendProvider = providers.firstOrNull { it.id == entry.providerId } if (frontendProvider != null) { frontendProvider.handleClick(editor, range, entry) return } logger.trace { "No provider found with id ${entry.providerId}" } } open fun handleLensExtraAction(editor: Editor, range: TextRange, entry: CodeVisionEntry, actionId: String) { if (actionId == settingsLensProviderId) { val provider = getProviderById(entry.providerId) openCodeVisionSettings(provider?.groupId) return } val frontendProvider = providers.firstOrNull { it.id == entry.providerId } if (frontendProvider != null) { frontendProvider.handleExtraAction(editor, range, actionId) return } logger.trace { "No provider found with id ${entry.providerId}" } } protected fun CodeVisionAnchorKind?.nullIfDefault(): CodeVisionAnchorKind? = if (this === CodeVisionAnchorKind.Default) null else this open fun getAnchorForEntry(entry: CodeVisionEntry): CodeVisionAnchorKind { val provider = getProviderById(entry.providerId) ?: return lifeSettingModel.defaultPosition.value return getAnchorForProvider(provider) } private fun getAnchorForProvider(provider: CodeVisionProvider<*>): CodeVisionAnchorKind { return lifeSettingModel.codeVisionGroupToPosition[provider.groupId].nullIfDefault() ?: lifeSettingModel.defaultPosition.value } private fun getPriorityForId(id: String): Int { return defaultSortedProvidersList.indexOf(id) } open fun getProviderById(id: String): CodeVisionProvider<*>? { return providers.firstOrNull { it.id == id } } fun getPriorityForEntry(entry: CodeVisionEntry): Int { return getPriorityForId(entry.providerId) } // we are only interested in text editors, and BRFE behaves exceptionally bad so ignore them private fun isAllowedFileEditor(fileEditor: FileEditor?) = fileEditor is TextEditor && fileEditor !is BaseRemoteFileEditor private fun subscribeForFrontendEditor(editorLifetime: Lifetime, editor: Editor) { if (editor.document !is DocumentImpl) return val calculationLifetimes = SequentialLifetimes(editorLifetime) val editorManager = FileEditorManager.getInstance(project) var recalculateWhenVisible = false var previousLenses: List<Pair<TextRange, CodeVisionEntry>> = ArrayList() val openTime = System.nanoTime() editor.putUserData(editorTrackingStart, openTime) val mergingQueueFront = MergingUpdateQueue(CodeVisionHost::class.simpleName!!, 100, true, null, editorLifetime.createNestedDisposable(), null, Alarm.ThreadToUse.POOLED_THREAD) mergingQueueFront.isPassThrough = false var calcRunning = false fun recalculateLenses(groupToRecalculate: Collection<String> = emptyList()) { if (!isInlaySettingsEditor(editor) && !editorManager.selectedEditors.any { isAllowedFileEditor(it) && (it as TextEditor).editor == editor }) { recalculateWhenVisible = true return } recalculateWhenVisible = false if (calcRunning && groupToRecalculate.isNotEmpty()) return recalculateLenses(emptyList()) calcRunning = true val lt = calculationLifetimes.next() calculateFrontendLenses(lt, editor, groupToRecalculate) { lenses, providersToUpdate -> val newLenses = previousLenses.filter { !providersToUpdate.contains(it.second.providerId) } + lenses editor.lensContextOrThrow.setResults(newLenses) previousLenses = newLenses calcRunning = false } } fun pokeEditor(providersToRecalculate: Collection<String> = emptyList()) { editor.lensContextOrThrow.notifyPendingLenses() val shouldRecalculateAll = mergingQueueFront.isEmpty.not() mergingQueueFront.cancelAllUpdates() mergingQueueFront.queue(object : Update("") { override fun run() { application.invokeLater( { recalculateLenses(if (shouldRecalculateAll) emptyList() else providersToRecalculate) }, ModalityState.stateForComponent(editor.contentComponent)) } }) } invalidateProviderSignal.advise(editorLifetime) { if (it.editor == null || it.editor === editor) { pokeEditor(it.providerIds) } } editor.lensContextOrThrow.notifyPendingLenses() recalculateLenses() application.messageBus.connect(editorLifetime.createNestedDisposable()).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { override fun selectionChanged(event: FileEditorManagerEvent) { if (isAllowedFileEditor( event.newEditor) && (event.newEditor as TextEditor).editor == editor && recalculateWhenVisible) recalculateLenses() } }) editor.document.addDocumentListener(object : DocumentListener { override fun documentChanged(event: DocumentEvent) { pokeEditor() } }, editorLifetime.createNestedDisposable()) editorLifetime.onTermination { editor.lensContextOrThrow.clearLenses() } } private fun calculateFrontendLenses(calcLifetime: Lifetime, editor: Editor, groupsToRecalculate: Collection<String> = emptyList(), inTestSyncMode: Boolean = false, consumer: (List<Pair<TextRange, CodeVisionEntry>>, List<String>) -> Unit) { val precalculatedUiThings = providers.associate { if (groupsToRecalculate.isNotEmpty() && !groupsToRecalculate.contains(it.id)) return@associate it.id to null it.id to it.precomputeOnUiThread(editor) } // dropping all lenses if CV disabled if (lifeSettingModel.isEnabled.value.not()) { consumer(emptyList(), providers.map { it.id }) return } executeOnPooledThread(calcLifetime, inTestSyncMode) { ProgressManager.checkCanceled() var results = mutableListOf<Pair<TextRange, CodeVisionEntry>>() val providerWhoWantToUpdate = mutableListOf<String>() var everyProviderReadyToUpdate = true val inlaySettingsEditor = isInlaySettingsEditor(editor) val editorOpenTime = editor.getUserData(editorTrackingStart) val watcher = project.service<CodeVisionProvidersWatcher>() providers.forEach { @Suppress("UNCHECKED_CAST") it as CodeVisionProvider<Any?> if (!inlaySettingsEditor && !lifeSettingModel.disabledCodeVisionProviderIds.contains(it.groupId)) { if (!it.shouldRecomputeForEditor(editor, precalculatedUiThings[it.id])) { everyProviderReadyToUpdate = false return@forEach } } if (groupsToRecalculate.isNotEmpty() && !groupsToRecalculate.contains(it.id)) return@forEach ProgressManager.checkCanceled() if (project.isDisposed) return@executeOnPooledThread if (!inlaySettingsEditor && lifeSettingModel.disabledCodeVisionProviderIds.contains(it.groupId)) { if (editor.lensContextOrThrow.hasProviderCodeVision(it.id)) { providerWhoWantToUpdate.add(it.id) } return@forEach } providerWhoWantToUpdate.add(it.id) try { val state = it.computeCodeVision(editor, precalculatedUiThings[it.id]) if (state.isReady.not()) { if (editorOpenTime != null) { watcher.reportProvider(it.groupId, System.nanoTime() - editorOpenTime) if (watcher.shouldConsiderProvider(it.groupId)) { everyProviderReadyToUpdate = false } } else { everyProviderReadyToUpdate = false } } else { watcher.dropProvider(it.groupId) results.addAll(state.result) } } catch (e: Exception) { if (e is ControlFlowException) throw e logger.error("Exception during computeForEditor for ${it.id}", e) } } val previewData = CodeVisionGroupDefaultSettingModel.isEnabledInPreview(editor) if (previewData == false) { results = results.map { val richText = RichText() richText.append(it.second.longPresentation, SimpleTextAttributes(SimpleTextAttributes.STYLE_STRIKEOUT, null)) val entry = RichTextCodeVisionEntry(it.second.providerId, richText) it.first to entry }.toMutableList() } if (!everyProviderReadyToUpdate) { editor.lensContextOrThrow.discardPending() return@executeOnPooledThread } if (providerWhoWantToUpdate.isEmpty()) { editor.lensContextOrThrow.discardPending() return@executeOnPooledThread } if (!inTestSyncMode) { application.invokeLater({ calcLifetime.executeIfAlive { consumer(results, providerWhoWantToUpdate) } }, ModalityState.stateForComponent(editor.component)) } else { consumer(results, providerWhoWantToUpdate) } } } private fun executeOnPooledThread(lifetime: Lifetime, inTestSyncMode: Boolean, runnable: () -> Unit): ProgressIndicator { val indicator = EmptyProgressIndicator() indicator.start() if (!inTestSyncMode) { CompletableFuture.runAsync( { ProgressManager.getInstance().runProcess(runnable, indicator) }, AppExecutorUtil.getAppExecutorService() ) lifetime.onTermination { if (indicator.isRunning) indicator.cancel() } } else { runnable() } return indicator } protected open fun openCodeVisionSettings(groupId: String? = null) { InlayHintsConfigurable.showSettingsDialogForLanguage(project, Language.ANY) { if (groupId == null) return@showSettingsDialogForLanguage it.group == InlayGroup.CODE_VISION_GROUP_NEW return@showSettingsDialogForLanguage it.group == InlayGroup.CODE_VISION_GROUP_NEW && it.id == groupId } } @TestOnly fun calculateCodeVisionSync(editor: Editor, testRootDisposable: Disposable) { calculateFrontendLenses(testRootDisposable.createLifetime(), editor, inTestSyncMode = true) { lenses, _ -> editor.lensContextOrThrow.setResults(lenses) } } }
apache-2.0
loxal/FreeEthereum
free-ethereum-core/src/main/java/org/ethereum/config/net/RopstenNetConfig.kt
1
1525
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.config.net import org.ethereum.config.blockchain.HomesteadConfig import org.ethereum.config.blockchain.RopstenConfig class RopstenNetConfig : BaseNetConfig() { init { add(0, HomesteadConfig()) add(10, RopstenConfig(HomesteadConfig())) } }
mit
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/attic/attic--SpitCompareOperationsPage.kt
1
6981
//package alraune // //import alraune.* //import vgrechka.* // //class class SpitCompareOperationsPage : SpitPage { // override fun spit() {Spit()} // class Spit { // val params = AlGetParams() // val operationId = listOf( // getParamOrBailOut(params.id1), // getParamOrBailOut(params.id2)) // // val operations = operationId.map { // dbSelectMaybeOperationById(it) // ?: bailOutToLittleErrorPage(rawHtml(t("TOTE", "Операции с ID <b>$it</b> не существует"))) // } // // init { // operations.forEach { // if (it.orderId == null) // bailOutToLittleErrorPage(t("TOTE", "Операция <b>${it.id} не относится к заказам</b>")) // } // if (operations[0].orderId != operations[1].orderId) // bailOutToLittleErrorPage(t("TOTE", "Операции относятся к разным заказам. Толку их сравнивать?")) // } // val operation0 = operations[0]; val operation1 = operations[1] // // val afterness = mutableListOf( // params.afterness1.get() ?: Afterness.Before, // params.afterness2.get() ?: Afterness.After) // // val afternessSelectDomid = listOf(nextJsIdent(), nextJsIdent()) // // init { // for (i in 0..1) // if (!info[i].hasStateBefore()) // afterness[i] = Afterness.After // // val currentOrder = when (operation0) { // is OperationInfo.UpdateOrder_V1 -> dbSelectOrderById(operation0.data.orderAfterOperation.id) // else -> null // } // // rctx2.htmlHeadTitle = when { // currentOrder != null -> // AlText.shortOrder(currentOrder.id) + ": " + // AlText.shortOperation(operation0.operationId) + " ${AlText.leftRightArrow} " + // AlText.shortOperation(operation1.operationId) // else -> wtf() // } // // spitUsualPage_withNewContext1 { // composeMinimalMainContainer { // oo(composePageHeader(t("TOTE", "Сравниваем операции ${AlText.numString(operation0.operationId)} и ${AlText.numString(operation1.operationId)}"))) // // val tableStyle = nextJsIdent() // drooStylesheet(""" // .$tableStyle td {padding: 4px;} // .$tableStyle td:first-child {padding-left: 0px;} // """) // // oo(div().style("margin-top: 1em;").with { // if (currentOrder != null) { // oo(div().with { // oo(span(t("TOTE", "Заказ ") + AlText.numString(currentOrder.id)) // .style("font-weight: bold;")) // oo(span(currentOrder.documentTitle) // .style("margin-left: 0.5em;")) // }) // } // // oo(table().className(tableStyle).with { // oo(tr().with { // oo(td().style("text-align: left;").add(t("TOTE", "Сравнить состояние"))) // oo(td().add(composeAfternessSelect(0))) // oo(td().add(composeOperationDescrLine("1.", info[0]))) // }) // oo(tr().with { // oo(td().style("text-align: left;").add(t("TOTE", "с состоянием"))) // oo(td().add(composeAfternessSelect(1))) // oo(td().add(composeOperationDescrLine("2.", info[1]))) // }) // }) // }) // // oo(div().style("margin-top: 0.5em;").with { // oo(composeButton_primary(t("TOTE", "Поджигай")) // .attachOnClickWhenDomReady(""" // const href = ${jsStringLiteral(makeUrlPart(`attic--SpitCompareOperationsPage`::class) {})} // + "?${params.id1.name}=" + ${jsStringLiteral("" + operationId[0])} // + "&${params.afterness1.name}=" + ${jsByIDSingle(afternessSelectDomid[0])}.val() // + "&${params.id2.name}=" + ${jsStringLiteral("" + operationId[1])} // + "&${params.afterness2.name}=" + ${jsByIDSingle(afternessSelectDomid[1])}.val() // // console.log('href', href) // ${!JsProgressyNavigate().jsHref("href")} // """)) // }) // // oo(div().style("margin-top: 1em; padding-top: 1em; border-top: 2px solid ${Color.Gray500};").with { // when { // operation0 is OperationInfo.UpdateOrder_V1 && operation1 is OperationInfo.UpdateOrder_V1 -> { // val entity0 = bang(when (afterness[0]) { // Afterness.Before -> operation0.data.orderBeforeOperation // Afterness.After -> operation0.data.orderAfterOperation // }) // val entity1 = bang(when (afterness[1]) { // Afterness.Before -> operation1.data.orderBeforeOperation // Afterness.After -> operation1.data.orderAfterOperation // }) // drooOrderParamsComparison(entity0, entity1) // } // else -> wtf() // } // }) // } // } // } // // fun composeOperationDescrLine(num: String, info: OperationInfo) = // divFlexCenter().with { // oo(span().style("font-weight: bold; margin-right: 0.5em;") // .add(num)) // oo(composeOperationTitle2(info)) // } // // fun composeAfternessSelect(index: Int): AlTag { // val paramValue = afterness[index] // return select().id(afternessSelectDomid[index]).className("form-control").style("width: inherit;").with { // if (info[index].hasStateBefore()) // oo(option().value(Afterness.Before.name).selected(paramValue == Afterness.Before).add(t("TOTE", "до"))) // oo(option().value(Afterness.After.name).selected(paramValue == Afterness.After).add(t("TOTE", "после"))) // } // } // } // //}
apache-2.0
androidx/androidx
compose/ui/ui-text/src/jvmMain/kotlin/androidx/compose/ui/text/input/GapBuffer.jvm.kt
3
940
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.input internal actual fun String.toCharArray( destination: CharArray, destinationOffset: Int, startIndex: Int, endIndex: Int ) { @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") (this as java.lang.String).getChars(startIndex, endIndex, destination, destinationOffset) }
apache-2.0
androidx/androidx
compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/suspendfun/SuspendDoubleTapToLikeDemo.kt
3
4392
/* * 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.animation.demos.suspendfun import androidx.compose.animation.core.animate import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.tooling.preview.Preview import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @Preview @Composable fun SuspendDoubleTapToLikeDemo() { var alpha by remember { mutableStateOf(0f) } var scale by remember { mutableStateOf(0f) } val mutatorMutex = MutatorMutex() val scope = rememberCoroutineScope() Box( Modifier.fillMaxSize().background(Color.White).pointerInput(Unit) { detectTapGestures( onDoubleTap = { scope.launch { // MutatorMutex cancels the previous job (i.e. animations) before starting // a new job. This ensures the mutable states only being mutated by one // animation at a time. mutatorMutex.mutate { coroutineScope { // `launch` creates a new coroutine without blocking. This allows // the two animations in this CoroutineScope to run together. launch { animate(0f, 1f) { value, _ -> alpha = value } } launch { animate(0f, 2f) { value, _ -> scale = value } } } // CoroutineScope doesn't return until all animations in the scope // finish. So by the time we get here, the enter animations from the // previous CoroutineScope have all finished. coroutineScope { launch { animate(alpha, 0f) { value, _ -> alpha = value } } launch { animate(scale, 4f) { value, _ -> scale = value } } } } } } ) } ) { Icon( Icons.Filled.Favorite, "Like", Modifier.align(Alignment.Center) .graphicsLayer( alpha = alpha, scaleX = scale, scaleY = scale ), tint = Color.Red ) } }
apache-2.0
androidx/androidx
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/pager/PagerCrossAxisTest.kt
3
4114
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.pager import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertHeightIsEqualTo import androidx.compose.ui.test.assertWidthIsEqualTo import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.height import androidx.compose.ui.unit.width import androidx.test.filters.LargeTest import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @OptIn(ExperimentalFoundationApi::class) @LargeTest @RunWith(Parameterized::class) internal class PagerCrossAxisTest(val config: ParamConfig) : BasePagerTest(config) { @Test fun pagerOnInfiniteCrossAxisLayout_shouldWrapContentSize() { // Arrange rule.setContent { InfiniteAxisRootComposable { HorizontalOrVerticalPager( pageCount = DefaultPageCount, state = rememberPagerState(), modifier = Modifier .fillMaxHeight() .fillMaxWidth() .testTag(PagerTestTag), ) { val fillModifier = if (isVertical) { Modifier .fillMaxHeight() .width(200.dp) } else { Modifier .fillMaxWidth() .height(200.dp) } Box(fillModifier) } } } // Act val rootBounds = rule.onRoot().getUnclippedBoundsInRoot() // Assert: Max Cross Axis size is handled well by wrapping content if (isVertical) { rule.onNodeWithTag(PagerTestTag) .assertHeightIsEqualTo(rootBounds.height) .assertWidthIsEqualTo(200.dp) } else { rule.onNodeWithTag(PagerTestTag) .assertWidthIsEqualTo(rootBounds.width) .assertHeightIsEqualTo(200.dp) } } @Composable private fun InfiniteAxisRootComposable(content: @Composable () -> Unit) { if (isVertical) { Row(Modifier.horizontalScroll(rememberScrollState())) { content() } } else { Column(Modifier.verticalScroll(rememberScrollState())) { content() } } } companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun params() = mutableListOf<ParamConfig>().apply { for (orientation in TestOrientation) { add(ParamConfig(orientation = orientation)) } } } }
apache-2.0
androidx/androidx
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/runner/CompilationTestRunner.kt
3
1763
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.util.runner import androidx.room.compiler.processing.ExperimentalProcessingApi import androidx.room.compiler.processing.XProcessingEnvConfig import androidx.room.compiler.processing.util.CompilationResult import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import java.io.File /** * Common interface for compilation tests */ @ExperimentalProcessingApi internal interface CompilationTestRunner { // user visible name that we can print in assertions val name: String fun canRun(params: TestCompilationParameters): Boolean fun compile(workingDir: File, params: TestCompilationParameters): CompilationResult } @ExperimentalProcessingApi internal data class TestCompilationParameters( val sources: List<Source> = emptyList(), val classpath: List<File> = emptyList(), val options: Map<String, String> = emptyMap(), val javacArguments: List<String> = emptyList(), val kotlincArguments: List<String> = emptyList(), val config: XProcessingEnvConfig, val handlers: List<(XTestInvocation) -> Unit>, )
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/hints/ranges/simple.kt
4
2589
val range = 0<# ≤ #>..<# ≤ #>10 val rangeUntil = 0<# ≤ #>..<10 val errorRange = 4downTo 0 class Foo : Comparable<Foo> { override fun compareTo(other: Foo): Int = TODO("Not yet implemented") } fun foo() { // rangeTo and rangeUntil are not an infix functions and shouldn't have hints for (index in 0 rangeTo 100) {} for (index in 0 rangeUntil 100) {} for (index in 0.rangeTo(100)) {} for (index in 'a'.rangeTo('z')) {} for (index in 0L.rangeTo(100L)) {} for (index in Foo().rangeTo(Foo())) {} for (index in 0.0.rangeTo(100.0)) {} for (index in 0f.rangeTo(100f)) {} for (index in 0<# ≤ #> .. <# ≤ #>100) {} for (index in 'a'<# ≤ #> .. <# ≤ #>'z') {} for (index in 0L<# ≤ #> .. <# ≤ #>100L) {} for (index in Foo()<# ≤ #> .. <# ≤ #>Foo()) {} for (index in 0.0<# ≤ #> .. <# ≤ #>100.0) {} for (index in 0f<# ≤ #> .. <# ≤ #>100f) {} for (index in 0<# ≤ #> ..< 100) {} for (index in 'a'<# ≤ #> ..< 'z') {} for (index in 0.0<# ≤ #> ..< 100.0) {} for (index in 0f<# ≤ #> ..< 100f) {} for (index in 0.rangeUntil(100)) {} for (index in 'a'.rangeUntil('z')) {} for (index in 0L.rangeUntil(100L)) {} for (index in Foo().rangeUntil(Foo())) {} for (index in 0.0.rangeUntil(100.0)) {} for (index in 0f.rangeUntil(100f)) {} for (index in 0<# ≤ #> until <# < #>100) {} for (index in 'a'<# ≤ #> until <# < #>'z') {} for (index in 0L<# ≤ #> until <# < #>100L) {} for (index in 100<# ≥ #> downTo <# ≥ #>0) {} for (index in 'z'<# ≥ #> downTo <# ≥ #>'a') {} for (index in 100L<# ≥ #> downTo <# ≥ #>0L) {} for (i in 0 until 0<# ≤ #>..<# ≤ #>5 ) {} for (i in 1<# ≤ #> until <# < #>10 step 2) {} run { val left: Short = 0 val right: Short = 10 for (i in left.rangeTo(right)) {} for (i in left<# ≤ #> .. <# ≤ #>right) {} for (i in left<# ≤ #> ..< right) {} for (i in left<# ≤ #> until <# < #>right) {} for (index in right<# ≥ #> downTo <# ≥ #>left) {} for (index in left.rangeUntil(right)) {} } for (index in someVeryVeryLongLongLongLongFunctionName(0)<# ≤ #> .. <# ≤ #>someVeryVeryLongLongLongLongFunctionName(100)) {} } private infix fun Int.until(intRange: IntRange): IntRange = TODO() private fun someVeryVeryLongLongLongLongFunctionName(x: Int): Int = x private fun check(x: Int, y: Int) { val b = x in 8<# ≤ #>..<# ≤ #>9 if (x in 7<# ≤ #>..<# ≤ #>9 && y in 5<# ≤ #>..<# ≤ #>9) { } }
apache-2.0
GunoH/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EclipseModuleManagerSerializer.kt
2
5029
// 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.idea.eclipse.config import com.intellij.workspaceModel.ide.impl.jps.serialization.CustomModuleComponentSerializer import com.intellij.workspaceModel.ide.impl.jps.serialization.ErrorReporter import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsFileContentReader import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsFileContentWriter import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.idea.eclipse.config.EclipseModuleManagerImpl.* import org.jetbrains.jps.eclipse.model.JpsEclipseClasspathSerializer import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.JpsProjectLoader /** * Implements loading and saving configuration from [EclipseModuleManagerImpl] in iml file when workspace model is used */ class EclipseModuleManagerSerializer : CustomModuleComponentSerializer { override fun loadComponent(builder: MutableEntityStorage, moduleEntity: ModuleEntity, reader: JpsFileContentReader, imlFileUrl: VirtualFileUrl, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { val componentTag = reader.loadComponent(imlFileUrl.url, "EclipseModuleManager") ?: return val entity = builder.addEclipseProjectPropertiesEntity(moduleEntity, moduleEntity.entitySource) builder.modifyEntity(entity) { componentTag.getChildren(LIBELEMENT).forEach { eclipseUrls.add(virtualFileManager.fromUrl(it.getAttributeValue(VALUE_ATTR)!!)) } componentTag.getChildren(VARELEMENT).forEach { variablePaths = variablePaths.toMutableMap().also { map -> map[it.getAttributeValue(VAR_ATTRIBUTE)!!] = it.getAttributeValue(PREFIX_ATTR, "") + it.getAttributeValue(VALUE_ATTR) } } componentTag.getChildren(CONELEMENT).forEach { unknownCons.add(it.getAttributeValue(VALUE_ATTR)!!) } forceConfigureJdk = componentTag.getAttributeValue(FORCED_JDK)?.toBoolean() ?: false val srcDescriptionTag = componentTag.getChild(SRC_DESCRIPTION) if (srcDescriptionTag != null) { expectedModuleSourcePlace = srcDescriptionTag.getAttributeValue(EXPECTED_POSITION)?.toInt() ?: 0 srcDescriptionTag.getChildren(SRC_FOLDER).forEach { srcPlace = srcPlace.toMutableMap().also { map -> map[it.getAttributeValue(VALUE_ATTR)!!] = it.getAttributeValue(EXPECTED_POSITION)!!.toInt() } } } } } override fun saveComponent(moduleEntity: ModuleEntity, imlFileUrl: VirtualFileUrl, writer: JpsFileContentWriter) { val moduleOptions = moduleEntity.customImlData?.customModuleOptions if (moduleOptions != null && moduleOptions[JpsProjectLoader.CLASSPATH_ATTRIBUTE] == JpsEclipseClasspathSerializer.CLASSPATH_STORAGE_ID) { return } val eclipseProperties = moduleEntity.eclipseProperties if (eclipseProperties == null || eclipseProperties.eclipseUrls.isEmpty() && eclipseProperties.variablePaths.isEmpty() && !eclipseProperties.forceConfigureJdk && eclipseProperties.unknownCons.isEmpty()) { return } val componentTag = JDomSerializationUtil.createComponentElement("EclipseModuleManager") eclipseProperties.eclipseUrls.forEach { componentTag.addContent(Element(LIBELEMENT).setAttribute(VALUE_ATTR, it.url)) } eclipseProperties.variablePaths.forEach { name, path -> val prefix = listOf(SRC_PREFIX, SRC_LINK_PREFIX, LINK_PREFIX).firstOrNull { name.startsWith(it) } ?: "" val varTag = Element(VARELEMENT) varTag.setAttribute(VAR_ATTRIBUTE, name.removePrefix(prefix)) if (prefix != "") { varTag.setAttribute(PREFIX_ATTR, prefix) } varTag.setAttribute(VALUE_ATTR, path) componentTag.addContent(varTag) } eclipseProperties.unknownCons.forEach { componentTag.addContent(Element(CONELEMENT).setAttribute(VALUE_ATTR, it)) } if (eclipseProperties.forceConfigureJdk) { componentTag.setAttribute(FORCED_JDK, true.toString()) } val srcDescriptionTag = Element(SRC_DESCRIPTION) srcDescriptionTag.setAttribute(EXPECTED_POSITION, eclipseProperties.expectedModuleSourcePlace.toString()) eclipseProperties.srcPlace.forEach { url, position -> srcDescriptionTag.addContent(Element(SRC_FOLDER).setAttribute(VALUE_ATTR, url).setAttribute(EXPECTED_POSITION, position.toString())) } componentTag.addContent(srcDescriptionTag) writer.saveComponent(imlFileUrl.url, "EclipseModuleManager", componentTag) } }
apache-2.0
lnr0626/cfn-templates
base-models/src/main/kotlin/com/lloydramey/cfn/model/resources/Resource.kt
1
1688
/* * Copyright 2017 Lloyd Ramey <[email protected]> * * 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.lloydramey.cfn.model.resources import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.lloydramey.cfn.model.functions.ReferencableWithAttributes import com.lloydramey.cfn.model.resources.attributes.ResourceDefinitionAttribute @Suppress("unused") @JsonIgnoreProperties("Id", "Attributes") class Resource<out T : ResourceProperties>( id: String, @JsonIgnore val attributes: List<ResourceDefinitionAttribute> = emptyList(), val properties: T ) : ReferencableWithAttributes(id) { val type = properties.resourceType @JsonAnyGetter fun json() = attributes.associateBy { it.name } } inline fun <reified T : ResourceProperties> resource(id: String, vararg attributes: ResourceDefinitionAttribute, init: T.() -> Unit): Resource<T> { val properties = T::class.java.newInstance() properties.init() properties.validate() return Resource(id = id, attributes = attributes.asList(), properties = properties) }
apache-2.0
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/test/org/jetbrains/uast/test/common/kotlin/IndentedPrintingVisitor.kt
4
1320
// 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.uast.test.common.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import org.jetbrains.uast.UFile import kotlin.reflect.KClass abstract class IndentedPrintingVisitor(val shouldIndent: (PsiElement) -> Boolean) : PsiElementVisitor() { constructor(vararg kClasses: KClass<*>) : this({ psi -> kClasses.any { it.isInstance(psi) } }) private val builder = StringBuilder() var level = 0 private set override fun visitElement(element: PsiElement) { val charSequence = render(element) if (charSequence != null) { builder.append(" ".repeat(level)) builder.append(charSequence) builder.appendLine() } val shouldIndent = shouldIndent(element) if (shouldIndent) level++ element.acceptChildren(this) if (shouldIndent) level-- } protected abstract fun render(element: PsiElement): CharSequence? val result: String get() = builder.toString() } fun IndentedPrintingVisitor.visitUFileAndGetResult(uFile: UFile): String { uFile.sourcePsi.accept(this) return result }
apache-2.0
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/wanandroid/fragemnts/UserCollectionFragment.kt
1
5489
package com.kingz.module.wanandroid.fragemnts import android.view.View import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.chad.library.adapter.base.animation.ScaleInAnimation import com.kingz.base.factory.ViewModelFactory import com.kingz.module.common.R import com.kingz.module.common.utils.RvUtils import com.kingz.module.wanandroid.adapter.ArticleAdapter import com.kingz.module.wanandroid.bean.Article import com.kingz.module.wanandroid.viewmodel.CollectArticleViewModel import com.kingz.module.wanandroid.viewmodel.WanAndroidViewModelV2 import com.scwang.smart.refresh.layout.SmartRefreshLayout import com.scwang.smart.refresh.layout.api.RefreshLayout import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener import com.zeke.kangaroo.utils.ZLog import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * author:ZekeWang * date:2021/3/29 * description:用户文章收藏页面的Fragment * * FIXME 排查有网络请求时,从首页跳转时卡顿的问题 */ class UserCollectionFragment : CommonFragment<WanAndroidViewModelV2>() { private lateinit var mRecyclerView: RecyclerView private var articleAdapter: ArticleAdapter? = null private var swipeRefreshLayout: SmartRefreshLayout? = null override val viewModel: CollectArticleViewModel by viewModels { ViewModelFactory.build { CollectArticleViewModel() } } override fun getLayoutResID() = R.layout.fragment_common_page override fun initView() { super.initView() initRecyclerView() initFABInflate() } private fun initRecyclerView() { ZLog.d("init recyclerView.") mRecyclerView = rootView?.findViewById(R.id.recycler_view) as RecyclerView mRecyclerView.apply { isVerticalScrollBarEnabled = true layoutManager = LinearLayoutManager(context) articleAdapter = ArticleAdapter(mType = ArticleAdapter.TYPE_COLLECTION) articleAdapter?.apply { adapterAnimation = ScaleInAnimation() setOnItemClickListener { adapter, view, position -> if (articleAdapter!!.getDefItemCount() > position) { openWeb(articleAdapter?.getItem(position)) } } //设置文章收藏监听器 likeListener = object : ArticleAdapter.LikeListener { override fun liked(item: Article, adapterPosition: Int) { viewModel.changeArticleLike(item, adapterPosition, true) } override fun unLiked(item: Article, adapterPosition: Int) { viewModel.changeArticleLike(item, adapterPosition, false) } } } adapter = articleAdapter } } private fun initSwipeRefreshLayout() { swipeRefreshLayout = rootView?.findViewById(R.id.swipeRefreshLayout)!! swipeRefreshLayout?.apply { setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener { override fun onRefresh(refreshLayout: RefreshLayout) { ZLog.d("onRefresh") fireVibrate() } override fun onLoadMore(refreshLayout: RefreshLayout) { // finishLoadMore(2000/*,false*/)//传入false表示加载失败 } }) } } private fun initFABInflate() { val fabView = rootView?.findViewById<View>(R.id.app_fab_btn) fabView?.setOnClickListener { RvUtils.smoothScrollTop(mRecyclerView) } } override fun initData() { super.initData() ZLog.d("articleAdapter?.itemCount = ${articleAdapter?.itemCount}") getMyCollectArticalData() } override fun initViewModel() { super.initViewModel() viewModel.userCollectArticleListLiveData.observe(this, Observer { ZLog.d("userCollectArticalListLiveData onChanged: $it") if (it == null) { ZLog.d("User collection data is null.") swipeRefreshLayout?.apply { finishRefresh() visibility = View.GONE } showErrorStatus() return@Observer } dismissLoading() swipeRefreshLayout?.visibility = View.VISIBLE loadStatusView?.visibility = View.GONE launchIO { val datas = it.datas ZLog.d("collectionList Size = ${datas?.size};") //当前数据为空时 if (articleAdapter?.getDefItemCount() == 0) { withContext(Dispatchers.Main) { articleAdapter?.addData(datas!!) } return@launchIO } // 数据非空时 val currentFirstData = articleAdapter?.getItem(0) if (currentFirstData?.id != datas!![0].id) { withContext(Dispatchers.Main) { articleAdapter?.addData(datas) } } } }) } private fun getMyCollectArticalData() { viewModel.getCollectArticleData() } }
gpl-2.0
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/link/related/RelatedWidgetPresenterFactory.kt
1
556
package io.github.feelfreelinux.wykopmobilny.ui.widgets.link.related import io.github.feelfreelinux.wykopmobilny.api.links.LinksApi import io.github.feelfreelinux.wykopmobilny.base.Schedulers import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi import javax.inject.Inject class RelatedWidgetPresenterFactory @Inject constructor( val schedulers: Schedulers, val linksApi: LinksApi, val linkHandlerApi: WykopLinkHandlerApi ) { fun create() = RelatedWidgetPresenter(schedulers, linksApi, linkHandlerApi) }
mit
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/tests/testData/incremental/classHierarchyAffected/overrideImplicit/BA.kt
5
22
open class BA : B(), A
apache-2.0
jwren/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageExtensions.kt
2
14289
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.thisLogger import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntityStorage // ------------------------- Updating references ------------------------ @Suppress("unused") fun WorkspaceEntityStorage.updateOneToManyChildrenOfParent(connectionId: ConnectionId, parent: WorkspaceEntity, children: Sequence<WorkspaceEntity>) { (this as WorkspaceEntityStorageBuilderImpl).updateOneToManyChildrenOfParent(connectionId, (parent as WorkspaceEntityBase).id, children.map { (it as WorkspaceEntityBase).id.asChild() }) } internal fun WorkspaceEntityStorageBuilderImpl.updateOneToManyChildrenOfParent(connectionId: ConnectionId, parentId: EntityId, childrenIds: Sequence<ChildEntityId>) { if (!connectionId.isParentNullable) { val existingChildren = extractOneToManyChildrenIds(connectionId, parentId).toHashSet() childrenIds.forEach { existingChildren.remove(it.id) } existingChildren.forEach { removeEntity(it) } } refs.updateOneToManyChildrenOfParent(connectionId, parentId.arrayId, childrenIds) } @Suppress("unused") fun WorkspaceEntityStorage.updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId, parent: WorkspaceEntity, children: Sequence<WorkspaceEntity>) { (this as WorkspaceEntityStorageBuilderImpl).updateOneToAbstractManyChildrenOfParent(connectionId, (parent as WorkspaceEntityBase).id.asParent(), children.map { (it as WorkspaceEntityBase).id.asChild() }) } internal fun WorkspaceEntityStorageBuilderImpl.updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId, parentId: ParentEntityId, childrenIds: Sequence<ChildEntityId>) { refs.updateOneToAbstractManyChildrenOfParent(connectionId, parentId, childrenIds) } @Suppress("unused") fun WorkspaceEntityStorage.updateOneToAbstractOneChildOfParent(connectionId: ConnectionId, parent: WorkspaceEntity, child: WorkspaceEntity?) { (this as WorkspaceEntityStorageBuilderImpl).updateOneToAbstractOneChildOfParent(connectionId, (parent as WorkspaceEntityBase).id.asParent(), (child as? WorkspaceEntityBase)?.id?.asChild()) } internal fun WorkspaceEntityStorageBuilderImpl.updateOneToAbstractOneChildOfParent(connectionId: ConnectionId, parentId: ParentEntityId, childId: ChildEntityId?) { if (childId != null) { refs.updateOneToAbstractOneChildOfParent(connectionId, parentId, childId) } else { refs.removeOneToAbstractOneRefByParent(connectionId, parentId) } } @Suppress("unused") fun WorkspaceEntityStorage.updateOneToOneChildOfParent(connectionId: ConnectionId, parent: WorkspaceEntity, childEntity: WorkspaceEntity?) { (this as WorkspaceEntityStorageBuilderImpl).updateOneToOneChildOfParent(connectionId, (parent as WorkspaceEntityBase).id, (childEntity as? WorkspaceEntityBase)?.id?.asChild()) } internal fun WorkspaceEntityStorageBuilderImpl.updateOneToOneChildOfParent(connectionId: ConnectionId, parentId: EntityId, childEntityId: ChildEntityId?) { if (childEntityId != null) { refs.updateOneToOneChildOfParent(connectionId, parentId.arrayId, childEntityId) } else { refs.removeOneToOneRefByParent(connectionId, parentId.arrayId) } } @Suppress("unused") fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorage.updateOneToManyParentOfChild(connectionId: ConnectionId, child: WorkspaceEntity, parent: Parent?) { (this as WorkspaceEntityStorageBuilderImpl).updateOneToManyParentOfChild(connectionId, (child as WorkspaceEntityBase).id, parent) } internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToManyParentOfChild(connectionId: ConnectionId, childId: EntityId, parent: Parent?) { if (parent != null) { refs.updateOneToManyParentOfChild(connectionId, childId.arrayId, parent) } else { refs.removeOneToManyRefsByChild(connectionId, childId.arrayId) } } @Suppress("unused") fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorage.updateOneToOneParentOfChild(connectionId: ConnectionId, child: WorkspaceEntity, parent: Parent?) { (this as WorkspaceEntityStorageBuilderImpl).updateOneToOneParentOfChild(connectionId, (child as WorkspaceEntityBase).id, parent) } internal fun <Parent : WorkspaceEntityBase> WorkspaceEntityStorageBuilderImpl.updateOneToOneParentOfChild(connectionId: ConnectionId, childId: EntityId, parent: Parent?) { if (!connectionId.isParentNullable && parent != null) { // A very important thing. If we replace a field in one-to-one connection, the previous entity is automatically removed. val existingChild = extractOneToOneChild<WorkspaceEntityBase>(connectionId, parent.id) if (existingChild != null) { removeEntity(existingChild) } } if (parent != null) { refs.updateOneToOneParentOfChild(connectionId, childId.arrayId, parent) } else { refs.removeOneToOneRefByChild(connectionId, childId.arrayId) } } // ------------------------- Extracting references references ------------------------ @Suppress("unused") fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractOneToManyChildren(connectionId: ConnectionId, parent: WorkspaceEntity): Sequence<Child> { return (this as AbstractEntityStorage).extractOneToManyChildren(connectionId, (parent as WorkspaceEntityBase).id) } @Suppress("UNCHECKED_CAST") internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToManyChildren(connectionId: ConnectionId, parentId: EntityId): Sequence<Child> { val entitiesList = entitiesByType[connectionId.childClass] ?: return emptySequence() return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map { val entityData = entitiesList[it] if (entityData == null) { if (!brokenConsistency) { thisLogger().error( """Cannot resolve entity. |Connection id: $connectionId |Unresolved array id: $it |All child array ids: ${refs.getOneToManyChildren(connectionId, parentId.arrayId)?.toArray()} """.trimMargin() ) } null } else entityData.createEntity(this) }?.filterNotNull() as? Sequence<Child> ?: emptySequence() } internal fun AbstractEntityStorage.extractOneToManyChildrenIds(connectionId: ConnectionId, parentId: EntityId): Sequence<EntityId> { return refs.getOneToManyChildren(connectionId, parentId.arrayId)?.map { createEntityId(it, connectionId.childClass) } ?: emptySequence() } @Suppress("unused") fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId, parent: WorkspaceEntity): Sequence<Child> { return (this as AbstractEntityStorage).extractOneToAbstractManyChildren(connectionId, (parent as WorkspaceEntityBase).id.asParent()) } @Suppress("UNCHECKED_CAST") internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToAbstractManyChildren(connectionId: ConnectionId, parentId: ParentEntityId): Sequence<Child> { return refs.getOneToAbstractManyChildren(connectionId, parentId)?.asSequence()?.map { pid -> entityDataByIdOrDie(pid.id).createEntity(this) } as? Sequence<Child> ?: emptySequence() } @Suppress("unused") fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractAbstractOneToOneChild(connectionId: ConnectionId, parent: WorkspaceEntity): Child? { return (this as AbstractEntityStorage).extractAbstractOneToOneChild(connectionId, (parent as WorkspaceEntityBase).id.asParent()) } @Suppress("UNCHECKED_CAST") internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractAbstractOneToOneChild(connectionId: ConnectionId, parentId: ParentEntityId): Child? { return refs.getAbstractOneToOneChildren(connectionId, parentId)?.let { entityDataByIdOrDie(it.id).createEntity(this) as Child } } @Suppress("unused") fun <Child : WorkspaceEntity> WorkspaceEntityStorage.extractOneToOneChild(connectionId: ConnectionId, parent: WorkspaceEntity): Child? { return (this as AbstractEntityStorage).extractOneToOneChild(connectionId, (parent as WorkspaceEntityBase).id) } @Suppress("UNCHECKED_CAST") internal fun <Child : WorkspaceEntity> AbstractEntityStorage.extractOneToOneChild(connectionId: ConnectionId, parentId: EntityId): Child? { val entitiesList = entitiesByType[connectionId.childClass] ?: return null return refs.getOneToOneChild(connectionId, parentId.arrayId) { val childEntityData = entitiesList[it] if (childEntityData == null) { if (!brokenConsistency) { logger<AbstractEntityStorage>().error(""" Consistency issue. Cannot get a child in one to one connection. Connection id: $connectionId Parent id: $parentId Child array id: $it """.trimIndent()) } null } else childEntityData.createEntity(this) as Child } } @Suppress("unused") fun <Parent : WorkspaceEntity> WorkspaceEntityStorage.extractOneToOneParent(connectionId: ConnectionId, child: WorkspaceEntity): Parent? { return (this as AbstractEntityStorage).extractOneToOneParent(connectionId, (child as WorkspaceEntityBase).id) } @Suppress("UNCHECKED_CAST") internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToOneParent(connectionId: ConnectionId, childId: EntityId): Parent? { val entitiesList = entitiesByType[connectionId.parentClass] ?: return null return refs.getOneToOneParent(connectionId, childId.arrayId) { val parentEntityData = entitiesList[it] if (parentEntityData == null) { if (!brokenConsistency) { logger<AbstractEntityStorage>().error(""" Consistency issue. Cannot get a parent in one to one connection. Connection id: $connectionId Child id: $childId Parent array id: $it """.trimIndent()) } null } else parentEntityData.createEntity(this) as Parent } } @Suppress("unused") fun <Parent : WorkspaceEntity> WorkspaceEntityStorage.extractOneToManyParent(connectionId: ConnectionId, child: WorkspaceEntity): Parent? { return (this as AbstractEntityStorage).extractOneToManyParent(connectionId, (child as WorkspaceEntityBase).id) } @Suppress("UNCHECKED_CAST") internal fun <Parent : WorkspaceEntity> AbstractEntityStorage.extractOneToManyParent(connectionId: ConnectionId, childId: EntityId): Parent? { val entitiesList = entitiesByType[connectionId.parentClass] ?: return null return refs.getOneToManyParent(connectionId, childId.arrayId) { val parentEntityData = entitiesList[it] if (parentEntityData == null) { if (!brokenConsistency) { logger<AbstractEntityStorage>().error(""" Consistency issue. Cannot get a parent in one to many connection. Connection id: $connectionId Child id: $childId Parent array id: $it """.trimIndent()) } null } else parentEntityData.createEntity(this) as Parent } }
apache-2.0
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinStringULiteralExpression.kt
4
1280
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry import org.jetbrains.uast.UElement import org.jetbrains.uast.ULiteralExpression import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement import org.jetbrains.uast.wrapULiteral @ApiStatus.Internal class KotlinStringULiteralExpression( override val sourcePsi: PsiElement, givenParent: UElement?, val text: String ) : KotlinAbstractUExpression(givenParent), ULiteralExpression, KotlinUElementWithType, KotlinFakeUElement { constructor(psi: PsiElement, uastParent: UElement?) : this(psi, uastParent, if (psi is KtEscapeStringTemplateEntry) psi.unescapedValue else psi.text) override val value: String get() = text override fun evaluate() = value override fun getExpressionType(): PsiType = PsiType.getJavaLangString(sourcePsi.manager, sourcePsi.resolveScope) override fun unwrapToSourcePsi(): List<PsiElement> = listOfNotNull(wrapULiteral(this).sourcePsi) }
apache-2.0
loxal/FreeEthereum
free-ethereum-core/src/main/java/org/ethereum/vm/program/listener/CompositeProgramListener.kt
1
2632
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * 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 org.ethereum.vm.program.listener import org.ethereum.vm.DataWord import java.util.* class CompositeProgramListener : ProgramListener { private val listeners = ArrayList<ProgramListener>() override fun onMemoryExtend(delta: Int) { for (listener in listeners) { listener.onMemoryExtend(delta) } } override fun onMemoryWrite(address: Int, data: ByteArray, size: Int) { for (listener in listeners) { listener.onMemoryWrite(address, data, size) } } override fun onStackPop() { for (listener in listeners) { listener.onStackPop() } } override fun onStackPush(value: DataWord) { for (listener in listeners) { listener.onStackPush(value) } } override fun onStackSwap(from: Int, to: Int) { for (listener in listeners) { listener.onStackSwap(from, to) } } override fun onStoragePut(key: DataWord, value: DataWord) { for (listener in listeners) { listener.onStoragePut(key, value) } } override fun onStorageClear() { for (listener in listeners) { listener.onStorageClear() } } fun addListener(listener: ProgramListener) { listeners.add(listener) } val isEmpty: Boolean get() = listeners.isEmpty() }
mit
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt
1
32457
// 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.refactoring.pullUp import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.impl.light.LightField import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.classMembers.MemberInfoBase import com.intellij.refactoring.memberPullUp.PullUpData import com.intellij.refactoring.memberPullUp.PullUpHelper import com.intellij.refactoring.util.RefactoringUtil import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.dropDefaultValue import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.inspections.CONSTRUCTOR_VAL_VAR_MODIFIERS import org.jetbrains.kotlin.idea.refactoring.createJavaField import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.memberInfo.toKtDeclarationWrapperAware import org.jetbrains.kotlin.idea.refactoring.safeDelete.removeOverrideModifier import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull import org.jetbrains.kotlin.idea.util.hasComments import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.Variance class KotlinPullUpHelper( private val javaData: PullUpData, private val data: KotlinPullUpData ) : PullUpHelper<MemberInfoBase<PsiMember>> { companion object { private val MODIFIERS_TO_LIFT_IN_SUPERCLASS = listOf(KtTokens.PRIVATE_KEYWORD) private val MODIFIERS_TO_LIFT_IN_INTERFACE = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.INTERNAL_KEYWORD) } private fun KtExpression.isMovable(): Boolean { return accept( object : KtVisitor<Boolean, Nothing?>() { override fun visitKtElement(element: KtElement, arg: Nothing?): Boolean { return element.allChildren.all { (it as? KtElement)?.accept(this, arg) ?: true } } override fun visitKtFile(file: KtFile, data: Nothing?) = false override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, arg: Nothing?): Boolean { val resolvedCall = expression.getResolvedCall(data.resolutionFacade.analyze(expression)) ?: return true val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression && receiver !is KtSuperExpression) return true var descriptor: DeclarationDescriptor = resolvedCall.resultingDescriptor if (descriptor is ConstructorDescriptor) { descriptor = descriptor.containingDeclaration } // todo: local functions if (descriptor is ValueParameterDescriptor) return true if (descriptor is ClassDescriptor && !descriptor.isInner) return true if (descriptor is MemberDescriptor) { if (descriptor.source.getPsi() in propertiesToMoveInitializers) return true descriptor = descriptor.containingDeclaration } return descriptor is PackageFragmentDescriptor || (descriptor is ClassDescriptor && DescriptorUtils.isSubclass(data.targetClassDescriptor, descriptor)) } }, null ) } private fun getCommonInitializer( currentInitializer: KtExpression?, scope: KtBlockExpression?, propertyDescriptor: PropertyDescriptor, elementsToRemove: MutableSet<KtElement> ): KtExpression? { if (scope == null) return currentInitializer var initializerCandidate: KtExpression? = null for (statement in scope.statements) { statement.asAssignment()?.let body@{ val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body) val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression if (receiver != null && receiver !is KtThisExpression) return@body val resolvedCall = lhs.getResolvedCall(data.resolutionFacade.analyze(it)) ?: return@body if (resolvedCall.resultingDescriptor != propertyDescriptor) return@body if (initializerCandidate == null) { if (currentInitializer == null) { if (!statement.isMovable()) return null initializerCandidate = statement elementsToRemove.add(statement) } else { if (!KotlinPsiUnifier.DEFAULT.unify(statement, currentInitializer).isMatched) return null initializerCandidate = currentInitializer elementsToRemove.add(statement) } } else if (!KotlinPsiUnifier.DEFAULT.unify(statement, initializerCandidate).isMatched) return null } } return initializerCandidate } private data class InitializerInfo( val initializer: KtExpression?, val usedProperties: Set<KtProperty>, val usedParameters: Set<KtParameter>, val elementsToRemove: Set<KtElement> ) private fun getInitializerInfo( property: KtProperty, propertyDescriptor: PropertyDescriptor, targetConstructor: KtElement ): InitializerInfo? { val sourceConstructors = targetToSourceConstructors[targetConstructor] ?: return null val elementsToRemove = LinkedHashSet<KtElement>() val commonInitializer = sourceConstructors.fold(null as KtExpression?) { commonInitializer, constructor -> val body = (constructor as? KtSecondaryConstructor)?.bodyExpression getCommonInitializer(commonInitializer, body, propertyDescriptor, elementsToRemove) } if (commonInitializer == null) { elementsToRemove.clear() } val usedProperties = LinkedHashSet<KtProperty>() val usedParameters = LinkedHashSet<KtParameter>() val visitor = object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val context = data.resolutionFacade.analyze(expression) val resolvedCall = expression.getResolvedCall(context) ?: return val receiver = (resolvedCall.getExplicitReceiverValue() as? ExpressionReceiver)?.expression if (receiver != null && receiver !is KtThisExpression) return val target = (resolvedCall.resultingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() when (target) { is KtParameter -> usedParameters.add(target) is KtProperty -> usedProperties.add(target) } } } commonInitializer?.accept(visitor) if (targetConstructor == ((data.targetClass as? KtClass)?.primaryConstructor ?: data.targetClass)) { property.initializer?.accept(visitor) } return InitializerInfo(commonInitializer, usedProperties, usedParameters, elementsToRemove) } private val propertiesToMoveInitializers = with(data) { membersToMove .filterIsInstance<KtProperty>() .filter { val descriptor = memberDescriptors[it] as? PropertyDescriptor descriptor != null && data.sourceClassContext[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false } } private val targetToSourceConstructors = LinkedHashMap<KtElement, MutableList<KtElement>>().let { result -> if (!data.isInterfaceTarget && data.targetClass is KtClass) { result[data.targetClass.primaryConstructor ?: data.targetClass] = ArrayList() data.sourceClass.accept( object : KtTreeVisitorVoid() { private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) { val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression] val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) { result.getOrPut(constructorElement as KtElement) { ArrayList() }.add(callingConstructorElement) } } override fun visitSuperTypeCallEntry(specifier: KtSuperTypeCallEntry) { val constructorRef = specifier.calleeExpression.constructorReferenceExpression ?: return val containingClass = specifier.getStrictParentOfType<KtClassOrObject>() ?: return val callingConstructorElement = containingClass.primaryConstructor ?: containingClass processConstructorReference(constructorRef, callingConstructorElement) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { val constructorRef = constructor.getDelegationCall().calleeExpression ?: return processConstructorReference(constructorRef, constructor) } } ) } result } private val targetConstructorToPropertyInitializerInfoMap = LinkedHashMap<KtElement, Map<KtProperty, InitializerInfo>>().let { result -> for (targetConstructor in targetToSourceConstructors.keys) { val propertyToInitializerInfo = LinkedHashMap<KtProperty, InitializerInfo>() for (property in propertiesToMoveInitializers) { val propertyDescriptor = data.memberDescriptors[property] as? PropertyDescriptor ?: continue propertyToInitializerInfo[property] = getInitializerInfo(property, propertyDescriptor, targetConstructor) ?: continue } val unmovableProperties = RefactoringUtil.transitiveClosure( object : RefactoringUtil.Graph<KtProperty> { override fun getVertices() = propertyToInitializerInfo.keys override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties } ) { !propertyToInitializerInfo.containsKey(it) } propertyToInitializerInfo.keys.removeAll(unmovableProperties) result[targetConstructor] = propertyToInitializerInfo } result } private var dummyField: PsiField? = null private fun addMovedMember(newMember: KtNamedDeclaration) { if (newMember is KtProperty) { // Add dummy light field since PullUpProcessor won't invoke moveFieldInitializations() if no PsiFields are present if (dummyField == null) { val factory = JavaPsiFacade.getElementFactory(newMember.project) val dummyField = object : LightField( newMember.manager, factory.createField("dummy", PsiType.BOOLEAN), factory.createClass("Dummy") ) { // Prevent processing by JavaPullUpHelper override fun getLanguage() = KotlinLanguage.INSTANCE } javaData.movedMembers.add(dummyField) } } when (newMember) { is KtProperty, is KtNamedFunction -> { newMember.getRepresentativeLightMethod()?.let { javaData.movedMembers.add(it) } } is KtClassOrObject -> { newMember.toLightClass()?.let { javaData.movedMembers.add(it) } } } } private fun liftVisibility(declaration: KtNamedDeclaration, ignoreUsages: Boolean = false) { val newModifier = if (data.isInterfaceTarget) KtTokens.PUBLIC_KEYWORD else KtTokens.PROTECTED_KEYWORD val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS val currentModifier = declaration.visibilityModifierTypeOrDefault() if (currentModifier !in modifiersToLift) return if (ignoreUsages || willBeUsedInSourceClass(declaration, data.sourceClass, data.membersToMove)) { if (newModifier != KtTokens.DEFAULT_VISIBILITY_KEYWORD) { declaration.addModifier(newModifier) } else { declaration.removeModifier(currentModifier) } } } override fun setCorrectVisibility(info: MemberInfoBase<PsiMember>) { val member = info.member.namedUnwrappedElement as? KtNamedDeclaration ?: return if (data.isInterfaceTarget) { member.removeModifier(KtTokens.PUBLIC_KEYWORD) } val modifiersToLift = if (data.isInterfaceTarget) MODIFIERS_TO_LIFT_IN_INTERFACE else MODIFIERS_TO_LIFT_IN_SUPERCLASS if (member.visibilityModifierTypeOrDefault() in modifiersToLift) { member.accept( object : KtVisitorVoid() { override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { when (declaration) { is KtClass -> { liftVisibility(declaration) declaration.declarations.forEach { it.accept(this) } } is KtNamedFunction, is KtProperty -> { liftVisibility(declaration, declaration == member && info.isToAbstract) } } } } ) } } override fun encodeContextInfo(info: MemberInfoBase<PsiMember>) { } private fun fixOverrideAndGetClashingSuper( sourceMember: KtCallableDeclaration, targetMember: KtCallableDeclaration ): KtCallableDeclaration? { val memberDescriptor = data.memberDescriptors[sourceMember] as CallableMemberDescriptor if (memberDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() return null } val clashingSuperDescriptor = data.getClashingMemberInTargetClass(memberDescriptor) ?: return null if (clashingSuperDescriptor.overriddenDescriptors.isEmpty()) { targetMember.removeOverrideModifier() } return clashingSuperDescriptor.source.getPsi() as? KtCallableDeclaration } private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) { val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return when (data.targetClass) { is KtClass -> { data.sourceClass.removeSuperTypeListEntry(currentSpecifier) addSuperTypeEntry( currentSpecifier, data.targetClass, data.targetClassDescriptor, data.sourceClassContext, data.sourceToTargetClassSubstitutor ) } is PsiClass -> { val elementFactory = JavaPsiFacade.getElementFactory(member.project) val sourcePsiClass = data.sourceClass.toLightClass() ?: return val superRef = sourcePsiClass.implementsList ?.referenceElements ?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi } ?: return val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef)) data.sourceClass.removeSuperTypeListEntry(currentSpecifier) if (DescriptorUtils.isSubclass(data.targetClassDescriptor, classDescriptor)) return val refList = if (data.isInterfaceTarget) data.targetClass.extendsList else data.targetClass.implementsList refList?.add(elementFactory.createReferenceFromText(superTypeForTarget.canonicalText, null)) } } return } private fun removeOriginalMemberOrAddOverride(member: KtCallableDeclaration) { if (member.isAbstract()) { member.deleteWithCompanion() } else { member.addModifier(KtTokens.OVERRIDE_KEYWORD) KtTokens.VISIBILITY_MODIFIERS.types.forEach { member.removeModifier(it as KtModifierKeywordToken) } (member as? KtNamedFunction)?.valueParameters?.forEach { it.dropDefaultValue() } } } private fun moveToJavaClass(member: KtNamedDeclaration, substitutor: PsiSubstitutor) { if (!(data.targetClass is PsiClass && member.canMoveMemberToJavaClass(data.targetClass))) return // TODO: Drop after PsiTypes in light elements are properly generated if (member is KtCallableDeclaration && member.typeReference == null) { val returnType = (data.memberDescriptors[member] as CallableDescriptor).returnType returnType?.anonymousObjectSuperTypeOrNull()?.let { member.setType(it, false) } } val project = member.project val elementFactory = JavaPsiFacade.getElementFactory(project) val lightMethod = member.getRepresentativeLightMethod()!! val movedMember: PsiMember = when (member) { is KtProperty, is KtParameter -> { val newType = substitutor.substitute(lightMethod.returnType) val newField = createJavaField(member, data.targetClass) newField.typeElement?.replace(elementFactory.createTypeElement(newType)) if (member.isCompanionMemberOf(data.sourceClass)) { newField.modifierList?.setModifierProperty(PsiModifier.STATIC, true) } if (member is KtParameter) { (member.parent as? KtParameterList)?.removeParameter(member) } else { member.deleteWithCompanion() } newField } is KtNamedFunction -> { val newReturnType = substitutor.substitute(lightMethod.returnType) val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) } val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project)) val newTypeParameterBounds = lightMethod.typeParameters.map { it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType } } val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass) RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod) newMethod.returnTypeElement?.replace(elementFactory.createTypeElement(newReturnType)) newMethod.parameterList.parameters.forEachIndexed { i, parameter -> parameter.typeElement?.replace(elementFactory.createTypeElement(newParameterTypes[i])) } newMethod.typeParameters.forEachIndexed { i, typeParameter -> typeParameter.extendsList.referenceElements.forEachIndexed { j, referenceElement -> referenceElement.replace(elementFactory.createReferenceElementByType(newTypeParameterBounds[i][j])) } } removeOriginalMemberOrAddOverride(member) if (!data.isInterfaceTarget && !data.targetClass.hasModifierProperty(PsiModifier.ABSTRACT)) { data.targetClass.modifierList?.setModifierProperty(PsiModifier.ABSTRACT, true) } newMethod } else -> return } JavaCodeStyleManager.getInstance(project).shortenClassReferences(movedMember) } override fun move(info: MemberInfoBase<PsiMember>, substitutor: PsiSubstitutor) { val member = info.member.toKtDeclarationWrapperAware() ?: return if ((member is KtClass || member is KtPsiClassWrapper) && info.overrides != null) { moveSuperInterface(member, substitutor) return } if (data.targetClass is PsiClass) { moveToJavaClass(member, substitutor) return } val markedElements = markElements(member, data.sourceClassContext, data.sourceClassDescriptor, data.targetClassDescriptor) val memberCopy = member.copy() as KtNamedDeclaration fun moveClassOrObject(member: KtClassOrObject, memberCopy: KtClassOrObject): KtClassOrObject { if (data.isInterfaceTarget) { memberCopy.removeModifier(KtTokens.INNER_KEYWORD) } val movedMember = addMemberToTarget(memberCopy, data.targetClass as KtClass) as KtClassOrObject member.deleteWithCompanion() return movedMember } fun moveCallableMember(member: KtCallableDeclaration, memberCopy: KtCallableDeclaration): KtCallableDeclaration { data.targetClass as KtClass val movedMember: KtCallableDeclaration val clashingSuper = fixOverrideAndGetClashingSuper(member, memberCopy) val psiFactory = KtPsiFactory(member) val originalIsAbstract = member.hasModifier(KtTokens.ABSTRACT_KEYWORD) val toAbstract = when { info.isToAbstract -> true !data.isInterfaceTarget -> false member is KtProperty -> member.mustBeAbstractInInterface() else -> false } val classToAddTo = if (member.isCompanionMemberOf(data.sourceClass)) data.targetClass.getOrCreateCompanionObject() else data.targetClass if (toAbstract) { if (!originalIsAbstract) { makeAbstract( memberCopy, data.memberDescriptors[member] as CallableMemberDescriptor, data.sourceToTargetClassSubstitutor, data.targetClass ) } movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member.typeReference == null) { movedMember.typeReference?.addToShorteningWaitSet() } if (movedMember.nextSibling.hasComments()) { movedMember.parent.addAfter(psiFactory.createNewLine(), movedMember) } removeOriginalMemberOrAddOverride(member) } else { movedMember = doAddCallableMember(memberCopy, clashingSuper, classToAddTo) if (member is KtParameter && movedMember is KtParameter) { member.valOrVarKeyword?.delete() CONSTRUCTOR_VAL_VAR_MODIFIERS.forEach { member.removeModifier(it) } val superEntry = data.superEntryForTargetClass val superResolvedCall = data.targetClassSuperResolvedCall if (superResolvedCall != null) { val superCall = if (superEntry !is KtSuperTypeCallEntry || superEntry.valueArgumentList == null) { superEntry!!.replaced(psiFactory.createSuperTypeCallEntry("${superEntry.text}()")) } else superEntry val argumentList = superCall.valueArgumentList!! val parameterIndex = movedMember.parameterIndex() val prevParameterDescriptor = superResolvedCall.resultingDescriptor.valueParameters.getOrNull(parameterIndex - 1) val prevArgument = superResolvedCall.valueArguments[prevParameterDescriptor]?.arguments?.singleOrNull() as? KtValueArgument val newArgumentName = if (prevArgument != null && prevArgument.isNamed()) Name.identifier(member.name!!) else null val newArgument = psiFactory.createArgument(psiFactory.createExpression(member.name!!), newArgumentName) if (prevArgument == null) { argumentList.addArgument(newArgument) } else { argumentList.addArgumentAfter(newArgument, prevArgument) } } } else { member.deleteWithCompanion() } } if (originalIsAbstract && data.isInterfaceTarget) { movedMember.removeModifier(KtTokens.ABSTRACT_KEYWORD) } if (movedMember.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { data.targetClass.makeAbstract() } return movedMember } try { val movedMember = when (member) { is KtCallableDeclaration -> moveCallableMember(member, memberCopy as KtCallableDeclaration) is KtClassOrObject -> moveClassOrObject(member, memberCopy as KtClassOrObject) else -> return } movedMember.modifierList?.reformatted() applyMarking(movedMember, data.sourceToTargetClassSubstitutor, data.targetClassDescriptor) addMovedMember(movedMember) } finally { clearMarking(markedElements) } } override fun postProcessMember(member: PsiMember) { val declaration = member.unwrapped as? KtNamedDeclaration ?: return dropOverrideKeywordIfNecessary(declaration) } override fun moveFieldInitializations(movedFields: LinkedHashSet<PsiField>) { val psiFactory = KtPsiFactory(data.sourceClass) fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer { getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer } return addDeclaration(psiFactory.createAnonymousInitializer()) } fun KtElement.getConstructorBodyBlock(): KtBlockExpression? { return when (this) { is KtClassOrObject -> { getOrCreateClassInitializer().body } is KtPrimaryConstructor -> { getContainingClassOrObject().getOrCreateClassInitializer().body } is KtSecondaryConstructor -> { bodyExpression ?: add(psiFactory.createEmptyBody()) } else -> null } as? KtBlockExpression } fun KtClassOrObject.getDelegatorToSuperCall(): KtSuperTypeCallEntry? { return superTypeListEntries.singleOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry } fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) { if (info.usedParameters.isEmpty()) return val constructor: KtConstructor<*> = when (constructorElement) { is KtConstructor<*> -> constructorElement is KtClass -> constructorElement.createPrimaryConstructorIfAbsent() else -> return } with(constructor.getValueParameterList()!!) { info.usedParameters.forEach { val newParameter = addParameter(it) val originalType = data.sourceClassContext[BindingContext.VALUE_PARAMETER, it]!!.type newParameter.setType( data.sourceToTargetClassSubstitutor.substitute(originalType, Variance.INVARIANT) ?: originalType, false ) newParameter.typeReference!!.addToShorteningWaitSet() } } targetToSourceConstructors[constructorElement]!!.forEach { val superCall: KtCallElement? = when (it) { is KtClassOrObject -> it.getDelegatorToSuperCall() is KtPrimaryConstructor -> it.getContainingClassOrObject().getDelegatorToSuperCall() is KtSecondaryConstructor -> { if (it.hasImplicitDelegationCall()) { it.replaceImplicitDelegationCallWithExplicit(false) } else { it.getDelegationCall() } } else -> null } superCall?.valueArgumentList?.let { args -> info.usedParameters.forEach { parameter -> args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_"))) } } } } for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entries) { val properties = propertyToInitializerInfo.keys.sortedWith( Comparator { property1, property2 -> val info1 = propertyToInitializerInfo[property1]!! val info2 = propertyToInitializerInfo[property2]!! when { property2 in info1.usedProperties -> -1 property1 in info2.usedProperties -> 1 else -> 0 } } ) for (oldProperty in properties) { val info = propertyToInitializerInfo.getValue(oldProperty) addUsedParameters(constructorElement, info) info.initializer?.let { val body = constructorElement.getConstructorBodyBlock() body?.addAfter(it, body.statements.lastOrNull() ?: body.lBrace!!) } info.elementsToRemove.forEach { it.delete() } } } } override fun updateUsage(element: PsiElement) { } } internal fun KtNamedDeclaration.deleteWithCompanion() { val containingClass = this.containingClassOrObject if (containingClass is KtObjectDeclaration && containingClass.isCompanion() && containingClass.declarations.size == 1 && containingClass.getSuperTypeList() == null ) { containingClass.delete() } else { this.delete() } }
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/AddMethodCreateCallableFromUsageFix.kt
5
2799
// 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.quickfix.crossLanguage import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateMethodRequest import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.AbstractCreateCallableFromUsageFixWithTextAndFamilyName import org.jetbrains.kotlin.idea.quickfix.crossLanguage.KotlinElementActionsFactory.Companion.toKotlinTypeInfo import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtModifierList import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer class AddMethodCreateCallableFromUsageFix( private val request: CreateMethodRequest, modifierList: KtModifierList, providedText: String, @Nls familyName: String, targetContainer: KtElement ) : AbstractCreateCallableFromUsageFixWithTextAndFamilyName<KtElement>( providedText = providedText, familyName = familyName, originalExpression = targetContainer ) { private val modifierListPointer = modifierList.createSmartPointer() init { init() } override val callableInfo: FunctionInfo? get() = run { val targetContainer = element ?: return@run null val modifierList = modifierListPointer.element ?: return@run null val resolutionFacade = KotlinCacheService.getInstance(targetContainer.project) .getResolutionFacadeByFile(targetContainer.containingFile, JvmPlatforms.unspecifiedJvmPlatform) ?: return null val returnTypeInfo = request.returnType.toKotlinTypeInfo(resolutionFacade) val parameters = request.expectedParameters val parameterInfos = parameters.map { parameter -> ParameterInfo(parameter.expectedTypes.toKotlinTypeInfo(resolutionFacade), parameter.semanticNames.toList()) } val methodName = request.methodName FunctionInfo( methodName, TypeInfo.Empty, returnTypeInfo, listOf(targetContainer), parameterInfos, isForCompanion = JvmModifier.STATIC in request.modifiers, modifierList = modifierList, preferEmptyBody = true ) } }
apache-2.0
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/codeinsight/EditorConfigCommenter.kt
16
540
// 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.editorconfig.language.codeinsight import com.intellij.lang.Commenter class EditorConfigCommenter : Commenter { override fun getLineCommentPrefix() = "# " override fun getBlockCommentPrefix() = "" override fun getBlockCommentSuffix(): String? = null override fun getCommentedBlockCommentPrefix(): String? = null override fun getCommentedBlockCommentSuffix(): String? = null }
apache-2.0
smmribeiro/intellij-community
python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt
1
17797
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.jetbrains.python.PyNames import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.codeInsight.typing.PyTypedDictTypeProvider import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.documentation.PythonDocumentationProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.types.* import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_FIELDS_PARAMETER import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_NAME_PARAMETER import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL_PARAMETER class PyTypedDictInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return Visitor(holder, PyInspectionVisitor.getContext(session)) } private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { override fun visitPySubscriptionExpression(node: PySubscriptionExpression) { val operandType = myTypeEvalContext.getType(node.operand) if (operandType !is PyTypedDictType || operandType.isInferred()) return val indexExpression = node.indexExpression val indexExpressionValueOptions = getIndexExpressionValueOptions(indexExpression) if (indexExpressionValueOptions.isNullOrEmpty()) { val keyList = operandType.fields.keys.joinToString(transform = { "'$it'" }) registerProblem(indexExpression, PyPsiBundle.message("INSP.typeddict.typeddict.key.must.be.string.literal.expected.one", keyList)) return } val nonMatchingFields = indexExpressionValueOptions.filterNot { it in operandType.fields } if (nonMatchingFields.isNotEmpty()) { registerProblem(indexExpression, if (nonMatchingFields.size == 1) PyPsiBundle.message("INSP.typeddict.typeddict.has.no.key", operandType.name, nonMatchingFields[0]) else { val nonMatchingFieldList = nonMatchingFields.joinToString(transform = { "'$it'" }) PyPsiBundle.message("INSP.typeddict.typeddict.has.no.keys", operandType.name, nonMatchingFieldList) }) } } override fun visitPyTargetExpression(node: PyTargetExpression) { val value = node.findAssignedValue() if (value is PyCallExpression && value.callee != null && PyTypedDictTypeProvider.isTypedDict(value.callee!!, myTypeEvalContext)) { val typedDictName = value.getArgument(0, TYPED_DICT_NAME_PARAMETER, PyExpression::class.java) if (typedDictName is PyStringLiteralExpression && node.name != typedDictName.stringValue) { registerProblem(typedDictName, PyPsiBundle.message("INSP.typeddict.first.argument.has.to.match.variable.name")) } } } override fun visitPyArgumentList(node: PyArgumentList) { if (node.parent is PyClass && PyTypedDictTypeProvider.isTypingTypedDictInheritor(node.parent as PyClass, myTypeEvalContext)) { val arguments = node.arguments for (argument in arguments) { val type = myTypeEvalContext.getType(argument) if (argument !is PyKeywordArgument && type !is PyTypedDictType && !PyTypedDictTypeProvider.isTypedDict(argument, myTypeEvalContext)) { registerProblem(argument, PyPsiBundle.message("INSP.typeddict.typeddict.cannot.inherit.from.non.typeddict.base.class")) } if (argument is PyKeywordArgument && argument.keyword == TYPED_DICT_TOTAL_PARAMETER && argument.valueExpression != null) { checkValidTotality(argument.valueExpression!!) } } } else if (node.callExpression != null) { val callExpression = node.callExpression val callee = callExpression!!.callee if (callee != null && PyTypedDictTypeProvider.isTypedDict(callee, myTypeEvalContext)) { val fields = callExpression.getArgument(1, TYPED_DICT_FIELDS_PARAMETER, PyExpression::class.java) if (fields !is PyDictLiteralExpression) { return } fields.elements.forEach { if (it !is PyKeyValueExpression) return checkValueIsAType(it.value, it.value?.text) } val totalityArgument = callExpression.getArgument(2, TYPED_DICT_TOTAL_PARAMETER, PyExpression::class.java) if (totalityArgument != null) { checkValidTotality(totalityArgument) } } } } override fun visitPyClass(node: PyClass) { if (!PyTypedDictTypeProvider.isTypingTypedDictInheritor(node, myTypeEvalContext)) return if (node.metaClassExpression != null) { registerProblem((node.metaClassExpression as PyExpression).parent, PyPsiBundle.message("INSP.typeddict.specifying.metaclass.not.allowed.in.typeddict")) } val ancestorsFields = mutableMapOf<String, PyTypedDictType.FieldTypeAndTotality>() val typedDictAncestors = node.getAncestorTypes(myTypeEvalContext).filterIsInstance<PyTypedDictType>() typedDictAncestors.forEach { typedDict -> typedDict.fields.forEach { field -> val key = field.key val value = field.value if (key in ancestorsFields && !matchTypedDictFieldTypeAndTotality(ancestorsFields[key]!!, value)) { registerProblem(node.superClassExpressionList, PyPsiBundle.message("INSP.typeddict.cannot.overwrite.typeddict.field.while.merging", key)) } else { ancestorsFields[key] = value } } } val singleStatement = node.statementList.statements.singleOrNull() if (singleStatement != null && singleStatement is PyExpressionStatement && singleStatement.expression is PyNoneLiteralExpression && (singleStatement.expression as PyNoneLiteralExpression).isEllipsis) { registerProblem(tryGetNameIdentifier(singleStatement), PyPsiBundle.message("INSP.typeddict.invalid.statement.in.typeddict.definition.expected.field.name.field.type"), ProblemHighlightType.WEAK_WARNING) return } node.processClassLevelDeclarations { element, _ -> if (element !is PyTargetExpression) { registerProblem(tryGetNameIdentifier(element), PyPsiBundle.message("INSP.typeddict.invalid.statement.in.typeddict.definition.expected.field.name.field.type"), ProblemHighlightType.WEAK_WARNING) return@processClassLevelDeclarations true } if (element.hasAssignedValue()) { registerProblem(element.findAssignedValue(), PyPsiBundle.message("INSP.typeddict.right.hand.side.values.are.not.supported.in.typeddict")) return@processClassLevelDeclarations true } if (element.name in ancestorsFields) { registerProblem(element, PyPsiBundle.message("INSP.typeddict.cannot.overwrite.typeddict.field")) return@processClassLevelDeclarations true } checkValueIsAType(element.annotation?.value, element.annotationValue) true } } override fun visitPyDelStatement(node: PyDelStatement) { for (target in node.targets) { for (expr in PyUtil.flattenedParensAndTuples(target)) { if (expr !is PySubscriptionExpression) continue val type = myTypeEvalContext.getType(expr.operand) if (type is PyTypedDictType && !type.isInferred()) { val index = PyEvaluator.evaluate(expr.indexExpression, String::class.java) if (index == null || index !in type.fields) continue if (type.fields[index]!!.isRequired) { registerProblem(expr.indexExpression, PyPsiBundle.message("INSP.typeddict.key.cannot.be.deleted", index, type.name)) } } } } } override fun visitPyCallExpression(node: PyCallExpression) { val callee = node.callee if (callee !is PyReferenceExpression || callee.qualifier == null) return val nodeType = myTypeEvalContext.getType(callee.qualifier!!) if (nodeType !is PyTypedDictType || nodeType.isInferred()) return val arguments = node.arguments if (PyNames.UPDATE == callee.name) { inspectUpdateSequenceArgument( if (arguments.size == 1 && arguments[0] is PySequenceExpression) (arguments[0] as PySequenceExpression).elements else arguments, nodeType) } if (PyNames.CLEAR == callee.name || PyNames.POPITEM == callee.name) { if (nodeType.fields.any { it.value.isRequired }) { registerProblem(callee.nameElement?.psi, PyPsiBundle.message("INSP.typeddict.this.operation.might.break.typeddict.consistency"), if (PyNames.CLEAR == callee.name) ProblemHighlightType.WARNING else ProblemHighlightType.WEAK_WARNING) } } if (PyNames.POP == callee.name) { val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null if (key != null && key in nodeType.fields && nodeType.fields[key]!!.isRequired) { registerProblem(callee.nameElement?.psi, PyPsiBundle.message("INSP.typeddict.key.cannot.be.deleted", key, nodeType.name)) } } if (PyNames.SETDEFAULT == callee.name) { val key = if (arguments.isNotEmpty()) PyEvaluator.evaluate(arguments[0], String::class.java) else null if (key != null && key in nodeType.fields && !nodeType.fields[key]!!.isRequired) { if (node.arguments.size > 1) { val valueType = myTypeEvalContext.getType(arguments[1]) if (!PyTypeChecker.match(nodeType.fields[key]!!.type, valueType, myTypeEvalContext)) { val expectedTypeName = PythonDocumentationProvider.getTypeName(nodeType.fields[key]!!.type, myTypeEvalContext) val actualTypeName = PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext) registerProblem(arguments[1], PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName)) } } } } if (PyTypingTypeProvider.resolveToQualifiedNames(callee, myTypeEvalContext).contains(PyTypingTypeProvider.MAPPING_GET)) { val keyArgument = node.getArgument(0, "key", PyExpression::class.java) ?: return val key = PyEvaluator.evaluate(keyArgument, String::class.java) if (key == null) { registerProblem(keyArgument, PyPsiBundle.message("INSP.typeddict.key.should.be.string")) return } if (!nodeType.fields.containsKey(key)) { registerProblem(keyArgument, PyPsiBundle.message("INSP.typeddict.typeddict.has.no.key", nodeType.name, key)) } } } override fun visitPyAssignmentStatement(node: PyAssignmentStatement) { val targetsToValuesMapping = node.targetsToValuesMapping node.targets.forEach { target -> if (target !is PySubscriptionExpression) return@forEach val targetType = myTypeEvalContext.getType(target.operand) if (targetType !is PyTypedDictType) return@forEach val indexString = PyEvaluator.evaluate(target.indexExpression, String::class.java) if (indexString == null) return@forEach val expected = targetType.getElementType(indexString) val actualExpressions = targetsToValuesMapping.filter { it.first == target }.map { it.second } actualExpressions.forEach { actual -> val actualType = myTypeEvalContext.getType(actual) if (!PyTypeChecker.match(expected, actualType, myTypeEvalContext)) { val expectedTypeName = PythonDocumentationProvider.getTypeName(expected, myTypeEvalContext) val actualTypeName = PythonDocumentationProvider.getTypeName(actualType, myTypeEvalContext) registerProblem(actual, PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName)) } } } } private fun getIndexExpressionValueOptions(indexExpression: PyExpression?): List<String>? { if (indexExpression == null) return null val indexExprValue = PyEvaluator.evaluate(indexExpression, String::class.java) if (indexExprValue == null) { val type = myTypeEvalContext.getType(indexExpression) ?: return null val members = PyTypeUtil.toStream(type) .map { if (it is PyLiteralType) PyEvaluator.evaluate(it.expression, String::class.java) else null } .toList() return if (members.contains(null)) null else members .filterNotNull() } else { return listOf(indexExprValue) } } /** * Checks that [expression] with [strType] name is a type */ private fun checkValueIsAType(expression: PyExpression?, strType: String?) { if (expression !is PyReferenceExpression && expression !is PySubscriptionExpression && expression !is PyNoneLiteralExpression || strType == null) { registerProblem(expression, PyPsiBundle.message("INSP.typeddict.value.must.be.type"), ProblemHighlightType.WEAK_WARNING) return } val type = Ref.deref(PyTypingTypeProvider.getStringBasedType(strType, expression, myTypeEvalContext)) if (type == null && !PyTypingTypeProvider.resolveToQualifiedNames(expression, myTypeEvalContext).any { qualifiedName -> PyTypingTypeProvider.ANY == qualifiedName }) { registerProblem(expression, PyPsiBundle.message("INSP.typeddict.value.must.be.type"), ProblemHighlightType.WEAK_WARNING) } } private fun tryGetNameIdentifier(element: PsiElement): PsiElement { return if (element is PsiNameIdentifierOwner) element.nameIdentifier ?: element else element } private fun checkValidTotality(totalityValue: PyExpression) { if (LanguageLevel.forElement(totalityValue.originalElement).isPy3K && totalityValue !is PyBoolLiteralExpression || !listOf(PyNames.TRUE, PyNames.FALSE).contains(totalityValue.text)) { registerProblem(totalityValue, PyPsiBundle.message("INSP.typeddict.total.value.must.be.true.or.false")) } } private fun matchTypedDictFieldTypeAndTotality(expected: PyTypedDictType.FieldTypeAndTotality, actual: PyTypedDictType.FieldTypeAndTotality): Boolean { return expected.isRequired == actual.isRequired && PyTypeChecker.match(expected.type, actual.type, myTypeEvalContext) } private fun inspectUpdateSequenceArgument(sequenceElements: Array<PyExpression>, typedDictType: PyTypedDictType) { sequenceElements.forEach { var key: PsiElement? = null var keyAsString: String? = null var value: PyExpression? = null if (it is PyKeyValueExpression && it.key is PyStringLiteralExpression) { key = it.key keyAsString = (it.key as PyStringLiteralExpression).stringValue value = it.value } else if (it is PyParenthesizedExpression) { val expression = PyPsiUtils.flattenParens(it) if (expression == null) return@forEach if (expression is PyTupleExpression && expression.elements.size == 2 && expression.elements[0] is PyStringLiteralExpression) { key = expression.elements[0] keyAsString = (expression.elements[0] as PyStringLiteralExpression).stringValue value = expression.elements[1] } } else if (it is PyKeywordArgument && it.valueExpression != null) { key = it.keywordNode?.psi keyAsString = it.keyword value = it.valueExpression } else return@forEach val fields = typedDictType.fields if (value == null) { return@forEach } if (keyAsString == null) { registerProblem(key, PyPsiBundle.message("INSP.typeddict.cannot.add.non.string.key.to.typeddict", typedDictType.name)) return@forEach } if (!fields.containsKey(keyAsString)) { registerProblem(key, PyPsiBundle.message("INSP.typeddict.typeddict.cannot.have.key", typedDictType.name, keyAsString)) return@forEach } val valueType = myTypeEvalContext.getType(value) if (!PyTypeChecker.match(fields[keyAsString]?.type, valueType, myTypeEvalContext)) { val expectedTypeName = PythonDocumentationProvider.getTypeName(fields[keyAsString]!!.type, myTypeEvalContext) val actualTypeName = PythonDocumentationProvider.getTypeName(valueType, myTypeEvalContext) registerProblem(value, PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName)) return@forEach } } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssertBooleanWithAssertEquality/assertFalseWithMessage.kt
13
230
// RUNTIME_WITH_KOTLIN_TEST import kotlin.test.assertFalse fun foo() { val a = "a" val b = "b" assertFalse(<caret>a == b, "message") } fun bar() { val a = "a" val b = "b" assertFalse(a == b, "message") }
apache-2.0
craftsmenlabs/gareth-jvm
gareth-execution-ri/src/main/kotlin/org/craftsmenlabs/gareth/execution/definitions/InvokableMethod.kt
1
4949
package org.craftsmenlabs.gareth.execution.definitions import org.craftsmenlabs.gareth.validator.GarethIllegalDefinitionException import org.craftsmenlabs.gareth.validator.GarethInvocationException import org.craftsmenlabs.gareth.validator.model.ExecutionRunContext import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Type import java.util.* import java.util.regex.Pattern class InvokableMethod { private val parameters = ArrayList<Class<*>>() val pattern: Pattern val method: Method val description: String? val humanReadable: String? val runcontextParameter: Boolean constructor(glueLine: String, description: String? = null, humanReadable: String, method: Method, runcontextParameter: Boolean) { try { this.runcontextParameter = runcontextParameter pattern = Pattern.compile(glueLine) this.method = method this.description = description this.humanReadable = humanReadable parseMethod() } catch (e: Exception) { throw GarethIllegalDefinitionException(cause = e) } } fun hasRunContext(): Boolean { return this.runcontextParameter } fun getMethodName(): String { return method.name } fun getClassName(): String { return method.declaringClass.name } fun invokeWith(glueLineInExperiment: String, declaringClassInstance: Any, runContext: ExecutionRunContext): Any? { val arguments = ArrayList<Any>() if (hasRunContext()) arguments.add(runContext) val argumentValuesFromInputString = getArgumentValuesFromInputString(glueLineInExperiment) arguments.addAll(argumentValuesFromInputString) try { return method.invoke(declaringClassInstance, *arguments.toArray()) } catch (e: InvocationTargetException) { throw GarethInvocationException(e.targetException.message, e.targetException) } catch (e: Exception) { throw GarethInvocationException(cause = e) } } fun getRegexPatternForGlueLine(): String { return pattern.pattern() } fun getRegularParameters() = parameters.filter({ !isContextParameter(it) }) fun getPattern(): String { return pattern.pattern() } private fun getArgumentValuesFromInputString(input: String): List<Any> { val parametersFromPattern = getParametersFromPattern(input.trim { it <= ' ' }) val parameters = ArrayList<Any>() for (i in parametersFromPattern.indices) { val cls = getRegularParameters()[i] parameters.add(getValueFromString(cls, parametersFromPattern[i])) } return parameters } private fun parseMethod() { for (parameter in method.parameters) { val cls = parameter.type if (isValidType(parameter.parameterizedType)) { if (!isValidType(cls)) { throw IllegalStateException("Parameter type $cls is not supported") } parameters.add(cls) } } } private fun isValidType(type: Type): Boolean { return type.typeName == "java.lang.String" || type.typeName == "int" || type.typeName == "long" || type.typeName == "double" } private fun getValueFromString(cls: Class<*>, stringVal: String): Any { if (cls == String::class.java) { return stringVal } else if (cls == java.lang.Integer.TYPE) { return java.lang.Integer.valueOf(stringVal).toInt() } else if (cls == java.lang.Long.TYPE) { return java.lang.Long.valueOf(stringVal).toLong() } else if (cls == java.lang.Double.TYPE) { return java.lang.Double.valueOf(stringVal).toDouble() } throw IllegalArgumentException("Parameter must be of class String, Int, Long or Double") } private fun getParametersFromPattern(s: String): List<String> { val output = ArrayList<String>() val matcher = pattern.matcher(s) if (!matcher.matches()) { throw IllegalArgumentException("Input string " + s + " could not be matched against pattern " + getPattern()) } val groupCount = matcher.groupCount() val expectedParameters = getRegularParameters().size if (groupCount != expectedParameters) { throw IllegalArgumentException("Input string $s must have $expectedParameters parameters.") } for (i in 1..groupCount) { output.add(matcher.group(i)) } return output } companion object { fun isContextParameter(parameterClass: Class<*>) = ExecutionRunContext::class.java.isAssignableFrom(parameterClass) } }
gpl-2.0
smmribeiro/intellij-community
platform/vcs-impl/testSrc/com/intellij/vcs/log/VcsUserParserTest.kt
13
1081
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log import org.junit.Assert.assertEquals import org.junit.Test class VcsUserParserTest { @Test fun add_space_before_email_in_brackets() { assertCorrection("foo<[email protected]>", "foo <[email protected]>") } @Test fun add_brackets() { val expected = "John Smith <[email protected]>" assertCorrection("John Smith [email protected]", expected) assertCorrection("John Smith <[email protected]", expected) assertCorrection("John Smith [email protected]>", expected) } @Test fun no_correction_needed() { assertDoNothing("John Smith <[email protected]>") } @Test fun correction_not_possible() { assertDoNothing("foo") assertDoNothing("foo bar") } private fun assertCorrection(source: String, expected: String) = assertEquals(expected, VcsUserParser.correct(source)) private fun assertDoNothing(source: String) = assertCorrection(source, source) }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/override/nothingToOverride/changeParameterTypeSingleExpressionFunction.kt
13
196
// "Change function signature to 'fun f(a: Int): Int'" "true" open class A { open fun f(a: Int): Int { return 0 } } class B : A(){ <caret>override fun f(a: String): Int = 7 }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantUnitExpression/atLastAfterClass.kt
13
76
fun test(b: Boolean): Unit = if (b) { class A <caret>Unit } else { }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertBinaryExpressionWithDemorgansLaw/doubleNegation.kt
9
185
// AFTER-WARNING: Parameter 'a' is never used operator fun String.not(): Boolean { return length == 0 } fun foo(a: Boolean, b: Boolean) : Boolean { return !(<caret>!"" || b) }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/run/MainInTest/module/src/mainNullableArray.kt
13
42
fun main(args: Array<String>?) { // yes }
apache-2.0
SirWellington/alchemy-test
src/test/java/tech/sirwellington/alchemy/test/kotlin/KotlinAssertsKtTest.kt
1
2186
/* * Copyright © 2019. Sir Wellington. * 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 tech.sirwellington.alchemy.test.kotlin import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import tech.sirwellington.alchemy.generator.NumberGenerators import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner import tech.sirwellington.alchemy.test.junit.runners.GenerateDouble import tech.sirwellington.alchemy.test.junit.runners.Repeat @RunWith(AlchemyTestRunner::class) @Repeat(50) class KotlinAssertsKtTest { @GenerateDouble(min = 0.0, max = 1000.0) private var double: Double = 0.0 @Before fun setUp() { setupData() setupMocks() } @Test fun testAssertDoubleEquals() { assertDoubleEquals(double, double, 0.0) assertDoubleEquals(double, double, 0.1) assertDoubleEquals(double, double, 0.2) } @Test fun testAssertDoubleEqualsWhenFails() { val margin = NumberGenerators.smallPositiveDoubles().get() val result = double + (margin * 2) assertThrows { assertDoubleEquals(result = result, expected = double, marginOfError = margin) } .isInstanceOf(AssertionError::class.java) } @Test fun testAssertDoubleWithDifferentValues() { val otherDouble = NumberGenerators.smallPositiveDoubles().get() assertThrows { assertDoubleEquals(otherDouble, double, 0.1) } .isInstanceOf(AssertionError::class.java) } private fun setupData() { double = NumberGenerators.smallPositiveDoubles().get() } private fun setupMocks() { } }
apache-2.0
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/check/UnavailableCheck.kt
1
2060
package com.cognifide.gradle.aem.common.instance.check import com.cognifide.gradle.aem.common.instance.LocalInstance import com.cognifide.gradle.aem.common.instance.local.Status import java.util.concurrent.TimeUnit class UnavailableCheck(group: CheckGroup) : DefaultCheck(group) { /** * Status of remote instances cannot be checked easily. Because of that, check will work just a little bit longer. */ val utilisationTime = aem.obj.long { convention(TimeUnit.SECONDS.toMillis(15)) } override fun check() { if (instance.available) { val bundleState = state(sync.osgiFramework.determineBundleState()) if (!bundleState.unknown) { statusLogger.error( "Bundles stable (${bundleState.stablePercent})", "Bundles stable (${bundleState.stablePercent}). HTTP server still responding on $instance" ) return } } else { val reachableStatus = state(sync.status.checkReachableStatus()) if (reachableStatus >= 0) { statusLogger.error( "Reachable ($reachableStatus)", "Reachable - status code ($reachableStatus). HTTP server still responding on $instance" ) return } } if (instance is LocalInstance) { val status = state(instance.checkStatus()) if (!status.runnable) { statusLogger.error( "Awaiting not running", "Unexpected instance status '$status'. Waiting for status '${Status.Type.RUNNABLE.map { it.name }}' of $instance" ) } } else { if (utilisationTime.get() !in 0..progress.stateTime) { statusLogger.error( "Awaiting utilized", "HTTP server not responding. Waiting for utilization (port releasing) of $instance" ) } } } }
apache-2.0
TimePath/java-vfs
src/main/kotlin/com/timepath/vfs/provider/local/LocalFileProvider.kt
1
2910
package com.timepath.vfs.provider.local import com.timepath.vfs.SimpleVFile import java.io.File import java.util.LinkedList import java.util.concurrent.ExecutionException import java.util.concurrent.Future import java.util.logging.Level import java.util.logging.Logger /** * @author TimePath */ public open class LocalFileProvider(file: File) : LocalFile(file) { init { // TODO: lazy loading if (file.isDirectory()) { insert(file) } } /** * Insert children of a directory * * @param toInsert the directory */ private fun insert(toInsert: File) { val start = System.currentTimeMillis() val tasks = LinkedList<Future<Unit>>() visit(toInsert, object : SimpleVFile.FileVisitor { override fun visit(file: File, parent: SimpleVFile) { val entry = LocalFile(file) parent.add(entry) if (file.isDirectory()) { // Depth first search entry.visit(file, this) } else { // Start background identification tasks.add(SimpleVFile.pool.submit<Unit> { SimpleVFile.handlers.forEach { it.handle(file)?.let { // Defensive copy it.toTypedArray().forEach { merge(it, parent) } } } }) } } }) // Await all tasks.forEach { try { it.get() } catch (e: InterruptedException) { LOG.log(Level.SEVERE, null, e) } catch (e: ExecutionException) { LOG.log(Level.SEVERE, null, e) } } LOG.log(Level.INFO, "Recursive file load took {0}ms", System.currentTimeMillis() - start) } companion object { private val LOG = Logger.getLogger(javaClass<LocalFileProvider>().getName()) /** * Adds one file to another, merging any directories. * TODO: additive/union directories to avoid this kludge * * @param src * @param parent */ synchronized private fun merge(src: SimpleVFile, parent: SimpleVFile) { val existing = parent[src.name] if (existing == null) { // Parent does not have this file, simple case parent.add(src) } else { // Add all child files, silently ignore duplicates val children = src.list() // Defensive copy for (file in children.toTypedArray()) { merge(file, existing) } } } } }
artistic-2.0
xmartlabs/bigbang
core/src/main/java/com/xmartlabs/bigbang/core/helper/gsonadapters/LocalDateCustomFormatterAdapter.kt
2
1614
package com.xmartlabs.bigbang.core.helper.gsonadapters import com.google.gson.Gson import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.xmartlabs.bigbang.core.extensions.ifException import com.xmartlabs.bigbang.core.extensions.localDatefromEpochMilli import com.xmartlabs.bigbang.core.extensions.toInstant import org.threeten.bp.LocalDate import org.threeten.bp.format.DateTimeFormatter import timber.log.Timber import java.lang.reflect.Type /** [Gson] type adapter that serializes [LocalDate] objects to any specified format. */ class LocalDateCustomFormatterAdapter(private val dateFormat: DateTimeFormatter) : JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> { @Synchronized override fun serialize(date: LocalDate?, type: Type?, jsonSerializationContext: JsonSerializationContext?) = date?.toInstant() ?.let(dateFormat::format) .ifException(::JsonPrimitive) { Timber.e(it, "Date cannot be serialized, date='%s'", date) } @Synchronized override fun deserialize(jsonElement: JsonElement?, type: Type?, jsonDeserializationContext: JsonDeserializationContext?) = jsonElement ?.let(JsonElement::toString) ?.takeIf(String::isNotEmpty) ?.let(String::toLong) ?.ifException(::localDatefromEpochMilli) { Timber.e(it, "Date cannot be parsed, date='%s'", jsonElement) } }
apache-2.0
juzraai/ted-xml-model
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/common/ContactContractingBody.kt
1
2316
package hu.juzraai.ted.xml.model.tedexport.common import hu.juzraai.ted.xml.model.tedexport.coded.noticedata.Nuts import org.simpleframework.xml.Element /** * @author Zsolt Jurányi */ open class ContactContractingBody( @field:Element(name = "ADDRESS", required = false) var address: String = "", @field:Element(name = "TOWN") var town: String = "", @field:Element(name = "POSTAL_CODE", required = false) var postalcode: String = "", @field:Element(name = "COUNTRY") var country: Country = Country(), @field:Element(name = "CONTACT_POINT", required = false) var contactpoint: String = "", @field:Element(name = "PHONE", required = false) var phone: String = "", @field:Element(name = "E_MAIL") var email: String = "", @field:Element(name = "FAX", required = false) var fax: String = "", @field:Element(name = "NUTS") var nuts: Nuts = Nuts(), @field:Element(name = "URL_GENERAL") var urlgeneral: String = "", @field:Element(name = "URL_BUYER", required = false) var urlbuyer: String = "" ) : OrgIdNew() { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ContactContractingBody) return false if (!super.equals(other)) return false if (address != other.address) return false if (town != other.town) return false if (postalcode != other.postalcode) return false if (country != other.country) return false if (contactpoint != other.contactpoint) return false if (phone != other.phone) return false if (email != other.email) return false if (fax != other.fax) return false if (nuts != other.nuts) return false if (urlgeneral != other.urlgeneral) return false if (urlbuyer != other.urlbuyer) return false return true } override fun hashCode(): Int { var result = address.hashCode() result = 31 * result + town.hashCode() result = 31 * result + postalcode.hashCode() result = 31 * result + country.hashCode() result = 31 * result + contactpoint.hashCode() result = 31 * result + phone.hashCode() result = 31 * result + email.hashCode() result = 31 * result + fax.hashCode() result = 31 * result + nuts.hashCode() result = 31 * result + urlgeneral.hashCode() result = 31 * result + urlbuyer.hashCode() result = 31 * result + super.hashCode() return result } }
apache-2.0
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/test/kotlin/ch/rmy/android/http_shortcuts/utils/ValidationTest.kt
1
4761
package ch.rmy.android.http_shortcuts.utils import android.net.Uri import androidx.core.net.toUri import ch.rmy.android.http_shortcuts.utils.Validation.isAcceptableHttpUrl import ch.rmy.android.http_shortcuts.utils.Validation.isAcceptableUrl import ch.rmy.android.http_shortcuts.utils.Validation.isValidHttpUrl import ch.rmy.android.http_shortcuts.utils.Validation.isValidUrl import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class ValidationTest { @Test fun testValidUrlAcceptable() { assertThat(isAcceptableHttpUrl("http://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("https://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("HTTP://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("HTTPS://example.com"), equalTo(true)) } @Test fun testEmptyStringNotAcceptable() { assertThat(isAcceptableUrl(""), equalTo(false)) assertThat(isAcceptableHttpUrl(""), equalTo(false)) } @Test fun testSchemeOnlyNotAcceptable() { assertThat(isAcceptableUrl("http://"), equalTo(false)) assertThat(isAcceptableHttpUrl("http://"), equalTo(false)) assertThat(isAcceptableHttpUrl("https://"), equalTo(false)) } @Test fun testInvalidSchemeNotAcceptable() { assertThat(isAcceptableHttpUrl("ftp://example.com"), equalTo(false)) } @Test fun testNoSchemeNotAcceptable() { assertThat(isAcceptableHttpUrl("example.com"), equalTo(false)) } @Test fun testVariableSchemeAcceptable() { assertThat(isAcceptableHttpUrl("{{12a21268-84a3-4e79-b7cd-51b87fc49eb7}}://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("{{12a21268-84a3-4e79-b7cd-51b87fc49eb7}}example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("http{{12a21268-84a3-4e79-b7cd-51b87fc49eb7}}://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("{{42}}://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("{{42}}example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("http{{42}}://example.com"), equalTo(true)) } @Test fun testVariableOnlyUrlAcceptable() { assertThat(isAcceptableHttpUrl("{{12a21268-84a3-4e79-b7cd-51b87fc49eb7}}"), equalTo(true)) assertThat(isAcceptableHttpUrl("{{42}}"), equalTo(true)) } @Test fun testPartialVariableSchemeAcceptable() { assertThat(isAcceptableHttpUrl("http{{12a21268-84a3-4e79-b7cd-51b87fc49eb7}}://example.com"), equalTo(true)) assertThat(isAcceptableHttpUrl("http{{42}}://example.com"), equalTo(true)) } @Test fun testNoSchemeNotValid() { assertThat(isValidUrl("example.com".toUri()), equalTo(false)) } @Test fun testNonHttpSchemeNotValidHttpUrl() { assertThat(isValidHttpUrl("ftp://example.com".toUri()), equalTo(false)) } @Test fun testNonHttpSchemeValidUrl() { assertThat(isValidUrl("ftp://example.com".toUri()), equalTo(true)) } @Test fun testEmptyUrlNotValid() { assertThat(isValidHttpUrl("http://".toUri()), equalTo(false)) assertThat(isValidHttpUrl("https://".toUri()), equalTo(false)) assertThat(isValidHttpUrl("https:".toUri()), equalTo(false)) assertThat(isValidHttpUrl("https".toUri()), equalTo(false)) assertThat(isValidHttpUrl("https:/".toUri()), equalTo(false)) assertThat(isValidHttpUrl("https:///".toUri()), equalTo(false)) assertThat(isValidHttpUrl("https://:".toUri()), equalTo(false)) } @Test fun testHttpSchemeValid() { assertThat(isValidHttpUrl("http://example.com".toUri()), equalTo(true)) } @Test fun testHttpSchemeValidCaseInsensitive() { assertThat(isValidHttpUrl("HTTP://example.com".toUri()), equalTo(true)) } @Test fun testHttpsSchemeValid() { assertThat(isValidHttpUrl("https://example.com".toUri()), equalTo(true)) } @Test fun testHttpsSchemeValidCaseInsensitive() { assertThat(isValidHttpUrl("HTTPS://example.com".toUri()), equalTo(true)) } @Test fun testNotValidWithInvalidCharacters() { assertThat(isValidHttpUrl("http://{{1234⁻5678}}".toUri()), equalTo(false)) assertThat(isValidHttpUrl(Uri.parse("https://\"+document.domain+\"/")), equalTo(false)) assertThat(isValidHttpUrl("http://a</".toUri()), equalTo(false)) } @Test fun testUrlWithWhitespacesIsValid() { assertThat(isValidHttpUrl("http://example.com/?cmd=Hello World".toUri()), equalTo(true)) } }
mit