inline fun < R > withClassScopes ( firClass : FirClass , crossinline actionInsideStaticScope : ( ) -> Unit = { } , crossinline action : ( ) -> R , ) : R

= withScopeCleanup { <EOL> if ( removeOuterTypeParameterScope ( firClass ) ) { <EOL> this . scopes = staticScopes <EOL> } <EOL> actionInsideStaticScope ( ) <EOL> val superTypes = lookupSuperTypes ( firClass , lookupInterfaces = false , deep = true , substituteTypes = true , useSiteSession = session ) . asReversed ( ) <EOL> val scopesToAdd = mutableListOf < FirScope > ( ) <EOL> for ( superType in superTypes ) { <EOL> superType . lookupTag . getNestedClassifierScope ( session , scopeSession ) ? . let { nestedClassifierScope -> <EOL> val scope = nestedClassifierScope . wrapNestedClassifierScopeWithSubstitutionForSuperType ( superType , session ) <EOL> scopesToAdd . add ( scope ) <EOL> } <EOL> } <EOL> if ( firClass is FirRegularClass ) { <EOL> firClass . companionObjectSymbol ? . fir <EOL> ? . let ( session :: nestedClassifierScope ) <EOL> ? . let ( scopesToAdd :: add ) <EOL> session . nestedClassifierScope ( firClass ) ? . let ( scopesToAdd :: add ) <EOL> addScopes ( scopesToAdd ) <EOL> addTypeParametersScope ( firClass ) <EOL> } else { <EOL> session . nestedClassifierScope ( firClass ) ? . let ( scopesToAdd :: add ) <EOL> addScopes ( scopesToAdd ) <EOL> } <EOL> action ( ) <EOL> }

/**
 * Changes to the order of scopes should also be reflected in
 * [org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.BodyResolveContext.withScopesForClass].
 * Otherwise, we get different behavior between type resolve and body resolve phases.
 */


private fun FirVariable . moveOrDeleteIrrelevantAnnotations ( )

{ <EOL> if ( annotations . isEmpty ( ) ) return <EOL> val backingFieldAnnotations by lazy ( LazyThreadSafetyMode . NONE ) { backingField ? . annotations ? . toMutableList ( ) ? : mutableListOf ( ) } <EOL> var replaceBackingFieldAnnotations = false <EOL> replaceAnnotations ( annotations . filter { annotation -> <EOL> when ( annotation . useSiteTarget ) { <EOL> null -> { <EOL> val allowedTargets = annotation . useSiteTargetsFromMetaAnnotation ( session ) <EOL> when { <EOL> this is FirValueParameter -> CONSTRUCTOR_PARAMETER in allowedTargets <EOL> this . source ? . kind == KtFakeSourceElementKind . PropertyFromParameter && CONSTRUCTOR_PARAMETER in allowedTargets -> false <EOL> this is FirProperty && backingField != null && annotationShouldBeMovedToField ( allowedTargets ) -> { <EOL> backingFieldAnnotations += annotation <EOL> replaceBackingFieldAnnotations = true <EOL> false <EOL> } <EOL> else -> true <EOL> } <EOL> } <EOL> else -> true <EOL> } <EOL> } ) <EOL> if ( replaceBackingFieldAnnotations ) { <EOL> backingField ? . replaceAnnotations ( backingFieldAnnotations ) <EOL> } <EOL> }

/**
 * Filters annotations by target.
 * For example, in the following snippet the annotation may apply to the constructor value parameter, the property or the underlying field:
 * ```
 * class Foo(@Ann val x: String)
 * ```
 * This ambiguity may be resolved by specifying the use-site explicitly, i.e. `@field:Ann` or by analysing the allowed targets from
 * the [kotlin.annotation.Target] meta-annotation.
 * In latter case, the method will ensure that the annotation is moved to the correct element (field or parameter) or left at the property.
 */


fun resnet50additionalTrainingNoTopWithHelper ( )

{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CVnoTop . ResNet50 ( inputShape = intArrayOf ( IMAGE_SIZE , IMAGE_SIZE , NUM_CHANNELS ) ) <EOL> val noTopModel = modelHub . loadModel ( modelType ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> val topModel = Sequential . of ( GlobalAvgPool2D ( name = "<STR_LIT>" , ) , Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) , Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = NUM_CLASSES , activation = Activations . Linear ) , noInput = true ) <EOL> val model = Functional . of ( pretrainedModel = noTopModel , topModel = topModel ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsCatsSmallDatasetPath ( ) ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , modelType . createPreprocessing ( model ) ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> val accuracyBeforeTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , batchSize = TRAINING_BATCH_SIZE , epochs = EPOCHS ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the transfer learning concept on ResNet'50 model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - All layers, excluding the last [Dense], are added to the new Neural Network, its weights are frozen.
 * - New Dense layers are added and initialized via defined initializers.
 * - Model is re-trained on [dogsCatsSmallDatasetPath] dataset.
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 * We demonstrate the workflow on the subset of Kaggle Cats vs Dogs binary classification dataset.
 */


= resnet50additionalTrainingNoTopWithHelper ( )


internal fun Project . compositeBuildRootProject ( block : ( Project ) -> Unit )

= compositeBuildRootGradle . rootProject ( block )

/**
 * Run block function on root project of the root build in composite build only when a root project becomes available
 */


override fun visitClass ( declaration : IrClass , data : KeepData )

{ <EOL> val prevShouldBeKept = data . classShouldBeKept <EOL> val prevClassInKeep = data . classInKeep <EOL> data . classShouldBeKept = false <EOL> val keptClass = data . classInKeep || isInKeep ( declaration ) <EOL> if ( keptClass ) { <EOL> keptDeclarations . add ( declaration ) <EOL> } <EOL> data . classInKeep = keptClass <EOL> super . visitClass ( declaration , data ) <EOL> if ( data . classShouldBeKept ) { <EOL> keptDeclarations . add ( declaration ) <EOL> } <EOL> data . classShouldBeKept = prevShouldBeKept <EOL> data . classInKeep = prevClassInKeep <EOL> }

/** Keep declarations can work both ways
 * if member of a class is in keep, the class should be also kept
 * if a class is kept, members of the class should be also kept
 * but there can be nested classes, and for nested classes we need only to propagate "keep" from top-level to nested (not vice versa)
 * because we have 2 directions, we need 2 boolean flags
 * [KeepData.classInKeep] responsible to propagate "keep" from class level to members direction
 * [KeepData.classShouldBeKept] responsible to bubble "keep" from members to class level direction
 */


abstract fun compileModuleChunk ( commonArguments : CommonCompilerArguments , dirtyFilesHolder : KotlinDirtySourceFilesHolder , environment : JpsCompilerEnvironment , buildMetricReporter : JpsBuilderMetricReporter ? <EOL> ) : Boolean

/**
 * Called for `ModuleChunk.representativeTarget`
 */


open fun updateChunkMappings ( localContext : CompileContext , chunk : ModuleChunk , dirtyFilesHolder : KotlinDirtySourceFilesHolder , outputItems : Map < ModuleBuildTarget , Iterable < GeneratedFile > > , incrementalCaches : Map < KotlinModuleBuildTarget < * > , JpsIncrementalCache > , environment : JpsCompilerEnvironment )

{ <EOL> }


protected fun collectSourcesToCompile ( dirtyFilesHolder : KotlinDirtySourceFilesHolder )

= SourcesToCompile ( sources = when { <EOL> chunk . representativeTarget . isIncrementalCompilationEnabled -> <EOL> dirtyFilesHolder . getDirtyFiles ( jpsModuleBuildTarget ) . values <EOL> else -> sources . values <EOL> } , removedFiles = dirtyFilesHolder . getRemovedFiles ( jpsModuleBuildTarget ) )

/**
 * Should be used only for particular target in chunk (jvm)
 *
 * Should not be cached since may be vary in different rounds.
 */


{ <EOL> val hasRemovedSources = removedFiles . isNotEmpty ( ) <EOL> val hasDirtyOrRemovedSources = allFiles . isNotEmpty ( ) || hasRemovedSources <EOL> if ( hasDirtyOrRemovedSources ) { <EOL> val logger = jpsGlobalContext . loggingManager . projectBuilderLogger <EOL> if ( logger . isEnabled ) { <EOL> logger . logCompiledFiles ( allFiles , KotlinBuilder . KOTLIN_BUILDER_NAME , "<STR_LIT>" ) <EOL> } <EOL> } <EOL> return hasDirtyOrRemovedSources <EOL> }

/**
 * @return true, if there are removed files or files to compile
 */


internal fun < T > sortTopologically ( start : T , nextNodes : ( T ) -> Collection < T > ) : List < T >

{ <EOL> val visited = mutableSetOf < T > ( ) <EOL> val grayStack : Stack < T > = mutableListOf ( ) <EOL> recursiveTopologicalSort ( start , grayStack , visited , nextNodes ) <EOL> val sortedList = mutableListOf < T > ( ) <EOL> while ( grayStack . isNotEmpty ( ) ) <EOL> sortedList . add ( grayStack . pop ( ) ! ! ) <EOL> return sortedList <EOL> }

/**
 * Topologically sort nodes in the DAG defined by a provided start node and a function returning next nodes.
 * @param [start] a node from which to start the sort
 * @param [nextNodes] a function which returns a collection of next nodes for a given node
 * @return a list of topologically sorted nodes in the graph
 */


public inline fun < reified T > emptyOf ( ) : DataFrame < T >

= createEmptyDataFrameOf ( T :: class ) . cast ( )

/**
 * Creates a DataFrame with empty columns (rows = 0).
 * Can be used as a "null object" in aggregation operations, operations that work on columns (select, reorder, ...)
 *
 */


public fun empty ( schema : DataFrameSchema ) : AnyFrame

= schema . createEmptyDataFrame ( )

/**
 * Creates a DataFrame with empty columns (rows = 0).
 * Can be used as a "null object" in aggregation operations, operations that work on columns (select, reorder, ...)
 */


override fun < C > get ( columns : ColumnsSelector < T , C > ) : List < DataColumn < C > >

= <EOL> getColumnsImpl ( UnresolvedColumnsPolicy . Fail , columns )

/**
 * Returns a list of columns selected by [columns], a [ColumnsSelectionDsl].
 *
 * NOTE: This doesn't work in [ColumnsSelectionDsl], use [ColumnsSelectionDsl.cols] to select columns by predicate.
 */


public operator fun < T , C > DataFrame < T > . get ( columns : ColumnsSelector < T , C > ) : List < DataColumn < C > >

= <EOL> this . get ( columns )

/**
 * Returns a list of columns selected by [columns], a [ColumnsSelectionDsl].
 */


fun KtModifierKeywordToken . toVisibilityOrNull ( ) : Visibility ?

{ <EOL> return when ( this ) { <EOL> KtTokens . PUBLIC_KEYWORD -> Visibilities . Public <EOL> KtTokens . PRIVATE_KEYWORD -> Visibilities . Private <EOL> KtTokens . PROTECTED_KEYWORD -> Visibilities . Protected <EOL> KtTokens . INTERNAL_KEYWORD -> Visibilities . Internal <EOL> else -> null <EOL> } <EOL> }

/**
 * Returns Visibility by token or null
 */


fun KtSourceElement . findContextReceiverListSource ( ) : KtLightSourceElement ?

{ <EOL> if ( this . lighterASTNode . tokenType == KtNodeTypes . CONTEXT_RECEIVER_LIST ) <EOL> return this . lighterASTNode . toKtLightSourceElement ( treeStructure ) <EOL> return treeStructure . findDescendantByType ( lighterASTNode , KtNodeTypes . CONTEXT_RECEIVER_LIST , false ) ? . toKtLightSourceElement ( treeStructure ) <EOL> }

/**
 * Locates first [CONTEXT_RECEIVER_LIST] and returns position in source.
 */


fun findMetadataPackageParts ( packageFqName : String ) : List < String >

/**
 * @return simple names of .kotlin_metadata files that store data for top level declarations in the package with the given FQ name
 */


fun publishLibraryVariants ( vararg names : String )

{ <EOL> publishLibraryVariants = publishLibraryVariants . orEmpty ( ) + names <EOL> }

/** Add Android library variant names to [publishLibraryVariants]. */


{ <EOL> publishLibraryVariants = null <EOL> }

/** Set up all of the Android library variants to be published from this target's project within the default publications, which are
 * set up if the `maven-publish` Gradle plugin is applied. This overrides the variants chosen with [publishLibraryVariants] */


private fun createSourcesElementsIfNeeded ( variantName : String , apiElementsConfigurationName : String , sourcesElementsConfigurationName : String , ) : Configuration

{ <EOL> val existingConfiguration = project . configurations . findByName ( sourcesElementsConfigurationName ) <EOL> if ( existingConfiguration != null ) return existingConfiguration <EOL> val apiElementsConfiguration = project . configurations . findConsumable ( apiElementsConfigurationName ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> return project . configurations . createConsumable ( sourcesElementsConfigurationName ) . apply { <EOL> description = "<STR_LIT>" <EOL> isVisible = false <EOL> apiElementsConfiguration . copyAttributesTo ( project , dest = this ) <EOL> configureSourcesPublicationAttributes ( this @ KotlinAndroidTarget ) <EOL> } <EOL> }

/**
 * TODO: Ask Google about providing such configuration where they could set their attributes and control them.
 * Just like as they do with apiElements or runtimeElements
 */


private fun filterOutAndroidVariantAttribute ( attribute : Attribute < * > , ) : Boolean

= <EOL> attribute . name != "<STR_LIT>" && <EOL> attribute . name != "<STR_LIT>"

/** We filter this variant out as it is never requested on the consumer side, while keeping it leads to ambiguity between Android and
 * JVM variants due to non-nesting sets of unmatched attributes. */


@ ExternalApi <EOL> public fun List < ClassBinarySignature > . extractAnnotatedPackages ( targetAnnotations : Set < String > ) : List < String >

{ <EOL> if ( targetAnnotations . isEmpty ( ) ) return emptyList ( ) <EOL> return filter { <EOL> it . name . endsWith ( "<STR_LIT>" ) <EOL> } . filter { <EOL> it . access . isInterface && it . access . isSynthetic && it . access . isAbstract <EOL> } . filter { <EOL> it . annotations . any { <EOL> ann -> targetAnnotations . any { ann . refersToName ( it ) } <EOL> } <EOL> } . map { <EOL> val res = it . name . substring ( <NUM_LIT:0> , it . name . length - "<STR_LIT>" . length ) <EOL> res <EOL> } <EOL> }

/**
 * Extracts name of packages annotated by one of the [targetAnnotations].
 * If there are no such packages, returns an empty list.
 *
 * Package is checked for being annotated by looking at classes with `package-info` name
 * ([see JSL 7.4.1](https://docs.oracle.com/javase/specs/jls/se21/html/jls-7.html#jls-7.4)
 * for details about `package-info`).
 */


override fun testCase ( testCase : XCTestCase , didRecordIssue : XCTIssue )

{ <EOL> if ( testCase is XCTestCaseWrapper ) { <EOL> val duration = testCase . getTestDuration ( ) <EOL> val error = didRecordIssue . associatedError as NSError <EOL> val throwable = if ( error is NSErrorWithKotlinException ) { <EOL> error . kotlinException <EOL> } else { <EOL> Throwable ( didRecordIssue . compactDescription ) <EOL> } <EOL> sendToListeners { fail ( testCase . testCase , throwable , duration . inWholeMilliseconds ) } <EOL> } <EOL> }

/**
 * Failed test case execution.
 *
 * Records test failures sending them to test listeners.
 */


override fun testCase ( testCase : XCTestCase , didRecordExpectedFailure : XCTExpectedFailure )

{ <EOL> logger . log ( "<STR_LIT>" ) <EOL> this . testCase ( testCase , didRecordExpectedFailure . issue ) <EOL> }

/**
 * Records expected failures as failed test as soon as such expectations should be processed in the test.
 */


override fun testCaseDidFinish ( testCase : XCTestCase )

{ <EOL> val duration = testCase . getTestDuration ( ) <EOL> if ( testCase . testRun ? . hasSucceeded == true ) { <EOL> if ( testCase is XCTestCaseWrapper ) { <EOL> val test = testCase . testCase <EOL> if ( ! test . ignored ) sendToListeners { pass ( test , duration . inWholeMilliseconds ) } <EOL> } <EOL> } <EOL> }

/**
 * Test case finish notification.
 * Both successful and failed executions get this notification.
 */


override fun testCaseWillStart ( testCase : XCTestCase )

{ <EOL> if ( testCase is XCTestCaseWrapper ) { <EOL> val test = testCase . testCase <EOL> if ( test . ignored ) { <EOL> sendToListeners { ignore ( test ) } <EOL> } else { <EOL> sendToListeners { start ( test ) } <EOL> } <EOL> } <EOL> }

/**
 * Test case start notification.
 */


override fun testSuite ( testSuite : XCTestSuite , didRecordIssue : XCTIssue )

{ <EOL> logger . log ( "<STR_LIT>" ) <EOL> }

/**
 * Test suite failure notification.
 *
 * Logs the failure of the test suite execution.
 */


override fun testSuite ( testSuite : XCTestSuite , didRecordExpectedFailure : XCTExpectedFailure )

{ <EOL> logger . log ( "<STR_LIT>" ) <EOL> this . testSuite ( testSuite , didRecordExpectedFailure . issue ) <EOL> }

/**
 * Test suite expected failure.
 *
 * Logs the failure of the test suite execution.
 * Treat expected failures as ordinary unexpected one.
 */


override fun testSuiteDidFinish ( testSuite : XCTestSuite )

{ <EOL> val duration = testSuite . getTestDuration ( ) . inWholeMilliseconds <EOL> if ( testSuite is XCTestSuiteWrapper ) { <EOL> sendToListeners { finishSuite ( testSuite . testSuite , duration ) } <EOL> } else if ( testSuite . name == TOP_LEVEL_SUITE ) { <EOL> sendToListeners { <EOL> finishIteration ( testSettings , <NUM_LIT:0> , duration ) <EOL> finishTesting ( testSettings , duration ) <EOL> } <EOL> } <EOL> }

/**
 * Test suite finish notification.
 */


override fun testSuiteWillStart ( testSuite : XCTestSuite )

{ <EOL> if ( testSuite is XCTestSuiteWrapper ) { <EOL> sendToListeners { startSuite ( testSuite . testSuite ) } <EOL> } else if ( testSuite . name == TOP_LEVEL_SUITE ) { <EOL> sendToListeners { <EOL> startTesting ( testSettings ) <EOL> startIteration ( testSettings , <NUM_LIT:0> , testSettings . testSuites ) <EOL> } <EOL> } <EOL> }

/**
 * Test suite start notification.
 */


fun preprocessCommandLineArguments ( args : List < String > , errors : Lazy < ArgumentParseErrors > ) : List < String >

= <EOL> args . flatMap { arg -> <EOL> if ( arg . isArgfileArgument ) { <EOL> File ( arg . argfilePath ) . expand ( errors . value ) <EOL> } else if ( arg . isDeprecatedArgfileArgument ) { <EOL> errors . value . deprecatedArguments [ EXPERIMENTAL_ARGFILE_ARGUMENT ] = ARGFILE_ARGUMENT <EOL> File ( arg . deprecatedArgfilePath ) . expand ( errors . value ) <EOL> } else { <EOL> listOf ( arg ) <EOL> } <EOL> }

/**
 * Performs initial preprocessing of arguments, passed to the compiler.
 * This is done prior to *any* arguments parsing, and result of preprocessing
 * will be used instead of actual passed arguments.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun java . util . regex . Pattern . toRegex ( ) : Regex

= Regex ( this )

/**
 * Converts this [java.util.regex.Pattern] to an instance of [Regex].
 *
 * Provides the way to use Regex API on the instances of [java.util.regex.Pattern].
 */


= <EOL> if ( value == null ) { <EOL> DAEMON <EOL> } else { <EOL> values ( ) . find { it . propertyValue . equals ( value , ignoreCase = true ) } <EOL> ? : error ( "<STR_LIT>" ) <EOL> }


{ <EOL> val ( _ , test ) = fashionMnist ( ) <EOL> val jsonConfigFile = getJSONConfigFileToyResNet ( ) <EOL> val model = Functional . loadModelConfiguration ( jsonConfigFile ) <EOL> var copiedModel : Functional <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = getWeightsFileToyResNet ( ) <EOL> it . loadWeights ( hdfFile ) <EOL> copiedModel = it . copy ( copyWeights = true ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = <NUM_LIT> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> copiedModel . use { <EOL> copiedModel . logSummary ( ) <EOL> val accuracy = copiedModel . evaluate ( dataset = test , batchSize = <NUM_LIT> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/** Just loading ToyResNet trained in Keras, making a copy and using for prediction. */


inline fun < reified T : Number > prod ( a : KtNDArray < T > ) : T

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , None . none , a . dtype ) , kClass = T :: class )

/**
 * Return the product of array elements over a given axis.
 */


inline fun < reified T : Number > sum ( a : KtNDArray < T > ) : T

/**
 * Sum of array elements over a given axis.
 */


inline fun < reified T : Number > nanprod ( a : KtNDArray < T > ) : T

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

/**
 * Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.
 */


inline fun < reified T : Number > nansum ( a : KtNDArray < T > ) : T

/**
 * Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
 */


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

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

/**
 * Return the cumulative product of elements along a given axis.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < T : Number > cumsum ( a : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >

/**
 * Return the cumulative sum of the elements along a given axis.
 */


fun < T : Number > nancumprod ( a : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >

/**
 * Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one.
 */


fun < T : Number > nancumsum ( a : KtNDArray < T > , axis : Int ? = null ) : KtNDArray < T >

/**
 * Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
 */


fun < T : Number > diff ( a : KtNDArray < T > , n : Int = <NUM_LIT:1> , axis : Int = - <NUM_LIT:1> ) : KtNDArray < T >

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

/**
 * Calculate the n-th discrete difference along the given axis.
 */


fun < T : Number > ediff1d ( ary : KtNDArray < T > , toEnd : KtNDArray < T > ? = null , toStart : KtNDArray < T > ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( ary , toEnd ? : None . none , toStart ? : None . none ) )

/**
 * The differences between consecutive elements of an array.
 */


fun < T : Any > gradient1D ( f : KtNDArray < T > ) : KtNDArray < Double >

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

/**
 * Return the gradient of an one-dimensional array.
 */


fun < T : Any > gradientND ( f : KtNDArray < T > ) : List < KtNDArray < Double > >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( f ) , kClass = List :: class ) as List < KtNDArray < Double > >

/**
 * Return the gradient of an N-dimensional array.
 */


fun < T : Number , E : Number > cross ( a : KtNDArray < T > , b : KtNDArray < E > , axisa : Int = - <NUM_LIT:1> , axisb : Int = - <NUM_LIT:1> , axisc : Int = - <NUM_LIT:1> , axis : Int ? = null ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , b , axisa , axisb , axisc , axis ? : None . none ) )

/**
 * Return the cross product of two (arrays of) vectors.
 */


fun < T : Number > trapz ( y : KtNDArray < T > , x : KtNDArray < out Number > ? = null , dx : Double = <NUM_LIT:1.0> ) : Double

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( y , x ? : None . none , dx ) , kClass = Double :: class )

/**
 * Integrate along the given axis using the composite trapezoidal rule.
 */


{ <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = ONNXModels . FaceAlignment . Fan2d106 <EOL> val model = modelHub . loadModel ( modelType ) <EOL> model . printSummary ( ) <EOL> model . use { <EOL> println ( it ) <EOL> val preprocessor = pipeline < BufferedImage > ( ) <EOL> . resize { <EOL> outputHeight = <NUM_LIT> <EOL> outputWidth = <NUM_LIT> <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . call ( modelType . preprocessor ) <EOL> val result = mutableMapOf < BufferedImage , List < Landmark > > ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputFile = getFileFromResource ( "<STR_LIT>" ) <EOL> val inputImage = ImageConverter . toBufferedImage ( inputFile ) <EOL> val inputData = preprocessor . apply ( inputImage ) <EOL> val floats = it . predict ( inputData ) { output -> output . getFloatArray ( "<STR_LIT>" ) } <EOL> println ( floats . contentToString ( ) ) <EOL> val landMarks = mutableListOf < Landmark > ( ) <EOL> for ( j in floats . indices step <NUM_LIT:2> ) { <EOL> landMarks . add ( Landmark ( ( <NUM_LIT:1> + floats [ j ] ) / <NUM_LIT:2> , ( <NUM_LIT:1> + floats [ j + <NUM_LIT:1> ] ) / <NUM_LIT:2> ) ) <EOL> } <EOL> result [ inputImage ] = landMarks <EOL> } <EOL> val panel = JPanel ( GridLayout ( <NUM_LIT:2> , <NUM_LIT:4> ) ) <EOL> val resize = pipeline < BufferedImage > ( ) . resize { outputWidth = <NUM_LIT> ; outputHeight = <NUM_LIT> } <EOL> for ( ( image , landmarks ) in result ) { <EOL> panel . add ( createDetectedLandmarksPanel ( resize . apply ( image ) , landmarks ) ) <EOL> } <EOL> showFrame ( "<STR_LIT>" , panel ) <EOL> } <EOL> }

/**
 * This examples demonstrates the light-weight inference API with [Fan2D106FaceAlignmentModel] on Fan2d106 model:
 * - Model is obtained from [ONNXModelHub].
 * - Model predicts landmarks on a few images located in resources.
 * - The detected landmarks are drawn on the images used for prediction.
 */


private fun Candidate . isSyntheticFunctionCallThatShouldUseEqualityConstraint ( expectedType : ConeKotlinType ) : Boolean

{ <EOL> if ( components . context . isInsideAssignmentRhs ) return false <EOL> val symbol = symbol as? FirCallableSymbol ? : return false <EOL> if ( symbol . origin != FirDeclarationOrigin . Synthetic . FakeFunction || expectedType . isUnitOrNullableUnit || expectedType . isAnyOrNullableAny || ( symbol . callableId == SyntheticCallableId . CHECK_NOT_NULL && expectedType . canBeNull ( session ) ) ) { <EOL> return false <EOL> } <EOL> if ( system . allTypeVariables . values . any { <EOL> it is ConeTypeParameterBasedTypeVariable && it . typeParameterSymbol . containingDeclarationSymbol . isSyntheticElvisFunction ( ) <EOL> } ) { <EOL> return false <EOL> } <EOL> return true <EOL> }

/**
 * For synthetic functions (when, try, !!, but **not** elvis), we need to add an equality constraint for the expected type
 * so that some type variables aren't inferred to `Nothing` that appears in one of the branches.
 *
 * @See org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createKnownTypeParameterSubstitutorForSpecialCall
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> @ OptIn ( ExperimentalSerializationApi :: class ) <EOL> public fun buildClassSerialDescriptor ( serialName : String , vararg typeParameters : SerialDescriptor , builderAction : ClassSerialDescriptorBuilder . ( ) -> Unit = { } ) : SerialDescriptor

{ <EOL> require ( serialName . isNotBlank ( ) ) { "<STR_LIT>" } <EOL> val sdBuilder = ClassSerialDescriptorBuilder ( serialName ) <EOL> sdBuilder . builderAction ( ) <EOL> return SerialDescriptorImpl ( serialName , StructureKind . CLASS , sdBuilder . elementNames . size , typeParameters . toList ( ) , sdBuilder ) <EOL> }

/**
 * Builder for [SerialDescriptor].
 * The resulting descriptor will be uniquely identified by the given [serialName], [typeParameters] and
 * elements structure described in [builderAction] function.
 *
 * Example:
 * ```
 * // Class with custom serializer and custom serial descriptor
 * class Data(
 * val intField: Int, // This field is ignored by custom serializer
 * val longField: Long, // This field is written as long, but in serialized form is named as "_longField"
 * val stringList: List<String> // This field is written as regular list of strings
 * val nullableInt: Int?
 * )
 * // Descriptor for such class:
 * buildClassSerialDescriptor("my.package.Data") {
 * // intField is deliberately ignored by serializer -- not present in the descriptor as well
 * element<Long>("_longField") // longField is named as _longField
 * element("stringField", listSerialDescriptor<String>()) // or ListSerializer(String.serializer()).descriptor
 * element("nullableInt", serialDescriptor<Int>().nullable)
 * }
 * ```
 *
 * Example for generic classes:
 * ```
 * import kotlinx.serialization.builtins.*
 *
 * @Serializable(CustomSerializer::class)
 * class BoxedList<T>(val list: List<T>)
 *
 * class CustomSerializer<T>(tSerializer: KSerializer<T>): KSerializer<BoxedList<T>> {
 * // here we use tSerializer.descriptor because it represents T
 * override val descriptor = buildClassSerialDescriptor("pkg.BoxedList", tSerializer.descriptor) {
 * // here we have to wrap it with List first, because property has type List<T>
 * element("list", ListSerializer(tSerializer).descriptor) // or listSerialDescriptor(tSerializer.descriptor)
 * }
 * }
 * ```
 */


public fun PrimitiveSerialDescriptor ( serialName : String , kind : PrimitiveKind ) : SerialDescriptor

{ <EOL> require ( serialName . isNotBlank ( ) ) { "<STR_LIT>" } <EOL> return PrimitiveDescriptorSafe ( serialName , kind ) <EOL> }

/**
 * Factory to create a trivial primitive descriptors.
 * Primitive descriptors should be used when the serialized form of the data has a primitive form, for example:
 * ```
 * object LongAsStringSerializer : KSerializer<Long> {
 * override val descriptor: SerialDescriptor =
 * PrimitiveSerialDescriptor("kotlinx.serialization.LongAsStringSerializer", PrimitiveKind.STRING)
 *
 * override fun serialize(encoder: Encoder, value: Long) {
 * encoder.encodeString(value.toString())
 * }
 *
 * override fun deserialize(decoder: Decoder): Long {
 * return decoder.decodeString().toLong()
 * }
 * }
 * ```
 */


@ ExperimentalSerializationApi <EOL> public fun SerialDescriptor ( serialName : String , original : SerialDescriptor ) : SerialDescriptor

{ <EOL> require ( serialName . isNotBlank ( ) ) { "<STR_LIT>" } <EOL> require ( original . kind !is PrimitiveKind ) { "<STR_LIT>" } <EOL> require ( serialName != original . serialName ) { "<STR_LIT>" } <EOL> return WrappedSerialDescriptor ( serialName , original ) <EOL> }

/**
 * Factory to create a new descriptor that is identical to [original] except that the name is equal to [serialName].
 * Should be used when you want to serialize a type as another non-primitive type.
 * Don't use this if you want to serialize a type as a primitive value, use [PrimitiveSerialDescriptor] instead.
 *
 * Example:
 * ```
 * @Serializable(CustomSerializer::class)
 * class CustomType(val a: Int, val b: Int, val c: Int)
 *
 * class CustomSerializer: KSerializer<CustomType> {
 * override val descriptor = SerialDescriptor("CustomType", IntArraySerializer().descriptor)
 *
 * override fun serialize(encoder: Encoder, value: CustomType) {
 * encoder.encodeSerializableValue(IntArraySerializer(), intArrayOf(value.a, value.b, value.c))
 * }
 *
 * override fun deserialize(decoder: Decoder): CustomType {
 * val array = decoder.decodeSerializableValue(IntArraySerializer())
 * return CustomType(array[0], array[1], array[2])
 * }
 * }
 * ```
 */


@ InternalSerializationApi <EOL> @ OptIn ( ExperimentalSerializationApi :: class ) <EOL> public fun buildSerialDescriptor ( serialName : String , kind : SerialKind , vararg typeParameters : SerialDescriptor , builder : ClassSerialDescriptorBuilder . ( ) -> Unit = { } ) : SerialDescriptor

{ <EOL> require ( serialName . isNotBlank ( ) ) { "<STR_LIT>" } <EOL> require ( kind != StructureKind . CLASS ) { "<STR_LIT>" } <EOL> val sdBuilder = ClassSerialDescriptorBuilder ( serialName ) <EOL> sdBuilder . builder ( ) <EOL> return SerialDescriptorImpl ( serialName , kind , sdBuilder . elementNames . size , typeParameters . toList ( ) , sdBuilder ) <EOL> }

/**
 * An unsafe alternative to [buildClassSerialDescriptor] that supports an arbitrary [SerialKind].
 * This function is left public only for migration of pre-release users and is not intended to be used
 * as generally-safe and stable mechanism. Beware that it can produce inconsistent or non spec-compliant instances.
 *
 * If you end up using this builder, please file an issue with your use-case in kotlinx.serialization issue tracker.
 */


public inline fun < reified T > serialDescriptor ( ) : SerialDescriptor

= serializer < T > ( ) . descriptor

/**
 * Retrieves descriptor of type [T] using reified [serializer] function.
 */


public fun serialDescriptor ( type : KType ) : SerialDescriptor

= serializer ( type ) . descriptor

/**
 * Retrieves descriptor of type associated with the given [KType][type]
 */


@ ExperimentalSerializationApi <EOL> public fun listSerialDescriptor ( elementDescriptor : SerialDescriptor ) : SerialDescriptor

{ <EOL> return ArrayListClassDesc ( elementDescriptor ) <EOL> }

/**
 * Creates a descriptor for the type `List<T>` where `T` is the type associated with [elementDescriptor].
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > listSerialDescriptor ( ) : SerialDescriptor

{ <EOL> return listSerialDescriptor ( serializer < T > ( ) . descriptor ) <EOL> }

/**
 * Creates a descriptor for the type `List<T>`.
 */


@ ExperimentalSerializationApi <EOL> public fun mapSerialDescriptor ( keyDescriptor : SerialDescriptor , valueDescriptor : SerialDescriptor ) : SerialDescriptor

{ <EOL> return HashMapClassDesc ( keyDescriptor , valueDescriptor ) <EOL> }

/**
 * Creates a descriptor for the type `Map<K, V>` where `K` and `V` are types
 * associated with [keyDescriptor] and [valueDescriptor] respectively.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified K , reified V > mapSerialDescriptor ( ) : SerialDescriptor

{ <EOL> return mapSerialDescriptor ( serializer < K > ( ) . descriptor , serializer < V > ( ) . descriptor ) <EOL> }

/**
 * Creates a descriptor for the type `Map<K, V>`.
 */


@ ExperimentalSerializationApi <EOL> public fun setSerialDescriptor ( elementDescriptor : SerialDescriptor ) : SerialDescriptor

{ <EOL> return HashSetClassDesc ( elementDescriptor ) <EOL> }

/**
 * Creates a descriptor for the type `Set<T>` where `T` is the type associated with [elementDescriptor].
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > setSerialDescriptor ( ) : SerialDescriptor

{ <EOL> return setSerialDescriptor ( serializer < T > ( ) . descriptor ) <EOL> }

/**
 * Creates a descriptor for the type `Set<T>`.
 */


public fun element ( elementName : String , descriptor : SerialDescriptor , annotations : List < Annotation > = emptyList ( ) , isOptional : Boolean = false )

{ <EOL> require ( uniqueNames . add ( elementName ) ) { "<STR_LIT>" } <EOL> elementNames += elementName <EOL> elementDescriptors += descriptor <EOL> elementAnnotations += annotations <EOL> elementOptionality += isOptional <EOL> }

/**
 * Add an element with a given [name][elementName], [descriptor],
 * type annotations and optionality the resulting descriptor.
 *
 * Example of usage:
 * ```
 * class Data(
 * val intField: Int? = null, // Optional, has default value
 * @ProtoNumber(1) val longField: Long
 * )
 *
 * // Corresponding descriptor
 * SerialDescriptor("package.Data") {
 * element<Int?>("intField", isOptional = true)
 * element<Long>("longField", annotations = listOf(protoIdAnnotationInstance))
 * }
 * ```
 */


public inline fun < reified T > ClassSerialDescriptorBuilder . element ( elementName : String , annotations : List < Annotation > = emptyList ( ) , isOptional : Boolean = false )

{ <EOL> val descriptor = serializer < T > ( ) . descriptor <EOL> element ( elementName , descriptor , annotations , isOptional ) <EOL> }

/**
 * A reified version of [element] function that
 * extract descriptor using `serializer<T>().descriptor` call with all the restrictions of `serializer<T>().descriptor`.
 */


@ Test <EOL> fun testAwaitCancellation ( )

= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> val observable = ObservableSource < Int > { s -> <EOL> s . onSubscribe ( object : Disposable { <EOL> override fun dispose ( ) { expect ( <NUM_LIT:4> ) } <EOL> override fun isDisposed ( ) : Boolean { expectUnreached ( ) ; return false } <EOL> } ) <EOL> } <EOL> val job = launch ( start = CoroutineStart . UNDISPATCHED ) { <EOL> try { <EOL> expect ( <NUM_LIT:2> ) <EOL> observable . awaitFirst ( ) <EOL> } catch ( e : CancellationException ) { <EOL> expect ( <NUM_LIT:5> ) <EOL> throw e <EOL> } <EOL> } <EOL> expect ( <NUM_LIT:3> ) <EOL> job . cancelAndJoin ( ) <EOL> finish ( <NUM_LIT:6> ) <EOL> }

/** Tests that calls to [awaitFirst] (and, thus, the other methods) throw [CancellationException] and dispose of
 * the subscription when their [Job] is cancelled. */


private fun FunctionDescriptor . hasDifferentParameterNames ( other : FunctionDescriptor ) : Boolean

{ <EOL> return valueParameters . drop ( <NUM_LIT:1> ) . map { it . name } != other . valueParameters . drop ( <NUM_LIT:1> ) . map { it . name } <EOL> }

/**
 * This function basically checks that these two functions have different objective-C signature.
 *
 * This signature consists of function name and parameter names except first.
 *
 * So we ignore the first parameter name, but check others
 */


fun verifyGolden ( testInfo : GoldenTransformTestInfo )

{ <EOL> if ( generateGoldens || ( ! goldenFile . exists ( ) && generateMissingGoldens ) || goldenFile . nameWithoutExtension in generateGoldenFiles ) { <EOL> saveGolden ( testInfo ) <EOL> } <EOL> if ( ! goldenFile . exists ( ) ) { <EOL> throw FileNotFoundException ( "<STR_LIT>" ) <EOL> } <EOL> val loadedTestInfo = try { <EOL> GoldenTransformTestInfo . fromEncodedString ( goldenFile . readText ( ) ) <EOL> } catch ( e : IllegalStateException ) { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> Assert . assertEquals ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" , loadedTestInfo . transformed , testInfo . transformed ) <EOL> }

/**
 * Verify the current test against the matching golden file.
 * If generateGoldens is true, the golden file will first be generated.
 */


@ JvmStatic <EOL> public fun invariant ( type : KType ) : KTypeProjection

= <EOL> KTypeProjection ( KVariance . INVARIANT , type )

/**
 * Creates an invariant projection of a given type. Invariant projection is just the type itself,
 * without any use-site variance modifiers applied to it.
 * For example, in the type `Set<String>`, `String` is an invariant projection of the type represented by the class `String`.
 */


@ JvmStatic <EOL> public fun contravariant ( type : KType ) : KTypeProjection

= <EOL> KTypeProjection ( KVariance . IN , type )

/**
 * Creates a contravariant projection of a given type, denoted by the `in` modifier applied to a type.
 * For example, in the type `MutableList<in Number>`, `in Number` is a contravariant projection of the type of class `Number`.
 */


@ JvmStatic <EOL> public fun covariant ( type : KType ) : KTypeProjection

= <EOL> KTypeProjection ( KVariance . OUT , type )

/**
 * Creates a covariant projection of a given type, denoted by the `out` modifier applied to a type.
 * For example, in the type `Array<out Number>`, `out Number` is a covariant projection of the type of class `Number`.
 */


public fun serializeToBuffer ( src : Array < FloatArray > , start : Int , length : Int ) : FloatBuffer

{ <EOL> val buffer = FloatBuffer . allocate ( length * src [ <NUM_LIT:0> ] . size ) <EOL> for ( i in start until start + length ) { <EOL> buffer . put ( src [ i ] ) <EOL> } <EOL> return ( buffer as Buffer ) . rewind ( ) as FloatBuffer <EOL> }

/** Converts [src] to [FloatBuffer] from [start] position for the next [length] positions. */


public fun serializeToBuffer ( src : Array < FloatArray > ) : FloatBuffer

{ <EOL> val buffer = FloatBuffer . allocate ( src . size * src [ <NUM_LIT:0> ] . size ) <EOL> for ( element in src ) { <EOL> buffer . put ( element ) <EOL> } <EOL> return ( buffer as Buffer ) . rewind ( ) as FloatBuffer <EOL> }


public fun serializeToBuffer ( src : FloatArray ) : FloatBuffer

{ <EOL> val buffer = FloatBuffer . allocate ( src . size ) <EOL> buffer . put ( src ) <EOL> return ( buffer as Buffer ) . rewind ( ) as FloatBuffer <EOL> }


public fun serializeLabelsToBuffer ( src : FloatArray , amountOfClasses : Long ) : FloatBuffer

{ <EOL> val oneHotEncodedLabels = Array ( src . size ) { <EOL> FloatArray ( amountOfClasses . toInt ( ) ) { <NUM_LIT:0.0f> } <EOL> } <EOL> for ( i in src . indices ) { <EOL> val label = src [ i ] <EOL> if ( amountOfClasses == <NUM_LIT:1L> ) { <EOL> oneHotEncodedLabels [ i ] [ <NUM_LIT:0> ] = label <EOL> } else { <EOL> require ( <NUM_LIT:0.0f> <= label && label < amountOfClasses ) { "<STR_LIT>" } <EOL> oneHotEncodedLabels [ i ] [ label . toInt ( ) ] = <NUM_LIT> <EOL> } <EOL> } <EOL> val buffer = FloatBuffer . allocate ( oneHotEncodedLabels . size * oneHotEncodedLabels [ <NUM_LIT:0> ] . size ) <EOL> for ( element in oneHotEncodedLabels ) { <EOL> buffer . put ( element ) <EOL> } <EOL> return ( buffer as Buffer ) . rewind ( ) as FloatBuffer <EOL> }


private fun Candidate . mightBeAnalyzedAndCompletedIndependently ( ) : Boolean

{ <EOL> when ( callInfo . resolutionMode ) { <EOL> is ResolutionMode . Delegate -> return false <EOL> is ResolutionMode . WithExpectedType -> when { <EOL> callInfo . resolutionMode . expectedTypeRef . type . containsNotFixedTypeVariables ( ) -> return false <EOL> } <EOL> is ResolutionMode . WithStatus , is ResolutionMode . LambdaResolution -> <EOL> error ( "<STR_LIT>" ) <EOL> is ResolutionMode . AssignmentLValue , <EOL> is ResolutionMode . ContextDependent , <EOL> is ResolutionMode . ContextIndependent , <EOL> is ResolutionMode . ReceiverResolution , <EOL> -> { <EOL> } <EOL> } <EOL> val callSite = callInfo . callSite <EOL> if ( callSite is FirAnnotationCall || callSite is FirArrayLiteral ) return true <EOL> if ( callSite !is FirResolvable && callSite !is FirVariableAssignment ) return false <EOL> if ( dispatchReceiver ? . isReceiverPostponed ( ) == true ) return false <EOL> if ( givenExtensionReceiverOptions . any { it . isReceiverPostponed ( ) } ) return false <EOL> val returnType = ( symbol as? FirCallableSymbol ) ? . let ( returnTypeCalculator :: tryCalculateReturnType ) <EOL> if ( returnType ? . type ? . containsNotFixedTypeVariables ( ) == true ) return false <EOL> if ( callInfo . arguments . any { ! it . isTrivialArgument ( ) } ) return false <EOL> return true <EOL> }

/**
 * This function returns true only when it's safe & sound to analyze and complete the candidate outside the PCLA context,
 * i.e., independently of outer CS.
 *
 * That might be some plain variable accesses that do not contain type variables or regular function calls with only trivial arguments.
 *
 * The basic purpose of that function is performance enhancement because resolving all the calls inside PCLA lambda in the outer context
 * might be too much.
 *
 * Mostly, that means that this function might always return false and it should be correct.
 * TODO: Currently, making it always returning "false" leads to few test failures
 * TODO: due to some corner cases like annotations calls (KT-65465)
 */


fun removeUnusedFunctionDefinitions ( root : JsNode , functions : Map < JsName , JsFunction > )

{ <EOL> val removable = with ( UnusedLocalFunctionsCollector ( functions ) ) { <EOL> process ( ) <EOL> accept ( root ) <EOL> removableFunctions <EOL> } . toSet ( ) <EOL> val remover = NodeRemover ( JsStatement :: class . java ) { statement -> <EOL> val expression = when ( statement ) { <EOL> is JsExpressionStatement -> statement . expression <EOL> is JsVars -> if ( statement . vars . size == <NUM_LIT:1> ) statement . vars [ <NUM_LIT:0> ] . initExpression else null <EOL> else -> null <EOL> } <EOL> expression is JsFunction && expression in removable <EOL> } <EOL> remover . accept ( root ) <EOL> }

/**
 * Removes unused function definitions:
 * f: function() { return 10 }
 *
 * At now, it only removes unused local functions and function literals,
 * because named functions can be referenced from another module.
 */


fun createIfNeeded ( session : FirSession , moduleData : FirModuleData , kotlinScopeProvider : FirKotlinScopeProvider , ) : FirExtensionSyntheticFunctionInterfaceProvider ?

{ <EOL> if ( ! session . functionTypeService . hasExtensionKinds ( ) ) return null <EOL> return FirExtensionSyntheticFunctionInterfaceProvider ( session , moduleData , kotlinScopeProvider ) <EOL> }

/**
 * A [FirExtensionSyntheticFunctionInterfaceProvider] only needs to be created if the session's function type service has extension
 * function kinds. Otherwise, the provider would be useless.
 *
 * Important note: this provider should be created once per compiled set of modules, so all sessions will share the same provider
 * Otherwise it may lead to the situation when there are two different symbols for the same classId, which may trigger
 * errors during expect/actual matching
 */


@ FirSymbolProviderInternals <EOL> fun ClassId . mayBeSyntheticFunctionClassName ( ) : Boolean

= relativeClassName . asString ( ) . lastOrNull ( ) ? . isDigit ( ) == true

/**
 * A [ClassId] can only be a name for a generated function class if it ends with a digit. See [FunctionTypeKind].
 *
 * Checking this first is usually faster than checking `functionTypeService.getKindByClassNamePrefix` or a class cache.
 */


@ Synchronized <EOL> internal fun updateState ( state : String , frame : Continuation < * > , shouldBeMatched : Boolean )

{ <EOL> if ( _state == RUNNING && state == RUNNING && shouldBeMatched ) { <EOL> ++ unmatchedResume <EOL> } else if ( unmatchedResume > <NUM_LIT:0> && state == SUSPENDED ) { <EOL> -- unmatchedResume <EOL> return <EOL> } <EOL> if ( _state == state && state == SUSPENDED && lastObservedFrame != null ) return <EOL> _state = state <EOL> lastObservedFrame = frame as? CoroutineStackFrame <EOL> lastObservedThread = if ( state == RUNNING ) { <EOL> Thread . currentThread ( ) <EOL> } else { <EOL> null <EOL> } <EOL> }

/**
 * Here we orchestrate overlapping state updates that are coming asynchronously.
 * In a nutshell, `probeCoroutineSuspended` can arrive **later** than its matching `probeCoroutineResumed`,
 * e.g. for the following code:
 * ```
 * suspend fun foo() = yield()
 * ```
 *
 * we have this sequence:
 * ```
 * fun foo(...) {
 * uCont.intercepted().dispatchUsingDispatcher() // 1
 * // Notify the debugger the coroutine is suspended
 * probeCoroutineSuspended() // 2
 * return COROUTINE_SUSPENDED // Unroll the stack
 * }
 * ```
 * Nothing prevents coroutine to be dispatched and invoke `probeCoroutineResumed` right between '1' and '2'.
 * See also: https://github.com/Kotlin/kotlinx.coroutines/issues/3193
 *
 * [shouldBeMatched] -- `false` if it is an expected consecutive `probeCoroutineResumed` from BaseContinuationImpl,
 * `true` otherwise.
 */


internal fun lastObservedStackTrace ( ) : List < StackTraceElement >

{ <EOL> var frame : CoroutineStackFrame ? = lastObservedFrame ? : return emptyList ( ) <EOL> val result = ArrayList < StackTraceElement > ( ) <EOL> while ( frame != null ) { <EOL> frame . getStackTraceElement ( ) ? . let { result . add ( it ) } <EOL> frame = frame . callerFrame <EOL> } <EOL> return result <EOL> }

/**
 * Last observed stacktrace of the coroutine captured on its suspension or resumption point.
 * It means that for [running][State.RUNNING] coroutines resulting stacktrace is inaccurate and
 * reflects stacktrace of the resumption point, not the actual current stacktrace.
 */


{ <EOL> val preprocessing = pipeline < BufferedImage > ( ) <EOL> . resize { <EOL> outputHeight = IMAGE_SIZE . toInt ( ) <EOL> outputWidth = IMAGE_SIZE . toInt ( ) <EOL> interpolation = InterpolationType . NEAREST <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . rescale { <EOL> scalingCoefficient = <NUM_LIT> <EOL> } <EOL> val dogsCatsImages = dogsCatsDatasetPath ( ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsCatsImages ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , preprocessing ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> vgg11 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val start = System . currentTimeMillis ( ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> println ( "<STR_LIT>" ) <EOL> it . save ( File ( PATH_TO_MODEL ) , writingMode = WritingMode . OVERRIDE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example shows how to do image classification from scratch using [vgg11] model, without leveraging pre-trained weights.
 * We demonstrate the workflow on the Kaggle Cats vs Dogs binary classification dataset.
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 *
 * It includes:
 * - dataset loading from S3
 * - preprocessing DSL declaration
 * - [OnFlyImageDataset] dataset creation
 * - dataset splitting
 * - model compilation
 * - model training
 * - model export
 * - model evaluation
 */


fun JsFunction . getInnerFunction ( ) : JsFunction ?

{ <EOL> val statements = body . statements <EOL> if ( statements . size != <NUM_LIT:1> ) return null <EOL> val statement = statements . get ( <NUM_LIT:0> ) <EOL> val returnExpr = ( statement as? JsReturn ) ? . expression <EOL> return returnExpr as? JsFunction <EOL> }

/**
 * Gets inner function from function, that creates closure
 *
 * For example:
 * function(a) {
 * return function() { return a; }
 * }
 *
 * Inner functions can only be generated when lambda
 * with closure is created
 */


fun KonanTarget . withSanitizer ( sanitizer : SanitizerKind ? = null )

= TargetWithSanitizer ( this , sanitizer )

/**
 * Construct [TargetWithSanitizer] from [target][KonanTarget] and optional [sanitizer][SanitizerKind].
 */


fun AttributesSchema . registerTargetWithSanitizerAttribute ( )

{ <EOL> attribute ( TargetWithSanitizer . TARGET_ATTRIBUTE ) { <EOL> disambiguationRules . add ( TargetDisambiguationRule :: class . java ) <EOL> } <EOL> }

/**
 * Register [TargetWithSanitizer] attribute with [AttributesSchema].
 */


fun runTestOrSkip ( block : suspend CoroutineScope . ( ) -> Unit ) : TestResult

{ <EOL> return runTest { <EOL> if ( shouldSkipTesting ( ) ) return@runTest <EOL> val testBody = launch ( Dispatchers . Default ) { <EOL> block ( ) <EOL> } <EOL> spinTest ( testBody ) <EOL> } <EOL> }

/** Runs the given block as a test, unless [shouldSkipTesting] indicates that the environment is not suitable. */


@ Test <EOL> fun testMainDispatcherToString ( )

{ <EOL> assertEquals ( "<STR_LIT>" , Dispatchers . Main . toString ( ) ) <EOL> assertEquals ( "<STR_LIT>" , Dispatchers . Main . immediate . toString ( ) ) <EOL> }

/** Tests the [toString] behavior of [Dispatchers.Main] and [MainCoroutineDispatcher.immediate] */


@ Test <EOL> fun testMainDispatcherOrderingInMainThread ( )

= runTestOrSkip { <EOL> withContext ( Dispatchers . Main ) { <EOL> testMainDispatcherOrdering ( ) <EOL> } <EOL> }

/** Tests that the tasks scheduled earlier from [MainCoroutineDispatcher.immediate] will be executed earlier,
 * even if the immediate dispatcher was entered from the main thread. */


@ Test <EOL> fun testMainDispatcherOrderingOutsideMainThread ( )

= runTestOrSkip { <EOL> testMainDispatcherOrdering ( ) <EOL> }

/** Tests that the tasks scheduled earlier from [MainCoroutineDispatcher.immediate] will be executed earlier
 * if the immediate dispatcher was entered from outside the main thread. */


@ Test <EOL> fun testHandlerDispatcherNotEqualToImmediate ( )

{ <EOL> assertNotEquals ( Dispatchers . Main , Dispatchers . Main . immediate ) <EOL> }

/** Tests that [Dispatchers.Main] and its [MainCoroutineDispatcher.immediate] are treated as different values. */


@ Test <EOL> fun testImmediateDispatcherYield ( )

= runTestOrSkip { <EOL> withContext ( Dispatchers . Main ) { <EOL> expect ( <NUM_LIT:1> ) <EOL> checkIsMainThread ( ) <EOL> launch ( Dispatchers . Main . immediate ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> yield ( ) <EOL> expect ( <NUM_LIT:4> ) <EOL> } <EOL> expect ( <NUM_LIT:3> ) <EOL> yield ( ) <EOL> expect ( <NUM_LIT:5> ) <EOL> } <EOL> finish ( <NUM_LIT:6> ) <EOL> }

/** Tests that [Dispatchers.Main] shares its queue with [MainCoroutineDispatcher.immediate]. */


@ Test <EOL> fun testEnteringImmediateFromMain ( )

= runTestOrSkip { <EOL> withContext ( Dispatchers . Main ) { <EOL> expect ( <NUM_LIT:1> ) <EOL> val job = launch { expect ( <NUM_LIT:3> ) } <EOL> withContext ( Dispatchers . Main . immediate ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> } <EOL> job . join ( ) <EOL> } <EOL> finish ( <NUM_LIT:4> ) <EOL> }

/** Tests that entering [MainCoroutineDispatcher.immediate] from [Dispatchers.Main] happens immediately. */


@ Test <EOL> fun testDispatchRequirements ( )

= runTestOrSkip { <EOL> checkDispatchRequirements ( ) <EOL> withContext ( Dispatchers . Main ) { <EOL> checkDispatchRequirements ( ) <EOL> withContext ( Dispatchers . Main . immediate ) { <EOL> checkDispatchRequirements ( ) <EOL> } <EOL> checkDispatchRequirements ( ) <EOL> } <EOL> checkDispatchRequirements ( ) <EOL> }

/** Tests that dispatching to [MainCoroutineDispatcher.immediate] is required from and only from dispatchers
 * other than the main dispatchers and that it's always required for [Dispatchers.Main] itself. */


@ Test <EOL> fun testLaunchInMainScope ( )

= runTestOrSkip { <EOL> var executed = false <EOL> withMainScope { <EOL> launch { <EOL> checkIsMainThread ( ) <EOL> executed = true <EOL> } . join ( ) <EOL> if ( ! executed ) throw AssertionError ( "<STR_LIT>" ) <EOL> } <EOL> }

/** Tests that launching a coroutine in [MainScope] will execute it in the main thread. */


@ Test <EOL> fun testFailureInMainScope ( )

= runTestOrSkip { <EOL> var exception : Throwable ? = null <EOL> withMainScope { <EOL> launch ( CoroutineExceptionHandler { ctx , e -> exception = e } ) { <EOL> checkIsMainThread ( ) <EOL> throw TestException ( ) <EOL> } . join ( ) <EOL> } <EOL> if ( exception ! ! !is TestException ) throw AssertionError ( "<STR_LIT>" ) <EOL> }

/** Tests that a failure in [MainScope] will not propagate upwards. */


@ Test <EOL> fun testCancellationInMainScope ( )

= runTestOrSkip { <EOL> withMainScope { <EOL> cancel ( ) <EOL> launch ( start = CoroutineStart . ATOMIC ) { <EOL> checkIsMainThread ( ) <EOL> delay ( Long . MAX_VALUE ) <EOL> } . join ( ) <EOL> } <EOL> }

/** Tests cancellation in [MainScope]. */


= runTestOrSkip { <EOL> expect ( <NUM_LIT:1> ) <EOL> checkNotMainThread ( ) <EOL> scheduleOnMainQueue { expect ( <NUM_LIT:2> ) } <EOL> withContext ( Dispatchers . Main ) { <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:3> ) <EOL> scheduleOnMainQueue { expect ( <NUM_LIT:4> ) } <EOL> delay ( <NUM_LIT:100> ) <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:5> ) <EOL> } <EOL> checkNotMainThread ( ) <EOL> finish ( <NUM_LIT:6> ) <EOL> }

/** Tests that after a delay, the execution gets back to the main thread. */


@ Test <EOL> fun testWithTimeoutContextDelayNoTimeout ( )

= runTestOrSkip { <EOL> expect ( <NUM_LIT:1> ) <EOL> withTimeout ( <NUM_LIT> ) { <EOL> withContext ( Dispatchers . Main ) { <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:2> ) <EOL> delay ( <NUM_LIT:100> ) <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:3> ) <EOL> } <EOL> } <EOL> checkNotMainThread ( ) <EOL> finish ( <NUM_LIT:4> ) <EOL> }

/** Tests that [Dispatchers.Main] is in agreement with the default time source: it's not much slower. */


@ Test <EOL> fun testWithTimeoutContextDelayTimeout ( )

= runTestOrSkip { <EOL> expect ( <NUM_LIT:1> ) <EOL> assertFailsWith < TimeoutCancellationException > { <EOL> withTimeout ( <NUM_LIT> ) { <EOL> launch ( Dispatchers . Main , start = CoroutineStart . ATOMIC ) { <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:2> ) <EOL> delay ( <NUM_LIT> ) <EOL> expectUnreached ( ) <EOL> } . join ( ) <EOL> } <EOL> expectUnreached ( ) <EOL> } <EOL> checkNotMainThread ( ) <EOL> finish ( <NUM_LIT:3> ) <EOL> }

/** Tests that [Dispatchers.Main] is in agreement with the default time source: it's not much faster. */


@ Test <EOL> fun testWithContextTimeoutDelayNoTimeout ( )

= runTestOrSkip { <EOL> expect ( <NUM_LIT:1> ) <EOL> withContext ( Dispatchers . Main ) { <EOL> withTimeout ( <NUM_LIT> ) { <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:2> ) <EOL> delay ( <NUM_LIT:100> ) <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:3> ) <EOL> } <EOL> } <EOL> checkNotMainThread ( ) <EOL> finish ( <NUM_LIT:4> ) <EOL> }

/** Tests that the timeout of [Dispatchers.Main] is in agreement with its [delay]: it's not much faster. */


@ Test <EOL> fun testWithContextTimeoutDelayTimeout ( )

= runTestOrSkip { <EOL> expect ( <NUM_LIT:1> ) <EOL> assertFailsWith < TimeoutCancellationException > { <EOL> withContext ( Dispatchers . Main ) { <EOL> withTimeout ( <NUM_LIT:100> ) { <EOL> checkIsMainThread ( ) <EOL> expect ( <NUM_LIT:2> ) <EOL> delay ( <NUM_LIT> ) <EOL> expectUnreached ( ) <EOL> } <EOL> } <EOL> expectUnreached ( ) <EOL> } <EOL> checkNotMainThread ( ) <EOL> finish ( <NUM_LIT:3> ) <EOL> }

/** Tests that the timeout of [Dispatchers.Main] is in agreement with its [delay]: it's not much slower. */


internal inline fun < reified T > Any . castIsolatedKotlinPluginClassLoaderAware ( ) : T

{ <EOL> if ( this is T ) return this <EOL> val targetClassFromReceiverClassLoader = try { <EOL> this :: class . java . classLoader . loadClass ( T :: class . java . name ) <EOL> } catch ( _ : ClassNotFoundException ) { <EOL> null <EOL> } <EOL> if ( targetClassFromReceiverClassLoader != null && targetClassFromReceiverClassLoader != T :: class . java ) { <EOL> if ( null is T && ! targetClassFromReceiverClassLoader . isInstance ( this ) ) return null as T <EOL> throw IsolatedKotlinClasspathClassCastException ( ) <EOL> } <EOL> return if ( null is T ) null as T <EOL> else this as T <EOL> }

/**
 * Behaves like a regular cast function, but will be able to detect cast failures because
 * of an isolated classpath. In this case a more detailed error message will be emitted.
 *
 * ```
 * "".castIsolatedKotlinPluginClassLoaderAware<Int>() // fails like "" as Int
 * "".castIsolatedKotlinPluginClassLoaderAware<Int?>() // returns null like "" as? Int
 * ```
 * @return [this] as T if possible (regular cast)
 * @throws ClassCastException is not castable
 * @throws IsolatedKotlinClasspathClassCastException when a separated classpath is detected. See [MULTIPLE_KOTLIN_PLUGINS_LOADED_WARNING]
 */


@ ExperimentalSerializationApi <EOL> public fun < T > encodeToMap ( serializer : SerializationStrategy < T > , value : T ) : Map < String , Any >

{ <EOL> val m = OutAnyMapper ( ) <EOL> m . encodeSerializableValue ( serializer , value ) <EOL> return m . map <EOL> }

/**
 * Encodes properties from the given [value] to a map using the given [serializer].
 * `null` values are omitted from the output.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > encodeToStringMap ( serializer : SerializationStrategy < T > , value : T ) : Map < String , String >

{ <EOL> val m = OutStringMapper ( ) <EOL> m . encodeSerializableValue ( serializer , value ) <EOL> return m . map <EOL> }

/**
 * Encodes properties from the given [value] to a map using the given [serializer].
 * Converts all primitive types to [String] using [toString] method.
 * `null` values are omitted from the output.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > decodeFromMap ( deserializer : DeserializationStrategy < T > , map : Map < String , Any > ) : T

{ <EOL> val m = InAnyMapper ( map , deserializer . descriptor ) <EOL> return m . decodeSerializableValue ( deserializer ) <EOL> }

/**
 * Decodes properties from the given [map] to a value of type [T] using the given [deserializer].
 * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > decodeFromStringMap ( deserializer : DeserializationStrategy < T > , map : Map < String , String > ) : T

{ <EOL> val m = InStringMapper ( map , deserializer . descriptor ) <EOL> return m . decodeSerializableValue ( deserializer ) <EOL> }

/**
 * Decodes properties from the given [map] to a value of type [T] using the given [deserializer].
 * [String] values are converted to respective primitive types using default conversion methods.
 * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present.
 */


@ ExperimentalSerializationApi <EOL> public fun Properties ( module : SerializersModule ) : Properties

= PropertiesImpl ( module )

/**
 * Creates an instance of [Properties] with a given [module].
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Properties . encodeToMap ( value : T ) : Map < String , Any >

= <EOL> encodeToMap ( serializersModule . serializer ( ) , value )

/**
 * Encodes properties from given [value] to a map using serializer for reified type [T] and returns this map.
 * `null` values are omitted from the output.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Properties . encodeToStringMap ( value : T ) : Map < String , String >

= <EOL> encodeToStringMap ( serializersModule . serializer ( ) , value )

/**
 * Encodes properties from given [value] to a map using serializer for reified type [T] and returns this map.
 * Converts all primitive types to [String] using [toString] method.
 * `null` values are omitted from the output.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Properties . decodeFromMap ( map : Map < String , Any > ) : T

= <EOL> decodeFromMap ( serializersModule . serializer ( ) , map )

/**
 * Decodes properties from given [map], assigns them to an object using serializer for reified type [T] and returns this object.
 * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Properties . decodeFromStringMap ( map : Map < String , String > ) : T

= <EOL> decodeFromStringMap ( serializersModule . serializer ( ) , map )

/**
 * Decodes properties from given [map], assigns them to an object using serializer for reified type [T] and returns this object.
 * [String] values are converted to respective primitive types using default conversion methods.
 * [T] may contain properties of nullable types; they will be filled by non-null values from the [map], if present.
 */


fun < T > withScopesForClass ( owner : FirClass , holder : SessionHolder , f : ( ) -> T ) : T

{ <EOL> val labelName = ( owner as? FirRegularClass ) ? . name <EOL> ? : if ( owner . classKind == ClassKind . ENUM_ENTRY ) { <EOL> owner . primaryConstructorIfAny ( holder . session ) ? . callableId ? . className ? . shortName ( ) <EOL> } else null <EOL> val type = owner . defaultType ( ) <EOL> val towerElementsForClass = holder . collectTowerDataElementsForClass ( owner , type ) <EOL> val base = towerDataContext . addNonLocalTowerDataElements ( towerElementsForClass . superClassesStaticsAndCompanionReceivers ) <EOL> val statics = base <EOL> . addNonLocalScopesIfNotNull ( towerElementsForClass . companionStaticScope , towerElementsForClass . staticScope ) <EOL> val staticsAndCompanion = when ( val companionReceiver = towerElementsForClass . companionReceiver ) { <EOL> null -> statics <EOL> else -> base <EOL> . addReceiver ( null , companionReceiver ) <EOL> . addNonLocalScopesIfNotNull ( towerElementsForClass . companionStaticScope , towerElementsForClass . staticScope ) <EOL> } <EOL> val typeParameterScope = ( owner as? FirRegularClass ) ? . typeParameterScope ( ) <EOL> val forConstructorHeader = if ( typeParameterScope != null ) { <EOL> towerDataContext <EOL> . addNonLocalTowerDataElements ( towerElementsForClass . superClassesStaticsAndCompanionReceivers ) <EOL> . run { towerElementsForClass . companionReceiver ? . let { addReceiver ( null , it ) } ? : this } <EOL> . addNonLocalScopesIfNotNull ( towerElementsForClass . companionStaticScope , towerElementsForClass . staticScope ) <EOL> . addNonLocalScope ( typeParameterScope ) <EOL> } else { <EOL> staticsAndCompanion <EOL> } <EOL> val forMembersResolution = forConstructorHeader <EOL> . addReceiver ( labelName , towerElementsForClass . thisReceiver ) <EOL> . addContextReceiverGroup ( towerElementsForClass . contextReceivers ) <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> val scopeForEnumEntries = forConstructorHeader <EOL> val newTowerDataContextForStaticNestedClasses = <EOL> if ( ( owner as? FirRegularClass ) ? . classKind ? . isSingleton == true ) <EOL> forMembersResolution <EOL> else <EOL> staticsAndCompanion <EOL> val constructor = ( owner as? FirRegularClass ) ? . declarations ? . firstOrNull { it is FirConstructor } as? FirConstructor <EOL> val ( primaryConstructorPureParametersScope , primaryConstructorAllParametersScope ) = <EOL> if ( constructor ? . isPrimary == true ) { <EOL> constructor . scopesWithPrimaryConstructorParameters ( holder . session ) <EOL> } else { <EOL> null to null <EOL> } <EOL> val newContexts = FirRegularTowerDataContexts ( regular = forMembersResolution , forClassHeaderAnnotations = base , forNestedClasses = newTowerDataContextForStaticNestedClasses , forCompanionObject = statics , forConstructorHeaders = forConstructorHeader , forEnumEntries = scopeForEnumEntries , primaryConstructorPureParametersScope = primaryConstructorPureParametersScope , primaryConstructorAllParametersScope = primaryConstructorAllParametersScope ) <EOL> return withTowerDataContexts ( newContexts ) { <EOL> f ( ) <EOL> } <EOL> }

/**
 * Changes to the order of scopes should also be reflected in
 * [org.jetbrains.kotlin.fir.resolve.transformers.FirTypeResolveTransformer.withClassScopes].
 * Otherwise, we get different behavior between type resolve and body resolve phases.
 */


{ <EOL> val fooKt = tmpdir . resolve ( "<STR_LIT>" ) . also { <EOL> it . writeText ( "<STR_LIT>" ) <EOL> } <EOL> val jar = tmpdir . resolve ( "<STR_LIT>" ) <EOL> AbstractCliTest . executeCompilerGrabOutput ( K2JVMCompiler ( ) , listOf ( fooKt . path , "<STR_LIT:-d>" , jar . path , "<STR_LIT>" ) ) <EOL> assertNoModuleInfoClass ( jar ) <EOL> }


public fun Window . asCoroutineDispatcher ( ) : CoroutineDispatcher

= <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> asDynamic ( ) . coroutineDispatcher ? : WindowDispatcher ( this ) . also { <EOL> asDynamic ( ) . coroutineDispatcher = it <EOL> }

/**
 * Converts an instance of [Window] to an implementation of [CoroutineDispatcher].
 */


public suspend fun Window . awaitAnimationFrame ( ) : Double

= suspendCancellableCoroutine { cont -> <EOL> asWindowAnimationQueue ( ) . enqueue ( cont ) <EOL> }

/**
 * Suspends coroutine until next JS animation frame and returns frame time on resumption.
 * The time is consistent with [window.performance.now()][org.w3c.performance.Performance.now].
 * This function is cancellable. If the [Job] of the current coroutine is completed while this suspending
 * function is waiting, this function immediately resumes with [CancellationException].
 */


private fun checkSuperTypeNotInitialized ( primaryConstructorSymbol : FirConstructorSymbol , regularClass : FirClass , context : CheckerContext , reporter : DiagnosticReporter )

{ <EOL> val containingClass = context . containingDeclarations . lastIsInstanceOrNull < FirRegularClass > ( ) <EOL> val delegatedConstructorCall = primaryConstructorSymbol . resolvedDelegatedConstructorCall ? : return <EOL> val constructedTypeRef = delegatedConstructorCall . constructedTypeRef <EOL> if ( constructedTypeRef is FirImplicitAnyTypeRef ) return <EOL> val superClassSymbol = constructedTypeRef . coneType . toRegularClassSymbol ( context . session ) ? : return <EOL> if ( superClassSymbol . classKind . isSingleton ) return <EOL> if ( regularClass . isEffectivelyExpect ( containingClass , context ) || regularClass . isEffectivelyExternal ( containingClass , context ) ) { <EOL> return <EOL> } <EOL> val delegatedCallSource = delegatedConstructorCall . source ? : return <EOL> if ( delegatedCallSource . kind !is KtFakeSourceElementKind ) return <EOL> val supertypesToSkip = context . session . primaryConstructorSuperTypePlatformSupport <EOL> . supertypesThatDontNeedInitializationInSubtypesConstructors <EOL> if ( superClassSymbol . classId in supertypesToSkip ) return <EOL> if ( delegatedCallSource . elementType != KtNodeTypes . SUPER_TYPE_CALL_ENTRY ) { <EOL> reporter . reportOn ( constructedTypeRef . source , FirErrors . SUPERTYPE_NOT_INITIALIZED , context ) <EOL> } <EOL> }

/**
 * SUPERTYPE_NOT_INITIALIZED is reported on code like the following. It's skipped if `A` has `()` after it, in which case any
 * diagnostics for that constructor call will be reported, if applicable.
 *
 * ```
 * open class A
 * class B : <!SUPERTYPE_NOT_INITIALIZED>A<!>
 * ```
 */


private fun checkSupertypeInitializedWithoutPrimaryConstructor ( regularClass : FirClass , reporter : DiagnosticReporter , context : CheckerContext )

{ <EOL> with ( SourceNavigator . forElement ( regularClass ) ) { <EOL> for ( superTypeRef in regularClass . superTypeRefs ) { <EOL> if ( superTypeRef . isInConstructorCallee ( ) ) { <EOL> reporter . reportOn ( regularClass . source , FirErrors . SUPERTYPE_INITIALIZED_WITHOUT_PRIMARY_CONSTRUCTOR , context ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * SUPERTYPE_INITIALIZED_WITHOUT_PRIMARY_CONSTRUCTOR is reported on code like the following, where `B` does not have a primary
 * constructor, in which case, one can not call the delegated constructor of `A` in the super type list. `B` doesn't have a primary
 * constructor because it doesn't declare it, nor is it implicitly created in presence of an explicitly declared constructor inside the
 * class body.
 *
 * ```
 * open class A
 * class B : <!SUPERTYPE_INITIALIZED_WITHOUT_PRIMARY_CONSTRUCTOR>A()<!> {
 * constructor()
 * }
 * ```
 */


fun assertProcessRunResult ( result : ProcessRunResult , assertions : ProcessRunResult . ( ) -> Unit )

{ <EOL> try { <EOL> result . assertions ( ) <EOL> } catch ( e : AssertionError ) { <EOL> println ( """<STR_LIT>""" . trimMargin ( ) ) <EOL> throw e <EOL> } <EOL> }

/**
 * Asserts the result of running a process by calling a set of assertions on the result object.
 * If any of the assertions fail, an [AssertionError] is thrown and the process output information is printed.
 *
 * @param result The result of running a process.
 * @param assertions A lambda expression that performs a set of assertions on it.
 *
 * @throws AssertionError If any of the assertions fail.
 */


abstract fun getContents ( ) : String

/**
 * Returns the string contents of this file.
 *
 * The contents must be complete, as if the user themselves wrote it. For Kotlin files,
 * it should return Kotlin source code (including the package and all import statements).
 * For `.md` files, it should return valid Markdown documentation.
 *
 * These contents will be used to populate the real input file to be used by Dokka.
 */


@ JvmStatic <EOL> fun getSyntheticMethodNameForAnnotatedProperty ( baseName : String ) : String

{ <EOL> return baseName + ANNOTATED_PROPERTY_METHOD_NAME_SUFFIX <EOL> }

/**
 * @param baseName JVM name of the property getter since Kotlin 1.4, or Kotlin name of the property otherwise.
 */


internal fun String . wildcardsToRegex ( ) : String

{ <EOL> val builder = StringBuilder ( length * <NUM_LIT:2> ) <EOL> forEach { char -> <EOL> when ( char ) { <EOL> in regexMetacharactersSet -> builder . append ( '<CHAR_LIT:\\>' ) . append ( char ) <EOL> '<CHAR_LIT:*>' -> builder . append ( '<CHAR_LIT:.>' ) . append ( "<STR_LIT:*>" ) <EOL> '<CHAR_LIT>' -> builder . append ( '<CHAR_LIT:.>' ) <EOL> '<CHAR_LIT>' -> builder . append ( "<STR_LIT>" ) <EOL> else -> builder . append ( char ) <EOL> } <EOL> } <EOL> return builder . toString ( ) <EOL> }

/**
 * Replaces characters `*` to `.*`, `#` to `[^.]*` and `?` to `.` regexp characters and also add escape char '\' before regexp metacharacters (see [regexMetacharactersSet]).
 */


public fun < T > width ( column : ColumnReference < T > ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping < T , Double > ( WIDTH , column . name ( ) , null ) <EOL> }

/**
 * Maps the `width` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the width.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > width ( column : KProperty < T > ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping < T , Double > ( WIDTH , column . name , null ) <EOL> }

/**
 * Maps the `width` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to map to the width.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun width ( column : String ) : NonPositionalMapping < Any ? , Double >

{ <EOL> return addNonPositionalMapping ( WIDTH , column , null ) <EOL> }

/**
 * Maps the `width` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the width.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > width ( values : Iterable < T > , name : String ? = null ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping ( WIDTH , values . toList ( ) , name , null ) <EOL> }

/**
 * Maps the `width` aesthetic to iterable of values.
 *
 * @param values the iterable containing the width values.
 * @param name optional name for this aesthetic mapping.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > width ( values : DataColumn < T > ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping ( WIDTH , values , null ) <EOL> }

/**
 * Maps the `width` aesthetic to a data column.
 *
 * @param values the data column to map to the width.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


inline fun < reified T : IMessage > dumpCompare ( it : T , alwaysPrint : Boolean = false , protoBuf : BinaryFormat = defaultProtobuf ) : Boolean

{ <EOL> val msg = it . toProtobufMessage ( ) <EOL> var parsed : GeneratedMessageV3 ? <EOL> val c = try { <EOL> val bytes = protoBuf . encodeToByteArray ( it ) <EOL> if ( alwaysPrint ) println ( "<STR_LIT>" ) <EOL> parsed = msg . parserForType . parseFrom ( bytes ) <EOL> msg == parsed <EOL> } catch ( e : Exception ) { <EOL> e . printStackTrace ( ) <EOL> parsed = null <EOL> false <EOL> } <EOL> if ( ! c || alwaysPrint ) println ( "<STR_LIT>" ) <EOL> return c <EOL> }

/**
 * Check serialization of [ProtoBuf].
 *
 * 1. Serializes the given [IMessage] into bytes using [ProtoBuf].
 * 2. Parses those bytes via the `Java ProtoBuf library`.
 * 3. Compares parsed `Java ProtoBuf object` to expected object ([IMessage.toProtobufMessage]).
 *
 * @param it The [IMessage] to check.
 * @param protoBuf Provide custom [ProtoBuf] instance (default: [ProtoBuf.plain]).
 *
 * @return `true` if the de-serialization returns the expected object.
 */


inline fun < reified T : IMessage > readCompare ( it : T , alwaysPrint : Boolean = false , protoBuf : BinaryFormat = defaultProtobuf ) : Boolean

{ <EOL> var obj : T ? <EOL> val c = try { <EOL> val msg = it . toProtobufMessage ( ) <EOL> val hex = msg . toHex ( ) <EOL> obj = protoBuf . decodeFromHexString < T > ( hex ) <EOL> obj == it <EOL> } catch ( e : Exception ) { <EOL> obj = null <EOL> e . printStackTrace ( ) <EOL> false <EOL> } <EOL> if ( ! c || alwaysPrint ) println ( "<STR_LIT>" ) <EOL> return c <EOL> }

/**
 * Check de-serialization of [ProtoBuf].
 *
 * 1. Converts expected `Java ProtoBuf object` ([IMessage.toProtobufMessage]) to bytes.
 * 2. Parses those bytes via [ProtoBuf].
 * 3. Compares parsed ProtoBuf object to given object.
 *
 * @param it The [IMessage] to check.
 * @param alwaysPrint Set to `true` if expected/found objects should always get printed to console (default: `false`).
 * @param protoBuf Provide custom [ProtoBuf] instance (default: [ProtoBuf.plain]).
 *
 * @return `true` if the de-serialization returns the original object.
 */


public fun < T > family ( column : ColumnReference < T > , ) : NonPositionalMapping < T , FontFamily >

{ <EOL> return addNonPositionalMapping < T , FontFamily > ( FONT_FAMILY , column . name ( ) , null ) <EOL> }

/**
 * Maps the `family` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to be mapped.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > family ( column : KProperty < T > , ) : NonPositionalMapping < T , FontFamily >

{ <EOL> return addNonPositionalMapping < T , FontFamily > ( FONT_FAMILY , column . name , null ) <EOL> }

/**
 * Maps the `family` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to be mapped.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun family ( column : String , ) : NonPositionalMapping < Any ? , FontFamily >

{ <EOL> return addNonPositionalMapping < Any ? , FontFamily > ( FONT_FAMILY , column , null ) <EOL> }

/**
 * Maps the `family` aesthetic to a data column by [String].
 *
 * @param column the data column to be mapped.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > family ( values : Iterable < T > , name : String ? = null , ) : NonPositionalMapping < T , FontFamily >

{ <EOL> return addNonPositionalMapping < T , FontFamily > ( FONT_FAMILY , values . toList ( ) , name , null ) <EOL> }

/**
 * Maps the `family` aesthetic to the iterable of values.
 *
 * @param values the iterable of values to be mapped.
 * @param name optional name for this aesthetic mapping.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > family ( values : DataColumn < T > , ) : NonPositionalMapping < T , FontFamily >

{ <EOL> return addNonPositionalMapping < T , FontFamily > ( FONT_FAMILY , values , null ) <EOL> }

/**
 * Maps the `family` aesthetic to a data column.
 *
 * @param values the data column to be mapped.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


fun linkerOpts ( vararg options : String )

{ <EOL> linkerOpts . addAll ( options . toList ( ) ) <EOL> }

/** Additional options passed to the linker by the Kotlin/Native compiler. */


fun linkerOpts ( options : Iterable < String > )

{ <EOL> linkerOpts . addAll ( options ) <EOL> }


{ <EOL> entryPoint = point <EOL> }

/**
 * Set the fully qualified name of the main function. For an example:
 *
 * - "main"
 * - "com.example.main"
 *
 * The main function can either take no arguments or an Array<String>.
 */


{ <EOL> project . dependencies . add ( exportConfigurationName , dependency ) <EOL> }

/**
 * Add a dependency to be exported in the framework.
 */


fun export ( dependency : Any , configure : Closure < * > )

{ <EOL> project . dependencies . add ( exportConfigurationName , dependency , configure ) <EOL> }


fun export ( dependency : Any , configure : Action < in Dependency > )

{ <EOL> project . dependencies . add ( exportConfigurationName , dependency ) ? . let { <EOL> configure . execute ( it ) <EOL> } <EOL> }


fun embedBitcode ( mode : org . jetbrains . kotlin . gradle . plugin . mpp . BitcodeEmbeddingMode )

{ <EOL> embedBitcodeMode . set ( mode ) <EOL> }

/**
 * Enable or disable embedding bitcode for the framework. See [BitcodeEmbeddingMode].
 */


= embedBitcode ( org . jetbrains . kotlin . gradle . plugin . mpp . BitcodeEmbeddingMode . valueOf ( mode . toUpperCaseAsciiOnly ( ) ) )

/**
 * Enable or disable embedding bitcode for the framework.
 * The parameter [mode] is one of the following string constants:
 *
 * disable - Don't embed LLVM IR bitcode.
 * bitcode - Embed LLVM IR bitcode as data.
 * Has the same effect as the -Xembed-bitcode command line option.
 * marker - Embed placeholder LLVM IR data as a marker.
 * Has the same effect as the -Xembed-bitcode-marker command line option.
 */


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . plus ( other : KtNDArray < Byte > ) : KtNDArray < Byte >

= add ( this , other )

/**
 * Plus. Returns new [KtNDArray].
 */


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . plusAssign ( other : KtNDArray < Byte > )

= plusAssignTwoKtNDArray ( this , other )


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . minus ( other : KtNDArray < Byte > ) : KtNDArray < Byte >

= subtract ( this , other )

/**
 * Subtract. Returns [KtNDArray].
 */


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . minusAssign ( other : KtNDArray < Byte > )

= minusAssignTwoKtNDArray ( this , other )

/**
 * Subtract. In-place operation.
 */


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . times ( other : KtNDArray < Byte > ) : KtNDArray < Byte >

= multiply ( this , other )

/**
 * Multiply. Returns [KtNDArray].
 */


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . timesAssign ( other : KtNDArray < Byte > )

= timesAssignTwoKtNDArray ( this , other )

/**
 * Multiply. In-place operation.
 */


@ JvmName ( "<STR_LIT>" ) operator fun < T : Number , T1 : Number , L : KtNDArray < T > , R : KtNDArray < T1 > > L . div ( other : R ) : KtNDArray < Double >

= divide ( this , other )


@ JvmName ( "<STR_LIT>" ) operator fun KtNDArray < Byte > . divAssign ( other : KtNDArray < Byte > )

= divAssignTwoKtNDArray ( this , other )


inline infix fun < reified T : Number > KtNDArray < T > . `@` ( other : KtNDArray < T > )

= dot ( this , other )


infix fun < T : Number > KtNDArray < T > . `**` ( other : Byte ) : KtNDArray < T >

= power ( this , other )


private fun BaseKotlinScope . createProjectWithSubModules ( )

{ <EOL> settingsGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> initLocalProperties ( ) <EOL> dir ( "<STR_LIT>" ) { <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> kotlin ( "<STR_LIT>" ) { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> apiFile ( projectName = "<STR_LIT>" ) { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> java ( "<STR_LIT>" ) { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> apiFile ( projectName = "<STR_LIT>" ) { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * Creates a single project with 2 (Kotlin and Java Android Library) modules, applies
 * the plugin on the root project.
 */


= <EOL> ( firstChild as? KDocTag ) ? . name

/**
 * Returns the name of the section (the name of the doc tag introducing the section,
 * or null for the default section).
 */


fun encodeConfigValue ( value : ConfigValue )

/**
 * Appends the given [ConfigValue] element to the current output.
 *
 * @param value to insert
 */


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun StringBuilder . appendLine ( value : Byte ) : StringBuilder

= append ( value ) . appendLine ( )

/** Appends [value] to this [StringBuilder], followed by a line feed character (`\n`). */


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun StringBuilder . appendLine ( value : Short ) : StringBuilder

= append ( value ) . appendLine ( )


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun StringBuilder . appendLine ( value : Int ) : StringBuilder

= append ( value ) . appendLine ( )


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun StringBuilder . appendLine ( value : Long ) : StringBuilder

= append ( value ) . appendLine ( )


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun StringBuilder . appendLine ( value : Float ) : StringBuilder

= append ( value ) . appendLine ( )


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun StringBuilder . appendLine ( value : Double ) : StringBuilder

= append ( value ) . appendLine ( )


@ JvmOverloads <EOL> public fun seconds ( seconds : Int , cancelOnTimeout : Boolean = false , enableCoroutineCreationStackTraces : Boolean = true ) : CoroutinesTimeout

= <EOL> seconds ( seconds . toLong ( ) , cancelOnTimeout , enableCoroutineCreationStackTraces )

/**
 * Creates [CoroutinesTimeout] rule with the given timeout in seconds.
 */


@ JvmOverloads <EOL> public fun seconds ( seconds : Long , cancelOnTimeout : Boolean = false , enableCoroutineCreationStackTraces : Boolean = true ) : CoroutinesTimeout

= <EOL> CoroutinesTimeout ( TimeUnit . SECONDS . toMillis ( seconds ) , cancelOnTimeout , enableCoroutineCreationStackTraces )


override fun apply ( base : Statement , description : Description ) : Statement

= <EOL> CoroutinesTimeoutStatement ( base , description , testTimeoutMs , cancelOnTimeout )

/**
 * @suppress suppress from Dokka
 */


{ <EOL> runImageRecognitionPrediction ( modelType = TFModels . CV . NASNetMobile ) <EOL> }

/**
 * This example demonstrates the inference concept on NasNetMobile model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Model predicts on a few images located in resources.
 * - Special preprocessing (used in NasNetMobile during training on ImageNet dataset) is applied to the images before prediction.
 *
 * NOTE: Input resolution is 224*224
 */


= nasNetMobilePrediction ( )


fun < T > Iterable < AcceptanceRule < T > > . accepts ( obj : T ) : Boolean ?

{ <EOL> return unionAcceptance ( map { it . accepts ( obj ) } ) <EOL> }

/**
 * List of acceptance rules:
 * 1) accepts [obj] if latest not-null acceptance result is `true`
 * 2) doesn't accept [obj] if latest not-null acceptance result is `false`
 * 3) returns `null` if all acceptance results are `null` or the iterable is empty
 */


private fun determineIfStandaloneTest ( ) : Boolean

= with ( structure ) { <EOL> if ( directives . contains ( NATIVE_STANDALONE_DIRECTIVE ) ) return true <EOL> if ( directives . contains ( FILECHECK_STAGE . name ) ) return true <EOL> if ( directives . contains ( ASSERTIONS_MODE . name ) ) return true <EOL> if ( isExpectedFailure ) return true <EOL> if ( directives . contains ( IGNORE_NATIVE . name ) || directives . contains ( IGNORE_NATIVE_K1 . name ) || directives . contains ( IGNORE_NATIVE_K2 . name ) ) return true <EOL> if ( pipelineType != PipelineType . K1 && testDataFileSettings . languageSettings . contains ( "<STR_LIT>" ) ) return true <EOL> var isStandaloneTest = false <EOL> filesToTransform . forEach { handler -> <EOL> handler . accept ( object : KtTreeVisitorVoid ( ) { <EOL> override fun visitKtFile ( file : KtFile ) = when { <EOL> isStandaloneTest -> Unit <EOL> file . packageFqName . startsWith ( StandardNames . BUILT_INS_PACKAGE_NAME ) -> { <EOL> isStandaloneTest = true <EOL> } <EOL> else -> super . visitKtFile ( file ) <EOL> } <EOL> } ) <EOL> } <EOL> isStandaloneTest <EOL> }

/**
 * Determine if the current test should be compiled as a standalone test, i.e.
 * - package names are not patched
 * - test is compiled independently of any other tests
 */


private fun patchPackageNames ( isStandaloneTest : Boolean )

= with ( structure ) { <EOL> if ( isStandaloneTest ) return <EOL> val basePackageName = FqName ( testDataFileSettings . nominalPackageName . toString ( ) ) <EOL> val oldPackageNames : Set < FqName > = filesToTransform . mapToSet { it . packageFqName } <EOL> val oldToNewPackageNameMapping : Map < FqName , FqName > = oldPackageNames . associateWith { oldPackageName -> <EOL> basePackageName . child ( oldPackageName ) <EOL> } <EOL> filesToTransform . forEach { handler -> <EOL> handler . accept ( object : KtVisitor < Unit , Set < Name > > ( ) { <EOL> override fun visitKtElement ( element : KtElement , parentAccessibleDeclarationNames : Set < Name > ) { <EOL> element . getChildrenOfType < KtElement > ( ) . forEach { child -> <EOL> child . accept ( this , parentAccessibleDeclarationNames ) <EOL> } <EOL> } <EOL> override fun visitKtFile ( file : KtFile , unused : Set < Name > ) { <EOL> val oldPackageDirective = file . packageDirective <EOL> val oldPackageName = oldPackageDirective ? . fqName ? : FqName . ROOT <EOL> val newPackageName = oldToNewPackageNameMapping . getValue ( file . packageFqNameForKLib ) <EOL> val newPackageDirective = handler . psiFactory . createPackageDirective ( newPackageName ) <EOL> if ( oldPackageDirective != null ) { <EOL> oldPackageDirective . replace ( newPackageDirective ) . ensureSurroundedByNewLines ( ) <EOL> } else { <EOL> file . addAfter ( newPackageDirective , file . fileAnnotationList ) . ensureSurroundedByNewLines ( ) <EOL> } <EOL> if ( ! file . name . endsWith ( "<STR_LIT>" ) ) { <EOL> val annotationText = <EOL> "<STR_LIT>" <EOL> val fileAnnotationList = handler . psiFactory . createFileAnnotationListWithAnnotation ( annotationText ) <EOL> file . addAnnotations ( fileAnnotationList ) <EOL> visitKtElement ( file , file . collectAccessibleDeclarationNames ( ) ) <EOL> } <EOL> } <EOL> override fun visitPackageDirective ( directive : KtPackageDirective , unused : Set < Name > ) = Unit <EOL> override fun visitImportDirective ( importDirective : KtImportDirective , unused : Set < Name > ) { <EOL> val importedFqName = importDirective . importedFqName <EOL> if ( importedFqName == null || importedFqName . startsWith ( StandardNames . BUILT_INS_PACKAGE_NAME ) || importedFqName . startsWith ( KOTLINX_PACKAGE_NAME ) || importedFqName . startsWith ( HELPERS_PACKAGE_NAME ) || importedFqName . startsWith ( CNAMES_PACKAGE_NAME ) || importedFqName . startsWith ( OBJCNAMES_PACKAGE_NAME ) || importedFqName . startsWith ( PLATFORM_PACKAGE_NAME ) ) { <EOL> return <EOL> } <EOL> val newImportPath = ImportPath ( fqName = basePackageName . child ( importedFqName ) , isAllUnder = importDirective . isAllUnder , alias = importDirective . aliasName ? . let ( Name :: identifier ) ) <EOL> importDirective . replace ( handler . psiFactory . createImportDirective ( newImportPath ) ) <EOL> } <EOL> override fun visitTypeAlias ( typeAlias : KtTypeAlias , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> super . visitTypeAlias ( typeAlias , parentAccessibleDeclarationNames + typeAlias . collectAccessibleDeclarationNames ( ) ) <EOL> override fun visitClassOrObject ( classOrObject : KtClassOrObject , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> super . visitClassOrObject ( classOrObject , parentAccessibleDeclarationNames + classOrObject . collectAccessibleDeclarationNames ( ) ) <EOL> override fun visitClassBody ( classBody : KtClassBody , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> super . visitClassBody ( classBody , parentAccessibleDeclarationNames + classBody . collectAccessibleDeclarationNames ( ) ) <EOL> override fun visitPropertyAccessor ( accessor : KtPropertyAccessor , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> transformDeclarationWithBody ( accessor , parentAccessibleDeclarationNames ) <EOL> override fun visitNamedFunction ( function : KtNamedFunction , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> transformDeclarationWithBody ( function , parentAccessibleDeclarationNames ) <EOL> override fun visitPrimaryConstructor ( constructor : KtPrimaryConstructor , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> transformDeclarationWithBody ( constructor , parentAccessibleDeclarationNames ) <EOL> override fun visitSecondaryConstructor ( constructor : KtSecondaryConstructor , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> transformDeclarationWithBody ( constructor , parentAccessibleDeclarationNames ) <EOL> private fun transformDeclarationWithBody ( declarationWithBody : KtDeclarationWithBody , parentAccessibleDeclarationNames : Set < Name > ) { <EOL> val ( expressions , nonExpressions ) = declarationWithBody . getChildrenOfType < KtElement > ( ) . partition { it is KtExpression } <EOL> val accessibleDeclarationNames = <EOL> parentAccessibleDeclarationNames + declarationWithBody . collectAccessibleDeclarationNames ( ) <EOL> nonExpressions . forEach { it . accept ( this , accessibleDeclarationNames ) } <EOL> val bodyAccessibleDeclarationNames = <EOL> accessibleDeclarationNames + declarationWithBody . valueParameters . map { it . nameAsSafeName } <EOL> expressions . forEach { it . accept ( this , bodyAccessibleDeclarationNames ) } <EOL> } <EOL> override fun visitExpression ( expression : KtExpression , parentAccessibleDeclarationNames : Set < Name > ) = <EOL> if ( expression is KtFunctionLiteral ) <EOL> transformDeclarationWithBody ( expression , parentAccessibleDeclarationNames ) <EOL> else <EOL> super . visitExpression ( expression , parentAccessibleDeclarationNames ) <EOL> override fun visitBlockExpression ( expression : KtBlockExpression , parentAccessibleDeclarationNames : Set < Name > ) { <EOL> val accessibleDeclarationNames = parentAccessibleDeclarationNames . toMutableSet ( ) <EOL> expression . getChildrenOfType < KtElement > ( ) . forEach { child -> <EOL> child . accept ( this , accessibleDeclarationNames ) <EOL> accessibleDeclarationNames . addIfNotNull ( child . name ? . let ( Name :: identifier ) ) <EOL> } <EOL> } <EOL> override fun visitDotQualifiedExpression ( dotQualifiedExpression : KtDotQualifiedExpression , accessibleDeclarationNames : Set < Name > ) { <EOL> val names = dotQualifiedExpression . collectNames ( ) <EOL> val newDotQualifiedExpression = <EOL> visitPossiblyTypeReferenceWithFullyQualifiedName ( names , accessibleDeclarationNames ) { newPackageName -> <EOL> val newDotQualifiedExpression = handler . psiFactory <EOL> . createFile ( "<STR_LIT>" ) <EOL> . getChildOfType < KtProperty > ( ) ! ! <EOL> . getChildOfType < KtDotQualifiedExpression > ( ) ! ! <EOL> dotQualifiedExpression . replace ( newDotQualifiedExpression ) as KtDotQualifiedExpression <EOL> } ? : dotQualifiedExpression <EOL> super . visitDotQualifiedExpression ( newDotQualifiedExpression , accessibleDeclarationNames ) <EOL> } <EOL> override fun visitUserType ( userType : KtUserType , accessibleDeclarationNames : Set < Name > ) { <EOL> val names = userType . collectNames ( ) <EOL> val newUserType = <EOL> visitPossiblyTypeReferenceWithFullyQualifiedName ( names , accessibleDeclarationNames ) { newPackageName -> <EOL> val newUserType = handler . psiFactory <EOL> . createFile ( "<STR_LIT>" ) <EOL> . getChildOfType < KtProperty > ( ) ! ! <EOL> . getChildOfType < KtTypeReference > ( ) ! ! <EOL> . typeElement as KtUserType <EOL> userType . replace ( newUserType ) as KtUserType <EOL> } ? : userType <EOL> newUserType . typeArgumentList ? . let { visitKtElement ( it , accessibleDeclarationNames ) } <EOL> } <EOL> private fun < T : KtElement > visitPossiblyTypeReferenceWithFullyQualifiedName ( names : List < Name > , accessibleDeclarationNames : Set < Name > , action : ( newSubPackageName : FqName ) -> T ) : T ? { <EOL> if ( names . size < <NUM_LIT:2> ) return null <EOL> if ( names . first ( ) in accessibleDeclarationNames ) return null <EOL> for ( index in <NUM_LIT:1> until names . size ) { <EOL> val subPackageName = names . fqNameBeforeIndex ( index ) <EOL> val newPackageName = oldToNewPackageNameMapping [ subPackageName ] <EOL> if ( newPackageName != null ) <EOL> return action ( newPackageName . removeSuffix ( subPackageName ) ) <EOL> } <EOL> return null <EOL> } <EOL> } , emptySet ( ) ) <EOL> } <EOL> }

/**
 * For every Kotlin file (*.kt) stored in this text:
 *
 * - If there is a "package" declaration, patch it to prepend unique package prefix.
 * Example: package foo -> package codegen.box.annotations.genericAnnotations.foo
 *
 * - If there is no "package" declaration, add one with the package name equal to unique package prefix.
 * Example (new line added): package codegen.box.annotations.genericAnnotations
 *
 * - All "import" declarations are patched to reflect appropriate changes in "package" declarations.
 * Example: import foo.* -> import codegen.box.annotations.genericAnnotations.foo.*
 *
 * - All fully-qualified references are patched to reflect appropriate changes in "package" declarations.
 * Example: val x = foo.Bar() -> val x = codegen.box.annotations.genericAnnotations.foo.Bar()
 *
 * The "unique package prefix" is computed individually for every test file and reflects relative path to the test file.
 * Example: codegen/box/annotations/genericAnnotations.kt -> codegen.box.annotations.genericAnnotations
 *
 * Note that packages with fully-qualified name starting with "kotlin." and "helpers." are kept unchanged.
 * Examples: package kotlin.coroutines -> package kotlin.coroutines
 * import kotlin.test.* -> import kotlin.test.*
 */


private fun patchFileLevelAnnotations ( )

= with ( structure ) { <EOL> fun getAnnotationText ( fullyQualifiedName : String ) = "<STR_LIT>" <EOL> if ( testDataFileSettings . optInsForSourceCode . isNotEmpty ( ) ) { <EOL> filesToTransform . forEach { handler -> <EOL> handler . accept ( object : KtTreeVisitorVoid ( ) { <EOL> override fun visitKtFile ( file : KtFile ) { <EOL> val newFileAnnotationList = handler . psiFactory . createFile ( buildString { <EOL> testDataFileSettings . optInsForSourceCode . forEach { <EOL> appendLine ( getAnnotationText ( it ) ) <EOL> } <EOL> } ) . fileAnnotationList ! ! <EOL> file . addAnnotations ( newFileAnnotationList ) <EOL> } <EOL> } ) <EOL> } <EOL> } <EOL> }

/**
 * Make sure that the OptIns specified in test directives (see [ExtTestDataFileSettings.optInsForSourceCode]) are represented
 * as file-level annotations in every individual test file.
 */


= with ( structure ) { <EOL> val result = mutableListOf < String > ( ) <EOL> filesToTransform . forEach { handler -> <EOL> handler . accept ( object : KtTreeVisitorVoid ( ) { <EOL> override fun visitKtFile ( file : KtFile ) { <EOL> val hasBoxFunction = file . getChildrenOfType < KtNamedFunction > ( ) . any { function -> <EOL> function . name == BOX_FUNCTION_NAME . asString ( ) && function . valueParameters . isEmpty ( ) <EOL> } <EOL> if ( hasBoxFunction ) { <EOL> val boxFunctionFqName = file . packageFqName . child ( BOX_FUNCTION_NAME ) . asString ( ) <EOL> result += boxFunctionFqName <EOL> handler . module . markAsMain ( ) <EOL> } <EOL> } <EOL> } ) <EOL> } <EOL> return result . singleOrNull ( ) <EOL> ? : fail { <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> } <EOL> }

/** Finds the fully-qualified name of the entry point function (aka `fun box(): String`). */