content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package ca.gabrielcastro.openotp.ext import android.text.Editable import android.text.TextWatcher import android.widget.TextView fun TextView.addAfterTextChangedListener(listener: (text: CharSequence) -> Unit) { this.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) { listener(s) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) }
app/src/main/kotlin/ca/gabrielcastro/openotp/ext/TextView+Ext.kt
117860278
package com.mindera.skeletoid.threads.threadpools import com.mindera.skeletoid.logs.LOG import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.util.concurrent.TimeUnit @RunWith(PowerMockRunner::class) @PrepareForTest(LOG::class) class ThreadPoolExecutorUnitTest { companion object { private const val CORE_POOL_SIZE = 10 private const val MAX_POOL_SIZE = 15 private const val KEEP_ALIVE: Long = 5 private val TIME_UNIT = TimeUnit.MILLISECONDS } private lateinit var threadFactory: NamedThreadFactory private lateinit var threadPoolExecutor: ThreadPoolExecutor @Before fun setUp() { threadFactory = NamedThreadFactory(threadPoolName = "", maxFactoryThreads = 1) threadPoolExecutor = ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE, TIME_UNIT, threadFactory) } @Test fun testConstructor() { Assert.assertEquals(CORE_POOL_SIZE, threadPoolExecutor.corePoolSize) Assert.assertEquals(MAX_POOL_SIZE, threadPoolExecutor.maximumPoolSize) Assert.assertEquals(KEEP_ALIVE, threadPoolExecutor.getKeepAliveTime(TIME_UNIT)) Assert.assertEquals(threadFactory, threadPoolExecutor.threadFactory) } @Test fun testThreadPoolInitialization() { Assert.assertEquals(CORE_POOL_SIZE, threadPoolExecutor.corePoolSize) } @Test fun testShutdownThreadPool() { threadPoolExecutor.shutdown() Assert.assertTrue(threadPoolExecutor.isShutdown) } @Test fun testShutdownNowThreadPool() { threadPoolExecutor.shutdownNow() Assert.assertTrue(threadPoolExecutor.isShutdown) } }
base/src/test/java/com/mindera/skeletoid/threads/threadpools/ThreadPoolExecutorUnitTest.kt
151851415
/** * Designed and developed by Aidan Follestad (@afollestad) * * 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.afollestad.materialdialogs.utils import android.graphics.Color import androidx.annotation.AttrRes import androidx.annotation.CheckResult import androidx.annotation.ColorInt import androidx.annotation.ColorRes import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.utils.MDUtil.resolveColor import com.afollestad.materialdialogs.utils.MDUtil.resolveColors @ColorInt @CheckResult internal fun MaterialDialog.resolveColor( @ColorRes res: Int? = null, @AttrRes attr: Int? = null, fallback: (() -> Int)? = null ): Int = resolveColor(windowContext, res, attr, fallback) @CheckResult internal fun MaterialDialog.resolveColors( attrs: IntArray, fallback: ((forAttr: Int) -> Int)? = null ) = resolveColors(windowContext, attrs, fallback) @ColorInt @CheckResult internal fun Int.adjustAlpha(alpha: Float): Int { return Color.argb((255 * alpha).toInt(), Color.red(this), Color.green(this), Color.blue(this)) }
core/src/main/java/com/afollestad/materialdialogs/utils/Colors.kt
453205896
package info.nightscout.androidaps.plugins.pump.omnipod.eros.di import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.di.ActivityScope import info.nightscout.androidaps.plugins.pump.omnipod.common.di.OmnipodWizardModule import info.nightscout.androidaps.plugins.pump.omnipod.eros.data.RLHistoryItemOmnipod import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.service.RileyLinkOmnipodService import info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.ErosPodHistoryActivity import info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.ErosPodManagementActivity import info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.OmnipodErosOverviewFragment import info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.wizard.activation.ErosPodActivationWizardActivity import info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.wizard.deactivation.ErosPodDeactivationWizardActivity @Module(includes = [OmnipodErosHistoryModule::class]) @Suppress("unused") abstract class OmnipodErosModule { // ACTIVITIES @ContributesAndroidInjector abstract fun contributesErosPodManagementActivity(): ErosPodManagementActivity @ContributesAndroidInjector abstract fun contributesErosPodHistoryActivity(): ErosPodHistoryActivity @ActivityScope @ContributesAndroidInjector(modules = [OmnipodWizardModule::class, OmnipodErosWizardViewModelsModule::class]) abstract fun contributesErosActivationWizardActivity(): ErosPodActivationWizardActivity @ActivityScope @ContributesAndroidInjector(modules = [OmnipodWizardModule::class, OmnipodErosWizardViewModelsModule::class]) abstract fun contributesErosDeactivationWizardActivity(): ErosPodDeactivationWizardActivity // FRAGMENTS @ContributesAndroidInjector abstract fun contributesOmnipodErosOverviewFragment(): OmnipodErosOverviewFragment // SERVICES @ContributesAndroidInjector abstract fun contributesOmnipodRileyLinkCommunicationManagerProvider(): OmnipodRileyLinkCommunicationManager @ContributesAndroidInjector abstract fun contributesRileyLinkOmnipodService(): RileyLinkOmnipodService // DATA @ContributesAndroidInjector abstract fun contributesRlHistoryItemOmnipod(): RLHistoryItemOmnipod companion object { @Provides fun erosPodStateManagerProvider(aapsErosPodStateManager: AapsErosPodStateManager): ErosPodStateManager = aapsErosPodStateManager } }
omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/di/OmnipodErosModule.kt
1160564775
// 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.move.changePackage import com.intellij.refactoring.RefactoringBundle import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.move.ContainerChangeInfo import org.jetbrains.kotlin.idea.refactoring.move.ContainerInfo import org.jetbrains.kotlin.idea.refactoring.move.getInternalReferencesToUpdateOnPackageNameChange import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.* import org.jetbrains.kotlin.idea.refactoring.move.postProcessMoveUsages import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile class KotlinChangePackageRefactoring(val file: KtFile) { private val project = file.project fun run(newFqName: FqName) { val packageDirective = file.packageDirective ?: return val currentFqName = packageDirective.fqName val declarationProcessor = MoveKotlinDeclarationsProcessor( MoveDeclarationsDescriptor( project = project, moveSource = MoveSource(file), moveTarget = KotlinDirectoryMoveTarget(newFqName, file.containingDirectory!!.virtualFile), delegate = MoveDeclarationsDelegate.TopLevel ) ) val declarationUsages = project.runSynchronouslyWithProgress(RefactoringBundle.message("progress.text"), true) { runReadAction { declarationProcessor.findUsages().toList() } } ?: return val changeInfo = ContainerChangeInfo(ContainerInfo.Package(currentFqName), ContainerInfo.Package(newFqName)) val internalUsages = file.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) project.executeWriteCommand(KotlinBundle.message("text.change.file.package.to.0", newFqName)) { packageDirective.fqName = newFqName.quoteIfNeeded() postProcessMoveUsages(internalUsages) performDelayedRefactoringRequests(project) declarationProcessor.execute(declarationUsages) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/changePackage/KotlinChangePackageRefactoring.kt
3654083280
package com.bajdcc.LALR1.interpret.module.web import com.bajdcc.LALR1.grammar.runtime.RuntimeObject import com.bajdcc.LALR1.grammar.runtime.data.RuntimeMap import java.net.MalformedURLException import java.net.URL import java.nio.channels.SelectionKey import java.util.concurrent.Semaphore import java.util.regex.Pattern /** * 【模块】请求上下文 * * @author bajdcc */ class ModuleNetWebContext(val key: SelectionKey) { private var sem: Semaphore? = null // 多线程同步只能用信号量 private var header: String? = null var response = "" var mime = "html-utf8" var code = 200 var contentType = 0 private var method: String? = null private var uri: String? = null private var protocol: String? = null private var version: String? = null var url: String? = null private set private val mapReqHeaders = mutableMapOf<String, String>() private val mapRespHeaders = mutableMapOf<String, String>() /** * 请求的结构: * headers(map), method, uri, protocol, version * @return HTTP请求 */ val reqHeader: RuntimeMap get() { val req = RuntimeMap() val headers = RuntimeMap() mapReqHeaders.forEach { key, value -> headers.put(key, RuntimeObject(value)) } req.put("headers", RuntimeObject(headers)) req.put("method", RuntimeObject(method)) req.put("uri", RuntimeObject(uri)) req.put("version", RuntimeObject(version)) req.put("protocol", RuntimeObject(protocol!!.toLowerCase())) req.put("url", RuntimeObject(url)) try { val u = URL(url!!) req.put("port", RuntimeObject(u.port.toLong())) req.put("host", RuntimeObject(u.host)) req.put("path", RuntimeObject(u.path)) req.put("query", RuntimeObject(u.query)) req.put("authority", RuntimeObject(u.authority)) val idx = u.path.lastIndexOf(".") if (idx >= 0) { val postfix = u.path.substring(idx + 1) req.put("ext", RuntimeObject(postfix)) } } catch (e: MalformedURLException) { e.printStackTrace() } return req } var respHeader: RuntimeMap get() { val resp = RuntimeMap() mapRespHeaders.forEach { key, value -> resp.put(key, RuntimeObject(value)) } return resp } set(map) = map.getMap().forEach { key, value -> mapRespHeaders[key] = value.obj.toString() } val respHeaderMap: Map<String, String> get() = mapRespHeaders val respText: String get() = String.format("%s/%s %d %s", protocol, version, code, ModuleNetWebHelper.getStatusCodeText(code)) val mimeString: String get() = ModuleNetWebHelper.getMimeByExtension(mime) fun setReqHeader(header: String) { this.header = header initHeader() } fun getReqHeaderValue(key: String): String { return mapReqHeaders.getOrDefault(key, "") } fun getRespHeaderValue(key: String): String { return mapRespHeaders.getOrDefault(key, "") } private fun initHeader() { val re1 = Pattern.compile("([A-Z]+) ([^ ]+) ([A-Z]+)/(\\d\\.\\d)") val headers = header!!.split("\r\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in 1 until headers.size) { val colon = headers[i].indexOf(':') if (colon != -1) { val key = headers[i].substring(0, colon) val value = headers[i].substring(colon + 1) mapReqHeaders[key.trim { it <= ' ' }] = value.trim { it <= ' ' } } } val m = re1.matcher(headers[0]) if (m.find()) { method = m.group(1).trim { it <= ' ' } uri = m.group(2).trim { it <= ' ' } protocol = m.group(3).trim { it <= ' ' } version = m.group(4).trim { it <= ' ' } url = String.format("%s://%s%s", protocol!!.toLowerCase(), mapReqHeaders.getOrDefault("Host", "unknown"), uri) } mapRespHeaders["Server"] = "jMiniLang Server" } fun block(): Semaphore { sem = Semaphore(0) return sem!! } fun unblock() { try { while (sem == null) { Thread.sleep(100) } } catch (e: InterruptedException) { e.printStackTrace() } sem!!.release() } }
src/main/kotlin/com/bajdcc/LALR1/interpret/module/web/ModuleNetWebContext.kt
3748415409
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.android.type import android.os.Parcel import androidx.test.ext.junit.runners.AndroidJUnit4 import arcs.core.data.FieldType import arcs.core.data.SchemaFields import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import org.junit.Test import org.junit.runner.RunWith /** Tests for [ParcelableSchemaFields]. */ @RunWith(AndroidJUnit4::class) class ParcelableSchemaFieldsTest { @Test fun parcelableRoundtrip_works() { val fields = SchemaFields( singletons = mapOf( "foo" to FieldType.Text, "bar" to FieldType.Number, "inst" to FieldType.Instant, "big" to FieldType.BigInt, "foolist" to FieldType.ListOf(FieldType.Text), "barlist" to FieldType.ListOf(FieldType.EntityRef("schema hash R Us")), "maybeFoo" to FieldType.Text.nullable(), "maybeBar" to FieldType.EntityRef("schema hash R Us").nullable() ), collections = mapOf( "fooCollection" to FieldType.Text, "barCollection" to FieldType.Number, "bigCollection" to FieldType.BigInt ) ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } @Test fun parcelable_invalidList_throwsException() { val unexpectedListType = SchemaFields( singletons = mapOf( "foo" to FieldType.ListOf(FieldType.ListOf(FieldType.Text)) ), collections = emptyMap() ) with(Parcel.obtain()) { assertFailsWith<IllegalStateException> { writeSchemaFields(unexpectedListType, 0) } } } @Test fun parcelable_invalidTuple_throwsException() { val unexpectedTupleType = SchemaFields( singletons = mapOf( "foo" to FieldType.Tuple(listOf(FieldType.Tuple(emptyList()))) ), collections = emptyMap() ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(unexpectedTupleType, 0) marshall() } with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) assertFailsWith<IllegalStateException> { readSchemaFields() } } } @Test fun parcelableRoundtrip_works_refs() { val fields = SchemaFields( singletons = mapOf( "ref" to FieldType.EntityRef("hash"), "refList" to FieldType.ListOf(FieldType.EntityRef("hash1")) ), collections = mapOf( "refCollection" to FieldType.EntityRef("hash2") ) ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } @Test fun parcelableRoundtrip_works_nullableRefs() { val fields = SchemaFields( singletons = mapOf( "maybeInline" to FieldType.InlineEntity("hash").nullable(), "maybeRef" to FieldType.EntityRef("hash2").nullable() ), collections = emptyMap() ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } @Test fun parcelableRoundtrip_works_nullableNullable() { val fields = SchemaFields( singletons = mapOf( "foo" to FieldType.Text.nullable().nullable() ), collections = emptyMap() ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } @Test fun parcelableRoundtrip_works_inlineEntities() { val fields = SchemaFields( singletons = mapOf( "inline" to FieldType.InlineEntity("hash"), "inlineList" to FieldType.ListOf(FieldType.InlineEntity("hash1")) ), collections = mapOf( "inlineCollection" to FieldType.InlineEntity("hash2") ) ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } @Test fun parcelableRoundtrip_works_emptySets() { val fields = SchemaFields( singletons = emptyMap(), collections = emptyMap() ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } @Test fun parcelableRoundtrip_works_tuples() { val fields = SchemaFields( singletons = mapOf( "foo" to FieldType.Text, "tup" to FieldType.Tuple( listOf( FieldType.Boolean, FieldType.Number, FieldType.EntityRef("hash"), FieldType.ListOf(FieldType.Boolean), FieldType.Text.nullable(), FieldType.InlineEntity("hash2") ) ) ), collections = mapOf( "fooCollection" to FieldType.Text, "tupCollection" to FieldType.Tuple(listOf(FieldType.Boolean, FieldType.Number)) ) ) val marshalled = with(Parcel.obtain()) { writeSchemaFields(fields, 0) marshall() } val unmarshalled = with(Parcel.obtain()) { unmarshall(marshalled, 0, marshalled.size) setDataPosition(0) readSchemaFields() } assertThat(unmarshalled).isEqualTo(fields) } }
javatests/arcs/android/type/ParcelableSchemaFieldsTest.kt
1532531868
@file:Suppress("EXPERIMENTAL_FEATURE_WARNING", "EXPERIMENTAL_API_USAGE") package arcs.showcase.nullable import arcs.jvm.host.TargetHost @TargetHost(arcs.android.integration.IntegrationHost::class) class Attending : AbstractAttending() { override fun onReady() { handles.attending.storeAll( handles.invited.fetchAll().filter { it.rsvp == true }.map { // Nulls can be propagated Guest(name = it.name, employee_id = it.employee_id, rsvp = it.rsvp) } ) handles.no_response.storeAll( // Nulls can be read & filtered on handles.invited.fetchAll().filter { it.rsvp == null }.map { Guest(name = it.name, employee_id = it.employee_id, rsvp = it.rsvp) } ) } }
javatests/arcs/showcase/nullable/Attending.kt
2577852840
package biz.eventually.atpl.ui.questions import biz.eventually.atpl.data.db.Question /** * Created by Thibault de Lambilly on 03/12/2017. * */ data class QuestionState(var question: Question, var index: Int, var size: Int) { var isLast: Boolean = false get() { return index == size } }
app/src/main/java/biz/eventually/atpl/ui/questions/QuestionState.kt
33712285
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers import com.intellij.ide.ui.AntialiasingType import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.GraphicsUtil import com.jetbrains.packagesearch.PackageSearchIcons import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.TableColors import java.awt.Component import javax.accessibility.AccessibleContext import javax.accessibility.AccessibleRole import javax.accessibility.AccessibleState import javax.accessibility.AccessibleStateSet import javax.swing.DefaultListCellRenderer import javax.swing.JLabel import javax.swing.JList internal class PopupMenuListItemCellRenderer<T>( private val selectedValue: T?, private val colors: TableColors, private val itemLabelRenderer: (T) -> String = { it.toString() } ) : DefaultListCellRenderer() { private val selectedIcon = PackageSearchIcons.Checkmark private val emptyIcon = EmptyIcon.create(selectedIcon.iconWidth) private var currentItemIsSelected = false override fun getListCellRendererComponent(list: JList<*>, value: Any, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { @Suppress("UNCHECKED_CAST") // It's ok to crash if this isn't true val item = value as T val itemLabel = itemLabelRenderer(item) + " " // The spaces are to compensate for the lack of padding in the label (yes, I know, it's a hack) val label = super.getListCellRendererComponent(list, itemLabel, index, isSelected, cellHasFocus) as JLabel label.font = list.font colors.applyTo(label, isSelected) currentItemIsSelected = item === selectedValue label.icon = if (currentItemIsSelected) selectedIcon else emptyIcon GraphicsUtil.setAntialiasingType(label, AntialiasingType.getAAHintForSwingComponent()) return label } override fun getAccessibleContext(): AccessibleContext { if (accessibleContext == null) { accessibleContext = AccessibleRenderer(currentItemIsSelected) } return accessibleContext } private inner class AccessibleRenderer( private val isSelected: Boolean ) : AccessibleJLabel() { override fun getAccessibleRole(): AccessibleRole = AccessibleRole.CHECK_BOX override fun getAccessibleStateSet(): AccessibleStateSet { val set = super.getAccessibleStateSet() if (isSelected) { set.add(AccessibleState.CHECKED) } return set } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PopupMenuListItemCellRenderer.kt
213492736
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.versions import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.OrderEnumerator import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.ScalarIndexExtension import org.jetbrains.annotations.Nls import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifactConstants import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.projectStructure.version import org.jetbrains.kotlin.idea.vfilefinder.KotlinJavaScriptMetaFileIndex import org.jetbrains.kotlin.idea.vfilefinder.hasSomethingInPackage import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.utils.JsMetadataVersion import org.jetbrains.kotlin.utils.PathUtil fun getLibraryRootsWithAbiIncompatibleKotlinClasses(module: Module): Collection<BinaryVersionedFile<JvmMetadataVersion>> { return getLibraryRootsWithAbiIncompatibleVersion(module, JvmMetadataVersion.INSTANCE, KotlinJvmMetadataVersionIndex) } fun getLibraryRootsWithAbiIncompatibleForKotlinJs(module: Module): Collection<BinaryVersionedFile<JsMetadataVersion>> { return getLibraryRootsWithAbiIncompatibleVersion(module, JsMetadataVersion.INSTANCE, KotlinJsMetadataVersionIndex) } fun Project.forEachAllUsedLibraries(processor: (Library) -> Boolean) { OrderEnumerator.orderEntries(this).forEachLibrary(processor) } enum class LibraryJarDescriptor(val mavenArtifactId: String) { STDLIB_JAR(PathUtil.KOTLIN_JAVA_STDLIB_NAME), REFLECT_JAR(PathUtil.KOTLIN_JAVA_REFLECT_NAME), SCRIPT_RUNTIME_JAR(PathUtil.KOTLIN_JAVA_SCRIPT_RUNTIME_NAME), TEST_JAR(PathUtil.KOTLIN_TEST_NAME), RUNTIME_JDK8_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME), JS_STDLIB_JAR(PathUtil.JS_LIB_NAME); fun findExistingJar(library: Library): VirtualFile? = library.getFiles(OrderRootType.CLASSES).firstOrNull { it.name.startsWith(mavenArtifactId) } val repositoryLibraryProperties: RepositoryLibraryProperties get() = RepositoryLibraryProperties( KotlinArtifactConstants.KOTLIN_MAVEN_GROUP_ID, mavenArtifactId, KotlinPluginLayout.standaloneCompilerVersion.artifactVersion, true, emptyList() ) } data class BinaryVersionedFile<out T : BinaryVersion>(val file: VirtualFile, val version: T, val supportedVersion: T) private fun <T : BinaryVersion> getLibraryRootsWithAbiIncompatibleVersion( module: Module, supportedVersion: T, index: ScalarIndexExtension<T> ): Collection<BinaryVersionedFile<T>> { val id = index.name val moduleWithAllDependencies = setOf(module) + ModuleUtil.getAllDependentModules(module) val moduleWithAllDependentLibraries = GlobalSearchScope.union( moduleWithAllDependencies.map { it.moduleWithLibrariesScope }.toTypedArray() ) val allVersions = FileBasedIndex.getInstance().getAllKeys(id, module.project) val badVersions = allVersions.filterNot(BinaryVersion::isCompatible).toHashSet() val badRoots = hashSetOf<BinaryVersionedFile<T>>() val fileIndex = ProjectFileIndex.getInstance(module.project) for (version in badVersions) { val indexedFiles = FileBasedIndex.getInstance().getContainingFiles(id, version, moduleWithAllDependentLibraries) for (indexedFile in indexedFiles) { val libraryRoot = fileIndex.getClassRootForFile(indexedFile) ?: error( "Only library roots were requested, and only class files should be indexed with the $id key. " + "File: ${indexedFile.path}" ) badRoots.add(BinaryVersionedFile(VfsUtil.getLocalFile(libraryRoot), version, supportedVersion)) } } return badRoots } private val KOTLIN_JS_FQ_NAME = FqName("kotlin.js") fun hasKotlinJsKjsmFile(scope: GlobalSearchScope): Boolean = runReadAction { KotlinJavaScriptMetaFileIndex.hasSomethingInPackage(KOTLIN_JS_FQ_NAME, scope) } fun getStdlibArtifactId(sdk: Sdk?, version: IdeKotlinVersion): String { if (!hasJreSpecificRuntime(version)) { return MAVEN_STDLIB_ID } val sdkVersion = sdk?.version if (hasJdkLikeUpdatedRuntime(version)) { return when { sdkVersion != null && sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) -> MAVEN_STDLIB_ID_JDK8 sdkVersion == JavaSdkVersion.JDK_1_7 -> MAVEN_STDLIB_ID_JDK7 else -> MAVEN_STDLIB_ID } } return when { sdkVersion != null && sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) -> MAVEN_STDLIB_ID_JRE8 sdkVersion == JavaSdkVersion.JDK_1_7 -> MAVEN_STDLIB_ID_JRE7 else -> MAVEN_STDLIB_ID } } fun getDefaultJvmTarget(sdk: Sdk?, version: IdeKotlinVersion): JvmTarget? { if (!hasJreSpecificRuntime(version)) { return null } val sdkVersion = sdk?.version return when { sdkVersion == null -> null sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) -> JvmTarget.JVM_1_8 sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_6) -> JvmTarget.JVM_1_6 else -> null } } fun hasJdkLikeUpdatedRuntime(version: IdeKotlinVersion): Boolean = version.compare("1.2.0-rc-39") >= 0 || version.isSnapshot fun hasJreSpecificRuntime(version: IdeKotlinVersion): Boolean = version.compare("1.1.0") >= 0 || version.isSnapshot const val MAVEN_STDLIB_ID = PathUtil.KOTLIN_JAVA_STDLIB_NAME const val MAVEN_STDLIB_ID_JRE7 = PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME const val MAVEN_STDLIB_ID_JDK7 = PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME const val MAVEN_STDLIB_ID_JRE8 = PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME const val MAVEN_STDLIB_ID_JDK8 = PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME const val MAVEN_JS_STDLIB_ID = PathUtil.JS_LIB_NAME const val MAVEN_JS_TEST_ID = PathUtil.KOTLIN_TEST_JS_NAME const val MAVEN_TEST_ID = PathUtil.KOTLIN_TEST_NAME const val MAVEN_TEST_JUNIT_ID = "kotlin-test-junit" const val MAVEN_COMMON_TEST_ID = "kotlin-test-common" const val MAVEN_COMMON_TEST_ANNOTATIONS_ID = "kotlin-test-annotations-common" val LOG = Logger.getInstance("org.jetbrains.kotlin.idea.versions.KotlinRuntimeLibraryUtilKt") data class LibInfo( val groupId: String, val name: String, val version: String = "0.0.0" ) data class DeprecatedLibInfo( val old: LibInfo, val new: LibInfo, val outdatedAfterVersion: String, @Nls val message: String ) private fun deprecatedLib( oldGroupId: String, oldName: String, newGroupId: String = oldGroupId, newName: String = oldName, outdatedAfterVersion: String, @Nls message: String ): DeprecatedLibInfo { return DeprecatedLibInfo( old = LibInfo(groupId = oldGroupId, name = oldName), new = LibInfo(groupId = newGroupId, name = newName), outdatedAfterVersion = outdatedAfterVersion, message = message ) } val DEPRECATED_LIBRARIES_INFORMATION = listOf( deprecatedLib( oldGroupId = "org.jetbrains.kotlin", oldName = PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME, newName = PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME, outdatedAfterVersion = "1.2.0-rc-39", message = KotlinBundle.message( "version.message.is.deprecated.since.1.2.0.and.should.be.replaced.with", PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME, PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME ) ), deprecatedLib( oldGroupId = "org.jetbrains.kotlin", oldName = PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME, newName = PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME, outdatedAfterVersion = "1.2.0-rc-39", message = KotlinBundle.message( "version.message.is.deprecated.since.1.2.0.and.should.be.replaced.with", PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME, PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME ) ) )
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/versions/KotlinRuntimeLibraryUtil.kt
3672843085
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action import com.google.common.collect.ImmutableSet import com.intellij.codeInsight.lookup.LookupManager import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.EmptyAction import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.application.invokeLater import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.Key import com.intellij.ui.KeyStrokeAdapter import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.helper.EditorDataContext import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.HandlerInjector import com.maddyhome.idea.vim.helper.inInsertMode import com.maddyhome.idea.vim.helper.inNormalMode import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere import com.maddyhome.idea.vim.helper.isPrimaryEditor import com.maddyhome.idea.vim.helper.isTemplateActive import com.maddyhome.idea.vim.helper.updateCaretsVisualAttributes import com.maddyhome.idea.vim.key.ShortcutOwner import com.maddyhome.idea.vim.key.ShortcutOwnerInfo import com.maddyhome.idea.vim.listener.AceJumpService import com.maddyhome.idea.vim.listener.AppCodeTemplates.appCodeTemplateCaptured import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.options.OptionChangeListener import com.maddyhome.idea.vim.options.OptionConstants import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.KeyStroke /** * Handles Vim keys that are treated as action shortcuts by the IDE. * * * These keys are not passed to [com.maddyhome.idea.vim.VimTypedActionHandler] and should be handled by actions. */ class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible*/ { private val traceTime = VimPlugin.getOptionService().isSet(OptionScope.GLOBAL, OptionConstants.ideatracetimeName) override fun actionPerformed(e: AnActionEvent) { LOG.trace("Executing shortcut key action") val editor = getEditor(e) val keyStroke = getKeyStroke(e) if (editor != null && keyStroke != null) { val owner = VimPlugin.getKey().savedShortcutConflicts[keyStroke] if ((owner as? ShortcutOwnerInfo.AllModes)?.owner == ShortcutOwner.UNDEFINED) { VimPlugin.getNotifications(editor.project).notifyAboutShortcutConflict(keyStroke) } // Should we use HelperKt.getTopLevelEditor(editor) here, as we did in former EditorKeyHandler? try { val start = if (traceTime) System.currentTimeMillis() else null KeyHandler.getInstance().handleKey(editor.vim, keyStroke, EditorDataContext.init(editor, e.dataContext).vim) if (start != null) { val duration = System.currentTimeMillis() - start LOG.info("VimShortcut update '$keyStroke': $duration ms") } } catch (ignored: ProcessCanceledException) { // Control-flow exceptions (like ProcessCanceledException) should never be logged // See {@link com.intellij.openapi.diagnostic.Logger.checkException} } catch (throwable: Throwable) { LOG.error(throwable) } } } // There is a chance that we can use BGT, but we call for isCell inside the update. // Not sure if can can use BGT with this call. Let's use EDT for now. override fun getActionUpdateThread() = ActionUpdateThread.EDT override fun update(e: AnActionEvent) { val start = if (traceTime) System.currentTimeMillis() else null e.presentation.isEnabled = isEnabled(e) LOG.debug { "Shortcut key. Enabled: ${e.presentation.isEnabled}" } if (start != null) { val keyStroke = getKeyStroke(e) val duration = System.currentTimeMillis() - start LOG.info("VimShortcut update '$keyStroke': $duration ms") } } private fun isEnabled(e: AnActionEvent): Boolean { if (!VimPlugin.isEnabled()) return false val editor = getEditor(e) val keyStroke = getKeyStroke(e) if (editor != null && keyStroke != null) { if (editor.isIdeaVimDisabledHere) { LOG.trace("Do not execute shortcut because it's disabled here") return false } // Workaround for smart step into @Suppress("DEPRECATION", "LocalVariableName", "VariableNaming") val SMART_STEP_INPLACE_DATA = Key.findKeyByName("SMART_STEP_INPLACE_DATA") if (SMART_STEP_INPLACE_DATA != null && editor.getUserData(SMART_STEP_INPLACE_DATA) != null) { LOG.trace("Do not execute shortcut because of smart step") return false } val keyCode = keyStroke.keyCode if (HandlerInjector.notebookCommandMode(editor)) { LOG.debug("Python Notebook command mode") if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_KP_RIGHT || keyCode == KeyEvent.VK_ENTER) { invokeLater { editor.updateCaretsVisualAttributes() } } return false } if (AceJumpService.getInstance()?.isActive(editor) == true) { LOG.trace("Do not execute shortcut because AceJump is active") return false } if (LookupManager.getActiveLookup(editor) != null && !LookupKeys.isEnabledForLookup(keyStroke)) { LOG.trace("Do not execute shortcut because of lookup keys") return false } if (keyCode == KeyEvent.VK_ESCAPE) return isEnabledForEscape(editor) if (keyCode == KeyEvent.VK_TAB && editor.isTemplateActive()) return false if ((keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ENTER) && editor.appCodeTemplateCaptured()) return false if (editor.inInsertMode) { if (keyCode == KeyEvent.VK_TAB) { // TODO: This stops VimEditorTab seeing <Tab> in insert mode and correctly scrolling the view // There are multiple actions registered for VK_TAB. The important items, in order, are this, the Live // Templates action and TabAction. Returning false in insert mode means that the Live Template action gets to // execute, and this allows Emmet to work (VIM-674). But it also means that the VimEditorTab handle is never // called, so we can't scroll the caret into view correctly. // If we do return true, VimEditorTab handles the Vim side of things and then invokes // IdeActions.ACTION_EDITOR_TAB, which inserts the tab. It also bypasses the Live Template action, and Emmet // no longer works. // This flag is used when recording text entry/keystrokes for repeated insertion. Because we return false and // don't execute the VimEditorTab handler, we don't record tab as an action. Instead, we see an incoming text // change of multiple whitespace characters, which is normally ignored because it's auto-indent content from // hitting <Enter>. When this flag is set, we record the whitespace as the output of the <Tab> VimPlugin.getChange().tabAction = true return false } // Debug watch, Python console, etc. if (keyStroke in NON_FILE_EDITOR_KEYS && !EditorHelper.isFileEditor(editor)) return false } if (keyStroke in VIM_ONLY_EDITOR_KEYS) return true val savedShortcutConflicts = VimPlugin.getKey().savedShortcutConflicts val info = savedShortcutConflicts[keyStroke] return when (info?.forEditor(editor.vim)) { ShortcutOwner.VIM -> true ShortcutOwner.IDE -> !isShortcutConflict(keyStroke) else -> { if (isShortcutConflict(keyStroke)) { savedShortcutConflicts[keyStroke] = ShortcutOwnerInfo.allUndefined } true } } } return false } private fun isEnabledForEscape(editor: Editor): Boolean { val ideaVimSupportValue = (VimPlugin.getOptionService().getOptionValue(OptionScope.LOCAL(IjVimEditor(editor)), IjVimOptionService.ideavimsupportName) as VimString).value return editor.isPrimaryEditor() || EditorHelper.isFileEditor(editor) && !editor.inNormalMode || ideaVimSupportValue.contains(IjVimOptionService.ideavimsupport_dialog) && !editor.inNormalMode } private fun isShortcutConflict(keyStroke: KeyStroke): Boolean { return VimPlugin.getKey().getKeymapConflicts(keyStroke).isNotEmpty() } /** * getDefaultKeyStroke is needed for NEO layout keyboard VIM-987 * but we should cache the value because on the second call (isEnabled -> actionPerformed) * the event is already consumed */ private var keyStrokeCache: Pair<KeyEvent?, KeyStroke?> = null to null private fun getKeyStroke(e: AnActionEvent): KeyStroke? { val inputEvent = e.inputEvent if (inputEvent is KeyEvent) { val defaultKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(inputEvent) val strokeCache = keyStrokeCache if (defaultKeyStroke != null) { keyStrokeCache = inputEvent to defaultKeyStroke return defaultKeyStroke } else if (strokeCache.first === inputEvent) { keyStrokeCache = null to null return strokeCache.second } return KeyStroke.getKeyStrokeForEvent(inputEvent) } return null } private fun getEditor(e: AnActionEvent): Editor? = e.getData(PlatformDataKeys.EDITOR) /** * Every time the key pressed with an active lookup, there is a decision: * should this key be processed by IdeaVim, or by IDE. For example, dot and enter should be processed by IDE, but * <C-W> by IdeaVim. * * The list of keys that should be processed by IDE is stored in the "lookupKeys" option. So, we should search * if the pressed key is presented in this list. The caches are used to speedup the process. */ private object LookupKeys { private var parsedLookupKeys: Set<KeyStroke> = parseLookupKeys() init { VimPlugin.getOptionService().addListener( OptionConstants.lookupkeysName, object : OptionChangeListener<VimDataType> { override fun processGlobalValueChange(oldValue: VimDataType?) { parsedLookupKeys = parseLookupKeys() } } ) } fun isEnabledForLookup(keyStroke: KeyStroke): Boolean = keyStroke !in parsedLookupKeys private fun parseLookupKeys() = (VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, OptionConstants.lookupkeysName) as VimString).value .split(",") .map { injector.parser.parseKeys(it) } .filter { it.isNotEmpty() } .map { it.first() } .toSet() } companion object { @JvmField val VIM_ONLY_EDITOR_KEYS: Set<KeyStroke> = ImmutableSet.builder<KeyStroke>().addAll(getKeyStrokes(KeyEvent.VK_ENTER, 0)) .addAll(getKeyStrokes(KeyEvent.VK_ESCAPE, 0)) .addAll(getKeyStrokes(KeyEvent.VK_TAB, 0)) .addAll(getKeyStrokes(KeyEvent.VK_BACK_SPACE, 0, InputEvent.CTRL_DOWN_MASK)) .addAll(getKeyStrokes(KeyEvent.VK_INSERT, 0)) .addAll(getKeyStrokes(KeyEvent.VK_DELETE, 0, InputEvent.CTRL_DOWN_MASK)) .addAll(getKeyStrokes(KeyEvent.VK_UP, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK)) .addAll(getKeyStrokes(KeyEvent.VK_DOWN, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK)) .addAll( getKeyStrokes( KeyEvent.VK_LEFT, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK ) ) .addAll( getKeyStrokes( KeyEvent.VK_RIGHT, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK ) ) .addAll( getKeyStrokes( KeyEvent.VK_HOME, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK ) ) .addAll( getKeyStrokes( KeyEvent.VK_END, 0, InputEvent.CTRL_DOWN_MASK, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK ) ) .addAll( getKeyStrokes( KeyEvent.VK_PAGE_UP, 0, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK ) ) .addAll( getKeyStrokes( KeyEvent.VK_PAGE_DOWN, 0, InputEvent.SHIFT_DOWN_MASK, InputEvent.CTRL_DOWN_MASK or InputEvent.SHIFT_DOWN_MASK ) ).build() private const val ACTION_ID = "VimShortcutKeyAction" private val NON_FILE_EDITOR_KEYS: Set<KeyStroke> = ImmutableSet.builder<KeyStroke>() .addAll(getKeyStrokes(KeyEvent.VK_ENTER, 0)) .addAll(getKeyStrokes(KeyEvent.VK_ESCAPE, 0)) .addAll(getKeyStrokes(KeyEvent.VK_TAB, 0)) .addAll(getKeyStrokes(KeyEvent.VK_UP, 0)) .addAll(getKeyStrokes(KeyEvent.VK_DOWN, 0)) .build() private val LOG = logger<VimShortcutKeyAction>() @JvmStatic val instance: AnAction by lazy { EmptyAction.wrap(ActionManager.getInstance().getAction(ACTION_ID)) } private fun getKeyStrokes(keyCode: Int, vararg modifiers: Int) = modifiers.map { KeyStroke.getKeyStroke(keyCode, it) } } }
src/main/java/com/maddyhome/idea/vim/action/VimShortcutKeyAction.kt
1775522456
package kebab.report import kebab.core.Browser import java.io.File /** * Created by yy_yank on 2016/10/05. */ class ReportState(val browser: Browser, val label: String, val outputDir: File)
src/main/kotlin/report/ReportState.kt
3662559364
package cc.femto.kommon.ui.recyclerview import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import rx.Observable import rx.subjects.PublishSubject import java.util.concurrent.TimeUnit /** * Inspired by https://gist.github.com/sebnapi/fde648c17616d9d3bcde * * If you extend this Adapter you are able to add a Header, a Footer or both by a similar ViewHolder pattern as in * RecyclerView. * Don't override (Be careful while overriding) - onCreateViewHolder - onBindViewHolder - * getItemCount - getItemViewType * You need to override the abstract methods introduced by this class. This class is * not using generics as RecyclerView.Adapter. Make yourself sure to cast right. */ abstract class AdvancedRecyclerViewAdapter(val paginationListener: OnPaginationListener? = null) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { val PAGINATION_OFFSET = 10 val TYPE_HEADER = Integer.MIN_VALUE val TYPE_FOOTER = Integer.MIN_VALUE + 1 val TYPE_ADAPTEE_OFFSET = 2 } interface OnPaginationListener { fun onPagination() } private var headerViewHolder: RecyclerView.ViewHolder? = null private var footerViewHolder: RecyclerView.ViewHolder? = null private var paginationSubject: PublishSubject<Void>? = null /** * Returns an Observable that emits items once the pagination threshold was reached. It is throttled to avoid * excessive pagination. */ val paginationObservable: Observable<Void> get() { if (paginationSubject == null) { paginationSubject = PublishSubject.create<Void>() } return paginationSubject!!.asObservable().throttleFirst(500, TimeUnit.MILLISECONDS) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { if (viewType == TYPE_HEADER && headerViewHolder != null) { return headerViewHolder!! } else if (viewType == TYPE_FOOTER && footerViewHolder != null) { return footerViewHolder!! } return onCreateBasicItemViewHolder(parent, viewType - TYPE_ADAPTEE_OFFSET) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { if (paginationListener != null && getBasicItemCount() != 0 //don't callback when list is empty && position >= itemCount - 1 - PAGINATION_OFFSET) { paginationListener.onPagination() } if (paginationSubject != null && paginationSubject!!.hasObservers() && getBasicItemCount() != 0 //don't callback when list is empty && position >= itemCount - 1 - PAGINATION_OFFSET) { paginationSubject!!.onNext(null) } if (position == 0 && holder!!.itemViewType == TYPE_HEADER) { //no need to bind, header is not being recycled return } val last = itemCount - 1 if (position == last && holder!!.itemViewType == TYPE_FOOTER) { //no need to bind, footer is not being recycled return } if (holder != null) { val headerOffset = if (headerViewHolder != null) 1 else 0 onBindBasicItemView(holder, position - headerOffset) } } fun offsetPosition(position: Int): Int = if (headerViewHolder != null) position - 1 else position override fun getItemCount(): Int { var itemCount = getBasicItemCount() if (headerViewHolder != null) { itemCount += 1 } if (footerViewHolder != null) { itemCount += 1 } return itemCount } val isEmpty: Boolean get() = getBasicItemCount() == 0 override fun getItemViewType(position: Int): Int { var position = position if (position == 0 && headerViewHolder != null) { return TYPE_HEADER } val last = itemCount - 1 if (position == last && footerViewHolder != null) { return TYPE_FOOTER } //if header exists, readjust position to pass back the true BasicItemViewType position if (headerViewHolder != null) { position-- } if (getBasicItemViewType(position) >= Integer.MAX_VALUE - TYPE_ADAPTEE_OFFSET) { throw IllegalStateException( "AdvancedRecyclerViewAdapter offsets your BasicItemType by $TYPE_ADAPTEE_OFFSET.") } return getBasicItemViewType(position) + TYPE_ADAPTEE_OFFSET } fun setHeaderView(view: View?) { if (view == null) { headerViewHolder = null return } //create concrete instance of abstract ViewHolder class val viewHolder = object : RecyclerView.ViewHolder(view) { } headerViewHolder = viewHolder } fun setFooterView(view: View?) { if (view == null) { footerViewHolder = null return } //create concrete instance of abstract ViewHolder class val viewHolder = object : RecyclerView.ViewHolder(view) { } footerViewHolder = viewHolder } protected abstract fun onCreateBasicItemViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder protected abstract fun onBindBasicItemView(holder: RecyclerView.ViewHolder, position: Int) abstract fun getBasicItemCount(): Int /** * Override when multiple row types are supported. * Make sure you don't use [Integer.MIN_VALUE, Integer.MIN_VALUE + 1] * or Integer.MAX_VALUE as BasicItemViewType */ protected open fun getBasicItemViewType(position: Int): Int { return 0 } }
app/src/main/java/cc/femto/kommon/ui/recyclerview/AdvancedRecyclerViewAdapter.kt
2696031906
package be.duncanc.discordmodbot.bot.sequences import be.duncanc.discordmodbot.bot.commands.CommandModule import be.duncanc.discordmodbot.bot.services.GuildLogger import be.duncanc.discordmodbot.bot.utils.messageTimeFormat import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername import be.duncanc.discordmodbot.data.repositories.jpa.MuteRolesRepository import be.duncanc.discordmodbot.data.services.ScheduledUnmuteService import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Guild import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.springframework.stereotype.Component import java.time.OffsetDateTime import java.util.concurrent.TimeUnit open class PlanUnmuteSequence( user: User, channel: MessageChannel, private val scheduledUnmuteService: ScheduledUnmuteService, private val targetUser: User, private val guildLogger: GuildLogger ) : Sequence( user, channel ), MessageSequence { init { super.channel.sendMessage("In how much days should the user be unmuted?").queue { addMessageToCleaner(it) } } override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) { val days = event.message.contentRaw.toLong() if (days <= 0) { throw IllegalArgumentException("The numbers of days should not be negative or 0") } val unmuteDateTime = OffsetDateTime.now().plusDays(days) scheduledUnmuteService.planUnmute((channel as TextChannel).guild.idLong, targetUser.idLong, unmuteDateTime) confirmationMessage() val guild = channel.guild logScheduledMute(guild, unmuteDateTime) super.destroy() } private fun confirmationMessage() { super.channel.sendMessage("Unmute has been planned.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } private fun logScheduledMute(guild: Guild, unmuteDateTime: OffsetDateTime) { val logEmbed = EmbedBuilder() .setColor(GuildLogger.LIGHT_BLUE) .setTitle("User unmute planned") .addField("User", guild.getMember(targetUser)?.nicknameAndUsername ?: targetUser.name, true) .addField("Moderator", guild.getMember(user)?.nicknameAndUsername ?: user.name, true) .addField("Unmute planned after", unmuteDateTime.format(messageTimeFormat), false) guildLogger.log(logEmbed, targetUser, guild, null, GuildLogger.LogTypeAction.MODERATOR) } } @Component class PlanUnmuteCommand( private val scheduledUnmuteService: ScheduledUnmuteService, private val guildLogger: GuildLogger, private val muteRolesRepository: MuteRolesRepository ) : CommandModule( arrayOf("PlanUnmute"), null, null, ignoreWhitelist = true, requiredPermissions = arrayOf(Permission.MANAGE_ROLES) ) { override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { val userId = try { event.message.contentRaw.substring(command.length + 2).trimStart('<', '@', '!').trimEnd('>').toLong() } catch (ignored: IndexOutOfBoundsException) { throw IllegalArgumentException("This command requires a user id or mention") } catch (ignored: NumberFormatException) { throw IllegalArgumentException("This command requires a user id or mention") } val guild = event.guild muteRolesRepository.findById(guild.idLong).ifPresent { val memberById = guild.getMemberById(userId) if (memberById != null && memberById.roles.contains(memberById.guild.getRoleById(it.roleId)) ) { event.jda.addEventListener( PlanUnmuteSequence( event.author, event.channel, scheduledUnmuteService, memberById.user, guildLogger ) ) } else { sendUserNotMutedMessage(event) } } } private fun sendUserNotMutedMessage(event: MessageReceivedEvent) { event.channel.sendMessage("${event.author.asMention} This user is not muted.").queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } }
src/main/kotlin/be/duncanc/discordmodbot/bot/sequences/PlanUnmuteSequence.kt
2751805808
package fr.free.nrw.commons.upload import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.jraska.livedata.test import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import depictedItem import fr.free.nrw.commons.explore.depictions.DepictsClient import fr.free.nrw.commons.repository.UploadRepository import fr.free.nrw.commons.upload.depicts.DepictsContract import fr.free.nrw.commons.upload.depicts.DepictsPresenter import fr.free.nrw.commons.wikidata.WikidataDisambiguationItems import io.reactivex.Flowable import io.reactivex.schedulers.TestScheduler import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations class DepictsPresenterTest { @get:Rule var testRule = InstantTaskExecutorRule() @Mock internal lateinit var repository: UploadRepository @Mock internal lateinit var view: DepictsContract.View private lateinit var depictsPresenter: DepictsPresenter private lateinit var testScheduler: TestScheduler @Mock lateinit var depictsClient: DepictsClient /** * initial setup */ @Before @Throws(Exception::class) fun setUp() { MockitoAnnotations.initMocks(this) testScheduler = TestScheduler() depictsPresenter = DepictsPresenter(repository, testScheduler, testScheduler) depictsPresenter.onAttachView(view) } @Test fun `Search emission shows view progress`() { depictsPresenter.searchForDepictions("") testScheduler.triggerActions() verify(view).showProgress(false) } @Test fun `search results emission returns distinct results + selected items without disambiguations`() { val searchResults = listOf( depictedItem(id="nonUnique"), depictedItem(id="nonUnique"), depictedItem( instanceOfs = listOf(WikidataDisambiguationItems.CATEGORY.id), id = "unique" ) ) whenever(repository.searchAllEntities("")).thenReturn(Flowable.just(searchResults)) val selectedItem = depictedItem(id = "selected") whenever(repository.selectedDepictions).thenReturn(listOf(selectedItem)) depictsPresenter.searchForDepictions("") testScheduler.triggerActions() verify(view).showProgress(false) verify(view).showError(false) depictsPresenter.depictedItems .test() .assertValue(listOf(selectedItem, depictedItem(id="nonUnique"))) } @Test fun `empty search results with empty term do not show error`() { whenever(repository.searchAllEntities("")).thenReturn(Flowable.just(emptyList())) depictsPresenter.searchForDepictions("") testScheduler.triggerActions() verify(view).showProgress(false) verify(view).showError(false) depictsPresenter.depictedItems .test() .assertValue(emptyList()) } @Test fun `empty search results with non empty term do show error`() { whenever(repository.searchAllEntities("a")).thenReturn(Flowable.just(emptyList())) depictsPresenter.searchForDepictions("a") testScheduler.triggerActions() verify(view).showProgress(false) verify(view).showError(true) depictsPresenter.depictedItems .test() .assertValue(emptyList()) } @Test fun `search error shows error`() { whenever(repository.searchAllEntities("")).thenReturn(Flowable.error(Exception())) depictsPresenter.searchForDepictions("") testScheduler.triggerActions() verify(view).showProgress(false) verify(view).showError(true) } @Test fun `onPreviousButtonClicked goes to previous screen`() { depictsPresenter.onPreviousButtonClicked() verify(view).goToPreviousScreen() } @Test fun `onDepictItemClicked calls repository`() { val depictedItem = depictedItem() depictsPresenter.onDepictItemClicked(depictedItem) verify(repository).onDepictItemClicked(depictedItem) } @Test fun `verifyDepictions with non empty selectedDepictions goes to next screen`() { whenever(repository.selectedDepictions).thenReturn(listOf(depictedItem())) depictsPresenter.verifyDepictions() verify(view).goToNextScreen() } @Test fun `verifyDepictions with empty selectedDepictions goes to noDepictionSelected`() { whenever(repository.selectedDepictions).thenReturn(emptyList()) depictsPresenter.verifyDepictions() verify(view).noDepictionSelected() } }
app/src/test/kotlin/fr/free/nrw/commons/upload/DepictsPresenterTest.kt
714882110
/* * Copyright 2016 Nicolas Picon <[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 fr.nicopico.dashclock.birthday import android.Manifest.permission.READ_CONTACTS import android.content.Intent import android.content.SharedPreferences import android.content.res.Configuration import android.content.res.Resources import android.net.Uri import android.preference.PreferenceManager import android.provider.ContactsContract import android.provider.ContactsContract.Contacts import com.google.android.apps.dashclock.api.DashClockExtension import com.google.android.apps.dashclock.api.ExtensionData import com.jakewharton.threetenabp.AndroidThreeTen import fr.nicopico.happybirthday.domain.model.Contact import fr.nicopico.happybirthday.domain.model.nextBirthdaySorter import fr.nicopico.happybirthday.extensions.hasPermissions import fr.nicopico.happybirthday.extensions.today import fr.nicopico.happybirthday.inject.DataModule import org.threeten.bp.LocalDate import rx.Observable import rx.Subscriber import rx.schedulers.Schedulers import timber.log.Timber import java.util.* import java.util.concurrent.TimeUnit class BirthdayService : DashClockExtension() { private val DEFAULT_LANG = BuildConfig.DEFAULT_LANG private val contactRepository by lazy { DaggerAppComponent.builder() .appModule(AppModule(application)) .dataModule(DataModule(BuildConfig.DEBUG)) .build() .contactRepository() } private val prefs: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(applicationContext) } private var daysLimit: Int = 0 private var showQuickContact: Boolean = false private var disableLocalization: Boolean = false private var contactGroupId: Long? = null private var needToRefreshLocalization: Boolean = false override fun onCreate() { super.onCreate() AndroidThreeTen.init(application) if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } override fun onInitialize(isReconnect: Boolean) { super.onInitialize(isReconnect) addWatchContentUris(arrayOf(ContactsContract.Contacts.CONTENT_URI.toString())) updatePreferences() } override fun onUpdateData(reason: Int) { if (reason == DashClockExtension.UPDATE_REASON_SETTINGS_CHANGED) { updatePreferences() } handleLocalization() if (hasPermissions(READ_CONTACTS)) { Timber.d("READ_CONTACTS permission granted") val today = today() val contactObs = contactRepository .list( filter = { it.inDays(today) <= daysLimit }, sorter = nextBirthdaySorter(), groupId = contactGroupId ) .first() .observeOn(Schedulers.immediate()) contactObs.subscribe(ContactSubscriber(today)) } else { Timber.d("READ_CONTACTS permission denied !") displayMissingPermissionInfo() Observable.timer(5, TimeUnit.SECONDS) .takeUntil { hasPermissions(READ_CONTACTS) } .toCompletable() .subscribe { onUpdateData(UPDATE_REASON_CONTENT_CHANGED) } } } @Suppress("DEPRECATION") private fun handleLocalization() { val config = Configuration() config.setToDefaults() if (needToRefreshLocalization || disableLocalization && DEFAULT_LANG != Locale.getDefault().language) { val locale = when { disableLocalization -> Locale(DEFAULT_LANG) else -> Resources.getSystem().configuration.locale } config.locale = locale Locale.setDefault(locale) baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics) } } private fun updatePreferences() { // Note daysLimit preference is stored as a String because of the EditTextPreference daysLimit = prefs.getString(SettingsActivity.PREF_DAYS_LIMIT_KEY, "7").toInt() showQuickContact = prefs.getBoolean(SettingsActivity.PREF_SHOW_QUICK_CONTACT, true) val noGroupId = SettingsActivity.NO_CONTACT_GROUP_SELECTED contactGroupId = prefs.getString(SettingsActivity.PREF_CONTACT_GROUP, noGroupId) .let { if (it != noGroupId) it else null } ?.toLong() val previousDisableLocalizationValue = disableLocalization disableLocalization = prefs.getBoolean(SettingsActivity.PREF_DISABLE_LOCALIZATION, false) needToRefreshLocalization = previousDisableLocalizationValue != disableLocalization } private fun buildClickIntent(contacts: List<Contact>): Intent { val clickIntent: Intent val firstContact = contacts.first() if (showQuickContact) { // Open QuickContact dialog on click clickIntent = QuickContactProxy.buildIntent(applicationContext, firstContact.lookupKey) } else { clickIntent = Intent(Intent.ACTION_VIEW) clickIntent.data = Uri.withAppendedPath(Contacts.CONTENT_URI, firstContact.id.toString()) } return clickIntent } private fun displayMissingPermissionInfo() { publishUpdate(ExtensionData() .visible(true) .icon(R.drawable.ic_extension_white) .status(getString(R.string.permission_error_title)) .expandedBody(getString(R.string.permission_error_body)) .clickIntent(PermissionActivity.createIntent(this)) ) } private inner class ContactSubscriber(val today: LocalDate) : Subscriber<List<Contact>>() { override fun onNext(contacts: List<Contact>) { if (contacts.isEmpty()) { publishUpdate(ExtensionData().visible(false)) } else { val res = resources val firstContactName = contacts.first().displayName val collapsedTitle = when (contacts.size) { 1 -> firstContactName else -> "$firstContactName + ${contacts.size - 1}" } val expandedTitle = res.getString(R.string.single_birthday_title_format, firstContactName) val body = StringBuilder() contacts.forEachIndexed { i, contact -> if (i > 0) { body.append(contact.displayName).append(", ") } val birthday = contact.birthday if (contact.canComputeAge()) { // Compute age on next birthday val nextBirthdayCal = birthday.nextBirthdayDate(today) val age = contact.getAge(nextBirthdayCal)!! body.append(res.getQuantityString(R.plurals.age_format, age, age)).append(' ') } val inDays = birthday.inDays(today) val inDaysFormat = when (inDays) { 0L -> R.string.when_today_format 1L -> R.string.when_tomorrow_format else -> R.string.when_days_format } body.append(res.getString(inDaysFormat, inDays)).append('\n') } publishUpdate(ExtensionData() .visible(true) .icon(R.drawable.ic_extension_white) .status(collapsedTitle) .expandedTitle(expandedTitle) .expandedBody(body.toString()) .clickIntent(buildClickIntent(contacts)) ) } } override fun onError(e: Throwable) { Timber.e(e, "Unable to retrieve birthdays") if (e is SecurityException) { displayMissingPermissionInfo() } } override fun onCompleted() { // no-op } } }
dashclock/src/main/java/fr/nicopico/dashclock/birthday/BirthdayService.kt
1256676200
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.script.ucache import com.intellij.ide.caches.CachesInvalidator import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.NonClasspathDirectoriesScope.compose import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.classpathEntryToVfs import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.toVfsRoots import org.jetbrains.kotlin.idea.core.script.configuration.utils.ScriptClassRootsStorage import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper import java.lang.ref.Reference import java.lang.ref.SoftReference import kotlin.io.path.Path class ScriptClassRootsCache( private val scripts: Map<String, LightScriptInfo>, private val classes: Set<String>, private val sources: Set<String>, val customDefinitionsUsed: Boolean, val sdks: ScriptSdks ) { companion object { val EMPTY = ScriptClassRootsCache( mapOf(), setOf(), setOf(), true, ScriptSdks(mapOf(), setOf(), setOf()) ) } fun withUpdatedSdks(newSdks: ScriptSdks) = ScriptClassRootsCache(scripts, classes, sources, customDefinitionsUsed, newSdks) fun builder(project: Project): ScriptClassRootsBuilder { return ScriptClassRootsBuilder( project, classes.toMutableSet(), sources.toMutableSet(), scripts.toMutableMap() ).also { builder -> if (customDefinitionsUsed) { builder.useCustomScriptDefinition() } builder.sdks.addAll(sdks) } } abstract class LightScriptInfo(val definition: ScriptDefinition?) { @Volatile var heavyCache: Reference<HeavyScriptInfo>? = null abstract fun buildConfiguration(): ScriptCompilationConfigurationWrapper? } class DirectScriptInfo(val result: ScriptCompilationConfigurationWrapper) : LightScriptInfo(null) { override fun buildConfiguration(): ScriptCompilationConfigurationWrapper = result } class HeavyScriptInfo( val scriptConfiguration: ScriptCompilationConfigurationWrapper, val classFilesScope: GlobalSearchScope, val sdk: Sdk? ) fun getLightScriptInfo(file: String) = scripts[file] fun contains(file: VirtualFile): Boolean = file.path in scripts private fun getHeavyScriptInfo(file: String): HeavyScriptInfo? { val lightScriptInfo = getLightScriptInfo(file) ?: return null val heavy0 = lightScriptInfo.heavyCache?.get() if (heavy0 != null) return heavy0 synchronized(lightScriptInfo) { val heavy1 = lightScriptInfo.heavyCache?.get() if (heavy1 != null) return heavy1 val heavy2 = computeHeavy(lightScriptInfo) lightScriptInfo.heavyCache = SoftReference(heavy2) return heavy2 } } private fun computeHeavy(lightScriptInfo: LightScriptInfo): HeavyScriptInfo? { val configuration = lightScriptInfo.buildConfiguration() ?: return null val roots = configuration.dependenciesClassPath val sdk = sdks[SdkId(configuration.javaHome?.toPath())] return if (sdk == null) { HeavyScriptInfo(configuration, compose(toVfsRoots(roots)), null) } else { val sdkClasses = sdk.rootProvider.getFiles(OrderRootType.CLASSES).toList() HeavyScriptInfo(configuration, compose(sdkClasses + toVfsRoots(roots)), sdk) } } val firstScriptSdk: Sdk? get() = sdks.first val allDependenciesClassFiles: Set<VirtualFile> val allDependenciesSources: Set<VirtualFile> init { allDependenciesClassFiles = mutableSetOf<VirtualFile>().also { result -> classes.mapNotNullTo(result) { classpathEntryToVfs(Path(it)) } } allDependenciesSources = mutableSetOf<VirtualFile>().also { result -> sources.mapNotNullTo(result) { classpathEntryToVfs(Path(it)) } } } val allDependenciesClassFilesScope = compose(allDependenciesClassFiles.toList() + sdks.nonIndexedClassRoots) val allDependenciesSourcesScope = compose(allDependenciesSources.toList() + sdks.nonIndexedSourceRoots) fun getScriptConfiguration(file: VirtualFile): ScriptCompilationConfigurationWrapper? = getHeavyScriptInfo(file.path)?.scriptConfiguration fun getScriptSdk(file: VirtualFile): Sdk? = getHeavyScriptInfo(file.path)?.sdk fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope = getHeavyScriptInfo(file.path)?.classFilesScope ?: GlobalSearchScope.EMPTY_SCOPE fun diff(project: Project, old: ScriptClassRootsCache?): Updates = when (old) { null -> FullUpdate(project, this) this -> NotChanged(this) else -> IncrementalUpdates( cache = this, hasNewRoots = this.hasNewRoots(old), hasOldRoots = old.hasNewRoots(this), updatedScripts = getChangedScripts(old), oldRoots = old.allDependenciesClassFiles + old.allDependenciesSources, newRoots = allDependenciesClassFiles + allDependenciesSources, oldSdkRoots = old.sdks.nonIndexedClassRoots + old.sdks.nonIndexedSourceRoots, newSdkRoots = sdks.nonIndexedClassRoots + sdks.nonIndexedSourceRoots ) } private fun hasNewRoots(old: ScriptClassRootsCache): Boolean { val oldClassRoots = old.allDependenciesClassFiles.toSet() val oldSourceRoots = old.allDependenciesSources.toSet() return allDependenciesClassFiles.any { it !in oldClassRoots } || allDependenciesSources.any { it !in oldSourceRoots } || old.sdks != sdks } private fun getChangedScripts(old: ScriptClassRootsCache): Set<String> { val changed = mutableSetOf<String>() scripts.forEach { if (old.scripts[it.key] != it.value) { changed.add(it.key) } } old.scripts.forEach { if (it.key !in scripts) { changed.add(it.key) } } return changed } interface Updates { val cache: ScriptClassRootsCache val changed: Boolean val hasNewRoots: Boolean val oldRoots: Collection<VirtualFile> val newRoots: Collection<VirtualFile> val oldSdkRoots: Collection<VirtualFile> val newSdkRoots: Collection<VirtualFile> val hasUpdatedScripts: Boolean fun isScriptChanged(scriptPath: String): Boolean } class IncrementalUpdates( override val cache: ScriptClassRootsCache, override val hasNewRoots: Boolean, override val oldRoots: Collection<VirtualFile>, override val newRoots: Collection<VirtualFile>, override val oldSdkRoots: Collection<VirtualFile>, override val newSdkRoots: Collection<VirtualFile>, private val hasOldRoots: Boolean, private val updatedScripts: Set<String> ) : Updates { override val hasUpdatedScripts: Boolean get() = updatedScripts.isNotEmpty() override fun isScriptChanged(scriptPath: String) = scriptPath in updatedScripts override val changed: Boolean get() = hasNewRoots || updatedScripts.isNotEmpty() || hasOldRoots } class FullUpdate(private val project: Project, override val cache: ScriptClassRootsCache) : Updates { override val changed: Boolean get() = true override val hasUpdatedScripts: Boolean get() = true override fun isScriptChanged(scriptPath: String): Boolean = true override val oldRoots: Collection<VirtualFile> = emptyList() override val oldSdkRoots: Collection<VirtualFile> = emptyList() override val newRoots: Collection<VirtualFile> get() = cache.allDependenciesClassFiles + cache.allDependenciesSources override val newSdkRoots: Collection<VirtualFile> get() = cache.sdks.nonIndexedClassRoots + cache.sdks.nonIndexedSourceRoots override val hasNewRoots: Boolean get() = cache.allDependenciesClassFiles.isNotEmpty() || cache.allDependenciesSources.isNotEmpty() || cache.sdks.nonIndexedClassRoots.isNotEmpty() || cache.sdks.nonIndexedSourceRoots.isNotEmpty() } class NotChanged(override val cache: ScriptClassRootsCache) : Updates { override val changed: Boolean get() = false override val hasNewRoots: Boolean get() = false override val hasUpdatedScripts: Boolean get() = false override val oldRoots: Collection<VirtualFile> = emptyList() override val newRoots: Collection<VirtualFile> = emptyList() override val oldSdkRoots: Collection<VirtualFile> = emptyList() override val newSdkRoots: Collection<VirtualFile> = emptyList() override fun isScriptChanged(scriptPath: String): Boolean = false } } class ScriptCacheDependenciesFileInvalidator : CachesInvalidator() { override fun invalidateCaches() { ProjectManager.getInstance().openProjects.forEach { ScriptClassRootsStorage.getInstance(it).clear() } } }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ucache/ScriptClassRootsCache.kt
627705844
package <%= appPackage %>.ui.mapper import <%= appPackage %>.presentation.model.BufferooView import <%= appPackage %>.ui.model.BufferooViewModel import javax.inject.Inject /** * Map a [BufferooView] to and from a [BufferooViewModel] instance when data is moving between * this layer and the Domain layer */ open class BufferooMapper @Inject constructor(): Mapper<BufferooViewModel, BufferooView> { /** * Map a [BufferooView] instance to a [BufferooViewModel] instance */ override fun mapToViewModel(type: BufferooView): BufferooViewModel { return BufferooViewModel(type.name, type.title, type.avatar) } }
templates/buffer-clean-kotlin/mobile-ui/src/main/java/org/buffer/android/boilerplate/ui/mapper/BufferooMapper.kt
3616997807
package org.thoughtcrime.securesms.emoji import androidx.annotation.AttrRes import androidx.annotation.StringRes import org.thoughtcrime.securesms.R /** * All the different Emoji categories the app is aware of in the order we want to display them. */ enum class EmojiCategory(val priority: Int, val key: String, @AttrRes val icon: Int) { PEOPLE(0, "People", R.attr.emoji_category_people), NATURE(1, "Nature", R.attr.emoji_category_nature), FOODS(2, "Foods", R.attr.emoji_category_foods), ACTIVITY(3, "Activity", R.attr.emoji_category_activity), PLACES(4, "Places", R.attr.emoji_category_places), OBJECTS(5, "Objects", R.attr.emoji_category_objects), SYMBOLS(6, "Symbols", R.attr.emoji_category_symbols), FLAGS(7, "Flags", R.attr.emoji_category_flags), EMOTICONS(8, "Emoticons", R.attr.emoji_category_emoticons); @StringRes fun getCategoryLabel(): Int { return getCategoryLabel(icon) } companion object { @JvmStatic fun forKey(key: String) = values().first { it.key == key } @JvmStatic @StringRes fun getCategoryLabel(@AttrRes iconAttr: Int): Int { return when (iconAttr) { R.attr.emoji_category_people -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__smileys_and_people R.attr.emoji_category_nature -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__nature R.attr.emoji_category_foods -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__food R.attr.emoji_category_activity -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__activities R.attr.emoji_category_places -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__places R.attr.emoji_category_objects -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__objects R.attr.emoji_category_symbols -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__symbols R.attr.emoji_category_flags -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__flags R.attr.emoji_category_emoticons -> R.string.ReactWithAnyEmojiBottomSheetDialogFragment__emoticons else -> throw AssertionError() } } } }
app/src/main/java/org/thoughtcrime/securesms/emoji/EmojiCategory.kt
3062858139
/* * 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 * * 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.nowinandroid.core.designsystem.theme import android.os.Build import androidx.annotation.ChecksSdkIntAtLeast import androidx.annotation.VisibleForTesting import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp /** * Light default theme color scheme */ @VisibleForTesting val LightDefaultColorScheme = lightColorScheme( primary = Purple40, onPrimary = Color.White, primaryContainer = Purple90, onPrimaryContainer = Purple10, secondary = Orange40, onSecondary = Color.White, secondaryContainer = Orange90, onSecondaryContainer = Orange10, tertiary = Blue40, onTertiary = Color.White, tertiaryContainer = Blue90, onTertiaryContainer = Blue10, error = Red40, onError = Color.White, errorContainer = Red90, onErrorContainer = Red10, background = DarkPurpleGray99, onBackground = DarkPurpleGray10, surface = DarkPurpleGray99, onSurface = DarkPurpleGray10, surfaceVariant = PurpleGray90, onSurfaceVariant = PurpleGray30, outline = PurpleGray50 ) /** * Dark default theme color scheme */ @VisibleForTesting val DarkDefaultColorScheme = darkColorScheme( primary = Purple80, onPrimary = Purple20, primaryContainer = Purple30, onPrimaryContainer = Purple90, secondary = Orange80, onSecondary = Orange20, secondaryContainer = Orange30, onSecondaryContainer = Orange90, tertiary = Blue80, onTertiary = Blue20, tertiaryContainer = Blue30, onTertiaryContainer = Blue90, error = Red80, onError = Red20, errorContainer = Red30, onErrorContainer = Red90, background = DarkPurpleGray10, onBackground = DarkPurpleGray90, surface = DarkPurpleGray10, onSurface = DarkPurpleGray90, surfaceVariant = PurpleGray30, onSurfaceVariant = PurpleGray80, outline = PurpleGray60 ) /** * Light Android theme color scheme */ @VisibleForTesting val LightAndroidColorScheme = lightColorScheme( primary = Green40, onPrimary = Color.White, primaryContainer = Green90, onPrimaryContainer = Green10, secondary = DarkGreen40, onSecondary = Color.White, secondaryContainer = DarkGreen90, onSecondaryContainer = DarkGreen10, tertiary = Teal40, onTertiary = Color.White, tertiaryContainer = Teal90, onTertiaryContainer = Teal10, error = Red40, onError = Color.White, errorContainer = Red90, onErrorContainer = Red10, background = DarkGreenGray99, onBackground = DarkGreenGray10, surface = DarkGreenGray99, onSurface = DarkGreenGray10, surfaceVariant = GreenGray90, onSurfaceVariant = GreenGray30, outline = GreenGray50 ) /** * Dark Android theme color scheme */ @VisibleForTesting val DarkAndroidColorScheme = darkColorScheme( primary = Green80, onPrimary = Green20, primaryContainer = Green30, onPrimaryContainer = Green90, secondary = DarkGreen80, onSecondary = DarkGreen20, secondaryContainer = DarkGreen30, onSecondaryContainer = DarkGreen90, tertiary = Teal80, onTertiary = Teal20, tertiaryContainer = Teal30, onTertiaryContainer = Teal90, error = Red80, onError = Red20, errorContainer = Red30, onErrorContainer = Red90, background = DarkGreenGray10, onBackground = DarkGreenGray90, surface = DarkGreenGray10, onSurface = DarkGreenGray90, surfaceVariant = GreenGray30, onSurfaceVariant = GreenGray80, outline = GreenGray60 ) /** * Light default gradient colors */ val LightDefaultGradientColors = GradientColors( primary = Purple95, secondary = Orange95, tertiary = Blue95, neutral = DarkPurpleGray95 ) /** * Light Android background theme */ val LightAndroidBackgroundTheme = BackgroundTheme(color = DarkGreenGray95) /** * Dark Android background theme */ val DarkAndroidBackgroundTheme = BackgroundTheme(color = Color.Black) /** * Now in Android theme. * * @param darkTheme Whether the theme should use a dark color scheme (follows system by default). * @param androidTheme Whether the theme should use the Android theme color scheme instead of the * default theme. If this is `false`, then dynamic theming will be used when supported. */ @Composable fun NiaTheme( darkTheme: Boolean = isSystemInDarkTheme(), androidTheme: Boolean = false, content: @Composable () -> Unit ) = NiaTheme( darkTheme = darkTheme, androidTheme = androidTheme, disableDynamicTheming = false, content = content ) /** * Now in Android theme. This is an internal only version, to allow disabling dynamic theming * in tests. * * @param darkTheme Whether the theme should use a dark color scheme (follows system by default). * @param androidTheme Whether the theme should use the Android theme color scheme instead of the * default theme. * @param disableDynamicTheming If `true`, disables the use of dynamic theming, even when it is * supported. This parameter has no effect if [androidTheme] is `true`. */ @Composable internal fun NiaTheme( darkTheme: Boolean = isSystemInDarkTheme(), androidTheme: Boolean = false, disableDynamicTheming: Boolean, content: @Composable () -> Unit ) { val colorScheme = if (androidTheme) { if (darkTheme) DarkAndroidColorScheme else LightAndroidColorScheme } else if (!disableDynamicTheming && supportsDynamicTheming()) { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } else { if (darkTheme) DarkDefaultColorScheme else LightDefaultColorScheme } val defaultGradientColors = GradientColors() val gradientColors = if (androidTheme || (!disableDynamicTheming && supportsDynamicTheming())) { defaultGradientColors } else { if (darkTheme) defaultGradientColors else LightDefaultGradientColors } val defaultBackgroundTheme = BackgroundTheme( color = colorScheme.surface, tonalElevation = 2.dp ) val backgroundTheme = if (androidTheme) { if (darkTheme) DarkAndroidBackgroundTheme else LightAndroidBackgroundTheme } else { defaultBackgroundTheme } CompositionLocalProvider( LocalGradientColors provides gradientColors, LocalBackgroundTheme provides backgroundTheme ) { MaterialTheme( colorScheme = colorScheme, typography = NiaTypography, content = content ) } } @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S) private fun supportsDynamicTheming() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/theme/Theme.kt
3845462190
package testing import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import org.junit.Assert.* import org.junit.Test class ViewModelTest { @Test fun `test greeting updates properly on name change`() { // Setup val mockGreetingProvider = mock<GreetingProvider> { on { greeting } doReturn "Hello" on { friendlyGreeting } doReturn "Hi! How are you?" } val classUnderTest = ViewModel("Nate", mockGreetingProvider) // When classUnderTest.greeting // Then verify(mockGreetingProvider, times(1)).greeting } }
kotlin/Mastering-Kotlin-master/Chapter11/src/testing/ViewModelTest.kt
3527956502
package vi_generics import util.TODO import java.util.* fun task41(): Nothing = TODO( """ Task41. Add a 'partitionTo' function that splits a collection into two collections according to a predicate. Uncomment the commented invocations of 'partitionTo' below and make them compile. There is a 'partition()' function in the standard library that always returns two newly created lists. You should write a function that splits the collection into two collections given as arguments. The signature of the 'toCollection()' function from the standard library may help you. """, references = { l: List<Int> -> l.partition { it > 0 } l.toCollection(HashSet<Int>()) } ) fun List<String>.partitionWordsAndLines(): Pair<List<String>, List<String>> { return partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } } fun Set<Char>.partitionLettersAndOtherSymbols(): Pair<Set<Char>, Set<Char>> { return partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'} } fun <T, C: MutableCollection<T>> Collection<T>.partitionTo(firstCollection: C, secondCollection: C, predicate: (T) -> Boolean): Pair<C, C>{ this.forEach { if(predicate(it)){ firstCollection.add(it) }else{ secondCollection.add(it) } } return Pair(firstCollection, secondCollection) }
src/vi_generics/n41GenericFunctions.kt
1534269099
package com.daveme.chocolateCakePHP.view import com.daveme.chocolateCakePHP.viewHelperTypeFromFieldName import com.daveme.chocolateCakePHP.startsWithUppercaseCharacter import com.daveme.chocolateCakePHP.Settings import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.jetbrains.php.lang.psi.elements.FieldReference import com.jetbrains.php.lang.psi.elements.PhpNamedElement import com.jetbrains.php.lang.psi.resolve.types.PhpType import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4 class ViewHelperInViewHelperTypeProvider : PhpTypeProvider4 { override fun getKey(): Char { return '\u8314' } override fun complete(p0: String?, p1: Project?): PhpType? = null override fun getType(psiElement: PsiElement): PhpType? { if (psiElement !is FieldReference) { return null } val settings = Settings.getInstance(psiElement.project) if (!settings.enabled) { return null } val classReference = psiElement.classReference ?: return null val referenceType = classReference.type if (!referenceType.isComplete) { return null } val fieldReferenceName = psiElement.name ?: return null if (!fieldReferenceName.startsWithUppercaseCharacter()) { return null } for (type in referenceType.types) { if (type.contains("Helper")) { return viewHelperTypeFromFieldName(settings, fieldReferenceName) } } return null } override fun getBySignature(s: String, set: Set<String>, i: Int, project: Project): Collection<PhpNamedElement> { // We use the default signature processor exclusively: return emptyList() } }
src/main/kotlin/com/daveme/chocolateCakePHP/view/ViewHelperInViewHelperTypeProvider.kt
4068674863
package com.eden.orchid.impl.generators import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.generators.OrchidCollection import com.eden.orchid.api.generators.OrchidGenerator import com.eden.orchid.api.generators.PageCollection import com.eden.orchid.api.indexing.OrchidIndex import com.eden.orchid.api.options.OptionsHolder import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.ImpliedKey import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.resources.resource.ExternalResource import com.eden.orchid.api.theme.pages.OrchidPage import org.apache.commons.io.FilenameUtils import org.json.JSONObject @Description(value = "Index external Orchid sites to create strong links between sites.", name = "External Indices") @Archetype(value = ConfigArchetype::class, key = "services.generators") class ExternalIndexGenerator : OrchidGenerator<ExternalIndexGenerator.ExternalIndexModel>(GENERATOR_KEY, Stage.WARM_UP) { @Option @Description( "The indices generated by an Orchid site can be included in the build of another Orchid site, to " + "make strong links between the two sites. The index at `meta/indices.json` will crawl all the sub-indices " + "of that site, or just a single one of that site's sub-indices can be included." ) @ImpliedKey(typeKey = "url") lateinit var externalIndices: List<ExternalIndex> override fun startIndexing(context: OrchidContext): ExternalIndexModel { val allPages = mutableMapOf<String, OrchidIndex>() if (!EdenUtils.isEmpty(externalIndices)) { for (externalIndex in externalIndices) { val indexResource = context.getDefaultResourceSource(null, null).getResourceEntry(context, externalIndex.url) if (indexResource != null) { if(indexResource is ExternalResource) { indexResource.download = true indexResource.downloadInProdOnly = false } val resourceContent = indexResource.parseContent(context, null) val index = OrchidIndex.fromJSON(context, JSONObject(resourceContent)) allPages[externalIndex.indexKey] = index } } } return ExternalIndexModel(allPages) } override fun startGeneration(context: OrchidContext, model: ExternalIndexModel) { } fun getCollections( model: ExternalIndexModel ): List<OrchidCollection<*>> { return model.indexMap.map { (key, value) -> PageCollection(this, key, value.allPages) } } inner class ExternalIndexModel( val indexMap: Map<String, OrchidIndex> ) : Model { override val allPages: List<OrchidPage> = indexMap.values.flatMap { it.allPages } override val collections: List<OrchidCollection<*>> = indexMap.map { (key, value) -> PageCollection(this@ExternalIndexGenerator, key, value.allPages) } } class ExternalIndex : OptionsHolder { @Option lateinit var collectionId: String @Option lateinit var url: String val indexKey: String get() { return if (collectionId.isNotBlank()) collectionId else FilenameUtils.getBaseName(url).replace(".index", "") } } companion object { val GENERATOR_KEY = "external" } }
OrchidCore/src/main/kotlin/com/eden/orchid/impl/generators/ExternalIndexGenerator.kt
321052642
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.testing import com.intellij.codeInsight.completion.* import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.DumbAware import com.intellij.patterns.PlatformPatterns import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.ProcessingContext import com.jetbrains.python.codeInsight.completion.PythonLookupElement import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyParameterList import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.testing.pyTestFixtures.PyTestFixtureAsParameterProvider import com.jetbrains.python.testing.pyTestParametrized.PyTestParameterFromParametrizeProvider import javax.swing.Icon internal class PyTestFunctionParameter(val name: String, val icon: Icon? = null) /** * Implement, inject into [completionProviders] */ internal interface PyTestFunctionParameterProvider { fun getArguments(function: PyFunction, evalContext: TypeEvalContext, module: Module): List<PyTestFunctionParameter> } private val completionProviders = arrayOf(PyTestFixtureAsParameterProvider, PyTestParameterFromParametrizeProvider) /** * Contributes function argument names. * @see completionProviders */ class PyTestParameterCompletionContributor : CompletionContributor(), DumbAware { init { extend(CompletionType.BASIC, PlatformPatterns.psiElement().inside(PyParameterList::class.java), PyTestFunctionArgumentCompletion) } } private object PyTestFunctionArgumentCompletion : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val pyFunction = PsiTreeUtil.getParentOfType(parameters.position, PyParameterList::class.java)?.containingFunction ?: return val module = ModuleUtilCore.findModuleForPsiElement(pyFunction) ?: return val typeEvalContext = TypeEvalContext.codeCompletion(pyFunction.project, pyFunction.containingFile) val usedParams = pyFunction.getParameters(typeEvalContext).mapNotNull { it.name }.toSet() completionProviders .flatMap { it.getArguments(pyFunction, typeEvalContext, module) } .filter { !usedParams.contains(it.name) } .forEach { result.addElement(PythonLookupElement(it.name, false, it.icon)) } } }
python/src/com/jetbrains/python/testing/PyTestFunctionParameterCompletion.kt
4084934881
// "Add non-null asserted (!!) call" "true" class Foo { val bar = Bar() } class Bar { fun f() = 1 } fun test(foo: Foo?) { val f = foo?.bar::f<caret> } // TODO: Enable when FIR reports UNSAFE_CALL for function reference on nullable (currently UNRESOLVED_REFERENCE) /* IGNORE_FIR */
plugins/kotlin/idea/tests/testData/quickfix/addExclExclCall/functionReference2.kt
2107511712
fun check() { 1<caret>.dec() } // SET_FALSE: CONTINUATION_INDENT_FOR_CHAINED_CALLS
plugins/kotlin/idea/tests/testData/editor/enterHandler/beforeDot/IntegerLiteralInFirstPosition.kt
2834694497
// 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.util.indexing.diagnostic import com.intellij.openapi.fileTypes.FileType import com.intellij.util.indexing.ID class FileIndexingStatistics( val fileType: FileType, val indexesProvidedByExtensions: Set<ID<*, *>>, val wasFullyIndexedByExtensions: Boolean, val perIndexerEvaluateIndexValueTimes: Map<ID<*, *>, TimeNano>, val perIndexerEvaluatingIndexValueRemoversTimes: Map<ID<*, *>, TimeNano> )
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/FileIndexingStatistics.kt
3211434588
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.history import com.google.common.util.concurrent.SettableFuture import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.content.TabGroupId import com.intellij.vcs.log.* import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.VcsLogStorage import com.intellij.vcs.log.impl.* import com.intellij.vcs.log.impl.VcsLogNavigationUtil.jumpToRow import com.intellij.vcs.log.impl.VcsLogTabLocation.Companion.findLogUi import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector import com.intellij.vcs.log.ui.MainVcsLogUi import com.intellij.vcs.log.ui.VcsLogUiEx import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.VisiblePack import com.intellij.vcs.log.visible.filters.VcsLogFilterObject import com.intellij.vcs.log.visible.filters.matches import com.intellij.vcsUtil.VcsUtil import java.util.function.Function class VcsLogFileHistoryProviderImpl(project: Project) : VcsLogFileHistoryProvider { private val providers = listOf(VcsLogSingleFileHistoryProvider(project), VcsLogDirectoryHistoryProvider(project)) override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean { return providers.any { it.canShowFileHistory(paths, revisionNumber) } } override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) { providers.firstOrNull { it.canShowFileHistory(paths, revisionNumber) }?.showFileHistory(paths, revisionNumber) } } private class VcsLogDirectoryHistoryProvider(private val project: Project) : VcsLogFileHistoryProvider { override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean { if (!Registry.`is`("vcs.history.show.directory.history.in.log")) return false val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false return createPathsFilter(project, dataManager, paths) != null } override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) { val hash = revisionNumber?.let { HashImpl.build(it) } val root = VcsLogUtil.getActualRoot(project, paths.first())!! triggerFileHistoryUsage(project, paths, hash) val logManager = VcsProjectLog.getInstance(project).logManager!! val pathsFilter = createPathsFilter(project, logManager.dataManager, paths)!! val hashFilter = createHashFilter(hash, root) var ui = logManager.findLogUi(VcsLogTabLocation.TOOL_WINDOW, MainVcsLogUi::class.java, true) { logUi -> matches(logUi.filterUi.filters, pathsFilter, hashFilter) } val firstTime = ui == null if (firstTime) { val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter) ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true) } selectRowWhenOpen(logManager, hash, root, ui!!, firstTime) } companion object { private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? { val forRootFilter = mutableSetOf<VirtualFile>() val forPathsFilter = mutableListOf<FilePath>() for (path in paths) { val root = VcsLogUtil.getActualRoot(project, path) if (root == null) return null if (!dataManager.roots.contains(root) || !VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null val correctedPath = getCorrectedPath(project, path, root, false) if (!correctedPath.isDirectory) return null if (path.virtualFile == root) { forRootFilter.add(root) } else { forPathsFilter.add(correctedPath) } if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null } if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter) return VcsLogFilterObject.fromRoots(forRootFilter) } private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter { if (hash == null) { return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD) } return VcsLogFilterObject.fromCommit(CommitId(hash, root)) } private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean { if (!filters.matches(hashFilter.key, pathsFilter.key)) { return false } return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter } } } private class VcsLogSingleFileHistoryProvider(private val project: Project) : VcsLogFileHistoryProvider { private val tabGroupId: TabGroupId = TabGroupId("History", VcsBundle.messagePointer("file.history.tab.name"), false) override fun canShowFileHistory(paths: Collection<FilePath>, revisionNumber: String?): Boolean { if (!isNewHistoryEnabled() || paths.size != 1) return false val root = VcsLogUtil.getActualRoot(project, paths.single()) ?: return false val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null) if (correctedPath.isDirectory) return false val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false if (dataManager.logProviders[root]?.diffHandler == null) return false return dataManager.index.isIndexingEnabled(root) || Registry.`is`("vcs.force.new.history") } override fun showFileHistory(paths: Collection<FilePath>, revisionNumber: String?) { if (paths.size != 1) return val root = VcsLogUtil.getActualRoot(project, paths.first())!! val path = getCorrectedPath(project, paths.single(), root, revisionNumber != null) if (path.isDirectory) return val hash = revisionNumber?.let { HashImpl.build(it) } triggerFileHistoryUsage(project, paths, hash) val logManager = VcsProjectLog.getInstance(project).logManager!! var fileHistoryUi = logManager.findLogUi(VcsLogTabLocation.TOOL_WINDOW, FileHistoryUi::class.java, true) { ui -> ui.matches(path, hash) } val firstTime = fileHistoryUi == null if (firstTime) { val suffix = if (hash != null) " (" + hash.toShortString() + ")" else "" fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, tabGroupId, Function { path.name + suffix }, FileHistoryUiFactory(path, root, hash), true) } selectRowWhenOpen(logManager, hash, root, fileHistoryUi!!, firstTime) } } fun isNewHistoryEnabled() = Registry.`is`("vcs.new.history") private fun selectRowWhenOpen(logManager: VcsLogManager, hash: Hash?, root: VirtualFile, ui: VcsLogUiEx, firstTime: Boolean) { if (hash != null) { ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true) } else if (firstTime) { ui.jumpToRow(0, true, true) } } private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) { jumpTo(hash, { visiblePack: VisiblePack, h: Hash? -> if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo VcsLogUiEx.COMMIT_NOT_FOUND val commitIndex: Int = storage.getCommitIndex(h, root) var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex) if (rowIndex == null) { rowIndex = findVisibleAncestorRow(commitIndex, visiblePack) } rowIndex ?: VcsLogUiEx.COMMIT_DOES_NOT_MATCH }, SettableFuture.create(), silently, true) } private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile, isRevisionHistory: Boolean): FilePath { var correctedPath = path if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) { correctedPath = VcsUtil.getFilePath(correctedPath.path, false) } if (!isRevisionHistory) { return VcsUtil.getLastCommitPath(project, correctedPath) } return correctedPath } private fun triggerFileHistoryUsage(project: Project, paths: Collection<FilePath>, hash: Hash?) { val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file" VcsLogUsageTriggerCollector.triggerFileHistoryUsage(project, kind, hash != null) }
platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt
3950702437
package io.ktor.utils.io.js import io.ktor.utils.io.bits.* import io.ktor.utils.io.core.* import io.ktor.utils.io.core.internal.* import org.khronos.webgl.* import org.w3c.dom.* public fun WebSocket.sendPacket(packet: ByteReadPacket) { send(packet.readArrayBuffer()) } public inline fun WebSocket.sendPacket(block: BytePacketBuilder.() -> Unit) { sendPacket(buildPacket(block = block)) } public inline fun MessageEvent.packet(): ByteReadPacket { @Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE", "UnsafeCastFromDynamic") return ByteReadPacket( ChunkBuffer(Memory.of(data.asDynamic() as DataView), null, ChunkBuffer.NoPool), ChunkBuffer.NoPool ) }
ktor-io/js/src/io/ktor/utils/io/js/WebSockets.kt
1890073497
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.logging import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.util.* /** * Generates a string representing this [ApplicationRequest] suitable for logging */ public fun ApplicationRequest.toLogString(): String = "${httpMethod.value} - ${path()}" /** * Base interface for plugins that can setup MDC. See [CallLogging] plugin. */ public interface MDCProvider { /** * Executes [block] with [MDC] setup */ public suspend fun withMDCBlock(call: ApplicationCall, block: suspend () -> Unit) } private object EmptyMDCProvider : MDCProvider { override suspend fun withMDCBlock(call: ApplicationCall, block: suspend () -> Unit) = block() } /** * Returns first instance of a plugin that implements [MDCProvider] * or default implementation with an empty context */ public val Application.mdcProvider: MDCProvider @Suppress("UNCHECKED_CAST") get() = pluginRegistry.allKeys .firstNotNullOfOrNull { pluginRegistry.getOrNull(it as AttributeKey<Any>) as? MDCProvider } ?: EmptyMDCProvider
ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/logging/Logging.kt
1199624419
package `in`.testpress.testpress.util import `in`.testpress.testpress.models.UserDetails import `in`.testpress.testpress.util.fakes.FakeRegistrationFormEmptyInputValidation import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class RegistrationFormEmptyInputValidatorTest { @Test fun nonEmptyDataShouldReturnTrue() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "helen01", "[email protected]", "9876543210", "1234567", "1234567" )) Assert.assertTrue(registrationFormEmptyInputValidation.isValid()) } @Test fun emptyEmailShouldReturnFalse() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "helen01", "", "9876543210", "1234567", "1234567" )) Assert.assertEquals(false, registrationFormEmptyInputValidation.isValid()) } @Test fun emptyUserNameShouldReturnFalse() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "", "[email protected]", "9876543210", "1234567", "1234567" )) Assert.assertEquals(false, registrationFormEmptyInputValidation.isValid()) } @Test fun emptyPasswordShouldReturnTrue() { val registrationFormEmptyInputValidation = FakeRegistrationFormEmptyInputValidation(UserDetails( "helen01", "[email protected]", "9876543210", "", "" )) Assert.assertEquals(false, registrationFormEmptyInputValidation.isValid()) } }
app/src/test/java/in/testpress/testpress/util/RegistrationFormEmptyInputValidatorTest.kt
2172427114
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http.content import io.ktor.http.* import io.ktor.util.cio.* import io.ktor.utils.io.* import io.ktor.utils.io.jvm.javaio.* import java.net.* /** * Represents a content that is served from the specified [uri] * @property uri that is used as a source */ public class URIFileContent( public val uri: URI, override val contentType: ContentType = ContentType.defaultForFilePath(uri.path), override val contentLength: Long? = null, ) : OutgoingContent.ReadChannelContent() { public constructor(url: URL, contentType: ContentType = ContentType.defaultForFilePath(url.path)) : this( url.toURI(), contentType ) // TODO: use http client override fun readFrom(): ByteReadChannel = uri.toURL().openStream().toByteReadChannel(pool = KtorDefaultPool) }
ktor-http/jvm/src/io/ktor/http/content/URIFileContent.kt
2875906395
package lt.markmerkk.utils import com.nhaarman.mockitokotlin2.doNothing import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.whenever import lt.markmerkk.Config import lt.markmerkk.ConfigPathProvider import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations import java.util.Properties class AdvHashSettingsGetLongTest { @Mock lateinit var configPathProvider: ConfigPathProvider @Mock lateinit var configSetSettings: ConfigSetSettings private lateinit var config: Config @Before fun setUp() { MockitoAnnotations.initMocks(this) doNothing().whenever(configSetSettings).load() doNothing().whenever(configSetSettings).save() doReturn("/").whenever(configSetSettings) .currentConfig() config = Config( debug = false, appName = "wt4", appFlavor = "basic", versionName = "test_version", versionCode = 1, cpp = configPathProvider, configSetSettings = configSetSettings, gaKey = "test" ) } @Test fun stringOutput() { // Arrange val settings = AdvHashSettings(config) val outputProperties = Properties() outputProperties.put("valid_key", "dmFsaWRfdmFsdWU=") // Act settings.onLoad(outputProperties) val resultValue = settings.getLong(key = "valid_key", defaultValue = -1) // Assert assertThat(resultValue).isEqualTo(-1) } @Test fun validOutput() { // Arrange val settings = AdvHashSettings(config) val outputProperties = Properties() outputProperties.put("valid_key", "MTA=") // Act settings.onLoad(outputProperties) val resultValue = settings.getLong(key = "valid_key", defaultValue = -1) // Assert assertThat(resultValue).isEqualTo(10) } @Test fun validInput() { // Arrange val settings = AdvHashSettings(config) val properties = Properties() // Act settings.set("valid_key", 10.toString()) settings.onSave(properties) settings.save() // Assert assertThat(properties["valid_key"]).isEqualTo("MTA=") } }
components/src/test/java/lt/markmerkk/utils/AdvHashSettingsGetLongTest.kt
1990952687
package scripts.histogram import org.junit.Test import java.io.File import kotlin.test.assertTrue import scripts.base.TestBase class HistogramTest : TestBase() { @Test fun generateHistogram() { System.setProperty("kotlin.script.file", file("/kotlin/histogram.kt").path) val output = File.createTempFile("histogram", ".png") output.deleteOnExit() main(arrayOf("-input", file("/test/resources/histogram-sample.txt").path, "-label", "Response (s)", "-title", "Web Server Response Times", "-output", output.path)) assertTrue(output.exists()) } }
test/kotlin/histogram-test.kt
744357552
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.userprefs.multisampling import android.content.Context import org.koin.dsl.module.module private const val PARAM_VIEW = 0 fun provideModuleMultisampling() = module { /* * Parameter at index 0 must be a MultisamplingPreferenceView. */ factory { MultisamplingPreferencePresenter( get(), get(), get(), get(), it[PARAM_VIEW], get() ) } factory { MultisamplingPreferenceValueMapper(get<Context>().resources) } factory { WallpaperCheckerUseCase(get()) } }
app/src/main/java/com/doctoror/particleswallpaper/userprefs/multisampling/MultisamplingModuleProvider.kt
2446371016
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.framework.app.actions import android.app.Activity import android.content.Intent import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify class ActivityStartActivityForResultActionTest { private val activity: Activity = mock() private val underTest = ActivityStartActivityForResultAction(activity) @Test fun startsActivityForResult() { // Given val intent = Intent() val requestCode = 1 // When underTest.startActivityForResult(intent, requestCode) // Then verify(activity).startActivityForResult(intent, requestCode) } }
app/src/test/java/com/doctoror/particleswallpaper/framework/app/actions/ActivityStartActivityForResultActionTest.kt
4028074068
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.tests.community import com.intellij.ide.projectWizard.CommandLineProjectGuiTest import com.intellij.testGuiFramework.framework.FirstStartWith import com.intellij.testGuiFramework.framework.GuiTestSuite import com.intellij.testGuiFramework.framework.GuiTestSuiteRunner import com.intellij.testGuiFramework.framework.RunWithIde import com.intellij.testGuiFramework.launcher.ide.CommunityIde import com.intellij.testGuiFramework.launcher.ide.CommunityIdeFirstStart import com.intellij.testGuiFramework.tests.community.toolWindow.DockedModeGuiTest import org.junit.runner.RunWith import org.junit.runners.Suite @RunWith(GuiTestSuiteRunner::class) @RunWithIde(CommunityIde::class) @FirstStartWith(CommunityIdeFirstStart::class) @Suite.SuiteClasses(CommandLineProjectGuiTest::class, DockedModeGuiTest::class, SaveFilesOnFrameDeactivationGuiTest::class) class CommunityTestSuite : GuiTestSuite()
community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/CommunityTestSuite.kt
1161583021
/* * Copyright 2022 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.android.ground.model.job import com.google.android.ground.model.task.Task import com.google.android.ground.util.toImmutableList import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import java8.util.Optional data class Job @JvmOverloads constructor( val id: String, val name: String? = null, val tasks: ImmutableMap<String, Task> = ImmutableMap.of(), val type: Type = Type.AUTOMATIC, val status: Status = Status.NOT_STARTED ) { val tasksSorted: ImmutableList<Task> get() = tasks.values.sortedBy { it.id }.toImmutableList() fun getTask(id: String): Optional<Task> = Optional.ofNullable(tasks[id]) enum class Type { AUTOMATIC, MANUAL } enum class Status { NOT_STARTED, IN_PROGRESS, COMPLETE } }
ground/src/main/java/com/google/android/ground/model/job/Job.kt
2192000974
/* * ShortURL (https://github.com/delight-im/ShortURL) * Copyright (c) delight.im (https://www.delight.im/) * Licensed under the MIT License (https://opensource.org/licenses/MIT) */ /** * ShortURL: Bijective conversion between natural numbers (IDs) and short strings * * ShortURL.encode() takes an ID and turns it into a short string * ShortURL.decode() takes a short string and turns it into an ID * * Features: * + large alphabet (51 chars) and thus very short resulting strings * + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u') * + unambiguous (removed 'I', 'l', '1', 'O' and '0') * * Example output: * 123456789 <=> pgK8p */ object ShortURL { private val ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_" private val BASE = ALPHABET.length fun encode(num: Int): String { var number = num val stringBuilder = StringBuilder() while (number > 0) { stringBuilder.insert(0, ALPHABET[number % BASE]) number /= BASE } return stringBuilder.toString() } fun decode(string: String): Int { var number = 0 for (i in 0 until string.length) { number = number * BASE + ALPHABET.indexOf(string[i]) } return number } }
Kotlin/ShortURL.kt
2083598295
// 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.workspaceModel.storage.impl class WorkspaceStorageConsistencyCheckingModeProviderForTests : ConsistencyCheckingModeProvider { override val mode: ConsistencyCheckingMode get() = ConsistencyCheckingMode.SYNCHRONOUS }
platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/impl/WorkspaceStorageConsistencyCheckingModeProviderForTests.kt
74396983
package custom.scriptDefinition import java.io.File import kotlin.script.dependencies.* import kotlin.script.experimental.dependencies.* import kotlin.script.templates.ScriptTemplateDefinition import kotlin.script.experimental.location.ScriptExpectedLocation import kotlin.script.experimental.location.ScriptExpectedLocations var count = 0 class TestDependenciesResolver : DependenciesResolver { override fun resolve( scriptContents: ScriptContents, environment: Environment ): DependenciesResolver.ResolveResult { if (count == 0) { count++ return ScriptDependencies.Empty.asSuccess() } return ScriptDependencies(classpath = listOf(environment["lib-classes"] as File)).asSuccess() } } @ScriptExpectedLocations([ScriptExpectedLocation.Everywhere]) @ScriptTemplateDefinition(TestDependenciesResolver::class, scriptFilePattern = "script.kts") open class Template
plugins/kotlin/idea/tests/testData/script/definition/complex/errorResolver/template/template.kt
2923242135
// IS_APPLICABLE: false // WITH_STDLIB // ERROR: Unresolved reference: unresolved import java.util.Objects val v = <caret>Objects.unresolved()
plugins/kotlin/idea/tests/testData/intentions/importAllMembers/UnresolvedMember.kt
3943185291
// AFTER-WARNING: Parameter 'a' is never used fun <T> doSomething(a: T) {} fun foo() { if (true) doSomething("test") <caret>else doSomething("test2") }
plugins/kotlin/idea/tests/testData/intentions/addBraces/addBracesForElse.kt
747256357
// INTENTION_TEXT: "Replace with '5'" val x = <caret>2 + 3
plugins/kotlin/idea/tests/testData/intentions/evaluateCompileTimeExpression/int.kt
3845262444
/* * Copyright (c) 2019 VenomVendor. All rights reserved. * Created by VenomVendor on 18-Feb-2019. */ package com.venomvendor.tigerspike.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.RequestManager import com.venomvendor.sdk.core.model.gallery.Feed import com.venomvendor.tigerspike.R import com.venomvendor.tigerspike.ui.factory.OnItemClickListener import com.venomvendor.tigerspike.util.DiffUtilHelper /** * Recycler Adapter for displaying list of results. */ internal class GalleryListAdapter(glideManager: RequestManager) : ListAdapter<Feed, GalleryListAdapter.GalleryViewHolder>(DiffUtilHelper.FEED_DIFF) { // Image renderer private val glide = glideManager // Event listener private var itemClickListener: OnItemClickListener<Feed>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GalleryViewHolder { val view = LayoutInflater.from(parent.context) // Update item view .inflate(R.layout.gallery_item, parent, false) return GalleryViewHolder(view) } override fun onBindViewHolder(holder: GalleryViewHolder, position: Int) { // Get item val feed = getItem(position) // Update views holder.author.text = feed.author holder.published.text = feed.published.toString() // Load image glide.load(feed.media.medium) .centerCrop() // place holder until image loads .placeholder(R.drawable.ic_launcher_background) .into(holder.media) } fun setOnItemClickLister(listener: OnItemClickListener<Feed>?) { itemClickListener = listener } /** * View Holder pattern, used by recycler view. */ internal inner class GalleryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { internal val author: TextView = itemView.findViewById(R.id.author) internal val published: TextView = itemView.findViewById(R.id.desc) internal val media: ImageView = itemView.findViewById(R.id.media) init { // Add event listener itemView.setOnClickListener(this) } override fun onClick(view: View) { val selectedPos = adapterPosition if (selectedPos == RecyclerView.NO_POSITION) { return } // Pass on to root level event listener itemClickListener?.onClick(getItem(selectedPos), view, selectedPos) } } }
demo/src/main/java/com/venomvendor/tigerspike/ui/adapter/GalleryListAdapter.kt
780805058
package de.axelrindle.simplecoins.command import de.axelrindle.simplecoins.CoinManager import de.axelrindle.simplecoins.command.util.CoinCommand /** * Command for removing an amount of coins from a player's balance. */ internal class RemoveCommand : CoinCommand() { override val localizedName: String = "Remove" override fun getName(): String { return "remove" } override fun getUsage(): String { return "/simplecoins remove <player> <amount>" } override fun getPermission(): String { return "simplecoins.remove" } override fun manipulateBalance(uuid: String, amount: Double): Double { return CoinManager.removeCoins(uuid, amount) } override fun validateArguments(args: Array<out String>): Boolean { return args.size == 2 } }
src/main/kotlin/de/axelrindle/simplecoins/command/RemoveCommand.kt
3256326808
// 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.introduce import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.unifier.KotlinPsiRange import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.refactoring.selectElement import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.SmartList fun showErrorHint(project: Project, editor: Editor, @NlsContexts.DialogMessage message: String, @NlsContexts.DialogTitle title: String) { CodeInsightUtils.showErrorHint(project, editor, message, title, null) } fun showErrorHintByKey(project: Project, editor: Editor, messageKey: String, @NlsContexts.DialogTitle title: String) { showErrorHint(project, editor, KotlinBundle.message(messageKey), title) } fun selectElementsWithTargetSibling( @NlsContexts.DialogTitle operationName: String, editor: Editor, file: KtFile, @NlsContexts.DialogTitle title: String, elementKinds: Collection<CodeInsightUtils.ElementKind>, elementValidator: (List<PsiElement>) -> String?, getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>, continuation: (elements: List<PsiElement>, targetSibling: PsiElement) -> Unit ) { fun onSelectionComplete(elements: List<PsiElement>, targetContainer: PsiElement) { val physicalElements = elements.map { it.substringContextOrThis } val parent = PsiTreeUtil.findCommonParent(physicalElements) ?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}") if (parent == targetContainer) { continuation(elements, physicalElements.first()) return } val outermostParent = parent.getOutermostParentContainedIn(targetContainer) if (outermostParent == null) { showErrorHintByKey(file.project, editor, "cannot.refactor.no.container", operationName) return } continuation(elements, outermostParent) } selectElementsWithTargetParent(operationName, editor, file, title, elementKinds, elementValidator, getContainers, ::onSelectionComplete) } fun selectElementsWithTargetParent( @NlsContexts.DialogTitle operationName: String, editor: Editor, file: KtFile, @NlsContexts.DialogTitle title: String, elementKinds: Collection<CodeInsightUtils.ElementKind>, elementValidator: (List<PsiElement>) -> String?, getContainers: (elements: List<PsiElement>, commonParent: PsiElement) -> List<PsiElement>, continuation: (elements: List<PsiElement>, targetParent: PsiElement) -> Unit ) { fun showErrorHintByKey(key: String) { showErrorHintByKey(file.project, editor, key, operationName) } fun selectTargetContainer(elements: List<PsiElement>) { elementValidator(elements)?.let { showErrorHint(file.project, editor, it, operationName) return } val physicalElements = elements.map { it.substringContextOrThis } val parent = PsiTreeUtil.findCommonParent(physicalElements) ?: throw AssertionError("Should have at least one parent: ${physicalElements.joinToString("\n")}") val containers = getContainers(physicalElements, parent) if (containers.isEmpty()) { showErrorHintByKey("cannot.refactor.no.container") return } chooseContainerElementIfNecessary( containers, editor, title, true ) { continuation(elements, it) } } fun selectMultipleElements() { val startOffset = editor.selectionModel.selectionStart val endOffset = editor.selectionModel.selectionEnd val elements = elementKinds.flatMap { CodeInsightUtils.findElements(file, startOffset, endOffset, it).toList() } if (elements.isEmpty()) { return when (elementKinds.singleOrNull()) { CodeInsightUtils.ElementKind.EXPRESSION -> showErrorHintByKey("cannot.refactor.no.expression") CodeInsightUtils.ElementKind.TYPE_ELEMENT -> showErrorHintByKey("cannot.refactor.no.type") else -> showErrorHint( file.project, editor, KotlinBundle.message("text.refactoring.can.t.be.performed.on.the.selected.code.element"), title ) } } selectTargetContainer(elements) } fun selectSingleElement() { selectElement(editor, file, false, elementKinds) { expr -> if (expr != null) { selectTargetContainer(listOf(expr)) } else { if (!editor.selectionModel.hasSelection()) { if (elementKinds.singleOrNull() == CodeInsightUtils.ElementKind.EXPRESSION) { val elementAtCaret = file.findElementAt(editor.caretModel.offset) elementAtCaret?.getParentOfTypeAndBranch<KtProperty> { nameIdentifier }?.let { return@selectElement selectTargetContainer(listOf(it)) } } editor.selectionModel.selectLineAtCaret() } selectMultipleElements() } } } editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) selectSingleElement() } fun PsiElement.findExpressionByCopyableDataAndClearIt(key: Key<Boolean>): KtExpression? { val result = findDescendantOfType<KtExpression> { it.getCopyableUserData(key) != null } ?: return null result.putCopyableUserData(key, null) return result } fun PsiElement.findElementByCopyableDataAndClearIt(key: Key<Boolean>): PsiElement? { val result = findDescendantOfType<PsiElement> { it.getCopyableUserData(key) != null } ?: return null result.putCopyableUserData(key, null) return result } fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key<Boolean>): List<KtExpression> { val results = collectDescendantsOfType<KtExpression> { it.getCopyableUserData(key) != null } results.forEach { it.putCopyableUserData(key, null) } return results } fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? { val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType<KtStringTemplateEntry>() ?: return null if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null if (entry2.parent != stringTemplate) return null val templateOffset = stringTemplate.startOffset if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate val prefixOffset = startOffset - entry1.startOffset if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null val suffixOffset = endOffset - entry2.startOffset if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null val prefix = entry1.text.substring(0, prefixOffset) val suffix = entry2.text.substring(suffixOffset) return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression() } fun KotlinPsiRange.getPhysicalTextRange(): TextRange { return (elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.contentRange ?: textRange } fun ExtractableSubstringInfo.replaceWith(replacement: KtExpression): KtExpression { return with(this) { val psiFactory = KtPsiFactory(replacement) val parent = startEntry.parent psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) } val refEntry = psiFactory.createBlockStringTemplateEntry(replacement) val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) } parent.deleteChildRange(startEntry, endEntry) addedRefEntry.expression!! } } fun KtExpression.mustBeParenthesizedInInitializerPosition(): Boolean { if (this !is KtBinaryExpression) return false if (left?.mustBeParenthesizedInInitializerPosition() == true) return true return PsiChildRange(left, operationReference).any { (it is PsiWhiteSpace) && it.textContains('\n') } } fun isObjectOrNonInnerClass(e: PsiElement): Boolean = e is KtObjectDeclaration || (e is KtClass && !e.isInner()) fun <T : KtDeclaration> insertDeclaration(declaration: T, targetSibling: PsiElement): T { val targetParent = targetSibling.parent val anchorCandidates = SmartList<PsiElement>() anchorCandidates.add(targetSibling) if (targetSibling is KtEnumEntry) { anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry }) } val anchor = anchorCandidates.minByOrNull { it.startOffset }!!.parentsWithSelf.first { it.parent == targetParent } val targetContainer = anchor.parent!! @Suppress("UNCHECKED_CAST") return (targetContainer.addBefore(declaration, anchor) as T).apply { targetContainer.addBefore(KtPsiFactory(declaration).createWhiteSpace("\n\n"), anchor) } } internal fun validateExpressionElements(elements: List<PsiElement>): String? { if (elements.any { it is KtConstructor<*> || it is KtParameter || it is KtTypeAlias || it is KtPropertyAccessor }) { return KotlinBundle.message("text.refactoring.is.not.applicable.to.this.code.fragment") } return null }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt
1909739253
package pl.elpassion.elspace.common.extensions import com.elpassion.android.commons.recycler.basic.WithStableId import org.junit.Assert.* import org.junit.Test class ListUpdateTest { class MyType(override val id: Long) : WithStableId @Test fun shouldRemoveItemWhenIdMatched() { val oldItem = MyType(1) val list = mutableListOf(oldItem) list.update(MyType(1)) assertNotEquals(list[0], oldItem) } @Test fun shouldAddItemToCorrectPositionWhenIdMatched() { val list = mutableListOf(MyType(1)) val newItem = MyType(1) list.update(newItem) assertEquals(list[0], newItem) } @Test fun shouldHaveCorrectSizeWhenIdMatched() { val list = mutableListOf(MyType(1), MyType(2)) val newItem = MyType(1) list.update(newItem) assertEquals(list.size, 2) } @Test fun shouldNotUpdateItemsWhenIdNotMatched() { val one = MyType(1) val two = MyType(2) val list = mutableListOf(one, two) list.update(MyType(3)) assertEquals(list[0], one) assertEquals(list[1], two) } @Test fun shouldAddItemToEmptyList() { val list = mutableListOf<MyType>() val newItem = MyType(1) list.update(newItem) assertEquals(list[0], newItem) } @Test fun shouldAddItemWhenIdNotMatched() { val list = mutableListOf(MyType(1), MyType(2)) val newItem = MyType(3) list.update(newItem) assertEquals(list[2], newItem) } @Test fun shouldHaveCorrectSizeWhenIdNotMatched() { val list = mutableListOf(MyType(1), MyType(2)) val newItem = MyType(3) list.update(newItem) assertEquals(list.size, 3) } @Test fun shouldAddItemOnCorrectListIndex() { val list = mutableListOf(MyType(1), MyType(3)) val newItem = MyType(2) list.update(newItem) assertEquals(list[1], newItem) } @Test fun shouldHaveCorrectSizeWhenNewItemIdIsLower() { val list = mutableListOf(MyType(2), MyType(3)) list.update(MyType(1)) assertEquals(list.size, 3) } @Test fun shouldHaveCorrectOrderWhenNewItemIdIsLower() { val three = MyType(3) val six = MyType(6) val list = mutableListOf(three, six) val one = MyType(1) list.update(one) assertEquals(list[0], one) assertEquals(list[1], three) assertEquals(list[2], six) } @Test fun shouldNotReturnNullPosition() { val list = mutableListOf<MyType>() val position = list.update(MyType(1)) assertNotNull(position) } @Test fun shouldReturnCorrectPositionWhenListIsEmpty() { val list = mutableListOf<MyType>() val position = list.update(MyType(1)) assertEquals(position, 0) } @Test fun shouldReturnCorrectPositionWhenIdMatched() { val list = mutableListOf(MyType(1)) val position = list.update(MyType(1)) assertEquals(position, 0) } @Test fun shouldReturnCorrectPositionWhenIdNotMatched() { val list = mutableListOf(MyType(1)) val position = list.update(MyType(2)) assertEquals(position, 1) } @Test fun shouldReturnCorrectPositionWhenIdIsLowerAndNotMatched() { val list = mutableListOf(MyType(2)) val position = list.update(MyType(1)) assertEquals(position, 0) } }
el-debate/src/test/java/pl/elpassion/elspace/common/extensions/ListUpdateTest.kt
3020492774
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.features.bows import androidx.fragment.app.Fragment import de.dreier.mytargets.base.activities.SimpleFragmentActivityBase class EditBowActivity : SimpleFragmentActivityBase() { override fun instantiateFragment(): Fragment { return EditBowFragment() } }
app/src/main/java/de/dreier/mytargets/features/bows/EditBowActivity.kt
2071138082
// snippet-sourcedescription:[ListAlgorithms.kt demonstrates how to list algorithms.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon SageMaker] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.sage // snippet-start:[sagemaker.kotlin.list_algs.import] import aws.sdk.kotlin.services.sagemaker.SageMakerClient import aws.sdk.kotlin.services.sagemaker.model.ListAlgorithmsRequest // snippet-end:[sagemaker.kotlin.list_algs.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { listAlgs() } // snippet-start:[sagemaker.kotlin.list_algs.main] suspend fun listAlgs() { SageMakerClient { region = "us-west-2" }.use { sageMakerClient -> val response = sageMakerClient.listAlgorithms(ListAlgorithmsRequest {}) response.algorithmSummaryList?.forEach { item -> println("Algorithm name is ${item.algorithmName}") } } } // snippet-end:[sagemaker.kotlin.list_algs.main]
kotlin/services/sagemaker/src/main/kotlin/com/kotlin/sage/ListAlgorithms.kt
3198975011
package com.github.spoptchev.kotlin.preconditions import org.junit.Test import kotlin.test.assertEquals import kotlin.test.fail class AssertionTest { private val boolMatcher = object : Matcher<Boolean>() { override fun test(condition: Condition<Boolean>): Result = Result(condition.value) { "message" } } @Test fun `test run with valid result`() { val assertion = Assertion(true, "value", ::require) val result = assertion.run(boolMatcher) assertEquals(true, result) } @Test(expected = IllegalArgumentException::class) fun `test run with invalid result`() { val assertion = Assertion(false, "value", ::require) assertion.run(boolMatcher) fail("should not be executed") } }
src/test/kotlin/com/github/spoptchev/kotlin/preconditions/AssertionTest.kt
2439325699
/* * 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 androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import kotlinx.coroutines.flow.Flow /** * Defines [SleepSegmentEventEntity] database operations. */ @Dao interface SleepSegmentEventDao { @Query("SELECT * FROM sleep_segment_events_table ORDER BY start_time_millis DESC") fun getAll(): Flow<List<SleepSegmentEventEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(sleepSegmentEventEntity: SleepSegmentEventEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(sleepSegmentEventEntities: List<SleepSegmentEventEntity>) @Delete suspend fun delete(sleepSegmentEventEntity: SleepSegmentEventEntity) @Query("DELETE FROM sleep_segment_events_table") suspend fun deleteAll() }
SleepSampleKotlin/app/src/main/java/com/android/example/sleepsamplekotlin/data/db/SleepSegmentEventDao.kt
3642672137
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val EXT_filter_cubic = "EXTFilterCubic".nativeClassVK("EXT_filter_cubic", type = "device", postfix = "EXT") { documentation = """ {@code VK_EXT_filter_cubic} extends {@code VK_IMG_filter_cubic}. It documents cubic filtering of other image view types. It adds new structures that <b>can</b> be added to the {@code pNext} chain of ##VkPhysicalDeviceImageFormatInfo2 and ##VkImageFormatProperties2 that <b>can</b> be used to determine which image types and which image view types support cubic filtering. <h5>VK_EXT_filter_cubic</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_EXT_filter_cubic}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>171</dd> <dt><b>Revision</b></dt> <dd>3</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Bill Licea-Kane <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_filter_cubic]%20@wwlk%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_filter_cubic%20extension%3E%3E">wwlk</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2019-12-13</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Bill Licea-Kane, Qualcomm Technologies, Inc.</li> <li>Andrew Garrard, Samsung</li> <li>Daniel Koch, NVIDIA</li> <li>Donald Scorgie, Imagination Technologies</li> <li>Graeme Leese, Broadcom</li> <li>Jan-Herald Fredericksen, ARM</li> <li>Jeff Leger, Qualcomm Technologies, Inc.</li> <li>Tobias Hector, AMD</li> <li>Tom Olson, ARM</li> <li>Stuart Smith, Imagination Technologies</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "EXT_FILTER_CUBIC_SPEC_VERSION".."3" ) StringConstant( "The extension name.", "EXT_FILTER_CUBIC_EXTENSION_NAME".."VK_EXT_filter_cubic" ) EnumConstant( "Extends {@code VkFilter}.", "FILTER_CUBIC_EXT".."1000015000" ) EnumConstant( "Extends {@code VkFormatFeatureFlagBits}.", "FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT".enum(0x00002000) ) EnumConstant( "Extends {@code VkStructureType}.", "STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_IMAGE_FORMAT_INFO_EXT".."1000170000", "STRUCTURE_TYPE_FILTER_CUBIC_IMAGE_VIEW_IMAGE_FORMAT_PROPERTIES_EXT".."1000170001" ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_filter_cubic.kt
2878974192
package net.pagejects.core.error import java.net.URL /** * Thrown when element is not specified in the selectors file * * @author [Andrey Paslavsky](mailto:[email protected]) * @since 0.1 */ class CantFindSelectorOfElementException(page: String, element: String) : PagejectsException( URL("https://github.com/Pagejects/pagejects-core/wiki/Selectors-file"), "Element (page name \"$page\", element name \"$element\") is not specified in the selectors file")
src/main/kotlin/net/pagejects/core/error/CantFindSelectorOfElementException.kt
3718114053
package com.edreams.android.workshops.kotlin.injection.data import com.edreams.android.workshops.kotlin.data.venues.remote.ExploreVenuesController import com.edreams.android.workshops.kotlin.data.venues.remote.ExploreVenuesNetController import dagger.Binds import dagger.Module import javax.inject.Singleton @Module abstract class ControllerModule { @Singleton @Binds abstract fun bindExploreVenuesController( exploreVenuesNetController: ExploreVenuesNetController): ExploreVenuesController }
injection/src/main/java/com/edreams/android/workshops/kotlin/injection/data/ControllerModule.kt
1530306768
/* * Copyright 2017, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.zanata.security import org.zanata.security.annotations.SAML import javax.enterprise.context.ApplicationScoped import javax.enterprise.inject.Produces import javax.inject.Inject import javax.inject.Named @ApplicationScoped class AuthenticationConfig @Inject constructor(private val authTypes: Set<AuthenticationType>) { @Produces @Named("saml2Enabled") @SAML fun isSaml2Enabled() = authTypes.contains(AuthenticationType.SAML2) }
server/services/src/main/java/org/zanata/security/AuthenticationConfig.kt
3274015499
package net.pagejects.core.click import com.codeborne.selenide.SelenideElement import net.pagejects.core.UserAction import net.pagejects.core.annotation.Click import net.pagejects.core.impl.wait import net.pagejects.core.service.PageObjectService import net.pagejects.core.service.PageObjectServiceAware import net.pagejects.core.service.SelenideElementService import net.pagejects.core.service.SelenideElementServiceAware /** * Implementation of the [UserAction] for @[Click] * * @author Andrey Paslavsky * @since 0.1 */ class ClickUserAction( private val pageObjectName: String, private val clickAnnotation: Click, private val returnType: Class<*>? = null ) : UserAction<Any?>, SelenideElementServiceAware, PageObjectServiceAware { private lateinit var selenideElementService: SelenideElementService private lateinit var pageObjectService: PageObjectService override fun aware(service: PageObjectService) { pageObjectService = service } override fun aware(service: SelenideElementService) { selenideElementService = service } override fun perform(params: Array<out Any>?): Any? { val selenideElement = selenideElementService.get(pageObjectName, clickAnnotation.elementName) selenideElement.waitBeforeClick() when (clickAnnotation.type) { Click.ClickType.CLICK -> selenideElement.click() Click.ClickType.DOUBLE_CLICK -> selenideElement.doubleClick() Click.ClickType.CONTEXT_CLICK -> selenideElement.contextClick() } selenideElement.waitAfterClick() return if (returnType == null) Unit else pageObjectService.pageObject(returnType) } fun SelenideElement.waitBeforeClick() { this.wait(clickAnnotation.waiteBefore) } fun SelenideElement.waitAfterClick() { this.wait(clickAnnotation.waiteAfter) } }
src/main/kotlin/net/pagejects/core/click/ClickUserAction.kt
1172807405
package top.zbeboy.isy.service.system import top.zbeboy.isy.domain.tables.pojos.Users /** * Created by zbeboy 2017-11-11 . **/ interface MailService { /** * 发送邮件 * * @param to 接收方 * @param subject 标题 * @param content 内容 * @param isMultipart 多段 * @param isHtml 是html? */ fun sendEmail(to: String, subject: String, content: String, isMultipart: Boolean, isHtml: Boolean) /** * 发送激活邮件 * * @param users 用户 * @param baseUrl 服务路径 */ fun sendActivationEmail(users: Users, baseUrl: String) /** * 发送账号创建成功邮件 * * @param users 用户 * @param baseUrl 服务路径 */ fun sendCreationEmail(users: Users, baseUrl: String) /** * 发送密码重置邮件 * * @param users 用户 * @param baseUrl 服务路径 */ fun sendPasswordResetMail(users: Users, baseUrl: String) /** * 发送邮箱验证邮件 * * @param users 用户 * @param baseUrl 服务路径 */ fun sendValidEmailMail(users: Users, baseUrl: String) /** * 发送通知邮件 * * @param users 用户 * @param baseUrl 服务路径 * @param notify 通知内容 */ fun sendNotifyMail(users: Users, baseUrl: String, notify: String) /** * 使用内置方式发送 * * @param to 接收方 * @param subject 标题 * @param content 内容 * @param isMultipart 多段 * @param isHtml 是html? */ fun sendDefaultMail(to: String, subject: String, content: String, isMultipart: Boolean, isHtml: Boolean) /** * 阿里云邮箱服务 * * @param userMail 用户邮箱 * @param subject 标题 * @param content 内容 */ fun sendAliDMMail(userMail: String, subject: String, content: String) /** * sendCloud邮箱服务 * * @param userMail 用户邮箱 * @param subject 标题 * @param content 内容 */ fun sendCloudMail(userMail: String, subject: String, content: String) }
src/main/java/top/zbeboy/isy/service/system/MailService.kt
1165940135
package com.user.invoicemanagement.view.adapter import android.support.v7.widget.RecyclerView import android.view.View import com.user.invoicemanagement.model.data.WeightEnum import com.user.invoicemanagement.model.dto.Product import com.user.invoicemanagement.model.dto.ProductFactory import com.user.invoicemanagement.other.Constant import com.user.invoicemanagement.view.adapter.holder.MainFooterViewHolder import com.user.invoicemanagement.view.adapter.holder.MainHeaderViewHolder import com.user.invoicemanagement.view.adapter.holder.MainViewHolder import com.user.invoicemanagement.view.interfaces.MainView import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters import io.github.luizgrp.sectionedrecyclerviewadapter.StatelessSection class MainSection(sectionParameters: SectionParameters, private val factory: ProductFactory, var list: List<Product>, private val mainView: MainView) : StatelessSection(sectionParameters) { private var footerHolder: MainFooterViewHolder? = null private var holders = mutableListOf<MainViewHolder>() override fun getContentItemsTotal(): Int = list.size override fun getItemViewHolder(view: View): RecyclerView.ViewHolder = MainViewHolder(view) override fun onBindItemViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { val itemHolder = holder as MainViewHolder val product = list[position] holders.add(itemHolder) itemHolder.product = product itemHolder.setListener(View.OnLongClickListener { if (itemHolder.product != null) { mainView.deleteProduct(itemHolder.product!!) } true }) itemHolder.edtName.setText(product.name) itemHolder.btnWeightOnStore.text = product.weightOnStore.toString() itemHolder.btnWeightInFridge.text = product.weightInFridge.toString() itemHolder.btnWeightInStorage.text = product.weightInStorage.toString() itemHolder.btnWeight4.text = product.weight4.toString() itemHolder.btnWeight5.text = product.weight5.toString() itemHolder.edtWeightOnStore.setText(product.weightOnStore.toString()) itemHolder.edtWeightInFridge.setText(product.weightInFridge.toString()) itemHolder.edtWeightInStorage.setText(product.weightInStorage.toString()) itemHolder.edtWeight4.setText(product.weight4.toString()) itemHolder.edtWeight5.setText(product.weight5.toString()) if (product.purchasePrice != 0f) { itemHolder.edtPurchasePrice.setText(product.purchasePrice.toString()) } if (product.sellingPrice != 0f) { itemHolder.edtSellingPrice.setText(product.sellingPrice.toString()) } itemHolder.tvPurchasePriceSummary.text = Constant.priceFormat.format(product.purchasePriceSummary) itemHolder.tvSellingPriceSummary.text = Constant.priceFormat.format(product.sellingPriceSummary) itemHolder.btnWeightOnStore.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeightOnStore, product, WeightEnum.WEIGHT_1) } itemHolder.btnWeightInFridge.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeightInFridge, product, WeightEnum.WEIGHT_2) } itemHolder.btnWeightInStorage.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeightInStorage, product, WeightEnum.WEIGHT_3) } itemHolder.btnWeight4.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeight4, product, WeightEnum.WEIGHT_4) } itemHolder.btnWeight5.setOnClickListener { mainView.showSetWeightDialog(itemHolder.btnWeight5, product, WeightEnum.WEIGHT_5) } } override fun getHeaderViewHolder(view: View): RecyclerView.ViewHolder = MainHeaderViewHolder(view) override fun onBindHeaderViewHolder(holder: RecyclerView.ViewHolder?) { val itemHolder = holder as MainHeaderViewHolder itemHolder.tvHeader.text = factory.name itemHolder.btnAddProduct.setOnClickListener { mainView.saveAll() mainView.addNewProduct(factory.id) } itemHolder.btnEditName.setOnClickListener { mainView.saveAll() mainView.showEditFactoryDialog(factory) } itemHolder.btnDelete.setOnClickListener { mainView.saveAll() mainView.deleteFactory(factory.id) } } override fun getFooterViewHolder(view: View): RecyclerView.ViewHolder = MainFooterViewHolder(view) override fun onBindFooterViewHolder(holder: RecyclerView.ViewHolder?) { val itemHolder = holder as MainFooterViewHolder footerHolder = itemHolder setFooterData() itemHolder.btnAddNew.setOnClickListener { mainView.saveAll() mainView.addNewProduct(factory.id) } } fun getViewData(): List<Product> { val products = mutableListOf<Product>() for (item in holders) { if (item.product != null) { try { item.product!!.name = item.edtName.text.toString() item.product!!.weightOnStore = prepareString(item.btnWeightOnStore.text.toString()).toFloatOrNull() ?: 0f item.product!!.weightInFridge = prepareString(item.btnWeightInFridge.text.toString()).toFloatOrNull() ?: 0f item.product!!.weightInStorage = prepareString(item.btnWeightInStorage.text.toString()).toFloatOrNull() ?: 0f item.product!!.weight4 = prepareString(item.btnWeight4.text.toString()).toFloatOrNull() ?: 0f item.product!!.weight5 = prepareString(item.btnWeight5.text.toString()).toFloatOrNull() ?: 0f item.product!!.purchasePrice = prepareString(item.edtPurchasePrice.text.toString()).toFloatOrNull() ?: 0f item.product!!.sellingPrice = prepareString(item.edtSellingPrice.text.toString()).toFloatOrNull() ?: 0f } catch (e: Exception) { continue } products.add(item.product!!) } } return products } fun updateSummaryData() { for (item in holders) { if (item.product != null) { item.tvPurchasePriceSummary.text = Constant.priceFormat.format(item.product!!.purchasePriceSummary) item.tvSellingPriceSummary.text = Constant.priceFormat.format(item.product!!.sellingPriceSummary) setFooterData() } } } private fun setFooterData() { if (footerHolder == null) { return } var purchaseSummary = 0f var sellingSummary = 0f list.forEach { product: Product -> purchaseSummary += product.purchasePriceSummary sellingSummary += product.sellingPriceSummary } footerHolder?.mainFooterPurchaseSummary?.text = Constant.priceFormat.format(purchaseSummary) footerHolder?.mainFooterSellingSummary?.text = Constant.priceFormat.format(sellingSummary) } private fun prepareString(string: String): String { return string .replace(',', '.') .replace(Constant.whiteSpaceRegex, "") } }
app/src/main/java/com/user/invoicemanagement/view/adapter/MainSection.kt
4191103191
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diff.comparison import com.intellij.diff.DiffTestCase import com.intellij.diff.util.IntPair import com.intellij.diff.util.MergeRange import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.util.Couple import com.intellij.util.containers.ContainerUtil import java.util.* abstract class ComparisonMergeUtilTestBase : DiffTestCase() { private fun doCharTest(texts: Trio<Document>, expected: List<Change>?, matchings: Trio<BitSet>?) { val iterable1 = ByChar.compare(texts.data2.charsSequence, texts.data1.charsSequence, INDICATOR) val iterable2 = ByChar.compare(texts.data2.charsSequence, texts.data3.charsSequence, INDICATOR) val fragments = ComparisonMergeUtil.buildFair(iterable1, iterable2, INDICATOR) val actual = convertDiffFragments(fragments) checkConsistency(actual, texts) if (matchings != null) checkDiffMatching(actual, matchings) if (expected != null) checkDiffChanges(actual, expected) } private fun checkConsistency(actual: List<Change>, texts: Trio<Document>) { var lasts = Trio(-1, -1, -1) for (change in actual) { val starts = change.starts val ends = change.ends var empty = true var squashed = true ThreeSide.values.forEach { val start = starts(it) val end = ends(it) val last = lasts(it) assertTrue(last <= start) assertTrue(start <= end) empty = empty && (start == end) squashed = squashed && (start == last) } assertTrue(!empty) assertTrue(!squashed) lasts = ends } } private fun checkDiffChanges(actual: List<Change>, expected: List<Change>) { assertOrderedEquals(expected, actual) } private fun checkDiffMatching(changes: List<Change>, matchings: Trio<BitSet>) { val sets = Trio(BitSet(), BitSet(), BitSet()) for (change in changes) { sets.forEach({ set: BitSet, side: ThreeSide -> set.set(change.start(side), change.end(side)) }) } assertEquals(matchings.data1, sets.data1) assertEquals(matchings.data2, sets.data2) assertEquals(matchings.data3, sets.data3) } private fun convertDiffFragments(fragments: List<MergeRange>): List<Change> { return fragments.map { Change( it.start1, it.end1, it.start2, it.end2, it.start3, it.end3) } } private enum class TestType { CHAR } inner class MergeTestBuilder(val type: TestType) { private var isExecuted: Boolean = false private var texts: Trio<Document>? = null private var changes: List<Change>? = null private var matching: Trio<BitSet>? = null fun assertExecuted() { assertTrue(isExecuted) } fun test() { isExecuted = true assertTrue(changes != null || matching != null) when (type) { TestType.CHAR -> doCharTest(texts!!, changes, matching) } } operator fun String.minus(v: String): Couple<String> { return Couple(this, v) } operator fun Couple<String>.minus(v: String): Helper { return Helper(Trio(this.first, this.second, v)) } inner class Helper(val texts: Trio<String>) { init { val builder = this@MergeTestBuilder if (builder.texts == null) { builder.texts = texts.map { it -> DocumentImpl(it) } } } fun matching() { matching = texts.map { it -> parseMatching(it) } } } fun changes(vararg expected: Change): Unit { changes = ContainerUtil.list(*expected) } fun mod(line1: Int, line2: Int, line3: Int, count1: Int, count2: Int, count3: Int): Change { return Change(line1, line1 + count1, line2, line2 + count2, line3, line3 + count3) } } fun chars(f: MergeTestBuilder.() -> Unit) { doTest(TestType.CHAR, f) } private fun doTest(type: TestType, f: MergeTestBuilder.() -> Unit) { val builder = MergeTestBuilder(type) builder.f() builder.assertExecuted() } class Change(start1: Int, end1: Int, start2: Int, end2: Int, start3: Int, end3: Int) : Trio<IntPair>(IntPair(start1, end1), IntPair(start2, end2), IntPair(start3, end3)) { val start1 = start(ThreeSide.LEFT) val start2 = start(ThreeSide.BASE) val start3 = start(ThreeSide.RIGHT) val end1 = end(ThreeSide.LEFT) val end2 = end(ThreeSide.BASE) val end3 = end(ThreeSide.RIGHT) val starts = Trio(start1, start2, start3) val ends = Trio(end1, end2, end3) fun start(side: ThreeSide): Int = this(side).val1 fun end(side: ThreeSide): Int = this(side).val2 override fun toString(): String { return "($start1, $end1) - ($start2, $end2) - ($start3, $end3)" } } }
platform/diff-impl/tests/com/intellij/diff/comparison/ComparisonMergeUtilTestBase.kt
1970173292
/* * Copyright 2014 Cazcade Limited (http://cazcade.com) * * 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 kontrol.webserver import org.apache.commons.io.IOUtils import java.io.* import java.text.SimpleDateFormat import java.util.* /* * Copyright 2014 Cazcade Limited (http://cazcade.com) * * 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. */ /** * HTTP response. Return one of these from serve(). */ public open class Response(var status: Status = Status.OK, var mimeType: String = "text/html", text: String? = null, var data: InputStream? = if (text != null) ByteArrayInputStream(text.getBytes("UTF-8")) else null) { /** * Headers for the HTTP response. Use addHeader() to add lines. */ var header: MutableMap<String, String> = HashMap<String, String>() /** * The request method that spawned this response. */ var requestMethod: Method? = null /** * Use chunkedTransfer */ var chunkedTransfer: Boolean = false /** * Adds given line to the header. */ public open fun addHeader(name: String, value: String): Unit { header.put(name, value) } /** * Sends given response to the socket. */ open fun send(outputStream: OutputStream): Unit { val mime = mimeType val gmtFrmt = SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US) gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")) try { val pw = PrintWriter(outputStream) pw.print("HTTP/1.1 " + status.getFullDescription() + " \r\n") pw.print("Content-Type: " + mime + "\r\n") if ( header.get("Date") == null) { pw.print("Date: " + gmtFrmt.format(Date()) + "\r\n") } for (key in header.keySet()!!) { val value = header.get(key) pw.print(key + ": " + value + "\r\n") } pw.print("Connection: keep-alive\r\n") if (requestMethod != Method.HEAD && chunkedTransfer) { sendAsChunked(outputStream, pw) } else { sendAsFixedLength(outputStream, pw) } outputStream.flush() IOUtils.closeQuietly(data) } catch (ioe: IOException) { // Couldn't write? No can do. } } private fun sendAsChunked(outputStream: OutputStream, pw: PrintWriter): Unit { pw.print("Transfer-Encoding: chunked\r\n") pw.print("\r\n") pw.flush() val BUFFER_SIZE = 16 * 1024 val CRLF = "\r\n".getBytes() val buff = ByteArray(BUFFER_SIZE) while ( true) { val read = data?.read(buff)!! if (read < 0) { break } outputStream.write("%x\r\n".format(read).getBytes()) outputStream.write(buff, 0, read) outputStream.write(CRLF) } outputStream.write(("0\r\n\r\n".format().getBytes())) } private fun sendAsFixedLength(outputStream: OutputStream, pw: PrintWriter): Unit { var pending: Int = (if (data != null) data?.available()?:-1 else 0) pw.print("Content-Length: " + pending + "\r\n") pw.print("\r\n") pw.flush() if (requestMethod != Method.HEAD && data != null) { val BUFFER_SIZE = 16 * 1024 val buff = ByteArray(BUFFER_SIZE) while (pending > 0) { val read = data?.read(buff, 0, ((if ((pending > BUFFER_SIZE)) BUFFER_SIZE else pending)))!! if (read <= 0) { break } outputStream.write(buff, 0, read) pending -= read } } } }
webserver/src/main/kotlin/kontrol/webserver/Response.kt
652169360
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.diff.statistics import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings import com.intellij.diff.tools.external.ExternalDiffSettings import com.intellij.diff.tools.fragmented.UnifiedDiffTool import com.intellij.diff.tools.simple.SimpleDiffTool import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings import com.intellij.diff.util.DiffPlaces import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.utils.getBooleanUsage import com.intellij.internal.statistic.utils.getEnumUsage import java.util.* class DiffUsagesCollector : ApplicationUsagesCollector() { override fun getGroupId(): String { return "vcs.diff" } override fun getUsages(): MutableSet<UsageDescriptor> { val usages = HashSet<UsageDescriptor>() val places = listOf(DiffPlaces.DEFAULT, DiffPlaces.CHANGES_VIEW, DiffPlaces.VCS_LOG_VIEW, DiffPlaces.COMMIT_DIALOG, DiffPlaces.MERGE, DiffPlaces.TESTS_FAILED_ASSERTIONS) for (place in places) { val diffSettings = DiffSettings.getSettings(place) val textSettings = TextDiffSettings.getSettings(place) usages.add(getEnumUsage("ignore.policy.$place", textSettings.ignorePolicy)) usages.add(getEnumUsage("highlight.policy.$place", textSettings.highlightPolicy)) usages.add(getEnumUsage("show.warnings.policy.$place", textSettings.highlightingLevel)) usages.add(getBooleanUsage("collapse.unchanged.$place", !textSettings.isExpandByDefault)) usages.add(getBooleanUsage("show.line.numbers.$place", textSettings.isShowLineNumbers)) usages.add(getBooleanUsage("use.soft.wraps.$place", textSettings.isUseSoftWraps)) usages.add(getBooleanUsage("use.unified.diff.$place", isUnifiedToolDefault(diffSettings))) if (place == DiffPlaces.COMMIT_DIALOG) { usages.add(getBooleanUsage("enable.read.lock.$place", textSettings.isReadOnlyLock)) } } val diffSettings = DiffSettings.getSettings(null) usages.add(getBooleanUsage("iterate.next.file", diffSettings.isGoToNextFileOnNextDifference)) val externalSettings = ExternalDiffSettings.getInstance() usages.add(getBooleanUsage("external.diff", externalSettings.isDiffEnabled)) usages.add(getBooleanUsage("external.diff.default", externalSettings.isDiffEnabled && externalSettings.isDiffDefault)) usages.add(getBooleanUsage("external.merge", externalSettings.isMergeEnabled)) return usages } private fun isUnifiedToolDefault(settings: DiffSettings): Boolean { val toolOrder = settings.diffToolsOrder val defaultToolIndex = toolOrder.indexOf(SimpleDiffTool::class.java.canonicalName) val unifiedToolIndex = toolOrder.indexOf(UnifiedDiffTool::class.java.canonicalName) if (unifiedToolIndex == -1) return false return defaultToolIndex == -1 || unifiedToolIndex < defaultToolIndex } }
platform/diff-impl/src/com/intellij/diff/statistics/DiffUsagesCollector.kt
463852975
package io.georocket.util import java.util.Locale import java.text.DecimalFormat import java.text.DecimalFormatSymbols import kotlin.math.log10 import kotlin.math.pow /** * Convert data sizes to human-readable strings. Used by all commands that * output sizes, so the output always looks the same. * * Code has been adapted from * [https://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc](https://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc) * and corrected in a way that it displays correct SI units. * @author Michel Kraemer */ object SizeFormat { private val UNITS = arrayOf( "B", "kB", "MB", "GB", "TB", "PB", "EB" ) private val FORMATTER = DecimalFormat( "#,##0.#", DecimalFormatSymbols.getInstance(Locale.ENGLISH) ) /** * Convert the given data size to a human-readable string * @param size the data size * @return the human-readable string */ fun format(size: Long): String { if (size <= 0) { return "0 B" } val d = (log10(size.toDouble()) / 3).toInt() return FORMATTER.format(size / 1000.0.pow(d.toDouble())) + " " + UNITS[d] } }
src/main/kotlin/io/georocket/util/SizeFormat.kt
426714234
package com.company.commonbusiness.http.rx import com.company.commonbusiness.http.ExceptionHandle import com.orhanobut.logger.Logger import io.reactivex.disposables.Disposable import io.reactivex.observers.DisposableObserver /** * @author 李昭鸿 * @desc: 观察者基类,统一处理数据及异常 * @date Created on 2017/7/28 11:31 */ abstract class BaseObserver<T> : DisposableObserver<T>() { private var disposable: Disposable? = null override fun onNext(data: T) { Logger.d("BaseObserver onNext: " + data.toString()) onSuccess(data) } override fun onComplete() { Logger.d("BaseObserver onComplete") } override fun onError(e: Throwable) { Logger.d("BaseObserver onError") onFailure(ExceptionHandle.handleException(e).msg ?: "未知错误") } abstract fun onSuccess(data: T) abstract fun onFailure(errorMsg: String) }
CommonBusiness/src/main/java/com/company/commonbusiness/http/rx/BaseObserver.kt
2469515052
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.intentions import com.demonwav.mcdev.translations.TranslationFiles import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.util.IncorrectOperationException class RemoveUnmatchedEntryIntention : PsiElementBaseIntentionAction() { override fun getText() = "Remove translation" override fun isAvailable(project: Project, editor: Editor, element: PsiElement) = true override fun getFamilyName() = "Minecraft" @Throws(IncorrectOperationException::class) override fun invoke(project: Project, editor: Editor, element: PsiElement) { TranslationFiles.remove(TranslationFiles.seekTranslation(element) ?: return) } }
src/main/kotlin/com/demonwav/mcdev/translations/intentions/RemoveUnmatchedEntryIntention.kt
378625647
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.j2k.ast import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.append abstract class Statement : Element() { object Empty : Statement() { override fun generateCode(builder: CodeBuilder) { } override val isEmpty: Boolean get() = true } } class DeclarationStatement(val elements: List<Element>) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append(elements, "\n") } } class ExpressionListStatement(val expressions: List<Expression>) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append(expressions, "\n") } } class LabeledStatement(val name: Identifier, val statement: Element) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append name append "@" append " " append statement } } class ReturnStatement(val expression: Expression, val label: Identifier? = null) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append "return" if (label != null) { builder append "@" append label } builder append " " append expression } } class IfStatement( val condition: Expression, val thenStatement: Element, val elseStatement: Element, singleLine: Boolean ) : Expression() { private val br = if (singleLine) " " else "\n" private val brAfterElse = if (singleLine || elseStatement is IfStatement) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "if (" append condition append ")" append br append thenStatement.wrapToBlockIfRequired() if (!elseStatement.isEmpty) { builder append br append "else" append brAfterElse append elseStatement.wrapToBlockIfRequired() } else if (thenStatement.isEmpty) { builder append ";" } } } // Loops -------------------------------------------------------------------------------------------------- class WhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() { private val br = if (singleLine) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "while (" append condition append ")" append br append body.wrapToBlockIfRequired() if (body.isEmpty) { builder append ";" } } } class DoWhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() { private val br = if (singleLine) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "do" append br append body.wrapToBlockIfRequired() append br append "while (" append condition append ")" } } class ForeachStatement( val variableName: Identifier, val explicitVariableType: Type?, val collection: Expression, val body: Element, singleLine: Boolean ) : Statement() { private val br = if (singleLine) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "for (" append variableName if (explicitVariableType != null) { builder append ":" append explicitVariableType } builder append " in " append collection append ")" append br append body.wrapToBlockIfRequired() if (body.isEmpty) { builder append ";" } } } class BreakStatement(val label: Identifier = Identifier.Empty) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("break").appendWithPrefix(label, "@") } } class ContinueStatement(val label: Identifier = Identifier.Empty) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("continue").appendWithPrefix(label, "@") } } // Exceptions ---------------------------------------------------------------------------------------------- class TryStatement(val block: Block, val catches: List<CatchStatement>, val finallyBlock: Block) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("try\n").append(block).append("\n").append(catches, "\n").append("\n") if (!finallyBlock.isEmpty) { builder append "finally\n" append finallyBlock } } } class ThrowStatement(val expression: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder append "throw " append expression } } class CatchStatement(val variable: FunctionParameter, val block: Block) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append "catch (" append variable append ") " append block } } // when -------------------------------------------------------------------------------------------------- class WhenStatement(val subject: Expression, val caseContainers: List<WhenEntry>) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("when (").append(subject).append(") {\n").append(caseContainers, "\n").append("\n}") } } class WhenEntry(val selectors: List<WhenEntrySelector>, val body: Statement) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append(selectors, ", ").append(" -> ").append(body) } } abstract class WhenEntrySelector : Statement() class ValueWhenEntrySelector(val expression: Expression) : WhenEntrySelector() { override fun generateCode(builder: CodeBuilder) { builder.append(expression) } } class ElseWhenEntrySelector : WhenEntrySelector() { override fun generateCode(builder: CodeBuilder) { builder.append("else") } } // Other ------------------------------------------------------------------------------------------------------ class SynchronizedStatement(val expression: Expression, val block: Block) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append "synchronized (" append expression append ") " append block } }
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Statements.kt
2728874801
package quickbeer.android.ui.adapter.brewer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import quickbeer.android.data.state.State import quickbeer.android.databinding.BrewerListItemBinding import quickbeer.android.domain.brewer.Brewer import quickbeer.android.domain.country.Country import quickbeer.android.feature.beerdetails.model.Address import quickbeer.android.ui.adapter.base.ScopeListViewHolder class BrewerListViewHolder( private val binding: BrewerListItemBinding ) : ScopeListViewHolder<BrewerListModel>(binding.root) { override fun bind(item: BrewerListModel, scope: CoroutineScope) { clear() scope.launch { item.getBrewer(item.brewerId).collect { if (it is State.Loading && it.value?.countryId != null) { getCountry(it.value, item, scope) } else if (it is State.Success && it.value.countryId != null) { getCountry(it.value, item, scope) } withContext(Dispatchers.Main) { updateState(it) } } } } private fun getCountry(brewer: Brewer?, item: BrewerListModel, scope: CoroutineScope) { if (brewer?.countryId == null) return scope.launch { item.getCountry(brewer.countryId) .map { mergeAddress(brewer, it) } .collect { withContext(Dispatchers.Main) { setAddress(it) } } } } private fun mergeAddress(brewer: Brewer, country: State<Country>): Address? { return if (country is State.Success) { Address.from(brewer, country.value) } else null } private fun updateState(state: State<Brewer>) { when (state) { is State.Initial -> Unit is State.Loading -> state.value?.let(::setBrewer) is State.Empty -> Unit is State.Success -> setBrewer(state.value) is State.Error -> Unit } } private fun setBrewer(brewer: Brewer) { binding.brewerName.text = brewer.name } private fun setAddress(address: Address?) { if (address == null) return binding.brewerLocation.text = address.cityAndCountry() binding.brewerCountry.text = address.code } private fun clear() { binding.brewerName.text = "" binding.brewerLocation.text = "" } }
app/src/main/java/quickbeer/android/ui/adapter/brewer/BrewerListViewHolder.kt
2191591992
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 class ClientError : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == RuntimeException::class.type } class cause : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Throwable::class.type } } class message : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == String::class.type } } }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/ClientError.kt
1067324103
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder import com.intellij.psi.PsiElement import com.intellij.util.ArrayUtil import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.getResolvableApproximations import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.makeNotNullable import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import java.util.* /** * Represents a concrete type or a set of types yet to be inferred from an expression. */ abstract class TypeInfo(val variance: Variance) { object Empty : TypeInfo(Variance.INVARIANT) { override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = Collections.emptyList() } class ByExpression(val expression: KtExpression, variance: Variance) : TypeInfo(variance) { override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> { return Fe10KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray() } override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = expression.guessTypes( context = builder.currentFileContext, module = builder.currentFileModule, pseudocode = try { builder.pseudocode } catch (stackException: EmptyStackException) { val originalElement = builder.config.originalElement val containingDeclarationForPseudocode = originalElement.containingDeclarationForPseudocode // copy-pasted from org.jetbrains.kotlin.cfg.pseudocode.PseudocodeUtilsKt.getContainingPseudocode val enclosingPseudocodeDeclaration = (containingDeclarationForPseudocode as? KtFunctionLiteral)?.let { functionLiteral -> functionLiteral.parents.firstOrNull { it is KtDeclaration && it !is KtFunctionLiteral } as? KtDeclaration } ?: containingDeclarationForPseudocode throw KotlinExceptionWithAttachments(stackException.message, stackException) .withPsiAttachment("original_expression.txt", originalElement) .withPsiAttachment("containing_declaration.txt", containingDeclarationForPseudocode) .withPsiAttachment("enclosing_declaration.txt", enclosingPseudocodeDeclaration) } ).flatMap { it.getPossibleSupertypes(variance, builder) } } class ByTypeReference(val typeReference: KtTypeReference, variance: Variance) : TypeInfo(variance) { override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder) } class ByType(val theType: KotlinType, variance: Variance) : TypeInfo(variance) { override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = theType.getPossibleSupertypes(variance, builder) } class ByReceiverType(variance: Variance) : TypeInfo(variance) { override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = (builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder) } class ByExplicitCandidateTypes(val types: List<KotlinType>) : TypeInfo(Variance.INVARIANT) { override fun getPossibleTypes(builder: CallableBuilder) = types } abstract class DelegatingTypeInfo(val delegate: TypeInfo) : TypeInfo(delegate.variance) { override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed override fun getPossibleNamesFromExpression(bindingContext: BindingContext) = delegate.getPossibleNamesFromExpression(bindingContext) override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = delegate.getPossibleTypes(builder) } class NoSubstitutions(delegate: TypeInfo) : DelegatingTypeInfo(delegate) { override val substitutionsAllowed: Boolean = false } class StaticContextRequired(delegate: TypeInfo) : DelegatingTypeInfo(delegate) { override val staticContextRequired: Boolean = true } class OfThis(delegate: TypeInfo) : DelegatingTypeInfo(delegate) val isOfThis: Boolean get() = when (this) { is OfThis -> true is DelegatingTypeInfo -> delegate.isOfThis else -> false } open val substitutionsAllowed: Boolean = true open val staticContextRequired: Boolean = false open fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array<String> = ArrayUtil.EMPTY_STRING_ARRAY abstract fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> private fun getScopeForTypeApproximation(config: CallableBuilderConfiguration, placement: CallablePlacement?): LexicalScope? { if (placement == null) return config.originalElement.getResolutionScope() val containingElement = when (placement) { is CallablePlacement.NoReceiver -> { placement.containingElement } is CallablePlacement.WithReceiver -> { val receiverClassDescriptor = placement.receiverTypeCandidate.theType.constructor.declarationDescriptor val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile } } return when (containingElement) { is KtClassOrObject -> (containingElement.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution is KtBlockExpression -> (containingElement.statements.firstOrNull() ?: containingElement).getResolutionScope() is KtElement -> containingElement.containingKtFile.getResolutionScope() else -> null } } protected fun KotlinType?.getPossibleSupertypes(variance: Variance, callableBuilder: CallableBuilder): List<KotlinType> { if (this == null || ErrorUtils.containsErrorType(this)) { return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType) } val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement) val approximations = getResolvableApproximations(scope, checkTypeParameters = false, allowIntersections = true) return when (variance) { Variance.IN_VARIANCE -> approximations.toList() else -> listOf(approximations.firstOrNull() ?: this) } } } fun TypeInfo(expressionOfType: KtExpression, variance: Variance): TypeInfo = TypeInfo.ByExpression(expressionOfType, variance) fun TypeInfo(typeReference: KtTypeReference, variance: Variance): TypeInfo = TypeInfo.ByTypeReference(typeReference, variance) fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByType(theType, variance) fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this) fun TypeInfo.forceNotNull(): TypeInfo { class ForcedNotNull(delegate: TypeInfo) : TypeInfo.DelegatingTypeInfo(delegate) { override fun getPossibleTypes(builder: CallableBuilder): List<KotlinType> = super.getPossibleTypes(builder).map { it.makeNotNullable() } } return (this as? ForcedNotNull) ?: ForcedNotNull(this) } fun TypeInfo.ofThis() = TypeInfo.OfThis(this) /** * Encapsulates information about a function parameter that is going to be created. */ class ParameterInfo( val typeInfo: TypeInfo, val nameSuggestions: List<String> ) { constructor(typeInfo: TypeInfo, preferredName: String? = null) : this(typeInfo, listOfNotNull(preferredName)) } enum class CallableKind { FUNCTION, CLASS_WITH_PRIMARY_CONSTRUCTOR, CONSTRUCTOR, PROPERTY } abstract class CallableInfo( val name: String, val receiverTypeInfo: TypeInfo, val returnTypeInfo: TypeInfo, val possibleContainers: List<KtElement>, val typeParameterInfos: List<TypeInfo>, val isForCompanion: Boolean = false, val modifierList: KtModifierList? = null ) { abstract val kind: CallableKind abstract val parameterInfos: List<ParameterInfo> val isAbstract get() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true abstract fun copy( receiverTypeInfo: TypeInfo = this.receiverTypeInfo, possibleContainers: List<KtElement> = this.possibleContainers, modifierList: KtModifierList? = this.modifierList ): CallableInfo } class FunctionInfo( name: String, receiverTypeInfo: TypeInfo, returnTypeInfo: TypeInfo, possibleContainers: List<KtElement> = Collections.emptyList(), override val parameterInfos: List<ParameterInfo> = Collections.emptyList(), typeParameterInfos: List<TypeInfo> = Collections.emptyList(), isForCompanion: Boolean = false, modifierList: KtModifierList? = null, val preferEmptyBody: Boolean = false ) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) { override val kind: CallableKind get() = CallableKind.FUNCTION override fun copy( receiverTypeInfo: TypeInfo, possibleContainers: List<KtElement>, modifierList: KtModifierList? ) = FunctionInfo( name, receiverTypeInfo, returnTypeInfo, possibleContainers, parameterInfos, typeParameterInfos, isForCompanion, modifierList ) } class ClassWithPrimaryConstructorInfo( val classInfo: ClassInfo, expectedTypeInfo: TypeInfo, modifierList: KtModifierList? = null, val primaryConstructorVisibility: DescriptorVisibility? = null ) : CallableInfo( classInfo.name, TypeInfo.Empty, expectedTypeInfo.forceNotNull(), Collections.emptyList(), classInfo.typeArguments, false, modifierList = modifierList ) { override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR override val parameterInfos: List<ParameterInfo> get() = classInfo.parameterInfos override fun copy( receiverTypeInfo: TypeInfo, possibleContainers: List<KtElement>, modifierList: KtModifierList? ) = throw UnsupportedOperationException() } class ConstructorInfo( override val parameterInfos: List<ParameterInfo>, val targetClass: PsiElement, val isPrimary: Boolean = false, modifierList: KtModifierList? = null, val withBody: Boolean = false ) : CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) { override val kind: CallableKind get() = CallableKind.CONSTRUCTOR override fun copy( receiverTypeInfo: TypeInfo, possibleContainers: List<KtElement>, modifierList: KtModifierList? ) = throw UnsupportedOperationException() } class PropertyInfo( name: String, receiverTypeInfo: TypeInfo, returnTypeInfo: TypeInfo, val writable: Boolean, possibleContainers: List<KtElement> = Collections.emptyList(), typeParameterInfos: List<TypeInfo> = Collections.emptyList(), val isLateinitPreferred: Boolean = false, val isConst: Boolean = false, isForCompanion: Boolean = false, val annotations: List<KtAnnotationEntry> = emptyList(), modifierList: KtModifierList? = null, val initializer: KtExpression? = null ) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) { override val kind: CallableKind get() = CallableKind.PROPERTY override val parameterInfos: List<ParameterInfo> get() = Collections.emptyList() override fun copy( receiverTypeInfo: TypeInfo, possibleContainers: List<KtElement>, modifierList: KtModifierList? ) = copyProperty(receiverTypeInfo, possibleContainers, modifierList) fun copyProperty( receiverTypeInfo: TypeInfo = this.receiverTypeInfo, possibleContainers: List<KtElement> = this.possibleContainers, modifierList: KtModifierList? = this.modifierList, isLateinitPreferred: Boolean = this.isLateinitPreferred ) = PropertyInfo( name, receiverTypeInfo, returnTypeInfo, writable, possibleContainers, typeParameterInfos, isConst, isLateinitPreferred, isForCompanion, annotations, modifierList, initializer ) }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt
3134035193
package br.com.concretesolutions.kappuccino.matchers.drawable import android.support.annotation.DrawableRes import android.support.test.InstrumentationRegistry import android.support.test.espresso.matcher.BoundedMatcher import android.view.View import android.widget.TextView import br.com.concretesolutions.kappuccino.utils.checkResIdAgainstDrawable import org.hamcrest.Description import org.hamcrest.Matcher sealed class DrawablePosition { data class Start(@DrawableRes val resId: Int) : DrawablePosition() data class End(@DrawableRes val resId: Int) : DrawablePosition() data class Top(@DrawableRes val resId: Int) : DrawablePosition() data class Bottom(@DrawableRes val resId: Int) : DrawablePosition() override fun toString(): String { return this::class.java.name } } class TextViewDrawableMatcher { fun withCompoundDrawable(drawablePosition: DrawablePosition): Matcher<View> { val context = InstrumentationRegistry.getTargetContext() return object : BoundedMatcher<View, TextView>(TextView::class.java) { override fun describeTo(description: Description) { description.appendText("Expected but not equal to drawable $drawablePosition") } override fun matchesSafely(actual: TextView): Boolean { return when (drawablePosition) { is DrawablePosition.Start -> { checkResIdAgainstDrawable(drawablePosition.resId, actual.compoundDrawablesRelative[0], context) } is DrawablePosition.Top -> { checkResIdAgainstDrawable(drawablePosition.resId, actual.compoundDrawablesRelative[1], context) } is DrawablePosition.End -> { checkResIdAgainstDrawable(drawablePosition.resId, actual.compoundDrawablesRelative[2], context) } is DrawablePosition.Bottom -> { checkResIdAgainstDrawable(drawablePosition.resId, actual.compoundDrawablesRelative[3], context) } } } } } }
kappuccino/src/main/kotlin/br/com/concretesolutions/kappuccino/matchers/drawable/TextViewDrawableMatcher.kt
1857128383
package uk.co.cacoethes.lazybones.scm import groovy.util.logging.Log import org.ini4j.Wini import uk.co.cacoethes.lazybones.config.Configuration import java.io.* import java.util.logging.Logger /** * An SCM adapter for git. Make sure that when executing the external processes * you use the {@code text} property to ensure that the process output is fully * read. */ class GitAdapter : ScmAdapter { val GIT = "git" val log = Logger.getLogger(this.javaClass.getName()) val userName : String val userEmail : String constructor(config : Configuration) { // Load the current user's git config if it exists. val configFile = File(System.getProperty("user.home"), ".gitconfig") if (configFile.exists()) { val ini = Wini(configFile) val userKey = "user" userName = ini.get(userKey, "name") userEmail = ini.get(userKey, "email") } else { // Use Lazybones config entries if they exist. userName = config.getSetting("git.name")?.toString() ?: "Unknown" userEmail = config.getSetting("git.email")?.toString() ?: "[email protected]" } } override fun getExclusionsFilename() : String { return ".gitignore" } /** * Creates a new git repository in the given location by spawning an * external {@code git init} command. */ override fun initializeRepository(location : File) : Unit { execGit(arrayListOf("init"), location) } /** * Adds the initial files in the given location and commits them to the * git repository. * @param location The location of the git repository to commit the files * in. * @param message The commit message to use. */ override fun commitInitialFiles(location : File, message : String) : Unit { val configCmd = "config" execGit(arrayListOf("add", "."), location) execGit(arrayListOf(configCmd, "user.name", userName), location) execGit(arrayListOf(configCmd, "user.email", userEmail), location) execGit(arrayListOf("commit", "-m", message), location) } /** * Executes a git command using an external process. The executable must be * on the path! It also logs the output of each command at FINEST level. * @param args The git sub-command (e.g. 'status') + its arguments * @param location The working directory for the command. * @return The return code from the process. */ private fun execGit(args : List<String>, location : File) : Int { val process = ProcessBuilder(arrayListOf(GIT) + args).directory(location).redirectErrorStream(true).start() val out = StringWriter() val stdout = consumeProcessStream(process.getInputStream(), out) stdout.start() val exitCode = process.waitFor() stdout.join(1000) log.finest(out.toString()) return exitCode } private fun consumeProcessStream(stream : InputStream, w : Writer) : Thread { val buffer = CharArray(255) return object : Thread() { init { setDaemon(true) } override fun run() { val reader = InputStreamReader(stream) var charsRead = 0 while (charsRead != -1) { charsRead = reader.read(buffer, 0, 256) if (charsRead > 0) { synchronized (w) { w.write(buffer, 0, charsRead) } } } } } } }
lazybones-app/src/main/kotlin/uk/co/cacoethes/lazybones/scm/GitAdapter.kt
1325234112
// COMPILER_ARGUMENTS: -XXLanguage:+EnumEntries -opt-in=kotlin.ExperimentalStdlibApi // WITH_STDLIB enum class EnumClass fun foo() { // No special handling for method references EnumClass.values<caret>()::size }
plugins/kotlin/idea/tests/testData/inspectionsLocal/enumValuesSoftDeprecate/methodReferenceSuitableForList.kt
2104101695
package io.github.chrislo27.toolboks.lazysound import com.badlogic.gdx.assets.AssetDescriptor import com.badlogic.gdx.assets.AssetLoaderParameters import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.assets.loaders.FileHandleResolver import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.utils.Array class LazySoundLoader(resolver: FileHandleResolver) : SynchronousAssetLoader<LazySound, LazySoundLoaderParameter>( resolver) { override fun getDependencies(fileName: String?, file: FileHandle?, parameter: LazySoundLoaderParameter?): Array<AssetDescriptor<Any>>? { return null } override fun load(assetManager: AssetManager?, fileName: String?, file: FileHandle, parameter: LazySoundLoaderParameter?): LazySound { val ls = LazySound(file) if (!LazySound.loadLazilyWithAssetManager) ls.sound return ls } } class LazySoundLoaderParameter : AssetLoaderParameters<LazySound>()
core/src/main/kotlin/io/github/chrislo27/toolboks/lazysound/LazySoundLoader.kt
2156598756
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.updateSettings.impl import com.intellij.diagnostic.IdeErrorsDialog import com.intellij.externalDependencies.DependencyOnPlugin import com.intellij.externalDependencies.ExternalDependenciesManager import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.externalComponents.UpdatableExternalComponent import com.intellij.ide.plugins.* import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.* import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.LogUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.loadElement import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.apache.http.client.utils.URIBuilder import org.jdom.JDOMException import java.io.File import java.io.IOException import java.util.* /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. * * @author mike * @since Oct 31, 2002 */ object UpdateChecker { private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker") @JvmField val NOTIFICATIONS = NotificationGroup(IdeBundle.message("update.notifications.title"), NotificationDisplayType.STICKY_BALLOON, true) private val DISABLED_UPDATE = "disabled_update.txt" private var ourDisabledToUpdatePlugins: MutableSet<String>? = null private val ourAdditionalRequestOptions = hashMapOf<String, String>() private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>() private val ourShownNotifications = MultiMap<NotificationUniqueType, Notification>() val excludedFromUpdateCheckPlugins = hashSetOf<String>() private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { val callback = ActionCallback() ApplicationManager.getApplication().executeOnPooledThread { doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback) } return callback } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action may pass customised update settings). */ @JvmStatic fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) { val settings = customSettings ?: UpdateSettings.getInstance() val fromSettings = customSettings != null ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null) override fun isConditionalModal(): Boolean = fromSettings override fun shouldStartInBackground(): Boolean = !fromSettings }) } @JvmStatic fun doUpdateAndShowResult(project: Project?, fromSettings: Boolean, manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?, callback: ActionCallback?) { // check platform update indicator?.text = IdeBundle.message("updates.checking.platform") val result = checkPlatformUpdate(updateSettings) if (result.state == UpdateStrategy.State.CONNECTION_ERROR) { val e = result.error if (e != null) LOG.debug(e) showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e?.message ?: "internal error")) return } // check plugins update (with regard to potential platform update) indicator?.text = IdeBundle.message("updates.checking.plugins") val buildNumber: BuildNumber? = result.newBuild?.apiVersion val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? = if (buildNumber != null) HashSet<IdeaPluginDescriptor>() else null val updatedPlugins: Collection<PluginDownloader>? val externalUpdates: Collection<ExternalUpdate>? try { updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber) externalUpdates = updateExternal(manualCheck, updateSettings, indicator) } catch (e: IOException) { showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message)) return } // show result UpdateSettings.getInstance().saveLastCheckedInfo() ApplicationManager.getApplication().invokeLater({ showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, externalUpdates, !fromSettings, manualCheck) callback?.setDone() }, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL) } private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult { if (!settings.isPlatformUpdateEnabled) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val updateInfo: UpdatesInfo? try { val uriBuilder = URIBuilder(updateUrl) if (URLUtil.FILE_PROTOCOL != uriBuilder.scheme) { prepareUpdateCheckArgs(uriBuilder) } val updateUrl = uriBuilder.build().toString() LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl) updateInfo = HttpRequests.request(updateUrl) .forceHttps(settings.canUseSecureConnection()) .connect { try { UpdatesInfo(loadElement(it.reader)) } catch (e: JDOMException) { // corrupted content, don't bother telling user LOG.info(e) null } } } catch (e: Exception) { LOG.info(e) return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e) } if (updateInfo == null) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, settings) return strategy.checkForUpdates() } @JvmStatic fun checkPluginsUpdate(updateSettings: UpdateSettings, indicator: ProgressIndicator?, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, buildNumber: BuildNumber?): Collection<PluginDownloader>? { val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) return null // check custom repositories and the main one for updates val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>() val hosts = RepositoryHelper.getPluginHosts() val state = InstalledPluginsState.getInstance() outer@ for (host in hosts) { try { val forceHttps = host == null && updateSettings.canUseSecureConnection() val list = RepositoryHelper.loadPlugins(host, buildNumber, forceHttps, indicator) for (descriptor in list) { val id = descriptor.pluginId if (updateable.containsKey(id)) { updateable.remove(id) state.onDescriptorDownload(descriptor) val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber, forceHttps) checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator) if (updateable.isEmpty()) { break@outer } } } } catch (e: IOException) { LOG.debug(e) if (host != null) { LOG.info("failed to load plugin descriptions from " + host + ": " + e.message) } else { throw e } } } return if (toUpdate.isEmpty) null else toUpdate.values } /** * Returns a list of plugins which are currently installed or were installed in the previous installation from which * we're importing the settings. */ private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> { val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>() updateable += PluginManagerCore.getPlugins().filter { !it.isBundled || it.allowBundledUpdate()}.associateBy { it.pluginId } val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { for (line in FileUtil.loadLines(onceInstalled)) { val id = PluginId.getId(line.trim { it <= ' ' }) if (id !in updateable) { updateable.put(id, null) } } } catch (e: IOException) { LOG.error(onceInstalled.path, e) } //noinspection SSBasedInspection onceInstalled.deleteOnExit() } for (excludedPluginId in excludedFromUpdateCheckPlugins) { if (!isRequiredForAnyOpenProject(excludedPluginId)) { updateable.remove(PluginId.getId(excludedPluginId)) } } return updateable } private fun isRequiredForAnyOpenProject(pluginId: String) = ProjectManager.getInstance().openProjects.any { isRequiredForProject(it, pluginId) } private fun isRequiredForProject(project: Project, pluginId: String) = ExternalDependenciesManager.getInstance(project).getDependencies(DependencyOnPlugin::class.java).any { it.pluginId == pluginId } @Throws(IOException::class) @JvmStatic fun updateExternal(manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?) : Collection<ExternalUpdate> { val result = arrayListOf<ExternalUpdate>() val manager = ExternalComponentManager.getInstance() indicator?.text = IdeBundle.message("updates.external.progress") for (source in manager.componentSources) { indicator?.checkCanceled() if (source.name in updateSettings.enabledExternalUpdateSources) { try { val siteResult = arrayListOf<UpdatableExternalComponent>() for (component in source.getAvailableVersions(indicator, updateSettings)) { if (component.isUpdateFor(manager.findExistingComponentMatching(component, source))) { siteResult.add(component) } } if (!siteResult.isEmpty()) { result.add(ExternalUpdate(siteResult, source)) } } catch (e: Exception) { LOG.warn(e) showErrorMessage(manualCheck, IdeBundle.message("updates.external.error.message", source.name, e.message ?: "internal error")) } } } return result } @Throws(IOException::class) @JvmStatic fun checkAndPrepareToInstall(downloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, indicator: ProgressIndicator?) { @Suppress("NAME_SHADOWING") var downloader = downloader val pluginId = downloader.pluginId if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return val pluginVersion = downloader.pluginVersion val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId)) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) { var descriptor: IdeaPluginDescriptor? val oldDownloader = ourUpdatedPlugins[pluginId] if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { descriptor = downloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) { descriptor = downloader.descriptor } ourUpdatedPlugins.put(pluginId, downloader) } } else { downloader = oldDownloader descriptor = oldDownloader.descriptor } if (descriptor != null && PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate.put(PluginId.getId(pluginId), downloader) } } //collect plugins which were not updated and would be incompatible with new version if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled && !toUpdate.containsKey(installedPlugin.pluginId) && PluginManagerCore.isIncompatible(installedPlugin, downloader.buildNumber)) { incompatiblePlugins.add(installedPlugin) } } private fun showErrorMessage(showDialog: Boolean, message: String) { LOG.info(message) if (showDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) } } } private fun showUpdateResult(project: Project?, checkForUpdateResult: CheckForUpdateResult, updateSettings: UpdateSettings, updatedPlugins: Collection<PluginDownloader>?, incompatiblePlugins: Collection<IdeaPluginDescriptor>?, externalUpdates: Collection<ExternalUpdate>?, enableLink: Boolean, alwaysShowResults: Boolean) { val updatedChannel = checkForUpdateResult.updatedChannel val newBuild = checkForUpdateResult.newBuild if (updatedChannel != null && newBuild != null) { val runnable = { val patch = checkForUpdateResult.findPatchForBuild(ApplicationInfo.getInstance().build) val forceHttps = updateSettings.canUseSecureConnection() UpdateInfoDialog(updatedChannel, newBuild, patch, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show() } ourShownNotifications.remove(NotificationUniqueType.PLATFORM)?.forEach { it.expire() } if (alwaysShowResults) { runnable.invoke() } else { val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName) showNotification(project, message, runnable, NotificationUniqueType.PLATFORM) } return } var updateFound = false if (updatedPlugins != null && !updatedPlugins.isEmpty()) { updateFound = true val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() } ourShownNotifications.remove(NotificationUniqueType.PLUGINS)?.forEach { it.expire() } if (alwaysShowResults) { runnable.invoke() } else { val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName } val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins) showNotification(project, message, runnable, NotificationUniqueType.PLUGINS) } } if (externalUpdates != null && !externalUpdates.isEmpty()) { updateFound = true ourShownNotifications.remove(NotificationUniqueType.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (alwaysShowResults) { runnable.invoke() } else { val updates = update.components.joinToString(", ") val message = IdeBundle.message("updates.external.ready.message", update.components.size, updates) showNotification(project, message, runnable, NotificationUniqueType.EXTERNAL) } } } if (!updateFound && alwaysShowResults) { NoUpdatesDialog(enableLink).show() } } private fun showNotification(project: Project?, message: String, action: () -> Unit, notificationType: NotificationUniqueType) { val listener = NotificationListener { notification, event -> notification.expire() action.invoke() } val title = IdeBundle.message("update.notifications.title") val notification = NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener) notification.whenExpired { ourShownNotifications.remove(notificationType, notification) } notification.notify(project) ourShownNotifications.putValue(notificationType, notification) } @JvmStatic fun addUpdateRequestParameter(name: String, value: String) { ourAdditionalRequestOptions.put(name, value) } private fun prepareUpdateCheckArgs(uriBuilder: URIBuilder) { addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString()) addUpdateRequestParameter("uid", PermanentInstallationID.get()) addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ApplicationInfoEx.getInstanceEx().isEAP) { addUpdateRequestParameter("eap", "") } for ((name, value) in ourAdditionalRequestOptions) { uriBuilder.addParameter(name, if (StringUtil.isEmpty(value)) null else value) } } @Deprecated("Replaced", ReplaceWith("PermanentInstallationID.get()", "com.intellij.openapi.application.PermanentInstallationID")) @JvmStatic @Suppress("unused", "UNUSED_PARAMETER") fun getInstallationUID(c: PropertiesComponent) = PermanentInstallationID.get() @JvmStatic val disabledToUpdatePlugins: Set<String> get() { if (ourDisabledToUpdatePlugins == null) { ourDisabledToUpdatePlugins = TreeSet<String>() if (!ApplicationManager.getApplication().isUnitTestMode) { try { val file = File(PathManager.getConfigPath(), DISABLED_UPDATE) if (file.isFile) { FileUtil.loadFile(file) .split("[\\s]".toRegex()) .map { it.trim() } .filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() } } } catch (e: IOException) { LOG.error(e) } } } return ourDisabledToUpdatePlugins!! } @JvmStatic fun saveDisabledToUpdatePlugins() { val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE) try { PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins) } catch (e: IOException) { LOG.error(e) } } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (app != null && !app.isDisposed && !app.isDisposeInProgress && UpdateSettings.getInstance().isCheckNeeded) { val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } private enum class NotificationUniqueType { PLATFORM, PLUGINS, EXTERNAL } }
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
768868840
/* * Copyright (c) 2015 PocketHub * * 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.github.pockethub.android.ui.user import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import com.github.pockethub.android.Intents.Builder import com.github.pockethub.android.Intents.EXTRA_USER import com.github.pockethub.android.R import com.github.pockethub.android.accounts.AccountUtils import com.github.pockethub.android.rx.AutoDisposeUtils import com.github.pockethub.android.ui.base.BaseActivity import com.github.pockethub.android.ui.MainActivity import com.github.pockethub.android.ui.helpers.PagerHandler import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.core.ServiceGenerator import com.meisolsson.githubsdk.model.User import com.meisolsson.githubsdk.service.users.UserFollowerService import com.meisolsson.githubsdk.service.users.UserService import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.pager_with_tabs.* import kotlinx.android.synthetic.main.tabbed_progress_pager.* import retrofit2.Response /** * Activity to view a user's various pages */ class UserViewActivity : BaseActivity(), OrganizationSelectionProvider { private var user: User? = null private var isFollowing: Boolean = false private var followingStatusChecked: Boolean = false private var pagerHandler: PagerHandler<UserPagerAdapter>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tabbed_progress_pager) user = intent.getParcelableExtra(EXTRA_USER) val actionBar = supportActionBar!! actionBar.setDisplayHomeAsUpEnabled(true) actionBar.title = user!!.login() if (!TextUtils.isEmpty(user!!.avatarUrl())) { configurePager() } else { pb_loading.visibility = View.VISIBLE ServiceGenerator.createService(this, UserService::class.java) .getUser(user!!.login()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe({ response -> user = response.body() configurePager() }, { e -> ToastUtils.show(this, R.string.error_person_load) pb_loading.visibility = View.GONE }) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_user_follow, menu) return super.onCreateOptionsMenu(menu) } override fun onPrepareOptionsMenu(menu: Menu): Boolean { val followItem = menu.findItem(R.id.m_follow) val isCurrentUser = user!!.login() == AccountUtils.getLogin(this) followItem.isVisible = followingStatusChecked && !isCurrentUser followItem.setTitle(if (isFollowing) R.string.unfollow else R.string.follow) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.m_follow -> { followUser() true } android.R.id.home -> { val intent = Intent(this, MainActivity::class.java) intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP) startActivity(intent) true } else -> super.onOptionsItemSelected(item) } } private fun configurePager() { val adapter = UserPagerAdapter(this) pagerHandler = PagerHandler(this, vp_pages, adapter) lifecycle.addObserver(pagerHandler!!) pagerHandler!!.tabs = sliding_tabs_layout pb_loading.visibility = View.GONE pagerHandler!!.setGone(false) checkFollowingUserStatus() } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(pagerHandler!!) } override fun addListener(listener: OrganizationSelectionListener): User? { return user } override fun removeListener( listener: OrganizationSelectionListener ): OrganizationSelectionProvider { return this } private fun followUser() { val service = ServiceGenerator.createService(this, UserFollowerService::class.java) val followSingle: Single<Response<Void>> followSingle = if (isFollowing) { service.unfollowUser(user!!.login()) } else { service.followUser(user!!.login()) } followSingle.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe({ aVoid -> isFollowing = !isFollowing }, { e -> val message = if (isFollowing) R.string.error_unfollowing_person else R.string.error_following_person ToastUtils.show(this, message) }) } private fun checkFollowingUserStatus() { followingStatusChecked = false ServiceGenerator.createService(this, UserFollowerService::class.java) .isFollowing(user!!.login()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .`as`(AutoDisposeUtils.bindToLifecycle(this)) .subscribe { response -> isFollowing = response.code() == 204 followingStatusChecked = true invalidateOptionsMenu() } } companion object { /** * Create intent for this activity * * @param user * @return intent */ fun createIntent(user: User): Intent { return Builder("user.VIEW").user(user).toIntent() } } }
app/src/main/java/com/github/pockethub/android/ui/user/UserViewActivity.kt
1360535496
/* * Copyright (c) 2019. * Neato Robotics Inc. */ package com.neatorobotics.sdk.android.robotservices.housecleaning import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.MockitoAnnotations import org.mockito.junit.MockitoJUnitRunner import org.junit.Assert.assertFalse @RunWith(MockitoJUnitRunner::class) class HouseCleaningBasic4ServiceTest { lateinit var service: HouseCleaningBasic4Service @Before fun setup() { service = HouseCleaningBasic4Service() // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To // inject the mocks in the test the initMocks method needs to be called. MockitoAnnotations.initMocks(this) } @Test fun testMultipleZonesSupport() { assertFalse(service.isMultipleZonesCleaningSupported) } }
Neato-SDK/neato-sdk-android/src/test/java/com/neatorobotics/sdk/android/robotservices/housecleaning/HouseCleaningBasic4ServiceTest.kt
2505666194
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.pyi import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.DelegatingScopeProcessor import com.intellij.psi.scope.PsiScopeProcessor import com.jetbrains.python.PyNames import com.jetbrains.python.PythonFileType import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyImportElement import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.PyFileImpl import com.jetbrains.python.psi.resolve.ImportedResolveResult import com.jetbrains.python.psi.resolve.RatedResolveResult /** * @author vlan */ class PyiFile(viewProvider: FileViewProvider) : PyFileImpl(viewProvider, PyiLanguageDialect.getInstance()) { override fun getFileType(): PythonFileType = PyiFileType.INSTANCE override fun toString(): String = "PyiFile:$name" override fun getLanguageLevel(): LanguageLevel = LanguageLevel.getLatest() override fun multiResolveName(name: String, exported: Boolean): List<RatedResolveResult> { if (name == "function" && PyBuiltinCache.getInstance(this).builtinsFile == this) return emptyList() if (exported && isPrivateName(name) && !resolvingBuiltinPathLike(name)) return emptyList() val baseResults = super.multiResolveName(name, exported) val dunderAll = dunderAll ?: emptyList() return if (exported) baseResults.filterNot { isPrivateImport((it as? ImportedResolveResult)?.definer, dunderAll) } else baseResults } override fun processDeclarations(processor: PsiScopeProcessor, resolveState: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean { val dunderAll = dunderAll ?: emptyList() val wrapper = object : DelegatingScopeProcessor(processor) { override fun execute(element: PsiElement, state: ResolveState): Boolean = when { isPrivateImport(element, dunderAll) -> true element is PsiNamedElement && isPrivateName(element.name) -> true else -> super.execute(element, state) } } return super.processDeclarations(wrapper, resolveState, lastParent, place) } private fun isPrivateName(name: String?) = PyUtil.getInitialUnderscores(name) == 1 private fun isPrivateImport(element: PsiElement?, dunderAll: List<String>): Boolean { return element is PyImportElement && element.asName == null && element.visibleName !in dunderAll } private fun resolvingBuiltinPathLike(name: String): Boolean { return name == PyNames.BUILTIN_PATH_LIKE && PyBuiltinCache.getInstance(this).builtinsFile == this } }
python/python-psi-impl/src/com/jetbrains/python/pyi/PyiFile.kt
4073608339
// 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.ide.ui.experimental.toolbar import com.intellij.openapi.components.BaseState import com.intellij.util.xmlb.annotations.OptionTag class ExperimentalToolbarStateWrapper: BaseState() { @get:OptionTag("NEW_TOOLBAR_SETTINGS") var state by enum(ExperimentalToolbarStateEnum.NEW_TOOLBAR_WITHOUT_NAVBAR) }
platform/editor-ui-api/src/com/intellij/ide/ui/experimental/toolbar/ExperimentalToolbarStateWrapper.kt
257177265
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.configurationStore.ROOT_CONFIG import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.ide.actions.ExportableItem import com.intellij.ide.actions.getExportableComponentsMap import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.stateStore import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import java.io.File fun copyLocalConfig(storageManager: StateStorageManagerImpl = ApplicationManager.getApplication()!!.stateStore.stateStorageManager as StateStorageManagerImpl) { val streamProvider = storageManager.streamProvider!! as IcsManager.IcsStreamProvider val fileToComponents = getExportableComponentsMap(true, false, storageManager) for (file in fileToComponents.keySet()) { val absolutePath = FileUtilRt.toSystemIndependentName(file.absolutePath) var fileSpec = storageManager.collapseMacros(absolutePath) LOG.assertTrue(!fileSpec.contains(ROOT_CONFIG)) if (fileSpec.equals(absolutePath)) { // we have not experienced such problem yet, but we are just aware val canonicalPath = FileUtilRt.toSystemIndependentName(file.canonicalPath) if (!canonicalPath.equals(absolutePath)) { fileSpec = storageManager.collapseMacros(canonicalPath) } } val roamingType = getRoamingType(fileToComponents.get(file)) if (file.isFile) { val fileBytes = FileUtil.loadFileBytes(file) streamProvider.doSave(fileSpec, fileBytes, fileBytes.size(), roamingType) } else { saveDirectory(file, fileSpec, roamingType, streamProvider) } } } private fun saveDirectory(parent: File, parentFileSpec: String, roamingType: RoamingType, streamProvider: IcsManager.IcsStreamProvider) { val files = parent.listFiles() if (files != null) { for (file in files) { val childFileSpec = parentFileSpec + '/' + file.name if (file.isFile) { val fileBytes = FileUtil.loadFileBytes(file) streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size(), roamingType) } else { saveDirectory(file, childFileSpec, roamingType, streamProvider) } } } } private fun getRoamingType(components: Collection<ExportableItem>): RoamingType { for (component in components) { if (component is ExportableItem) { return component.roamingType } // else if (component is PersistentStateComponent<*>) { // val stateAnnotation = component.javaClass.getAnnotation(State::class.java) // if (stateAnnotation != null) { // val storages = stateAnnotation.storages // if (!storages.isEmpty()) { // return storages[0].roamingType // } // } // } } return RoamingType.DEFAULT }
plugins/settings-repository/src/copyAppSettingsToRepository.kt
710968509
package no.skatteetaten.aurora.boober.model.openshift import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonPropertyOrder import io.fabric8.kubernetes.api.model.HasMetadata import io.fabric8.kubernetes.api.model.ObjectMeta @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder(value = ["apiVersion", "kind", "metadata", "spec"]) data class AuroraAzureCname( val spec: AzureCnameSpec, @JsonIgnore var _metadata: ObjectMeta?, @JsonIgnore val _kind: String = "AuroraAzureCname", @JsonIgnore var _apiVersion: String = "skatteetaten.no/v1" ) : HasMetadata { override fun getMetadata(): ObjectMeta { return _metadata ?: ObjectMeta() } override fun getKind(): String { return _kind } override fun getApiVersion(): String { return _apiVersion } override fun setMetadata(metadata: ObjectMeta?) { _metadata = metadata } override fun setApiVersion(version: String?) { _apiVersion = apiVersion } } @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) data class AzureCnameSpec( val host: String, val cname: String, val ttl: Int )
src/main/kotlin/no/skatteetaten/aurora/boober/model/openshift/AuroraAzureCname.kt
1533689595
package pl.edu.amu.wmi.erykandroidcommon.di import android.app.Application import android.content.Context import android.preference.PreferenceManager import com.f2prateek.rx.preferences2.RxSharedPreferences import com.google.gson.ExclusionStrategy import com.google.gson.FieldAttributes import com.google.gson.FieldNamingPolicy import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.annotations.Expose import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import dagger.Module import dagger.Provides import okhttp3.ConnectionPool import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import pl.edu.amu.wmi.erykandroidcommon.location.LocationService import pl.edu.amu.wmi.erykandroidcommon.service.PicassoCache import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.security.SecureRandom import java.security.cert.X509Certificate import java.util.concurrent.TimeUnit import javax.inject.Singleton import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager fun retroFactory(baseUrl: String, gson: Gson, okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder().baseUrl(baseUrl) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build() fun okHttpFactory(debug: Boolean, interceptor: Interceptor?): OkHttpClient { val clientBuilder = OkHttpClient.Builder() interceptor?.let { clientBuilder.addInterceptor(interceptor) } val sslContext = SSLContext.getInstance("SSL") val connectionPool = ConnectionPool(5, 60, TimeUnit.SECONDS) val connectionTrustManager = arrayOf<TrustManager>(object : X509TrustManager { override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) = Unit override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) = Unit override fun getAcceptedIssuers(): Array<out X509Certificate> = arrayOf() }) sslContext.init(null, connectionTrustManager, SecureRandom()) clientBuilder.sslSocketFactory(sslContext.socketFactory) clientBuilder.hostnameVerifier { _, _ -> true } clientBuilder.connectionPool(connectionPool) if (debug) { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY clientBuilder.addInterceptor(loggingInterceptor).build() } return clientBuilder.build() } @Module class CommonApplicationModule(private val application: CommonApplication) { @Provides @Singleton fun provideContext(): Context = application @Provides @Singleton fun provideApplication(): Application = application @Provides @Singleton fun provideCommonApplication(): CommonApplication = application @Provides @Singleton fun provideGson(): Gson = GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .addSerializationExclusionStrategy(object : ExclusionStrategy { override fun shouldSkipField(fieldAttributes: FieldAttributes): Boolean { val expose = fieldAttributes.getAnnotation(Expose::class.java) return expose != null && !expose.serialize } override fun shouldSkipClass(aClass: Class<*>): Boolean = false }) .addDeserializationExclusionStrategy(object : ExclusionStrategy { override fun shouldSkipField(fieldAttributes: FieldAttributes): Boolean { val expose = fieldAttributes.getAnnotation(Expose::class.java) return expose != null && !expose.deserialize } override fun shouldSkipClass(aClass: Class<*>): Boolean = false }) .create() @Provides @Singleton fun provideCachedImageManager(): PicassoCache = PicassoCache(application) @Provides @Singleton fun provideLocationService(): LocationService = LocationService(application) @Provides @Singleton fun provideSharedPreferences(): RxSharedPreferences = RxSharedPreferences.create( PreferenceManager.getDefaultSharedPreferences(application)) }
src/main/java/pl/edu/amu/wmi/erykandroidcommon/di/CommonApplicationModule.kt
3051616687
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.google.protobuf.kotlin /** * Indicates an API that is part of a DSL to generate protocol buffer messages. */ @DslMarker @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) @OnlyForUseByGeneratedProtoCode annotation class ProtoDslMarker
third_party/protobuf/java/kotlin/src/main/kotlin/com/google/protobuf/ProtoDslMarker.kt
1710578864
/* * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ // This file was automatically generated from coroutines-guide-ui.md by Knit tool. Do not edit. package kotlinx.coroutines.javafx.guide.exampleUiActor02 import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.javafx.JavaFx as Main import javafx.application.Application import javafx.event.EventHandler import javafx.geometry.* import javafx.scene.* import javafx.scene.input.MouseEvent import javafx.scene.layout.StackPane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.scene.text.Text import javafx.stage.Stage fun main(args: Array<String>) { Application.launch(ExampleApp::class.java, *args) } class ExampleApp : Application() { val hello = Text("Hello World!").apply { fill = Color.valueOf("#C0C0C0") } val fab = Circle(20.0, Color.valueOf("#FF4081")) val root = StackPane().apply { children += hello children += fab StackPane.setAlignment(hello, Pos.CENTER) StackPane.setAlignment(fab, Pos.BOTTOM_RIGHT) StackPane.setMargin(fab, Insets(15.0)) } val scene = Scene(root, 240.0, 380.0).apply { fill = Color.valueOf("#303030") } override fun start(stage: Stage) { stage.title = "Example" stage.scene = scene stage.show() setup(hello, fab) } } fun setup(hello: Text, fab: Circle) { fab.onClick { // start coroutine when the circle is clicked for (i in 10 downTo 1) { // countdown from 10 to 1 hello.text = "Countdown $i ..." // update text delay(500) // wait half a second } hello.text = "Done!" } } fun Node.onClick(action: suspend (MouseEvent) -> Unit) { // launch one actor to handle all events on this node val eventActor = GlobalScope.actor<MouseEvent>(Dispatchers.Main) { for (event in channel) action(event) // pass event to action } // install a listener to offer events to this actor onMouseClicked = EventHandler { event -> eventActor.trySend(event) } }
ui/kotlinx-coroutines-javafx/test/guide/example-ui-actor-02.kt
2108709365
package org.neo4j.graphql import graphql.GraphQL import org.junit.After import org.junit.Before import org.junit.Test import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.kernel.impl.proc.Procedures import org.neo4j.kernel.internal.GraphDatabaseAPI import org.neo4j.test.TestGraphDatabaseFactory import kotlin.test.assertEquals /** * @author mh * * * @since 05.05.17 */ class ReturnNodesTest { private lateinit var db: GraphDatabaseService private lateinit var ctx: GraphQLContext private var graphQL: GraphQL? = null @Before @Throws(Exception::class) fun setUp() { db = TestGraphDatabaseFactory().newImpermanentDatabase() (db as GraphDatabaseAPI).dependencyResolver.resolveDependency(Procedures::class.java).let { it.registerFunction(GraphQLProcedure::class.java) it.registerProcedure(GraphQLProcedure::class.java) } db.execute(data)?.close() ctx = GraphQLContext(db) GraphSchemaScanner.storeIdl(db, schema) graphQL = GraphSchema.getGraphQL(db) } val data = """ MERGE(start_node:Node { id: 1 }) MERGE(end_node:Node { id: 2 }) CREATE (start_node)-[e:Edge]->(end_node) SET e.id = 1, e.distance=10.0 CREATE (start_node)-[:HasSubNode]->(:SubNode { id: 1, name: 'foo' }) CREATE (end_node)-[:HasSubNode]->(:SubNode { id: 2, name: 'bar' }) """ val schema = """ type Node { id: ID! subnodes: [SubNode] @relation(name:"HasSubNode") nodes: [Node] @relation(name:"Edge") } type SubNode { id: ID! name: String! nodes: [Node] @relation(name: "HasSubNode", direction: IN) } type Edge { id: ID! distance: Float! } schema { query: QueryType } type QueryType { shortestPath(fromSubNode: String!, toSubNode: String!): [Node] @cypher(statement:"MATCH (from:Node)-[:HasSubNode]-(:SubNode {name: ${"$"}fromSubNode}), (to:Node)-[:HasSubNode]-(:SubNode {name: ${"$"}toSubNode}) match p = shortestPath((from)-[*]->(to)) UNWIND nodes(p) as n RETURN distinct n") } """ @After @Throws(Exception::class) fun tearDown() { db.shutdown() } private fun assertResult(query: String, expected: Any, params: Map<String,Any> = emptyMap()) { val ctx2 = GraphQLContext(ctx.db, ctx.log, params) val result = graphQL!!.execute(query, ctx2, params) if (result.errors.isNotEmpty()) println(result.errors) assertEquals(expected, result.getData()) } @Test fun findShortestPath() { val query = """ query { shortestPath(fromSubNode: "foo" toSubNode: "bar") { id } } """ assertResult(query, mapOf("shortestPath" to listOf(mapOf("id" to "1"),mapOf("id" to "2")))) } }
src/test/java/org/neo4j/graphql/ReturnNodesTest.kt
449355146
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.atomicfu.* import kotlinx.coroutines.internal.* import kotlin.coroutines.* import kotlin.jvm.* internal fun <T> Result<T>.toState( onCancellation: ((cause: Throwable) -> Unit)? = null ): Any? = fold( onSuccess = { if (onCancellation != null) CompletedWithCancellation(it, onCancellation) else it }, onFailure = { CompletedExceptionally(it) } ) internal fun <T> Result<T>.toState(caller: CancellableContinuation<*>): Any? = fold( onSuccess = { it }, onFailure = { CompletedExceptionally(recoverStackTrace(it, caller)) } ) @Suppress("RESULT_CLASS_IN_RETURN_TYPE", "UNCHECKED_CAST") internal fun <T> recoverResult(state: Any?, uCont: Continuation<T>): Result<T> = if (state is CompletedExceptionally) Result.failure(recoverStackTrace(state.cause, uCont)) else Result.success(state as T) internal data class CompletedWithCancellation( @JvmField val result: Any?, @JvmField val onCancellation: (cause: Throwable) -> Unit ) /** * Class for an internal state of a job that was cancelled (completed exceptionally). * * @param cause the exceptional completion cause. It's either original exceptional cause * or artificial [CancellationException] if no cause was provided */ internal open class CompletedExceptionally( @JvmField public val cause: Throwable, handled: Boolean = false ) { private val _handled = atomic(handled) val handled: Boolean get() = _handled.value fun makeHandled(): Boolean = _handled.compareAndSet(false, true) override fun toString(): String = "$classSimpleName[$cause]" } /** * A specific subclass of [CompletedExceptionally] for cancelled [AbstractContinuation]. * * @param continuation the continuation that was cancelled. * @param cause the exceptional completion cause. If `cause` is null, then a [CancellationException] * if created on first access to [exception] property. */ internal class CancelledContinuation( continuation: Continuation<*>, cause: Throwable?, handled: Boolean ) : CompletedExceptionally(cause ?: CancellationException("Continuation $continuation was cancelled normally"), handled) { private val _resumed = atomic(false) fun makeResumed(): Boolean = _resumed.compareAndSet(false, true) }
kotlinx-coroutines-core/common/src/CompletionState.kt
2054665717
package com.intellij.workspace.jps import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.testFramework.ApplicationRule import com.intellij.workspace.api.TypedEntityStorageBuilder import com.intellij.workspace.api.verifySerializationRoundTrip import org.junit.ClassRule import org.junit.Test import java.io.File class ImlSerializationTest { @Test fun sampleProject() { val projectDir = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject") serializationRoundTrip(projectDir) } @Test fun communityProject() { val projectDir = File(PathManagerEx.getCommunityHomePath()) serializationRoundTrip(projectDir) } private fun serializationRoundTrip(projectFile: File) { val storageBuilder = TypedEntityStorageBuilder.create() JpsProjectEntitiesLoader.loadProject(projectFile.asStoragePlace(), storageBuilder) val storage = storageBuilder.toStorage() val byteArray = verifySerializationRoundTrip(storage) println("Serialized size: ${byteArray.size}") } companion object { @JvmField @ClassRule val appRule = ApplicationRule() } }
platform/workspaceModel-ide-tests/testSrc/com/intellij/workspace/jps/ImlSerializationTest.kt
937040292
// 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.stats.completion import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.CaretModel import com.intellij.openapi.editor.Editor import com.intellij.stats.storage.FilePathProvider import com.intellij.testFramework.HeavyPlatformTestCase import com.intellij.testFramework.replaceService import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import java.io.File import java.nio.file.FileSystems import java.nio.file.StandardWatchEventKinds import java.util.* import java.util.concurrent.TimeUnit class FileLoggerTest : HeavyPlatformTestCase() { private lateinit var dir: File private lateinit var logFile: File private lateinit var pathProvider: FilePathProvider override fun setUp() { super.setUp() dir = createTempDirectory() logFile = File(dir, "unique_1") pathProvider = mock(FilePathProvider::class.java).apply { `when`(getStatsDataDirectory()).thenReturn(dir) `when`(getUniqueFile()).thenReturn(logFile) } CompletionTrackerInitializer.isEnabledInTests = true } override fun tearDown() { CompletionTrackerInitializer.isEnabledInTests = false try { dir.deleteRecursively() } finally { super.tearDown() } } @Test fun testLogging() { val fileLengthBefore = logFile.length() val uidProvider = mock(InstallationIdProvider::class.java).apply { `when`(installationId()).thenReturn(UUID.randomUUID().toString()) } ApplicationManager.getApplication().replaceService(FilePathProvider::class.java, pathProvider, testRootDisposable) ApplicationManager.getApplication().replaceService(InstallationIdProvider::class.java, uidProvider, testRootDisposable) val loggerProvider = CompletionFileLoggerProvider() val logger = loggerProvider.newCompletionLogger() val editorMock = mock(Editor::class.java).apply { `when`(caretModel).thenReturn(mock(CaretModel::class.java)) } val lookup = mock(LookupImpl::class.java).apply { `when`(getRelevanceObjects(ArgumentMatchers.any(), ArgumentMatchers.anyBoolean())).thenReturn(emptyMap()) `when`(items).thenReturn(emptyList()) `when`(psiFile).thenReturn(null) `when`(editor).thenReturn(editorMock) } val watchService = FileSystems.getDefault().newWatchService() val key = dir.toPath().register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY) logger.completionStarted(lookup, true, 2, System.currentTimeMillis()) logger.completionCancelled(Fixtures.performance, System.currentTimeMillis()) loggerProvider.dispose() var attemps = 0 while (!logFile.exists() && attemps < 5) { watchService.poll(15, TimeUnit.SECONDS) attemps += 1 } key.cancel() watchService.close() assertThat(logFile.length()).isGreaterThan(fileLengthBefore) } }
plugins/stats-collector/test/com/intellij/stats/completion/FileLoggerTest.kt
3787216645
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.db.builders import java.rmi.UnexpectedException import slatekit.common.Types import slatekit.common.data.DataType import slatekit.common.data.DataTypeMap import slatekit.common.data.Encoding import slatekit.common.newline /** * Builds up database tables, indexes and other database components */ open class PostGresBuilder : DbBuilder { val types = listOf( DataTypeMap(DataType.DTString, "NVARCHAR", Types.JStringClass), DataTypeMap(DataType.DTBool, "BIT", Types.JBoolClass), DataTypeMap(DataType.DTShort, "TINYINT", Types.JStringClass), DataTypeMap(DataType.DTInt, "INTEGER", Types.JStringClass), DataTypeMap(DataType.DTLong, "BIGINT", Types.JStringClass), DataTypeMap(DataType.DTFloat, "FLOAT", Types.JStringClass), DataTypeMap(DataType.DTDouble, "DOUBLE", Types.JStringClass), DataTypeMap(DataType.DTDecimal, "DECIMAL", Types.JStringClass), DataTypeMap(DataType.DTLocalDate, "DATE", Types.JStringClass), DataTypeMap(DataType.DTLocalTime, "TIME", Types.JStringClass), DataTypeMap(DataType.DTLocalDateTime, "DATETIME", Types.JStringClass), DataTypeMap(DataType.DTZonedDateTime, "DATETIME", Types.JStringClass), DataTypeMap(DataType.DTInstant, "INSTANT", Types.JStringClass), DataTypeMap(DataType.DTDateTime, "DATETIME", Types.JStringClass) ) /** * Mapping of normalized types ot postgres type names */ val dataToColumnTypes = types.map { Pair(it.metaType, it.dbType) }.toMap() val langToDataTypes = types.map { Pair(it.langType, it.metaType) }.toMap() /** * Builds the drop table DDL for the name supplied. */ override fun dropTable(name: String): String = build(name, "DROP TABLE IF EXISTS") /** * Builds a delete statement to delete all rows */ override fun truncate(name: String): String = build(name, "DELETE FROM") /** * Builds an add column DDL sql statement */ override fun addCol(name: String, dataType: DataType, required: Boolean, maxLen: Int): String { val nullText = if (required) "NOT NULL" else "" val colType = colType(dataType, maxLen) val colName = colName(name) val sql = " $newline$colName $colType $nullText" return sql } /** * Builds a valid column name */ override fun colName(name: String): String = "`" + Encoding.ensureField(name) + "`" /** * Builds a valid column type */ override fun colType(colType: DataType, maxLen: Int): String { return if (colType == DataType.DTString && maxLen == -1) "longtext" else if (colType == DataType.DTString) "VARCHAR($maxLen)" else getColTypeName(colType) } private fun build(name: String, prefix: String): String { val tableName = Encoding.ensureField(name) val sql = "$prefix `$tableName`;" return sql } private fun getColTypeName(sqlType: DataType): String { return if (dataToColumnTypes.containsKey(sqlType)) dataToColumnTypes[sqlType] ?: "" else throw UnexpectedException("Unexpected db type : $sqlType") } }
src/lib/kotlin/slatekit-db/src/main/kotlin/slatekit/db/builders/PostGresBuilder.kt
2487138423
// 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.internal import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import com.google.common.hash.Hashing import com.google.common.io.Files import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.* import com.intellij.openapi.roots.OrderEntry import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.registry.Registry import com.intellij.util.indexing.IndexInfrastructureVersion import com.intellij.util.indexing.provided.SharedIndexChunkLocator import com.intellij.util.io.HttpRequests import org.jetbrains.annotations.TestOnly import org.tukaani.xz.XZInputStream import java.io.ByteArrayInputStream import java.io.File import java.io.IOException import java.nio.file.Path private object SharedIndexesCdn { private const val innerVersion = "v1" private val indexesCdnUrl get() = Registry.stringValue("shared.indexes.url").trimEnd('/') fun hashIndexUrls(request: SharedIndexRequest) = sequence { request.run { if (hash != null) { yield("$indexesCdnUrl/$innerVersion/$kind/$hash/index.json.xz") } for (alias in request.aliases) { yield("$indexesCdnUrl/$innerVersion/$kind/-$alias/index.json.xz") } //TODO[jo] remove prefix! for (alias in request.aliases) { yield("$indexesCdnUrl/$innerVersion/$kind/-$kind-$alias/index.json.xz") } } }.toList().distinct() } data class SharedIndexRequest( val kind: String, val hash: String? = null, val aliases: List<String> = listOf() ) data class SharedIndexInfo( val url: String, val sha256: String, val metadata: ObjectNode ) data class SharedIndexResult( val kind: String, val url: String, val sha256: String, val version: IndexInfrastructureVersion ) { val chunkUniqueId get() = "$kind-$sha256-${version.weakVersionHash}" override fun toString(): String = "SharedIndex sha=${sha256.take(8)}, wv=${version.weakVersionHash.take(8)}" } fun SharedIndexResult.toChunkDescriptor(sdkEntries: Collection<OrderEntry>) = object: SharedIndexChunkLocator.ChunkDescriptor { override fun getChunkUniqueId() = [email protected] override fun getSupportedInfrastructureVersion() = [email protected] override fun getOrderEntries() = sdkEntries override fun downloadChunk(targetFile: Path, indicator: ProgressIndicator) { SharedIndexesLoader.getInstance().downloadSharedIndex(this@toChunkDescriptor, indicator, targetFile.toFile()) } } class SharedIndexesLoader { private val LOG = logger<SharedIndexesLoader>() companion object { @JvmStatic fun getInstance() = service<SharedIndexesLoader>() } fun lookupSharedIndex(request: SharedIndexRequest, indicator: ProgressIndicator): SharedIndexResult? { indicator.text = "Looking for Shared Indexes..." val ourVersion = IndexInfrastructureVersion.getIdeVersion() for (entries in downloadIndexesList(request, indicator)) { indicator.checkCanceled() if (entries.isEmpty()) continue indicator.pushState() try { indicator.text = "Inspecting Shared Indexes..." val best = SharedIndexMetadata.selectBestSuitableIndex(ourVersion, entries) if (best == null) { LOG.info("No matching index found $request") continue } val (info, metadata) = best LOG.info("Selected index ${info} for $request") return SharedIndexResult(request.kind, info.url, info.sha256, metadata) } finally { indicator.popState() } } return null } fun downloadSharedIndex(info: SharedIndexResult, indicator: ProgressIndicator, targetFile: File) { val downloadFile = selectNewFileName(info, info.version, File(PathManager.getTempPath()), ".ijx.xz") indicator.text = "Downloading Shared Index..." indicator.checkCanceled() try { downloadSharedIndexXZ(info, downloadFile, indicator) indicator.text = "Unpacking Shared Index..." indicator.checkCanceled() unpackSharedIndexXZ(targetFile, downloadFile) } catch (t: Throwable) { FileUtil.delete(targetFile) throw t } finally { FileUtil.delete(downloadFile) } } private fun selectNewFileName(info: SharedIndexResult, version: IndexInfrastructureVersion, basePath: File, ext: String): File { var infix = 0 while (true) { val name = info.kind + "-" + info.sha256 + "-" + version.weakVersionHash + "-" + infix + ext val resultFile = File(basePath, name) if (!resultFile.isFile) { resultFile.parentFile?.mkdirs() return resultFile } infix++ } } fun selectIndexFileDestination(info: SharedIndexResult, version: IndexInfrastructureVersion) = selectNewFileName(info, version, File(PathManager.getSystemPath(), "shared-indexes"), ".ijx") @TestOnly fun downloadSharedIndexXZ(info: SharedIndexResult, downloadFile: File, indicator: ProgressIndicator?) { val url = info.url indicator?.pushState() indicator?.isIndeterminate = false try { try { HttpRequests.request(url) .productNameAsUserAgent() .saveToFile(downloadFile, indicator) } catch (t: IOException) { throw RuntimeException("Failed to download JDK from $url. ${t.message}", t) } val actualHashCode = Files.asByteSource(downloadFile).hash(Hashing.sha256()).toString() if (!actualHashCode.equals(info.sha256, ignoreCase = true)) { throw RuntimeException("SHA-256 checksums does not match. Actual value is $actualHashCode, expected ${info.sha256}") } } catch (e: Exception) { FileUtil.delete(downloadFile) if (e !is ProcessCanceledException) throw e } finally { indicator?.popState() } } @TestOnly fun unpackSharedIndexXZ(targetFile: File, downloadFile: File) { val bufferSize = 1024 * 1024 targetFile.parentFile?.mkdirs() targetFile.outputStream().use { out -> downloadFile.inputStream().buffered(bufferSize).use { input -> XZInputStream(input).use { it.copyTo(out, bufferSize) } } } } fun downloadIndexesList(request: SharedIndexRequest, indicator: ProgressIndicator? ): Sequence<List<SharedIndexInfo>> { val urls = SharedIndexesCdn.hashIndexUrls(request) return urls.asSequence().mapIndexedNotNull { idx, indexUrl -> indicator?.pushState() indicator?.text = when { urls.size > 1 -> "Looking for shared indexes (${idx + 1} of ${urls.size})" else -> "Looking for shared indexes" } val result = downloadIndexList(request, indexUrl, indicator) indicator?.popState() result } } private fun downloadIndexList(request: SharedIndexRequest, indexUrl: String, indicator: ProgressIndicator?) : List<SharedIndexInfo> { LOG.info("Checking index at $indexUrl...") val rawDataXZ = try { HttpRequests.request(indexUrl).throwStatusCodeException(true).readBytes(indicator) } catch (e: HttpRequests.HttpStatusException) { LOG.info("No indexes available for $request. ${e.message}", e) return listOf() } val rawData = try { ByteArrayInputStream(rawDataXZ).use { input -> XZInputStream(input).use { it.readBytes() } } } catch (e: Exception) { LOG.warn("Failed to unpack index data for $request. ${e.message}", e) return listOf() } LOG.info("Downloaded the $indexUrl...") val json = try { ObjectMapper().readTree(rawData) } catch (e: Exception) { LOG.warn("Failed to read index data JSON for $request. ${e.message}", e) return listOf() } val listVersion = json.get("list_version")?.asText() if (listVersion != "1") { LOG.warn("Index data version mismatch. The current version is $listVersion") return listOf() } val entries = (json.get("entries") as? ArrayNode) ?: run { LOG.warn("Index data format is incomplete. Missing 'entries' element") return listOf() } val indexes = entries.elements().asSequence().mapNotNull { node -> if (node !is ObjectNode) return@mapNotNull null val url = node.get("url")?.asText() ?: return@mapNotNull null val sha = node.get("sha256")?.asText() ?: return@mapNotNull null val data = (node.get("metadata") as? ObjectNode) ?: return@mapNotNull null SharedIndexInfo(url, sha, data) }.toList() LOG.info("Detected ${indexes.size} batches for the $request") if (indexes.isEmpty()) { LOG.info("No indexes found $request") } return indexes } }
java/idea-ui/src/com/intellij/internal/SharedIndexesLoader.kt
1586379191
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* import kotlin.test.assertEquals suspend fun suspendHere(): String = suspendCoroutineOrReturn { x -> x.resume("OK") COROUTINE_SUSPENDED } suspend fun suspendWithException(): String = suspendCoroutineOrReturn { x -> x.resumeWithException(RuntimeException("OK")) COROUTINE_SUSPENDED } fun builder(shouldSuspend: Boolean, expectedCount: Int, c: suspend () -> String): String { var fromSuspension: String? = null var counter = 0 val result = try { c.startCoroutineUninterceptedOrReturn(object: Continuation<String> { override val context: CoroutineContext get() = ContinuationDispatcher { counter++ } override fun resumeWithException(exception: Throwable) { fromSuspension = "Exception: " + exception.message!! } override fun resume(value: String) { fromSuspension = value } }) } catch (e: Exception) { "Exception: ${e.message}" } if (counter != expectedCount) throw RuntimeException("fail 0") if (shouldSuspend) { if (result !== COROUTINE_SUSPENDED) throw RuntimeException("fail 1") if (fromSuspension == null) throw RuntimeException("fail 2") return fromSuspension!! } if (result === COROUTINE_SUSPENDED) throw RuntimeException("fail 3") return result as String } class ContinuationDispatcher(val dispatcher: () -> Unit) : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor { override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> = DispatchedContinuation(dispatcher, continuation) } private class DispatchedContinuation<T>( val dispatcher: () -> Unit, val continuation: Continuation<T> ): Continuation<T> { override val context: CoroutineContext = continuation.context override fun resume(value: T) { dispatcher() continuation.resume(value) } override fun resumeWithException(exception: Throwable) { dispatcher() continuation.resumeWithException(exception) } } fun box(): String { if (builder(false, 0) { "OK" } != "OK") return "fail 4" if (builder(true, 1) { suspendHere() } != "OK") return "fail 5" if (builder(false, 0) { throw RuntimeException("OK") } != "Exception: OK") return "fail 6" if (builder(true, 1) { suspendWithException() } != "Exception: OK") return "fail 7" return "OK" }
backend.native/tests/external/codegen/box/coroutines/intrinsicSemantics/startCoroutineUninterceptedOrReturnInterception.kt
320751056
// WITH_RUNTIME // WITH_COROUTINES // FILE: stuff.kt package stuff import helpers.* import kotlin.coroutines.experimental.intrinsics.* object Host { suspend fun suspendHere(): String = suspendCoroutineOrReturn { x -> x.resume("OK") COROUTINE_SUSPENDED } } // FILE: test.kt import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* import stuff.Host.suspendHere fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var result = "" builder { result = suspendHere() } return result }
backend.native/tests/external/codegen/box/coroutines/suspendFunImportedFromObject.kt
1302866825
// IGNORE_BACKEND: JVM, JS, NATIVE // Here we check that there is compilation error, so ignore_backend directive is actual @Target(AnnotationTarget.FIELD, AnnotationTarget.CLASS) annotation class Anno class UnresolvedArgument(@Anno(BLA) val s: Int) class WithoutArguments(@Deprecated val s: Int) fun box(): String { UnresolvedArgument(3) WithoutArguments(0) return "OK" }
backend.native/tests/external/codegen/box/annotations/wrongAnnotationArgumentInCtor.kt
203425416
package abi43_0_0.expo.modules.imagemanipulator import android.content.Context import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.util.Base64 import abi43_0_0.expo.modules.imagemanipulator.arguments.Actions import abi43_0_0.expo.modules.imagemanipulator.arguments.SaveOptions import abi43_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface import abi43_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface.ResultListener import abi43_0_0.expo.modules.core.ExportedModule import abi43_0_0.expo.modules.core.ModuleRegistry import abi43_0_0.expo.modules.core.ModuleRegistryDelegate import abi43_0_0.expo.modules.core.Promise import abi43_0_0.expo.modules.core.arguments.ReadableArguments import abi43_0_0.expo.modules.core.interfaces.ExpoMethod import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.util.* private const val TAG = "ExpoImageManipulator" private const val ERROR_TAG = "E_IMAGE_MANIPULATOR" class ImageManipulatorModule( context: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ExportedModule(context) { private val mImageLoader: ImageLoaderInterface by moduleRegistry() private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() override fun getName() = TAG override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } @ExpoMethod fun manipulateAsync(uri: String, actionsRaw: ArrayList<Any?>, saveOptionsRaw: ReadableArguments, promise: Promise) { val saveOptions = SaveOptions.fromArguments(saveOptionsRaw) val actions = Actions.fromArgument(actionsRaw) mImageLoader.loadImageForManipulationFromURL( uri, object : ResultListener { override fun onSuccess(bitmap: Bitmap) { runActions(bitmap, actions, saveOptions, promise) } override fun onFailure(cause: Throwable?) { // No cleanup required here. val basicMessage = "Could not get decoded bitmap of $uri" if (cause != null) { promise.reject("${ERROR_TAG}_DECODE", "$basicMessage: $cause", cause) } else { promise.reject("${ERROR_TAG}_DECODE", "$basicMessage.") } } } ) } private fun runActions(bitmap: Bitmap, actions: Actions, saveOptions: SaveOptions, promise: Promise) { val resultBitmap = actions.actions.fold(bitmap, { acc, action -> action.run(acc) }) val path = FileUtils.generateRandomOutputPath(context, saveOptions.format) val compression = (saveOptions.compress * 100).toInt() var base64String: String? = null FileOutputStream(path).use { fileOut -> resultBitmap.compress(saveOptions.format, compression, fileOut) if (saveOptions.base64) { ByteArrayOutputStream().use { byteOut -> resultBitmap.compress(saveOptions.format, compression, byteOut) base64String = Base64.encodeToString(byteOut.toByteArray(), Base64.NO_WRAP) } } } val result = Bundle().apply { putString("uri", Uri.fromFile(File(path)).toString()) putInt("width", resultBitmap.width) putInt("height", resultBitmap.height) if (base64String != null) { putString("base64", base64String) } } promise.resolve(result) } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/imagemanipulator/ImageManipulatorModule.kt
4003447772
import Main.Companion.next import Main.Companion.hasNext import Main.Companion.iterator fun test() { for (i in 42) { } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/fromObject/fromCompanion/operators/next/Implicit.kt
2024963148
// "Create actual function for module fullStackWebApplication.jvmMain (JVM)" "true" // ACTION: Convert function to property package my.project.pack expect fun isJs(): Boolean
plugins/kotlin/idea/tests/testData/gradle/fixes/createActualForJvm/after/src/commonMain/kotlin/my.project.pack/JsUtils.kt
3139207328
package testing class Some : NewName() { val test = NewName() fun testFun(param : NewName) : NewName { return test; } }
plugins/kotlin/idea/tests/testData/refactoring/rename/renameJavaClassSamePackage/after/RenameJavaClassSamePackage.kt
3815277872
// SUGGESTED_NAMES: i, getY fun foo() { val x = 1 + 1 val y = <selection>1 + 1</selection> }
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/duplicates/insertBeforeDuplicates.kt
2301939542
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeIntention import org.jetbrains.kotlin.idea.intentions.isSetterParameter import org.jetbrains.kotlin.psi.parameterVisitor import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class RemoveSetterParameterTypeInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return parameterVisitor { parameter -> val typeReference = parameter.takeIf { it.isSetterParameter } ?.typeReference ?.takeIf { it.endOffset > it.startOffset } ?: return@parameterVisitor holder.registerProblem( typeReference, KotlinBundle.message("redundant.setter.parameter.type"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, IntentionWrapper(RemoveExplicitTypeIntention()) ) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveSetterParameterTypeInspection.kt
1098479182