public operator fun minus ( other : Byte ) : ComplexFloat

= ComplexFloat ( re - other , im )

/**
 * Subtracts the other byte value from this value.
 *
 * @param other the [Byte] value to be subtracted from this value.
 * @return a new [ComplexFloat] representing the result of the subtraction operation.
 */


public operator fun minus ( other : Short ) : ComplexFloat

= ComplexFloat ( re - other , im )

/**
 * Subtracts the other short value from this value.
 *
 * @param other the [Short] value to be subtracted from this value.
 * @return a new [ComplexFloat] representing the result of the subtraction operation.
 */


public operator fun minus ( other : Int ) : ComplexFloat

= ComplexFloat ( re - other , im )

/**
 * Subtracts the other integer value from this value.
 *
 * @param other the [Int] value to be subtracted from this value.
 * @return a new [ComplexFloat] representing the result of the subtraction operation.
 */


public operator fun minus ( other : Long ) : ComplexFloat

= ComplexFloat ( re - other , im )

/**
 * Subtracts the other long value from this value.
 *
 * @param other the [Long] value to be subtracted from this value.
 * @return a new [ComplexFloat] representing the result of the subtraction operation.
 */


public operator fun minus ( other : Float ) : ComplexFloat

= ComplexFloat ( re - other , im )

/**
 * Subtracts the other float value from this value.
 *
 * @param other the [Float] value to be subtracted from this value.
 * @return a new [ComplexFloat] representing the result of the subtraction operation.
 */


public operator fun minus ( other : Double ) : ComplexDouble

= ComplexDouble ( re - other , im . toDouble ( ) )

/**
 * Subtracts the other double value from this value.
 *
 * @param other The [Double] value to be subtracted from this value.
 * @return A new [ComplexDouble] representing the result of the subtraction operation.
 */


public operator fun minus ( other : ComplexFloat ) : ComplexFloat

= ComplexFloat ( re - other . re , im - other . im )

/**
 * Subtracts the other value from this value.
 *
 * @param other The value to be subtracted from this value.
 * @return A new [ComplexFloat] representing the result of the subtraction operation.
 */


public operator fun minus ( other : ComplexDouble ) : ComplexDouble

= ComplexDouble ( re - other . re , im - other . im )

/**
 * Subtracts the other value from this value.
 *
 * @param other The value to be subtracted from this value.
 * @return A new [ComplexDouble] representing the result of the subtraction operation.
 */


public operator fun times ( other : Byte ) : ComplexFloat

= ComplexFloat ( re * other , im * other )

/**
 * Multiplies this complex number by the given byte value.
 *
 * @param other the [Byte] value to multiply this complex number by
 * @return a new [ComplexFloat] representing the result of the multiplication
 */


public operator fun times ( other : Short ) : ComplexFloat

/**
 * Multiplies this complex number by the given short value.
 *
 * @param other the [Short] value to multiply this complex number by
 * @return a new [ComplexFloat] representing the result of the multiplication
 */


public operator fun times ( other : Int ) : ComplexFloat

/**
 * Multiplies this complex number by the given integer value.
 *
 * @param other the [Int] value to multiply this complex number by
 * @return a new [ComplexFloat] representing the result of the multiplication
 */


public operator fun times ( other : Long ) : ComplexFloat

/**
 * Multiplies this complex number by the given long value.
 *
 * @param other the [Long] value to multiply this complex number by
 * @return a new [ComplexFloat] representing the result of the multiplication
 */


public operator fun times ( other : Float ) : ComplexFloat

/**
 * Multiplies this complex number by the given float value.
 *
 * @param other the [Float] value to multiply this complex number by
 * @return a new [ComplexFloat] representing the result of the multiplication
 */


public operator fun times ( other : Double ) : ComplexDouble

= ComplexDouble ( re * other , im * other )

/**
 * Multiplies this complex number by the given double value.
 *
 * @param other the [Double] value to multiply this complex number by
 * @return a new [ComplexDouble] representing the result of the multiplication
 */


public operator fun times ( other : ComplexFloat ) : ComplexFloat

= <EOL> ComplexFloat ( re * other . re - im * other . im , re * other . im + other . re * im )

/**
 * Multiplies this complex number by the given ComplexFloat value.
 *
 * @param other the [ComplexFloat] value to multiply this complex number by
 * @return a new [ComplexFloat] representing the result of the multiplication
 */


public operator fun times ( other : ComplexDouble ) : ComplexDouble

= <EOL> ComplexDouble ( re * other . re - im * other . im , re * other . im + other . re * im )

/**
 * Multiplies this complex number by the given ComplexDouble value.
 *
 * @param other the [ComplexDouble] value to multiply this complex number by
 * @return a new [ComplexDouble] representing the result of the multiplication
 */


public operator fun div ( other : Byte ) : ComplexFloat

= ComplexFloat ( re / other , im / other )

/**
 * Divides this value by the given byte value.
 *
 * @param other the [Byte] value to divide this ComplexFloat by.
 * @return a new [ComplexFloat] value after division.
 */


public operator fun div ( other : Short ) : ComplexFloat

/**
 * Divides this value by the given short value.
 *
 * @param other the [Short] value to divide this ComplexFloat by.
 * @return a new [ComplexFloat] value after division.
 */


public operator fun div ( other : Int ) : ComplexFloat

/**
 * Divides this value by the given integer value.
 *
 * @param other the [Int] value to divide this ComplexFloat by.
 * @return a new [ComplexFloat] value after division.
 */


public operator fun div ( other : Long ) : ComplexFloat

/**
 * Divides this value by the given long value.
 *
 * @param other the [Long] value to divide this ComplexFloat by.
 * @return a new [ComplexFloat] value after division.
 */


public operator fun div ( other : Float ) : ComplexFloat

/**
 * Divides this value by the given float value.
 *
 * @param other the [Float] value to divide this ComplexFloat by.
 * @return a new [ComplexFloat] value after division.
 */


public operator fun div ( other : Double ) : ComplexDouble

= ComplexDouble ( re / other , im / other )

/**
 * Divides this value by the given double value.
 *
 * @param other the [Double] value to divide this ComplexFloat by.
 * @return a new [ComplexDouble] value after division.
 */


public operator fun div ( other : ComplexFloat ) : ComplexFloat

= when { <EOL> kotlin . math . abs ( other . re ) > kotlin . math . abs ( other . im ) -> { <EOL> val dr = other . im / other . re <EOL> val dd = other . re + dr * other . im <EOL> if ( dd . isNaN ( ) || dd == <NUM_LIT> ) throw ArithmeticException ( "<STR_LIT>" ) <EOL> ComplexFloat ( ( re + im * dr ) / dd , ( im - re * dr ) / dd ) <EOL> } <EOL> other . im == <NUM_LIT> -> throw ArithmeticException ( "<STR_LIT>" ) <EOL> else -> { <EOL> val dr = other . re / other . im <EOL> val dd = other . im + dr * other . re <EOL> if ( dd . isNaN ( ) || dd == <NUM_LIT> ) throw ArithmeticException ( "<STR_LIT>" ) <EOL> ComplexFloat ( ( re * dr + im ) / dd , ( im * dr - re ) / dd ) <EOL> } <EOL> }

/**
 * Divides this value by the given ComplexFloat value.
 *
 * @param other the [ComplexFloat] value to divide this ComplexFloat by.
 * @return a new [ComplexFloat] value after division.
 */


public operator fun div ( other : ComplexDouble ) : ComplexDouble

= when { <EOL> kotlin . math . abs ( other . re ) > kotlin . math . abs ( other . im ) -> { <EOL> val dr = other . im / other . re <EOL> val dd = other . re + dr * other . im <EOL> if ( dd . isNaN ( ) || dd == <NUM_LIT:0.0> ) throw ArithmeticException ( "<STR_LIT>" ) <EOL> ComplexDouble ( ( re + im * dr ) / dd , ( im - re * dr ) / dd ) <EOL> } <EOL> other . im == <NUM_LIT:0.0> -> throw ArithmeticException ( "<STR_LIT>" ) <EOL> else -> { <EOL> val dr = other . re / other . im <EOL> val dd = other . im + dr * other . re <EOL> if ( dd . isNaN ( ) || dd == <NUM_LIT:0.0> ) throw ArithmeticException ( "<STR_LIT>" ) <EOL> ComplexDouble ( ( re * dr + im ) / dd , ( im * dr - re ) / dd ) <EOL> } <EOL> }

/**
 * Divides this value by the given ComplexDouble value.
 *
 * @param other the [ComplexDouble] value to divide this ComplexFloat by.
 * @return a new [ComplexDouble] value after division.
 */


public operator fun unaryPlus ( ) : ComplexFloat

= this


public operator fun unaryMinus ( ) : ComplexFloat

= ComplexFloat ( - re , - im )

/** Returns the negative of this value. */


public operator fun component1 ( ) : Float

= re

/**
 * Returns the real component of a complex number.
 *
 * @return the real part of the complex number as a Float value.
 */


public operator fun component2 ( ) : Float

= im

/**
 * Returns the imaginary component of a complex number.
 *
 * @return the imaginary part of the complex number as a Float value.
 */


= "<STR_LIT>"

/**
 * Returns a string representation of the complex number object in the form of
 * "real_part + (imaginary_part)i"
 *
 * @return the string representation of the complex number object
 */


fun lazyResolve ( target : FirElementWithResolveState , toPhase : FirResolvePhase )

{ <EOL> if ( target . resolvePhase >= toPhase ) return <EOL> lazyResolve ( target , toPhase , LLFirResolveDesignationCollector :: getDesignationToResolve ) <EOL> }

/**
 * Lazily resolves the [target] to a given [toPhase].
 *
 * Might resolve additional required declarations.
 *
 * Resolution is performed under the lock specific to each declaration that is going to be resolved.
 */


fun lazyResolveWithCallableMembers ( target : FirRegularClass , toPhase : FirResolvePhase )

{ <EOL> lazyResolve ( target , toPhase , LLFirResolveDesignationCollector :: getDesignationToResolveWithCallableMembers ) <EOL> }

/**
 * Lazily resolves the [target] with all callable members to a given [toPhase].
 *
 * Might resolve additional required declarations.
 *
 * Resolution is performed under the lock specific to each declaration that is going to be resolved.
 */


fun lazyResolveRecursively ( target : FirElementWithResolveState , toPhase : FirResolvePhase )

{ <EOL> lazyResolve ( target , toPhase , LLFirResolveDesignationCollector :: getDesignationToResolveRecursively ) <EOL> }

/**
 * Lazily resolves the [target] with nested declarations to a given [toPhase] recursively.
 *
 * Might resolve additional required declarations.
 *
 * Resolution is performed under the lock specific to each declaration that is going to be resolved.
 */


fun lazyResolveTarget ( target : LLFirResolveTarget , toPhase : FirResolvePhase , )

{ <EOL> try { <EOL> target . firFile ? . let ( :: resolveFileToImportsWithLock ) <EOL> if ( toPhase == FirResolvePhase . IMPORTS ) return <EOL> lazyResolveTargets ( target , toPhase ) <EOL> } catch ( e : Exception ) { <EOL> handleExceptionFromResolve ( e , target , toPhase ) <EOL> } <EOL> }

/**
 * Lazily resolves all the declarations which are specified for resolve by [target]
 *
 * Might resolve additional required declarations.
 *
 * Resolution is performed under the lock specific to each declaration which is going to be resolved.
 */


@ JvmStatic <EOL> fun newInstance ( param1 : String , param2 : String )

= <EOL> DestinationFragment2 ( ) . apply { <EOL> arguments = Bundle ( ) . apply { <EOL> putString ( ARG_PARAM1 , param1 ) <EOL> putString ( ARG_PARAM2 , param2 ) <EOL> } <EOL> }

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment DestinationFragment2.
 */


{ <EOL> aggregatingGenerated . forEach { it . delete ( ) } <EOL> aggregatingGenerated . clear ( ) <EOL> aggregatedTypes . clear ( ) <EOL> }

/**
 * Invalidates all data collected about aggregating APs, making the cache ready for the next round of data collection. Also,
 * all files generated by aggregating APs are deleted.
 */


fun invalidateIsolatingForOriginTypes ( originatingTypes : Set < String > )

{ <EOL> val isolatingGenerated = mutableSetOf < File > ( ) <EOL> isolatingMapping . forEach { ( file , type ) -> <EOL> if ( type in originatingTypes ) { <EOL> isolatingGenerated . add ( file ) <EOL> } <EOL> } <EOL> isolatingGenerated . forEach { <EOL> isolatingMapping . remove ( it ) <EOL> it . delete ( ) <EOL> } <EOL> }

/**
 * Prepares isolating processors for incremental compilation. The specified generated files are removed, and mapping
 * information is deleted for them. The invalidation is non-transitive.
 */


fun getOriginForGeneratedIsolatingType ( generatedType : String , sourceFileProvider : ( String ) -> File ) : String

{ <EOL> val generatedFile = sourceFileProvider ( generatedType ) <EOL> return isolatingMapping . getValue ( generatedFile ) <EOL> }

/** Gets the originating type for the specified type generated by isolating AP. */


fun getAggregatingOrigins ( ) : Set < String >

= aggregatedTypes

/** Returns types that were processed by aggregating APs. */


fun getAggregatingGeneratedTypes ( typeInfoProvider : ( Collection < File > ) -> Set < String > ) : Set < String >

{ <EOL> val generatedAggregating : MutableSet < File > = HashSet ( aggregatingGenerated . size ) <EOL> aggregatingGenerated . forEach { <EOL> if ( it . isJavaFileOrClass ( ) ) { <EOL> generatedAggregating . add ( it ) <EOL> } <EOL> } <EOL> return typeInfoProvider ( generatedAggregating ) <EOL> }

/** Returns all types generated by aggregating APs. */


fun getIsolatingGeneratedTypes ( typeInfoProvider : ( Collection < File > ) -> Set < String > ) : Set < String >

{ <EOL> val generatedIsolating : MutableSet < File > = HashSet ( isolatingMapping . size ) <EOL> isolatingMapping . keys . forEach { <EOL> if ( it . isJavaFileOrClass ( ) ) { <EOL> generatedIsolating . add ( it ) <EOL> } <EOL> } <EOL> return typeInfoProvider ( generatedIsolating ) <EOL> }

/** Returns all types generated by isolating APs. */


fun linkage ( messageWithoutHashes : String ) : FailurePattern

/** N.B. It is expected that [messageWithoutHashes] contains IR linkage error message without hashes in ID signatures. */


abstract fun configureBuilders ( )

/**
 * A customization point to fine-tune existing builder classes or add new ones.
 *
 * Override this method and use the following DSL methods to configure builder generation:
 * - [builder]
 * - [noBuilder]
 * - [configureFieldInAllLeafBuilders]
 */


protected abstract fun builderFieldFromElementField ( elementField : ElementField ) : BuilderField

/**
 * Must return a copy of [elementField] that will be used in builder configuration.
 */


protected fun builder ( config : IntermediateBuilderConfigurationContext . ( ) -> Unit )

= IntermediateBuilderDelegateProvider ( config )

/**
 * Provides a way to configure an intermediate builder class.
 *
 * @param config The configuration block. See [IntermediateBuilderConfigurationContext]'s documentation for description of its DSL
 * methods.
 */


protected fun builder ( element : Element , type : String ? = null , config : LeafBuilderConfigurationContext . ( ) -> Unit )

{ <EOL> val implementation = element . extractImplementation ( type ) <EOL> val builder = implementation . builder <EOL> requireNotNull ( builder ) <EOL> LeafBuilderConfigurationContext ( builder ) . apply ( config ) <EOL> }

/**
 * Provides a way to configure a leaf builder class, i.e. the builder class responsible for finally constructing an instance of
 * the corresponding implementation class.
 *
 * @param element The element for which to configure builder generation.
 * @param config The configuration block. See [LeafBuilderConfigurationContext]'s documentation for description of its DSL
 * methods.
 */


protected fun noBuilder ( element : Element , type : String ? = null )

{ <EOL> val implementation = element . extractImplementation ( type ) <EOL> implementation . builder = null <EOL> }

/**
 * Disables generating any builder classes for [element].
 */


protected inline fun findImplementationsWithElementInParents ( element : Element , implementationPredicate : ( Implementation ) -> Boolean = { true } ) : Collection < Implementation >

{ <EOL> return elements <EOL> . flatMap { it . implementations } <EOL> . mapNotNullTo ( mutableSetOf ( ) ) { implementation -> <EOL> if ( ! implementationPredicate ( implementation ) ) return@mapNotNullTo null <EOL> if ( implementation . element == element ) return@mapNotNullTo null <EOL> val hasElementInParents = implementation . element . elementAncestorsAndSelfDepthFirst ( ) . any { it == element } <EOL> implementation . takeIf { hasElementInParents } <EOL> } <EOL> }

/**
 * Out of all implementations, returns those for which [implementationPredicate] returns `true`
 * _and_ [element] is one of its non-immediate parents.
 */


protected fun configureFieldInAllLeafBuilders ( field : String , builderPredicate : ( ( LeafBuilder < BuilderField , Element , Implementation > ) -> Boolean ) ? = null , fieldPredicate : ( ( BuilderField ) -> Boolean ) ? = null , config : LeafBuilderConfigurationContext . ( field : String ) -> Unit )

{ <EOL> for ( builder in allLeafBuilders ) { <EOL> if ( builderPredicate != null && ! builderPredicate ( builder ) ) continue <EOL> if ( ! builder . allFields . any { it . name == field } ) continue <EOL> if ( fieldPredicate != null && ! fieldPredicate ( builder [ field ] ) ) continue <EOL> LeafBuilderConfigurationContext ( builder ) . config ( field ) <EOL> } <EOL> }

/**
 * Allows to batch-apply [config] to certain fields in _all_ the builders that satisfy the given
 * [builderPredicate].
 *
 * @param field The name of the field to configure across all builder classes.
 * @param builderPredicate Only builders satisfying this predicate will participate in this configuration.
 * @param fieldPredicate Only fields satisfying this predicate will be configured.
 * @param config The configuration block. Accepts the field name as an argument.
 * See [LeafBuilderConfigurationContext]'s documentation for description of its DSL methods.
 */


protected fun configureAllLeafBuilders ( config : LeafBuilderConfigurationContext . ( ) -> Unit )

{ <EOL> for ( builder in allLeafBuilders ) { <EOL> LeafBuilderConfigurationContext ( builder ) . config ( ) <EOL> } <EOL> }

/**
 * Allows to batch-apply [config] to _all_ leaf builders.
 *
 * @param config The configuration block. See [LeafBuilderConfigurationContext]'s documentation for description of its DSL methods.
 */


fun additionalImports ( vararg types : Importable )

{ <EOL> types . forEach { builder . usedTypes += it } <EOL> }

/**
 * Types/functions that you want to additionally import in the file with the builder class.
 *
 * This is useful if, for example, default values of fields reference classes or functions from other packages.
 *
 * Note that classes referenced in field types will be imported automatically.
 */


fun default ( field : String , value : String )

{ <EOL> default ( field ) { <EOL> this . value = value <EOL> } <EOL> }

/**
 * Specifies the default value of [field] in this builder class. The default value can be arbitrary code.
 *
 * Use [additionalImports] if the default value uses types/functions that are not otherwise imported.
 */


fun defaultTrue ( vararg fields : String )

{ <EOL> for ( field in fields ) { <EOL> default ( field ) { <EOL> value = "<STR_LIT:true>" <EOL> } <EOL> } <EOL> }

/**
 * Specifies that the default value of each field in [fields] in this builder class should be `true`.
 */


fun defaultFalse ( vararg fields : String )

{ <EOL> for ( field in fields ) { <EOL> default ( field ) { <EOL> value = "<STR_LIT:false>" <EOL> } <EOL> } <EOL> }

/**
 * Specifies that the default value of each field in [fields] in this builder class should be `false`.
 */


fun defaultNull ( vararg fields : String )

{ <EOL> for ( field in fields ) { <EOL> default ( field ) { <EOL> value = "<STR_LIT:null>" <EOL> } <EOL> require ( getField ( field ) . nullable ) { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> }

/**
 * Specifies that the default value of each field of [fields] in this builder class should be `null`.
 *
 * Note: the field must be configured as nullable.
 */


fun default ( field : String , init : DefaultValueContext . ( ) -> Unit )

{ <EOL> DefaultValueContext ( getField ( field ) ) . apply ( init ) . applyConfiguration ( ) <EOL> }

/**
 * Allows to configure the default value of [field] in this builder class.
 *
 * See the [DefaultValueContext] documentation for description of its DSL methods.
 */


infix fun from ( element : Element ) : ExceptConfigurator

{ <EOL> builder . fields += element . allFields . map ( this @ AbstractBuilderConfigurator :: builderFieldFromElementField ) <EOL> builder . packageName = "<STR_LIT>" <EOL> builder . materializedElement = element <EOL> return ExceptConfigurator ( ) <EOL> }

/**
 * Copy all fields from [element] to this builder class.
 */


{ <EOL> without ( listOf ( name ) ) <EOL> }

/**
 * Exclude the field with [name] from this builder class.
 */


infix fun without ( names : List < String > )

{ <EOL> builder . fields . removeAll { it . name in names } <EOL> }

/**
 * Exclude the fields with [names] from this builder class.
 */


{ <EOL> builder . isOpen = true <EOL> }

/**
 * Makes this builder an open class.
 */


{ <EOL> builder . wantsCopy = true <EOL> }

/**
 * In addition to the regular `build*()` function, generate `build*Copy()` function that accepts
 * an instance of the corresponding tree element and copies values from that instance to the builder, allowing to change them
 * in the process.
 */


fun < Dependency : KotlinLibrary , SourceFile > serializeModuleIntoKlib ( moduleName : String , irModuleFragment : IrModuleFragment ? , configuration : CompilerConfiguration , diagnosticReporter : DiagnosticReporter , compatibilityMode : CompatibilityMode , cleanFiles : List < KotlinFileSerializedData > , dependencies : List < Dependency > , createModuleSerializer : ( irDiagnosticReporter : IrDiagnosticReporter , irBuiltins : IrBuiltIns , compatibilityMode : CompatibilityMode , normalizeAbsolutePaths : Boolean , sourceBaseDirs : Collection < String > , languageVersionSettings : LanguageVersionSettings , shouldCheckSignaturesOnUniqueness : Boolean , ) -> IrModuleSerializer < * > , metadataSerializer : KlibSingleFileMetadataSerializer < SourceFile > , runKlibCheckers : ( IrModuleFragment , IrDiagnosticReporter , CompilerConfiguration ) -> Unit = { _ , _ , _ -> } , processCompiledFileData : ( ( File , KotlinFileSerializedData ) -> Unit ) ? = null , processKlibHeader : ( ByteArray ) -> Unit = { } , ) : SerializerOutput < Dependency >

{ <EOL> if ( irModuleFragment != null ) { <EOL> assert ( metadataSerializer . numberOfSourceFiles == irModuleFragment . files . size ) { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> val sourceBaseDirs = configuration [ CommonConfigurationKeys . KLIB_RELATIVE_PATH_BASES ] ? : emptyList ( ) <EOL> val normalizeAbsolutePath = configuration . getBoolean ( CommonConfigurationKeys . KLIB_NORMALIZE_ABSOLUTE_PATH ) <EOL> val signatureClashChecks = configuration [ CommonConfigurationKeys . PRODUCE_KLIB_SIGNATURES_CLASH_CHECKS ] ? : true <EOL> val serializedIr = irModuleFragment ? . let { <EOL> val irDiagnosticReporter = KtDiagnosticReporterWithImplicitIrBasedContext ( diagnosticReporter , configuration . languageVersionSettings ) <EOL> runKlibCheckers ( it , irDiagnosticReporter , configuration ) <EOL> createModuleSerializer ( irDiagnosticReporter , it . irBuiltins , compatibilityMode , normalizeAbsolutePath , sourceBaseDirs , configuration . languageVersionSettings , signatureClashChecks , ) . serializedIrModule ( it ) <EOL> } <EOL> val serializedFiles = serializedIr ? . files ? . toList ( ) <EOL> val compiledKotlinFiles = buildList { <EOL> addAll ( cleanFiles ) <EOL> metadataSerializer . forEachFile { i , sourceFile , ktSourceFile , packageFqName -> <EOL> val binaryFile = serializedFiles ? . get ( i ) ? . also { <EOL> assert ( ktSourceFile . path == it . path ) { <EOL> """<STR_LIT>""" . trimMargin ( ) <EOL> } <EOL> } <EOL> val protoBuf = metadataSerializer . serializeSingleFileMetadata ( sourceFile ) <EOL> val metadata = protoBuf . toByteArray ( ) <EOL> val compiledKotlinFile = if ( binaryFile == null ) <EOL> KotlinFileSerializedData ( metadata , ktSourceFile . path , packageFqName . asString ( ) ) <EOL> else <EOL> KotlinFileSerializedData ( metadata , binaryFile ) <EOL> if ( processCompiledFileData != null ) { <EOL> val ioFile = ktSourceFile . toIoFileOrNull ( ) ? : error ( "<STR_LIT>" ) <EOL> processCompiledFileData ( ioFile , compiledKotlinFile ) <EOL> } <EOL> add ( compiledKotlinFile ) <EOL> } <EOL> } <EOL> val header = serializeKlibHeader ( languageVersionSettings = configuration . languageVersionSettings , moduleName = moduleName , fragmentNames = compiledKotlinFiles . map { it . fqName } . distinct ( ) . sorted ( ) , emptyPackages = emptyList ( ) , ) . toByteArray ( ) <EOL> processKlibHeader ( header ) <EOL> val ( fragmentNames , fragmentParts ) = compiledKotlinFiles <EOL> . groupBy { it . fqName } <EOL> . map { ( fqn , data ) -> <EOL> fqn to data . sortedBy { it . path } . map { it . metadata } <EOL> } <EOL> . sortedBy { it . first } <EOL> . unzip ( ) <EOL> val serializedMetadata = SerializedMetadata ( module = header , fragments = fragmentParts , fragmentNames = fragmentNames ) <EOL> return SerializerOutput ( serializedMetadata = serializedMetadata , serializedIr = if ( serializedIr == null ) null else SerializedIrModule ( compiledKotlinFiles . mapNotNull { it . irData } ) , dataFlowGraph = null , neededLibraries = dependencies , ) <EOL> }

/**
 * Produces all the necessary binary data for writing a KLIB for a Kotlin module, including its metadata.
 *
 * If [irModuleFragment] is not `null`, serializes the module's IR into binary form by running [IrModuleSerializer].
 *
 * For producing a metadata-only KLIB, pass `null` to [irModuleFragment].
 *
 * @param moduleName The name of the module being serialized to be written into the KLIB header.
 * @param irModuleFragment The IR to be serialized into the KLIB being produced, or `null` if this is going to be a metadata-only KLIB.
 * @param configuration Used to determine certain serialization parameters and enable/disable serialization diagnostics.
 * @param diagnosticReporter Used for reporting serialization-time diagnostics, for example, about clashing IR signatures.
 * @param compatibilityMode The information about KLIB ABI.
 * @param cleanFiles In the case of incremental compilation, the list of files that were not changed and therefore don't need to be
 * serialized again.
 * @param dependencies The list of KLIBs that the KLIB being produced depends on.
 * @param createModuleSerializer Used for creating a backend-specific instance of [IrModuleSerializer].
 * @param metadataSerializer Something capable of serializing the metadata of the source files. See the corresponding interface KDoc.
 * @param runKlibCheckers Additional checks to be run before serializing [irModuleFragment]. Can be used to report serialization-time
 * diagnostics.
 * @param processCompiledFileData Called for each newly serialized file. Useful for incremental compilation.
 * @param processKlibHeader Called after serializing the KLIB header. Useful for incremental compilation.
 */


{ <EOL> return base . hasChildren ( ) || <EOL> base . nonJavaResources . any { obj -> <EOL> obj is IFile && ( obj . name . endsWith ( "<STR_LIT>" ) || EclipseScriptDefinitionProvider . isScript ( FileScriptSource ( obj . asFile ) ) ) <EOL> } <EOL> }

/**
 * Returns true also when a package contains any Kotlin source file.
 *
 * Used by [JavaElementImageProvider.getPackageFragmentIcon]
 */


fun read ( library : MetadataLibraryProvider , readStrategy : KlibModuleFragmentReadStrategy = KlibModuleFragmentReadStrategy . DEFAULT ) : KlibModuleMetadata

{ <EOL> val moduleHeaderProto = parseModuleHeader ( library . moduleHeaderData ) <EOL> val headerNameResolver = NameResolverImpl ( moduleHeaderProto . strings , moduleHeaderProto . qualifiedNames ) <EOL> val moduleHeader = moduleHeaderProto . readHeader ( headerNameResolver ) <EOL> val fileIndex = SourceFileIndexReadExtension ( moduleHeader . file ) <EOL> val moduleFragments = moduleHeader . packageFragmentName . flatMap { packageFqName -> <EOL> library . packageMetadataParts ( packageFqName ) . map { part -> <EOL> val packageFragment = parsePackageFragment ( library . packageMetadata ( packageFqName , part ) ) <EOL> val nameResolver = NameResolverImpl ( packageFragment . strings , packageFragment . qualifiedNames ) <EOL> packageFragment . toKmModuleFragment ( nameResolver , listOf ( fileIndex ) ) <EOL> } . let ( readStrategy :: processModuleParts ) <EOL> } <EOL> return KlibModuleMetadata ( moduleHeader . moduleName , moduleFragments , moduleHeader . annotation ) <EOL> }

/**
 * Deserializes metadata from the given [library].
 * @param readStrategy specifies the way module fragments of a single package are modified (e.g. merged) after deserialization.
 */


fun write ( writeStrategy : KlibModuleFragmentWriteStrategy = KlibModuleFragmentWriteStrategy . DEFAULT ) : SerializedKlibMetadata

{ <EOL> val reverseIndex = ReverseSourceFileIndexWriteExtension ( ) <EOL> val groupedFragments = fragments <EOL> . groupBy ( KmModuleFragment :: fqNameOrFail ) <EOL> . mapValues { writeStrategy . processPackageParts ( it . value ) } <EOL> val header = KlibHeader ( name , reverseIndex . fileIndex , groupedFragments . map { it . key } , groupedFragments . filter { it . value . all ( KmModuleFragment :: isEmpty ) } . map { it . key } , annotations ) <EOL> val groupedProtos = groupedFragments . mapValues { ( _ , fragments ) -> <EOL> fragments . map { mf -> <EOL> val c = WriteContext ( ApproximatingStringTable ( ) , listOf ( reverseIndex ) ) <EOL> KlibModuleFragmentWriter ( c . strings as ApproximatingStringTable , c . contextExtensions ) . also { it . writeModuleFragment ( mf ) } . write ( ) <EOL> } <EOL> } <EOL> val c = WriteContext ( ApproximatingStringTable ( ) , listOf ( reverseIndex ) ) <EOL> return SerializedKlibMetadata ( header . writeHeader ( c ) . build ( ) . toByteArray ( ) , groupedProtos . map { it . value . map ( ProtoBuf . PackageFragment :: toByteArray ) } , header . packageFragmentName ) <EOL> }

/**
 * Writes metadata back to serialized representation.
 * @param writeStrategy specifies the way module fragments are modified (e.g. split) before serialization.
 */


fun render ( notebook : Notebook ) : DisplayResult

/**
 * Render to display result
 *
 * @param notebook Current notebook
 * @return Display result
 */


fun toJson ( additionalMetadata : JsonObject = Json . EMPTY , overrideId : String ? = null , ) : JsonObject

/**
 * Converts display data to JSON object for `display_data` response
 *
 * @param additionalMetadata Additional reply metadata
 * @return Display JSON
 */


override fun render ( notebook : Notebook ) : DisplayResult

= this

/**
 * Renders display result, generally should return `this`
 */


@ Suppress ( "<STR_LIT:unused>" ) <EOL> fun DisplayResult ? . toJson ( ) : JsonObject

{ <EOL> if ( this != null ) return this . toJson ( Json . EMPTY , null ) <EOL> return Json . encodeToJsonElement ( mapOf ( "<STR_LIT>" to null , "<STR_LIT>" to JsonObject ( mapOf ( ) ) ) ) as JsonObject <EOL> }

/**
 * Convenience method for converting nullable [DisplayResult] to JSON
 *
 * @return JSON for `display_data` response
 */


fun MutableJsonObject . setDisplayId ( id : String ? = null , force : Boolean = false , ) : String ?

{ <EOL> val transient = get ( "<STR_LIT>" ) ? . let { Json . decodeFromJsonElement < MutableJsonObject > ( it ) } <EOL> val oldId = ( transient ? . get ( "<STR_LIT>" ) as? JsonPrimitive ) ? . content <EOL> if ( id == null ) return oldId <EOL> if ( oldId != null && ! force ) return oldId <EOL> val newTransient = transient ? : mutableMapOf ( ) <EOL> newTransient [ "<STR_LIT>" ] = JsonPrimitive ( id ) <EOL> this [ "<STR_LIT>" ] = Json . encodeToJsonElement ( newTransient ) <EOL> return id <EOL> }

/**
 * Sets display ID to JSON.
 * If ID was not set, sets it to [id] and returns it back
 * If ID was set and [force] is false, just returns old ID
 * If ID was set, [force] is true and [id] is `null`, just returns old ID
 * If ID was set, [force] is true and [id] is not `null`, sets ID to [id] and returns it back
 */


fun JsonObject . containsDisplayId ( id : String ) : Boolean

{ <EOL> val transient : JsonObject ? = get ( "<STR_LIT>" ) as? JsonObject <EOL> return ( transient ? . get ( "<STR_LIT>" ) as? JsonPrimitive ) ? . content == id <EOL> }

/**
 * Check if the JSON object contains a `display_id` entry.
 */


private fun markdownCodeBlockBackticksCount ( code : String ) : Int

{ <EOL> return markdownBackticksRegex . findAll ( code ) . maxOfOrNull { it . value . length + <NUM_LIT:1> } ? : <NUM_LIT:3> <EOL> }

/** Return minimum number of backticks that are required to wrap [code] in Markdown code block without escaping it. */


fun Notebook . renderHtmlAsIFrameIfNeeded ( data : HtmlData ) : MimeTypedResult

{ <EOL> return if ( jupyterClientType == JupyterClientType . KOTLIN_NOTEBOOK ) { <EOL> data . toIFrame ( currentColorScheme ) <EOL> } else { <EOL> data . toSimpleHtml ( currentColorScheme ) <EOL> } <EOL> }

/**
 * Renders HTML as iframe in Kotlin Notebook or simply in other clients
 *
 * @param data
 */


@ SlicedGeneratedTest ( allLanguages = true , allTools = true ) <EOL> fun SlicedBuildConfigurator . testDisableInstrumentationOfTask ( )

{ <EOL> addProjectWithKover { <EOL> sourcesFrom ( "<STR_LIT:simple>" ) <EOL> kover { <EOL> currentProject { <EOL> instrumentation { <EOL> disabledForTestTasks . add ( defaultTestTaskName ( slice . type ) ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> run ( "<STR_LIT>" ) { <EOL> checkOutcome ( "<STR_LIT>" , "<STR_LIT:SUCCESS>" ) <EOL> checkOutcome ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> taskNotCalled ( defaultTestTaskName ( slice . type ) ) <EOL> checkDefaultBinReport ( false ) <EOL> } <EOL> }

/**
 * Compile tasks must be executed even if all test tasks are disabled.
 */


private fun testWritableByteChannel ( isBuffer : Boolean , channel : WritableByteChannel )

{ <EOL> assertTrue ( channel . isOpen ( ) ) <EOL> val byteBuffer = ByteBuffer . allocate ( <NUM_LIT> ) <EOL> byteBuffer . put ( "<STR_LIT>" . toByteArray ( UTF_8 ) ) <EOL> byteBuffer . flip ( ) <EOL> byteBuffer . position ( <NUM_LIT:3> ) <EOL> byteBuffer . limit ( <NUM_LIT:23> ) <EOL> val byteCount : Int = channel . write ( byteBuffer ) <EOL> assertEquals ( <NUM_LIT:20> , byteCount ) <EOL> assertEquals ( <NUM_LIT:23> , byteBuffer . position ( ) ) <EOL> assertEquals ( <NUM_LIT:23> , byteBuffer . limit ( ) ) <EOL> channel . close ( ) <EOL> assertEquals ( isBuffer , channel . isOpen ) <EOL> }

/**
 * Does some basic writes to `channel`. We execute this against both Okio's channels and
 * also a standard implementation from the JDK to confirm that their behavior is consistent.
 */


private fun testReadableByteChannel ( isBuffer : Boolean , channel : ReadableByteChannel )

{ <EOL> assertTrue ( channel . isOpen ) <EOL> val byteBuffer = ByteBuffer . allocate ( <NUM_LIT> ) <EOL> byteBuffer . position ( <NUM_LIT:3> ) <EOL> byteBuffer . limit ( <NUM_LIT:23> ) <EOL> val byteCount : Int = channel . read ( byteBuffer ) <EOL> assertEquals ( <NUM_LIT:20> , byteCount ) <EOL> assertEquals ( <NUM_LIT:23> , byteBuffer . position ( ) ) <EOL> assertEquals ( <NUM_LIT:23> , byteBuffer . limit ( ) ) <EOL> channel . close ( ) <EOL> assertEquals ( isBuffer , channel . isOpen ( ) ) <EOL> byteBuffer . flip ( ) <EOL> byteBuffer . position ( <NUM_LIT:3> ) <EOL> val data = ByteArray ( byteBuffer . remaining ( ) ) <EOL> byteBuffer [ data ] <EOL> assertEquals ( "<STR_LIT>" , String ( data , UTF_8 ) ) <EOL> }

/**
 * Does some basic reads from `channel`. We execute this against both Okio's channels and
 * also a standard implementation from the JDK to confirm that their behavior is consistent.
 */


public fun get ( ) : V

/**
 * Returns the current value of the property.
 */


public fun set ( value : V )

/**
 * Modifies the value of the property.
 *
 * @param value the new value to be assigned to this property.
 */


public fun get ( receiver : T ) : V

/**
 * Returns the current value of the property.
 *
 * @param receiver the receiver which is used to obtain the value of the property.
 * For example, it should be a class instance if this is a member property of that class,
 * or an extension receiver if this is a top level extension property.
 */


public fun set ( receiver : T , value : V )

/**
 * Modifies the value of the property.
 *
 * @param receiver the receiver which is used to modify the value of the property.
 * For example, it should be a class instance if this is a member property of that class,
 * or an extension receiver if this is a top level extension property.
 * @param value the new value to be assigned to this property.
 */


public fun get ( receiver1 : D , receiver2 : E ) : V

/**
 * Returns the current value of the property. In case of the extension property in a class,
 * the instance of the class should be passed first and the instance of the extension receiver second.
 *
 * @param receiver1 the instance of the first receiver.
 * @param receiver2 the instance of the second receiver.
 */


public fun set ( receiver1 : D , receiver2 : E , value : V )

/**
 * Modifies the value of the property.
 *
 * @param receiver1 the instance of the first receiver.
 * @param receiver2 the instance of the second receiver.
 * @param value the new value to be assigned to this property.
 */


fun shouldCheckDeclaration ( declaration : Any ) : Boolean

= <EOL> when ( declaration ) { <EOL> is KmFunction -> ! declaration . name . startsWith ( KNI_BRIDGE_FUNCTION_PREFIX ) <EOL> else -> true <EOL> }

/**
 * Certain auxiliary metadata entities may be intentionally excluded from comparison.
 * Ex: Kotlin/Native interface bridge functions.
 */


private fun KmFunction . dumpToString ( ) : String

= buildString { <EOL> receiverParameterType ? . classifier ? . let { classifier -> <EOL> append ( classifier . dumpToString ( dumpClassifierType = true ) ) . append ( '<CHAR_LIT:.>' ) <EOL> } <EOL> append ( name ) <EOL> if ( typeParameters . isNotEmpty ( ) ) { <EOL> typeParameters . joinTo ( this , prefix = "<STR_LIT:<>" , postfix = "<STR_LIT:>>" ) { typeParameter -> <EOL> val typeParameterText = "<STR_LIT>" <EOL> if ( typeParameter . upperBounds . isNotEmpty ( ) ) { <EOL> val upperBoundsText = typeParameter . upperBounds . joinToString { type -> type . dumpToString ( dumpExtras = false ) } <EOL> "<STR_LIT>" <EOL> } else typeParameterText <EOL> } <EOL> } <EOL> valueParameters . joinTo ( this , prefix = "<STR_LIT:(>" , postfix = "<STR_LIT:)>" ) { valueParameter -> <EOL> valueParameter . type . dumpToString ( dumpExtras = false ) <EOL> } <EOL> }

/**
 * We need a stable order for overloaded functions.
 */


fun < T : Number > around ( a : KtNDArray < T > , decimals : Int = <NUM_LIT:0> ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , decimals ) )

/**
 * Evenly round to the given number of decimals.
 */


fun < T : Number > rint ( a : KtNDArray < T > ) : KtNDArray < Double >

= callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a ) )

/**
 * Round an array to the given number of decimals.
 */


fun < T : Number > fix ( a : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Round to nearest integer towards zero.
 */


fun < T : Number > floor ( a : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Return the floor of the input, element-wise.
 */


fun < T : Number > ceil ( a : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Return the ceiling of the input, element-wise.
 */


fun < T : Number > trunc ( a : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Return the truncated value of the input, element-wise.
 */


fun parkedWorkersStackTopUpdate ( worker : Worker , oldIndex : Int , newIndex : Int )

{ <EOL> parkedWorkersStack . loop { top -> <EOL> val index = ( top and PARKED_INDEX_MASK ) . toInt ( ) <EOL> val updVersion = ( top + PARKED_VERSION_INC ) and PARKED_VERSION_MASK <EOL> val updIndex = if ( index == oldIndex ) { <EOL> if ( newIndex == <NUM_LIT:0> ) { <EOL> parkedWorkersStackNextIndex ( worker ) <EOL> } else { <EOL> newIndex <EOL> } <EOL> } else { <EOL> index <EOL> } <EOL> if ( updIndex < <NUM_LIT:0> ) return@loop <EOL> if ( parkedWorkersStack . compareAndSet ( top , updVersion or updIndex . toLong ( ) ) ) return <EOL> } <EOL> }

/**
 * Updates index of the worker at the top of [parkedWorkersStack].
 * It always updates version to ensure interference with [parkedWorkersStackPop] operation
 * that might have already decided to put this index to the top.
 *
 * Note, [newIndex] can be zero for the worker that is being terminated (removed from [workers]).
 */


fun parkedWorkersStackPush ( worker : Worker ) : Boolean

{ <EOL> if ( worker . nextParkedWorker !== NOT_IN_STACK ) return false <EOL> parkedWorkersStack . loop { top -> <EOL> val index = ( top and PARKED_INDEX_MASK ) . toInt ( ) <EOL> val updVersion = ( top + PARKED_VERSION_INC ) and PARKED_VERSION_MASK <EOL> val updIndex = worker . indexInArray <EOL> assert { updIndex != <NUM_LIT:0> } <EOL> worker . nextParkedWorker = workers [ index ] <EOL> if ( parkedWorkersStack . compareAndSet ( top , updVersion or updIndex . toLong ( ) ) ) return true <EOL> } <EOL> }

/**
 * Pushes worker into [parkedWorkersStack].
 * It does nothing is this worker is already physically linked to the stack.
 * This method is invoked only from the worker thread itself.
 * This invocation always precedes [LockSupport.parkNanos].
 * See [Worker.tryPark].
 *
 * Returns `true` if worker was added to the stack by this invocation, `false` if it was already
 * registered in the stack.
 */


private fun parkedWorkersStackPop ( ) : Worker ?

{ <EOL> parkedWorkersStack . loop { top -> <EOL> val index = ( top and PARKED_INDEX_MASK ) . toInt ( ) <EOL> val worker = workers [ index ] ? : return null <EOL> val updVersion = ( top + PARKED_VERSION_INC ) and PARKED_VERSION_MASK <EOL> val updIndex = parkedWorkersStackNextIndex ( worker ) <EOL> if ( updIndex < <NUM_LIT:0> ) return@loop <EOL> if ( parkedWorkersStack . compareAndSet ( top , updVersion or updIndex . toLong ( ) ) ) { <EOL> worker . nextParkedWorker = NOT_IN_STACK <EOL> return worker <EOL> } <EOL> } <EOL> }

/**
 * Pops worker from [parkedWorkersStack].
 * It can be invoked concurrently from any thread that is looking for help and needs to unpark some worker.
 * This invocation is always followed by an attempt to [LockSupport.unpark] resulting worker.
 * See [tryUnpark].
 */


private fun parkedWorkersStackNextIndex ( worker : Worker ) : Int

{ <EOL> var next = worker . nextParkedWorker <EOL> findNext @ while ( true ) { <EOL> when { <EOL> next === NOT_IN_STACK -> return - <NUM_LIT:1> <EOL> next === null -> return <NUM_LIT:0> <EOL> else -> { <EOL> val nextWorker = next as Worker <EOL> val updIndex = nextWorker . indexInArray <EOL> if ( updIndex != <NUM_LIT:0> ) return updIndex <EOL> next = nextWorker . nextParkedWorker <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Finds next usable index for [parkedWorkersStack]. The problem is that workers can
 * be terminated at their [Worker.indexInArray] becomes zero, so they cannot be
 * put at the top of the stack. In which case we are looking for next.
 *
 * Returns `index >= 0` or `-1` for retry.
 */


fun dispatch ( block : Runnable , taskContext : TaskContext = NonBlockingContext , tailDispatch : Boolean = false )

{ <EOL> trackTask ( ) <EOL> val task = createTask ( block , taskContext ) <EOL> val isBlockingTask = task . isBlocking <EOL> val stateSnapshot = if ( isBlockingTask ) incrementBlockingTasks ( ) else <NUM_LIT:0> <EOL> val currentWorker = currentWorker ( ) <EOL> val notAdded = currentWorker . submitToLocalQueue ( task , tailDispatch ) <EOL> if ( notAdded != null ) { <EOL> if ( ! addToGlobalQueue ( notAdded ) ) { <EOL> throw RejectedExecutionException ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> val skipUnpark = tailDispatch && currentWorker != null <EOL> if ( isBlockingTask ) { <EOL> signalBlockingWork ( stateSnapshot , skipUnpark = skipUnpark ) <EOL> } else { <EOL> if ( skipUnpark ) return <EOL> signalCpuWork ( ) <EOL> } <EOL> }

/**
 * Dispatches execution of a runnable [block] with a hint to a scheduler whether
 * this [block] may execute blocking operations (IO, system calls, locking primitives etc.)
 *
 * [taskContext] -- concurrency context of given [block].
 * [tailDispatch] -- whether this [dispatch] call is the last action the (presumably) worker thread does in its current task.
 * If `true`, then the task will be dispatched in a FIFO manner and no additional workers will be requested,
 * but only if the current thread is a corresponding worker thread.
 * Note that caller cannot be ensured that it is being executed on worker thread for the following reasons:
 * - [CoroutineStart.UNDISPATCHED]
 * - Concurrent [close] that effectively shutdowns the worker thread
 */


{ <EOL> val worker : Worker <EOL> return synchronized ( workers ) { <EOL> if ( isTerminated ) return - <NUM_LIT:1> <EOL> val state = controlState . value <EOL> val created = createdWorkers ( state ) <EOL> val blocking = blockingTasks ( state ) <EOL> val cpuWorkers = ( created - blocking ) . coerceAtLeast ( <NUM_LIT:0> ) <EOL> if ( cpuWorkers >= corePoolSize ) return <NUM_LIT:0> <EOL> if ( created >= maxPoolSize ) return <NUM_LIT:0> <EOL> val newIndex = createdWorkers + <NUM_LIT:1> <EOL> require ( newIndex > <NUM_LIT:0> && workers [ newIndex ] == null ) <EOL> worker = Worker ( newIndex ) <EOL> workers . setSynchronized ( newIndex , worker ) <EOL> require ( newIndex == incrementCreatedWorkers ( ) ) <EOL> cpuWorkers + <NUM_LIT:1> <EOL> } . also { worker . start ( ) } <EOL> }

/**
 * Returns the number of CPU workers after this function (including new worker) or
 * 0 if no worker was created.
 */


private fun Worker ? . submitToLocalQueue ( task : Task , tailDispatch : Boolean ) : Task ?

{ <EOL> if ( this == null ) return task <EOL> if ( state === WorkerState . TERMINATED ) return task <EOL> if ( task . mode == TASK_NON_BLOCKING && state === WorkerState . BLOCKING ) { <EOL> return task <EOL> } <EOL> mayHaveLocalTasks = true <EOL> return localQueue . add ( task , fair = tailDispatch ) <EOL> }

/**
 * Returns `null` if task was successfully added or an instance of the
 * task that was not added or replaced (thus should be added to global queue).
 */


{ <EOL> var parkedWorkers = <NUM_LIT:0> <EOL> var blockingWorkers = <NUM_LIT:0> <EOL> var cpuWorkers = <NUM_LIT:0> <EOL> var dormant = <NUM_LIT:0> <EOL> var terminated = <NUM_LIT:0> <EOL> val queueSizes = arrayListOf < String > ( ) <EOL> for ( index in <NUM_LIT:1> until workers . currentLength ( ) ) { <EOL> val worker = workers [ index ] ? : continue <EOL> val queueSize = worker . localQueue . size <EOL> when ( worker . state ) { <EOL> WorkerState . PARKING -> ++ parkedWorkers <EOL> WorkerState . BLOCKING -> { <EOL> ++ blockingWorkers <EOL> queueSizes += queueSize . toString ( ) + "<STR_LIT:b>" <EOL> } <EOL> WorkerState . CPU_ACQUIRED -> { <EOL> ++ cpuWorkers <EOL> queueSizes += queueSize . toString ( ) + "<STR_LIT:c>" <EOL> } <EOL> WorkerState . DORMANT -> { <EOL> ++ dormant <EOL> if ( queueSize > <NUM_LIT:0> ) queueSizes += queueSize . toString ( ) + "<STR_LIT:d>" <EOL> } <EOL> WorkerState . TERMINATED -> ++ terminated <EOL> } <EOL> } <EOL> val state = controlState . value <EOL> return "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> }

/**
 * Returns a string identifying the state of this scheduler for nicer debugging.
 * Note that this method is not atomic and represents rough state of pool.
 *
 * State of the queues:
 * b for blocking, c for CPU, r for retiring.
 * E.g. for [1b, 1b, 2c, 1d] means that pool has
 * two blocking workers with queue size 1, one worker with CPU permit and queue size 1
 * and one dormant (executing his local queue before parking) worker with queue size 1.
 */


private fun tryAcquireCpuPermit ( ) : Boolean

= when { <EOL> state == WorkerState . CPU_ACQUIRED -> true <EOL> this@CoroutineScheduler . tryAcquireCpuPermit ( ) -> { <EOL> state = WorkerState . CPU_ACQUIRED <EOL> true <EOL> } <EOL> else -> false <EOL> }

/**
 * Tries to acquire CPU token if worker doesn't have one
 * @return whether worker acquired (or already had) CPU token
 */


fun tryReleaseCpu ( newState : WorkerState ) : Boolean

{ <EOL> val previousState = state <EOL> val hadCpu = previousState == WorkerState . CPU_ACQUIRED <EOL> if ( hadCpu ) releaseCpuPermit ( ) <EOL> if ( previousState != newState ) state = newState <EOL> return hadCpu <EOL> }

/**
 * Releases CPU token if worker has any and changes state to [newState].
 * Returns `true` if CPU permit was returned to the pool
 */


{ <EOL> val stateSnapshot = state <EOL> val isCpuThread = state == WorkerState . CPU_ACQUIRED <EOL> val task = if ( isCpuThread ) { <EOL> findCpuTask ( ) <EOL> } else { <EOL> findBlockingTask ( ) <EOL> } <EOL> if ( task == null ) { <EOL> if ( minDelayUntilStealableTaskNs == <NUM_LIT:0L> ) return - <NUM_LIT:1L> <EOL> return minDelayUntilStealableTaskNs <EOL> } <EOL> runSafely ( task ) <EOL> if ( ! isCpuThread ) decrementBlockingTasks ( ) <EOL> assert { state == stateSnapshot } <EOL> return <NUM_LIT:0L> <EOL> }

/**
 * See [runSingleTaskFromCurrentSystemDispatcher] for rationale and details.
 * This is a fine-tailored method for a specific use-case not expected to be used widely.
 */


{ <EOL> synchronized ( workers ) { <EOL> if ( isTerminated ) return <EOL> if ( createdWorkers <= corePoolSize ) return <EOL> if ( ! workerCtl . compareAndSet ( PARKED , TERMINATED ) ) return <EOL> val oldIndex = indexInArray <EOL> indexInArray = <NUM_LIT:0> <EOL> parkedWorkersStackTopUpdate ( this , oldIndex , <NUM_LIT:0> ) <EOL> val lastIndex = decrementCreatedWorkers ( ) <EOL> if ( lastIndex != oldIndex ) { <EOL> val lastWorker = workers [ lastIndex ] ! ! <EOL> workers . setSynchronized ( oldIndex , lastWorker ) <EOL> lastWorker . indexInArray = oldIndex <EOL> parkedWorkersStackTopUpdate ( lastWorker , lastIndex , oldIndex ) <EOL> } <EOL> workers . setSynchronized ( lastIndex , null ) <EOL> } <EOL> state = WorkerState . TERMINATED <EOL> }

/**
 * Stops execution of current thread and removes it from [createdWorkers].
 */


@ JvmName ( "<STR_LIT>" ) <EOL> internal fun isSchedulerWorker ( thread : Thread )

= thread is CoroutineScheduler . Worker

/**
 * Checks if the thread is part of a thread pool that supports coroutines.
 * This function is needed for integration with BlockHound.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> internal fun mayNotBlock ( thread : Thread )

= thread is CoroutineScheduler . Worker && <EOL> thread . state == CoroutineScheduler . WorkerState . CPU_ACQUIRED

/**
 * Checks if the thread is running a CPU-bound task.
 * This function is needed for integration with BlockHound.
 */


private fun String . getRootLength ( ) : Int

{ <EOL> var first = indexOf ( File . separatorChar , <NUM_LIT:0> ) <EOL> if ( first == <NUM_LIT:0> ) { <EOL> if ( length > <NUM_LIT:1> && this [ <NUM_LIT:1> ] == File . separatorChar ) { <EOL> first = indexOf ( File . separatorChar , <NUM_LIT:2> ) <EOL> if ( first >= <NUM_LIT:0> ) { <EOL> first = indexOf ( File . separatorChar , first + <NUM_LIT:1> ) <EOL> if ( first >= <NUM_LIT:0> ) <EOL> return first + <NUM_LIT:1> <EOL> else <EOL> return length <EOL> } <EOL> } <EOL> return <NUM_LIT:1> <EOL> } <EOL> if ( first > <NUM_LIT:0> && this [ first - <NUM_LIT:1> ] == '<CHAR_LIT::>' ) { <EOL> first ++ <EOL> return first <EOL> } <EOL> if ( first == - <NUM_LIT:1> && endsWith ( '<CHAR_LIT::>' ) ) <EOL> return length <EOL> return <NUM_LIT:0> <EOL> }

/**
 * Estimation of a root name by a given file name.
 *
 * This implementation is able to find /, Drive:/, Drive: or
 * //network.name/root as possible root names.
 * / denotes File.separator here so \ can be used instead.
 * All other possible roots cannot be identified by this implementation.
 * It's also not guaranteed (but possible) that function will be able to detect a root
 * which is incorrect for current OS. For instance, in Unix function cannot detect
 * network root names like //network.name/root, but can detect Windows roots like C:/.
 *
 * @return length or a substring representing the root for this path, or zero if this file name is relative.
 */


public fun subPath ( beginIndex : Int , endIndex : Int ) : File

{ <EOL> if ( beginIndex < <NUM_LIT:0> || beginIndex > endIndex || endIndex > size ) <EOL> throw IllegalArgumentException ( ) <EOL> return File ( segments . subList ( beginIndex , endIndex ) . joinToString ( File . separator ) ) <EOL> }

/**
 * Returns a sub-path of the path, starting with the directory at the specified [beginIndex] and up
 * to the specified [endIndex].
 */


internal fun File . toComponents ( ) : FilePathComponents

{ <EOL> val path = path <EOL> val rootLength = path . getRootLength ( ) <EOL> val rootName = path . substring ( <NUM_LIT:0> , rootLength ) <EOL> val subPath = path . substring ( rootLength ) <EOL> val list = if ( subPath . isEmpty ( ) ) listOf ( ) else subPath . split ( File . separatorChar ) . map ( :: File ) <EOL> return FilePathComponents ( File ( rootName ) , list ) <EOL> }

/**
 * Splits the file into path components (the names of containing directories and the name of the file
 * itself) and returns the resulting collection of components.
 */


internal fun File . subPath ( beginIndex : Int , endIndex : Int ) : File

= toComponents ( ) . subPath ( beginIndex , endIndex )

/**
 * Returns a relative pathname which is a subsequence of this pathname,
 * beginning from component [beginIndex], inclusive,
 * ending at component [endIndex], exclusive.
 * Number 0 belongs to a component closest to the root,
 * number count-1 belongs to a component farthest from the root.
 * @throws IllegalArgumentException if [beginIndex] is negative,
 * or [endIndex] is greater than existing number of components,
 * or [beginIndex] is greater than [endIndex].
 */


@ Test <EOL> fun `test - diamond hierarchy from documentation example` ( )

{ <EOL> kotlin . applyHierarchyTemplate { <EOL> common { <EOL> group ( "<STR_LIT>" ) { <EOL> withIos ( ) <EOL> } <EOL> group ( "<STR_LIT>" ) { <EOL> withJvm ( ) <EOL> group ( "<STR_LIT>" ) <EOL> } <EOL> group ( "<STR_LIT>" ) { <EOL> withMacos ( ) <EOL> group ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> kotlin . iosX64 ( ) <EOL> kotlin . iosArm64 ( ) <EOL> kotlin . macosX64 ( ) <EOL> kotlin . jvm ( ) <EOL> assertEquals ( stringSetOf ( "<STR_LIT>" , "<STR_LIT>" ) , kotlin . dependingSourceSetNames ( "<STR_LIT:commonMain>" ) ) <EOL> assertEquals ( stringSetOf ( "<STR_LIT:jvmMain>" , "<STR_LIT>" ) , kotlin . dependingSourceSetNames ( "<STR_LIT>" ) ) <EOL> assertEquals ( stringSetOf ( "<STR_LIT>" , "<STR_LIT>" ) , kotlin . dependingSourceSetNames ( "<STR_LIT>" ) ) <EOL> assertEquals ( stringSetOf ( "<STR_LIT>" , "<STR_LIT>" ) , kotlin . dependingSourceSetNames ( "<STR_LIT>" ) ) <EOL> }


private fun ClassId . getOutermostClassName ( )

= relativeClassName . pathSegments ( ) . first ( ) . asString ( )

/**
 * Gets the short outermost class name. For example, `foo.bar.Foo` -> `Foo`. `foo.bar.Outer.Inner.InnerAgain` -> `Outer`.
 */


internal fun artifactGenerationTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for task for generating Kover artifact.
 */


internal fun htmlReportTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for HTML reporting task for specified report namespace.
 */


internal fun xmlReportTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for XML reporting task for specified report namespace.
 */


internal fun binaryReportTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for binary reporting task for specified report namespace.
 */


internal fun verifyCachedTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for cached verifying task for specified report namespace.
 */


internal fun verifyTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for verifying task for specified report namespace.
 */


internal fun logTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for coverage logging task.
 */


internal fun printLogTaskName ( variant : String )

= "<STR_LIT>"

/**
 * Name for task to print coverage to the log.
 */


internal fun binReportName ( taskName : String , toolVendor : CoverageToolVendor ) : String

{ <EOL> return "<STR_LIT>" <EOL> }

/**
 * Name of binary report for specified test task name (without directory path).
 */


internal fun artifactConfigurationName ( variantName : String ) : String

= "<STR_LIT>"

/**
 * Name of the Gradle configuration for sharing Kover artifact.
 */


internal fun externalArtifactConfigurationName ( variantName : String ) : String

= "<STR_LIT>"

/**
 * Name of the Gradle configuration for collecting Kover artifacts from dependencies.
 */


public inline fun < M : ExecutionProviderCompatible , R > M . inferAndCloseUsing ( vararg providers : ExecutionProvider , block : ( M ) -> R ) : R

{ <EOL> this . initializeWith ( * providers ) <EOL> return this . use ( block ) <EOL> }

/**
 * Extension function for explicitly specifying the execution provider for specific code block.
 * Follows [kotlin.use] semantics.
 */


public inline fun < M : ExecutionProviderCompatible , R > M . inferUsing ( vararg providers : ExecutionProvider , block : ( M ) -> R ) : R

{ <EOL> this . initializeWith ( * providers ) <EOL> return this . run ( block ) <EOL> }

/**
 * Extension function for explicitly specifying the execution provider for specific code block.
 * Follows [kotlin.run] semantics.
 */


public fun BarContext . border ( block : BorderLayerContext . ( ) -> Unit )

{ <EOL> BorderLayerContext ( this ) . apply ( block ) <EOL> }

/**
 * Adds [border][BorderLayerContext] settings to [bars][org.jetbrains.kotlinx.kandy.echarts.layers.bars].
 */


public fun PointContext . border ( block : BorderLayerContext . ( ) -> Unit )

/**
 * Adds [border][BorderLayerContext] settings to [points][org.jetbrains.kotlinx.kandy.echarts.layers.points].
 */


public operator fun get ( index : Int ) : MatchGroup ?

/** Returns a group with the specified [index].
 *
 * @return An instance of [MatchGroup] if the group with the specified [index] was matched or `null` otherwise.
 *
 * Groups are indexed from 1 to the count of groups in the regular expression. A group with the index 0
 * corresponds to the entire match.
 */


public operator fun get ( name : String ) : MatchGroup ?

/**
 * Returns a named group with the specified [name].
 * @return An instance of [MatchGroup] if the group with the specified [name] was matched or `null` otherwise.
 * @throws IllegalArgumentException if there is no group with the specified [name] defined in the regex pattern.
 * @throws UnsupportedOperationException if this match group collection doesn't support getting match groups by name,
 * for example, when it's not supported by the current platform.
 */


public fun next ( ) : MatchResult ?

/** Returns a new [MatchResult] with the results for the next match, starting at the position
 * at which the last match ended (at the character after the last matched character).
 */


= match . groupValues . subList ( <NUM_LIT:1> , match . groupValues . size )

/**
 * Returns destructured group values as a list of strings.
 * First value in the returned list corresponds to the value of the first group, and so on.
 *
 * @sample samples.text.Regexps.matchDestructuringToGroupValues
 */


public suspend inline fun < T > MaybeSource < T > . collect ( action : ( T ) -> Unit ) : Unit

= <EOL> toChannel ( ) . consumeEach ( action )

/**
 * Subscribes to this [MaybeSource] and performs the specified action for each received element.
 *
 * If [action] throws an exception at some point or if the [MaybeSource] raises an error, the exception is rethrown from
 * [collect].
 */


public suspend inline fun < T > ObservableSource < T > . collect ( action : ( T ) -> Unit ) : Unit

/**
 * Subscribes to this [ObservableSource] and performs the specified action for each received element.
 *
 * If [action] throws an exception at some point, the subscription is cancelled, and the exception is rethrown from
 * [collect]. Also, if the [ObservableSource] signals an error, that error is rethrown from [collect].
 */


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < T > ObservableSource < T & Any > . openSubscription ( ) : ReceiveChannel < T >

{ <EOL> val channel = SubscriptionChannel < T > ( ) <EOL> subscribe ( channel ) <EOL> return channel <EOL> }


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN ) <EOL> public fun < T > MaybeSource < T & Any > . openSubscription ( ) : ReceiveChannel < T >


public inline fun EChartsLayout . tooltip ( crossinline block : Tooltip . ( ) -> Unit )

{ <EOL> this . tooltip = Tooltip ( ) . apply ( block ) <EOL> }

/**
 * Configures global tooltip.
 *
 * - [trigger][Tooltip.trigger] - [type][Trigger] of triggering
 * - [formatter][Tooltip.formatter] - the content formatter of tooltip's floating layer
 *
 * ```kotlin
 * plot {
 * layout {
 * tooltip {
 * trigger = Trigger.AXIS
 * formatter = "layer {a}}
 * }
 * }
 * }
 * ```
 *
 * @see org.jetbrains.kotlinx.kandy.echarts.layers.layout
 * @see EChartsLayout
 */


@ ContractsDsl public fun returns ( ) : Returns

/**
 * Describes a situation when a function returns normally, without any exceptions thrown.
 *
 * Use [SimpleEffect.implies] function to describe a conditional effect that happens in such case.
 *
 */


@ ContractsDsl public fun returns ( value : Any ? ) : Returns

/**
 * Describes a situation when a function returns normally with the specified return [value].
 *
 * The possible values of [value] are limited to `true`, `false` or `null`.
 *
 * Use [SimpleEffect.implies] function to describe a conditional effect that happens in such case.
 *
 */


@ ContractsDsl public fun returnsNotNull ( ) : ReturnsNotNull

/**
 * Describes a situation when a function returns normally with any value that is not `null`.
 *
 * Use [SimpleEffect.implies] function to describe a conditional effect that happens in such case.
 *
 */


inline fun < reified E : Exception > assertThrows ( message : String = "<STR_LIT>" , body : ( ) -> Unit , ) : Throwable

{ <EOL> try { <EOL> body ( ) <EOL> } catch ( e : Throwable ) { <EOL> if ( e is E ) { <EOL> return e <EOL> } <EOL> } <EOL> throw AssertionError ( message ) <EOL> }

/**
 * A replacement for the JUnit Jupiter function to be used in JUnit 4 tests.
 *
 * Asserts that the given code block throws an exception of the specified type.
 *
 * @param E the type of exception that is expected to be thrown
 * @param message the error message to be used if the exception is not thrown
 * @param body the code block to be executed and verified
 * @return the caught exception if it is of the specified type
 * @throws AssertionError if the specified exception is not thrown
 */


fun < R > assertDoesNotThrow ( message : String = "<STR_LIT>" , body : ( ) -> R , ) : R

{ <EOL> try { <EOL> return body ( ) <EOL> } catch ( e : Throwable ) { <EOL> throw AssertionError ( message . format ( e ) ) <EOL> } <EOL> }

/**
 * A replacement for the JUnit Jupiter function to be used in JUnit 4 tests.
 *
 * Asserts that the specified code block does not throw any exception.
 *
 * @param message The message to be included in the AssertionError if an exception is thrown.
 * It can contain the "{}" placeholder, which will be replaced with the thrown exception.
 * @param body The code block to be executed.
 *
 * @return The result of executing the code block.
 *
 * @throws AssertionError If the code block throws an exception.
 */


private fun createModules ( moduleStructure : TestModuleStructure , testServices : TestServices , project : Project , ) : List < KtTestModule >

{ <EOL> val moduleCount = moduleStructure . modules . size <EOL> val existingModules = HashMap < String , KtTestModule > ( moduleCount ) <EOL> val result = ArrayList < KtTestModule > ( moduleCount ) <EOL> for ( testModule in moduleStructure . modules ) { <EOL> val contextModuleName = testModule . directives . singleOrZeroValue ( AnalysisApiTestDirectives . CONTEXT_MODULE ) <EOL> val contextModule = contextModuleName ? . let ( existingModules :: getValue ) <EOL> val dependencyBinaryRoots = testModule . regularDependencies . flatMap { dependency -> <EOL> val libraryModule = existingModules . getValue ( dependency . moduleName ) . ktModule as? KtLibraryModule <EOL> libraryModule ? . getBinaryRoots ( ) . orEmpty ( ) <EOL> } <EOL> val ktTestModule = testServices <EOL> . getKtModuleFactoryForTestModule ( testModule ) <EOL> . createModule ( testModule , contextModule , dependencyBinaryRoots , testServices , project ) <EOL> existingModules [ testModule . name ] = ktTestModule <EOL> result . add ( ktTestModule ) <EOL> } <EOL> return result <EOL> }

/**
 * The test infrastructure ensures that the given [moduleStructure] contains properly ordered dependencies: a [TestModule] can only
 * depend on test modules which precede it. Hence, this function does not need to order dependencies itself.
 *
 * @return A list of [KtTestModule]s in the same order as [TestModuleStructure.modules].
 */


private fun KtModule . addToLibraryCacheIfNeeded ( libraryCache : LibraryCache )

{ <EOL> if ( this is KtBinaryModule ) { <EOL> libraryCache . put ( getBinaryRoots ( ) . toSet ( ) , this ) <EOL> } <EOL> }

/**
 * A main module may be a binary library module, which may be a dependency of subsequent main modules. We need to add such a module to
 * the library cache before it is processed as a dependency. Otherwise, when another module's binary dependency is processed,
 * [addLibraryDependencies] will create a *duplicate* binary library module with the same roots and name as the already existing binary
 * library module.
 */


private inline fun < reified T : PsiElement > PsiElement . forEachDescendantOfType ( noinline predicate : ( T ) -> Boolean = { true } , noinline action : ( T ) -> Unit , )

= this . accept ( object : PsiRecursiveElementVisitor ( ) { <EOL> override fun visitElement ( element : PsiElement ) { <EOL> if ( element is T && predicate ( element ) ) { <EOL> action ( element ) <EOL> } <EOL> super . visitElement ( element ) <EOL> } <EOL> } )

/**
 * Processes the descendants of the element using the preorder implementation of tree traversal.
 */


private fun isRelated ( a : KotlinType , b : KotlinType , platformToKotlinClassMapper : PlatformToKotlinClassMapper ) : Boolean

{ <EOL> val aClasses = mapToPlatformIndependentClasses ( a , platformToKotlinClassMapper ) <EOL> val bClasses = mapToPlatformIndependentClasses ( b , platformToKotlinClassMapper ) <EOL> return aClasses . any { DescriptorUtils . isSubtypeOfClass ( b , it ) } || bClasses . any { DescriptorUtils . isSubtypeOfClass ( a , it ) } <EOL> }

/**
 * Two types are related, roughly, when one of them is a subtype of the other constructing class
 *
 * Note that some types have platform-specific counterparts, i.e. kotlin.String is mapped to java.lang.String,
 * such types (and all their sub- and supertypes) are related too.
 *
 * Due to limitations in PlatformToKotlinClassMap, we only consider mapping of platform classes to Kotlin classed
 * (i.e. java.lang.String -> kotlin.String) and ignore mappings that go the other way.
 */


@ JvmStatic <EOL> fun isCastErased ( supertype : KotlinType , subtype : KotlinType , typeChecker : KotlinTypeChecker ) : Boolean

{ <EOL> val isNonReifiedTypeParameter = TypeUtils . isNonReifiedTypeParameter ( subtype ) <EOL> val isUpcast = typeChecker . isSubtypeOf ( supertype , subtype ) <EOL> if ( isNonReifiedTypeParameter && ! isUpcast ) { <EOL> val nullableToDefinitelyNotNull = ! TypeUtils . isNullableType ( subtype ) && supertype . makeNotNullable ( ) == subtype <EOL> if ( ! nullableToDefinitelyNotNull ) { <EOL> return true <EOL> } <EOL> } <EOL> if ( supertype . isMarkedNullable || subtype . isMarkedNullable ) { <EOL> return isCastErased ( TypeUtils . makeNotNullable ( supertype ) , TypeUtils . makeNotNullable ( subtype ) , typeChecker ) <EOL> } <EOL> if ( isUpcast ) return false <EOL> if ( isNonReifiedTypeParameter ) return true <EOL> if ( allParametersReified ( subtype ) ) return false <EOL> val staticallyKnownSubtype = findStaticallyKnownSubtype ( supertype , subtype . constructor ) . resultingType ? : return true <EOL> return ! typeChecker . isSubtypeOf ( staticallyKnownSubtype , subtype ) <EOL> }

/**
 * Check if cast from supertype to subtype is erased.
 * It is an error in "is" statement and warning in "as".
 */


@ JvmStatic <EOL> fun findStaticallyKnownSubtype ( supertype : KotlinType , subtypeConstructor : TypeConstructor ) : TypeReconstructionResult

{ <EOL> assert ( ! supertype . isMarkedNullable ) { "<STR_LIT>" } <EOL> val descriptor = subtypeConstructor . declarationDescriptor ? : error ( "<STR_LIT>" + subtypeConstructor ) <EOL> val subtypeWithVariables = descriptor . defaultType <EOL> val supertypeWithVariables = TypeCheckingProcedure . findCorrespondingSupertype ( subtypeWithVariables , supertype ) <EOL> val variables = subtypeWithVariables . constructor . parameters <EOL> val variableConstructors = variables . map ( TypeParameterDescriptor :: getTypeConstructor ) . toSet ( ) <EOL> val substitution : MutableMap < TypeConstructor , TypeProjection > = if ( supertypeWithVariables != null ) { <EOL> val solution = TypeUnifier . unify ( TypeProjectionImpl ( supertype ) , TypeProjectionImpl ( supertypeWithVariables ) , variableConstructors :: contains ) <EOL> Maps . newHashMap ( solution . substitution ) <EOL> } else { <EOL> Maps . newHashMapWithExpectedSize < TypeConstructor , TypeProjection > ( variables . size ) <EOL> } <EOL> var allArgumentsInferred = true <EOL> for ( variable in variables ) { <EOL> val value = substitution [ variable . typeConstructor ] <EOL> if ( value == null ) { <EOL> substitution . put ( variable . typeConstructor , TypeUtils . makeStarProjection ( variable ) ) <EOL> allArgumentsInferred = false <EOL> } <EOL> } <EOL> val substituted = TypeSubstitutor . create ( substitution ) . substitute ( subtypeWithVariables , Variance . INVARIANT ) <EOL> return TypeReconstructionResult ( substituted , allArgumentsInferred ) <EOL> }

/**
 * Remember that we are trying to cast something of type `supertype` to `subtype`.

 * Since at runtime we can only check the class (type constructor), the rest of the subtype should be known statically, from supertype.
 * This method reconstructs all static information that can be obtained from supertype.

 * Example 1:
 * supertype = Collection
 * subtype = List<...>
 * result = List, all arguments are inferred

 * Example 2:
 * supertype = Any
 * subtype = List<...>
 * result = List<*>, some arguments were not inferred, replaced with '*'
 */


actual fun getTimesInMillis ( ) : String

= Date . now ( ) . toString ( )

/**
 * JS implementation of getTimeInMillis
 */


{ <EOL> TODO ( "<STR_LIT:notU+0020implemented>" ) <EOL> }


open fun nonReflectKind ( ) : FunctionTypeKind

{ <EOL> return if ( isReflectType ) error ( "<STR_LIT>" ) else this <EOL> }

/**
 * @return corresponding non-reflect kind for reflect kind
 * @return [this] if [isReflectType] is false
 *
 * Should be overridden for reflect kinds
 */


open fun reflectKind ( ) : FunctionTypeKind

{ <EOL> return if ( isReflectType ) this else error ( "<STR_LIT>" ) <EOL> }

/**
 * @return corresponding reflect kind for non-reflect kind
 * @return [this] if [isReflectType] is true
 *
 * Should be overridden for non reflect kinds
 */


private fun FirPropertySymbol . containingClassOrFile ( context : CheckerContext ) : FirBasedSymbol < * > ?

{ <EOL> return getContainingClassSymbol ( context . session ) <EOL> ? : context . session . firProvider . getFirCallableContainerFile ( this ) ? . symbol <EOL> }

/**
 * Returns the containing class or file if the property is top-level.
 */


abstract fun transformVariableAssignment ( variableAssignment : FirVariableAssignment ) : FirStatement ?

/**
 * At this point [variableAssignment] contains resolved and completed lhs and calleeReference(lvalue)
 * and unresolved rValue expression
 *
 * It's allowed to transform [variableAssignment] into any kind of statement. This state should be unresolved
 * (modulo usages of already resolved parts, like lValue). Later this statement will be resolved by compiler
 * itself using regular resolution algorithms
 */


public fun < T > color ( column : ColumnReference < T > , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Color > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Color >

{ <EOL> return addNonPositionalMapping < T , Color > ( COLOR , column . name ( ) , LetsPlotNonPositionalMappingParametersContinuous < T , Color > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `color` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > color ( column : KProperty < T > , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Color > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Color >

{ <EOL> return addNonPositionalMapping < T , Color > ( COLOR , column . name , LetsPlotNonPositionalMappingParametersContinuous < T , Color > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `color` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun color ( column : String , parameters : LetsPlotNonPositionalMappingParametersContinuous < Any ? , Color > . ( ) -> Unit = { } ) : NonPositionalMapping < Any ? , Color >

{ <EOL> return addNonPositionalMapping < Any ? , Color > ( COLOR , column , LetsPlotNonPositionalMappingParametersContinuous < Any ? , Color > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `color` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > color ( values : Iterable < T > , name : String ? = null , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Color > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Color >

{ <EOL> return addNonPositionalMapping < T , Color > ( COLOR , values . toList ( ) , name , LetsPlotNonPositionalMappingParametersContinuous < T , Color > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `color` aesthetic to iterable of discrete values.
 *
 * @param values the iterable containing the discrete values.
 * @param name optional name for this aesthetic mapping.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > color ( values : DataColumn < T > , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Color > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Color >

{ <EOL> return addNonPositionalMapping < T , Color > ( COLOR , values , LetsPlotNonPositionalMappingParametersContinuous < T , Color > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `color` aesthetic to a data column.
 *
 * @param values the data column to map to the color.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


private fun KtDotQualifiedExpression . fqNameSegments ( ) : List < String > ?

{ <EOL> val qualifiers = generateSequence ( this as KtExpression ) { ( it as? KtDotQualifiedExpression ) ? . receiverExpression } <EOL> . map { ( it as? KtDotQualifiedExpression ) ? . selectorExpression ? : it } <EOL> . toList ( ) <EOL> . asReversed ( ) <EOL> val qualifyingReferences = qualifiers . mapIndexed { index , qualifier -> <EOL> if ( qualifier is KtCallExpression && index != qualifiers . lastIndex ) return null <EOL> qualifier . referenceExpression ( ) as? KtNameReferenceExpression ? : return null <EOL> } <EOL> return qualifyingReferences . map { it . getReferencedName ( ) } <EOL> }

/**
 * Returns the segments of a qualified access PSI. For example, given `foo.bar.OuterClass.InnerClass`, this returns `["foo", "bar",
 * "OuterClass", "InnerClass"]`.
 */


private fun ClassId . dropLastNestedClasses ( classesToDrop : Int )

= <EOL> generateSequence ( this ) { it . outerClassId } . drop ( classesToDrop ) . firstOrNull ( )

/**
 * @return class id without [classesToDrop] last nested classes, or `null` if [classesToDrop] is too big.
 *
 * Example: `foo.bar.Baz.Inner` with 1 dropped class is `foo.bar.Baz`, and with 2 dropped class is `null`.
 */


private fun countQualifiersToDrop ( wholeType : KtUserType , nestedType : KtUserType ) : Int

{ <EOL> val qualifierIndex = generateSequence ( wholeType ) { it . qualifier } . indexOf ( nestedType ) <EOL> require ( qualifierIndex != - <NUM_LIT:1> ) { "<STR_LIT>" } <EOL> return qualifierIndex <EOL> }

/**
 * @return How many qualifiers needs to be dropped from [wholeType] to get [nestedType].
 *
 * Example: to get `foo.bar` from `foo.bar.Baz.Inner`, you need to drop 2 qualifiers (`Inner` and `Baz`).
 */


fun collectDiagnostics ( file : KtFile , filter : DiagnosticCheckerFilter ) : List < KtPsiDiagnostic >

/**
 * Returns all compiler diagnostics for the [file], matching the [filter].
 */


fun getDiagnostics ( element : KtElement , filter : DiagnosticCheckerFilter ) : List < KtPsiDiagnostic >

/**
 * Returns all compiler diagnostics for the specific [element], matching the [filter].
 * This function is not recursive; diagnostics for nested elements are not returned.
 */


fun < T : Number > median ( a : KtNDArray < T > ) : Double

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a ) , kClass = Double :: class )

/**
 * Compute the median along the specified axis.
 */


fun < T : Number > median ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , axis ) )


fun < T : Number > average ( a : KtNDArray < T > ) : Double

/**
 * Compute the weighted average along the specified axis.
 */


fun < T : Number > average ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Double >


fun < T : Number > mean ( a : KtNDArray < T > ) : Double

/**
 * Compute the arithmetic mean along the specified axis.
 */


fun < T : Number > mean ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Double >


fun < T : Number > std ( a : KtNDArray < T > , ddof : Int = <NUM_LIT:0> ) : Double

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , ddof ) , kClass = Double :: class )

/**
 * Compute the standard deviation along the specified axis.
 */


fun < T : Number > std ( a : KtNDArray < T > , axis : Int , ddof : Int = <NUM_LIT:0> ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , axis , ddof ) )


fun < T : Number > `var` ( a : KtNDArray < T > , ddof : Int = <NUM_LIT:0> ) : Double

/**
 * Compute the variance along the specified axis.
 */


fun < T : Number > `var` ( a : KtNDArray < T > , axis : Int , ddof : Int = <NUM_LIT:0> ) : KtNDArray < Double >


fun < T : Number > nanMedian ( a : KtNDArray < T > ) : Double

/**
 * Compute the median along the specified axis, while ignoring NaNs.
 */


fun < T : Number > nanMedian ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Double >


fun < T : Number > nanMean ( a : KtNDArray < T > ) : Double

/**
 * Compute the arithmetic mean along the specified axis, ignoring NaNs.
 */


fun < T : Number > nanMean ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Double >


fun < T : Number > nanStd ( a : KtNDArray < T > , ddof : Int = <NUM_LIT:0> ) : Double

/**
 * Compute the standard deviation along the specified axis, while ignoring NaNs.
 */


fun < T : Number > nanStd ( a : KtNDArray < T > , axis : Int , ddof : Int = <NUM_LIT:0> ) : KtNDArray < Double >


fun < T : Number > nanVar ( a : KtNDArray < T > , ddof : Int = <NUM_LIT:0> ) : Double

/**
 * Compute the variance along the specified axis, while ignoring NaNs.
 */


fun < T : Number > nanVar ( a : KtNDArray < T > , axis : Int , ddof : Int = <NUM_LIT:0> ) : KtNDArray < Double >


fun looksLikeReplCommand ( code : String ) : Boolean

= replCommandRegex . matches ( code )

/**
 * If this function returns true for the [code], it will be interpreted as Jupyter REPL command
 */


fun assertLooksLikeReplCommand ( code : String )

{ <EOL> require ( looksLikeReplCommand ( code ) ) { "<STR_LIT>" } <EOL> }

/**
 * Throws [IllegalArgumentException] in case [looksLikeReplCommand] returns false for [code]
 */


fun replCommandOrNull ( code : String ) : Pair < ReplCommand ? , String >

{ <EOL> assertLooksLikeReplCommand ( code ) <EOL> val match = replCommandRegex . matchEntire ( code ) ! ! <EOL> val commandString = match . groupValues [ <NUM_LIT:2> ] <EOL> return ReplCommand . valueOfOrNull ( commandString ) ? . value to commandString <EOL> }

/**
 * Preprocesses REPL command and returns its value,
 * or null in case it's invalid, packed with string used for value
 * extraction
 *
 * @param code Code snippet for which [looksLikeReplCommand] should return true
 * @return Command value or null in case it is not valid, packed with value used for value extraction
 */


@ DisplayName ( "<STR_LIT>" ) <EOL> @ GradleTest <EOL> fun testNoDeprecationOnAssociatedDep ( gradleVersion : GradleVersion )

{ <EOL> project ( "<STR_LIT>" , gradleVersion ) { <EOL> build ( "<STR_LIT>" ) <EOL> } <EOL> }


override fun toProtobufMessage ( ) : TestData . MessageWithOptionals

= <EOL> TestData . MessageWithOptionals . newBuilder ( ) . also { builder -> <EOL> if ( _a != null ) builder . a = _a <EOL> if ( _b != null ) builder . b = _b <EOL> if ( _c != null ) builder . c = _c . toProtoBuf ( ) <EOL> if ( _d != null ) builder . d = _d <EOL> if ( _e != null ) builder . addAllE ( _e ) <EOL> } . build ( )

/**
 * Convert this [Serializable] object to its expected [TestData.MessageWithOptionals] ProtoBuf message.
 *
 * For this test we expect that `null` values are not encoded.
 */


fun deserializeAndSave ( data : SerializedCompiledScriptsData , scriptsDir : Path , sourcesDir : Path , ) : List < String >

{ <EOL> val classNames = mutableListOf < String > ( ) <EOL> deserializeCompiledScripts ( data ) . forEach { ( script , bytes ) -> <EOL> val file = scriptsDir . resolve ( script . fileName ) . toFile ( ) <EOL> file . parentFile . mkdirs ( ) <EOL> if ( script . isImplicitReceiver ) { <EOL> classNames . add ( file . nameWithoutExtension ) <EOL> } <EOL> FileOutputStream ( file ) . use { fos -> <EOL> BufferedOutputStream ( fos ) . use { out -> <EOL> out . write ( bytes ) <EOL> out . flush ( ) <EOL> } <EOL> } <EOL> } <EOL> data . sources . forEach { scriptSource -> <EOL> val file = sourcesDir . resolve ( scriptSource . fileName ) . toFile ( ) <EOL> file . parentFile . mkdirs ( ) <EOL> file . writeText ( scriptSource . text ) <EOL> } <EOL> return classNames <EOL> }

/**
 * Deserializes [data] containing information about compiled scripts, saves
 * it to the [scriptsDir] directory, returns the list of names of classes
 * which are meant to be implicit receivers. Saves script sources to [sourcesDir].
 */


@ Test <EOL> fun testStringRepresentationWithConstants ( )

{ <EOL> val format = DateTimeComponents . Format { <EOL> date ( LocalDate . Formats . ISO ) <EOL> char ( '<CHAR_LIT:U+0020>' ) <EOL> time ( LocalTime . Formats . ISO ) <EOL> optional { <EOL> offset ( UtcOffset . Formats . ISO ) <EOL> } <EOL> } <EOL> val kotlinCode = DateTimeFormat . formatAsKotlinBuilderDsl ( format ) <EOL> assertEquals ( """<STR_LIT>""" . trimIndent ( ) , kotlinCode ) <EOL> }

/**
 * Tests printing of a format that embeds some constants.
 */


@ OptIn ( FormatStringsInDatetimeFormats :: class ) <EOL> @ Test <EOL> fun testStringRepresentationAfterIncorrectConversion ( )

{ <EOL> for ( format in listOf ( "<STR_LIT>" , "<STR_LIT>" ) ) { <EOL> assertContains ( DateTimeFormat . formatAsKotlinBuilderDsl ( DateTimeComponents . Format { byUnicodePattern ( format ) } ) , "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Check that we mention [byUnicodePattern] in the string representation of the format when the conversion is
 * incorrect.
 */


fun < R : Any , T : Any > copyto ( dst : KtNDArray < R > , src : KtNDArray < T > , casting : Casting = Casting . SAME_KIND ) : Unit

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( dst , src , casting . str ) , kClass = Unit :: class )

/**
 * Copies values from one array to another, broadcasting as necessary.
 *
 * Two arrays must be of the same type and match in size, otherwise raise ValueError.
 * @param dst the array into which values are copied.
 * @param src the array from which values are copied.
 * @param casting see [Casting].
 */


fun < T : Any > ravel ( a : KtNDArray < T > , order : Order = Order . C )

= a . ravel ( order )

/**
 * Return a contiguous flattened array.
 *
 * @param a input array [KtNDArray] of type [T].
 * @return view of an array.
 * @see KtNDArray.ravel
 */


fun < T : Any > moveAxis ( a : KtNDArray < T > , source : Int , destination : Int ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , source , destination ) )

/**
 * Move axis of an array to new positions.
 * Other axis remain in their original order.
 *
 * @param a input array [KtNDArray] of type [T]
 * @param source original positions of the axes to move. These must be unique.
 * @param destination destination positions for each of the original axes. These must be unique.
 * @return view of the input array.
 */


fun < T : Any > rollAxis ( a : KtNDArray < T > , axis : Int , start : Int = <NUM_LIT:0> ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , axis , start ) )

/**
 * Roll the specified axis backwards, until it lies in a given position.
 *
 * @param a - input array [KtNDArray] of type [T]
 * @param axis - the axis to roll backwards. The positions of the other axes do not change relative to one another.
 * @param start - the axis is rolled until it lies before this position. The default - 0.
 *
 * @return view of the input array.
 */


fun < T : Any > swapAxes ( a : KtNDArray < T > , axis1 : Int , axis2 : Int ) : KtNDArray < T >

= <EOL> a . swapAxes ( axis1 , axis2 )

/**
 * Interchange two axes of an array.
 *
 * @param a input array [KtNDArray] of type [T]
 * @param axis1 first axis.
 * @param axis2 second axis.
 * @return view of the input array.
 * @see KtNDArray.swapAxes
 */


fun < T : Any > transpose ( a : KtNDArray < T > , vararg axis : Int ? = emptyArray ( ) ) : KtNDArray < T >

= a . transpose ( * axis )

/**
 * Permute the dimensions of an array.
 *
 * @param a input array [KtNDArray] of type [T]
 * @param axis permute the axes according to the values given. By default, reverse dimensions.
 * @return view of input array.
 * @see KtNDArray.transpose
 */


fun atleast1D ( vararg arys : Any ) : List < KtNDArray < Any > >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( * arys ) , kClass = List :: class ) as List < KtNDArray < Any > >

/**
 * Inputs are converted to list 1-dim [KtNDArray].
 *
 * @param arys one or more input arrays.
 * @return [List] of [KtNDArray].
 * @see atleast2D
 * @see atleast3D
 */


fun atleast2D ( vararg arys : Any ) : List < KtNDArray < Any > >

/**
 * Inputs are converted to list 2-dim [KtNDArray].
 *
 * @param arys one or more input arrays.
 * @return [List] of [KtNDArray].
 * @see atleast1D
 * @see atleast3D
 */


fun atleast3D ( vararg arys : Any ) : List < KtNDArray < Any > >

/**
 * Inputs are converted to list 1-dim [KtNDArray].
 *
 * @param arys one or more input arrays.
 * @return [List] of [KtNDArray].
 * @see atleast1D
 * @see atleast2D
 */


inline fun < reified T : Any > asArray ( a : List < Any > , order : Order ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , T :: class . javaObjectType ) , order = order )

/**
 * Convert the input list to an [KtNDArray].
 *
 * @param a - [List] of type [T]
 * @param order [Order]. Default is 'C'.
 * @return The input will be returned uncopied iff it's a compatible.
 * @see asAnyArray
 * @see asContiguousArray
 * @see asFArray
 */


inline fun < reified T : Any > asAnyArray ( a : Array < out Any > , order : Order ? = null ) : KtNDArray < T >

/**
 * Convert the input [Array] to an [KtNDArray].
 *
 * @param a is [Array] of [Any].
 * @param order [Order]. Default is 'C'.
 * @return new [KtNDArray] of type [T].
 * @see asArray
 * @see asContiguousArray
 * @see asFArray
 */


inline fun < reified T : Any > asAnyArray ( a : List < Any > , order : Order ? = null ) : KtNDArray < T >

/**
 * Convert the input [List] to an [KtNDArray].
 *
 * @param a is [List] of [Any].
 * @param order [Order]. Default is 'C'.
 * @return new [KtNDArray] of type [T].
 * @see asArray
 * @see asContiguousArray
 * @see asFArray
 */


inline fun < reified T : Any > asAnyArray ( a : KtNDArray < out Any > , order : Order ? = null ) : KtNDArray < T >

/**
 * Convert the input [KtNDArray] to an [KtNDArray] of type [T].
 *
 * @param a is [KtNDArray] of [Any].
 * @param order [Order]. Default is 'C'.
 * @return new [KtNDArray] of type [T].
 * @see asArray
 * @see asContiguousArray
 * @see asFArray
 */


inline fun < reified T : Any > asContiguousArray ( a : KtNDArray < out Any > ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , T :: class . javaObjectType ) )

/**
 * Return a contiguous array.
 *
 * @param a input array.
 * @return contiguous [KtNDArray].
 */


fun < T : Any > asFArray ( a : KtNDArray < T > ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a ) )

/**
 * Return an array converted to a float type.
 *
 * @param a [KtNDArray] of type [T].
 * @return new [KtNDArray] of type [Double]
 */


fun < T : Any > concatenate ( vararg arrs : KtNDArray < T > , axis : Int = <NUM_LIT:0> ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( arrs , axis ) )

/**
 * Join a sequence of arrays along an existing axis.
 *
 * @param arrs the input arrays.
 * The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default).
 * @param axis the axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.
 * @return new concatenated array.
 */


fun < T : Any > stack ( vararg arrs : KtNDArray < T > , axis : Int = <NUM_LIT:0> ) : KtNDArray < T >

/**
 * Join a sequence of arrays along a new axis.
 *
 * @param arrs the input arrays. Each array must have the same shape.
 * @param axis the axis in the result array along which the input arrays are stacked. Default is 0.
 * @return new [KtNDArray]. The stacked array has one more dimension than the input arrays.
 */


fun < T : Any > columnStack ( vararg tup : KtNDArray < T > ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( tup ) )

/**
 * Stack 1-D arrays as columns into a 2-D array.
 *
 * @param tup arrays to stack. All of them must have the same first dimension.
 * @return 2D array. The array formed by stacking the given arrays.
 */


fun < T : Any > dstack ( vararg tup : KtNDArray < T > ) : KtNDArray < T >

/**
 * Stack arrays in sequence depth wise (along third axis).
 *
 * @param tup the arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.
 * @return The array formed by stacking the given arrays, will be at least 3-D.
 * @see stack
 * @see vstack
 * @see hstack
 * @see concatenate
 */


fun < T : Any > hstack ( vararg tup : KtNDArray < T > ) : KtNDArray < T >

/**
 * Stack arrays in sequence horizontally (column wise).
 *
 * @param tup the arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.
 * @return The array formed by stacking the given arrays.
 */


fun < T : Any > vstack ( vararg tup : KtNDArray < T > ) : KtNDArray < T >

/**
 * Stack arrays in sequence vertically (row wise).
 *
 * @param tup the arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.
 * @return The array formed by stacking the given arrays, will be at least 2-D.
 */


fun < T : Any > block ( list : List < KtNDArray < T > > ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( list ) )

/**
 * Assemble an [KtNDArray] from nested lists of blocks.
 *
 * @param list nested [List] of [KtNDArray].
 * @return [KtNDArray].
 * @see concatenate
 * @see stack
 * @see hstack
 * @see vstack
 * @see dstack
 */


fun < T : Any > hsplit ( arr : KtNDArray < T > , idx : Int ) : List < KtNDArray < T > >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( arr , idx ) , kClass = List :: class ) as List < KtNDArray < T > >

/**
 * Split an array into multiple sub-arrays horizontally (column-wise).
 *
 * [hsplit] is equivalent to [split] with axis=1.
 *
 * @param arr input data.
 * @param idx indices of sections.
 * @see split
 */


fun < T : Any > tile ( a : KtNDArray < T > , reps : Int ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , reps ) )

/**
 * Construct an array by repeating [a] the number of times given by reps.
 *
 * @param a input array.
 * @param reps the number of repetitions array along each axis.
 * @return the tiled output array (view).
 */


fun < T : Any > tile ( a : KtNDArray < T > , reps : IntArray ) : KtNDArray < T >


fun < T : Any > repeat ( a : KtNDArray < T > , reps : Int , axis : Int ? = null ) : KtNDArray < T >

= a . repeat ( reps , axis )

/**
 * Repeat elements of an array.
 *
 * @param a input array.
 * @param reps the number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.
 * @param axis the axis along which to repeat values. By default, use the flattened input array, and return a flat output array.
 * @return output array which has the same shape as [a], except along the given axis.
 */


fun < T : Any > repeat ( a : KtNDArray < T > , reps : IntArray , axis : Int ? = null ) : KtNDArray < T >

= a . repeat ( reps , axis )

/**
 * Repeat elements of an array.
 *
 * @param a input array.
 * @param reps the list number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.
 * @param axis the axis along which to repeat values. By default, use the flattened input array, and return a flat output array.
 * @return output array which has the same shape as [a], except along the given axis.
 */


fun < T : Any > delete ( arr : KtNDArray < T > , obj : Int , axis : Int ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( arr , obj , axis ? : None . none ) )

/**
 * Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr.get(obj).
 *
 * @param arr input array.
 * @param obj index.
 * @param axis The axis along which to delete the subarray defined by obj. If axis is null, obj is applied to the flattened array.
 * @return A copy of [arr] with the elements specified by [obj] removed. Note that [delete] does not occur in-place.
 * If [axis] is null, return is a flattened array.
 */


fun < T : Any > delete ( arr : KtNDArray < T > , obj : IntArray , axis : Int ? = null ) : KtNDArray < T >


fun < T : Any > delete ( arr : KtNDArray < T > , obj : Array < Slice > , axis : Int ? = null ) : KtNDArray < T >


fun < T : Any > insert ( arr : KtNDArray < T > , obj : Int , values : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( arr , obj , values , axis ? : None . none ) )

/**
 * Insert values along the given axis before the given indices.
 *
 * @param arr input array
 * @param obj object that defines the index before which [values] is inserted.
 * @param values values to insert into [arr].
 * @param axis axis along which to insert [values]. If axis is null then [arr] is flattened first.
 *
 * @return A copy of [arr] with [values] inserted. Note that insert does not occur in-place: a new array is returned.
 * If [axis] is null, return is a flattened array.
 */


fun < T : Any > insert ( arr : KtNDArray < T > , obj : IntArray , values : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >


fun < T : Any > insert ( arr : KtNDArray < T > , obj : Array < Slice > , values : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >


fun < T : Any > append ( arr : KtNDArray < T > , values : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( arr , values , axis ? : None . none ) )

/**
 * Append values to the end of an array.
 *
 * @param arr input array.
 * @param values these values are appended to a copy of [arr]. It must be of the same shape as arr, excluding [axis].
 * If axis is not specified, [values] can be any shape and will be flattened before use.
 * @param axis the axis along which [values] are appended.
 * If [axis] is not given, both [arr] and [values] are flattened before use.
 * @return A copy of [arr] with [values] appended to [axis].
 * Note that append does not occur in-place: a new array is allocated and filled.
 * If [axis] is null, return is a flattened array.
 */


fun < T : Any > resize ( a : KtNDArray < T > , vararg newshape : Int ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , newshape ) )

/**
 * Return a new array with the specified shape.
 *
 * @param a array to be resized.
 * @param newshape shape of resized array.
 * @return The new [KtNDArray] is formed from the data in the old array and new shape.
 * @see KtNDArray.resize
 */


fun < T : Any > trimZeros ( filt : KtNDArray < T > , trim : String = "<STR_LIT>" ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( filt , trim ) )

/**
 * Trim the leading and/or trailing zeros from a 1-D array or sequence.
 *
 * @param filt 1-D input array.
 * @param trim a string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb'.
 * @return The result of trimming the input.
 */