fun Project . createGradleCommonSourceSet ( ) : SourceSet

{ <EOL> val commonSourceSet = sourceSets . create ( commonSourceSetName ) { <EOL> excludeGradleCommonDependencies ( this ) <EOL> val commonGradleApiConfiguration = configurations . create ( "<STR_LIT>" ) { <EOL> isVisible = false <EOL> isCanBeConsumed = false <EOL> isCanBeResolved = true <EOL> } <EOL> configurations [ compileClasspathConfigurationName ] . extendsFrom ( commonGradleApiConfiguration ) <EOL> dependencies { <EOL> compileOnlyConfigurationName ( kotlinStdlib ( ) ) <EOL> "<STR_LIT>" ( "<STR_LIT>" ) <EOL> if ( this @ createGradleCommonSourceSet . name !in testPlugins ) { <EOL> compileOnlyConfigurationName ( project ( "<STR_LIT>" ) ) { <EOL> capabilities { <EOL> requireCapability ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> plugins . withType < JavaLibraryPlugin > ( ) . configureEach { <EOL> this@createGradleCommonSourceSet . extensions . configure < JavaPluginExtension > { <EOL> registerFeature ( commonSourceSet . name ) { <EOL> usingSourceSet ( commonSourceSet ) <EOL> disablePublication ( ) <EOL> } <EOL> } <EOL> } <EOL> tasks . named < KotlinJvmCompile > ( "<STR_LIT>" ) { <EOL> compilerOptions . moduleName . set ( "<STR_LIT>" ) <EOL> } <EOL> registerValidatePluginTasks ( commonSourceSet ) <EOL> return commonSourceSet <EOL> }

/**
 * Common sources for all variants.
 * Should contain classes that are independent of Gradle API version or using minimal supported Gradle api.
 */


private fun Project . fixWiredSourceSetSecondaryVariants ( wireSourceSet : SourceSet , commonSourceSet : SourceSet , )

{ <EOL> configurations <EOL> . matching { <EOL> it . name == wireSourceSet . apiElementsConfigurationName || <EOL> it . name == wireSourceSet . runtimeElementsConfigurationName <EOL> } <EOL> . configureEach { <EOL> outgoing { <EOL> variants . maybeCreate ( "<STR_LIT>" ) . apply { <EOL> attributes { <EOL> attribute ( LibraryElements . LIBRARY_ELEMENTS_ATTRIBUTE , objects . named ( LibraryElements . CLASSES ) ) <EOL> } <EOL> ( commonSourceSet . output . classesDirs . files + wireSourceSet . output . classesDirs . files ) <EOL> . toSet ( ) <EOL> . forEach { <EOL> if ( ! artifacts . files . contains ( it ) ) { <EOL> artifact ( it ) { <EOL> type = ArtifactTypeDefinition . JVM_CLASS_DIRECTORY <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> configurations <EOL> . matching { it . name == wireSourceSet . runtimeElementsConfigurationName } <EOL> . configureEach { <EOL> outgoing { <EOL> val resourcesDirectories = listOfNotNull ( commonSourceSet . output . resourcesDir , wireSourceSet . output . resourcesDir ) <EOL> if ( resourcesDirectories . isNotEmpty ( ) ) { <EOL> variants . maybeCreate ( "<STR_LIT>" ) . apply { <EOL> attributes { <EOL> attribute ( LibraryElements . LIBRARY_ELEMENTS_ATTRIBUTE , objects . named ( LibraryElements . RESOURCES ) ) <EOL> } <EOL> resourcesDirectories . forEach { <EOL> if ( ! artifacts . files . contains ( it ) ) { <EOL> artifact ( it ) { <EOL> type = ArtifactTypeDefinition . JVM_RESOURCES_DIRECTORY <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Fixes wired SourceSet does not expose compiled common classes and common resources as secondary variant
 * which is used in the Kotlin Project compilation.
 */


fun Project . wireGradleVariantToCommonGradleVariant ( wireSourceSet : SourceSet , commonSourceSet : SourceSet , )

{ <EOL> wireSourceSet . compileClasspath += commonSourceSet . output <EOL> wireSourceSet . runtimeClasspath += commonSourceSet . output <EOL> ( extensions . getByName ( "<STR_LIT:kotlin>" ) as KotlinSingleJavaTargetExtension ) . target . compilations . run { <EOL> getByName ( wireSourceSet . name ) . associateWith ( getByName ( commonSourceSet . name ) ) <EOL> } <EOL> configurations [ wireSourceSet . apiConfigurationName ] . extendsFrom ( configurations [ commonSourceSet . apiConfigurationName ] ) <EOL> configurations [ wireSourceSet . implementationConfigurationName ] . extendsFrom ( configurations [ commonSourceSet . implementationConfigurationName ] ) <EOL> configurations [ wireSourceSet . runtimeOnlyConfigurationName ] . extendsFrom ( configurations [ commonSourceSet . runtimeOnlyConfigurationName ] ) <EOL> configurations [ wireSourceSet . compileOnlyConfigurationName ] . extendsFrom ( configurations [ commonSourceSet . compileOnlyConfigurationName ] ) <EOL> fixWiredSourceSetSecondaryVariants ( wireSourceSet , commonSourceSet ) <EOL> tasks . withType < Jar > ( ) . configureEach { <EOL> if ( name == wireSourceSet . jarTaskName ) { <EOL> from ( wireSourceSet . output , commonSourceSet . output ) <EOL> setupPublicJar ( archiveBaseName . get ( ) ) <EOL> addEmbeddedRuntime ( ) <EOL> addEmbeddedRuntime ( wireSourceSet . embeddedConfigurationName ) <EOL> } else if ( name == wireSourceSet . sourcesJarTaskName ) { <EOL> from ( wireSourceSet . allSource , commonSourceSet . allSource ) <EOL> } <EOL> } <EOL> }

/**
 * Make [wireSourceSet] to extend [commonSourceSet].
 */


fun Project . reconfigureMainSourcesSetForGradlePlugin ( commonSourceSet : SourceSet , )

{ <EOL> sourceSets . named ( SourceSet . MAIN_SOURCE_SET_NAME ) { <EOL> plugins . withType < JavaGradlePluginPlugin > ( ) . configureEach { <EOL> configurations [ apiConfigurationName ] . dependencies . remove ( dependencies . gradleApi ( ) ) <EOL> } <EOL> dependencies { <EOL> "<STR_LIT>" ( kotlinStdlib ( ) ) <EOL> "<STR_LIT>" ( "<STR_LIT>" ) <EOL> if ( this @ reconfigureMainSourcesSetForGradlePlugin . name !in testPlugins ) { <EOL> "<STR_LIT>" ( project ( "<STR_LIT>" ) ) <EOL> } <EOL> } <EOL> excludeGradleCommonDependencies ( this ) <EOL> wireGradleVariantToCommonGradleVariant ( this , commonSourceSet ) <EOL> if ( configurations [ "<STR_LIT:default>" ] . attributes . contains ( TargetJvmEnvironment . TARGET_JVM_ENVIRONMENT_ATTRIBUTE ) ) { <EOL> configurations [ "<STR_LIT:default>" ] . attributes . attribute ( TargetJvmEnvironment . TARGET_JVM_ENVIRONMENT_ATTRIBUTE , objects . named ( TargetJvmEnvironment :: class , "<STR_LIT>" ) ) <EOL> } <EOL> plugins . withType < JavaLibraryPlugin > ( ) . configureEach { <EOL> this@reconfigureMainSourcesSetForGradlePlugin <EOL> . extensions <EOL> . configure < JavaPluginExtension > { <EOL> withSourcesJar ( ) <EOL> if ( kotlinBuildProperties . publishGradlePluginsJavadoc ) { <EOL> withJavadocJar ( ) <EOL> } <EOL> } <EOL> configurations . create ( sourceSets . getByName ( "<STR_LIT:main>" ) . embeddedConfigurationName ) { <EOL> isCanBeConsumed = false <EOL> isCanBeResolved = true <EOL> attributes { <EOL> attribute ( Usage . USAGE_ATTRIBUTE , objects . named ( Usage . JAVA_RUNTIME ) ) <EOL> attribute ( LibraryElements . LIBRARY_ELEMENTS_ATTRIBUTE , objects . named ( LibraryElements . JAR ) ) <EOL> } <EOL> } <EOL> } <EOL> val javaComponent = project . components [ "<STR_LIT:java>" ] as AdhocComponentWithVariants <EOL> listOf ( runtimeElementsConfigurationName , apiElementsConfigurationName ) <EOL> . map { configurations [ it ] } <EOL> . forEach { originalConfiguration -> <EOL> configurations . create ( "<STR_LIT>" ) { <EOL> isCanBeResolved = originalConfiguration . isCanBeResolved <EOL> isCanBeConsumed = originalConfiguration . isCanBeConsumed <EOL> isVisible = originalConfiguration . isVisible <EOL> setExtendsFrom ( originalConfiguration . extendsFrom ) <EOL> artifacts { <EOL> originalConfiguration . artifacts . forEach { <EOL> add ( name , it ) <EOL> } <EOL> } <EOL> attributes { <EOL> originalConfiguration . attributes . keySet ( ) <EOL> . filter { it . name != KotlinPlatformType . attribute . name } <EOL> . forEach { originalAttribute -> <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> attribute ( originalAttribute as Attribute < Any > , originalConfiguration . attributes . getAttribute ( originalAttribute ) ! ! <EOL> ) <EOL> } <EOL> plugins . withType < JavaPlugin > { <EOL> tasks . named < JavaCompile > ( compileJavaTaskName ) . get ( ) . apply { <EOL> attribute ( TargetJvmVersion . TARGET_JVM_VERSION_ATTRIBUTE , when ( targetCompatibility ) { <EOL> "<STR_LIT:1.8>" -> <NUM_LIT:8> <EOL> else -> targetCompatibility . toInt ( ) <EOL> } ) <EOL> } <EOL> } <EOL> } <EOL> val expectedAttributes = setOf ( Category . CATEGORY_ATTRIBUTE , Bundling . BUNDLING_ATTRIBUTE , Usage . USAGE_ATTRIBUTE , LibraryElements . LIBRARY_ELEMENTS_ATTRIBUTE , TargetJvmEnvironment . TARGET_JVM_ENVIRONMENT_ATTRIBUTE , TargetJvmVersion . TARGET_JVM_VERSION_ATTRIBUTE ) <EOL> if ( attributes . keySet ( ) != expectedAttributes ) { <EOL> error ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) <EOL> } <EOL> javaComponent . addVariantsFromConfiguration ( this ) { <EOL> mapToMavenScope ( when ( originalConfiguration . name ) { <EOL> runtimeElementsConfigurationName -> "<STR_LIT>" <EOL> apiElementsConfigurationName -> "<STR_LIT>" <EOL> else -> error ( "<STR_LIT>" ) <EOL> } ) <EOL> } <EOL> originalConfiguration . isCanBeConsumed = false <EOL> originalConfiguration . isVisible = false <EOL> javaComponent . withVariantsFromConfiguration ( originalConfiguration ) { <EOL> skip ( ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> sourceSets . named ( SourceSet . TEST_SOURCE_SET_NAME ) { <EOL> compileClasspath += commonSourceSet . output <EOL> runtimeClasspath += commonSourceSet . output <EOL> } <EOL> ( extensions . getByName ( "<STR_LIT:kotlin>" ) as KotlinSingleJavaTargetExtension ) . target . compilations . run { <EOL> getByName ( SourceSet . TEST_SOURCE_SET_NAME ) . associateWith ( getByName ( commonSourceSet . name ) ) <EOL> } <EOL> }

/**
 * 'main' sources are used for minimal supported Gradle versions (6.7) up to Gradle 7.0.
 */


fun Project . createGradlePluginVariant ( variant : GradlePluginVariant , commonSourceSet : SourceSet , isGradlePlugin : Boolean = true , ) : SourceSet

{ <EOL> val variantSourceSet = sourceSets . create ( variant . sourceSetName ) { <EOL> excludeGradleCommonDependencies ( this ) <EOL> wireGradleVariantToCommonGradleVariant ( this , commonSourceSet ) <EOL> } <EOL> plugins . withType < JavaLibraryPlugin > ( ) . configureEach { <EOL> extensions . configure < JavaPluginExtension > { <EOL> registerFeature ( variantSourceSet . name ) { <EOL> usingSourceSet ( variantSourceSet ) <EOL> if ( isGradlePlugin ) { <EOL> capability ( project . group . toString ( ) , project . name , project . version . toString ( ) ) <EOL> } <EOL> if ( kotlinBuildProperties . publishGradlePluginsJavadoc ) { <EOL> withJavadocJar ( ) <EOL> } <EOL> withSourcesJar ( ) <EOL> } <EOL> configurations . named ( variantSourceSet . apiElementsConfigurationName , commonVariantAttributes ( ) ) <EOL> configurations . named ( variantSourceSet . runtimeElementsConfigurationName , commonVariantAttributes ( ) ) <EOL> configurations . create ( variantSourceSet . embeddedConfigurationName ) { <EOL> isCanBeConsumed = false <EOL> isCanBeResolved = true <EOL> attributes { <EOL> attribute ( Usage . USAGE_ATTRIBUTE , objects . named ( Usage . JAVA_RUNTIME ) ) <EOL> attribute ( LibraryElements . LIBRARY_ELEMENTS_ATTRIBUTE , objects . named ( LibraryElements . JAR ) ) <EOL> } <EOL> } <EOL> } <EOL> tasks . named < Jar > ( variantSourceSet . sourcesJarTaskName ) { <EOL> addEmbeddedSources ( ) <EOL> addEmbeddedSources ( variantSourceSet . embeddedConfigurationName ) <EOL> } <EOL> } <EOL> plugins . withId ( "<STR_LIT>" ) { <EOL> tasks . named < Copy > ( variantSourceSet . processResourcesTaskName ) { <EOL> val copyPluginDescriptors = rootSpec . addChild ( ) <EOL> copyPluginDescriptors . into ( "<STR_LIT>" ) <EOL> copyPluginDescriptors . from ( tasks . named ( "<STR_LIT>" ) ) <EOL> } <EOL> } <EOL> configurations . configureEach { <EOL> if ( this @ configureEach . name . startsWith ( variantSourceSet . name ) && ( isCanBeResolved || isCanBeConsumed ) ) { <EOL> attributes { <EOL> attribute ( GradlePluginApiVersion . GRADLE_PLUGIN_API_VERSION_ATTRIBUTE , objects . named ( variant . minimalSupportedGradleVersion ) ) <EOL> } <EOL> } <EOL> } <EOL> tasks . named < KotlinJvmCompile > ( "<STR_LIT>" ) { <EOL> compilerOptions . moduleName . set ( this @ createGradlePluginVariant . name ) <EOL> } <EOL> dependencies { <EOL> variantSourceSet . compileOnlyConfigurationName ( kotlinStdlib ( ) ) <EOL> variantSourceSet . compileOnlyConfigurationName ( "<STR_LIT>" ) <EOL> if ( this @ createGradlePluginVariant . name !in testPlugins ) { <EOL> variantSourceSet . apiConfigurationName ( project ( "<STR_LIT>" ) ) { <EOL> capabilities { <EOL> requireCapability ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> registerValidatePluginTasks ( variantSourceSet ) <EOL> return variantSourceSet <EOL> }

/**
 * Adding plugin variants: https://docs.gradle.org/current/userguide/implementing_gradle_plugins.html#plugin-with-variants
 */


private fun Project . commonVariantAttributes ( ) : Action < Configuration >

= Action < Configuration > { <EOL> attributes { <EOL> attribute ( TargetJvmEnvironment . TARGET_JVM_ENVIRONMENT_ATTRIBUTE , objects . named ( TargetJvmEnvironment . STANDARD_JVM ) ) <EOL> } <EOL> }

/**
 * All additional configuration attributes in plugin variant should be the same as in the 'main' variant.
 * Otherwise, Gradle <7.0 will fail to select plugin variant.
 */


fun report ( whenExpressionFilePath : String , enumClassFqName : String )

/**
 * Report Java enum class, which FqName is [enumClassFqName].
 * This enum class is used in Kotlin file with [whenExpressionFilePath] path in when expression.
 * Format of [enumClassFqName] class is "package.Outer$Inner"
 */


fun reference ( classifier : Classifier ) : String

/**
 * @return the string to be used to reference the classifier in current scope.
 */


fun declare ( classifier : Classifier ) : String

/**
 * @return the string to be used as a name in the declaration of the classifier in current scope.
 */


fun declareProperty ( receiver : String ? , name : String ) : String ?

/**
 * @return the string to be used as a name in the declaration of the property in current scope,
 * or `null` if the property with given name can't be declared.
 */


fun render ( scope : KotlinScope ) : String

/**
 * @return the string to be used in the given scope to denote this.
 */


@ Test <EOL> fun testCrossModule_ComposableInterfaceFunctionWithInlineClasses ( )

{ <EOL> compile ( mapOf ( "<STR_LIT>" to mapOf ( "<STR_LIT>" to """<STR_LIT>""" . trimIndent ( ) ) , "<STR_LIT>" to mapOf ( "<STR_LIT>" to """<STR_LIT>""" . trimIndent ( ) ) ) ) <EOL> }


@ Test <EOL> fun testOverriddenSymbolParentsInDefaultParameters ( )

{ <EOL> compile ( mapOf ( "<STR_LIT>" to mapOf ( "<STR_LIT>" to """<STR_LIT>""" ) , "<STR_LIT>" to mapOf ( "<STR_LIT>" to """<STR_LIT>""" ) ) ) <EOL> }


public operator fun < C > ColumnReference < C > . invoke ( ) : DataColumn < C >

= get ( this )

/**
 * @include [CommonColumnReferenceInvokeDocs]
 * @return The [DataColumn] this [Column Reference][ColumnReference] or [-Accessor][ColumnAccessor] points to.
 */


public operator fun < T > ColumnReference < DataRow < T > > . invoke ( ) : ColumnGroup < T >

= get ( this )

/**
 * @include [CommonColumnReferenceInvokeDocs]
 * @return The [ColumnGroup] this [Column Reference][ColumnReference] or [-Accessor][ColumnAccessor] points to.
 */


public operator fun < T > ColumnReference < DataFrame < T > > . invoke ( ) : FrameColumn < T >

= get ( this )

/**
 * @include [CommonColumnReferenceInvokeDocs]
 * @return The [FrameColumn] this [Column Reference][ColumnReference] or [-Accessor][ColumnAccessor] points to.
 */


public operator fun < C > ColumnPath . invoke ( ) : DataColumn < C >

= getColumn ( this ) . cast ( )

/**
 * Retrieves the value of this [ColumnPath] from the [DataFrame].
 * This is a shorthand for [getColumn][ColumnsContainer.getColumn]`(myColumnPath)` and
 * is most often used in combination with `operator fun String.get(column: String)`, {@comment cannot point to the right function.}
 * for instance:
 * ```kotlin
 * "myColumn"["myNestedColumn"]<NestedColumnType>()
 * ```
 *
 * @throws [IllegalArgumentException] if the column is not found.
 * @return The [DataColumn] this [ColumnPath] points to.
 */


public operator fun < T > KProperty < T > . invoke ( ) : DataColumn < T >

= this@ColumnSelectionDsl [ this ]

/**
 * @include [CommonKPropertyInvokeDocs]
 * @return The [DataColumn] this [KProperty Accessor][KProperty] points to.
 */


public operator fun < T > KProperty < DataRow < T > > . invoke ( ) : ColumnGroup < T >

= this@ColumnSelectionDsl [ this ]

/**
 * @include [CommonKPropertyInvokeDocs]
 * @return The [ColumnGroup] this [KProperty Accessor][KProperty] points to.
 */


public operator fun < T > KProperty < DataFrame < T > > . invoke ( ) : FrameColumn < T >

= this@ColumnSelectionDsl [ this ]

/**
 * @include [CommonKPropertyInvokeDocs]
 * @return The [FrameColumn] this [KProperty Accessor][KProperty] points to.
 */


@ Suppress ( "<STR_LIT:INAPPLICABLE_JVM_NAME>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public operator fun < T , R > KProperty < DataRow < T > > . get ( column : KProperty < R > ) : DataColumn < R >

= invoke ( ) [ column ]

/**
 * @include [CommonKPropertyGetDocs]
 * @return The [DataColumn] these [KProperty Accessors][KProperty] point to.
 */


@ Suppress ( "<STR_LIT:INAPPLICABLE_JVM_NAME>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public operator fun < T , R > KProperty < DataRow < T > > . get ( column : KProperty < DataRow < R > > ) : ColumnGroup < R >

= <EOL> invoke ( ) [ column ]

/**
 * @include [CommonKPropertyGetDocs]
 * @return The [ColumnGroup] these [KProperty Accessors][KProperty] point to.
 */


@ Suppress ( "<STR_LIT:INAPPLICABLE_JVM_NAME>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public operator fun < T , R > KProperty < DataRow < T > > . get ( column : KProperty < DataFrame < R > > ) : FrameColumn < R >

= <EOL> invoke ( ) [ column ]

/**
 * @include [CommonKPropertyGetDocs]
 * @return The [FrameColumn] these [KProperty Accessors][KProperty] point to.
 */


public operator fun < T , R > KProperty < T > . get ( column : KProperty < R > ) : DataColumn < R >

= invoke ( ) . asColumnGroup ( ) [ column ]


public operator fun < T , R > KProperty < T > . get ( column : KProperty < DataRow < R > > ) : ColumnGroup < R >

= <EOL> invoke ( ) . asColumnGroup ( ) [ column ]


public operator fun < T , R > KProperty < T > . get ( column : KProperty < DataFrame < R > > ) : FrameColumn < R >


@ Suppress ( "<STR_LIT:INAPPLICABLE_JVM_NAME>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public operator fun < C > String . invoke ( ) : DataColumn < C >

= getColumn ( this ) . cast ( )

/**
 * Retrieves the value of the column with this name from the [DataFrame]. This can be
 * both typed and untyped.
 * This is a shorthand for [get][ColumnsContainer.get]`("myColumnName")` and can be
 * written as `"myColumnName"<MyColumnType>()` instead.
 *
 * @throws [IllegalArgumentException] if there is no column with this name.
 * @return The [DataColumn] with this name.
 */


@ Suppress ( "<STR_LIT:INAPPLICABLE_JVM_NAME>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public operator fun String . invoke ( ) : DataColumn < * >

= getColumn ( this )

/**
 * Retrieves the value of the column with this name from the [DataFrame]. This can be
 * both typed and untyped.
 * This is a shorthand for [get][ColumnsContainer.get]`("myColumnName")` and can be
 * written as `"myColumnName"()` instead.
 *
 * @throws [IllegalArgumentException] if there is no column with this name.
 * @return The [DataColumn] with this name.
 */


public operator fun String . get ( column : String ) : ColumnPath

= pathOf ( this , column )

/**
 * Creates a [ColumnPath] from the receiver and the given column name [column].
 * This is a shorthand for [pathOf]`("myColumnName", "myNestedColumnName")` and is often used
 * in combination with [ColumnPath.invoke] to retrieve the value of a nested column.
 * For instance:
 * ```kotlin
 * "myColumn"["myNestedColumn"]<NestedColumnType>()
 *
 * "myColumn"["myNestedColumn"]["myDoublyNestedColumn"]<NestedColumnType>()
 * ```
 */


public operator fun ColumnPath . get ( column : String ) : ColumnPath

= this + column

/**
 * As extension to `"myColumn"["myNestedColumn"]`, this function enables
 * `"myColumn"["myNestedColumn"]["myDoublyNestedColumn"]` as alternative to
 * [pathOf]`("myColumn", "myNestedColumn", "myDoublyNestedColumn")`
 */


internal fun List < Layer > . variables ( ) : List < KVariable >

{ <EOL> return filterIsInstance < ParametrizedLayer > ( ) . flatMap { it . variables } <EOL> }

/**
 * Returns all variables used in all layers.
 */


internal fun List < Layer > . trainableVariables ( ) : List < KVariable >

{ <EOL> return filterIsInstance < TrainableLayer > ( ) . filter { it . isTrainable } . flatMap { it . variables } <EOL> }

/**
 * Returns a list of trainable variables used in the layers.
 */


internal fun List < Layer > . frozenVariables ( ) : List < KVariable >

{ <EOL> return filterIsInstance < ParametrizedLayer > ( ) <EOL> . filter { it !is TrainableLayer || ! it . isTrainable } <EOL> . flatMap { it . variables } <EOL> }

/**
 * Returns a list of non-trainable, 'frozen' variables used in the layers.
 */


public fun ParametrizedLayer . initialize ( session : Session )

{ <EOL> variables . map { it . initializerOperation } . init ( session ) <EOL> }

/**
 * Initializes this layers variables using provided initializer operands.
 */


public fun List < Layer > . initializeVariables ( session : Session )

{ <EOL> filterIsInstance < ParametrizedLayer > ( ) . forEach { it . initialize ( session ) } <EOL> }

/**
 * Initializes variables for [ParametrizedLayer] instances using provided initializer operands.
 */


abstract fun computeSealedSubclasses ( sealedClass : ClassDescriptor , allowSealedInheritorsInDifferentFilesOfSamePackage : Boolean ) : Collection < ClassDescriptor >

/**
 * This method may be called by compiler only for classes/interfaces with sealed modality
 */


@ HtmlTagMarker <EOL> inline fun FlowContent . address ( classes : String ? = null , crossinline block : ADDRESS . ( ) -> Unit = { } ) : Unit

= ADDRESS ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . blockQuote ( classes : String ? = null , crossinline block : BLOCKQUOTE . ( ) -> Unit = { } ) : Unit

= BLOCKQUOTE ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . dialog ( classes : String ? = null , crossinline block : DIALOG . ( ) -> Unit = { } ) : Unit

= DIALOG ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . div ( classes : String ? = null , crossinline block : DIV . ( ) -> Unit = { } ) : Unit

= DIV ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )

/**
 * Generic language/style container
 */


@ HtmlTagMarker <EOL> inline fun FlowContent . dl ( classes : String ? = null , crossinline block : DL . ( ) -> Unit = { } ) : Unit

= DL ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . fieldSet ( classes : String ? = null , crossinline block : FIELDSET . ( ) -> Unit = { } ) : Unit

= FIELDSET ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . figure ( classes : String ? = null , crossinline block : FIGURE . ( ) -> Unit = { } ) : Unit

= FIGURE ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . figcaption ( classes : String ? = null , crossinline block : FIGCAPTION . ( ) -> Unit = { } ) : Unit

= FIGCAPTION ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . footer ( classes : String ? = null , crossinline block : FOOTER . ( ) -> Unit = { } ) : Unit

= FOOTER ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . form ( action : String ? = null , encType : FormEncType ? = null , method : FormMethod ? = null , classes : String ? = null , crossinline block : FORM . ( ) -> Unit = { } ) : Unit

= FORM ( attributesMapOf ( "<STR_LIT>" , action , "<STR_LIT>" , encType ? . enumEncode ( ) , "<STR_LIT>" , method ? . enumEncode ( ) , "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . header ( classes : String ? = null , crossinline block : HEADER . ( ) -> Unit = { } ) : Unit

= HEADER ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )

/**
 * Introductory or navigational aids for a page or section
 */


@ HtmlTagMarker <EOL> inline fun FlowContent . hr ( classes : String ? = null , crossinline block : HR . ( ) -> Unit = { } ) : Unit

= HR ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . ol ( classes : String ? = null , crossinline block : OL . ( ) -> Unit = { } ) : Unit

= OL ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . p ( classes : String ? = null , crossinline block : P . ( ) -> Unit = { } ) : Unit

= P ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . pre ( classes : String ? = null , crossinline block : PRE . ( ) -> Unit = { } ) : Unit

= PRE ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . summary ( classes : String ? = null , crossinline block : SUMMARY . ( ) -> Unit = { } ) : Unit

= SUMMARY ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . table ( classes : String ? = null , crossinline block : TABLE . ( ) -> Unit = { } ) : Unit

= TABLE ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . u ( classes : String ? = null , crossinline block : U . ( ) -> Unit = { } ) : Unit

= U ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . ul ( classes : String ? = null , crossinline block : UL . ( ) -> Unit = { } ) : Unit

= UL ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun FlowContent . s ( classes : String ? = null , crossinline block : S . ( ) -> Unit = { } ) : Unit

= S ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun MetaDataContent . base ( classes : String ? = null , crossinline block : BASE . ( ) -> Unit = { } ) : Unit

= BASE ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> inline fun MetaDataContent . title ( crossinline block : TITLE . ( ) -> Unit = { } ) : Unit

= TITLE ( emptyMap , consumer ) . visit ( block )


@ HtmlTagMarker <EOL> fun MetaDataContent . title ( content : String = "<STR_LIT>" ) : Unit

= TITLE ( emptyMap , consumer ) . visit ( { + content } )


@ HtmlTagMarker <EOL> inline fun PhrasingContent . template ( classes : String ? = null , crossinline block : TEMPLATE . ( ) -> Unit = { } ) : Unit

= TEMPLATE ( attributesMapOf ( "<STR_LIT:class>" , classes ) , consumer ) . visit ( block )


private fun String . looksLikeRemovedTarget ( ) : Boolean

= <EOL> this in removedTargetsNames || this . startsWith ( "<STR_LIT>" )

/**
 * [this] is a value passed to `-target` CLI-argument (see [KonanConfigKeys.TARGET])
 * Returns 'true' if this argument is most likely a removed [KonanTarget], allowing for a
 * more readable and graceful error message.
 */


public fun < T : Number , D : Dimension > median ( a : MultiArray < T , D > ) : Double ?

/**
 * Returns the median of the [a] elements.
 */


public fun < T : Number , D : Dimension > average ( a : MultiArray < T , D > , weights : MultiArray < T , D > ? = null ) : Double

/**
 * Returns the weighted average over the [a] elements and [weights] elements.
 */


public fun < T : Number , D : Dimension > mean ( a : MultiArray < T , D > ) : Double

/**
 * Returns the arithmetic mean of the [a] elements.
 */


public fun < T : Number , D : Dimension , O : Dimension > mean ( a : MultiArray < T , D > , axis : Int ) : NDArray < Double , O >

/**
 * Returns the arithmetic mean of the [a] elements along the given [axis].
 */


public fun < T : Number > meanD2 ( a : MultiArray < T , D2 > , axis : Int ) : NDArray < Double , D1 >

/**
 * Returns the arithmetic mean of the two-dimensional ndarray [a] elements along the given [axis].
 */


public fun < T : Number > meanD3 ( a : MultiArray < T , D3 > , axis : Int ) : NDArray < Double , D2 >

/**
 * Returns the arithmetic mean of the three-dimensional ndarray [a] elements along the given [axis].
 */


public fun < T : Number > meanD4 ( a : MultiArray < T , D4 > , axis : Int ) : NDArray < Double , D3 >

/**
 * Returns the arithmetic mean of the four-dimensional ndarray [a] elements along the given [axis].
 */


public fun < T : Number > meanDN ( a : MultiArray < T , DN > , axis : Int ) : NDArray < Double , D4 >

/**
 * Returns the arithmetic mean of the n-dimensional ndarray [a] elements along the given [axis].
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < Byte , D > ) : NDArray < Byte , D >

{ <EOL> val ret = initMemoryView < Byte > ( a . size , a . dtype ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = absByte ( element ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }

/**
 * Returns the absolute value of the given ndarray [a].
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < Short , D > ) : NDArray < Short , D >

{ <EOL> val ret = initMemoryView < Short > ( a . size , a . dtype ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = absShort ( element ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < Int , D > ) : NDArray < Int , D >

{ <EOL> val ret = initMemoryView < Int > ( a . size , a . dtype ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = kotlin . math . abs ( element ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < Long , D > ) : NDArray < Long , D >

{ <EOL> val ret = initMemoryView < Long > ( a . size , a . dtype ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = kotlin . math . abs ( element ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < Float , D > ) : NDArray < Float , D >

{ <EOL> val ret = initMemoryView < Float > ( a . size ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = kotlin . math . abs ( element ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < Double , D > ) : NDArray < Double , D >

{ <EOL> val ret = initMemoryView < Double > ( a . size ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = kotlin . math . abs ( element ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < ComplexFloat , D > ) : NDArray < Float , D >

{ <EOL> val ret = initMemoryView < Float > ( a . size ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = element . abs ( ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > abs ( a : MultiArray < ComplexDouble , D > ) : NDArray < Double , D >

{ <EOL> val ret = initMemoryView < Double > ( a . size ) <EOL> var index = <NUM_LIT:0> <EOL> for ( element in a ) { <EOL> ret [ index ++ ] = element . abs ( ) <EOL> } <EOL> return NDArray ( ret , <NUM_LIT:0> , a . shape . copyOf ( ) , dim = a . dim ) <EOL> }


@ Suppress ( "<STR_LIT>" ) <EOL> private inline fun absByte ( a : Byte ) : Byte

= if ( a < <NUM_LIT:0> ) ( - a ) . toByte ( ) else a

/**
 * Returns the absolute value of the given value [a].
 */


@ Suppress ( "<STR_LIT>" ) <EOL> private inline fun absShort ( a : Short ) : Short

= if ( a < <NUM_LIT:0> ) ( - a ) . toShort ( ) else a


@ Test <EOL> fun loadSequentialJSONConfigWithUnsupportedJSONFormat ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfigWithWrongJSON ) <EOL> val exception = <EOL> assertThrows ( IllegalArgumentException :: class . java ) { <EOL> Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> } <EOL> assertEquals ( "<STR_LIT>" , exception . message ) <EOL> }

/**
 * This test covers the case, when Python Keras user saves JSON as a String.
 *
 * ```
 * json_config = model.to_json()
 * with open('keras-cifar-10/model.json', 'w') as f:
 * json.dump(json_config, f)
 * ```
 */


@ Test <EOL> fun loadModelConfigFromKerasAndTrain ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfig ) <EOL> val testModel = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val ( train , test ) = fashionMnist ( ) <EOL> testModel . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . fit ( dataset = train , validationRate = VALIDATION_RATE , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = VALIDATION_BATCH_SIZE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = VALIDATION_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracy != null ) { <EOL> assertTrue ( accuracy > <NUM_LIT> ) <EOL> } <EOL> } <EOL> }

/** Weights are not loaded, but initialized via default initializers. */


@ Test <EOL> fun loadModelConfigFromKerasAndMissCompilation ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfig ) <EOL> val testModel = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val ( train , _ ) = fashionMnist ( ) <EOL> testModel . use { <EOL> val exception = <EOL> assertThrows ( IllegalStateException :: class . java ) { <EOL> it . fit ( dataset = train , validationRate = VALIDATION_RATE , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = VALIDATION_BATCH_SIZE ) <EOL> } <EOL> assertEquals ( "<STR_LIT>" , exception . message ) <EOL> } <EOL> }


@ Test <EOL> fun loadModelConfigAndWeightsFromKerasAndTrain ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfig ) <EOL> val testModel = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val file = File ( realPathToWeights ) <EOL> val hdfFile = HdfFile ( file ) <EOL> val ( train , test ) = fashionMnist ( ) <EOL> testModel . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeights ( hdfFile ) <EOL> val accuracyBefore = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyBefore != null ) { <EOL> assertTrue ( accuracyBefore > <NUM_LIT> ) <EOL> } <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = <NUM_LIT:3> , trainBatchSize = <NUM_LIT> , validationBatchSize = <NUM_LIT:100> ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyAfterTraining != null && accuracyBefore != null ) { <EOL> assertTrue ( accuracyAfterTraining > accuracyBefore ) <EOL> } <EOL> } <EOL> }

/** Simple transfer learning with additional training and without layers freezing. */


@ Test <EOL> fun loadModelConfigAndWeightsFromKerasAndTrainDenseLayersOnly ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfig ) <EOL> val testModel = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val file = File ( realPathToWeights ) <EOL> val hdfFile = HdfFile ( file ) <EOL> val ( train , test ) = fashionMnist ( ) <EOL> testModel . use { <EOL> it . layers . filterIsInstance < Conv2D > ( ) . forEach ( Layer :: freeze ) <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeights ( hdfFile ) <EOL> val accuracyBefore = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyBefore != null ) { <EOL> assertTrue ( accuracyBefore > <NUM_LIT> ) <EOL> } <EOL> val conv2DKernelWeightsBeforeTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights [ "<STR_LIT>" ] as Array < Array < Array < FloatArray > > > <EOL> assertEquals ( conv2DKernelWeightsBeforeTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> val denseDKernelWeightsBeforeTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights [ "<STR_LIT>" ] as Array < FloatArray > <EOL> assertEquals ( denseDKernelWeightsBeforeTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = <NUM_LIT:3> , trainBatchSize = <NUM_LIT> , validationBatchSize = <NUM_LIT:100> ) <EOL> val conv2DKernelWeightsAfterTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights [ "<STR_LIT>" ] as Array < Array < Array < FloatArray > > > <EOL> assertEquals ( conv2DKernelWeightsAfterTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> assertArrayEquals ( conv2DKernelWeightsBeforeTraining , conv2DKernelWeightsAfterTraining ) <EOL> val denseDKernelWeightsAfterTraining = it . getLayer ( "<STR_LIT>" ) . weights [ "<STR_LIT>" ] <EOL> assertFalse ( denseDKernelWeightsBeforeTraining . contentEquals ( denseDKernelWeightsAfterTraining ) ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyAfterTraining != null && accuracyBefore != null ) { <EOL> assertTrue ( accuracyAfterTraining > accuracyBefore ) <EOL> } <EOL> } <EOL> }

/** Simple transfer learning with additional training and Conv2D layers weights freezing. */


@ Test <EOL> fun loadModelConfigAndWeightsPartiallyFromKerasAndTrainDenseLayersOnly ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfig ) <EOL> val testModel = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val file = File ( realPathToWeights ) <EOL> val hdfFile = HdfFile ( file ) <EOL> val ( train , test ) = fashionMnist ( ) <EOL> testModel . use { <EOL> val layerList = it . layers . filterIsInstance < Conv2D > ( ) <EOL> layerList . forEach ( Layer :: freeze ) <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeights ( hdfFile , layerList ) <EOL> val accuracyBefore = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyBefore != null ) { <EOL> assertTrue ( accuracyBefore > <NUM_LIT> ) <EOL> } <EOL> val conv2DKernelWeighsBeforeTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < Array < Array < FloatArray > > > <EOL> assertEquals ( conv2DKernelWeighsBeforeTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> val denseDKernelWeightsBeforeTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < FloatArray > <EOL> assertEquals ( denseDKernelWeightsBeforeTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = <NUM_LIT:4> , trainBatchSize = <NUM_LIT> , validationBatchSize = <NUM_LIT:100> ) <EOL> val conv2DKernelWeightsAfterTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < Array < Array < FloatArray > > > <EOL> assertEquals ( conv2DKernelWeightsAfterTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> assertArrayEquals ( conv2DKernelWeighsBeforeTraining , conv2DKernelWeightsAfterTraining ) <EOL> val denseDKernelWeightsAfterTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < FloatArray > <EOL> assertFalse ( denseDKernelWeightsBeforeTraining . contentEquals ( denseDKernelWeightsAfterTraining ) ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyAfterTraining != null && accuracyBefore != null ) { <EOL> assertTrue ( accuracyAfterTraining > accuracyBefore ) <EOL> } <EOL> } <EOL> }

/**
 * Simple transfer learning with additional training and Conv2D layers weights freezing.
 *
 * NOTE: Dense weights are initialized via default initializers and trained from zero to hero.
 */


@ Test <EOL> fun loadModelConfigAndWeightsPartiallyByLayersListFromKerasAndTrainDenseLayersOnly ( )

{ <EOL> val jsonConfigFile = File ( realPathToConfig ) <EOL> val testModel = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> val file = File ( realPathToWeights ) <EOL> val hdfFile = HdfFile ( file ) <EOL> val ( train , test ) = fashionMnist ( ) <EOL> testModel . use { <EOL> it . layers . filterIsInstance < Conv2D > ( ) . forEach ( Layer :: freeze ) <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> val accuracyBefore = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyBefore != null ) { <EOL> assertTrue ( accuracyBefore > <NUM_LIT> ) <EOL> } <EOL> val conv2DKernelWeighsBeforeTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < Array < Array < FloatArray > > > <EOL> assertEquals ( conv2DKernelWeighsBeforeTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> val denseDKernelWeightsBeforeTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < FloatArray > <EOL> assertEquals ( denseDKernelWeightsBeforeTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = <NUM_LIT:4> , trainBatchSize = <NUM_LIT> , validationBatchSize = <NUM_LIT:100> ) <EOL> val conv2DKernelWeightsAfterTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < Array < Array < FloatArray > > > <EOL> assertEquals ( conv2DKernelWeightsAfterTraining [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT> ) <EOL> assertArrayEquals ( conv2DKernelWeighsBeforeTraining , conv2DKernelWeightsAfterTraining ) <EOL> val denseDKernelWeightsAfterTraining = <EOL> it . getLayer ( "<STR_LIT>" ) . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] as Array < FloatArray > <EOL> assertFalse ( denseDKernelWeightsBeforeTraining . contentEquals ( denseDKernelWeightsAfterTraining ) ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> if ( accuracyAfterTraining != null && accuracyBefore != null ) { <EOL> assertTrue ( accuracyAfterTraining > accuracyBefore ) <EOL> } <EOL> } <EOL> }


public fun SinglePoseDetectionModelBase < Bitmap > . detectPose ( imageProxy : ImageProxy ) : DetectedPose

= <EOL> when ( this ) { <EOL> is CameraXCompatibleModel -> { <EOL> doWithRotation ( imageProxy . imageInfo . rotationDegrees ) { detectPose ( imageProxy . toBitmap ( ) ) } <EOL> } <EOL> else -> detectPose ( imageProxy . toBitmap ( applyRotation = true ) ) <EOL> }

/**
 * Detects a pose for the given [imageProxy].
 * Internal preprocessing is updated to rotate image to match target orientation.
 * After prediction, internal preprocessing is restored to the original state.
 *
 * @param [imageProxy] input image.
 */


override fun iterator ( ) : Iterator < T >

{ <EOL> return MyIterator ( ) <EOL> }

/**
 * Collection iterator
 * Amortized next()/hasNext() complexity: O(1)
 */


fun add ( value : T , priority : Int , )

{ <EOL> if ( latterFirst ) { <EOL> ++ count <EOL> } else { <EOL> -- count <EOL> } <EOL> c . add ( Entry ( value , priority , count ) ) <EOL> }

/**
 * Adds [value] to the list with specified [priority]
 * Complexity: O(log n)
 */


{ <EOL> removeIf { it == value } <EOL> }

/**
 * Removes all values that are equal to [value]
 * Complexity: O(n + k * log(n)) where k is a number of elements to remove
 */


{ <EOL> return c . map { it . value } <EOL> }

/**
 * All collection elements
 * Complexity: O(n)
 */


fun addOrUpdatePriority ( value : T , priority : Int , )

{ <EOL> val maxPriority : Int ? = c . filter { it . value == value } . maxByOrNull { it . priority } ? . priority <EOL> if ( maxPriority != null ) { <EOL> if ( maxPriority >= priority ) { <EOL> return <EOL> } else { <EOL> remove ( value ) <EOL> } <EOL> } <EOL> add ( value , priority ) <EOL> }

/**
 * If a [value] wasn't previously added to the list, simply adds it with a given [priority].
 * Otherwise, in case if [priority] is less or equal to the priority of existent element(s), does nothing.
 * Otherwise, removes all existing elements from the list and adds [value] with a given [priority].
 * Complexity: O(n + k * log(n)) where k is a number of elements equal to [value]
 */


fun elementsWithPriority ( ) : List < Pair < T , Int > >

{ <EOL> return c . sortedBy { it . order } . map { it . value to it . priority } <EOL> }

/**
 * All elements with their priorities ordered by the time of adding
 * (elements added earlier go first)
 * Complexity: O(n log(n))
 */


public fun < T : Number , D : Dimension > argMax ( a : MultiArray < T , D > ) : Int

/**
 * Returns flat index of maximum element in an ndarray.
 */


public fun < T : Number , D : Dimension , O : Dimension > argMax ( a : MultiArray < T , D > , axis : Int ) : NDArray < Int , O >

/**
 * Returns an ndarray of indices of maximum elements in an ndarray [a] over a given [axis].
 */


public fun < T : Number > argMaxD2 ( a : MultiArray < T , D2 > , axis : Int ) : NDArray < Int , D1 >

/**
 * Returns an ndarray of indices of maximum elements in a two-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > argMaxD3 ( a : MultiArray < T , D3 > , axis : Int ) : NDArray < Int , D2 >

/**
 * Returns an ndarray of indices of maximum elements in a three-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > argMaxD4 ( a : MultiArray < T , D4 > , axis : Int ) : NDArray < Int , D3 >

/**
 * Returns an ndarray of indices of maximum elements in a four-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > argMaxDN ( a : MultiArray < T , DN > , axis : Int ) : NDArray < Int , DN >

/**
 * Returns an ndarray of indices of maximum elements in an n-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number , D : Dimension > argMin ( a : MultiArray < T , D > ) : Int

/**
 * Returns flat index of minimum element in an ndarray.
 */


public fun < T : Number , D : Dimension , O : Dimension > argMin ( a : MultiArray < T , D > , axis : Int ) : NDArray < Int , O >

/**
 * Returns an ndarray of indices of minimum elements in an ndarray [a] over a given [axis].
 */


public fun < T : Number > argMinD2 ( a : MultiArray < T , D2 > , axis : Int ) : NDArray < Int , D1 >

/**
 * Returns an ndarray of indices of minimum elements in a two-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > argMinD3 ( a : MultiArray < T , D3 > , axis : Int ) : NDArray < Int , D2 >

/**
 * Returns an ndarray of indices of minimum elements in a three-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > argMinD4 ( a : MultiArray < T , D4 > , axis : Int ) : NDArray < Int , D3 >

/**
 * Returns an ndarray of indices of minimum elements in a four-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > argMinDN ( a : MultiArray < T , DN > , axis : Int ) : NDArray < Int , DN >

/**
 * Returns an ndarray of indices of minimum elements in an n-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number , D : Dimension > max ( a : MultiArray < T , D > ) : T

/**
 * Returns maximum element of the given ndarray.
 */


public fun < T : Number , D : Dimension , O : Dimension > max ( a : MultiArray < T , D > , axis : Int ) : NDArray < T , O >

/**
 * Returns maximum of an ndarray [a] along a given [axis].
 */


public fun < T : Number > maxD2 ( a : MultiArray < T , D2 > , axis : Int ) : NDArray < T , D1 >

/**
 * Returns maximum of a two-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number > maxD3 ( a : MultiArray < T , D3 > , axis : Int ) : NDArray < T , D2 >

/**
 * Returns maximum of a three-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number > maxD4 ( a : MultiArray < T , D4 > , axis : Int ) : NDArray < T , D3 >

/**
 * Returns maximum of a four-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number > maxDN ( a : MultiArray < T , DN > , axis : Int ) : NDArray < T , DN >

/**
 * Returns maximum of an n-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number , D : Dimension > min ( a : MultiArray < T , D > ) : T

/**
 * Returns minimum element of the given ndarray.
 */


public fun < T : Number , D : Dimension , O : Dimension > min ( a : MultiArray < T , D > , axis : Int ) : NDArray < T , O >

/**
 * Returns minimum of an ndarray [a] along a given [axis].
 */


public fun < T : Number > minD2 ( a : MultiArray < T , D2 > , axis : Int ) : NDArray < T , D1 >

/**
 * Returns minimum of a two-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number > minD3 ( a : MultiArray < T , D3 > , axis : Int ) : NDArray < T , D2 >

/**
 * Returns minimum of a three-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number > minD4 ( a : MultiArray < T , D4 > , axis : Int ) : NDArray < T , D3 >

/**
 * Returns minimum of a four-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number > minDN ( a : MultiArray < T , DN > , axis : Int ) : NDArray < T , DN >

/**
 * Returns minimum of an n-dimensional ndarray [a] along a given [axis].
 */


public fun < T : Number , D : Dimension > sum ( a : MultiArray < T , D > ) : T

/**
 * Returns sum of all elements in the given ndarray.
 */


public fun < T : Number , D : Dimension , O : Dimension > sum ( a : MultiArray < T , D > , axis : Int ) : NDArray < T , O >

/**
 * Returns an ndarray of sum all elements over a given [axis].
 */


public fun < T : Number > sumD2 ( a : MultiArray < T , D2 > , axis : Int ) : NDArray < T , D1 >

/**
 * Returns an ndarray of sum all elements in a two-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > sumD3 ( a : MultiArray < T , D3 > , axis : Int ) : NDArray < T , D2 >

/**
 * Returns an ndarray of sum all elements in a three-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > sumD4 ( a : MultiArray < T , D4 > , axis : Int ) : NDArray < T , D3 >

/**
 * Returns an ndarray of sum all elements in a four-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number > sumDN ( a : MultiArray < T , DN > , axis : Int ) : NDArray < T , DN >

/**
 * Returns an ndarray of sum all elements in a n-dimensional ndarray [a] over a given [axis].
 */


public fun < T : Number , D : Dimension > cumSum ( a : MultiArray < T , D > ) : D1Array < T >

/**
 * Returns cumulative sum of all elements in the given ndarray.
 */


public fun < T : Number , D : Dimension > cumSum ( a : MultiArray < T , D > , axis : Int ) : NDArray < T , D >

/**
 * Returns cumulative sum of all elements in the given ndarray along the given [axis].
 */


private fun storeMetricsIntoFile ( buildId : String )

{ <EOL> try { <EOL> statisticsFolder . mkdirs ( ) <EOL> val file = File ( statisticsFolder , buildId + PROFILE_FILE_NAME_SUFFIX ) <EOL> FileOutputStream ( file , true ) . bufferedWriter ( ) . use { <EOL> metricsContainer . flush ( it ) <EOL> } <EOL> } catch ( _ : IOException ) { <EOL> } <EOL> }

/**
 * Initializes a new build report file
 * The following contracts are implemented:
 * - each file contains metrics for one build
 * - any other process can add metrics to the file during build
 * - files with age (current time - last modified) more than maxFileAge should be deleted (if we trust lastModified returned by FS)
 */


public fun start ( errorReporting : Boolean = true , name : String ? = null ) : Worker <EOL>

= Worker ( startInternal ( errorReporting , name ) )

/**
 * Start new scheduling primitive, such as thread, to accept new tasks via `execute` interface.
 * Typically new worker may be needed for computations offload to another core, for IO it may be
 * better to use non-blocking IO combined with more lightweight coroutines.
 *
 * @param errorReporting controls if an uncaught exceptions in the worker will be reported.
 * @param name defines the optional name of this worker, if none - default naming is used.
 * @return worker object, usable across multiple concurrent contexts.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . WARNING ) <EOL> public fun fromCPointer ( pointer : COpaquePointer ? ) : Worker

= <EOL> if ( pointer != null ) Worker ( pointer . toLong ( ) . toInt ( ) ) else throw IllegalArgumentException ( )

/**
 * Create worker object from a C pointer.
 *
 * This function is deprecated. See [Worker.asCPointer] for more details.
 *
 * @param pointer value returned earlier by [Worker.asCPointer]
 */


public fun requestTermination ( processScheduledJobs : Boolean = true ) : Future < Unit >

= <EOL> Future < Unit > ( requestTerminationInternal ( id , processScheduledJobs ) )

/**
 * Requests termination of the worker.
 *
 * Returns [Future] that **must** be joined with [Future.result] blocking call.
 * Failure to do so will leak native memory and underlying native thread handles.
 *
 * @param processScheduledJobs controls is we shall wait until all scheduled jobs processed,
 * or terminate immediately. If there are jobs to be execucted with [executeAfter] their execution
 * is awaited for.
 */


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> @ TypedIntrinsic ( IntrinsicType . WORKER_EXECUTE ) <EOL> public fun < T1 , T2 > execute ( mode : TransferMode , producer : ( ) -> T1 , @ VolatileLambda job : ( T1 ) -> T2 ) : Future < T2 >

= <EOL> throw RuntimeException ( "<STR_LIT>" )

/**
 * Plan job for further execution in the worker. Execute is a two-phase operation:
 * 1. [producer] function is executed on the caller's thread.
 * 2. the result of [producer] and [job] function pointer is being added to jobs queue
 * of the selected worker. Note that [job] must not capture any state itself.
 *
 * Parameter [mode] has no effect.
 *
 * Behavior is more complex in case of legacy memory manager:
 *
 * - first [producer] function is executed, and resulting object and whatever it refers to
 * is analyzed for being an isolated object subgraph, if in checked mode.
 * - Afterwards, this disconnected object graph and [job] function pointer is being added to jobs queue
 * of the selected worker. Note that [job] must not capture any state itself, so that whole state is
 * explicitly stored in object produced by [producer]. Scheduled job is being executed by the worker,
 * and result of such a execution is being disconnected from worker's object graph. Whoever will consume
 * the future, can use result of worker's computations.
 * Note, that some technically disjoint subgraphs may lead to `kotlin.IllegalStateException`
 * so `kotlin.native.runtime.GC.collect()` could be called in the end of `producer` and `job`
 * if garbage cyclic structures or other uncollected objects refer to the value being transferred.
 *
 * @return the future with the computation result of [job].
 */


@ OptIn ( ExperimentalNativeApi :: class ) <EOL> public fun executeAfter ( afterMicroseconds : Long = <NUM_LIT:0> , operation : ( ) -> Unit ) : Unit

{ <EOL> val current = currentInternal ( ) <EOL> if ( Platform . memoryModel != MemoryModel . EXPERIMENTAL && current != id && ! operation . isFrozen ) throw IllegalStateException ( "<STR_LIT>" ) <EOL> if ( afterMicroseconds < <NUM_LIT:0> ) throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> executeAfterInternal ( id , operation , afterMicroseconds ) <EOL> }

/**
 * Plan job for further execution in the worker.
 *
 * If the worker was created with `errorReporting` set to true, any exception escaping from [operation] will
 * be handled by [processUnhandledException].
 *
 * @param afterMicroseconds defines after how many microseconds delay execution shall happen, 0 means immediately,
 * @throws [IllegalArgumentException] on negative values of [afterMicroseconds].
 * @throws [IllegalStateException] if [operation] parameter is not frozen and worker is not current.
 */


= processQueueInternal ( id )

/**
 * Process pending job(s) on the queue of this worker.
 * Note that jobs scheduled with [executeAfter] using non-zero timeout are
 * not processed this way. If termination request arrives while processing the queue via this API,
 * worker is marked as terminated and will exit once the current request is done with.
 *
 * @throws [IllegalStateException] if this request is executed on non-current [Worker].
 * @return `true` if request(s) was processed and `false` otherwise.
 */


public fun park ( timeoutMicroseconds : Long , process : Boolean = false ) : Boolean

{ <EOL> if ( timeoutMicroseconds < - <NUM_LIT:1> ) throw IllegalArgumentException ( ) <EOL> return parkInternal ( id , timeoutMicroseconds , process ) <EOL> }

/**
 * Park execution of the current worker until a new request arrives or timeout specified in
 * [timeoutMicroseconds] elapsed. If [process] is true, pending queue elements are processed,
 * including delayed requests. Note that multiple requests could be processed this way.
 *
 * @param timeoutMicroseconds defines how long to park worker if no requests arrive, waits forever if -1.
 * @param process defines if arrived request(s) shall be processed.
 * @return if [process] is `true`: if request(s) was processed `true` and `false` otherwise.
 * if [process] is `false`:` true` if request(s) has arrived and `false` if timeout happens.
 * @throws [IllegalStateException] if this request is executed on non-current [Worker].
 * @throws [IllegalArgumentException] if timeout value is incorrect.
 */


override public fun toString ( ) : String

= "<STR_LIT>"

/**
 * String representation of the worker.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . WARNING ) <EOL> public fun asCPointer ( ) : COpaquePointer ?

= id . toLong ( ) . toCPointer ( )

/**
 * Convert worker to a COpaquePointer value that could be passed via native void* pointer.
 * Can be used as an argument of [Worker.fromCPointer].
 *
 * This function is deprecated. Use `kotlinx.cinterop.StableRef.create(worker).asCPointer()` instead.
 * The result can be unwrapped with `pointer.asStableRef<Worker>().get()`.
 * [StableRef] should be eventually disposed manually with [StableRef.dispose].
 *
 * @return worker identifier as C pointer.
 */


@ ObsoleteWorkersApi <EOL> public inline fun < R > withWorker ( name : String ? = null , errorReporting : Boolean = true , block : Worker . ( ) -> R ) : R

{ <EOL> val worker = Worker . start ( errorReporting , name ) <EOL> try { <EOL> return worker . block ( ) <EOL> } finally { <EOL> worker . requestTermination ( ) . result <EOL> } <EOL> }

/**
 * Executes [block] with new [Worker] as resource, by starting the new worker, calling provided [block]
 * (in current context) with newly started worker as [this] and terminating worker after the block completes.
 * Note that this operation is pretty heavyweight, use preconfigured worker or worker pool if need to
 * execute it frequently.
 *
 * @param name of the started worker.
 * @param errorReporting controls if uncaught errors in worker to be reported.
 * @param block to be executed.
 * @return value returned by the block.
 */


@ Test <EOL> fun indexOfByteStringAcrossSegmentBoundaries ( )

{ <EOL> sink . writeString ( "<STR_LIT:a>" . repeat ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:3> ) ) <EOL> sink . writeString ( "<STR_LIT>" ) <EOL> sink . emit ( ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:4> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:4> ) . toLong ( ) , source . indexOf ( "<STR_LIT:abc>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:4> ) . toLong ( ) , source . indexOf ( "<STR_LIT:abcd>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:4> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:4> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:4> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:3> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:2> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> - <NUM_LIT:1> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> + <NUM_LIT:1> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> assertEquals ( ( Segment . SIZE * <NUM_LIT:2> + <NUM_LIT:2> ) . toLong ( ) , source . indexOf ( "<STR_LIT>" . encodeToByteString ( ) ) ) <EOL> }

/**
 * With [BufferedSourceFactory.ONE_BYTE_AT_A_TIME_BUFFERED_SOURCE], this code was extremely slow.
 * https://github.com/square/okio/issues/171
 */


private fun IrFunction . isTargetMethod ( ) : Boolean

{ <EOL> val fqName = fqNameWhenAvailable ? . asString ( ) ? : return false <EOL> return fqName == "<STR_LIT>" || fqName == "<STR_LIT>" <EOL> }

/**
 * Method for intrinsification `kotlinx.serialization.serializer` is a top-level function.
 * For the rest of the world, it is located in the facade `kotlinx.serialization.SerializersKt`.
 * However, when we compile `kotlinx-serialization-core` itself, facade contains only synthetic bridges.
 * Real function is contained in IR class with `SerializersKt__SerializersKt` name.
 * (as we have `@file:JvmMultifileClass @file:JvmName("SerializersKt")` on both common Serializers.kt and a platform-specific SerializersJvm.kt files)
 */


override fun rewritePluginDefinedOperationMarker ( v : InstructionAdapter , reifiedInsn : AbstractInsnNode , instructions : InsnList , type : IrType ) : Boolean

{ <EOL> val operationTypeStr = ( reifiedInsn . next as LdcInsnNode ) . cst as String <EOL> if ( ! operationTypeStr . startsWith ( magicMarkerStringPrefix ) ) return false <EOL> val operationType = if ( operationTypeStr . endsWith ( "<STR_LIT>" ) ) { <EOL> val aload = reifiedInsn . next . next . next as VarInsnNode <EOL> val storedVar = aload . `var` <EOL> instructions . remove ( aload . next ) <EOL> instructions . remove ( aload ) <EOL> IntrinsicType . WithModule ( storedVar ) <EOL> } else IntrinsicType . Simple <EOL> instructions . remove ( reifiedInsn . next . next . next ) <EOL> instructions . remove ( reifiedInsn . next . next ) <EOL> instructions . remove ( reifiedInsn . next ) <EOL> instructions . remove ( reifiedInsn ) <EOL> generateSerializerForType ( type , v , operationType ) <EOL> return true <EOL> }

/**
 * Instructions at the moment of call:
 *
 * -3: iconst(6) // TYPE_OF
 * -2: aconst(typeParamName) // TYPE_OF
 * -1: invokestatic(reifiedOperationMarker)
 * < instructions from instructionAdapter will be inserted here by inliner >
 * 0 (stubConstNull): aconst(null)
 * 1: aconst(kotlinx.serialization.serializer.<operationType>)
 * 2: invokestatic(voidMagicApiCall)
 * 3: aload(moduleVar) // if withModule
 * 4: swap // if withModule
 * 5: invokestatic(kotlinx.serialization.serializer(module?, kType)
 *
 * We need to remove instructions from 0 to 5
 * Instructions -1, -2 and -3 would be removed by inliner.
 */


private fun InstructionAdapter . putReifyMarkerIfNeeded ( type : IrType , intrinsicType : IntrinsicType ) : Boolean

= <EOL> with ( typeSystemContext ) { <EOL> val typeDescriptor = type . typeConstructor ( ) . getTypeParameterClassifier ( ) <EOL> if ( typeDescriptor != null ) { <EOL> ReifiedTypeInliner . putReifiedOperationMarkerIfNeeded ( typeDescriptor , type . isMarkedNullable ( ) , ReifiedTypeInliner . OperationKind . TYPE_OF , this @ putReifyMarkerIfNeeded , typeSystemContext ) <EOL> aconst ( null ) <EOL> aconst ( intrinsicType . magicMarkerString ( ) ) <EOL> invokestatic ( pluginIntrinsicsMarkerOwner , pluginIntrinsicsMarkerMethod , pluginIntrinsicsMarkerSignature , false ) <EOL> if ( intrinsicType is IntrinsicType . WithModule ) { <EOL> load ( intrinsicType . storedIndex , serializersModuleType ) <EOL> swap ( ) <EOL> } <EOL> invokestatic ( serializersKtInternalName , callMethodName , intrinsicType . methodDescriptor , false ) <EOL> return true <EOL> } <EOL> return false <EOL> }

/**
 * This function produces identical to TYPE_OF reification marker. This is needed for compatibility reasons:
 * old compiler should be able to inline and run newer versions of kotlinx-serialization or other libraries.
 *
 * Operation detection in new compilers performed by voidMagicApiCall.
 */


private fun LLFirDeclarationModificationService . modifyElement ( element : PsiElement ) : Boolean

{ <EOL> val disposable = Disposer . newDisposable ( "<STR_LIT>" ) <EOL> var isOutOfBlock = false <EOL> try { <EOL> project . analysisMessageBus . connect ( disposable ) . subscribe ( KotlinTopics . MODULE_OUT_OF_BLOCK_MODIFICATION , KotlinModuleOutOfBlockModificationListener { isOutOfBlock = true } , ) <EOL> elementModified ( element ) <EOL> } finally { <EOL> Disposer . dispose ( disposable ) <EOL> } <EOL> return isOutOfBlock <EOL> }

/**
 * @return **true** if out-of-block happens
 */


{ <EOL> for ( parent in parentsWithSelf ) { <EOL> when ( parent ) { <EOL> is ASTDelegatePsiElement -> parent . subtreeChanged ( ) <EOL> is KtCodeFragment -> parent . subtreeChanged ( ) <EOL> } <EOL> } <EOL> }

/**
 * Emulate modification inside the body
 */


private fun createIncrementalCompilationContext ( fileLocations : FileLocations ? , transaction : CompilationTransaction , fragmentContext : FragmentContext ? = null , )

= IncrementalCompilationContext ( pathConverterForSourceFiles = fileLocations ? . getRelocatablePathConverterForSourceFiles ( ) ? : BasicFileToPathConverter , pathConverterForOutputFiles = fileLocations ? . getRelocatablePathConverterForOutputFiles ( ) ? : BasicFileToPathConverter , transaction = transaction , reporter = reporter , trackChangesInLookupCache = shouldTrackChangesInLookupCache , storeFullFqNamesInLookupCache = shouldStoreFullFqNamesInLookupCache , icFeatures = icFeatures , fragmentContext = fragmentContext , )

/**
 * Creates an instance of [IncrementalCompilationContext] that holds common incremental compilation context mostly required for [CacheManager]
 */


private fun tryCompileIncrementally ( allSourceFiles : List < File > , changedFiles : ChangedFiles ? , args : Args , fileLocations : FileLocations ? , messageCollector : MessageCollector , ) : ICResult

{ <EOL> if ( changedFiles is ChangedFiles . Unknown ) { <EOL> return ICResult . RequiresRebuild ( UNKNOWN_CHANGES_IN_GRADLE_INPUTS ) <EOL> } <EOL> val fragmentContext = if ( ! icFeatures . enableUnsafeIncrementalCompilationForMultiplatform ) { <EOL> FragmentContext . fromCompilerArguments ( args ) <EOL> } else { <EOL> null <EOL> } <EOL> return createTransaction ( ) . runWithin ( :: incrementalCompilationExceptionTransformer ) { transaction -> <EOL> val icContext = createIncrementalCompilationContext ( fileLocations , transaction , fragmentContext ) <EOL> val caches = createCacheManager ( icContext , args ) . also { <EOL> transaction . cachesManager = it <EOL> } <EOL> fun compile ( ) : ICResult { <EOL> val knownChangedFiles : ChangedFiles . Known = try { <EOL> getChangedFiles ( changedFiles as ChangedFiles . Known ? , allSourceFiles , caches ) <EOL> } catch ( e : Throwable ) { <EOL> return ICResult . Failed ( IC_FAILED_TO_GET_CHANGED_FILES , e ) <EOL> } <EOL> val classpathAbiSnapshot = if ( icFeatures . withAbiSnapshot ) getClasspathAbiSnapshot ( args ) else null <EOL> val compilationMode = try { <EOL> reporter . measure ( GradleBuildTime . IC_CALCULATE_INITIAL_DIRTY_SET ) { <EOL> calculateSourcesToCompile ( caches , knownChangedFiles , args , messageCollector , classpathAbiSnapshot ? : emptyMap ( ) ) <EOL> } <EOL> } catch ( e : Throwable ) { <EOL> return ICResult . Failed ( IC_FAILED_TO_COMPUTE_FILES_TO_RECOMPILE , e ) <EOL> } <EOL> if ( compilationMode is CompilationMode . Rebuild ) { <EOL> return ICResult . RequiresRebuild ( compilationMode . reason ) <EOL> } <EOL> val abiSnapshotData = if ( icFeatures . withAbiSnapshot ) { <EOL> if ( ! abiSnapshotFile . exists ( ) ) { <EOL> reporter . debug { "<STR_LIT>" } <EOL> return ICResult . RequiresRebuild ( NO_ABI_SNAPSHOT ) <EOL> } <EOL> reporter . info { "<STR_LIT>" } <EOL> AbiSnapshotData ( snapshot = AbiSnapshotImpl . read ( abiSnapshotFile ) , classpathAbiSnapshot = classpathAbiSnapshot ! ! <EOL> ) <EOL> } else null <EOL> val exitCode = try { <EOL> compileImpl ( icContext , compilationMode as CompilationMode . Incremental , allSourceFiles , args , caches , abiSnapshotData , messageCollector , ) <EOL> } catch ( e : RequireRebuildForCorrectnessInKMPException ) { <EOL> return ICResult . RequiresRebuild ( UNSAFE_INCREMENTAL_CHANGE_KT_62686 ) <EOL> } catch ( e : Throwable ) { <EOL> return ICResult . Failed ( IC_FAILED_TO_COMPILE_INCREMENTALLY , e ) <EOL> } <EOL> return ICResult . Completed ( exitCode ) <EOL> } <EOL> compile ( ) . also { icResult -> <EOL> if ( icResult is ICResult . Completed && icResult . exitCode == ExitCode . OK ) { <EOL> transaction . markAsSuccessful ( ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Attempts to compile incrementally and returns either [ICResult.Completed], [ICResult.RequiresRebuild], or [ICResult.Failed].
 *
 * Note that parts of this function may still throw exceptions that are not caught and wrapped by [ICResult.Failed] because they are not
 * meant to be caught.
 */


private fun cleanOrCreateDirectories ( outputDirs : Collection < File > )

{ <EOL> outputDirs . toSet ( ) . forEach { <EOL> when { <EOL> it . isDirectory -> it . deleteDirectoryContents ( ) <EOL> it . isFile -> "<STR_LIT>" <EOL> else -> it . createDirectory ( ) <EOL> } <EOL> } <EOL> }

/**
 * Deletes the contents of the given directories (not the directories themselves).
 *
 * If the directories do not yet exist, they will be created.
 */


{ <EOL> val ( train , test ) = mnist ( ) <EOL> lenet5Classic . use { <EOL> val earlyStopping = EarlyStopping ( monitor = EpochTrainingEvent :: valLossValue , minDelta = <NUM_LIT:0.0> , patience = <NUM_LIT:2> , verbose = true , mode = EarlyStoppingMode . AUTO , baseline = <NUM_LIT> , restoreBestWeights = false ) <EOL> val terminateOnNaN = TerminateOnNaN ( ) <EOL> it . compile ( optimizer = Adam ( clipGradient = ClipGradientByValue ( <NUM_LIT> ) ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE , callbacks = listOf ( earlyStopping , terminateOnNaN ) ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE , callback = EvaluateCallback ( ) ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> val predictions = it . predict ( dataset = test , batchSize = TEST_BATCH_SIZE , callback = PredictCallback ( ) ) <EOL> println ( predictions . size ) <EOL> } <EOL> }

/**
 * This example shows how to do image classification from scratch using [lenet5Classic], without leveraging pre-trained weights or a pre-made model.
 * We demonstrate the workflow on the Mnist classification dataset.
 *
 * It includes:
 * - dataset loading from S3
 * - callback definition
 * - model compilation with [EarlyStopping] and [TerminateOnNaN] callbacks
 * - model summary
 * - model training
 * - model evaluation
 */


= lenetWithMultipleCallbacks ( )


public operator fun CoroutineScope . plus ( context : CoroutineContext ) : CoroutineScope

= <EOL> ContextScope ( coroutineContext + context )

/**
 * Adds the specified coroutine context to this scope, overriding existing elements in the current
 * scope's context with the corresponding keys.
 *
 * This is a shorthand for `CoroutineScope(thisScope.coroutineContext + context)`.
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public fun MainScope ( ) : CoroutineScope

= ContextScope ( SupervisorJob ( ) + Dispatchers . Main )

/**
 * Creates the main [CoroutineScope] for UI components.
 *
 * Example of use:
 * ```
 * class MyAndroidActivity {
 * private val scope = MainScope()
 *
 * override fun onDestroy() {
 * super.onDestroy()
 * scope.cancel()
 * }
 * }
 * ```
 *
 * The resulting scope has [SupervisorJob] and [Dispatchers.Main] context elements.
 * If you want to append additional elements to the main scope, use [CoroutineScope.plus] operator:
 * `val scope = MainScope() + CoroutineName("MyActivity")`.
 */


public suspend fun < R > coroutineScope ( block : suspend CoroutineScope . ( ) -> R ) : R

{ <EOL> contract { <EOL> callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return suspendCoroutineUninterceptedOrReturn { uCont -> <EOL> val coroutine = ScopeCoroutine ( uCont . context , uCont ) <EOL> coroutine . startUndispatchedOrReturn ( coroutine , block ) <EOL> } <EOL> }

/**
 * Creates a [CoroutineScope] and calls the specified suspend block with this scope.
 * The provided scope inherits its [coroutineContext][CoroutineScope.coroutineContext] from the outer scope, using the
 * [Job] from that context as the parent for a new [Job].
 *
 * This function is designed for _concurrent decomposition_ of work. When any child coroutine in this scope fails,
 * this scope fails, cancelling all the other children (for a different behavior, see [supervisorScope]).
 * This function returns as soon as the given block and all its child coroutines are completed.
 * A usage of a scope looks like this:
 *
 * ```
 * suspend fun showSomeData() = coroutineScope {
 * val data = async(Dispatchers.IO) { // <- extension on current scope
 * ... load some UI data for the Main thread ...
 * }
 *
 * withContext(Dispatchers.Main) {
 * doSomeWork()
 * val result = data.await()
 * display(result)
 * }
 * }
 * ```
 *
 * The scope in this example has the following semantics:
 * 1) `showSomeData` returns as soon as the data is loaded and displayed in the UI.
 * 2) If `doSomeWork` throws an exception, then the `async` task is cancelled and `showSomeData` rethrows that exception.
 * 3) If the outer scope of `showSomeData` is cancelled, both started `async` and `withContext` blocks are cancelled.
 * 4) If the `async` block fails, `withContext` will be cancelled.
 *
 * The method may throw a [CancellationException] if the current job was cancelled externally,
 * rethrow the exception thrown by [block], or throw an unhandled [Throwable] if there is one
 * (for example, from a crashed coroutine that was started with [launch][CoroutineScope.launch] in this scope).
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public fun CoroutineScope ( context : CoroutineContext ) : CoroutineScope

= <EOL> ContextScope ( if ( context [ Job ] != null ) context else context + Job ( ) )

/**
 * Creates a [CoroutineScope] that wraps the given coroutine [context].
 *
 * If the given [context] does not contain a [Job] element, then a default `Job()` is created.
 * This way, failure of any child coroutine in this scope or [cancellation][CoroutineScope.cancel] of the scope itself
 * cancels all the scope's children, just like inside [coroutineScope] block.
 */


public fun CoroutineScope . cancel ( cause : CancellationException ? = null )

{ <EOL> val job = coroutineContext [ Job ] ? : error ( "<STR_LIT>" ) <EOL> job . cancel ( cause ) <EOL> }

/**
 * Cancels this scope, including its job and all its children with an optional cancellation [cause].
 * A cause can be used to specify an error message or to provide other details on
 * a cancellation reason for debugging purposes.
 * Throws [IllegalStateException] if the scope does not have a job in it.
 */


public fun CoroutineScope . cancel ( message : String , cause : Throwable ? = null ) : Unit

= cancel ( CancellationException ( message , cause ) )

/**
 * Cancels this scope, including its job and all its children with a specified diagnostic error [message].
 * A [cause] can be specified to provide additional details on a cancellation reason for debugging purposes.
 * Throws [IllegalStateException] if the scope does not have a job in it.
 */


public fun CoroutineScope . ensureActive ( ) : Unit

= coroutineContext . ensureActive ( )

/**
 * Ensures that current scope is [active][CoroutineScope.isActive].
 *
 * If the job is no longer active, throws [CancellationException].
 * If the job was cancelled, thrown exception contains the original cancellation cause.
 * This function does not do anything if there is no [Job] in the scope's [coroutineContext][CoroutineScope.coroutineContext].
 *
 * This method is a drop-in replacement for the following code, but with more precise exception:
 * ```
 * if (!isActive) {
 * throw CancellationException()
 * }
 * ```
 *
 * @see CoroutineContext.ensureActive
 */


public suspend inline fun currentCoroutineContext ( ) : CoroutineContext

= coroutineContext

/**
 * Returns the current [CoroutineContext] retrieved by using [kotlin.coroutines.coroutineContext].
 * This function is an alias to avoid name clash with [CoroutineScope.coroutineContext] in a receiver position:
 *
 * ```
 * launch { // this: CoroutineScope
 * val flow = flow<Unit> {
 * coroutineContext // Resolves into the context of outer launch, which is incorrect, see KT-38033
 * currentCoroutineContext() // Retrieves actual context where the flow is collected
 * }
 * }
 * ```
 */


fun ValueParameterDescriptor . hasDefaultValue ( ) : Boolean

{ <EOL> return DFS . ifAny ( listOf ( this ) , { current -> current . overriddenDescriptors . map ( ValueParameterDescriptor :: getOriginal ) } , { it . declaresDefaultValue ( ) || it . isActualParameterWithCorrespondingExpectedDefault } ) <EOL> }

/**
 * @return `true` iff the parameter has a default value, i.e. declares it, inherits it by overriding a parameter which has a default value,
 * or is a parameter of an 'actual' declaration, such that the corresponding 'expect' parameter has a default value.
 */


internal fun < T > assertJsonFormAndRestored ( serializer : KSerializer < T > , data : T , expected : String , json : Json = default )

{ <EOL> parametrizedTest { jsonTestingMode -> <EOL> val serialized = json . encodeToString ( serializer , data , jsonTestingMode ) <EOL> assertEquals ( expected , serialized , "<STR_LIT>" ) <EOL> val deserialized : T = json . decodeFromString ( serializer , serialized , jsonTestingMode ) <EOL> assertEquals ( data , deserialized , "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Same as [assertStringFormAndRestored], but tests both json converters (streaming and tree)
 * via [parametrizedTest]
 */


internal fun < T > assertJsonFormAndRestoredCustom ( serializer : KSerializer < T > , data : T , expected : String , check : ( T , T ) -> Boolean )

{ <EOL> parametrizedTest { jsonTestingMode -> <EOL> val serialized = Json . encodeToString ( serializer , data , jsonTestingMode ) <EOL> assertEquals ( expected , serialized , "<STR_LIT>" ) <EOL> val deserialized : T = Json . decodeFromString ( serializer , serialized , jsonTestingMode ) <EOL> assertTrue ( "<STR_LIT>" ) { check ( data , deserialized ) } <EOL> } <EOL> }

/**
 * Same as [assertStringFormAndRestored], but tests both json converters (streaming and tree)
 * via [parametrizedTest]. Use custom checker for deserialized value.
 */


private fun findLibraries ( unresolvedLibraries : List < UnresolvedLibrary > , noStdLib : Boolean , noDefaultLibs : Boolean , noEndorsedLibs : Boolean , ) : List < KotlinLibrary >

{ <EOL> val userProvidedLibraries = unresolvedLibraries . asSequence ( ) <EOL> . mapNotNull { searchPathResolver . resolve ( it ) } <EOL> . toList ( ) <EOL> val defaultLibraries = searchPathResolver . defaultLinks ( noStdLib , noDefaultLibs , noEndorsedLibs ) <EOL> return userProvidedLibraries + defaultLibraries <EOL> }

/**
 * Returns the list of libraries based on [libraryNames], [noStdLib], [noDefaultLibs] and [noEndorsedLibs] criteria.
 *
 * This method does not return any libraries that might be available via transitive dependencies
 * from the original library set (root set).
 */


private fun List < KotlinLibrary > . leaveDistinct ( ) : List < KotlinLibrary >

{ <EOL> if ( size <= <NUM_LIT:1> ) return this <EOL> val deduplicatedLibraries : Map < String , List < KotlinLibrary > > = groupByTo ( linkedMapOf ( ) ) { it . libraryFile . absolutePath } <EOL> return deduplicatedLibraries . values . map { it . first ( ) } <EOL> }

/**
 * Leaves only distinct libraries (by absolute path).
 */


private fun List < KotlinLibrary > . omitDuplicateNames ( )

= <EOL> groupBy { it . uniqueName } . let { groupedByUniqName -> <EOL> val librariesWithDuplicatedUniqueNames = groupedByUniqName . filterValues { it . size > <NUM_LIT:1> } <EOL> librariesWithDuplicatedUniqueNames . entries . sortedBy { it . key } . forEach { ( uniqueName , libraries ) -> <EOL> val libraryPaths = libraries . map { it . libraryFile . absolutePath } . sorted ( ) . joinToString ( ) <EOL> logger . warning ( "<STR_LIT>" ) <EOL> } <EOL> groupedByUniqName . map { it . value . first ( ) } <EOL> }

/**
 * Having two libraries with the same `unique_name` we only keep the first one.
 *
 * TODO: This is actually undesirable behavior.
 * - In certain situations it harms, e.g. KT-63573
 * - But sometimes it is really necessary, e.g. KT-64115
 * - Overall, we should not do any resolve inside the compiler (such as skipping KLIBs that happen to have repeated `unique_name`).
 * This is an opaque process which better should be performed by the build system (e.g. Gradle). To be fixed in KT-64169
 */


override fun List < KotlinLibrary > . resolveDependencies ( ) : KotlinLibraryResolveResult

{ <EOL> val rootLibraries = this . map { KotlinResolvedLibraryImpl ( it ) } <EOL> val result = KotlinLibraryResolverResultImpl ( rootLibraries ) <EOL> val cache = mutableMapOf < Any , KotlinResolvedLibrary > ( ) <EOL> cache . putAll ( rootLibraries . map { it . library . libraryFile . fileKey to it } ) <EOL> var newDependencies = rootLibraries <EOL> do { <EOL> newDependencies = newDependencies . map { library : KotlinResolvedLibraryImpl -> <EOL> library . library . unresolvedDependencies ( resolveManifestDependenciesLenient ) . asSequence ( ) <EOL> . filterNot { searchPathResolver . isProvidedByDefault ( it ) } <EOL> . mapNotNull { searchPathResolver . resolve ( it ) ? . let ( :: KotlinResolvedLibraryImpl ) } <EOL> . map { resolved -> <EOL> val fileKey = resolved . library . libraryFile . fileKey <EOL> if ( fileKey in cache ) { <EOL> library . addDependency ( cache [ fileKey ] ! ! ) <EOL> null <EOL> } else { <EOL> cache . put ( fileKey , resolved ) <EOL> library . addDependency ( resolved ) <EOL> resolved <EOL> } <EOL> } . filterNotNull ( ) <EOL> . toList ( ) <EOL> } . flatten ( ) <EOL> } while ( newDependencies . isNotEmpty ( ) ) <EOL> return result <EOL> }

/**
 * Given the list of root libraries does the following:
 *
 * 1. Evaluates other libraries that are available via transitive dependencies.
 * 2. Wraps each [KotlinLibrary] into a [KotlinResolvedLibrary] with information about dependencies on other libraries.
 * 3. Creates resulting [KotlinLibraryResolveResult] object.
 */


@ ExperimentalSerializationApi <EOL> public fun Cbor ( from : Cbor = Cbor , builderAction : CborBuilder . ( ) -> Unit ) : Cbor

{ <EOL> val builder = CborBuilder ( from ) <EOL> builder . builderAction ( ) <EOL> return CborImpl ( builder . encodeDefaults , builder . ignoreUnknownKeys , builder . serializersModule ) <EOL> }

/**
 * Creates an instance of [Cbor] configured from the optionally given [Cbor instance][from]
 * and adjusted with [builderAction].
 */


public fun content ( value : Any ? , configuration : DisplayConfiguration ) : RenderedContent

/**
 * Returns [value] rendered to HTML text, or null if such rendering is impossible
 */


public fun tooltip ( value : Any ? , configuration : DisplayConfiguration ) : String

/**
 * Returns cell tooltip for this [value]
 */


fun invokeInterop ( flavor : String , args : Array < String > , runFromDaemon : Boolean ) : Array < String > ?

{ <EOL> check ( flavor == "<STR_LIT:native>" ) { <EOL> "<STR_LIT>" <EOL> } <EOL> val arguments = CInteropArguments ( ) <EOL> arguments . argParser . parse ( args ) <EOL> val outputFileName = arguments . output <EOL> val noDefaultLibs = arguments . nodefaultlibs || arguments . nodefaultlibsDeprecated <EOL> val noEndorsedLibs = arguments . noendorsedlibs <EOL> val purgeUserLibs = arguments . purgeUserLibs <EOL> val nopack = arguments . nopack <EOL> val temporaryFilesDir = arguments . tempDir <EOL> val moduleName = arguments . moduleName <EOL> val shortModuleName = arguments . shortModuleName <EOL> val buildDir = File ( "<STR_LIT>" ) <EOL> val generatedDir = File ( buildDir , "<STR_LIT:kotlin>" ) <EOL> val nativesDir = File ( buildDir , "<STR_LIT>" ) <EOL> val manifest = File ( buildDir , "<STR_LIT>" ) <EOL> val cstubsName = "<STR_LIT>" <EOL> val libraries = arguments . library <EOL> val repos = arguments . repo <EOL> val targetRequest = arguments . target <EOL> val target = PlatformManager ( KotlinNativePaths . homePath . absolutePath , konanDataDir = arguments . konanDataDir ) . targetManager ( targetRequest ) . target <EOL> val cinteropArgsToCompiler = Interop ( ) . interop ( "<STR_LIT:native>" , args , InternalInteropOptions ( generatedDir . absolutePath , nativesDir . absolutePath , manifest . path , cstubsName ) , runFromDaemon ) ? : return null <EOL> val nativeStubs = <EOL> arrayOf ( "<STR_LIT>" , File ( nativesDir , "<STR_LIT>" ) . path ) <EOL> return arrayOf ( generatedDir . path , "<STR_LIT>" , "<STR_LIT:library>" , "<STR_LIT>" , outputFileName , "<STR_LIT>" , target . visibleName , "<STR_LIT>" , manifest . path , "<STR_LIT>" , "<STR_LIT>" ) + <EOL> nativeStubs + <EOL> cinteropArgsToCompiler + <EOL> libraries . flatMap { listOf ( "<STR_LIT>" , it ) } + <EOL> repos . flatMap { listOf ( "<STR_LIT>" , it ) } + <EOL> ( if ( noDefaultLibs ) arrayOf ( "<STR_LIT>" ) else emptyArray ( ) ) + <EOL> ( if ( noEndorsedLibs ) arrayOf ( "<STR_LIT>" ) else emptyArray ( ) ) + <EOL> ( if ( purgeUserLibs ) arrayOf ( "<STR_LIT>" ) else emptyArray ( ) ) + <EOL> ( if ( nopack ) arrayOf ( "<STR_LIT>" ) else emptyArray ( ) ) + <EOL> moduleName ? . let { arrayOf ( "<STR_LIT>" , it ) } . orEmpty ( ) + <EOL> shortModuleName ? . let { arrayOf ( "<STR_LIT>" ) } . orEmpty ( ) + <EOL> "<STR_LIT>" + <EOL> arguments . kotlincOption <EOL> }

/**
 * @return null if there is no need in compiler invocation.
 * Otherwise returns array of compiler args.
 */


abstract override fun equals ( other : Any ? ) : Boolean

/**
 * @return true if this type is equal to [other] symbolically. Note that this is NOT EQUIVALENT to the full type checking algorithm
 * used in the compiler frontend. For example, this method will return `false` on the types `List<*>` and `List<Any?>`,
 * whereas the real type checker from the compiler frontend would return `true`.
 *
 * Classes are compared by FQ names, which means that even if two types refer to different symbols of the class with the same FQ name,
 * such types will be considered equal. Type annotations do not have any effect on the behavior of this method.
 */


inline fun checkParcelizeClassSymbols ( symbol : FirClassSymbol < * > , session : FirSession , predicate : ( FirClassSymbol < * > ) -> Boolean , ) : Boolean

{ <EOL> if ( predicate ( symbol ) ) return true <EOL> return symbol . resolvedSuperTypeRefs . any { superTypeRef -> <EOL> val superTypeSymbol = superTypeRef . type . toRegularClassSymbol ( session ) <EOL> ? . takeIf { it . rawStatus . modality == Modality . SEALED } <EOL> ? : return@any false <EOL> predicate ( superTypeSymbol ) <EOL> } <EOL> }

/**
 * Check all related [FirClassSymbol]s to the provided [symbol] which are valid locations for a
 * `Parcelize` annotation to be present. This commonizes class symbol navigation between checker and
 * generator, even though [predicate] implementation is different.
 */


fun < K , V : Any > createMemoizedFunction ( compute : ( K ) -> V ) : MemoizedFunctionToNotNull < K , V >

/**
 * Given a function compute: K -> V create a memoized version of it that computes a value only once for each key
 * @param compute the function to be memoized
 * @param valuesReferenceKind how to store the memoized values
 *
 * NOTE: if compute() has side-effects the WEAK reference kind is dangerous: the side-effects will be repeated if
 * the value gets collected and then re-computed
 */


fun < T : Any > createLazyValueWithPostCompute ( computable : ( ) -> T , onRecursiveCall : ( ( Boolean ) -> T ) ? , postCompute : ( T ) -> Unit ) : NotNullLazyValue < T >

/**
 * @param onRecursiveCall is called if the computation calls itself recursively.
 * The parameter to it is {@code true} for the first call, {@code false} otherwise.
 * If {@code onRecursiveCall} is {@code null}, an exception will be thrown on a recursive call,
 * otherwise it's executed and its result is returned
 *
 * @param postCompute is called after the value is computed AND published (and some clients rely on that
 * behavior - notably, AbstractTypeConstructor). It means that it is up to particular implementation
 * to provide (or not to provide) thread-safety guarantees on writes made in postCompute -- see javadoc for
 * LockBasedLazyValue for details.
 */


fun < T : Any > createNullableLazyValueWithPostCompute ( computable : ( ) -> T ? , postCompute : ( T ? ) -> Unit ) : NullableLazyValue < T >

/**
 * See javadoc for createLazyValueWithPostCompute
 */


public fun load ( dataSource : D ) : FloatData

/**
 * Load the data from the specified [dataSource].
 */


fun < TypeParam > Receiver . function ( param1 : Param1 , param2 : Param2 ) : TypeParam


private fun dropOutdatedModifications ( ktModuleWithOutOfBlockModification : KtModule )

{ <EOL> processQueue { value , iterator -> <EOL> if ( value . ktModule == ktModuleWithOutOfBlockModification ) iterator . remove ( ) <EOL> } <EOL> }

/**
 * We can avoid processing of in-block modification with the same [KtModule] because they
 * will be invalidated anyway by OOBM
 */


private inline fun processQueue ( action : ( value : ChangeType . InBlock , iterator : MutableIterator < ChangeType . InBlock > ) -> Unit )

{ <EOL> val queue = inBlockModificationQueue ? : return <EOL> val iterator = queue . iterator ( ) <EOL> while ( iterator . hasNext ( ) ) { <EOL> val element = iterator . next ( ) <EOL> if ( ! element . blockOwner . isValid ) { <EOL> iterator . remove ( ) <EOL> continue <EOL> } <EOL> action ( element , iterator ) <EOL> } <EOL> }

/**
 * Process valid elements in the current queue.
 * Non-valid elements will be dropped from the queue during this iteration.
 *
 * @param action will be executed for each valid element in the queue;
 * **value** is a current element;
 * **iterator** is the corresponding iterator for this element.
 */


{ <EOL> ApplicationManager . getApplication ( ) . assertIsWriteThread ( ) <EOL> processQueue { value , _ -> <EOL> inBlockModification ( value . blockOwner , value . ktModule ) <EOL> } <EOL> inBlockModificationQueue = null <EOL> }

/**
 * Force the service to publish delayed modifications.
 * This action is required to fix inconsistencies in [FirFile][org.jetbrains.kotlin.fir.declarations.FirFile] tree.
 */


fun elementModified ( element : PsiElement , modificationType : ModificationType = ModificationType . Unknown )

{ <EOL> ApplicationManager . getApplication ( ) . assertIsWriteThread ( ) <EOL> when ( val changeType = calculateChangeType ( element , modificationType ) ) { <EOL> is ChangeType . Invisible -> { } <EOL> is ChangeType . InBlock -> addModificationToQueue ( changeType ) <EOL> is ChangeType . OutOfBlock -> outOfBlockModification ( element ) <EOL> } <EOL> }

/**
 * This method should be called during some [PsiElement] modification.
 * This method must be called from write action.
 *
 * Will publish event to [MODULE_OUT_OF_BLOCK_MODIFICATION] in case of out-of-block modification.
 *
 * @param element is an element that we want to/did already modify, remove, or add.
 * Some examples:
 * * [element] is [KtNamedFunction][org.jetbrains.kotlin.psi.KtNamedFunction] if we
 * dropped body ([KtBlockExpression][org.jetbrains.kotlin.psi.KtBlockExpression]) of this function
 * * [element] is [KtBlockExpression][org.jetbrains.kotlin.psi.KtBlockExpression] if we replaced one body-expression with another one
 * * [element] is [KtBlockExpression][org.jetbrains.kotlin.psi.KtBlockExpression] if added a body to the function without body
 * * [element] is the parent of an already removed element, while [ModificationType.ElementRemoved] will contain the removed element
 *
 * @param modificationType additional information to make more accurate decisions
 */


private fun PsiElement . isNewDirectChildOf ( inBlockModificationOwner : KtAnnotated , modificationType : ModificationType ) : Boolean

= <EOL> modificationType == ModificationType . ElementAdded && parent == inBlockModificationOwner

/**
 * This check covers cases such as a new body that was added to a function, which should cause an out-of-block modification.
 */


private fun ModificationType . isContractRemoval ( ) : Boolean

= <EOL> this is ModificationType . ElementRemoved && ( removedElement as? KtExpression ) ? . isContractDescriptionCallPsiCheck ( ) == true

/**
 * Contract changes are always out-of-block modifications. If a contract is removed all at once, e.g. via [PsiElement.delete],
 * [isElementInsideBody] will not see the removed contract inside the PSI *after* removal and treat the change as an in-block
 * modification. "Before removal" events aren't necessarily paired up with "after removal" events in the IDE, so we cannot rely on the
 * presence of the contract statement in some "before removal" event.
 *
 * [isContractRemoval] has to analyze the removed element out of context, as it has already been removed from its parent PSI. There
 * might occasionally be false positives, for example removing the contract statement from:
 *
 * ```
 * if (condition) {
 * contract { ... }
 * }
 * ```
 *
 * As it is not a valid contract statement, its removal doesn't need to trigger an out-of-block modification. Nonetheless, as such a
 * situation should not occur frequently, false positives are acceptable and this simplifies the analysis, making it less error-prone.
 */


fun elementToRehighlight ( changedElement : PsiElement ) : PsiElement ?

{ <EOL> return nonLocalDeclarationForLocalChange ( changedElement ) <EOL> }

/**
 * @return the psi element (ancestor of the changedElement) which should be re-highlighted in case of in-block changes or null if unsure
 */


internal fun bodyResolved ( element : FirElementWithResolveState , phase : FirResolvePhase )

{ <EOL> when ( element ) { <EOL> is FirSimpleFunction -> { <EOL> if ( phase != FirResolvePhase . BODY_RESOLVE ) return <EOL> } <EOL> is FirProperty -> { <EOL> if ( phase != FirResolvePhase . BODY_RESOLVE && phase != FirResolvePhase . IMPLICIT_TYPES_BODY_RESOLVE ) return <EOL> } <EOL> is FirCodeFragment -> { <EOL> if ( phase != FirResolvePhase . BODY_RESOLVE ) return <EOL> } <EOL> else -> return <EOL> } <EOL> val declaration = element . source ? . psi as? KtAnnotated ? : return <EOL> when ( declaration ) { <EOL> is KtNamedFunction -> { <EOL> if ( declaration . isReanalyzableContainer ( ) ) { <EOL> declaration . hasFirBody = true <EOL> } <EOL> } <EOL> is KtProperty -> { <EOL> if ( declaration . isReanalyzableContainer ( ) || declaration . accessors . any ( KtPropertyAccessor :: isReanalyzableContainer ) ) { <EOL> declaration . hasFirBody = true <EOL> } <EOL> } <EOL> is KtCodeFragment -> { <EOL> declaration . hasFirBody = true <EOL> } <EOL> } <EOL> }

/**
 * This function have to be called from Low Level FIR body transformers.
 * It is fine to have false-positives, but false-negatives are not acceptable.
 */


internal fun PsiElement . getNonLocalReanalyzableContainingDeclaration ( ) : KtDeclaration ?

{ <EOL> return when ( val declaration = getNonLocalContainingOrThisDeclaration ( ) ) { <EOL> is KtNamedFunction -> declaration . takeIf { function -> <EOL> function . isReanalyzableContainer ( ) && isElementInsideBody ( declaration = function , child = this ) <EOL> } <EOL> is KtPropertyAccessor -> declaration . takeIf { accessor -> <EOL> accessor . isReanalyzableContainer ( ) && isElementInsideBody ( declaration = accessor , child = this ) <EOL> } <EOL> is KtProperty -> declaration . takeIf { property -> <EOL> property . isReanalyzableContainer ( ) && property . delegateExpressionOrInitializer ? . isAncestor ( this ) == true <EOL> } <EOL> else -> null <EOL> } <EOL> }

/**
 * Covered by org.jetbrains.kotlin.analysis.low.level.api.fir.file.structure.AbstractInBlockModificationTest
 * on the compiler side and by
 * org.jetbrains.kotlin.idea.fir.analysis.providers.trackers.AbstractProjectWideOutOfBlockKotlinModificationTrackerTest
 * on the plugin part
 *
 * @return The declaration in which a change of the passed receiver parameter can be treated as in-block modification
 */


private fun TypeSystemCommonSuperTypesContext . allCommonSuperTypeConstructors ( types : List < SimpleTypeMarker > , stateStubTypesEqualToAnything : TypeCheckerState ) : List < TypeConstructorMarker >

{ <EOL> val result = collectAllSupertypes ( types . first ( ) , stateStubTypesEqualToAnything ) <EOL> for ( type in types ) { <EOL> if ( type === types . first ( ) ) continue <EOL> result . retainAll ( collectAllSupertypes ( type , stateStubTypesEqualToAnything ) ) <EOL> } <EOL> return result . filterNot { target -> <EOL> result . any { other -> <EOL> other != target && other . supertypes ( ) . any { it . typeConstructor ( ) == target } <EOL> } <EOL> } <EOL> }

/**
 * Note that if there is captured type C, then no one else is not subtype of C => lowerType cannot help here
 */