content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
// "Add parameter to function 'foo'" "true" // ERROR: Too many arguments for public fun foo(): Unit defined in b in file addParameterWithImport.before.Dependency.kt package a import b.foo class Bar fun test() { foo(Bar()) }
plugins/kotlin/idea/tests/testData/quickfix/changeSignature/addParameterWithImport.after.kt
3992747198
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix.crossLanguage import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.lang.jvm.actions.AnnotationRequest import com.intellij.lang.jvm.actions.ChangeParametersRequest import com.intellij.lang.jvm.actions.ExpectedParameter import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.JvmPsiConversionHelper import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.SourceElement import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.resolveToKotlinType import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType internal class ChangeMethodParameters( target: KtNamedFunction, val request: ChangeParametersRequest ) : KotlinQuickFixAction<KtNamedFunction>(target) { override fun getText(): String { val target = element ?: return KotlinBundle.message("fix.change.signature.unavailable") val helper = JvmPsiConversionHelper.getInstance(target.project) val parametersString = request.expectedParameters.joinToString(", ", "(", ")") { ep -> val kotlinType = ep.expectedTypes.firstOrNull()?.theType?.let { helper.convertType(it).resolveToKotlinType(target.getResolutionFacade()) } val parameterName = ep.semanticNames.firstOrNull() ?: KotlinBundle.message("fix.change.signature.unnamed.parameter") "$parameterName: ${kotlinType?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it) } ?: KotlinBundle.message("fix.change.signature.error")}" } val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5) return QuickFixBundle.message("change.method.parameters.text", shortenParameterString) } override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family") override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && request.isValid private sealed class ParameterModification { data class Keep(val ktParameter: KtParameter) : ParameterModification() data class Remove(val ktParameter: KtParameter) : ParameterModification() data class Add( val name: String, val ktType: KotlinType, val expectedAnnotations: Collection<AnnotationRequest>, val beforeAnchor: KtParameter? ) : ParameterModification() } private tailrec fun getParametersModifications( target: KtNamedFunction, currentParameters: List<KtParameter>, expectedParameters: List<ExpectedParameter>, index: Int = 0, collected: List<ParameterModification> = ArrayList(expectedParameters.size) ): List<ParameterModification> { val expectedHead = expectedParameters.firstOrNull() ?: return collected + currentParameters.map { ParameterModification.Remove(it) } if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) { val expectedExistingParameter = expectedHead.existingKtParameter if (expectedExistingParameter == null) { LOG.error("can't find the kotlinOrigin for parameter ${expectedHead.existingParameter} at index $index") return collected } val existingInTail = currentParameters.indexOf(expectedExistingParameter) if (existingInTail == -1) { throw IllegalArgumentException("can't find existing for parameter ${expectedHead.existingParameter} at index $index") } return getParametersModifications( target, currentParameters.subList(existingInTail + 1, currentParameters.size), expectedParameters.subList(1, expectedParameters.size), index, collected + currentParameters.subList(0, existingInTail).map { ParameterModification.Remove(it) } + ParameterModification.Keep(expectedExistingParameter) ) } val helper = JvmPsiConversionHelper.getInstance(target.project) val theType = expectedHead.expectedTypes.firstOrNull()?.theType ?: return emptyList() val kotlinType = helper.convertType(theType).resolveToKotlinType(target.getResolutionFacade()) ?: return emptyList() return getParametersModifications( target, currentParameters, expectedParameters.subList(1, expectedParameters.size), index + 1, collected + ParameterModification.Add( expectedHead.semanticNames.firstOrNull() ?: "param$index", kotlinType, expectedHead.expectedAnnotations, currentParameters.firstOrNull { anchor -> expectedParameters.any { it is ChangeParametersRequest.ExistingParameterWrapper && it.existingKtParameter == anchor } }) ) } private val ChangeParametersRequest.ExistingParameterWrapper.existingKtParameter get() = (existingParameter as? KtLightElement<*, *>)?.kotlinOrigin as? KtParameter override fun invoke(project: Project, editor: Editor?, file: KtFile) { if (!request.isValid) return val target = element ?: return val functionDescriptor = target.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return val parameterActions = getParametersModifications(target, target.valueParameters, request.expectedParameters) val parametersGenerated = parameterActions.filterIsInstance<ParameterModification.Add>().let { it zip generateParameterList(project, functionDescriptor, it).parameters }.toMap() for (action in parameterActions) { when (action) { is ParameterModification.Add -> { val parameter = parametersGenerated.getValue(action) for (expectedAnnotation in action.expectedAnnotations.reversed()) { addAnnotationEntry(parameter, expectedAnnotation, null) } val anchor = action.beforeAnchor if (anchor != null) { target.valueParameterList!!.addParameterBefore(parameter, anchor) } else { target.valueParameterList!!.addParameter(parameter) } } is ParameterModification.Keep -> { // Do nothing } is ParameterModification.Remove -> { target.valueParameterList!!.removeParameter(action.ktParameter) } } } ShortenReferences.DEFAULT.process(target.valueParameterList!!) } private fun generateParameterList( project: Project, functionDescriptor: FunctionDescriptor, paramsToAdd: List<ParameterModification.Add> ): KtParameterList { val newFunctionDescriptor = SimpleFunctionDescriptorImpl.create( functionDescriptor.containingDeclaration, functionDescriptor.annotations, functionDescriptor.name, functionDescriptor.kind, SourceElement.NO_SOURCE ).apply { initialize( functionDescriptor.extensionReceiverParameter?.copy(this), functionDescriptor.dispatchReceiverParameter, functionDescriptor.contextReceiverParameters.map { it.copy(this) }, functionDescriptor.typeParameters, paramsToAdd.mapIndexed { index, parameter -> ValueParameterDescriptorImpl( this, null, index, Annotations.EMPTY, Name.identifier(parameter.name), parameter.ktType, declaresDefaultValue = false, isCrossinline = false, isNoinline = false, varargElementType = null, source = SourceElement.NO_SOURCE ) }, functionDescriptor.returnType, functionDescriptor.modality, functionDescriptor.visibility ) } val renderer = IdeDescriptorRenderers.SOURCE_CODE.withOptions { defaultParameterValueRenderer = null } val newFunction = KtPsiFactory(project).createFunction(renderer.render(newFunctionDescriptor)).apply { valueParameters.forEach { param -> param.annotationEntries.forEach { a -> a.typeReference?.run { val fqName = FqName(this.text) if (fqName in (NULLABLE_ANNOTATIONS + NOT_NULL_ANNOTATIONS)) a.delete() } } } } return newFunction.valueParameterList!! } companion object { fun create(ktNamedFunction: KtNamedFunction, request: ChangeParametersRequest): ChangeMethodParameters = ChangeMethodParameters(ktNamedFunction, request) private val LOG = Logger.getInstance(ChangeMethodParameters::class.java) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt
3273538843
/* * 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.internal.statistic import com.intellij.internal.statistic.beans.GroupDescriptor import com.intellij.internal.statistic.beans.UsageDescriptor import java.lang.management.ManagementFactory /** * @author Konstantin Bulenkov */ class JdkSettingsUsageCollector: UsagesCollector() { override fun getUsages(): Set<UsageDescriptor> { return ManagementFactory.getRuntimeMXBean().inputArguments .map { s -> hideUserPath(s) } .map { s -> UsageDescriptor(s) } .toSet() } val keysWithPath = arrayOf("-Didea.home.path", "-Didea.launcher.bin.path", "-Didea.plugins.path", "-Xbootclasspath", "-Djb.vmOptionsFile", "-XX ErrorFile", "-XX HeapDumpPath", " -Didea.launcher.bin.path", "-agentlib:jdwp") private fun hideUserPath(key: String): String { @Suppress("LoopToCallChain") for (s in keysWithPath) { if (key.startsWith(s)) return "$s ..." } return key } override fun getGroupId(): GroupDescriptor { return GroupDescriptor.create("user.jdk.settings") } }
platform/platform-impl/src/com/intellij/internal/statistic/JdkSettingsUsageCollector.kt
2426078245
/* * Copyright (c) 2021. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, you may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.pdvrieze.jdbc.recorder import io.github.pdvrieze.jdbc.recorder.actions.ResultSetClose import io.github.pdvrieze.jdbc.recorder.actions.StringAction import java.io.InputStream import java.io.Reader import java.lang.Exception import java.math.BigDecimal import java.net.URL import java.sql.* import java.sql.Array as SqlArray import java.sql.Date import java.util.* abstract class AbstractRecordingResultSet( delegate: ResultSet, val query: String ) : WrappingActionRecorder<ResultSet>(delegate), ResultSet { protected val columnNames = arrayOfNulls<String>(delegate.metaData.columnCount) protected inline fun <R> recordGet(columnNo: Int, crossinline action: () -> R): R { return action().also { val p = columnNames[columnNo-1]?.let { n -> "$columnNo ~> $n"} ?: columnNo.toString() recordRes3(it, p) } } protected inline fun <R> recordGet(columnNo: Int, arg2: Any?, crossinline action: () -> R): R { return action().also { val p = columnNames[columnNo-1]?.let { n -> "$columnNo ~> $n"} ?: columnNo.toString() recordRes3(it, p, arg2) } } protected fun <R> recordRes3(result: R, columnIndex: String, arg2: Any? = Unit): R { val calledFunction = Exception().stackTrace[2].methodName val arg2s = if (arg2==Unit) "" else ", ${arg2.stringify()}" val ac = when { result == Unit -> StringAction("$this.$calledFunction($columnIndex$arg2s)") else -> StringAction("$this.$calledFunction($columnIndex$arg2s) -> ${result.stringify()}") } recordAction(ac) return result } protected fun recordUpdate(columnNo: Int, vararg args: Any?) { val p = columnNames[columnNo-1]?.let { n -> "$columnNo -> $n"} ?: columnNo.toString() val calledFunction = Exception().stackTrace[1].methodName val ac = StringAction("$this.$calledFunction($p, ${args.joinToString()})") recordAction(ac) } override fun absolute(row: Int): Boolean = record(row) { delegate.absolute(row) } override fun afterLast() { record() delegate.afterLast() } override fun beforeFirst() { record() delegate.beforeFirst() } override fun cancelRowUpdates() { record() delegate.cancelRowUpdates() } override fun clearWarnings() { record() delegate.clearWarnings() } override fun close() { recordAction(ResultSetClose) } override fun deleteRow() { record() delegate.deleteRow() } override fun findColumn(columnLabel: String): Int = record(columnLabel) { delegate.findColumn(columnLabel).also { columnNames[it-1] = columnLabel } } override fun first(): Boolean = record { delegate.first() } override fun getArray(columnIndex: Int): SqlArray = recordGet(columnIndex) { delegate.getArray(columnIndex) } override fun getArray(columnLabel: String?): SqlArray = record(columnLabel) { delegate.getArray(columnLabel) } override fun getAsciiStream(columnIndex: Int): InputStream = recordGet(columnIndex) { delegate.getAsciiStream(columnIndex) } override fun getAsciiStream(columnLabel: String?): InputStream = record(columnLabel) { delegate.getAsciiStream(columnLabel) } override fun getBigDecimal(columnIndex: Int, scale: Int): BigDecimal = recordGet(columnIndex, scale) { @Suppress("DEPRECATION") delegate.getBigDecimal(columnIndex, scale) } override fun getBigDecimal(columnLabel: String?, scale: Int): BigDecimal = record(columnLabel, scale) { @Suppress("DEPRECATION") delegate.getBigDecimal(columnLabel, scale) } override fun getBigDecimal(columnIndex: Int): BigDecimal = recordGet(columnIndex) { delegate.getBigDecimal(columnIndex) } override fun getBigDecimal(columnLabel: String?): BigDecimal = record(columnLabel) { delegate.getBigDecimal(columnLabel) } override fun getBinaryStream(columnIndex: Int): InputStream = recordGet(columnIndex) { delegate.getBinaryStream(columnIndex) } override fun getBinaryStream(columnLabel: String?): InputStream = record(columnLabel) { delegate.getBinaryStream(columnLabel) } override fun getBlob(columnIndex: Int): Blob = recordGet(columnIndex) { delegate.getBlob(columnIndex) } override fun getBlob(columnLabel: String?): Blob = record(columnLabel) { delegate.getBlob(columnLabel) } override fun getBoolean(columnIndex: Int): Boolean = recordGet(columnIndex) { delegate.getBoolean(columnIndex) } override fun getBoolean(columnLabel: String?): Boolean = record(columnLabel) { delegate.getBoolean(columnLabel) } override fun getByte(columnIndex: Int): Byte = recordGet(columnIndex) { delegate.getByte(columnIndex) } override fun getByte(columnLabel: String?): Byte = record(columnLabel) { delegate.getByte(columnLabel) } override fun getBytes(columnIndex: Int): ByteArray = recordGet(columnIndex) { delegate.getBytes(columnIndex) } override fun getBytes(columnLabel: String?): ByteArray = record(columnLabel) { delegate.getBytes(columnLabel) } override fun getCharacterStream(columnIndex: Int): Reader = recordGet(columnIndex) { delegate.getCharacterStream(columnIndex) } override fun getCharacterStream(columnLabel: String?): Reader = record(columnLabel) { delegate.getCharacterStream(columnLabel) } override fun getClob(columnIndex: Int): Clob = recordGet(columnIndex) { delegate.getClob(columnIndex) } override fun getClob(columnLabel: String?): Clob = record(columnLabel) { delegate.getClob(columnLabel) } override fun getConcurrency(): Int = record { delegate.concurrency } override fun getCursorName(): String = record { delegate.cursorName } override fun getDate(columnIndex: Int): Date = recordGet(columnIndex) { delegate.getDate(columnIndex) } override fun getDate(columnLabel: String?): Date = record(columnLabel) { delegate.getDate(columnLabel) } override fun getDate(columnIndex: Int, cal: Calendar?): Date = recordGet(columnIndex, cal) { delegate.getDate(columnIndex, cal) } override fun getDate(columnLabel: String?, cal: Calendar?): Date = record(columnLabel, cal) { delegate.getDate(columnLabel, cal) } override fun getDouble(columnIndex: Int): Double = recordGet(columnIndex) { delegate.getDouble(columnIndex) } override fun getDouble(columnLabel: String?): Double = record(columnLabel) { delegate.getDouble(columnLabel) } override fun getFetchDirection(): Int = record { delegate.fetchDirection } override fun getFetchSize(): Int = record { delegate.fetchSize } override fun getFloat(columnIndex: Int): Float = recordGet(columnIndex) { delegate.getFloat(columnIndex) } override fun getFloat(columnLabel: String?): Float = record(columnLabel) { delegate.getFloat(columnLabel) } override fun getHoldability(): Int = record { delegate.holdability } override fun getInt(columnIndex: Int): Int = recordGet(columnIndex) { delegate.getInt(columnIndex) } override fun getInt(columnLabel: String): Int = record(columnLabel){ delegate.getInt(columnLabel) } override fun getLong(columnIndex: Int): Long = recordGet(columnIndex) { delegate.getLong(columnIndex) } override fun getLong(columnLabel: String?): Long = record(columnLabel) { delegate.getLong(columnLabel) } abstract override fun getMetaData(): AbstractRecordingResultsetMetaData override fun getNCharacterStream(columnIndex: Int): Reader = recordGet(columnIndex) { delegate.getNCharacterStream(columnIndex) } override fun getNCharacterStream(columnLabel: String?): Reader = record(columnLabel) { delegate.getNCharacterStream(columnLabel) } override fun getNClob(columnIndex: Int): NClob = recordGet(columnIndex) { delegate.getNClob(columnIndex) } override fun getNClob(columnLabel: String?): NClob = record(columnLabel) { delegate.getNClob(columnLabel) } override fun getNString(columnIndex: Int): String = recordGet(columnIndex) { delegate.getNString(columnIndex) } override fun getNString(columnLabel: String?): String = record(columnLabel) { delegate.getNString(columnLabel) } override fun getObject(columnIndex: Int): Any = recordGet(columnIndex) { delegate.getObject(columnIndex) } override fun getObject(columnLabel: String?): Any = record(columnLabel) { delegate.getObject(columnLabel) } override fun getObject(columnIndex: Int, map: MutableMap<String, Class<*>>): Any = recordGet(columnIndex, map) { delegate.getObject(columnIndex, map) } override fun getObject(columnLabel: String?, map: MutableMap<String, Class<*>>): Any = record(columnLabel, map) { delegate.getObject(columnLabel, map) } override fun <T : Any?> getObject(columnIndex: Int, type: Class<T>?): T = recordGet(columnIndex, type) { delegate.getObject(columnIndex, type) } override fun <T : Any?> getObject(columnLabel: String?, type: Class<T>?): T = record(columnLabel, type) { delegate.getObject(columnLabel, type) } override fun getRef(columnIndex: Int): Ref = recordGet(columnIndex) { delegate.getRef(columnIndex) } override fun getRef(columnLabel: String?): Ref = record(columnLabel) { delegate.getRef(columnLabel) } override fun getRow(): Int = record { delegate.row } override fun getRowId(columnIndex: Int): RowId = recordGet(columnIndex) { delegate.getRowId(columnIndex) } override fun getRowId(columnLabel: String?): RowId = record(columnLabel) { delegate.getRowId(columnLabel) } override fun getShort(columnIndex: Int): Short = recordGet(columnIndex) { delegate.getShort(columnIndex) } override fun getShort(columnLabel: String?): Short = record(columnLabel) { delegate.getShort(columnLabel) } override fun getSQLXML(columnIndex: Int): SQLXML = recordGet(columnIndex) { delegate.getSQLXML(columnIndex) } override fun getSQLXML(columnLabel: String?): SQLXML = record(columnLabel) { delegate.getSQLXML(columnLabel) } override fun getStatement(): Statement = record { delegate.statement } override fun getString(columnIndex: Int): String? = recordGet(columnIndex) { delegate.getString(columnIndex) } override fun getString(columnLabel: String): String? = record { delegate.getString(columnLabel) } override fun getTime(columnIndex: Int): Time = recordGet(columnIndex) { delegate.getTime(columnIndex) } override fun getTime(columnLabel: String?): Time = record(columnLabel) { delegate.getTime(columnLabel) } override fun getTime(columnIndex: Int, cal: Calendar?): Time = recordGet(columnIndex, cal) { delegate.getTime(columnIndex, cal) } override fun getTime(columnLabel: String?, cal: Calendar?): Time = record(columnLabel, cal) { delegate.getTime(columnLabel, cal) } override fun getTimestamp(columnIndex: Int): Timestamp = recordGet(columnIndex) { delegate.getTimestamp(columnIndex) } override fun getTimestamp(columnLabel: String?): Timestamp = record(columnLabel) { delegate.getTimestamp(columnLabel) } override fun getTimestamp(columnIndex: Int, cal: Calendar?): Timestamp = recordGet(columnIndex, cal) { delegate.getTimestamp(columnIndex, cal) } override fun getTimestamp(columnLabel: String?, cal: Calendar?): Timestamp = record(columnLabel, cal) { delegate.getTimestamp(columnLabel, cal) } override fun getType(): Int = record { delegate.type } override fun getUnicodeStream(columnIndex: Int): InputStream = recordGet(columnIndex) { @Suppress("DEPRECATION") delegate.getUnicodeStream(columnIndex) } override fun getUnicodeStream(columnLabel: String?): InputStream = record(columnLabel) { @Suppress("DEPRECATION") delegate.getUnicodeStream(columnLabel) } override fun getURL(columnIndex: Int): URL = recordGet(columnIndex) { delegate.getURL(columnIndex) } override fun getURL(columnLabel: String?): URL = record(columnLabel) { delegate.getURL(columnLabel) } override fun getWarnings(): SQLWarning = record { delegate.warnings } override fun insertRow() { record() delegate.insertRow() } override fun isAfterLast(): Boolean = record { delegate.isAfterLast } override fun isBeforeFirst(): Boolean = record { delegate.isBeforeFirst } override fun isClosed(): Boolean = record { delegate.isClosed } override fun isFirst(): Boolean = record { delegate.isFirst } override fun isLast(): Boolean = record { delegate.isLast } override fun last(): Boolean = record { delegate.last() } override fun moveToCurrentRow() { record() delegate.moveToCurrentRow() } override fun moveToInsertRow() { record() delegate.moveToInsertRow() } override fun relative(rows: Int): Boolean = record(rows) { delegate.relative(rows) } override fun next(): Boolean = record { delegate.next() } override fun previous(): Boolean = record { delegate.previous() } override fun refreshRow() { record() delegate.refreshRow() } override fun rowDeleted(): Boolean = record { delegate.rowDeleted() } override fun rowInserted(): Boolean = record { delegate.rowInserted() } override fun rowUpdated(): Boolean = record { delegate.rowUpdated() } override fun setFetchDirection(direction: Int) { record(direction) delegate.fetchDirection = direction } override fun setFetchSize(rows: Int) { record(rows) delegate.fetchSize = rows } override fun updateArray(columnIndex: Int, x: SqlArray?) { recordUpdate(columnIndex, x) delegate.updateArray(columnIndex, x) } override fun updateArray(columnLabel: String?, x: SqlArray?) { record(columnLabel, x) delegate.updateArray(columnLabel, x) } override fun updateAsciiStream(columnIndex: Int, x: InputStream?, length: Int) { recordUpdate(columnIndex, x, length) delegate.updateAsciiStream(columnIndex, x, length) } override fun updateAsciiStream(columnLabel: String?, x: InputStream?, length: Int) { record(columnLabel, x, length) delegate.updateAsciiStream(columnLabel, x, length) } override fun updateAsciiStream(columnIndex: Int, x: InputStream?, length: Long) { recordUpdate(columnIndex, x, length) delegate.updateAsciiStream(columnIndex, x, length) } override fun updateAsciiStream(columnLabel: String?, x: InputStream?, length: Long) { record(columnLabel, x, length) delegate.updateAsciiStream(columnLabel, x, length) } override fun updateAsciiStream(columnIndex: Int, x: InputStream?) { recordUpdate(columnIndex, x) delegate.updateAsciiStream(columnIndex, x) } override fun updateAsciiStream(columnLabel: String?, x: InputStream?) { record(columnLabel, x) delegate.updateAsciiStream(columnLabel, x) } override fun updateBigDecimal(columnIndex: Int, x: BigDecimal?) { recordUpdate(columnIndex, x) delegate.updateBigDecimal(columnIndex, x) } override fun updateBigDecimal(columnLabel: String?, x: BigDecimal?) { record(columnLabel, x) delegate.updateBigDecimal(columnLabel, x) } override fun updateBinaryStream(columnIndex: Int, x: InputStream?, length: Int) { recordUpdate(columnIndex, x, length) delegate.updateBinaryStream(columnIndex, x, length) } override fun updateBinaryStream(columnLabel: String?, x: InputStream?, length: Int) { record(columnLabel, x, length) delegate.updateBinaryStream(columnLabel, x, length) } override fun updateBinaryStream(columnIndex: Int, x: InputStream?, length: Long) { recordUpdate(columnIndex, x, length) delegate.updateBinaryStream(columnIndex, x, length) } override fun updateBinaryStream(columnLabel: String?, x: InputStream?, length: Long) { record(columnLabel, x, length) delegate.updateBinaryStream(columnLabel, x, length) } override fun updateBinaryStream(columnIndex: Int, x: InputStream?) { recordUpdate(columnIndex, x) delegate.updateBinaryStream(columnIndex, x) } override fun updateBinaryStream(columnLabel: String?, x: InputStream?) { record(columnLabel, x) delegate.updateBinaryStream(columnLabel, x) } override fun updateBlob(columnIndex: Int, x: Blob?) { recordUpdate(columnIndex, x) delegate.updateBlob(columnIndex, x) } override fun updateBlob(columnLabel: String?, x: Blob?) { record(columnLabel, x) delegate.updateBlob(columnLabel, x) } override fun updateBlob(columnIndex: Int, inputStream: InputStream?, length: Long) { recordUpdate(columnIndex, inputStream, length) delegate.updateBlob(columnIndex, inputStream, length) } override fun updateBlob(columnLabel: String?, inputStream: InputStream?, length: Long) { record(columnLabel, inputStream, length) delegate.updateBlob(columnLabel, inputStream, length) } override fun updateBlob(columnIndex: Int, inputStream: InputStream?) { recordUpdate(columnIndex, inputStream) delegate.updateBlob(columnIndex, inputStream) } override fun updateBlob(columnLabel: String?, inputStream: InputStream?) { record(columnLabel, inputStream) delegate.updateBlob(columnLabel, inputStream) } override fun updateBoolean(columnIndex: Int, x: Boolean) { recordUpdate(columnIndex, x) delegate.updateBoolean(columnIndex, x) } override fun updateBoolean(columnLabel: String?, x: Boolean) { record(columnLabel, x) delegate.updateBoolean(columnLabel, x) } override fun updateByte(columnIndex: Int, x: Byte) { recordUpdate(columnIndex, x) delegate.updateByte(columnIndex, x) } override fun updateByte(columnLabel: String?, x: Byte) { record(columnLabel, x) delegate.updateByte(columnLabel, x) } override fun updateBytes(columnIndex: Int, x: ByteArray?) { recordUpdate(columnIndex, x) delegate.updateBytes(columnIndex, x) } override fun updateBytes(columnLabel: String?, x: ByteArray?) { record(columnLabel, x) delegate.updateBytes(columnLabel, x) } override fun updateCharacterStream(columnIndex: Int, x: Reader?, length: Int) { recordUpdate(columnIndex, x, length) delegate.updateCharacterStream(columnIndex, x, length) } override fun updateCharacterStream(columnLabel: String?, reader: Reader?, length: Int) { record(columnLabel, reader, length) delegate.updateCharacterStream(columnLabel, reader, length) } override fun updateCharacterStream(columnIndex: Int, x: Reader?, length: Long) { recordUpdate(columnIndex, x, length) delegate.updateCharacterStream(columnIndex, x, length) } override fun updateCharacterStream(columnLabel: String?, reader: Reader?, length: Long) { record(columnLabel, reader, length) delegate.updateCharacterStream(columnLabel, reader, length) } override fun updateCharacterStream(columnIndex: Int, x: Reader?) { recordUpdate(columnIndex, x) delegate.updateCharacterStream(columnIndex, x) } override fun updateCharacterStream(columnLabel: String?, reader: Reader?) { record(columnLabel, reader) delegate.updateCharacterStream(columnLabel, reader) } override fun updateClob(columnIndex: Int, x: Clob?) { recordUpdate(columnIndex, x) delegate.updateClob(columnIndex, x) } override fun updateClob(columnLabel: String?, x: Clob?) { record(columnLabel, x) delegate.updateClob(columnLabel, x) } override fun updateClob(columnIndex: Int, reader: Reader?, length: Long) { recordUpdate(columnIndex, reader, length) delegate.updateClob(columnIndex, reader, length) } override fun updateClob(columnLabel: String?, reader: Reader?, length: Long) { record(columnLabel, reader, length) delegate.updateClob(columnLabel, reader, length) } override fun updateClob(columnIndex: Int, reader: Reader?) { recordUpdate(columnIndex, reader) delegate.updateClob(columnIndex, reader) } override fun updateClob(columnLabel: String?, reader: Reader?) { record(columnLabel, reader) delegate.updateClob(columnLabel, reader) } override fun updateDate(columnIndex: Int, x: Date?) { recordUpdate(columnIndex, x) delegate.updateDate(columnIndex, x) } override fun updateDate(columnLabel: String?, x: Date?) { record(columnLabel, x) delegate.updateDate(columnLabel, x) } override fun updateDouble(columnIndex: Int, x: Double) { recordUpdate(columnIndex, x) delegate.updateDouble(columnIndex, x) } override fun updateDouble(columnLabel: String?, x: Double) { record(columnLabel, x) delegate.updateDouble(columnLabel, x) } override fun updateFloat(columnIndex: Int, x: Float) { recordUpdate(columnIndex, x) delegate.updateFloat(columnIndex, x) } override fun updateFloat(columnLabel: String?, x: Float) { record(columnLabel, x) delegate.updateFloat(columnLabel, x) } override fun updateInt(columnIndex: Int, x: Int) { recordUpdate(columnIndex, x) delegate.updateInt(columnIndex, x) } override fun updateInt(columnLabel: String?, x: Int) { record(columnLabel, x) delegate.updateInt(columnLabel, x) } override fun updateLong(columnIndex: Int, x: Long) { recordUpdate(columnIndex, x) delegate.updateLong(columnIndex, x) } override fun updateLong(columnLabel: String?, x: Long) { record(columnLabel, x) delegate.updateLong(columnLabel, x) } override fun updateNCharacterStream(columnIndex: Int, x: Reader?, length: Long) { recordUpdate(columnIndex, x, length) delegate.updateNCharacterStream(columnIndex, x, length) } override fun updateNCharacterStream(columnLabel: String?, reader: Reader?, length: Long) { record(columnLabel, reader, length) delegate.updateNCharacterStream(columnLabel, reader, length) } override fun updateNCharacterStream(columnIndex: Int, x: Reader?) { recordUpdate(columnIndex, x) delegate.updateNCharacterStream(columnIndex, x) } override fun updateNCharacterStream(columnLabel: String?, reader: Reader?) { record(columnLabel, reader) delegate.updateNCharacterStream(columnLabel, reader) } override fun updateNClob(columnIndex: Int, nClob: NClob?) { recordUpdate(columnIndex, nClob) delegate.updateNClob(columnIndex, nClob) } override fun updateNClob(columnLabel: String?, nClob: NClob?) { record(columnLabel, nClob) delegate.updateNClob(columnLabel, nClob) } override fun updateNClob(columnIndex: Int, reader: Reader?, length: Long) { recordUpdate(columnIndex, reader, length) delegate.updateNClob(columnIndex, reader, length) } override fun updateNClob(columnLabel: String?, reader: Reader?, length: Long) { record(columnLabel, reader, length) delegate.updateNClob(columnLabel, reader, length) } override fun updateNClob(columnIndex: Int, reader: Reader?) { recordUpdate(columnIndex, reader) delegate.updateNClob(columnIndex, reader) } override fun updateNClob(columnLabel: String?, reader: Reader?) { record(columnLabel, reader) delegate.updateNClob(columnLabel, reader) } override fun updateNString(columnIndex: Int, nString: String?) { recordUpdate(columnIndex, nString) delegate.updateNString(columnIndex, nString) } override fun updateNString(columnLabel: String?, nString: String?) { record(columnLabel, nString) delegate.updateNString(columnLabel, nString) } override fun updateNull(columnIndex: Int) { recordUpdate(columnIndex) delegate.updateNull(columnIndex) } override fun updateNull(columnLabel: String?) { record(columnLabel) delegate.updateNull(columnLabel) } override fun updateObject(columnIndex: Int, x: Any?, scaleOrLength: Int) { recordUpdate(columnIndex, x, scaleOrLength) delegate.updateObject(columnIndex, x, scaleOrLength) } override fun updateObject(columnLabel: String?, x: Any?, scaleOrLength: Int) { record(columnLabel, x, scaleOrLength) delegate.updateObject(columnLabel, x, scaleOrLength) } override fun updateObject(columnIndex: Int, x: Any?) { recordUpdate(columnIndex, x) delegate.updateObject(columnIndex, x) } override fun updateObject(columnLabel: String?, x: Any?) { record(columnLabel, x) delegate.updateObject(columnLabel, x) } override fun updateRef(columnIndex: Int, x: Ref?) { recordUpdate(columnIndex, x) delegate.updateRef(columnIndex, x) } override fun updateRef(columnLabel: String?, x: Ref?) { record(columnLabel, x) delegate.updateRef(columnLabel, x) } override fun updateRow() { record() delegate.updateRow() } override fun updateRowId(columnIndex: Int, x: RowId?) { recordUpdate(columnIndex, x) delegate.updateRowId(columnIndex, x) } override fun updateRowId(columnLabel: String?, x: RowId?) { record(columnLabel, x) delegate.updateRowId(columnLabel, x) } override fun updateShort(columnIndex: Int, x: Short) { recordUpdate(columnIndex, x) delegate.updateShort(columnIndex, x) } override fun updateShort(columnLabel: String?, x: Short) { record(columnLabel, x) delegate.updateShort(columnLabel, x) } override fun updateSQLXML(columnIndex: Int, xmlObject: SQLXML?) { recordUpdate(columnIndex, xmlObject) delegate.updateSQLXML(columnIndex, xmlObject) } override fun updateSQLXML(columnLabel: String?, xmlObject: SQLXML?) { record(columnLabel, xmlObject) delegate.updateSQLXML(columnLabel, xmlObject) } override fun updateString(columnIndex: Int, x: String?) { recordUpdate(columnIndex, x) delegate.updateString(columnIndex, x) } override fun updateString(columnLabel: String?, x: String?) { record(columnLabel, x) delegate.updateString(columnLabel, x) } override fun updateTime(columnIndex: Int, x: Time?) { recordUpdate(columnIndex, x) delegate.updateTime(columnIndex, x) } override fun updateTime(columnLabel: String?, x: Time?) { record(columnLabel, x) delegate.updateTime(columnLabel, x) } override fun updateTimestamp(columnIndex: Int, x: Timestamp?) { recordUpdate(columnIndex, x) delegate.updateTimestamp(columnIndex, x) } override fun updateTimestamp(columnLabel: String?, x: Timestamp?) { record(columnLabel, x) delegate.updateTimestamp(columnLabel, x) } override fun wasNull(): Boolean = record { delegate.wasNull() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is AbstractRecordingResultSet) return false if (query != other.query) return false return true } override fun hashCode(): Int { return query.hashCode() } override fun toString(): String { return "ResultSet($query)" } }
util/src/main/kotlin/io/github/pdvrieze/jdbc/recorder/AbstractRecordingResultSet.kt
4222021870
package org.thoughtcrime.securesms.stories.tabs import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import org.thoughtcrime.securesms.database.DatabaseObserver import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.recipients.Recipient class ConversationListTabRepository { fun getNumberOfUnreadConversations(): Observable<Long> { return Observable.create<Long> { val listener = DatabaseObserver.Observer { it.onNext(SignalDatabase.threads.unreadThreadCount) } ApplicationDependencies.getDatabaseObserver().registerConversationListObserver(listener) it.setCancellable { ApplicationDependencies.getDatabaseObserver().unregisterObserver(listener) } it.onNext(SignalDatabase.threads.unreadThreadCount) }.subscribeOn(Schedulers.io()) } fun getNumberOfUnseenStories(): Observable<Long> { return Observable.create<Long> { emitter -> fun refresh() { emitter.onNext(SignalDatabase.mms.unreadStoryThreadRecipientIds.map { Recipient.resolved(it) }.filterNot { it.shouldHideStory() }.size.toLong()) } val listener = DatabaseObserver.Observer { refresh() } ApplicationDependencies.getDatabaseObserver().registerConversationListObserver(listener) emitter.setCancellable { ApplicationDependencies.getDatabaseObserver().unregisterObserver(listener) } refresh() }.subscribeOn(Schedulers.io()) } }
app/src/main/java/org/thoughtcrime/securesms/stories/tabs/ConversationListTabRepository.kt
1845048642
/* * 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.client.utils import io.ktor.client.content.* import io.ktor.utils.io.* import io.ktor.utils.io.pool.* import kotlinx.coroutines.* import kotlin.coroutines.* @OptIn(DelicateCoroutinesApi::class) internal fun ByteReadChannel.observable( context: CoroutineContext, contentLength: Long?, listener: ProgressListener ) = GlobalScope.writer(context, autoFlush = true) { ByteArrayPool.useInstance { byteArray -> val total = contentLength ?: -1 var bytesSend = 0L while ([email protected]) { val read = [email protected](byteArray) channel.writeFully(byteArray, offset = 0, length = read) bytesSend += read listener(bytesSend, total) } val closedCause = [email protected] channel.close(closedCause) if (closedCause == null && bytesSend == 0L) { listener(bytesSend, total) } } }.channel
ktor-client/ktor-client-core/common/src/io/ktor/client/utils/ByteChannelUtils.kt
4195734272
package com.cultureoftech.kotlinweather.weather /** * Created by bgogetap on 2/20/16. */ data class CityWeatherResponse( val name: String, val id: Long, val cod: Long, val weather: Array<WeatherItem>, val main: Main, val wind: Wind, val clouds: Clouds, val sys: Sys) { data class Main(val temp: Double, val pressure: Double, val humidity: Double, val temp_min: Double, val temp_max: Double) data class WeatherItem(val id: Long, val main: String, val description: String, val icon: String) data class Wind(val speed: Double, val deg: Double) data class Clouds(val all: Double) data class Sys(val message: Double, val country: String, val sunrise: Long, val sunset: Long) }
app/src/main/kotlin/com/cultureoftech/kotlinweather/weather/CityWeatherResponse.kt
4048862413
/* * Copyright © 2013 dvbviewer-controller Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dvbviewer.controller.ui.phone import android.os.Bundle import androidx.fragment.app.Fragment import org.dvbviewer.controller.ui.base.BaseSinglePaneActivity import org.dvbviewer.controller.ui.fragments.StreamConfig /** * The Class StreamConfigActivity. * * @author RayBa * @date 07.04.2013 */ class StreamConfigActivity : BaseSinglePaneActivity() { /* (non-Javadoc) * @see org.dvbviewer.controller.ui.base.BaseSinglePaneActivity#onCreate(android.os.Bundle) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setDisplayHomeAsUpEnabled(true) } /* (non-Javadoc) * @see org.dvbviewer.controller.ui.base.BaseSinglePaneActivity#onCreatePane() */ override fun onCreatePane(): Fragment { val cfg = StreamConfig() cfg.arguments = intentToFragmentArguments(intent) return cfg } }
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/phone/StreamConfigActivity.kt
2221709134
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.BasicTag import com.netflix.spectator.api.Registry import com.netflix.spinnaker.orca.* import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.exceptions.TimeoutException import com.netflix.spinnaker.orca.ext.failureStatus import com.netflix.spinnaker.orca.pipeline.model.Execution import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.InvalidTaskType import com.netflix.spinnaker.orca.q.PauseTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.metrics.MetricsTagHelper import com.netflix.spinnaker.orca.time.toDuration import com.netflix.spinnaker.orca.time.toInstant import com.netflix.spinnaker.q.Message import com.netflix.spinnaker.q.Queue import org.apache.commons.lang.time.DurationFormatUtils import org.springframework.stereotype.Component import java.time.Clock import java.time.Duration import java.time.Duration.ZERO import java.time.Instant import java.time.temporal.TemporalAmount import java.util.concurrent.TimeUnit import kotlin.collections.set @Component class RunTaskHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, override val contextParameterProcessor: ContextParameterProcessor, private val tasks: Collection<Task>, private val clock: Clock, private val exceptionHandlers: List<ExceptionHandler>, private val registry: Registry ) : OrcaMessageHandler<RunTask>, ExpressionAware, AuthenticationAware { override fun handle(message: RunTask) { message.withTask { stage, taskModel, task -> val execution = stage.execution val thisInvocationStartTimeMs = clock.millis() try { if (execution.isCanceled) { task.onCancel(stage) queue.push(CompleteTask(message, CANCELED)) } else if (execution.status.isComplete) { queue.push(CompleteTask(message, CANCELED)) } else if (execution.status == PAUSED) { queue.push(PauseTask(message)) } else { try { task.checkForTimeout(stage, taskModel, message) } catch (e: TimeoutException) { registry .timeoutCounter(stage.execution.type, stage.execution.application, stage.type, taskModel.name) .increment() task.onTimeout(stage) throw e } stage.withAuth { task.execute(stage.withMergedContext()).let { result: TaskResult -> // TODO: rather send this data with CompleteTask message stage.processTaskOutput(result) when (result.status) { RUNNING -> { queue.push(message, task.backoffPeriod(taskModel, stage)) trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status) } SUCCEEDED, REDIRECT, FAILED_CONTINUE -> { queue.push(CompleteTask(message, result.status)) trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status) } CANCELED -> { task.onCancel(stage) val status = stage.failureStatus(default = result.status) queue.push(CompleteTask(message, status, result.status)) trackResult(stage, thisInvocationStartTimeMs, taskModel, status) } TERMINAL -> { val status = stage.failureStatus(default = result.status) queue.push(CompleteTask(message, status, result.status)) trackResult(stage, thisInvocationStartTimeMs, taskModel, status) } else -> TODO("Unhandled task status ${result.status}") } } } } } catch (e: Exception) { val exceptionDetails = exceptionHandlers.shouldRetry(e, taskModel.name) if (exceptionDetails?.shouldRetry == true) { log.warn("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]") queue.push(message, task.backoffPeriod(taskModel, stage)) trackResult(stage, thisInvocationStartTimeMs, taskModel, RUNNING) } else if (e is TimeoutException && stage.context["markSuccessfulOnTimeout"] == true) { queue.push(CompleteTask(message, SUCCEEDED)) } else { log.error("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]", e) stage.context["exception"] = exceptionDetails repository.storeStage(stage) queue.push(CompleteTask(message, stage.failureStatus())) trackResult(stage, thisInvocationStartTimeMs, taskModel, stage.failureStatus()) } } } } private fun trackResult(stage: Stage, thisInvocationStartTimeMs: Long, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, status: ExecutionStatus) { val commonTags = MetricsTagHelper.commonTags(stage, taskModel, status) val detailedTags = MetricsTagHelper.detailedTaskTags(stage, taskModel, status) val elapsedMillis = clock.millis() - thisInvocationStartTimeMs hashMapOf( "task.invocations.duration" to commonTags + BasicTag("application", stage.execution.application), "task.invocations.duration.withType" to commonTags + detailedTags ).forEach { name, tags -> registry.timer(name, tags).record(elapsedMillis, TimeUnit.MILLISECONDS) } } override val messageType = RunTask::class.java private fun RunTask.withTask(block: (Stage, com.netflix.spinnaker.orca.pipeline.model.Task, Task) -> Unit) = withTask { stage, taskModel -> tasks .find { taskType.isAssignableFrom(it.javaClass) } .let { task -> if (task == null) { queue.push(InvalidTaskType(this, taskType.name)) } else { block.invoke(stage, taskModel, task) } } } private fun Task.backoffPeriod(taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, stage: Stage): TemporalAmount = when (this) { is RetryableTask -> Duration.ofMillis( getDynamicBackoffPeriod(stage, Duration.ofMillis(System.currentTimeMillis() - (taskModel.startTime ?: 0))) ) else -> Duration.ofSeconds(1) } private fun formatTimeout(timeout: Long): String { return DurationFormatUtils.formatDurationWords(timeout, true, true) } private fun Task.checkForTimeout(stage: Stage, taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, message: Message) { checkForStageTimeout(stage) checkForTaskTimeout(taskModel, stage, message) } private fun Task.checkForTaskTimeout(taskModel: com.netflix.spinnaker.orca.pipeline.model.Task, stage: Stage, message: Message) { if (this is RetryableTask) { val startTime = taskModel.startTime.toInstant() if (startTime != null) { val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime) val elapsedTime = Duration.between(startTime, clock.instant()) val actualTimeout = ( if (this is OverridableTimeoutRetryableTask && stage.parentWithTimeout.isPresent) stage.parentWithTimeout.get().timeout.get().toDuration() else timeout.toDuration() ) if (elapsedTime.minus(pausedDuration) > actualTimeout) { val durationString = formatTimeout(elapsedTime.toMillis()) val msg = StringBuilder("${javaClass.simpleName} of stage ${stage.name} timed out after $durationString. ") msg.append("pausedDuration: ${formatTimeout(pausedDuration.toMillis())}, ") msg.append("elapsedTime: ${formatTimeout(elapsedTime.toMillis())},") msg.append("timeoutValue: ${formatTimeout(actualTimeout.toMillis())}") log.warn(msg.toString()) throw TimeoutException(msg.toString()) } } } } private fun checkForStageTimeout(stage: Stage) { stage.parentWithTimeout.ifPresent { val startTime = it.startTime.toInstant() if (startTime != null) { val elapsedTime = Duration.between(startTime, clock.instant()) val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime) val timeout = Duration.ofMillis(it.timeout.get()) if (elapsedTime.minus(pausedDuration) > timeout) { throw TimeoutException("Stage ${stage.name} timed out after ${formatTimeout(elapsedTime.toMillis())}") } } } } private fun Registry.timeoutCounter(executionType: ExecutionType, application: String, stageType: String, taskType: String) = counter( createId("queue.task.timeouts") .withTags(mapOf( "executionType" to executionType.toString(), "application" to application, "stageType" to stageType, "taskType" to taskType )) ) private fun Execution.pausedDurationRelativeTo(instant: Instant?): Duration { val pausedDetails = paused return if (pausedDetails != null) { if (pausedDetails.pauseTime.toInstant()?.isAfter(instant) == true) { Duration.ofMillis(pausedDetails.pausedMs) } else ZERO } else ZERO } /** * Keys that should never be added to global context. Eventually this will * disappear along with global context itself. */ private val blacklistGlobalKeys = setOf( "propertyIdList", "originalProperties", "propertyAction", "propertyAction", "deploymentDetails" ) private fun Stage.processTaskOutput(result: TaskResult) { val filteredOutputs = result.outputs.filterKeys { it != "stageTimeoutMs" } if (result.context.isNotEmpty() || filteredOutputs.isNotEmpty()) { context.putAll(result.context) outputs.putAll(filteredOutputs) repository.storeStage(this) } } }
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandler.kt
1586982378
/* * 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.preview import android.app.Activity import android.app.Fragment import android.content.res.TypedArray import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.koin.standalone.StandAloneContext import org.koin.standalone.inject import org.koin.test.KoinTest import org.koin.test.declareMock import org.mockito.kotlin.* import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class PreviewPreferenceTest : KoinTest { private val mockTypedArray: TypedArray = mock() private val activity: Activity = mock { on(it.obtainStyledAttributes(anyOrNull(), any(), any(), any())).doReturn(mockTypedArray) on(it.packageName).doReturn("com.doctoror.particleswallpaper") } private val presenter: PreviewPreferencePresenter by inject() private val underTest = PreviewPreference(activity) @Before fun setup() { declareMock<OpenChangeWallpaperIntentProvider>() declareMock<PreviewPreferencePresenter>() } @After fun tearDown() { StandAloneContext.stopKoin() } @Test fun deliversHostToPresenter() { // Given val host: Fragment = mock() // When underTest.fragment = host // Then verify(presenter).host = host } @Test fun deliversUseCaseWithHost() { // When underTest.fragment = mock() // Then verify(presenter).useCase = any() } @Test fun resetsUseCaseWithHost() { // When underTest.fragment = null // Then verify(presenter).useCase = null } }
app/src/test/java/com/doctoror/particleswallpaper/userprefs/preview/PreviewPreferenceTest.kt
4002669226
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package egl.templates import egl.* import org.lwjgl.generator.* val KHR_image_base = "KHRImageBase".nativeClassEGL("KHR_image_base", postfix = KHR) { documentation = """ Native bindings to the $registryLink extension. This extension defines a new EGL resource type that is suitable for sharing 2D arrays of image data between client APIs, the EGLImage. Although the intended purpose is sharing 2D image data, the underlying interface makes no assumptions about the format or purpose of the resource being shared, leaving those decisions to the application and associated client APIs. Requires ${EGL12.core}. """ IntConstant( "", "IMAGE_PRESERVED_KHR"..0x30D2 ) LongConstant( "", "NO_IMAGE_KHR"..0L ) EGLImageKHR( "CreateImageKHR", "", EGLDisplay("dpy", ""), EGLContext("ctx", ""), EGLenum("target", ""), EGLClientBuffer("buffer", ""), nullable..noneTerminated..EGLint.const.p("attrib_list", "") ) EGLBoolean( "DestroyImageKHR", "", EGLDisplay("dpy", ""), EGLImageKHR("image", "") ) }
modules/lwjgl/egl/src/templates/kotlin/egl/templates/KHR_image_base.kt
562135003
package io.zhudy.uia.helper import com.mongodb.client.MongoDatabase import com.mongodb.client.model.Filters import com.mongodb.client.model.FindOneAndUpdateOptions import com.mongodb.client.model.Updates import org.springframework.stereotype.Component /** * @author Kevin Zou ([email protected]) */ @Component class MongoSeqHelper(db: MongoDatabase) { /** * */ private val counters = db.getCollection("counters") /** * */ fun next(name: String): Long { val doc = counters.findOneAndUpdate(Filters.eq(name), Updates.inc("seq", 1L), FindOneAndUpdateOptions().upsert(true)) return doc.getLong("seq") } }
server/src/main/kotlin/io/zhudy/uia/helper/MongoSeqHelper.kt
2070326916
package org.fountainmc.api.chat.events import java.lang.reflect.Type import java.util.Locale import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer class ClickEventSerializer : JsonSerializer<ClickEvent>, JsonDeserializer<ClickEvent> { @Throws(JsonParseException::class) override fun deserialize(element: JsonElement, type: Type, context: JsonDeserializationContext): ClickEvent { val `object` = element.asJsonObject val action = ClickEvent.Action.valueOf(`object`.get("action").asString) return ClickEvent(action, `object`.get("value").asString) } override fun serialize(event: ClickEvent, type: Type, context: JsonSerializationContext): JsonElement { val `object` = JsonObject() `object`.addProperty("action", event.action.name.toLowerCase(Locale.US)) `object`.addProperty("value", event.value) return `object` } }
src/main/kotlin/org/fountainmc/api/chat/events/ClickEventSerializer.kt
2563562353
package com.techlung.android.mortalityday.util import android.content.Context import android.widget.Toast object Toaster { fun show(message: String, context: Context?) { if (context != null) { Toast.makeText(context, message, Toast.LENGTH_LONG).show() } } }
app/src/main/java/com/techlung/android/mortalityday/util/Toaster.kt
3034115601
import java.io.File import java.text.NumberFormat import kotlin.math.sqrt import kotlin.test.assertEquals val nf: NumberFormat = NumberFormat.getInstance() inline val Number.isPalindrome get() = nf.format(this).let { it == it.reversed() } inline val Number.square get() = sqrt(toDouble()) fun IntRange.fairAndSquare() = fold(0) { acc, i -> acc + if (i.isPalindrome && i.square.isPalindrome) 1 else 0 } fun main(args: Array<String>) { val dir = File(args.firstOrNull() ?: ".") val input = File("$dir/C-small-practice.in").readLines() val output = File("$dir/C-small-practice.out").readLines().map { it.split(' ', limit = 3).last().toInt() } for (i in 1..input.first().toInt()) { input[i].split(' ', limit = 2).let { it[0].toInt()..it[1].toInt() }.fairAndSquare().let { val message = "Case #$i: $it" assertEquals(output[i - 1], it, message) println(message) } } }
problems/codejam/2013/quali/Fair-and-Square/fair-and-square.kt
2163333987
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.fileresource.internal import com.google.common.truth.Truth.assertThat import java.io.File import org.hisp.dhis.android.core.fileresource.FileResourceRoutine import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.Test import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) internal class FileResourceRoutineShould : BaseFileResourceRoutineIntegrationShould() { private val fileResourceRoutine by lazy { FileResourceRoutine( dataElementCollectionRepository = d2.dataElementModule().dataElements(), dataValueCollectionRepository = d2.dataValueModule().dataValues(), fileResourceCollectionRepository = d2.fileResourceModule().fileResources(), fileResourceStore = fileResourceStore, trackedEntityAttributeCollectionRepository = d2.trackedEntityModule().trackedEntityAttributes(), trackedEntityAttributeValueCollectionRepository = d2.trackedEntityModule().trackedEntityAttributeValues(), trackedEntityDataValueCollectionRepository = d2.trackedEntityModule().trackedEntityDataValues() ) } @Test fun delete_outdated_file_resources_if_present() { trackedEntityDataValueStore.delete() trackedEntityAttributeValueStore.delete() fileResourceRoutine.blockingDeleteOutdatedFileResources() val fileResources = d2.fileResourceModule().fileResources().blockingGet() assertThat(fileResources.size).isEqualTo(1) assertThat(File(FileResourceRoutineSamples.fileResource1.path()!!).exists()).isFalse() assertThat(File(FileResourceRoutineSamples.fileResource2.path()!!).exists()).isFalse() assertThat(File(FileResourceRoutineSamples.fileResource3.path()!!).exists()).isTrue() } }
core/src/androidTest/java/org/hisp/dhis/android/core/fileresource/internal/FileResourceRoutineShould.kt
1374925305
package rynkbit.tk.coffeelist.db.dao import androidx.room.Dao import androidx.room.Query import io.reactivex.Flowable import io.reactivex.Single import rynkbit.tk.coffeelist.contract.entity.InvoiceState import rynkbit.tk.coffeelist.db.entity.DatabaseInvoice @Dao interface InvoiceDao : BaseDao<DatabaseInvoice> { @Query("select * from invoice") override fun findAll(): Flowable<List<DatabaseInvoice>> @Query("select * from invoice where id = :invoiceId") fun findById(invoiceId: Int): Single<DatabaseInvoice> @Query("select * from invoice where customer_id = :customerId") fun findByCustomer(customerId: Int): Flowable<List<DatabaseInvoice>> @Query("select * from invoice where customer_id = :customerId and state = :state") fun findByCustomerAndState(customerId: Int, state: InvoiceState): Flowable<List<DatabaseInvoice>> @Query("delete from invoice where customer_id = :customerId") fun deleteByCustomer(customerId: Int): Single<Unit> @Query("delete from invoice") fun deleteAll(): Single<Unit> }
app/src/main/java/rynkbit/tk/coffeelist/db/dao/InvoiceDao.kt
3769880848
// 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.task.impl import com.intellij.internal.statistic.collectors.fus.ClassNameRuleValidator import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector class ProjectTaskManagerStatisticsCollector : CounterUsagesCollector() { companion object { val GROUP = EventLogGroup("build", 6) @JvmField val TASK_RUNNER = EventFields.StringListValidatedByCustomRule("task_runner_class", ClassNameRuleValidator::class.java) @JvmField val MODULES = EventFields.Int("modules") @JvmField val INCREMENTAL = EventFields.Boolean("incremental") @JvmField val HAS_ERRORS = EventFields.Boolean("has_errors") @JvmField val BUILD_ACTIVITY = GROUP.registerIdeActivity(null, startEventAdditionalFields = arrayOf(TASK_RUNNER, EventFields.PluginInfo, MODULES, INCREMENTAL), finishEventAdditionalFields = arrayOf(HAS_ERRORS)) } override fun getGroup(): EventLogGroup { return GROUP } }
platform/lang-impl/src/com/intellij/task/impl/ProjectTaskManagerStatisticsCollector.kt
2553165661
package com.mikepenz.fastadapter.drag import android.view.View import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView /** * Created by mikepenz on 30.12.15. */ interface IExtendedDraggable<VH : RecyclerView.ViewHolder> : IDraggable { /** * This returns the ItemTouchHelper * * @return the ItemTouchHelper if item has one or null */ val touchHelper: ItemTouchHelper? /** * This method returns the drag view inside the item * use this with (@withTouchHelper) to start dragging when this view is touched * * @param viewHolder the ViewHolder * @return the view that should start the dragging or null */ fun getDragView(viewHolder: VH): View? }
fastadapter-extensions-drag/src/main/java/com/mikepenz/fastadapter/drag/IExtendedDraggable.kt
268629102
internal class A { private val i = 0 // comment }
plugins/kotlin/j2k/new/tests/testData/newJ2k/comments/fieldWithEndOfLineCommentAndNoInitializer.kt
1427123375
// PROBLEM: none // DISABLE-ERRORS expect suspend fun a() actual <caret>suspend fun a() { }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantSuspend/actual.kt
3333654373
package me.serce.solidity.lang.core.resolve class SolUserDefinedValueTypeResolveTest : SolResolveTestBase() { fun testUserDefinedValueTypeResolveInFile() = checkByCode(""" type Decimal18 is uint256; //x interface MinimalERC20 { function transfer(address to, Decimal18 value) external; //^ } """) fun testUserDefinedValueTypeResolveInAnInterface() = checkByCode(""" interface MinimalERC20 { type Decimal18 is uint256; //x function transfer(address to, Decimal18 value) external; //^ } """) }
src/test/kotlin/me/serce/solidity/lang/core/resolve/SolUserDefinedValueTypeResolveTest.kt
3914472891
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.kotlin.comparison import org.jetbrains.uast.UFile import org.jetbrains.uast.test.common.kotlin.UastCommentLogTestBase import org.jetbrains.uast.test.kotlin.AbstractKotlinUastTest import java.io.File abstract class AbstractFE1UastCommentsTest : AbstractKotlinUastTest(), UastCommentLogTestBase { override val isFirUastPlugin: Boolean = false override fun check(filePath: String, file: UFile) { super<UastCommentLogTestBase>.check(filePath, file) } override var testDataDir = File("plugins/uast-kotlin-fir/testData") fun doTest(filePath: String) { testDataDir = File(filePath).parentFile val testName = filePath.substring(filePath.lastIndexOf('/') + 1).removeSuffix(".kt") val virtualFile = getVirtualFile(testName) val psiFile = psiManager.findFile(virtualFile) ?: error("Can't get psi file for $testName") val uFile = uastContext.convertElementWithParent(psiFile, null) ?: error("Can't get UFile for $testName") check(filePath, uFile as UFile) } }
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/comparison/AbstractFE1UastCommentsTest.kt
2946802628
// "Add ''Parcelable'' supertype" "true" // WITH_STDLIB package com.myapp.activity import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize class <caret>Test(val s: String)
plugins/kotlin/compiler-plugins/parcelize/tests/testData/quickfix/noParcelableSupertype/simple.kt
1211073612
package com.tungnui.dalatlaptop.utils import android.app.Activity import android.content.Context import android.support.annotation.IdRes import android.support.design.widget.Snackbar import android.support.design.widget.TextInputLayout import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction import android.support.v7.app.AppCompatActivity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.ImageView import com.tungnui.dalatlaptop.views.ResizableImageViewHeight import com.squareup.picasso.Picasso import com.tungnui.dalatlaptop.R import com.tungnui.dalatlaptop.libraryhelper.Utils import com.tungnui.dalatlaptop.models.Image import java.text.DecimalFormat import java.util.regex.Pattern /** * Created by thanh on 23/09/2017. */ fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot) } fun ImageView.loadImg(imageUrl: String?) { Picasso.with(context).load(imageUrl) .fit().centerInside() .placeholder(R.drawable.placeholder_loading) .error(R.drawable.placeholder_error) .into(this) } fun ResizableImageViewHeight.loadImg(imageUrl: String?){ Picasso.with(context) .load(imageUrl) .fit().centerInside() .placeholder(R.drawable.placeholder_loading) .error(R.drawable.placeholder_error) .into(this) } fun List<Image>.getFeaturedImage():Image{ for(item in this){ if(item.position == 0) return item } return Image() } fun String.formatPrice():String{ val formatter = DecimalFormat("#,###") return formatter.format(this.toDouble()) + "đ" } /* * GET NEXT URL FROM LINK IN HEADER * */ fun String.getNextUrl(): String? { val urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)" val pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE) val urlMatcher = pattern.matcher(this) val result = mutableListOf<String>() while (urlMatcher.find()) { result.add(this.substring(urlMatcher.start(0),urlMatcher.end(0))) } return when(result.count()){ 1->if(this.contains("rel=\"next\"")) result[0].replace("%5B0%5D","") else null else-> result[1].replace("%5B0%5D","") } } fun View.showSnackBar(message: String, duration: Int) { Snackbar.make(this, message, duration).show() } //Appcompat extension fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, @IdRes frameId: Int) { supportFragmentManager.transact { replace(frameId, fragment) } } /** * The `fragment` is added to the container view with tag. The operation is * performed by the `fragmentManager`. */ fun AppCompatActivity.addFragmentToActivity(fragment: Fragment, tag: String) { supportFragmentManager.transact { add(fragment, tag) } } /** * Runs a FragmentTransaction, then calls commit(). */ private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Unit) { beginTransaction().apply { action() }.commit() } fun <T1, T2> ifNotNull(value1: T1?, value2: T2?, bothNotNull: (T1, T2) -> (Unit)) { if (value1 != null && value2 != null) { bothNotNull(value1, value2) } } //TExt input fun TextInputLayout.getTextFromInputLayout(): String { return this.editText?.text.toString() } fun TextInputLayout.setTextToInputLayout(text: String) { if (this.editText != null) { this.editText?.setText(text) } } fun TextInputLayout.isVaildForEmail():Boolean{ val input = editText?.text.toString() if(input.isNullOrBlank()){ error = resources.getString(R.string.required) return false } return false } fun TextInputLayout.checkTextInputLayoutValueRequirement(errorValue: String): Boolean { if (this.editText != null) { val text = Utils.getTextFromInputLayout(this) if (text == null || text.isEmpty()) { this.isErrorEnabled = true this.error = errorValue return false } else { this.isErrorEnabled = false return true } } return false } //HideKeyboard fun Activity.hideKeyboard():Boolean{ val view= currentFocus view?.let{ val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager return inputMethodManager.hideSoftInputFromWindow(view.windowToken,InputMethodManager.HIDE_NOT_ALWAYS) } return false }
app/src/main/java/com/tungnui/dalatlaptop/utils/Extensions.kt
383705593
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import training.learn.lesson.LessonStateManager import training.util.LearningLessonsAutoExecutor private class AutorunAllLessons : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return LessonStateManager.resetPassedStatus() LearningLessonsAutoExecutor.runAllLessons(project) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
plugins/ide-features-trainer/src/training/actions/AutorunAllLessons.kt
2675117933
package b import a.A.O import a.A class Client { fun fooBar() { val a = A() println("foo = ${A.O.foo}") val obj = A.O println("length: ${obj.foo.length}") } }
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findObjectUsages/kotlinNestedObjectUsages.1.kt
323082891
class A { val x = if (true) { class L { } L() } else {} val y = if (true) { class L { } L() } else {} }
java/ql/test/kotlin/library-tests/classes/localClassField.kt
1179026208
/* * 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.views import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import android.util.AttributeSet import android.view.View import com.google.android.material.textfield.TextInputEditText class TextInputEditText : TextInputEditText { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) // Workaround for https://issuetracker.google.com/issues/67675432 @RequiresApi(Build.VERSION_CODES.O) override fun getAutofillType(): Int { return View.AUTOFILL_TYPE_NONE } }
app/src/main/java/de/dreier/mytargets/views/TextInputEditText.kt
1518589740
package fr.openium.auvergnewebcams.ui.search import android.os.Bundle import fr.openium.auvergnewebcams.R import fr.openium.auvergnewebcams.base.AbstractFragment import kotlinx.android.synthetic.main.fragment_search.* /** * Created by Openium on 19/02/2019. */ class FragmentSearch : AbstractFragment() { override val layoutId: Int = R.layout.fragment_search // --- Life cycle // --------------------------------------------------- override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) textViewSearch.requestFocus() setListener() } // --- Methods // --------------------------------------------------- private fun setListener() { } }
app/src/main/java/fr/openium/auvergnewebcams/ui/search/FragmentSearch.kt
762475105
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.vsphere.api import com.vmware.vim25.mo.GuestAuthManager import com.vmware.vim25.mo.GuestFileManager import com.vmware.vim25.mo.GuestProcessManager import com.vmware.vim25.mo.VirtualMachine interface GuestOperationsManagerApi { fun getAuthManager(vm: VirtualMachine): GuestAuthManager fun getFileManager(vm: VirtualMachine): GuestFileManager fun getProcessManager(vm: VirtualMachine): GuestProcessManager }
src/main/kotlin/org/jclouds/vsphere/api/GuestOperationsManagerApi.kt
2123030540
/* * 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.api import java.io.Serializable import java.io.Closeable /** * @todo document. * @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a> */ public trait TableStore<K : Comparable<K>, V : Serializable> : Closeable { fun add(value: V) fun addAll(list: List<V>) fun get(key: K): V? fun remove(value: V): V? fun contains(key: K): Boolean fun minus(value: V) { remove(value) } fun plusEquals(value: V): TableStore<K, V> { add(value) return this } fun minusEquals(value: V): TableStore<K, V> { remove(value) return this } fun last(n: Int): List<V> }
api/src/main/kotlin/kontrol/api/TableStore.kt
2600411711
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle.datahandler import com.demonwav.mcdev.platform.mcp.gradle.McpModelData import com.intellij.openapi.externalSystem.model.project.ModuleData import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext interface McpModelDataHandler { fun build(gradleModule: IdeaModule, module: ModuleData, resolverCtx: ProjectResolverContext): McpModelData? }
src/main/kotlin/com/demonwav/mcdev/platform/mcp/gradle/datahandler/McpModelDataHandler.kt
3609833787
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.identification import com.demonwav.mcdev.platform.mcp.util.McpConstants import com.demonwav.mcdev.translations.TranslationConstants import com.demonwav.mcdev.util.MemberReference import com.intellij.psi.PsiElement data class TranslationInstance( val foldingElement: PsiElement?, val foldStart: Int, val referenceElement: PsiElement?, val key: Key, val text: String?, val formattingError: FormattingError? = null, val superfluousVarargStart: Int = -1 ) { data class Key(val prefix: String, val infix: String, val suffix: String) { val full = (prefix + infix + suffix).trim() } companion object { enum class FormattingError { MISSING, SUPERFLUOUS } val translationFunctions = listOf( TranslationFunction( MemberReference( TranslationConstants.FORMAT, "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", TranslationConstants.I18N_CLIENT_CLASS ), 0, formatting = true, obfuscatedName = true ), TranslationFunction( MemberReference( TranslationConstants.TRANSLATE_TO_LOCAL, "(Ljava/lang/String;)Ljava/lang/String;", TranslationConstants.I18N_COMMON_CLASS ), 0, formatting = false, obfuscatedName = true ), TranslationFunction( MemberReference( TranslationConstants.TRANSLATE_TO_LOCAL_FORMATTED, "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", TranslationConstants.I18N_COMMON_CLASS ), 0, formatting = true, obfuscatedName = true ), TranslationFunction( MemberReference( TranslationConstants.CONSTRUCTOR, "(Ljava/lang/String;[Ljava/lang/Object;)V", TranslationConstants.TRANSLATION_COMPONENT_CLASS ), 0, formatting = true, foldParameters = true ), TranslationFunction( MemberReference( TranslationConstants.CONSTRUCTOR, "(Ljava/lang/String;[Ljava/lang/Object;)V", TranslationConstants.COMMAND_EXCEPTION_CLASS ), 0, formatting = true, foldParameters = true ), TranslationFunction( MemberReference( TranslationConstants.SET_BLOCK_NAME, "(Ljava/lang/String;)Lnet/minecraft/block/Block;", McpConstants.BLOCK ), 0, formatting = false, setter = true, foldParameters = true, prefix = "tile.", suffix = ".name", obfuscatedName = true ), TranslationFunction( MemberReference( TranslationConstants.SET_ITEM_NAME, "(Ljava/lang/String;)Lnet/minecraft/item/Item;", McpConstants.ITEM ), 0, formatting = false, setter = true, foldParameters = true, prefix = "item.", suffix = ".name", obfuscatedName = true ) ) fun find(element: PsiElement): TranslationInstance? = TranslationIdentifier.INSTANCES .firstOrNull { it.elementClass().isAssignableFrom(element.javaClass) } ?.identifyUnsafe(element) } }
src/main/kotlin/com/demonwav/mcdev/translations/identification/TranslationInstance.kt
1129093975
package com.alexstyl.specialdates.upcoming class UpcomingEventsFreeUserAdRules : UpcomingEventsAdRules { private var adAdded: Boolean = false override fun shouldAppendAd(): Boolean { return !this.adAdded } override fun onNewAdAdded() { this.adAdded = true } }
memento/src/main/java/com/alexstyl/specialdates/upcoming/UpcomingEventsFreeUserAdRules.kt
1243269179
package com.monkeyapp.blog.dtos import com.fasterxml.jackson.annotation.JsonProperty data class PageDto ( @JsonProperty("metadata") val metadata: PageMetadataDto, @JsonProperty("content") var content: String ) data class PageMetadataDto( @JsonProperty("creationTime") val crtime: String, @JsonProperty("url") val url: String, @JsonProperty("title") val title: String )
src/main/java/com/monkeyapp/blog/dtos/PageDto.kt
3205912085
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.withDimensions class VorbisMapping :IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.instanceFields.count { it.type == INT_TYPE } == 2 } .and { it.instanceFields.count { it.type == IntArray::class.type } == 2 } class submaps : OrderMapper.InConstructor.Field(VorbisMapping::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class mappingMux : OrderMapper.InConstructor.Field(VorbisMapping::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class submapFloor : OrderMapper.InConstructor.Field(VorbisMapping::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE.withDimensions(1) } } class submapResidue : OrderMapper.InConstructor.Field(VorbisMapping::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE.withDimensions(1) } } }
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/VorbisMapping.kt
1034600580
package mp internal actual class InternalClassHeaderDelegatedTo actual constructor(private val owner: CommonClassDelegatingToInternalClassHeader) { actual fun doIt() { println("Internal actual class in JavaScript for: $owner") } }
js/src/main/kotlin/mp/InternalClassHeaderDelegatedTo.kt
465794254
// 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.scratch.output import com.intellij.execution.filters.OpenFileHyperlinkInfo import com.intellij.execution.impl.ConsoleViewImpl import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.application.invokeLater import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.scratch.ScratchExpression import org.jetbrains.kotlin.idea.scratch.ScratchFile import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.KtPsiFactory /** * Method to retrieve shared instance of scratches ToolWindow output handler. * * [releaseToolWindowHandler] must be called for every output handler received from this method. * * Can be called from EDT only. * * @return new toolWindow output handler if one does not exist, otherwise returns the existing one. When application in test mode, * returns [TestOutputHandler]. */ fun requestToolWindowHandler(): ScratchOutputHandler { return if (isUnitTestMode()) { TestOutputHandler } else { ScratchToolWindowHandlerKeeper.requestOutputHandler() } } /** * Should be called once with the output handler received from the [requestToolWindowHandler] call. * * When release is called for every request, the output handler is actually disposed. * * When application in test mode, does nothing. * * Can be called from EDT only. */ fun releaseToolWindowHandler(scratchOutputHandler: ScratchOutputHandler) { if (!isUnitTestMode()) { ScratchToolWindowHandlerKeeper.releaseOutputHandler(scratchOutputHandler) } } /** * Implements logic of shared pointer for the toolWindow output handler. * * Not thread safe! Can be used only from the EDT. */ private object ScratchToolWindowHandlerKeeper { private var toolWindowHandler: ScratchOutputHandler? = null private var toolWindowDisposable = Disposer.newDisposable() private var counter = 0 fun requestOutputHandler(): ScratchOutputHandler { if (counter == 0) { toolWindowHandler = ToolWindowScratchOutputHandler(toolWindowDisposable) } counter += 1 return toolWindowHandler!! } fun releaseOutputHandler(scratchOutputHandler: ScratchOutputHandler) { require(counter > 0) { "Counter is $counter, nothing to release!" } require(toolWindowHandler === scratchOutputHandler) { "$scratchOutputHandler differs from stored $toolWindowHandler" } counter -= 1 if (counter == 0) { Disposer.dispose(toolWindowDisposable) toolWindowDisposable = Disposer.newDisposable() toolWindowHandler = null } } } private class ToolWindowScratchOutputHandler(private val parentDisposable: Disposable) : ScratchOutputHandlerAdapter() { override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) { printToConsole(file) { val psiFile = file.getPsiFile() if (psiFile != null) { printHyperlink( getLineInfo(psiFile, expression), OpenFileHyperlinkInfo( project, psiFile.virtualFile, expression.lineStart ) ) print(" ", ConsoleViewContentType.NORMAL_OUTPUT) } print(output.text, output.type.convert()) } } override fun error(file: ScratchFile, message: String) { printToConsole(file) { print(message, ConsoleViewContentType.ERROR_OUTPUT) } } private fun printToConsole(file: ScratchFile, print: ConsoleViewImpl.() -> Unit) { invokeLater { val project = file.project.takeIf { !it.isDisposed } ?: return@invokeLater val toolWindow = getToolWindow(project) ?: createToolWindow(file) val contents = toolWindow.contentManager.contents for (content in contents) { val component = content.component if (component is ConsoleViewImpl) { component.print() component.print("\n", ConsoleViewContentType.NORMAL_OUTPUT) } } toolWindow.setAvailable(true, null) if (!file.options.isInteractiveMode) { toolWindow.show(null) } toolWindow.setIcon(ExecutionUtil.getLiveIndicator(AllIcons.FileTypes.Text)) } } override fun clear(file: ScratchFile) { invokeLater { val toolWindow = getToolWindow(file.project) ?: return@invokeLater val contents = toolWindow.contentManager.contents for (content in contents) { val component = content.component if (component is ConsoleViewImpl) { component.clear() } } if (!file.options.isInteractiveMode) { toolWindow.hide(null) } toolWindow.setIcon(AllIcons.FileTypes.Text) } } private fun ScratchOutputType.convert() = when (this) { ScratchOutputType.OUTPUT -> ConsoleViewContentType.SYSTEM_OUTPUT ScratchOutputType.RESULT -> ConsoleViewContentType.NORMAL_OUTPUT ScratchOutputType.ERROR -> ConsoleViewContentType.ERROR_OUTPUT } private fun getToolWindow(project: Project): ToolWindow? { val toolWindowManager = ToolWindowManager.getInstance(project) return toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID) } private fun createToolWindow(file: ScratchFile): ToolWindow { val project = file.project val toolWindowManager = ToolWindowManager.getInstance(project) toolWindowManager.registerToolWindow(ScratchToolWindowFactory.ID, true, ToolWindowAnchor.BOTTOM) val window = toolWindowManager.getToolWindow(ScratchToolWindowFactory.ID) ?: error("ScratchToolWindowFactory.ID should be registered") ScratchToolWindowFactory().createToolWindowContent(project, window) Disposer.register(parentDisposable, Disposable { toolWindowManager.unregisterToolWindow(ScratchToolWindowFactory.ID) }) return window } } private fun getLineInfo(psiFile: PsiFile, expression: ScratchExpression) = "${psiFile.name}:${expression.lineStart + 1}" private class ScratchToolWindowFactory : ToolWindowFactory { companion object { const val ID = "Scratch Output" } override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val consoleView = ConsoleViewImpl(project, true) toolWindow.setToHideOnEmptyContent(true) toolWindow.setIcon(AllIcons.FileTypes.Text) toolWindow.hide(null) val contentManager = toolWindow.contentManager val content = contentManager.factory.createContent(consoleView.component, null, false) contentManager.addContent(content) val editor = consoleView.editor if (editor is EditorEx) { editor.isRendererMode = true } Disposer.register(KotlinPluginDisposable.getInstance(project), consoleView) } } private object TestOutputHandler : ScratchOutputHandlerAdapter() { private val errors = arrayListOf<String>() private val inlays = arrayListOf<Pair<ScratchExpression, String>>() override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) { inlays.add(expression to output.text) } override fun error(file: ScratchFile, message: String) { errors.add(message) } override fun onFinish(file: ScratchFile) { TransactionGuard.submitTransaction(KotlinPluginDisposable.getInstance(file.project), Runnable { val psiFile = file.getPsiFile() ?: error( "PsiFile cannot be found for scratch to render inlays in tests:\n" + "project.isDisposed = ${file.project.isDisposed}\n" + "inlays = ${inlays.joinToString { it.second }}\n" + "errors = ${errors.joinToString()}" ) if (inlays.isNotEmpty()) { testPrint(psiFile, inlays.map { (expression, text) -> "/** ${getLineInfo(psiFile, expression)} $text */" }) inlays.clear() } if (errors.isNotEmpty()) { testPrint(psiFile, listOf(errors.joinToString(prefix = "/** ", postfix = " */"))) errors.clear() } }) } private fun testPrint(file: PsiFile, comments: List<String>) { WriteCommandAction.runWriteCommandAction(file.project) { for (comment in comments) { file.addAfter( KtPsiFactory(file.project).createComment(comment), file.lastChild ) } } } }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/output/ToolWindowScratchOutputHandler.kt
1029154203
/* * Copyright (C) 2015 Antonio Leiva * * 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.antonioleiva.bandhookkotlin.domain.entity public data class Album(val id: String, val name: String, val url: String, val artist: Artist)
domain/src/main/java/com/antonioleiva/bandhookkotlin/domain/entity/Album.kt
3728781256
package net.nullsum.audinaut.domain import java.io.Serializable import java.util.* class Indexes(var shortcuts: MutableList<Artist> = mutableListOf(), var artists: MutableList<Artist> = mutableListOf(), var entries: MutableList<MusicDirectory.Entry> = mutableListOf()) : Serializable { fun sortChildren() { shortcuts.sortBy { s -> s.id.toLowerCase(Locale.ROOT) } artists.sortBy { a -> a.name.toLowerCase(Locale.ROOT) } entries.sortBy { e -> e.artist.toLowerCase(Locale.ROOT) } } }
app/src/main/kotlin/net/nullsum/audinaut/domain/Indexes.kt
308679635
package com.github.vhromada.catalog.web.connector.entity /** * A class represents statistics for shows. * * @author Vladimir Hromada */ class ShowStatistics( /** * Count of shows */ val count: Int, /** * Count of seasons */ val seasonsCount: Int, /** * Count of episodes */ val episodesCount: Int, /** * Length */ val length: String )
web/src/main/kotlin/com/github/vhromada/catalog/web/connector/entity/ShowStatistics.kt
2917169236
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.projectTree import com.intellij.ide.projectView.TreeStructureProvider import com.intellij.ide.projectView.ViewSettings import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.settings.MarkdownSettings class MarkdownTreeStructureProvider(private val project: Project) : TreeStructureProvider { override fun modify( parent: AbstractTreeNode<*>, children: MutableCollection<AbstractTreeNode<*>>, settings: ViewSettings? ): MutableCollection<AbstractTreeNode<*>> { if (children.find { it.value is MarkdownFile } == null) { return children } val result = mutableListOf<AbstractTreeNode<*>>() val childrenToRemove = mutableListOf<AbstractTreeNode<*>>() for (child in children) { val childValue = (child.value as? MarkdownFile) val childVirtualFile = childValue?.virtualFile if (childVirtualFile != null && parent.value !is MarkdownFileNode) { val markdownChildren = findMarkdownFileNodeChildren(childVirtualFile, children) if (markdownChildren.size <= 1) { result.add(child) continue } result.add(createMarkdownViewNode(childVirtualFile, markdownChildren, settings)) childrenToRemove.addAll(markdownChildren) } else { result.add(child) } } result.removeAll(childrenToRemove) return result } private fun findMarkdownFileNodeChildren( markdownFile: VirtualFile, children: MutableCollection<AbstractTreeNode<*>> ): MutableCollection<AbstractTreeNode<*>> { val fileName = markdownFile.nameWithoutExtension return children.asSequence().filter { node -> val file = (node.value as? PsiFile)?.virtualFile file?.let { isDocumentsGroupingEnabled(it, fileName) } == true }.toMutableList() } private fun createMarkdownViewNode( markdownFile: VirtualFile, children: MutableCollection<AbstractTreeNode<*>>, settings: ViewSettings? ): MarkdownViewNode { val nodeChildren = children.mapNotNull { it.value as? PsiFile } val markdownNode = MarkdownFileNode(markdownFile.nameWithoutExtension, nodeChildren) return MarkdownViewNode(project, markdownNode, settings, children) } private fun isDocumentsGroupingEnabled(file: VirtualFile, fileName: String) = file.extension?.lowercase() in extensionsToFold && file.nameWithoutExtension == fileName && MarkdownSettings.getInstance(project).isFileGroupingEnabled companion object { private val extensionsToFold = listOf("pdf", "docx", "html", "md") } }
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/projectTree/MarkdownTreeStructureProvider.kt
1766776905
// 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.base.facet import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager.checkCanceled import com.intellij.openapi.project.Project import com.intellij.workspaceModel.ide.WorkspaceModelTopics import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.util.caching.ModuleEntityChangeListener import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedValueCache import org.jetbrains.kotlin.platform.jvm.isJvm @Service(Service.Level.PROJECT) class JvmOnlyProjectChecker(project: Project) : SynchronizedFineGrainedValueCache<Boolean>(project) { override fun subscribe() { project.messageBus.connect(this).subscribe(WorkspaceModelTopics.CHANGED, ModelChangeListener(project)) } override fun calculate(): Boolean = runReadAction { ModuleManager.getInstance(project).modules.all { module -> checkCanceled() module.platform.isJvm() } } internal class ModelChangeListener(project: Project) : ModuleEntityChangeListener(project) { override fun entitiesChanged(outdated: List<Module>) = getInstance(project).invalidate(writeAccessRequired = true) } companion object { fun getInstance(project: Project): JvmOnlyProjectChecker = project.service() } }
plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/base/facet/JvmOnlyProjectChecker.kt
2870463451
package org.codetome.snap.adapter.parser import com.vladsch.flexmark.ast.Node import org.codetome.snap.model.rest.RestService import org.codetome.snap.service.parser.* class MarkdownRootSegmentParser( headerSegmentParser: HeaderSegmentParser<Node>, descriptionSegmentParser: DescriptionSegmentParser<Node>, endpointSegmentParser: EndpointSegmentParser<Node>, segmentTypeAnalyzer: SegmentTypeAnalyzer<Node>) : RootSegmentParser<Node>(headerSegmentParser, descriptionSegmentParser, endpointSegmentParser, segmentTypeAnalyzer)
src/main/kotlin/org/codetome/snap/adapter/parser/MarkdownRootSegmentParser.kt
3015030278
package org.stepic.droid.ui.dialogs import android.app.Dialog import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.stepic.droid.R import org.stepic.droid.util.resolveAttribute class DiscardTextDialogFragment : DialogFragment() { companion object { const val TAG = "DiscardTextDialogFragment" fun newInstance(): DialogFragment = DiscardTextDialogFragment() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.title_confirmation) .setMessage(R.string.are_you_sure_remove_comment_text) .setPositiveButton(R.string.delete_label) { _, _ -> (activity as? Callback ?: parentFragment as? Callback ?: targetFragment as? Callback) ?.onDiscardConfirmed() } .setNegativeButton(R.string.cancel, null) .create() .apply { setOnShowListener { val colorError = context .resolveAttribute(R.attr.colorError) ?.data ?: return@setOnShowListener getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(colorError) } } interface Callback { fun onDiscardConfirmed() } }
app/src/main/java/org/stepic/droid/ui/dialogs/DiscardTextDialogFragment.kt
1463221395
// 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.ide.actions.runAnything import com.intellij.ide.actions.runAnything.groups.RunAnythingCompletionGroup import com.intellij.ide.actions.runAnything.groups.RunAnythingGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.project.Project private const val GROUP_ID = "actions.runAnything" class RunAnythingUsageCollector { companion object { fun trigger(project: Project, featureId: String) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, featureId) } fun triggerExecCategoryStatistics(project: Project, groups: MutableCollection<out RunAnythingGroup>, clazz: Class<out RunAnythingSearchListModel>, index: Int, shiftPressed: Boolean, altPressed: Boolean) { for (i in index downTo 0) { val group = RunAnythingGroup.findGroup(groups, i) if (group != null) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "execute", FeatureUsageData() .addData("list", getSafeToReportClazzName(clazz)) .addData("group", getSafeToReportTitle(group)) .addData("with_shift", shiftPressed) .addData("with_alt", altPressed)) break } } } fun triggerMoreStatistics(project: Project, group: RunAnythingGroup, clazz: Class<out RunAnythingSearchListModel>) { FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, "click.more", FeatureUsageData() .addData("list", getSafeToReportClazzName(clazz)) .addData("group", getSafeToReportTitle(group))) } private fun getSafeToReportClazzName(clazz: Class<*>): String { return if (getPluginInfo(clazz).isSafeToReport()) clazz.name else "third.party" } private fun getSafeToReportTitle(group: RunAnythingGroup): String { return if (group is RunAnythingCompletionGroup<*, *>) getSafeToReportClazzName(group.provider.javaClass) else getSafeToReportClazzName(group.javaClass) } } }
platform/lang-impl/src/com/intellij/ide/actions/runAnything/RunAnythingUsageCollector.kt
452896012
package jp.gr.aqua.vtextviewer import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class PreferenceActivity : AppCompatActivity(), PreferenceFragment.OnFragmentInteractionListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_vtext_preference) setTitle(R.string.vtext_app_name) } }
vtextview/src/main/java/jp/gr/aqua/vtextviewer/PreferenceActivity.kt
3464290420
/* * Copyright 2016-2022 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.* import kotlinx.coroutines.exceptions.* import kotlin.test.* class LimitedParallelismConcurrentTest : TestBase() { private val targetParallelism = 4 private val iterations = 100_000 private val parallelism = atomic(0) private fun checkParallelism() { val value = parallelism.incrementAndGet() randomWait() assertTrue { value <= targetParallelism } parallelism.decrementAndGet() } @Test fun testLimitedExecutor() = runMtTest { val executor = newFixedThreadPoolContext(targetParallelism, "test") val view = executor.limitedParallelism(targetParallelism) doStress { repeat(iterations) { launch(view) { checkParallelism() } } } executor.close() } private suspend inline fun doStress(crossinline block: suspend CoroutineScope.() -> Unit) { repeat(stressTestMultiplier) { coroutineScope { block() } } } @Test fun testTaskFairness() = runMtTest { val executor = newSingleThreadContext("test") val view = executor.limitedParallelism(1) val view2 = executor.limitedParallelism(1) val j1 = launch(view) { while (true) { yield() } } val j2 = launch(view2) { j1.cancel() } joinAll(j1, j2) executor.close() } }
kotlinx-coroutines-core/concurrent/test/LimitedParallelismConcurrentTest.kt
3092807307
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import org.junit.Test import java.util.concurrent.* import kotlin.coroutines.* import kotlin.test.* class LimitedParallelismUnhandledExceptionTest : TestBase() { @Test fun testUnhandledException() = runTest { var caughtException: Throwable? = null val executor = Executors.newFixedThreadPool( 1 ) { Thread(it).also { it.uncaughtExceptionHandler = Thread.UncaughtExceptionHandler { _, e -> caughtException = e } } }.asCoroutineDispatcher() val view = executor.limitedParallelism(1) view.dispatch(EmptyCoroutineContext, Runnable { throw TestException() }) withContext(view) { // Verify it is in working state and establish happens-before } assertTrue { caughtException is TestException } executor.close() } }
kotlinx-coroutines-core/jvm/test/LimitedParallelismUnhandledExceptionTest.kt
978990801
/* * Copyright 2015-2019 The twitlatte authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.moko256.latte.client.twitter import com.github.moko256.latte.client.base.StatusCounter import com.github.moko256.latte.client.base.entity.UpdateStatus import com.twitter.twittertext.TwitterTextParseResults import com.twitter.twittertext.TwitterTextParser /** * Created by moko256 on 2018/12/06. * * @author moko256 */ internal class TwitterStatusCounter: StatusCounter { private var imageSize: Int = 0 private var resultCache: TwitterTextParseResults? = null override fun setUpdateStatus(updateStatus: UpdateStatus, imageSize: Int) { val context = updateStatus.context resultCache = TwitterTextParser.parseTweet(context, TwitterTextParser.TWITTER_TEXT_EMOJI_CHAR_COUNT_CONFIG) this.imageSize = imageSize } override fun getContextLength(): Int { return resultCache?.weightedLength ?: 0 } override fun isValidStatus(): Boolean { return if (resultCache?.weightedLength == 0) { imageSize > 0 } else { resultCache?.isValid?:false } } override val limit: Int = TwitterTextParser.TWITTER_TEXT_EMOJI_CHAR_COUNT_CONFIG.maxWeightedTweetLength }
component_client_twitter/src/main/java/com/github/moko256/latte/client/twitter/TwitterStatusCounter.kt
1433858236
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.util.recursionAwareLazy class ArgumentsInstruction(call: GrCall) : InstructionImpl(call) { override fun getElement(): GrCall = super.getElement() as GrCall override fun getElementPresentation(): String = "ARGUMENTS " + super.getElementPresentation() val variableDescriptors: Collection<VariableDescriptor> get() = arguments.keys val arguments: Map<VariableDescriptor, Collection<Argument>> by recursionAwareLazy(this::obtainArguments) private fun obtainArguments(): Map<VariableDescriptor, Collection<Argument>> { // don't use GrCall#getArguments() because it calls #getType() on GrSpreadArgument operand val argumentList = element.argumentList ?: return emptyMap() val result = ArrayList<Pair<VariableDescriptor, ExpressionArgument>>() for (expression in argumentList.expressionArguments) { if (expression !is GrReferenceExpression) continue if (expression.isQualified) continue val descriptor = expression.createDescriptor() ?: continue result += Pair(descriptor, ExpressionArgument(expression)) } if (result.isEmpty()) return emptyMap() return result.groupByTo(LinkedHashMap(), { it.first }, { it.second }) } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/impl/ArgumentsInstruction.kt
1814803396
package com.dbflow5.transaction import com.dbflow5.database.DatabaseWrapper /** * Description: Wraps multiple transactions together. */ class TransactionWrapper : ITransaction<Any> { private val transactions = arrayListOf<ITransaction<Any>>() constructor(vararg transactions: ITransaction<Any>) { this.transactions.addAll(transactions) } constructor(transactions: Collection<ITransaction<Any>>) { this.transactions.addAll(transactions) } override fun execute(databaseWrapper: DatabaseWrapper) { transactions.forEach { it.execute(databaseWrapper) } } }
lib/src/main/kotlin/com/dbflow5/transaction/TransactionWrapper.kt
1350548789
import kotlin.reflect.KProperty var result: String by Delegate object Delegate { var value = "lol" operator fun getValue(instance: Any?, data: KProperty<*>): String { return value } operator fun setValue(instance: Any?, data: KProperty<*>, newValue: String) { value = newValue } } fun box(): String { val f = ::result if (f.get() != "lol") return "Fail 1: {$f.get()}" Delegate.value = "rofl" if (f.get() != "rofl") return "Fail 2: {$f.get()}" f.set("OK") return f.get() }
backend.native/tests/external/codegen/box/callableReference/property/delegatedMutable.kt
3353860632
package codegen.bridges.test5 import kotlin.test.* // non-generic interface, generic impl, vtable call + interface call open class A<T> { open var size: T = 56 as T } interface C { var size: Int } open class B : C, A<Int>() fun box(): String { val b = B() if (b.size != 56) return "fail 1" b.size = 55 if (b.size != 55) return "fail 2" val c: C = b if (c.size != 55) return "fail 3" c.size = 57 if (c.size != 57) return "fail 4" return "OK" } @Test fun runTest() { println(box()) }
backend.native/tests/codegen/bridges/test5.kt
1649714452
// FILE: 1.kt package test inline fun inlineFun(capturedParam: String, noinline lambda: () -> String = { capturedParam }): String { return lambda() } // FILE: 2.kt //NO_CHECK_LAMBDA_INLINING import test.* fun box(): String { return inlineFun("OK") } // FILE: 1.smap //TODO maybe do smth with default method body mapping SMAP 1.kt Kotlin *S Kotlin *F + 1 1.kt test/_1Kt *L 1#1,8:1 5#1:9 *E SMAP 1.kt Kotlin *S Kotlin *F + 1 1.kt test/_1Kt$inlineFun$1 *L 1#1,8:1 *E // FILE: 2.TODO
backend.native/tests/external/codegen/boxInline/smap/defaultFunction.kt
2951630829
package net.ndrei.teslacorelib.gui import net.minecraft.client.renderer.RenderHelper import net.minecraft.item.ItemStack import net.ndrei.teslacorelib.render.GhostedItemRenderer /** * Created by CF on 2017-07-04. */ open class GhostedItemStackRenderPiece(left: Int, top: Int, val alpha: Float = .42f, val stack: ItemStack? = null) : BasicContainerGuiPiece(left, top, 18, 18) { override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) { super.drawBackgroundLayer(container, guiX, guiY, partialTicks, mouseX, mouseY) val left = this.left + guiX + 1 val top = this.top + guiY + 1 val stack = this.getRenderStack() if (!stack.isEmpty) { RenderHelper.enableGUIStandardItemLighting() GhostedItemRenderer.renderItemInGUI(container.itemRenderer, stack, left, top, this.alpha) RenderHelper.disableStandardItemLighting() } } open fun getRenderStack(): ItemStack { return this.stack ?: ItemStack.EMPTY } }
src/main/kotlin/net/ndrei/teslacorelib/gui/GhostedItemStackRenderPiece.kt
485473090
// WITH_RUNTIME import kotlin.test.assertEquals enum class Season { WINTER, SPRING, SUMMER, AUTUMN } fun foo(x : Any) : String { return when (x) { Season.WINTER -> "winter" Season.SPRING -> "spring" Season.SUMMER -> "summer" else -> "other" } } fun box() : String { assertEquals("winter", foo(Season.WINTER)) assertEquals("spring", foo(Season.SPRING)) assertEquals("summer", foo(Season.SUMMER)) assertEquals("other", foo(Season.AUTUMN)) assertEquals("other", foo(123)) return "OK" }
backend.native/tests/external/codegen/box/when/enumOptimization/subjectAny.kt
4010532565
fun box(): String { var i = 0 { if (1 == 1) { i++ } else { } }() return "OK" }
backend.native/tests/external/codegen/box/controlStructures/kt2597.kt
2269044285
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS package test val p = { "OK" }() val getter: String get() = { "OK" }() fun f() = { "OK" }() val obj = object : Function0<String> { override fun invoke() = "OK" } fun box(): String { if (p != "OK") return "FAIL" if (getter != "OK") return "FAIL" if (f() != "OK") return "FAIL" if (obj() != "OK") return "FAIL" return "OK" }
backend.native/tests/external/codegen/box/closures/closureOnTopLevel1.kt
2255597284
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.model data class LockWhitelistedEvent( val packageName: String, val activityName: String )
padlock-model/src/main/java/com/pyamsoft/padlock/model/LockWhitelistedEvent.kt
3630248793
// EXTRACTION_TARGET: property with initializer // WITH_STDLIB import java.util.* class Foo<T> { val map = HashMap<String, T>() fun test(): T { return <selection>map[""]</selection> } }
plugins/kotlin/idea/tests/testData/refactoring/introduceProperty/typeParameterResolvableInTargetScope.kt
80823215
package chat.willow.kale.irc.message.rfc1459.rpl import chat.willow.kale.core.ICommand import chat.willow.kale.core.message.* import chat.willow.kale.irc.CharacterCodes object Rpl005Message : ICommand { override val command = "005" data class Message(val source: String, val target: String, val tokens: Map<String, String?>) { object Descriptor : KaleDescriptor<Message>(matcher = commandMatcher(command), parser = Parser) object Parser : MessageParser<Message>() { override fun parseFromComponents(components: IrcMessageComponents): Message? { if (components.parameters.size < 2) { return null } val source = components.prefix ?: "" val target = components.parameters[0] val tokens = mutableMapOf<String, String?>() for (i in 1 until components.parameters.size) { val token = components.parameters[i].split(delimiters = CharacterCodes.EQUALS, limit = 2) if (token.isEmpty() || token[0].isEmpty()) { continue } var value = token.getOrNull(1) if (value != null && value.isEmpty()) { value = null } tokens[token[0]] = value } return Message(source, target, tokens) } } object Serialiser : MessageSerialiser<Message>(command) { override fun serialiseToComponents(message: Message): IrcMessageComponents { val tokens = mutableListOf<String>() for ((key, value) in message.tokens) { if (value.isNullOrEmpty()) { tokens.add(key) } else { tokens.add("$key${CharacterCodes.EQUALS}$value") } } val parameters = listOf(message.target) + tokens return IrcMessageComponents(prefix = message.source, parameters = parameters) } } } }
src/main/kotlin/chat/willow/kale/irc/message/rfc1459/rpl/Rpl005Message.kt
2706376149
package org.craftsmenlabs.gareth.execution import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import org.springframework.context.annotation.Bean import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration @Configuration @ComponentScan(basePackages = arrayOf("org.craftsmenlabs.gareth.execution")) open class GarethExecutionConfig { @Bean open fun getObjectMapper(): ObjectMapper { val mapper = ObjectMapper().registerModule(KotlinModule()) return mapper } }
gareth-execution-ri/src/main/kotlin/org/craftsmenlabs/gareth/execution/GarethExecutionConfig.kt
2568021887
// WITH_STDLIB package test import kotlinx.android.parcel.* import android.os.Parcel import android.os.Parcelable object Parceler1 : Parceler<String> { override fun create(parcel: Parcel) = parcel.readInt().toString() override fun String.write(parcel: Parcel, flags: Int) { parcel.writeInt(length) } } object Parceler2 : Parceler<List<String>> { override fun create(parcel: Parcel) = listOf(parcel.readString()!!) override fun List<String>.write(parcel: Parcel, flags: Int) { parcel.writeString(this.joinToString(",")) } } <warning descr="[DEPRECATED_ANNOTATION] Parcelize annotations from package 'kotlinx.android.parcel' are deprecated. Change package to 'kotlinx.parcelize'">@Parcelize</warning> <error descr="[FORBIDDEN_DEPRECATED_ANNOTATION] Parceler-related annotations from package 'kotlinx.android.parcel' are forbidden. Change package to 'kotlinx.parcelize'">@TypeParceler<String, <error descr="[UPPER_BOUND_VIOLATED] Type argument is not within its bounds: should be subtype of 'Parceler<in String>'">Parceler2</error>></error> data class Test( val a: String, val b: <error descr="[FORBIDDEN_DEPRECATED_ANNOTATION] Parceler-related annotations from package 'kotlinx.android.parcel' are forbidden. Change package to 'kotlinx.parcelize'">@WriteWith<Parceler1></error> String, val c: <error descr="[FORBIDDEN_DEPRECATED_ANNOTATION] Parceler-related annotations from package 'kotlinx.android.parcel' are forbidden. Change package to 'kotlinx.parcelize'">@WriteWith<Parceler2></error> List<<error descr="[FORBIDDEN_DEPRECATED_ANNOTATION] Parceler-related annotations from package 'kotlinx.android.parcel' are forbidden. Change package to 'kotlinx.parcelize'">@WriteWith<Parceler1></error> String> ) : Parcelable { <warning descr="[DEPRECATED_ANNOTATION] Parcelize annotations from package 'kotlinx.android.parcel' are deprecated. Change package to 'kotlinx.parcelize'">@IgnoredOnParcel</warning> val x by lazy { "foo" } } interface ParcelerForUser: Parceler<User> <warning descr="[DEPRECATED_ANNOTATION] Parcelize annotations from package 'kotlinx.android.parcel' are deprecated. Change package to 'kotlinx.parcelize'">@Parcelize</warning> class User(val name: String) : Parcelable { private companion <error descr="[DEPRECATED_PARCELER] 'kotlinx.android.parcel.Parceler' is deprecated. Use 'kotlinx.parcelize.Parceler' instead">object</error> : ParcelerForUser { override fun User.write(parcel: Parcel, flags: Int) { parcel.writeString(name) } override fun create(parcel: Parcel) = User(parcel.readString()!!) } }
plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/deprecatedAnnotations.kt
2635251521
// WITH_STDLIB // FULL_JDK open class A: java.applet.Applet() class B: A()
plugins/kotlin/idea/tests/testData/inspections/unusedSymbol/class/unusedButEntryPointApplet.kt
83935342
// "class org.jetbrains.kotlin.idea.quickfix.SuperClassNotInitialized$AddParametersFix" "false" // ACTION: Change to constructor invocation // ERROR: This type has a constructor, and thus must be initialized here open class Base class C : Base<caret>
plugins/kotlin/idea/tests/testData/quickfix/supertypeInitialization/noParameters.kt
4213737085
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.sequence.trace.impl.interpret import com.intellij.debugger.streams.trace.CallTraceInterpreter import com.intellij.debugger.streams.trace.TraceElement import com.intellij.debugger.streams.trace.TraceInfo import com.intellij.debugger.streams.trace.impl.TraceElementImpl import com.intellij.debugger.streams.trace.impl.interpret.ex.UnexpectedValueTypeException import com.intellij.debugger.streams.wrapper.StreamCall import com.sun.jdi.ArrayReference import com.sun.jdi.BooleanValue import com.sun.jdi.IntegerValue import com.sun.jdi.Value class FilterTraceInterpreter(private val predicateValueToAccept: Boolean) : CallTraceInterpreter { override fun resolve(call: StreamCall, value: Value): TraceInfo { if (value !is ArrayReference) throw UnexpectedValueTypeException("array reference excepted, but actual: ${value.type().name()}") val before = resolveValuesBefore(value.getValue(0)) val filteringMap = value.getValue(1) val after = resolveValuesAfter(before, filteringMap) return ValuesOrder(call, before, after) } private fun resolveValuesBefore(map: Value): Map<Int, TraceElement> { val (keys, objects) = InterpreterUtil.extractMap(map) val result: MutableList<TraceElement> = mutableListOf() for (i in 0.until(keys.length())) { val time = keys.getValue(i) val value = objects.getValue(i) if (time !is IntegerValue) throw UnexpectedValueTypeException("time should be represented by integer value") result.add(TraceElementImpl(time.value(), value)) } return InterpreterUtil.createIndexByTime(result) } private fun resolveValuesAfter(before: Map<Int, TraceElement>, filteringMap: Value): Map<Int, TraceElement> { val predicateValues = extractPredicateValues(filteringMap) val result = linkedMapOf<Int, TraceElement>() for ((beforeTime, element) in before) { val predicateValue = predicateValues[beforeTime] if (predicateValue == predicateValueToAccept) { result[beforeTime + 1] = TraceElementImpl(beforeTime + 1, element.value) } } return result } private fun extractPredicateValues(filteringMap: Value): Map<Int, Boolean> { val (keys, values) = InterpreterUtil.extractMap(filteringMap) val result = mutableMapOf<Int, Boolean>() for (i in 0.until(keys.length())) { val time = keys.getValue(i) val value = values.getValue(i) if (time !is IntegerValue) throw UnexpectedValueTypeException("time should be represented by integer value") if (value !is BooleanValue) throw UnexpectedValueTypeException("predicate value should be represented by boolean value") result[time.value()] = value.value() } return result } }
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/impl/interpret/FilterTraceInterpreter.kt
476506188
package test actual class C fun test() { C() }
plugins/kotlin/idea/tests/testData/refactoring/changeSignatureMultiModule/headerPrimaryConstructorNoParams/before/JVM/src/test/test.kt
1105056716
fun ClosedRangeUsage(c: ClosedRange<Int>) { 42 i<caret>n c }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/fromLibrary/ClosedRangeUsage.kt
1465108120
package io.fotoapparat.exception /** * Thrown when there is a problem while saving the file. */ class FileSaveException(cause: Throwable) : RuntimeException(cause)
fotoapparat/src/main/java/io/fotoapparat/exception/FileSaveException.kt
1422370212
fun foo(p: (String) -> Unit){} fun bar() { foo { (p<caret> } } // INVOCATION_COUNT: 0 // ELEMENT: * // CHAR: ':'
plugins/kotlin/completion/tests/testData/handlers/charFilter/FunctionLiteralParameter2.kt
2992934205
package flank.log import kotlin.reflect.KClass /** * Factory method for building and creating generic [Formatter]. */ fun <T> buildFormatter(build: Builder<T>.() -> Unit): Formatter<T> = Builder<T>().apply(build).run { @Suppress("UNCHECKED_CAST") Formatter( static = static as Map<StaticMatcher, Format<Any, T>>, dynamic = dynamic as Map<DynamicMatcher, Format<Any, T>>, ) } /** * Generic formatters builder. */ class Builder<T> internal constructor() { internal val static = mutableMapOf<StaticMatcher, Format<*, T>>() internal val dynamic = mutableMapOf<DynamicMatcher, Format<*, T>>() /** * Registers [V] formatter with [KClass] based static matcher. * * @receiver [KClass] as a identifier. * @param context Optional context. * @param format Reference to formatting function. */ operator fun <V : Event.Data> KClass<V>.invoke( context: Any? = null, format: Format<V, T>, ) { static += listOfNotNull(context, java) to format } /** * Registers [V] formatter with [Event.Type] based static matcher. * * @receiver [Event.Type] as a identifier. * @param context Optional context. * @param format Reference to formatting function. */ operator fun <V> Event.Type<V>.invoke( context: Any? = null, format: Format<V, T> ) { static += listOfNotNull(context, this) to format } /** * Creates matcher function. */ fun <V> match(f: (Any.(Any) -> V?)) = f /** * Registers [V] formatter with dynamic matcher function. * * @receiver Matching event function. The receiver is a context where * @param format Reference to formatting function. */ infix fun <V> (Any.(Any) -> V?).to( format: Format<V, T> ) { val wrap: DynamicMatcher = { invoke(this, it) != null } dynamic += wrap to format } }
tool/log/format/src/main/kotlin/flank/log/Builder.kt
2813792301
package com.kickstarter.viewmodels.projectpage import android.content.Intent import android.util.Pair import androidx.annotation.NonNull import com.kickstarter.R import com.kickstarter.libs.ActivityRequestCodes import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Either import com.kickstarter.libs.Environment import com.kickstarter.libs.ProjectPagerTabs import com.kickstarter.libs.RefTag import com.kickstarter.libs.models.OptimizelyExperiment import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair import com.kickstarter.libs.rx.transformers.Transformers.errors import com.kickstarter.libs.rx.transformers.Transformers.ignoreValues import com.kickstarter.libs.rx.transformers.Transformers.neverError import com.kickstarter.libs.rx.transformers.Transformers.takePairWhen import com.kickstarter.libs.rx.transformers.Transformers.takeWhen import com.kickstarter.libs.rx.transformers.Transformers.values import com.kickstarter.libs.utils.EventContextValues.ContextPageName.PROJECT import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.CAMPAIGN import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.ENVIRONMENT import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.FAQS import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.OVERVIEW import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.RISKS import com.kickstarter.libs.utils.ExperimentData import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.ProjectViewUtils import com.kickstarter.libs.utils.RefTagUtils import com.kickstarter.libs.utils.UrlUtils import com.kickstarter.libs.utils.extensions.ProjectMetadata import com.kickstarter.libs.utils.extensions.backedReward import com.kickstarter.libs.utils.extensions.isErrored import com.kickstarter.libs.utils.extensions.isFalse import com.kickstarter.libs.utils.extensions.isNonZero import com.kickstarter.libs.utils.extensions.isTrue import com.kickstarter.libs.utils.extensions.metadataForProject import com.kickstarter.libs.utils.extensions.negate import com.kickstarter.libs.utils.extensions.updateProjectWith import com.kickstarter.libs.utils.extensions.userIsCreator import com.kickstarter.models.Backing import com.kickstarter.models.Project import com.kickstarter.models.Reward import com.kickstarter.models.User import com.kickstarter.ui.IntentKey import com.kickstarter.ui.activities.ProjectPageActivity import com.kickstarter.ui.data.CheckoutData import com.kickstarter.ui.data.MediaElement import com.kickstarter.ui.data.PledgeData import com.kickstarter.ui.data.PledgeFlowContext import com.kickstarter.ui.data.PledgeReason import com.kickstarter.ui.data.ProjectData import com.kickstarter.ui.data.VideoModelElement import com.kickstarter.ui.intentmappers.ProjectIntentMapper import com.kickstarter.viewmodels.usecases.ShowPledgeFragmentUseCase import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import java.math.RoundingMode import java.util.concurrent.TimeUnit interface ProjectPageViewModel { interface Inputs { /** Call when the cancel pledge option is clicked. */ fun cancelPledgeClicked() /** Call when the comments text view is clicked. */ fun commentsTextViewClicked() /** Call when the contact creator option is clicked. */ fun contactCreatorClicked() /** Call when the fix payment method is clicked. */ fun fixPaymentMethodButtonClicked() /** Call when the count of fragments on the back stack changes. */ fun fragmentStackCount(count: Int) /** Call when the heart button is clicked. */ fun heartButtonClicked() /** Call when the native_project_action_button is clicked. */ fun nativeProjectActionButtonClicked() /** Call when the view has been laid out. */ fun onGlobalLayout() /** Call when the fullscreen video button is clicked. */ fun fullScreenVideoButtonClicked(videoInfo: kotlin.Pair<String, Long>) /** Call when the pledge's payment method has been successfully updated. */ fun pledgePaymentSuccessfullyUpdated() /** Call when the pledge has been successfully canceled. */ fun pledgeSuccessfullyCancelled() /** Call when the pledge has been successfully created. */ fun pledgeSuccessfullyCreated(checkoutDataAndPledgeData: Pair<CheckoutData, PledgeData>) /** Call when the pledge has been successfully updated. */ fun pledgeSuccessfullyUpdated() /** Call when the user clicks the navigation icon of the pledge toolbar. */ fun pledgeToolbarNavigationClicked() /** Call when the user has triggered a manual refresh of the project. */ fun refreshProject() /** Call when the reload container is clicked. */ fun reloadProjectContainerClicked() /** Call when the share button is clicked. */ fun shareButtonClicked() /** Call when the update payment option is clicked. */ fun updatePaymentClicked() /** Call when the update pledge option is clicked. */ fun updatePledgeClicked() /** Call when the updates button is clicked. */ fun updatesTextViewClicked() /** Call when the view rewards option is clicked. */ fun viewRewardsClicked() /** Call when some tab on the Tablayout has been pressed, with the position */ fun tabSelected(position: Int) fun closeFullScreenVideo(seekPosition: Long) fun onVideoPlayButtonClicked() } interface Outputs { /** Emits a boolean that determines if the backing details should be visible. */ fun backingDetailsIsVisible(): Observable<Boolean> /** Emits a string or string resource ID of the backing details subtitle. */ fun backingDetailsSubtitle(): Observable<Either<String, Int>?> /** Emits the string resource ID of the backing details title. */ fun backingDetailsTitle(): Observable<Int> /** Emits when rewards sheet should expand and if it should animate. */ fun expandPledgeSheet(): Observable<Pair<Boolean, Boolean>> /** Emits when we should go back in the navigation hierarchy. */ fun goBack(): Observable<Void> /** Emits a drawable id that corresponds to whether the project is saved. */ fun heartDrawableId(): Observable<Int> /** Emits a menu for managing your pledge or null if there's no menu. */ fun managePledgeMenu(): Observable<Int?> /** Emits the color resource ID for the pledge action button. */ fun pledgeActionButtonColor(): Observable<Int> /** Emits a boolean that determines if the pledge action button container should be visible. */ fun pledgeActionButtonContainerIsGone(): Observable<Boolean> /** Emits the string resource ID for the pledge action button. */ fun pledgeActionButtonText(): Observable<Int> /** Emits the proper string resource ID for the pledge toolbar navigation icon. */ fun pledgeToolbarNavigationIcon(): Observable<Int> /** Emits the proper string resource ID for the pledge toolbar title. */ fun pledgeToolbarTitle(): Observable<Int> /** Emits the url of a prelaunch activated project to open in the browser. */ fun prelaunchUrl(): Observable<String> /** Emits [ProjectData]. If the view model is created with a full project * model, this observable will emit that project immediately, and then again when it has updated from the api. */ fun projectData(): Observable<ProjectData> /** Emits a boolean that determines if the reload project container should be visible. */ fun reloadProjectContainerIsGone(): Observable<Boolean> /** Emits a boolean that determines if the progress bar in the retry container should be visible. */ fun reloadProgressBarIsGone(): Observable<Boolean> /** Emits when we should reveal the [com.kickstarter.ui.fragments.RewardsFragment] with an animation. */ fun revealRewardsFragment(): Observable<Void> /** Emits a boolean that determines if the scrim for secondary pledging actions should be visible. */ fun scrimIsVisible(): Observable<Boolean> /** Emits when we should set the Y position of the rewards container. */ fun setInitialRewardsContainerY(): Observable<Void> /** Emits when we should show the [com.kickstarter.ui.fragments.CancelPledgeFragment]. */ fun showCancelPledgeFragment(): Observable<Project> /** Emits when the backing has successfully been canceled. */ fun showCancelPledgeSuccess(): Observable<Void> /** Emits when we should show the not cancelable dialog. */ fun showPledgeNotCancelableDialog(): Observable<Void> /** Emits when the success prompt for saving should be displayed. */ fun showSavedPrompt(): Observable<Void> /** Emits when we should show the share sheet with the name of the project and share URL. */ fun showShareSheet(): Observable<Pair<String, String>> /** Emits when we should show the [com.kickstarter.ui.fragments.PledgeFragment]. */ fun showUpdatePledge(): Observable<Triple<PledgeData, PledgeReason, Boolean>> /** Emits when the backing has successfully been updated. */ fun showUpdatePledgeSuccess(): Observable<Void> /** Emits when we should start [com.kickstarter.ui.activities.RootCommentsActivity]. */ fun startRootCommentsActivity(): Observable<ProjectData> fun startRootCommentsForCommentsThreadActivity(): Observable<Pair<String, ProjectData>> /** Emits when we should start [com.kickstarter.ui.activities.LoginToutActivity]. */ fun startLoginToutActivity(): Observable<Void> /** Emits when we should show the [com.kickstarter.ui.activities.MessagesActivity]. */ fun startMessagesActivity(): Observable<Project> /** Emits when we should start [com.kickstarter.ui.activities.UpdateActivity]. */ fun startProjectUpdateActivity(): Observable< Pair<Pair<String, Boolean>, Pair<Project, ProjectData>>> /** Emits when we should start [com.kickstarter.ui.activities.UpdateActivity]. */ fun startProjectUpdateToRepliesDeepLinkActivity(): Observable< Pair<Pair<String, String>, Pair<Project, ProjectData>>> /** Emits when we the pledge was successful and should start the [com.kickstarter.ui.activities.ThanksActivity]. */ fun startThanksActivity(): Observable<Pair<CheckoutData, PledgeData>> /** Emits when we should update the [com.kickstarter.ui.fragments.BackingFragment] and [com.kickstarter.ui.fragments.RewardsFragment]. */ fun updateFragments(): Observable<ProjectData> fun projectMedia(): Observable<MediaElement> /** Emits when the play button should be gone. */ fun playButtonIsVisible(): Observable<Boolean> /** Emits when the backing view group should be gone. */ fun backingViewGroupIsVisible(): Observable<Boolean> /** Will emmit the need to show/hide the Campaign Tab and the Environmental Tab. */ fun updateTabs(): Observable<Boolean> fun hideVideoPlayer(): Observable<Boolean> fun onOpenVideoInFullScreen(): Observable<kotlin.Pair<String, Long>> fun updateVideoCloseSeekPosition(): Observable<Long> } class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<ProjectPageActivity>(environment), Inputs, Outputs { private val cookieManager = requireNotNull(environment.cookieManager()) private val currentUser = requireNotNull(environment.currentUser()) private val ksCurrency = requireNotNull(environment.ksCurrency()) private val optimizely = requireNotNull(environment.optimizely()) private val sharedPreferences = requireNotNull(environment.sharedPreferences()) private val apolloClient = requireNotNull(environment.apolloClient()) private val currentConfig = requireNotNull(environment.currentConfig()) private val closeFullScreenVideo = BehaviorSubject.create<Long>() private val cancelPledgeClicked = PublishSubject.create<Void>() private val commentsTextViewClicked = PublishSubject.create<Void>() private val contactCreatorClicked = PublishSubject.create<Void>() private val fixPaymentMethodButtonClicked = PublishSubject.create<Void>() private val fragmentStackCount = PublishSubject.create<Int>() private val heartButtonClicked = PublishSubject.create<Void>() private val nativeProjectActionButtonClicked = PublishSubject.create<Void>() private val onGlobalLayout = PublishSubject.create<Void>() private val fullScreenVideoButtonClicked = PublishSubject.create<kotlin.Pair<String, Long>>() private val pledgePaymentSuccessfullyUpdated = PublishSubject.create<Void>() private val pledgeSuccessfullyCancelled = PublishSubject.create<Void>() private val pledgeSuccessfullyCreated = PublishSubject.create<Pair<CheckoutData, PledgeData>>() private val pledgeSuccessfullyUpdated = PublishSubject.create<Void>() private val pledgeToolbarNavigationClicked = PublishSubject.create<Void>() private val refreshProject = PublishSubject.create<Void>() private val reloadProjectContainerClicked = PublishSubject.create<Void>() private val shareButtonClicked = PublishSubject.create<Void>() private val updatePaymentClicked = PublishSubject.create<Void>() private val updatePledgeClicked = PublishSubject.create<Void>() private val updatesTextViewClicked = PublishSubject.create<Void>() private val viewRewardsClicked = PublishSubject.create<Void>() private val onVideoPlayButtonClicked = PublishSubject.create<Void>() private val backingDetailsIsVisible = BehaviorSubject.create<Boolean>() private val backingDetailsSubtitle = BehaviorSubject.create<Either<String, Int>?>() private val backingDetailsTitle = BehaviorSubject.create<Int>() private val expandPledgeSheet = BehaviorSubject.create<Pair<Boolean, Boolean>>() private val goBack = PublishSubject.create<Void>() private val heartDrawableId = BehaviorSubject.create<Int>() private val managePledgeMenu = BehaviorSubject.create<Int?>() private val pledgeActionButtonColor = BehaviorSubject.create<Int>() private val pledgeActionButtonContainerIsGone = BehaviorSubject.create<Boolean>() private val pledgeActionButtonText = BehaviorSubject.create<Int>() private val pledgeToolbarNavigationIcon = BehaviorSubject.create<Int>() private val pledgeToolbarTitle = BehaviorSubject.create<Int>() private val prelaunchUrl = BehaviorSubject.create<String>() private val projectData = BehaviorSubject.create<ProjectData>() private val retryProgressBarIsGone = BehaviorSubject.create<Boolean>() private val reloadProjectContainerIsGone = BehaviorSubject.create<Boolean>() private val revealRewardsFragment = PublishSubject.create<Void>() private val scrimIsVisible = BehaviorSubject.create<Boolean>() private val setInitialRewardPosition = BehaviorSubject.create<Void>() private val showCancelPledgeFragment = PublishSubject.create<Project>() private val showCancelPledgeSuccess = PublishSubject.create<Void>() private val showPledgeNotCancelableDialog = PublishSubject.create<Void>() private val showShareSheet = PublishSubject.create<Pair<String, String>>() private val showSavedPrompt = PublishSubject.create<Void>() private val updatePledgeData = PublishSubject.create<Pair<PledgeData, PledgeReason>>() private val showUpdatePledge = PublishSubject.create<Triple<PledgeData, PledgeReason, Boolean>>() private val showUpdatePledgeSuccess = PublishSubject.create<Void>() private val startRootCommentsActivity = PublishSubject.create<ProjectData>() private val startRootCommentsForCommentsThreadActivity = PublishSubject.create<Pair<String, ProjectData>>() private val startLoginToutActivity = PublishSubject.create<Void>() private val startMessagesActivity = PublishSubject.create<Project>() private val startProjectUpdateActivity = PublishSubject.create< Pair<Pair<String, Boolean>, Pair<Project, ProjectData>>>() private val startProjectUpdateToRepliesDeepLinkActivity = PublishSubject.create< Pair<Pair<String, String>, Pair<Project, ProjectData>>>() private val startThanksActivity = PublishSubject.create<Pair<CheckoutData, PledgeData>>() private val updateFragments = BehaviorSubject.create<ProjectData>() private val hideVideoPlayer = BehaviorSubject.create<Boolean>() private val tabSelected = PublishSubject.create<Int>() private val projectMedia = PublishSubject.create<MediaElement>() private val playButtonIsVisible = PublishSubject.create<Boolean>() private val backingViewGroupIsVisible = PublishSubject.create<Boolean>() private val updateTabs = PublishSubject.create< Boolean>() private val onOpenVideoInFullScreen = PublishSubject.create<kotlin.Pair<String, Long>>() private val updateVideoCloseSeekPosition = BehaviorSubject.create< Long>() val inputs: Inputs = this val outputs: Outputs = this init { val progressBarIsGone = PublishSubject.create<Boolean>() val mappedProjectNotification = Observable.merge( intent(), intent() .compose(takeWhen<Intent, Void>(this.reloadProjectContainerClicked)) ) .switchMap { ProjectIntentMapper.project(it, this.apolloClient) .doOnSubscribe { progressBarIsGone.onNext(false) } .doAfterTerminate { progressBarIsGone.onNext(true) } .withLatestFrom(currentConfig.observable(), currentUser.observable()) { project, config, user -> return@withLatestFrom project.updateProjectWith(config, user) } .materialize() } .share() activityResult() .filter { it.isOk } .filter { it.isRequestCode(ActivityRequestCodes.SHOW_REWARDS) } .compose(bindToLifecycle()) .subscribe { this.expandPledgeSheet.onNext(Pair(true, true)) } intent() .take(1) .filter { it.getBooleanExtra(IntentKey.EXPAND_PLEDGE_SHEET, false) } .compose(bindToLifecycle()) .subscribe { this.expandPledgeSheet.onNext(Pair(true, true)) } val pledgeSheetExpanded = this.expandPledgeSheet .map { it.first } .startWith(false) progressBarIsGone .compose(bindToLifecycle()) .subscribe(this.retryProgressBarIsGone) val mappedProjectValues = mappedProjectNotification .compose(values()) val mappedProjectErrors = mappedProjectNotification .compose(errors()) mappedProjectValues .filter { it.displayPrelaunch().isTrue() } .map { it.webProjectUrl() } .compose(bindToLifecycle()) .subscribe(this.prelaunchUrl) val initialProject = mappedProjectValues .filter { it.displayPrelaunch().isFalse() } // An observable of the ref tag stored in the cookie for the project. Can emit `null`. val cookieRefTag = initialProject .take(1) .map { p -> RefTagUtils.storedCookieRefTagForProject(p, this.cookieManager, this.sharedPreferences) } val refTag = intent() .flatMap { ProjectIntentMapper.refTag(it) } val saveProjectFromDeepLinkActivity = intent() .take(1) .delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel .filter { it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_SAVE, false) } .flatMap { ProjectIntentMapper.deepLinkSaveFlag(it) } val saveProjectFromDeepUrl = intent() .take(1) .delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel .filter { ObjectUtils.isNotNull(it.data) } .map { requireNotNull(it.data) } .filter { ProjectIntentMapper.hasSaveQueryFromUri(it) } .map { UrlUtils.saveFlag(it.toString()) } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } val loggedInUserOnHeartClick = this.currentUser.observable() .compose<User>(takeWhen(this.heartButtonClicked)) .filter { u -> u != null } val loggedOutUserOnHeartClick = this.currentUser.observable() .compose<User>(takeWhen(this.heartButtonClicked)) .filter { u -> u == null } val projectOnUserChangeSave = initialProject .compose(takeWhen<Project, User>(loggedInUserOnHeartClick)) .withLatestFrom(projectData) { initProject, latestProjectData -> if (latestProjectData.project().isStarred() != initProject.isStarred()) latestProjectData.project() else initProject } .switchMap { this.toggleProjectSave(it) } .share() val refreshProjectEvent = Observable.merge( this.pledgeSuccessfullyCancelled, this.pledgeSuccessfullyCreated.compose(ignoreValues()), this.pledgeSuccessfullyUpdated, this.pledgePaymentSuccessfullyUpdated, this.refreshProject ) val refreshedProjectNotification = initialProject .compose(takeWhen<Project, Void>(refreshProjectEvent)) .switchMap { it.slug()?.let { slug -> this.apolloClient.getProject(slug) .doOnSubscribe { progressBarIsGone.onNext(false) } .doAfterTerminate { progressBarIsGone.onNext(true) } .withLatestFrom(currentConfig.observable(), currentUser.observable()) { project, config, user -> return@withLatestFrom project.updateProjectWith(config, user) } .materialize() } } .share() loggedOutUserOnHeartClick .compose(ignoreValues()) .subscribe(this.startLoginToutActivity) val savedProjectOnLoginSuccess = this.startLoginToutActivity .compose<Pair<Void, User>>(combineLatestPair(this.currentUser.observable())) .filter { su -> su.second != null } .withLatestFrom<Project, Project>(initialProject) { _, p -> p } .take(1) .switchMap { this.saveProject(it) } .share() val projectOnDeepLinkChangeSave = Observable.merge(saveProjectFromDeepLinkActivity, saveProjectFromDeepUrl) .compose(combineLatestPair(this.currentUser.observable())) .filter { it.second != null } .withLatestFrom(initialProject) { userAndFlag, p -> Pair(userAndFlag, p) } .take(1) .filter { it.second.isStarred() != it.first.first }.switchMap { if (it.first.first) { this.saveProject(it.second) } else { this.unSaveProject(it.second) } }.share() val currentProject = Observable.merge( initialProject, refreshedProjectNotification.compose(values()), projectOnUserChangeSave, savedProjectOnLoginSuccess, projectOnDeepLinkChangeSave ) val projectSavedStatus = Observable.merge(projectOnUserChangeSave, savedProjectOnLoginSuccess, projectOnDeepLinkChangeSave) projectSavedStatus .compose(bindToLifecycle()) .subscribe { this.analyticEvents.trackWatchProjectCTA(it, PROJECT) } projectSavedStatus .filter { p -> p.isStarred() && p.isLive && !p.isApproachingDeadline } .compose(ignoreValues()) .compose(bindToLifecycle()) .subscribe(this.showSavedPrompt) val currentProjectData = Observable.combineLatest<RefTag, RefTag, Project, ProjectData>(refTag, cookieRefTag, currentProject) { refTagFromIntent, refTagFromCookie, project -> projectData(refTagFromIntent, refTagFromCookie, project) } currentProjectData .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { this.projectData.onNext(it) val showEnvironmentalTab = it.project().envCommitments()?.isNotEmpty() ?: false this.updateTabs.onNext(showEnvironmentalTab) } currentProject .compose<Project>(takeWhen(this.shareButtonClicked)) .map { Pair(it.name(), UrlUtils.appendRefTag(it.webProjectUrl(), RefTag.projectShare().tag())) } .compose(bindToLifecycle()) .subscribe(this.showShareSheet) val latestProjectAndProjectData = currentProject.compose<Pair<Project, ProjectData>>(combineLatestPair(projectData)) intent() .take(1) .delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel .filter { it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_COMMENT, false) && it.getStringExtra(IntentKey.COMMENT)?.isEmpty() ?: true } .withLatestFrom(latestProjectAndProjectData) { _, project -> project } .map { it.second } .compose(bindToLifecycle()) .subscribe { this.startRootCommentsActivity.onNext(it) } intent() .take(1) .delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel .filter { it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_COMMENT, false) && it.getStringExtra(IntentKey.COMMENT)?.isNotEmpty() ?: false } .withLatestFrom(latestProjectAndProjectData) { intent, project -> Pair(intent.getStringExtra(IntentKey.COMMENT) ?: "", project) } .map { Pair(it.first, it.second.second) } .compose(bindToLifecycle()) .subscribe { this.startRootCommentsForCommentsThreadActivity.onNext(it) } intent() .take(1) .delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel .filter { it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)?.isNotEmpty() ?: false && it.getStringExtra(IntentKey.COMMENT)?.isEmpty() ?: true }.map { Pair( requireNotNull(it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)), it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE_COMMENT, false) ) } .withLatestFrom(latestProjectAndProjectData) { updateId, project -> Pair(updateId, project) } .compose(bindToLifecycle()) .subscribe { this.startProjectUpdateActivity.onNext(it) } intent() .take(1) .delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel .filter { it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)?.isNotEmpty() ?: false && it.getStringExtra(IntentKey.COMMENT)?.isNotEmpty() ?: false }.map { Pair( requireNotNull(it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)), it.getStringExtra(IntentKey.COMMENT) ?: "" ) } .withLatestFrom(latestProjectAndProjectData) { updateId, project -> Pair(updateId, project) } .compose(bindToLifecycle()) .subscribe { this.startProjectUpdateToRepliesDeepLinkActivity.onNext(it) } fullScreenVideoButtonClicked .compose(bindToLifecycle()) .subscribe(this.onOpenVideoInFullScreen) closeFullScreenVideo .compose(bindToLifecycle()) .subscribe { updateVideoCloseSeekPosition.onNext(it) } this.onGlobalLayout .compose(bindToLifecycle()) .subscribe(this.setInitialRewardPosition) this.nativeProjectActionButtonClicked .map { Pair(true, true) } .compose(bindToLifecycle()) .subscribe(this.expandPledgeSheet) val fragmentStackCount = this.fragmentStackCount.startWith(0) fragmentStackCount .compose(takeWhen(this.pledgeToolbarNavigationClicked)) .filter { it <= 0 } .map { Pair(false, true) } .compose(bindToLifecycle()) .subscribe(this.expandPledgeSheet) fragmentStackCount .compose<Int>(takeWhen(this.pledgeToolbarNavigationClicked)) .filter { it > 0 } .compose(ignoreValues()) .compose(bindToLifecycle()) .subscribe(this.goBack) Observable.merge(this.pledgeSuccessfullyCancelled, this.pledgeSuccessfullyCreated) .map { Pair(false, false) } .compose(bindToLifecycle()) .subscribe(this.expandPledgeSheet) val projectHasRewardsAndSheetCollapsed = currentProject .map { it.hasRewards() } .distinctUntilChanged() .compose<Pair<Boolean, Boolean>>(combineLatestPair(pledgeSheetExpanded)) .filter { it.second.isFalse() } .map { it.first } val rewardsLoaded = projectHasRewardsAndSheetCollapsed .filter { it.isTrue() } .map { true } Observable.merge(rewardsLoaded, this.reloadProjectContainerClicked.map { true }) .compose(bindToLifecycle()) .subscribe(this.reloadProjectContainerIsGone) mappedProjectErrors .map { false } .compose(bindToLifecycle()) .subscribe(this.reloadProjectContainerIsGone) projectHasRewardsAndSheetCollapsed .compose<Pair<Boolean, Boolean>>(combineLatestPair(this.retryProgressBarIsGone)) .map { (it.first && it.second).negate() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.pledgeActionButtonContainerIsGone) val projectData = Observable.combineLatest<RefTag, RefTag, Project, ProjectData>(refTag, cookieRefTag, currentProject) { refTagFromIntent, refTagFromCookie, project -> projectData(refTagFromIntent, refTagFromCookie, project) } projectData .filter { it.project().hasRewards() && !it.project().isBacking() } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.updateFragments) currentProject .compose<Pair<Project, Int>>(combineLatestPair(fragmentStackCount)) .map { managePledgeMenu(it) } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.managePledgeMenu) projectData .compose(takePairWhen(this.tabSelected)) .distinctUntilChanged() .delay(150, TimeUnit.MILLISECONDS, environment.scheduler()) // add delay to wait // until fragment subscribed to viewmodel .subscribe { this.projectData.onNext(it.first) } tabSelected .map { it != 0 } .compose(bindToLifecycle()) .subscribe { this.hideVideoPlayer.onNext(it) } val backedProject = currentProject .filter { it.isBacking() } val backing = backedProject .map { it.backing() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } // - Update fragments with the backing data projectData .filter { it.project().hasRewards() } .compose<Pair<ProjectData, Backing>>(combineLatestPair(backing)) .map { val updatedProject = if (it.first.project().isBacking()) it.first.project().toBuilder().backing(it.second).build() else it.first.project() projectData(it.first.refTagFromIntent(), it.first.refTagFromCookie(), updatedProject) } .compose(bindToLifecycle()) .subscribe(this.updateFragments) backedProject .compose<Project>(takeWhen(this.cancelPledgeClicked)) .filter { (it.backing()?.cancelable() ?: false).isTrue() } .compose(bindToLifecycle()) .subscribe(this.showCancelPledgeFragment) backedProject .compose<Project>(takeWhen(this.cancelPledgeClicked)) .filter { it.backing()?.cancelable().isFalse() } .compose(ignoreValues()) .compose(bindToLifecycle()) .subscribe(this.showPledgeNotCancelableDialog) currentProject .compose<Project>(takeWhen(this.contactCreatorClicked)) .compose(bindToLifecycle()) .subscribe(this.startMessagesActivity) val projectDataAndBackedReward = projectData .compose<Pair<ProjectData, Backing>>(combineLatestPair(backing)) .map { pD -> pD.first.project().backing()?.backedReward(pD.first.project())?.let { Pair(pD.first.toBuilder().backing(pD.second).build(), it) } } projectDataAndBackedReward .compose(takeWhen<Pair<ProjectData, Reward>, Void>(this.fixPaymentMethodButtonClicked)) .map { Pair(pledgeData(it.second, it.first, PledgeFlowContext.FIX_ERRORED_PLEDGE), PledgeReason.FIX_PLEDGE) } .compose(bindToLifecycle()) .subscribe(this.updatePledgeData) projectDataAndBackedReward .compose(takeWhen<Pair<ProjectData, Reward>, Void>(this.updatePaymentClicked)) .map { Pair(pledgeData(it.second, it.first, PledgeFlowContext.MANAGE_REWARD), PledgeReason.UPDATE_PAYMENT) } .compose(bindToLifecycle()) .subscribe { this.updatePledgeData.onNext(it) this.analyticEvents.trackChangePaymentMethod(it.first) } projectDataAndBackedReward .compose(takeWhen<Pair<ProjectData, Reward>, Void>(this.updatePledgeClicked)) .map { Pair(pledgeData(it.second, it.first, PledgeFlowContext.MANAGE_REWARD), PledgeReason.UPDATE_PLEDGE) } .compose(bindToLifecycle()) .subscribe(this.updatePledgeData) this.viewRewardsClicked .compose(bindToLifecycle()) .subscribe(this.revealRewardsFragment) currentProject .map { it.isBacking() && it.isLive || it.backing()?.isErrored() == true } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.backingDetailsIsVisible) currentProject .filter { it.isBacking() } .map { if (it.backing()?.isErrored() == true) R.string.Payment_failure else R.string.Youre_a_backer } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.backingDetailsTitle) currentProject .filter { it.isBacking() } .map { backingDetailsSubtitle(it) } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.backingDetailsSubtitle) val currentProjectAndUser = currentProject .compose<Pair<Project, User>>(combineLatestPair(this.currentUser.observable())) Observable.combineLatest(currentProjectData, this.currentUser.observable()) { data, user -> val experimentData = ExperimentData(user, data.refTagFromIntent(), data.refTagFromCookie()) ProjectViewUtils.pledgeActionButtonText( data.project(), user, this.optimizely?.variant(OptimizelyExperiment.Key.PLEDGE_CTA_COPY, experimentData) ) } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.pledgeActionButtonText) currentProject .compose<Pair<Project, Int>>(combineLatestPair(fragmentStackCount)) .map { if (it.second <= 0) R.drawable.ic_arrow_down else R.drawable.ic_arrow_back } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.pledgeToolbarNavigationIcon) currentProjectAndUser .map { ProjectViewUtils.pledgeToolbarTitle(it.first, it.second) } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.pledgeToolbarTitle) currentProjectAndUser .map { ProjectViewUtils.pledgeActionButtonColor(it.first, it.second) } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.pledgeActionButtonColor) this.pledgePaymentSuccessfullyUpdated .compose(bindToLifecycle()) .subscribe(this.showUpdatePledgeSuccess) this.pledgeSuccessfullyCancelled .compose(bindToLifecycle()) .subscribe(this.showCancelPledgeSuccess) this.pledgeSuccessfullyCreated .compose(bindToLifecycle()) .subscribe(this.startThanksActivity) this.pledgeSuccessfullyUpdated .compose(bindToLifecycle()) .subscribe(this.showUpdatePledgeSuccess) this.fragmentStackCount .compose<Pair<Int, Project>>(combineLatestPair(currentProject)) .map { if (it.second.isBacking()) it.first > 4 else it.first > 3 } .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe(this.scrimIsVisible) currentProject .map { p -> if (p.isStarred()) R.drawable.icon__heart else R.drawable.icon__heart_outline } .subscribe(this.heartDrawableId) val projectPhoto = currentProject .map { it.photo()?.full() } .filter { ObjectUtils.isNotNull(it) } .map { requireNotNull(it) } val projectVideo = currentProject.map { it.video() } .map { it?.hls() ?: it?.high() } .distinctUntilChanged() .take(1) projectPhoto .compose(combineLatestPair(projectVideo)) .compose(bindToLifecycle()) .subscribe { this.projectMedia.onNext(MediaElement(VideoModelElement(it.second), it.first)) } currentProject .map { it.hasVideo() } .subscribe(this.playButtonIsVisible) // Tracking val currentFullProjectData = currentProjectData .filter { it.project().hasRewards() } val fullProjectDataAndCurrentUser = currentFullProjectData .compose<Pair<ProjectData, User?>>(combineLatestPair(this.currentUser.observable())) val fullProjectDataAndPledgeFlowContext = fullProjectDataAndCurrentUser .map { Pair(it.first, pledgeFlowContext(it.first.project(), it.second)) } fullProjectDataAndPledgeFlowContext .take(1) .compose(bindToLifecycle()) .subscribe { projectDataAndPledgeFlowContext -> val data = projectDataAndPledgeFlowContext.first val pledgeFlowContext = projectDataAndPledgeFlowContext.second // If a cookie hasn't been set for this ref+project then do so. if (data.refTagFromCookie() == null) { data.refTagFromIntent()?.let { RefTagUtils.storeCookie(it, data.project(), this.cookieManager, this.sharedPreferences) } } val dataWithStoredCookieRefTag = storeCurrentCookieRefTag(data) this.analyticEvents.trackProjectScreenViewed(dataWithStoredCookieRefTag, OVERVIEW.contextName) } fullProjectDataAndPledgeFlowContext .map { it.first } .take(1) .compose(takePairWhen(this.tabSelected)) .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { this.analyticEvents.trackProjectPageTabChanged(it.first, getSelectedTabContextName(it.second)) } fullProjectDataAndPledgeFlowContext .compose<Pair<ProjectData, PledgeFlowContext?>>(takeWhen(this.nativeProjectActionButtonClicked)) .filter { it.first.project().isLive && !it.first.project().isBacking() } .compose(bindToLifecycle()) .subscribe { this.analyticEvents.trackPledgeInitiateCTA(it.first) } currentProject .map { it.metadataForProject() } .map { ProjectMetadata.BACKING == it } .compose(bindToLifecycle()) .subscribe(backingViewGroupIsVisible) ShowPledgeFragmentUseCase(this.updatePledgeData) .data(currentUser.observable(), this.optimizely) .compose(bindToLifecycle()) .subscribe { this.showUpdatePledge.onNext(it) } onVideoPlayButtonClicked .distinctUntilChanged() .compose(bindToLifecycle()) .subscribe { backingViewGroupIsVisible.onNext(false) } } private fun getSelectedTabContextName(selectedTabIndex: Int): String = when (selectedTabIndex) { ProjectPagerTabs.OVERVIEW.ordinal -> OVERVIEW.contextName ProjectPagerTabs.CAMPAIGN.ordinal -> CAMPAIGN.contextName ProjectPagerTabs.FAQS.ordinal -> FAQS.contextName ProjectPagerTabs.RISKS.ordinal -> RISKS.contextName ProjectPagerTabs.ENVIRONMENTAL_COMMITMENT.ordinal -> ENVIRONMENT.contextName else -> OVERVIEW.contextName } private fun managePledgeMenu(projectAndFragmentStackCount: Pair<Project, Int>): Int? { val project = projectAndFragmentStackCount.first val count = projectAndFragmentStackCount.second return when { !project.isBacking() || count.isNonZero() -> null project.isLive -> when { project.backing()?.status() == Backing.STATUS_PREAUTH -> R.menu.manage_pledge_preauth else -> R.menu.manage_pledge_live } else -> R.menu.manage_pledge_ended } } private fun pledgeData(reward: Reward, projectData: ProjectData, pledgeFlowContext: PledgeFlowContext): PledgeData { return PledgeData.with(pledgeFlowContext, projectData, reward) } private fun pledgeFlowContext(project: Project, currentUser: User?): PledgeFlowContext? { return when { project.userIsCreator(currentUser) -> null project.isLive && !project.isBacking() -> PledgeFlowContext.NEW_PLEDGE !project.isLive && project.backing()?.isErrored() ?: false -> PledgeFlowContext.FIX_ERRORED_PLEDGE else -> null } } private fun projectData(refTagFromIntent: RefTag?, refTagFromCookie: RefTag?, project: Project): ProjectData { return ProjectData .builder() .refTagFromIntent(refTagFromIntent) .refTagFromCookie(refTagFromCookie) .project(project) .build() } private fun storeCurrentCookieRefTag(data: ProjectData): ProjectData { return data .toBuilder() .refTagFromCookie(RefTagUtils.storedCookieRefTagForProject(data.project(), cookieManager, sharedPreferences)) .build() } override fun tabSelected(position: Int) { this.tabSelected.onNext(position) } override fun cancelPledgeClicked() { this.cancelPledgeClicked.onNext(null) } override fun commentsTextViewClicked() { this.commentsTextViewClicked.onNext(null) } override fun contactCreatorClicked() { this.contactCreatorClicked.onNext(null) } override fun fixPaymentMethodButtonClicked() { this.fixPaymentMethodButtonClicked.onNext(null) } override fun fragmentStackCount(count: Int) { this.fragmentStackCount.onNext(count) } override fun heartButtonClicked() { this.heartButtonClicked.onNext(null) } override fun nativeProjectActionButtonClicked() { this.nativeProjectActionButtonClicked.onNext(null) } override fun onGlobalLayout() { this.onGlobalLayout.onNext(null) } override fun pledgePaymentSuccessfullyUpdated() { this.pledgePaymentSuccessfullyUpdated.onNext(null) } override fun pledgeSuccessfullyCancelled() { this.pledgeSuccessfullyCancelled.onNext(null) } override fun pledgeSuccessfullyCreated(checkoutDataAndPledgeData: Pair<CheckoutData, PledgeData>) { this.pledgeSuccessfullyCreated.onNext(checkoutDataAndPledgeData) } override fun pledgeSuccessfullyUpdated() { this.pledgeSuccessfullyUpdated.onNext(null) } override fun pledgeToolbarNavigationClicked() { this.pledgeToolbarNavigationClicked.onNext(null) } override fun refreshProject() { this.refreshProject.onNext(null) } override fun reloadProjectContainerClicked() { this.reloadProjectContainerClicked.onNext(null) } override fun shareButtonClicked() { this.shareButtonClicked.onNext(null) } override fun updatePaymentClicked() { this.updatePaymentClicked.onNext(null) } override fun updatePledgeClicked() { this.updatePledgeClicked.onNext(null) } override fun updatesTextViewClicked() { this.updatesTextViewClicked.onNext(null) } override fun viewRewardsClicked() { this.viewRewardsClicked.onNext(null) } override fun fullScreenVideoButtonClicked(videoInfo: kotlin.Pair<String, Long>) { fullScreenVideoButtonClicked.onNext(videoInfo) } override fun closeFullScreenVideo(position: Long) = closeFullScreenVideo.onNext(position) override fun onVideoPlayButtonClicked() = onVideoPlayButtonClicked.onNext(null) override fun updateVideoCloseSeekPosition(): Observable< Long> = updateVideoCloseSeekPosition @NonNull override fun backingDetailsSubtitle(): Observable<Either<String, Int>?> = this.backingDetailsSubtitle @NonNull override fun backingDetailsTitle(): Observable<Int> = this.backingDetailsTitle @NonNull override fun backingDetailsIsVisible(): Observable<Boolean> = this.backingDetailsIsVisible @NonNull override fun expandPledgeSheet(): Observable<Pair<Boolean, Boolean>> = this.expandPledgeSheet @NonNull override fun goBack(): Observable<Void> = this.goBack @NonNull override fun heartDrawableId(): Observable<Int> = this.heartDrawableId @NonNull override fun managePledgeMenu(): Observable<Int?> = this.managePledgeMenu @NonNull override fun pledgeActionButtonColor(): Observable<Int> = this.pledgeActionButtonColor @NonNull override fun pledgeActionButtonContainerIsGone(): Observable<Boolean> = this.pledgeActionButtonContainerIsGone @NonNull override fun pledgeActionButtonText(): Observable<Int> = this.pledgeActionButtonText @NonNull override fun pledgeToolbarNavigationIcon(): Observable<Int> = this.pledgeToolbarNavigationIcon @NonNull override fun pledgeToolbarTitle(): Observable<Int> = this.pledgeToolbarTitle @NonNull override fun prelaunchUrl(): Observable<String> = this.prelaunchUrl @NonNull override fun projectData(): Observable<ProjectData> = this.projectData @NonNull override fun reloadProjectContainerIsGone(): Observable<Boolean> = this.reloadProjectContainerIsGone @NonNull override fun reloadProgressBarIsGone(): Observable<Boolean> = this.retryProgressBarIsGone @NonNull override fun revealRewardsFragment(): Observable<Void> = this.revealRewardsFragment @NonNull override fun scrimIsVisible(): Observable<Boolean> = this.scrimIsVisible @NonNull override fun setInitialRewardsContainerY(): Observable<Void> = this.setInitialRewardPosition @NonNull override fun showCancelPledgeFragment(): Observable<Project> = this.showCancelPledgeFragment @NonNull override fun showCancelPledgeSuccess(): Observable<Void> = this.showCancelPledgeSuccess @NonNull override fun showPledgeNotCancelableDialog(): Observable<Void> = this.showPledgeNotCancelableDialog @NonNull override fun showSavedPrompt(): Observable<Void> = this.showSavedPrompt @NonNull override fun showShareSheet(): Observable<Pair<String, String>> = this.showShareSheet @NonNull override fun showUpdatePledge(): Observable<Triple<PledgeData, PledgeReason, Boolean>> = this.showUpdatePledge @NonNull override fun showUpdatePledgeSuccess(): Observable<Void> = this.showUpdatePledgeSuccess @NonNull override fun startRootCommentsActivity(): Observable<ProjectData> = this.startRootCommentsActivity @NonNull override fun startRootCommentsForCommentsThreadActivity(): Observable<Pair<String, ProjectData>> = this.startRootCommentsForCommentsThreadActivity @NonNull override fun startLoginToutActivity(): Observable<Void> = this.startLoginToutActivity @NonNull override fun startMessagesActivity(): Observable<Project> = this.startMessagesActivity @NonNull override fun startThanksActivity(): Observable<Pair<CheckoutData, PledgeData>> = this.startThanksActivity @NonNull override fun startProjectUpdateActivity(): Observable<Pair<Pair<String, Boolean>, Pair<Project, ProjectData>>> = this.startProjectUpdateActivity @NonNull override fun startProjectUpdateToRepliesDeepLinkActivity(): Observable<Pair<Pair<String, String>, Pair<Project, ProjectData>>> = this.startProjectUpdateToRepliesDeepLinkActivity @NonNull override fun onOpenVideoInFullScreen(): Observable<kotlin.Pair<String, Long>> = this.onOpenVideoInFullScreen @NonNull override fun updateTabs(): Observable<Boolean> = this.updateTabs @NonNull override fun hideVideoPlayer(): Observable<Boolean> = this.hideVideoPlayer @NonNull override fun updateFragments(): Observable<ProjectData> = this.updateFragments @NonNull override fun projectMedia(): Observable<MediaElement> = this.projectMedia @NonNull override fun playButtonIsVisible(): Observable<Boolean> = this.playButtonIsVisible @NonNull override fun backingViewGroupIsVisible(): Observable<Boolean> = this.backingViewGroupIsVisible private fun backingDetailsSubtitle(project: Project): Either<String, Int>? { return project.backing()?.let { backing -> return if (backing.status() == Backing.STATUS_ERRORED) { Either.Right(R.string.We_cant_process_your_pledge) } else { val reward = project.rewards()?.firstOrNull { it.id() == backing.rewardId() } val title = reward?.let { "• ${it.title()}" } ?: "" val backingAmount = backing.amount() val formattedAmount = this.ksCurrency.format(backingAmount, project, RoundingMode.HALF_UP) Either.Left("$formattedAmount $title".trim()) } } } private fun saveProject(project: Project): Observable<Project> { return this.apolloClient.watchProject(project) .compose(neverError()) } private fun unSaveProject(project: Project): Observable<Project> { return this.apolloClient.unWatchProject(project).compose(neverError()) } private fun toggleProjectSave(project: Project): Observable<Project> { return if (project.isStarred()) unSaveProject(project) else saveProject(project) } } }
app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectPageViewModel.kt
3116044789
package de.fabmax.kool.physics import de.fabmax.kool.math.Mat4f import de.fabmax.kool.physics.geometry.CollisionGeometry expect class Shape( geometry: CollisionGeometry, material: Material = Physics.defaultMaterial, localPose: Mat4f = Mat4f(), simFilterData: FilterData? = null, queryFilterData: FilterData? = null ) { val geometry: CollisionGeometry val material: Material val localPose: Mat4f val simFilterData: FilterData? val queryFilterData: FilterData? }
kool-physics/src/commonMain/kotlin/de/fabmax/kool/physics/Shape.kt
3706895997
/* * Copyright 2022 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tensorflow.lite.examples.modelpersonalization.fragments import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import androidx.fragment.app.activityViewModels import org.tensorflow.lite.examples.modelpersonalization.MainViewModel import org.tensorflow.lite.examples.modelpersonalization.databinding.FragmentSettingBinding class SettingFragment : DialogFragment() { companion object { const val TAG = "SettingDialogFragment" } private var _fragmentSettingBinding: FragmentSettingBinding? = null private val fragmentSettingBinding get() = _fragmentSettingBinding!! private var numThreads = 2 private val viewModel: MainViewModel by activityViewModels() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return super.onCreateDialog(savedInstanceState).apply { setCancelable(false) setCanceledOnTouchOutside(false) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _fragmentSettingBinding = FragmentSettingBinding.inflate( inflater, container, false ) return fragmentSettingBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.getNumThreads()?.let { numThreads = it updateDialogUi() } initDialogControls() fragmentSettingBinding.btnConfirm.setOnClickListener { viewModel.configModel(numThreads) dismiss() } fragmentSettingBinding.btnCancel.setOnClickListener { dismiss() } } private fun initDialogControls() { // When clicked, decrease the number of threads used for classification fragmentSettingBinding.threadsMinus.setOnClickListener { if (numThreads > 1) { numThreads-- updateDialogUi() } } // When clicked, increase the number of threads used for classification fragmentSettingBinding.threadsPlus.setOnClickListener { if (numThreads < 4) { numThreads++ updateDialogUi() } } } // Update the values displayed in the dialog. private fun updateDialogUi() { fragmentSettingBinding.threadsValue.text = numThreads.toString() } }
lite/examples/model_personalization/android/app/src/main/java/org/tensorflow/lite/examples/modelpersonalization/fragments/SettingFragment.kt
2344304880
package com.example.testmodule1 import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.common.anotherSampleTestMethod import com.example.common.ignoredTest import com.example.common.testSampleMethod import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ModuleTests { @Test fun sampleTest() { testSampleMethod() } @Test fun sampleTest2() { anotherSampleTestMethod() } @Test @Ignore("For testing #818") fun sampleTest3() { ignoredTest() } }
test_projects/android/multi-modules/testModule1/src/androidTest/java/com/example/testmodule1/ModuleTests.kt
1714668368
package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class DanaRS_Packet_History_CarbohydrateTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { if (it is DanaRS_Packet) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } if (it is DanaRS_Packet_History_Carbohydrate) { it.rxBus = rxBus } } } @Test fun runTest() { val packet = DanaRS_Packet_History_Carbohydrate(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__CARBOHYDRATE", packet.friendlyName) } }
app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_CarbohydrateTest.kt
195187645
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRS_Packet_Notify_Missed_Bolus_Alarm( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { init { type = BleEncryption.DANAR_PACKET__TYPE_NOTIFY opCode = BleEncryption.DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { val startHour: Int val startMin: Int val endHour: Int val endMin: Int var dataIndex = DATA_START var dataSize = 1 startHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 startMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 endHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) dataIndex += dataSize dataSize = 1 endMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) failed = endMin == 1 && endMin == endHour && startHour == endHour && startHour == startMin aapsLogger.debug(LTag.PUMPCOMM, "Start hour: $startHour") aapsLogger.debug(LTag.PUMPCOMM, "Start min: $startMin") aapsLogger.debug(LTag.PUMPCOMM, "End hour: $endHour") aapsLogger.debug(LTag.PUMPCOMM, "End min: $endMin") } override fun getFriendlyName(): String { return "NOTIFY__MISSED_BOLUS_ALARM" } }
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.kt
1022918001
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'indexOfLast{}'" // IS_APPLICABLE_2: false // AFTER-WARNING: Variable 'result' is never used fun foo(list: List<String>) { var result = -1 <caret>for ((index, s) in list.withIndex()) { if (s.length > 0) { result = index } } }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/indexOf/indexOfLast_ifAssign.kt
1647738003
// 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 git4idea.log import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.ColorUtil import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.data.util.VcsCommitsDataLoader import com.intellij.vcs.log.ui.frame.VcsCommitExternalStatusPresentation import com.intellij.vcs.log.ui.frame.VcsCommitExternalStatusProvider import com.intellij.vcs.log.ui.table.column.util.VcsLogExternalStatusColumnService import git4idea.GitIcons import git4idea.commit.signature.GitCommitSignature import git4idea.i18n.GitBundle import org.jetbrains.annotations.Nls import javax.swing.Icon internal class GitCommitSignatureStatusProvider : VcsCommitExternalStatusProvider.WithColumn<GitCommitSignature>() { override val id = ID override val isColumnEnabledByDefault = false override val columnName = GitBundle.message("column.name.commit.signature") override fun createLoader(project: Project): VcsCommitsDataLoader<GitCommitSignature> { val loader = if (SystemInfo.isWindows) NonCancellableGitCommitSignatureLoader(project) else SimpleGitCommitSignatureLoader(project) return service<GitCommitSignatureLoaderSharedCache>().wrapWithCaching(loader) } override fun getPresentation(project: Project, status: GitCommitSignature): VcsCommitExternalStatusPresentation.Signature = GitCommitSignatureStatusPresentation(status) override fun getExternalStatusColumnService() = service<GitCommitSignatureColumnService>() override fun getStubStatus() = GitCommitSignature.NoSignature companion object { private const val ID = "Git.CommitSignature" private class GitCommitSignatureStatusPresentation(private val signature: GitCommitSignature) : VcsCommitExternalStatusPresentation.Signature { override val icon: Icon get() = when (signature) { is GitCommitSignature.Verified -> GitIcons.Verified is GitCommitSignature.NotVerified -> GitIcons.Signed GitCommitSignature.Bad -> GitIcons.Signed GitCommitSignature.NoSignature -> EmptyIcon.ICON_16 } override val text: String get() = when (signature) { is GitCommitSignature.Verified -> GitBundle.message("commit.signature.verified") is GitCommitSignature.NotVerified -> GitBundle.message("commit.signature.unverified") GitCommitSignature.Bad -> GitBundle.message("commit.signature.bad") GitCommitSignature.NoSignature -> GitBundle.message("commit.signature.none") } override val description: HtmlChunk? get() = when (signature) { is GitCommitSignature.Verified -> HtmlBuilder() .append(GitBundle.message("commit.signature.verified")).br() .br() .append(HtmlBuilder() .append(GitBundle.message("commit.signature.fingerprint")).br() .append(signature.fingerprint).br() .br() .append(GitBundle.message("commit.signature.signed.by")).br() .append(signature.user) .wrapWith(HtmlChunk.span("color: ${ColorUtil.toHtmlColor(UIUtil.getContextHelpForeground())}"))) .toFragment() is GitCommitSignature.NotVerified -> HtmlBuilder() .append(GitBundle.message("commit.signature.unverified.with.reason", getUnverifiedReason(signature.reason))) .toFragment() GitCommitSignature.Bad -> HtmlChunk.text(GitBundle.message("commit.signature.bad")) GitCommitSignature.NoSignature -> null } private fun getUnverifiedReason(reason: GitCommitSignature.VerificationFailureReason): @Nls String { return when (reason) { GitCommitSignature.VerificationFailureReason.UNKNOWN -> GitBundle.message("commit.signature.unverified.reason.unknown") GitCommitSignature.VerificationFailureReason.EXPIRED -> GitBundle.message("commit.signature.unverified.reason.expired") GitCommitSignature.VerificationFailureReason.EXPIRED_KEY -> GitBundle.message("commit.signature.unverified.reason.expired.key") GitCommitSignature.VerificationFailureReason.REVOKED_KEY -> GitBundle.message("commit.signature.unverified.reason.revoked.key") GitCommitSignature.VerificationFailureReason.CANNOT_VERIFY -> GitBundle.message("commit.signature.unverified.reason.cannot.verify") } } } } } @Service internal class GitCommitSignatureColumnService : VcsLogExternalStatusColumnService<GitCommitSignature>() { override fun getDataLoader(project: Project) = GitCommitSignatureStatusProvider().createLoader(project) }
plugins/git4idea/src/git4idea/log/GitCommitSignatureStatusProvider.kt
4165315009
// 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.coroutines import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.KotlinType class DirectUseOfResultTypeInspection : AbstractIsResultInspection( typeShortName = SHORT_NAME, typeFullName = "kotlin.Result", allowedSuffix = CATCHING, allowedNames = setOf("success", "failure", "runCatching"), suggestedFunctionNameToCall = "getOrThrow" ) { private fun MemberScope.hasCorrespondingNonCatchingFunction( nameWithoutCatching: String, valueParameters: List<ValueParameterDescriptor>, returnType: KotlinType?, extensionReceiverType: KotlinType? ): Boolean { val nonCatchingFunctions = getContributedFunctions(Name.identifier(nameWithoutCatching), NoLookupLocation.FROM_IDE) return nonCatchingFunctions.any { nonCatchingFun -> nonCatchingFun.valueParameters.size == valueParameters.size && nonCatchingFun.returnType == returnType && nonCatchingFun.extensionReceiverParameter?.type == extensionReceiverType } } private fun FunctionDescriptor.hasCorrespondingNonCatchingFunction(returnType: KotlinType, nameWithoutCatching: String): Boolean? { val scope = when (val containingDescriptor = containingDeclaration) { is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope is PackageFragmentDescriptor -> containingDescriptor.getMemberScope() else -> return null } val returnTypeArgument = returnType.arguments.firstOrNull()?.type val extensionReceiverType = extensionReceiverParameter?.type if (scope.hasCorrespondingNonCatchingFunction(nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType)) { return true } if (extensionReceiverType != null) { val extensionClassDescriptor = extensionReceiverType.constructor.declarationDescriptor as? ClassDescriptor if (extensionClassDescriptor != null) { val extensionClassScope = extensionClassDescriptor.unsubstitutedMemberScope if (extensionClassScope.hasCorrespondingNonCatchingFunction( nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType = null ) ) { return true } } } return false } override fun analyzeFunctionWithAllowedSuffix( name: String, descriptor: FunctionDescriptor, toReport: PsiElement, holder: ProblemsHolder ) { val returnType = descriptor.returnType ?: return val nameWithoutCatching = name.substringBeforeLast(CATCHING) if (descriptor.hasCorrespondingNonCatchingFunction(returnType, nameWithoutCatching) == false) { val returnTypeArgument = returnType.arguments.firstOrNull()?.type val typeName = returnTypeArgument?.constructor?.declarationDescriptor?.name?.asString() ?: "T" holder.registerProblem( toReport, KotlinBundle.message( "function.0.returning.1.without.the.corresponding", name, "$SHORT_NAME<$typeName>", nameWithoutCatching, typeName ), ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) } } } private const val SHORT_NAME = "Result" private const val CATCHING = "Catching"
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/DirectUseOfResultTypeInspection.kt
4155019816
package slatekit.telemetry import org.threeten.bp.Instant import org.threeten.bp.ZonedDateTime import slatekit.common.ext.durationFrom import slatekit.common.Identity import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference /** * Simple / Light-Weight implementation of the Metric interface for quick/in-memory purposes. * * NOTES: * 1. There is a provider/wrapper for https://micrometer.io/ available in the slatekit.providers * 2. If you are already using micro-meter, then use the wrapper above. * 3. SlateKit custom diagnostics components ( Calls, Counters, Events, Lasts ) are orthogonal to metrics * 4. SlateKit has its own ( just a few ) diagnostic level components like Calls/Counters/Events/Lasts * that are not available in other metrics libraries. These are specifically designed to work with * the Result<T, E> component in @see[slatekit.results.Result] for counting/tracking successes/failures * */ class MetricsLite( override val id: Identity, val tags:List<Tag> = listOf(), override val source: String = "slatekit", override val settings: MetricsSettings = MetricsSettings(true, true, Tags(tags)) ) : Metrics { private val counters = mutableMapOf<String, Counter>() private val gauges = mutableMapOf<String, Gauge<*>>() private val timers = mutableMapOf<String, Timer>() /** * The provider of the metrics ( Micrometer for now ) */ override val provider: Any = this override fun total(name: String): Double { return getOrCreate(name, counters) { Counter(globals(), null) }.get().toDouble() } /** * Increment a counter */ override fun count(name: String, tags: List<String>?) { getOrCreate(name, counters) { Counter(globals(), tags) }.inc() } /** * Set value on a gauge */ override fun <T> gauge(name: String, call: () -> T, tags: List<Tag>?) where T: kotlin.Number { getOrCreate(name, gauges) { Gauge(globals(), call, tags, 10) } } /** * Set value on a gauge */ override fun <T> gauge(name: String, value:T) where T: kotlin.Number { gauges[name]?.let{ (it as Gauge<T>).set(value) } } /** * Times an event */ override fun time(name: String, tags: List<String>?, call:() -> Unit ) { getOrCreate(name, timers) { Timer(globals(), tags) }.record(call) } val emptyGlobals = listOf<Tag>() private fun globals(): List<Tag> { return if (settings.standardize) settings.tags.global else emptyGlobals } private fun <T> getOrCreate(name:String, map:MutableMap<String, T>, creator:() -> T): T { return if(map.containsKey(name)){ map[name]!! } else { val item = creator() map[name] = item item } } /** * Simple timer */ data class Timer(override val tags: List<Tag>, val customTags:List<String>? = null) : Tagged { private val last = AtomicReference<Record>() private val value = AtomicLong(0L) fun record(call:() -> Unit ) { val start = ZonedDateTime.now() call() val end = ZonedDateTime.now() val diffMs = end.durationFrom(start).toMillis() last.set(Record(start.toInstant(), end.toInstant(), diffMs)) value.incrementAndGet() } data class Record(val start: Instant, val end: Instant, val diffMs:Long) } companion object { fun build(id: Identity, tags:List<Tag> = listOf()): MetricsLite { return MetricsLite(id, tags, settings = MetricsSettings(true, true, Tags(listOf()))) } } }
src/lib/kotlin/slatekit-telemetry/src/main/kotlin/slatekit/telemetry/MetricsLite.kt
2470661787
// WITH_RUNTIME fun foo() { val arrayOf = arrayOf(1, 2, 3) 0 < arrayOf.size<caret> }
plugins/kotlin/idea/tests/testData/intentions/replaceSizeCheckWithIsNotEmpty/array2.kt
3096195004
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.intellij.ide.CopyProvider import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.project.Project import com.intellij.ui.SpeedSearchComparator import com.intellij.ui.TableSpeedSearch import com.intellij.ui.TableUtil import com.intellij.ui.table.JBTable import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SelectedPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ActionsColumn import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.NameColumn import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeColumn import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionColumn import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint import com.jetbrains.packagesearch.intellij.plugin.ui.util.Displayable import com.jetbrains.packagesearch.intellij.plugin.ui.util.autosizeColumnsAt import com.jetbrains.packagesearch.intellij.plugin.ui.util.onMouseMotion import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.util.AppUI import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.awt.Dimension import java.awt.KeyboardFocusManager import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.ListSelectionModel import javax.swing.event.ListSelectionListener import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer import javax.swing.table.TableColumn import kotlin.math.roundToInt internal typealias SelectedPackageModelListener = (SelectedPackageModel<*>?) -> Unit @Suppress("MagicNumber") // Swing dimension constants internal class PackagesTable( project: Project, private val operationExecutor: OperationExecutor, operationFactory: PackageSearchOperationFactory, private val onItemSelectionChanged: SelectedPackageModelListener ) : JBTable(), CopyProvider, DataProvider, Displayable<PackagesTable.ViewModel> { private val operationFactory = PackageSearchOperationFactory() private val tableModel: PackagesTableModel get() = model as PackagesTableModel private var selectedPackage: SelectedPackageModel<*>? = null var transferFocusUp: () -> Unit = { transferFocusBackward() } private val columnWeights = listOf( .5f, // Name column .2f, // Scope column .2f, // Version column .1f // Actions column ) private val nameColumn = NameColumn() private val scopeColumn = ScopeColumn { packageModel, newScope -> updatePackageScope(packageModel, newScope) } private val versionColumn = VersionColumn { packageModel, newVersion -> updatePackageVersion(packageModel, newVersion) } private val actionsColumn = ActionsColumn( operationExecutor = ::executeUpdateActionColumnOperations, operationFactory = operationFactory ) private val actionsColumnIndex: Int private val autosizingColumnsIndices: List<Int> private var targetModules: TargetModules = TargetModules.None private var knownRepositoriesInTargetModules = KnownRepositories.InTargetModules.EMPTY private var allKnownRepositories = KnownRepositories.All.EMPTY private val listSelectionListener = ListSelectionListener { val item = getSelectedTableItem() if (selectedIndex >= 0 && item != null) { TableUtil.scrollSelectionToVisible(this) updateAndRepaint() selectedPackage = item.toSelectedPackageModule() onItemSelectionChanged(selectedPackage) PackageSearchEventsLogger.logPackageSelected(item is PackagesTableItem.InstalledPackage) } else { selectedPackage = null } } val hasInstalledItems: Boolean get() = tableModel.items.any { it is PackagesTableItem.InstalledPackage } val firstPackageIndex: Int get() = tableModel.items.indexOfFirst { it is PackagesTableItem.InstalledPackage } var selectedIndex: Int get() = selectedRow set(value) { if (tableModel.items.isNotEmpty() && (0 until tableModel.items.count()).contains(value)) { setRowSelectionInterval(value, value) } else { clearSelection() } } init { require(columnWeights.sum() == 1.0f) { "The column weights must sum to 1.0" } model = PackagesTableModel( onlyStable = PackageSearchGeneralConfiguration.getInstance(project).onlyStable, columns = arrayOf(nameColumn, scopeColumn, versionColumn, actionsColumn) ) val columnInfos = tableModel.columnInfos actionsColumnIndex = columnInfos.indexOf(actionsColumn) autosizingColumnsIndices = listOf( columnInfos.indexOf(scopeColumn), columnInfos.indexOf(versionColumn), actionsColumnIndex ) setTableHeader(InvisibleResizableHeader()) getTableHeader().apply { reorderingAllowed = false resizingAllowed = true } columnSelectionAllowed = false setShowGrid(false) rowHeight = 20.scaled() background = UIUtil.getTableBackground() foreground = UIUtil.getTableForeground() selectionBackground = UIUtil.getTableSelectionBackground(true) selectionForeground = UIUtil.getTableSelectionForeground(true) setExpandableItemsEnabled(false) selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION putClientProperty("terminateEditOnFocusLost", true) intercellSpacing = Dimension(0, 2) // By default, JTable uses Tab/Shift-Tab for navigation between cells; Ctrl-Tab/Ctrl-Shift-Tab allows to break out of the JTable. // In this table, we don't want to navigate between cells - so override the traversal keys by default values. setFocusTraversalKeys( KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) ) setFocusTraversalKeys( KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS) ) addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { if (tableModel.rowCount > 0 && selectedRows.isEmpty()) { setRowSelectionInterval(0, 0) } } }) PackageSearchUI.overrideKeyStroke(this, "jtable:RIGHT", "RIGHT") { transferFocus() } PackageSearchUI.overrideKeyStroke(this, "jtable:ENTER", "ENTER") { transferFocus() } PackageSearchUI.overrideKeyStroke(this, "shift ENTER") { clearSelection() transferFocusUp() } selectionModel.addListSelectionListener(listSelectionListener) addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { if (selectedIndex == -1) { selectedIndex = firstPackageIndex } } }) TableSpeedSearch(this) { item, _ -> if (item is PackagesTableItem.InstalledPackage) { item.packageModel.identifier } else { "" } }.apply { comparator = SpeedSearchComparator(false) } addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { applyColumnSizes(columnModel.totalColumnWidth, columnModel.columns.toList(), columnWeights) removeComponentListener(this) } }) onMouseMotion( onMouseMoved = { val point = it.point val hoverColumn = columnAtPoint(point) val hoverRow = rowAtPoint(point) if (tableModel.items.isEmpty() || !(0 until tableModel.items.count()).contains(hoverColumn)) { actionsColumn.hoverItem = null return@onMouseMotion } val item = tableModel.items[hoverRow] if (actionsColumn.hoverItem != item && hoverColumn == actionsColumnIndex) { actionsColumn.hoverItem = item updateAndRepaint() } else { actionsColumn.hoverItem = null } } ) } override fun getCellRenderer(row: Int, column: Int): TableCellRenderer = tableModel.columns[column].getRenderer(tableModel.items[row]) ?: DefaultTableCellRenderer() override fun getCellEditor(row: Int, column: Int): TableCellEditor? = tableModel.columns[column].getEditor(tableModel.items[row]) internal data class ViewModel( val displayItems: List<PackagesTableItem<*>>, val onlyStable: Boolean, val targetModules: TargetModules, val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules, val allKnownRepositories: KnownRepositories.All, val traceInfo: TraceInfo ) override suspend fun display(viewModel: ViewModel) = withContext(Dispatchers.AppUI) { knownRepositoriesInTargetModules = viewModel.knownRepositoriesInTargetModules allKnownRepositories = viewModel.allKnownRepositories targetModules = viewModel.targetModules logDebug(viewModel.traceInfo, "PackagesTable#displayData()") { "Displaying ${viewModel.displayItems.size} item(s)" } // We need to update those immediately before setting the items, on EDT, to avoid timing issues // where the target modules or only stable flags get updated after the items data change, thus // causing issues when Swing tries to render things (e.g., targetModules doesn't match packages' usages) versionColumn.updateData(viewModel.onlyStable, viewModel.targetModules) actionsColumn.updateData(viewModel.onlyStable, viewModel.targetModules, knownRepositoriesInTargetModules, allKnownRepositories) val previouslySelectedIdentifier = selectedPackage?.packageModel?.identifier selectionModel.removeListSelectionListener(listSelectionListener) tableModel.items = viewModel.displayItems if (viewModel.displayItems.isEmpty() || previouslySelectedIdentifier == null) { selectionModel.addListSelectionListener(listSelectionListener) onItemSelectionChanged(null) return@withContext } autosizeColumnsAt(autosizingColumnsIndices) var indexToSelect: Int? = null // TODO factor out with a lambda for ((index, item) in viewModel.displayItems.withIndex()) { if (item.packageModel.identifier == previouslySelectedIdentifier) { logDebug(viewModel.traceInfo, "PackagesTable#displayData()") { "Found previously selected package at index $index" } indexToSelect = index } } selectionModel.addListSelectionListener(listSelectionListener) if (indexToSelect != null) { selectedIndex = indexToSelect } else { logDebug(viewModel.traceInfo, "PackagesTable#displayData()") { "Previous selection not available anymore, clearing..." } } updateAndRepaint() } override fun getData(dataId: String): Any? = when { PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this else -> null } override fun performCopy(dataContext: DataContext) { getSelectedTableItem()?.performCopy(dataContext) } override fun isCopyEnabled(dataContext: DataContext) = getSelectedTableItem()?.isCopyEnabled(dataContext) ?: false override fun isCopyVisible(dataContext: DataContext) = getSelectedTableItem()?.isCopyVisible(dataContext) ?: false private fun getSelectedTableItem(): PackagesTableItem<*>? { if (selectedIndex == -1) { return null } return tableModel.getValueAt(selectedIndex, 0) as? PackagesTableItem<*> } private fun updatePackageScope(packageModel: PackageModel, newScope: PackageScope) { if (packageModel is PackageModel.Installed) { val operations = operationFactory.createChangePackageScopeOperations(packageModel, newScope, targetModules, repoToInstall = null) logDebug("PackagesTable#updatePackageScope()") { "The user has selected a new scope for ${packageModel.identifier}: '$newScope'. This resulted in ${operations.size} operation(s)." } operationExecutor.executeOperations(operations) } else if (packageModel is PackageModel.SearchResult) { tableModel.replaceItemMatching(packageModel) { item -> when (item) { is PackagesTableItem.InstalledPackage -> { throw IllegalStateException("Expecting a search result item model, got an installed item model") } is PackagesTableItem.InstallablePackage -> item.copy(item.selectedPackageModel.copy(selectedScope = newScope)) } } logDebug("PackagesTable#updatePackageScope()") { "The user has selected a new scope for search result ${packageModel.identifier}: '$newScope'." } updateAndRepaint() } } private fun updatePackageVersion(packageModel: PackageModel, newVersion: PackageVersion) { when (packageModel) { is PackageModel.Installed -> { val operations = packageModel.usageInfo.flatMap { val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading( packageModel, newVersion, allKnownRepositories ) operationFactory.createChangePackageVersionOperations( packageModel = packageModel, newVersion = newVersion, targetModules = targetModules, repoToInstall = repoToInstall ) } logDebug("PackagesTable#updatePackageVersion()") { "The user has selected a new version for ${packageModel.identifier}: '$newVersion'. " + "This resulted in ${operations.size} operation(s)." } operationExecutor.executeOperations(operations) } is PackageModel.SearchResult -> { tableModel.replaceItemMatching(packageModel) { item -> when (item) { is PackagesTableItem.InstalledPackage -> item.copy(item.selectedPackageModel.copy(selectedVersion = newVersion)) is PackagesTableItem.InstallablePackage -> item.copy(item.selectedPackageModel.copy(selectedVersion = newVersion)) } } logDebug("PackagesTable#updatePackageVersion()") { "The user has selected a new version for search result ${packageModel.identifier}: '$newVersion'." } updateAndRepaint() } } } private fun executeUpdateActionColumnOperations(operations: List<PackageSearchOperation<*>>) { logDebug("PackagesTable#updatePackageVersion()") { "The user has clicked the update action for a package. This resulted in ${operations.size} operation(s)." } operationExecutor.executeOperations(operations) } private fun PackagesTableItem<*>.toSelectedPackageModule() = SelectedPackageModel( packageModel = packageModel, selectedVersion = (tableModel.columns[2] as VersionColumn).valueOf(this).selectedVersion, selectedScope = (tableModel.columns[1] as ScopeColumn).valueOf(this).selectedScope, mixedBuildSystemTargets = targetModules.isMixedBuildSystems ) private fun applyColumnSizes(tW: Int, columns: List<TableColumn>, weights: List<Float>) { require(columnWeights.size == columns.size) { "Column weights count != columns count! We have ${columns.size} columns, ${columnWeights.size} weights" } for (column in columns) { column.preferredWidth = (weights[column.modelIndex] * tW).roundToInt() } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTable.kt
4211537169
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ift.lesson import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.invokeLater import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.ChangeListChange import com.intellij.openapi.vcs.changes.ChangesViewManager import com.intellij.openapi.vcs.changes.ui.ChangesListView import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBOptionButton import com.intellij.ui.table.JBTable import com.intellij.util.DocumentUtil import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.commit.* import com.intellij.vcs.log.ui.frame.VcsLogChangesBrowser import git4idea.i18n.GitBundle import git4idea.ift.GitLessonsBundle import git4idea.ift.GitLessonsUtil.checkoutBranch import git4idea.ift.GitLessonsUtil.highlightSubsequentCommitsInGitLog import git4idea.ift.GitLessonsUtil.openCommitWindowText import git4idea.ift.GitLessonsUtil.resetGitLogWindow import git4idea.ift.GitLessonsUtil.showWarningIfCommitWindowClosed import git4idea.ift.GitLessonsUtil.showWarningIfGitWindowClosed import git4idea.ift.GitLessonsUtil.showWarningIfModalCommitEnabled import training.dsl.* import training.project.ProjectUtils import training.ui.LearningUiHighlightingManager import java.awt.Rectangle import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.JTree import javax.swing.KeyStroke import javax.swing.tree.TreePath class GitCommitLesson : GitLesson("Git.Commit", GitLessonsBundle.message("git.commit.lesson.name")) { override val existedFile = "git/puss_in_boots.yml" private val branchName = "feature" private val firstFileName = "simple_cat.yml" private val secondFileName = "puss_in_boots.yml" private val firstFileAddition = """ | | - play: | condition: boring | actions: [ run after favourite plush mouse ]""".trimMargin() private val secondFileAddition = """ | | - play: | condition: boring | actions: [ run after mice or own tail ]""".trimMargin() override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true) override val lessonContent: LessonContext.() -> Unit = { checkoutBranch(branchName) prepareRuntimeTask { modifyFiles() } showWarningIfModalCommitEnabled() task { openCommitWindowText(GitLessonsBundle.message("git.commit.open.commit.window")) stateCheck { ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.COMMIT)?.isVisible == true } } prepareRuntimeTask { val lastCommitMessage = "Add facts about playing cats" VcsConfiguration.getInstance(project).apply { REFORMAT_BEFORE_PROJECT_COMMIT = false LAST_COMMIT_MESSAGE = lastCommitMessage myLastCommitMessages = mutableListOf(lastCommitMessage) } val commitWorkflowHandler: AbstractCommitWorkflowHandler<*, *> = ChangesViewManager.getInstanceEx(project).commitWorkflowHandler ?: return@prepareRuntimeTask commitWorkflowHandler.workflow.commitOptions.allOptions.forEach(RefreshableOnComponent::restoreState) commitWorkflowHandler.setCommitMessage(lastCommitMessage) } task { triggerByPartOfComponent(false) l@{ ui: ChangesListView -> val path = TreeUtil.treePathTraverser(ui).find { it.getPathComponent(it.pathCount - 1).toString().contains(firstFileName) } ?: return@l null val rect = ui.getPathBounds(path) ?: return@l null Rectangle(rect.x, rect.y, 20, rect.height) } } val commitWindowName = VcsBundle.message("commit.dialog.configurable") task { text(GitLessonsBundle.message("git.commit.choose.files", strong(commitWindowName), strong(secondFileName))) text(GitLessonsBundle.message("git.commit.choose.files.balloon"), LearningBalloonConfig(Balloon.Position.below, 300, cornerToPointerDistance = 55)) highlightVcsChange(firstFileName) triggerOnOneChangeIncluded(secondFileName) showWarningIfCommitWindowClosed() } task { triggerByUiComponentAndHighlight(usePulsation = true) { ui: ActionButton -> ActionManager.getInstance().getId(ui.action) == "ChangesView.ShowCommitOptions" } } lateinit var showOptionsTaskId: TaskContext.TaskId task { showOptionsTaskId = taskId text(GitLessonsBundle.message("git.commit.open.before.commit.options", icon(AllIcons.General.Gear))) text(GitLessonsBundle.message("git.commit.open.options.tooltip", strong(commitWindowName)), LearningBalloonConfig(Balloon.Position.above, 0)) triggerByUiComponentAndHighlight(false, false) { _: CommitOptionsPanel -> true } showWarningIfCommitWindowClosed() } val reformatCodeButtonText = VcsBundle.message("checkbox.checkin.options.reformat.code").dropMnemonic() task { triggerByUiComponentAndHighlight { ui: JBCheckBox -> if (ui.text == reformatCodeButtonText) { ui.isSelected = false true } else false } } task { val analyzeOptionText = VcsBundle.message("before.checkin.standard.options.check.smells").dropMnemonic() text(GitLessonsBundle.message("git.commit.analyze.code.explanation", strong(analyzeOptionText))) text(GitLessonsBundle.message("git.commit.enable.reformat.code", strong(reformatCodeButtonText))) triggerByUiComponentAndHighlight(false, false) { ui: JBCheckBox -> ui.text == reformatCodeButtonText && ui.isSelected } restoreByUi(showOptionsTaskId) } task { text(GitLessonsBundle.message("git.commit.close.commit.options", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE))) stateCheck { previous.ui?.isShowing != true } } val commitButtonText = GitBundle.message("commit.action.name").dropMnemonic() task { text(GitLessonsBundle.message("git.commit.perform.commit", strong(commitButtonText))) triggerByUiComponentAndHighlight(usePulsation = true) { ui: JBOptionButton -> ui.text?.contains(commitButtonText) == true } triggerOnCommitPerformed() showWarningIfCommitWindowClosed() } task("ActivateVersionControlToolWindow") { before { LearningUiHighlightingManager.clearHighlights() } text(GitLessonsBundle.message("git.commit.open.git.window", action(it))) stateCheck { val toolWindowManager = ToolWindowManager.getInstance(project) toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true } } resetGitLogWindow() task { text(GitLessonsBundle.message("git.commit.select.top.commit")) triggerOnTopCommitSelected() showWarningIfGitWindowClosed() } task { text(GitLessonsBundle.message("git.commit.committed.file.explanation")) triggerByUiComponentAndHighlight(highlightInside = false, usePulsation = true) { _: VcsLogChangesBrowser -> true } proceedLink() showWarningIfGitWindowClosed(restoreTaskWhenResolved = false) } task { val amendCheckboxText = VcsBundle.message("checkbox.amend").dropMnemonic() text(GitLessonsBundle.message("git.commit.select.amend.checkbox", strong(amendCheckboxText), LessonUtil.rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_DOWN_MASK)), strong(commitWindowName))) triggerByUiComponentAndHighlight(usePulsation = true) { ui: JBCheckBox -> ui.text?.contains(amendCheckboxText) == true } triggerByUiComponentAndHighlight(false, false) { ui: JBCheckBox -> ui.text?.contains(amendCheckboxText) == true && ui.isSelected } showWarningIfCommitWindowClosed() } task { text(GitLessonsBundle.message("git.commit.select.file")) highlightVcsChange(firstFileName) triggerOnOneChangeIncluded(firstFileName) showWarningIfCommitWindowClosed() } task { val amendButtonText = VcsBundle.message("amend.action.name", commitButtonText) text(GitLessonsBundle.message("git.commit.amend.commit", strong(amendButtonText))) triggerByUiComponentAndHighlight { ui: JBOptionButton -> ui.text?.contains(amendButtonText) == true } triggerOnCommitPerformed() showWarningIfCommitWindowClosed() } task { text(GitLessonsBundle.message("git.commit.select.top.commit.again")) triggerOnTopCommitSelected() showWarningIfGitWindowClosed() } text(GitLessonsBundle.message("git.commit.two.committed.files.explanation")) } private fun TaskContext.highlightVcsChange(changeFileName: String, highlightBorder: Boolean = true) { triggerByFoundPathAndHighlight(highlightBorder) { _: JTree, path: TreePath -> path.pathCount > 2 && path.getPathComponent(2).toString().contains(changeFileName) } } private fun TaskContext.triggerOnOneChangeIncluded(changeFileName: String) { triggerByUiComponentAndHighlight(false, false) l@{ ui: ChangesListView -> val includedChanges = ui.includedSet if (includedChanges.size != 1) return@l false val change = includedChanges.first() as? ChangeListChange ?: return@l false change.virtualFile?.name == changeFileName } } private fun TaskContext.triggerOnTopCommitSelected() { highlightSubsequentCommitsInGitLog(0) triggerByUiComponentAndHighlight(false, false) { ui: JBTable -> ui.isCellSelected(0, 1) } } private fun TaskContext.triggerOnCommitPerformed() { addFutureStep { val commitWorkflowHandler: NonModalCommitWorkflowHandler<*, *> = ChangesViewManager.getInstanceEx(project).commitWorkflowHandler ?: error("Changes view not initialized") commitWorkflowHandler.workflow.addListener(object : CommitWorkflowListener { override fun vcsesChanged() {} override fun executionStarted() {} override fun executionEnded() { completeStep() } override fun beforeCommitChecksStarted() {} override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) {} }, taskDisposable) } } private fun TaskRuntimeContext.modifyFiles() = invokeLater { DocumentUtil.writeInRunUndoTransparentAction { val projectRoot = ProjectUtils.getProjectRoot(project) appendToFile(projectRoot, firstFileName, firstFileAddition) appendToFile(projectRoot, secondFileName, secondFileAddition) } } private fun appendToFile(projectRoot: VirtualFile, fileName: String, text: String) { val file = VfsUtil.collectChildrenRecursively(projectRoot).find { it.name == fileName } ?: error("Failed to find ${fileName} in project root: ${projectRoot}") file.refresh(false, false) val document = FileDocumentManager.getInstance().getDocument(file)!! // it's not directory or binary file and it isn't large document.insertString(document.textLength, text) } }
plugins/git-features-trainer/src/git4idea/ift/lesson/GitCommitLesson.kt
1190990029
package org.gradle.gradlebuild.docs import org.gradle.api.DefaultTask import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.pegdown.PegDownProcessor import java.io.File import java.nio.charset.Charset import java.nio.charset.Charset.defaultCharset import javax.inject.Inject @CacheableTask open class PegDown @Inject constructor( @get:PathSensitive(PathSensitivity.NONE) @get:InputFile val markdownFile: File, @get:OutputFile val destination: File ) : DefaultTask() { @Input val inputEncoding = defaultCharset().name() @Input val outputEncoding = defaultCharset().name() @TaskAction fun process() { val processor = PegDownProcessor(0) val markdown = markdownFile.readText(Charset.forName(inputEncoding)) val html = processor.markdownToHtml(markdown) destination.writeText(html, Charset.forName(outputEncoding)) } }
buildSrc/subprojects/docs/src/main/kotlin/org/gradle/gradlebuild/docs/PegDown.kt
1903820843
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.connection import com.intellij.ide.browsers.WebBrowser import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.util.EventDispatcher import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.socketConnection.ConnectionState import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.util.io.socketConnection.SocketConnectionListener import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.* import org.jetbrains.debugger.DebugEventListener import org.jetbrains.debugger.Vm import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import javax.swing.event.HyperlinkListener abstract class VmConnection<T : Vm> : Disposable { open val browser: WebBrowser? = null private val stateRef = AtomicReference(ConnectionState(ConnectionStatus.NOT_CONNECTED)) private val dispatcher = EventDispatcher.create(DebugEventListener::class.java) private val connectionDispatcher = ContainerUtil.createLockFreeCopyOnWriteList<(ConnectionState) -> Unit>() @Volatile var vm: T? = null protected set private val opened = AsyncPromise<Any?>() private val closed = AtomicBoolean() val state: ConnectionState get() = stateRef.get() fun addDebugListener(listener: DebugEventListener) { dispatcher.addListener(listener) } @TestOnly fun opened(): Promise<*> = opened fun executeOnStart(runnable: Runnable) { opened.done { runnable.run() } } protected fun setState(status: ConnectionStatus, message: String? = null, messageLinkListener: HyperlinkListener? = null) { val newState = ConnectionState(status, message, messageLinkListener) val oldState = stateRef.getAndSet(newState) if (oldState == null || oldState.status != status) { if (status == ConnectionStatus.CONNECTION_FAILED) { opened.setError(newState.message) } for (listener in connectionDispatcher) { listener(newState) } } } fun stateChanged(listener: (ConnectionState) -> Unit) { connectionDispatcher.add(listener) } // backward compatibility, go debugger fun addListener(listener: SocketConnectionListener) { stateChanged { listener.statusChanged(it.status) } } protected val debugEventListener: DebugEventListener get() = dispatcher.multicaster protected open fun startProcessing() { opened.setResult(null) } fun close(message: String?, status: ConnectionStatus) { if (!closed.compareAndSet(false, true)) { return } if (opened.isPending) { opened.setError("closed") } setState(status, message) Disposer.dispose(this, false) } override fun dispose() { vm = null } open fun detachAndClose(): Promise<*> { if (opened.isPending) { opened.setError(createError("detached and closed")) } val currentVm = vm val callback: Promise<*> if (currentVm == null) { callback = nullPromise() } else { vm = null callback = currentVm.attachStateManager.detach() } close(null, ConnectionStatus.DISCONNECTED) return callback } }
platform/script-debugger/debugger-ui/src/VmConnection.kt
1130673075
// 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.featureStatistics.fusCollectors import com.intellij.internal.DebugAttachDetector import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields.Boolean import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.utils.StatisticsRecorderUtil import com.intellij.internal.statistic.utils.StatisticsUploadAssistant import com.intellij.openapi.application.ApplicationManager internal class IdeSessionDataCollector : ApplicationUsagesCollector() { private val GROUP = EventLogGroup("event.log.session", 1) private val DEBUG = GROUP.registerEvent("debug.mode", Boolean("debug_agent")) private val REPORT = GROUP.registerEvent("reporting", Boolean("suppress_report"), Boolean("only_local")) private val TEST = GROUP.registerEvent("test.mode", Boolean("fus_test"), Boolean("internal"), Boolean("teamcity")) private val HEADLESS = GROUP.registerEvent("headless", Boolean("headless"), Boolean("command_line")) override fun getGroup(): EventLogGroup = GROUP override fun getMetrics(): Set<MetricEvent> = ApplicationManager.getApplication().let { app -> setOf( DEBUG.metric(DebugAttachDetector.isDebugEnabled()), REPORT.metric(StatisticsUploadAssistant.isSuppressStatisticsReport(), StatisticsUploadAssistant.isLocalStatisticsWithoutReport()), TEST.metric(StatisticsRecorderUtil.isTestModeEnabled("FUS"), app.isInternal, StatisticsUploadAssistant.isTeamcityDetected()), HEADLESS.metric(app.isHeadlessEnvironment, app.isCommandLine)) } }
platform/platform-impl/src/com/intellij/featureStatistics/fusCollectors/IdeSessionDataCollector.kt
238616514
package io.github.feelfreelinux.wykopmobilny.api.patrons import io.github.feelfreelinux.wykopmobilny.base.WykopSchedulers import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.patrons.Patron import io.reactivex.Single import retrofit2.Retrofit class PatronsRepository(val retrofit: Retrofit) : PatronsApi { private val patronsApi by lazy { retrofit.create(PatronsRetrofitApi::class.java) } override lateinit var patrons : List<Patron> override fun <T>ensurePatrons(d : T) : Single<T> { return Single.create { emitter -> if (!::patrons.isInitialized) { getPatrons().subscribeOn(WykopSchedulers().backgroundThread()).observeOn(WykopSchedulers().mainThread()) .subscribe({ patrons -> this.patrons = patrons emitter.onSuccess(d) }, { e -> this.patrons = listOf() emitter.onSuccess(d) }) } else { emitter.onSuccess(d) } } } override fun getPatrons(): Single<List<Patron>> = patronsApi.getPatrons().map { it.patrons } .doOnSuccess { this.patrons = it }.doOnError { this.patrons = listOf() } }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/patrons/PatronsRepository.kt
1609324993
package net.erikkarlsson.smashapp.feature.tournament.domain import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import net.erikkarlsson.smashapp.base.data.Lce import net.erikkarlsson.smashapp.base.data.model.ranking.Smasher import net.erikkarlsson.smashapp.base.data.model.tournament.Match import net.erikkarlsson.smashapp.base.data.model.tournament.Participant import net.erikkarlsson.smashapp.base.data.model.tournament.Tournament import net.erikkarlsson.smashapp.feature.tournament.domain.projection.ProjectedMatchResult /** * This model is streamed to all Presenters interested in the state of the application. * The state is immutable which makes it thread safe and a lot easier to reason about. * This model will be incrementally re-created as results come back from the different actions. */ data class TournamentModel(val tournamentLce: Lce<Tournament>, val myParticipantId: Long, val projection: ImmutableList<ProjectedMatchResult>, val participantIdSmasherMap: ImmutableMap<Long, Smasher>) { companion object { @JvmField val EMPTY = TournamentModel(Lce.idle<Tournament>(), 0L, ImmutableList.of(), ImmutableMap.of()) } val participantSmasherMap: ImmutableMap<Participant, Smasher> get() { val participantSmasherMapBuilder = ImmutableMap.builder<Participant, Smasher>() tournament().participants.forEach { val smasher: Smasher = participantIdSmasherMap[it.id] ?: Smasher.NO_SMASHER participantSmasherMapBuilder.put(it, smasher) } return participantSmasherMapBuilder.build() } fun tournament(): Tournament { return tournamentLce.data ?: Tournament.NO_TOURNAMENT } fun isLoading(): Boolean { return tournamentLce.isLoading() } fun hasError(): Boolean { return tournamentLce.hasError() } fun isParticipating(): Boolean { return myParticipantId != 0L } fun shouldSearchForTournament(): Boolean { return tournamentLce.isIdle || isTournamentNotFound() || tournamentLce.hasError() } fun shouldFetchTournament(): Boolean { return isTournamentFound() } fun isTournamentFound(): Boolean { return tournament() != Tournament.NO_TOURNAMENT } fun isBracketProjected(): Boolean { return projection.size > 0 } fun isAllSmashersFetched(): Boolean { return participantIdSmasherMap.size == tournament().participants.size } fun isTournamentNotFound(): Boolean { return tournamentLce.hasData() && tournamentLce.data === Tournament.NO_TOURNAMENT } fun nextMatch(): Match { return tournament().nextMatch(myParticipantId) } fun hasTournamentBeenUpdated(updatedTournament: Tournament): Boolean { return tournament().updatedAt != updatedTournament.updatedAt } fun participants(): ImmutableList<Participant> { return tournament().participants } }
app/src/main/java/net/erikkarlsson/smashapp/feature/tournament/domain/TournamentModel.kt
1731771318
package com.kamer.orny.data.google import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential import io.reactivex.Completable import io.reactivex.Single interface GoogleAuthHolder { fun login(): Completable fun logout(): Completable fun getActiveCredentials(): Single<GoogleAccountCredential> }
app/src/main/kotlin/com/kamer/orny/data/google/GoogleAuthHolder.kt
1318556025
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.annotation /** * Denotes that an integer parameter, field or method return value is expected * to be a dimension resource reference (e.g. `android.R.dimen.app_icon_size`). */ @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.BINARY) @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.FIELD, AnnotationTarget.LOCAL_VARIABLE ) public annotation class DimenRes
annotation/annotation/src/jvmMain/kotlin/androidx/annotation/DimenRes.kt
2163707494
package org.thoughtcrime.securesms.stories.viewer.post import android.graphics.Typeface import android.net.Uri import org.thoughtcrime.securesms.blurhash.BlurHash import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost import org.thoughtcrime.securesms.linkpreview.LinkPreview import kotlin.time.Duration sealed class StoryPostState { data class TextPost( val storyTextPost: StoryTextPost? = null, val linkPreview: LinkPreview? = null, val typeface: Typeface? = null, val loadState: LoadState = LoadState.INIT ) : StoryPostState() data class ImagePost( val imageUri: Uri, val blurHash: BlurHash? ) : StoryPostState() data class VideoPost( val videoUri: Uri, val size: Long, val clipStart: Duration, val clipEnd: Duration, val blurHash: BlurHash? ) : StoryPostState() data class None(private val ts: Long = System.currentTimeMillis()) : StoryPostState() enum class LoadState { INIT, LOADED, FAILED } }
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/post/StoryPostState.kt
3156974212
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.foundation import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontSynthesis import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow internal actual class CurvedTextDelegate { actual var textWidth = 0f actual var textHeight = 0f actual var baseLinePosition = 0f actual fun updateIfNeeded( text: String, clockwise: Boolean, fontSizePx: Float ) { // TODO(b/194653251): Implement throw java.lang.RuntimeException("Not implemented") } actual fun UpdateFontIfNeeded( fontFamily: FontFamily?, fontWeight: FontWeight?, fontStyle: FontStyle?, fontSynthesis: FontSynthesis? ) { // TODO(b/194653251): Implement throw java.lang.RuntimeException("Not implemented") } actual fun DrawScope.doDraw( layoutInfo: CurvedLayoutInfo, parentSweepRadians: Float, overflow: TextOverflow, color: Color, background: Color ) { // TODO(b/194653251): Implement throw java.lang.RuntimeException("Not implemented") } }
wear/compose/compose-foundation/src/desktopMain/kotlin/androidx/wear/compose/foundation/CurvedTextDelegate.desktop.kt
2052645507
package taiwan.no1.app.ssfm.features.preference import android.databinding.ObservableBoolean import android.databinding.ObservableField import android.databinding.ObservableInt import android.view.View import com.devrapid.adaptiverecyclerview.AdaptiveViewHolder import taiwan.no1.app.ssfm.features.base.BaseViewModel import taiwan.no1.app.ssfm.models.entities.PreferenceToggleEntity /** * A [AdaptiveViewHolder] for controlling the main preference items with toggle button. * * @author jieyi * @since 9/8/17 */ class PreferenceToggleViewModel(private val entity: PreferenceToggleEntity) : BaseViewModel() { val title by lazy { ObservableField<String>() } val selected by lazy { ObservableBoolean() } val icon by lazy { ObservableInt() } var setBack: ((entityName: String, checked: Boolean) -> Unit)? = null init { title.set(entity.title) icon.set(entity.icon) selected.set(entity.isToggle) } fun onCheckedChange(view: View, checked: Boolean) { entity.isToggle = checked setBack?.invoke(entity.title, checked) } }
app/src/main/kotlin/taiwan/no1/app/ssfm/features/preference/PreferenceToggleViewModel.kt
2654641525
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.vo import androidx.room.compiler.processing.XConstructorElement import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XType import androidx.room.compiler.processing.XTypeElement import org.apache.commons.codec.digest.DigestUtils import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Mockito.mock @RunWith(JUnit4::class) class DatabaseTest { @Test fun indexLegacyHash() { val database = Database( element = mock(XTypeElement::class.java), type = mock(XType::class.java), entities = listOf( Entity( mock(XTypeElement::class.java), tableName = "TheTable", type = mock(XType::class.java), fields = emptyList(), embeddedFields = emptyList(), primaryKey = PrimaryKey(mock(XElement::class.java), Fields(), false), indices = listOf( Index( name = "leIndex", unique = false, fields = Fields(), orders = emptyList() ), Index( name = "leIndex2", unique = true, fields = Fields(), orders = emptyList() ) ), foreignKeys = emptyList(), constructor = Constructor(mock(XConstructorElement::class.java), emptyList()), shadowTableName = null ) ), views = emptyList(), daoMethods = emptyList(), version = 1, exportSchema = false, enableForeignKeys = false ) val expectedLegacyHash = DigestUtils.md5Hex( "CREATE TABLE IF NOT EXISTS `TheTable` ()¯\\_(ツ)_/¯" + "CREATE INDEX `leIndex` ON `TheTable` ()¯\\_(ツ)_/¯" + "CREATE UNIQUE INDEX `leIndex2` ON `TheTable` ()" ) assertEquals(expectedLegacyHash, database.legacyIdentityHash) } }
room/room-compiler/src/test/kotlin/androidx/room/vo/DatabaseTest.kt
935674697
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent /** * Used as a reserved cell in layout. Can be populated by content later via [component] property or reset to null * * @see Row.placeholder */ @ApiStatus.NonExtendable @ApiStatus.Experimental interface Placeholder : CellBase<Placeholder> { override fun visible(isVisible: Boolean): Placeholder override fun enabled(isEnabled: Boolean): Placeholder @Deprecated("Use align method instead") override fun horizontalAlign(horizontalAlign: HorizontalAlign): Placeholder @Deprecated("Use align method instead") override fun verticalAlign(verticalAlign: VerticalAlign): Placeholder override fun align(align: Align): Placeholder override fun resizableColumn(): Placeholder override fun gap(rightGap: RightGap): Placeholder override fun customize(customGaps: Gaps): Placeholder /** * Component placed in the cell. If the component is [DialogPanel] then all functionality related to * [DialogPanel.apply]/[DialogPanel.reset]/[DialogPanel.isModified] and validation mechanism is delegated from [component] * to parent [DialogPanel] that contains this placeholder. * * The property is not reset automatically when the component is removed from the panel by other methods like [java.awt.Container.remove] * or by adding the component to another parent */ var component: JComponent? }
platform/platform-impl/src/com/intellij/ui/dsl/builder/Placeholder.kt
749107072
// 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.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class ContainsOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtOperationReferenceExpression>( targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = listOf("in") ) { private companion object { private val OPERATION_TOKENS = setOf(KtTokens.IN_KEYWORD, KtTokens.NOT_IN) } override fun processPossibleReceiverExpression(expression: KtExpression) { when (val parent = expression.parent) { is KtBinaryExpression -> { if (parent.operationToken in OPERATION_TOKENS && expression == parent.right) { processReferenceElement(parent.operationReference) } } is KtWhenConditionInRange -> { processReferenceElement(parent.operationReference) } } } override fun isReferenceToCheck(ref: PsiReference): Boolean { if (ref !is KtSimpleNameReference) return false val element = ref.element as? KtOperationReferenceExpression ?: return false return element.getReferencedNameElementType() in OPERATION_TOKENS } override fun extractReference(element: KtElement): PsiReference? { val referenceExpression = element as? KtOperationReferenceExpression ?: return null if (referenceExpression.getReferencedNameElementType() !in OPERATION_TOKENS) return null return referenceExpression.references.firstIsInstance<KtSimpleNameReference>() } }
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/ContainsOperatorReferenceSearcher.kt
3119180109
fun test(j: J) { j.foo(<caret>/* s=*/"hello") }
plugins/kotlin/idea/tests/testData/inspectionsLocal/inconsistentCommentForJavaParameter/whitespace/notSameName3.kt
905859318