@ LeakedDeclarationCaches <EOL> internal fun fillUnboundSymbols ( )

{ <EOL> fillUnboundSymbols ( functionCache ) <EOL> fillUnboundSymbols ( propertyCache . normal ) <EOL> fillUnboundSymbols ( propertyCache . synthetic ) <EOL> }

/**
 * This function iterates over all non f/o callable symbols created in declaration storage and binds all unbound symbols
 *
 * Usually all symbols are bound after fir2ir conversion is over, but it's not true for `allowNonCachedDeclarations`, when
 * we convert to IR only part of sources from code fragments.
 *
 * ```
 * // Original code
 * fun foo(x: Int) {} // (1)
 *
 * fun bar() {
 * 1.let { // (2)
 * <context of code fragment>
 * }
 * }
 *
 * // Code fragment
 * foo(this@let)
 *
 * Here in the body of the code fragment we reference function (1) and lambda (2), which leads to creation of their symbols,
 * but not to generation of their IR. And since the original code won't be processed by fir2ir, we need to manually create
 * IR for all symbols from it, to avoid publication of unbound symbols after fir2ri conversion is over
 *
 * Note that in the code fragment we may capture even local functions and lambdas, which are stored not in global caches,
 * but in `localStorage`, which is getting cleared after leaving from corresponding scope. So to generate IR for them we need
 * to call this function not only after fir2ir conversion, but also after leaving each local scope (see `leaveScope` function)
 */


@ UnsafeDuringIrConstructionAPI <EOL> internal fun < D : IrDeclaration > IrBindableSymbol < * , D > . ownerIfBound ( ) : D ?

{ <EOL> return runIf ( isBound ) { owner } <EOL> }

/**
 * This function is introduced as preparation to publishing unbound symbols in fir2ir
 * There is a probability that it won't be non needed in future, but for now it allows
 * to easily track all places left when we need to extract owner from symbol
 */


public suspend fun ProducerScope < * > . awaitClose ( block : ( ) -> Unit = { } )

{ <EOL> check ( kotlin . coroutines . coroutineContext [ Job ] === this ) { "<STR_LIT>" } <EOL> try { <EOL> suspendCancellableCoroutine < Unit > { cont -> <EOL> invokeOnClose { <EOL> cont . resume ( Unit ) <EOL> } <EOL> } <EOL> } finally { <EOL> block ( ) <EOL> } <EOL> }

/**
 * Suspends the current coroutine until the channel is either [closed][SendChannel.close] or [cancelled][ReceiveChannel.cancel]
 * and invokes the given [block] before resuming the coroutine.
 *
 * This suspending function is cancellable: if the [Job] of the current coroutine is cancelled while this
 * suspending function is waiting, this function immediately resumes with [CancellationException].
 * There is a **prompt cancellation guarantee**: even if this function is ready to return, but was cancelled
 * while suspended, [CancellationException] will be thrown. See [suspendCancellableCoroutine] for low-level details.
 *
 * Note that when the producer channel is cancelled, this function resumes with a cancellation exception.
 * Therefore, in case of cancellation, no code after the call to this function will be executed.
 * That's why this function takes a lambda parameter.
 *
 * Example of usage:
 * ```
 * val callbackEventsStream = produce {
 * val disposable = registerChannelInCallback(channel)
 * awaitClose { disposable.dispose() }
 * }
 * ```
 */


@ ExperimentalCoroutinesApi <EOL> public fun < E > CoroutineScope . produce ( context : CoroutineContext = EmptyCoroutineContext , capacity : Int = <NUM_LIT:0> , @ BuilderInference block : suspend ProducerScope < E > . ( ) -> Unit ) : ReceiveChannel < E >

= <EOL> produce ( context , capacity , BufferOverflow . SUSPEND , CoroutineStart . DEFAULT , onCompletion = null , block = block )

/**
 * Launches a new coroutine to produce a stream of values by sending them to a channel
 * and returns a reference to the coroutine as a [ReceiveChannel]. This resulting
 * object can be used to [receive][ReceiveChannel.receive] elements produced by this coroutine.
 *
 * The scope of the coroutine contains the [ProducerScope] interface, which implements
 * both [CoroutineScope] and [SendChannel], so that the coroutine can invoke
 * [send][SendChannel.send] directly. The channel is [closed][SendChannel.close]
 * when the coroutine completes.
 * The running coroutine is cancelled when its receive channel is [cancelled][ReceiveChannel.cancel].
 *
 * The coroutine context is inherited from this [CoroutineScope]. Additional context elements can be specified with the [context] argument.
 * If the context does not have any dispatcher or other [ContinuationInterceptor], then [Dispatchers.Default] is used.
 * The parent job is inherited from the [CoroutineScope] as well, but it can also be overridden
 * with a corresponding [context] element.
 *
 * Any uncaught exception in this coroutine will close the channel with this exception as the cause and
 * the resulting channel will become _failed_, so that any attempt to receive from it thereafter will throw an exception.
 *
 * The kind of the resulting channel depends on the specified [capacity] parameter.
 * See the [Channel] interface documentation for details.
 *
 * See [newCoroutineContext] for a description of debugging facilities available for newly created coroutines.
 *
 * **Note: This is an experimental api.** Behaviour of producers that work as children in a parent scope with respect
 * to cancellation and error handling may change in the future.
 *
 * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine.
 * @param capacity capacity of the channel's buffer (no buffer by default).
 * @param block the coroutine code.
 */


@ InternalCoroutinesApi <EOL> public fun < E > CoroutineScope . produce ( context : CoroutineContext = EmptyCoroutineContext , capacity : Int = <NUM_LIT:0> , start : CoroutineStart = CoroutineStart . DEFAULT , onCompletion : CompletionHandler ? = null , @ BuilderInference block : suspend ProducerScope < E > . ( ) -> Unit ) : ReceiveChannel < E >

= <EOL> produce ( context , capacity , BufferOverflow . SUSPEND , start , onCompletion , block )

/**
 * **This is an internal API and should not be used from general code.**
 * The `onCompletion` parameter will be redesigned.
 * If you have to use the `onCompletion` operator, please report to https://github.com/Kotlin/kotlinx.coroutines/issues/.
 * As a temporary solution, [invokeOnCompletion][Job.invokeOnCompletion] can be used instead:
 * ```
 * fun <E> ReceiveChannel<E>.myOperator(): ReceiveChannel<E> = GlobalScope.produce(Dispatchers.Unconfined) {
 * coroutineContext[Job]?.invokeOnCompletion { consumes() }
 * }
 * ```
 * @suppress
 */


{ <EOL> val result = commonize { <EOL> outputTarget ( "<STR_LIT>" ) <EOL> simpleSingleSourceTarget ( "<STR_LIT:a>" , """<STR_LIT>""" ) <EOL> simpleSingleSourceTarget ( "<STR_LIT:b>" , """<STR_LIT>""" ) <EOL> } <EOL> result . assertCommonized ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> }

/**
 * See: https://youtrack.jetbrains.com/issue/KT-45992
 */


override actual fun add ( element : E ) : Boolean

{ <EOL> add ( size , element ) <EOL> return true <EOL> }

/**
 * Adds the specified element to the end of this list.
 *
 * @return `true` because the list is always modified as the result of this operation.
 */


protected actual open fun removeRange ( fromIndex : Int , toIndex : Int )

{ <EOL> val iterator = listIterator ( fromIndex ) <EOL> repeat ( toIndex - fromIndex ) { <EOL> iterator . next ( ) <EOL> iterator . remove ( ) <EOL> } <EOL> }

/**
 * Removes the range of elements from this list starting from [fromIndex] and ending with but not including [toIndex].
 */


override fun equals ( other : Any ? ) : Boolean

{ <EOL> if ( other === this ) return true <EOL> if ( other !is List < * > ) return false <EOL> return AbstractList . orderedEquals ( this , other ) <EOL> }

/**
 * Checks if the two specified lists are *structurally* equal to one another.
 *
 * Two lists are considered structurally equal if they have the same size, and elements at corresponding indices are equal.
 * Elements are compared for equality using the [equals][Any.equals] function.
 * For floating point numbers, this means `NaN` is equal to itself and `-0.0` is not equal to `0.0`.
 *
 * @param other the list to compare with this list.
 * @return `true` if [other] is a [List] that is structurally equal to this list, `false` otherwise.
 */


internal fun expandGlobTo ( unexpandedPath : File , output : MutableCollection < File > )

{ <EOL> assertTrue ( unexpandedPath . isAbsolute ) { "<STR_LIT>" } <EOL> val paths : List < File > = generateSequence ( unexpandedPath ) { it . parentFile } . toMutableList ( ) . apply { reverse ( ) } <EOL> for ( index in <NUM_LIT:1> until paths . size ) { <EOL> val path : File = paths [ index ] <EOL> val isGlob = '<CHAR_LIT:*>' in path . name <EOL> if ( isGlob ) { <EOL> val basePath : File = paths [ index - <NUM_LIT:1> ] <EOL> val basePathAsPath : Path = basePath . toPath ( ) <EOL> val pattern : String = unexpandedPath . relativeTo ( basePath ) . path . let { pattern -> <EOL> if ( File . separatorChar == '<CHAR_LIT:\\>' ) pattern . replace ( "<STR_LIT>" , "<STR_LIT>" ) else pattern <EOL> } <EOL> val matcher : PathMatcher = FileSystems . getDefault ( ) . getPathMatcher ( "<STR_LIT>" ) <EOL> Files . walkFileTree ( basePathAsPath , object : SimpleFileVisitor < Path > ( ) { <EOL> override fun visitFile ( file : Path , attrs : BasicFileAttributes ) : FileVisitResult { <EOL> if ( matcher . matches ( basePathAsPath . relativize ( file ) ) ) output += file . toFile ( ) <EOL> return FileVisitResult . CONTINUE <EOL> } <EOL> } ) <EOL> return <EOL> } <EOL> } <EOL> output += unexpandedPath <EOL> }

/**
 * Naive suboptimal implementation of glob expansion.
 */


public suspend fun emit ( value : T )

/**
 * Collects the value emitted by the upstream.
 * This method is not thread-safe and should not be invoked concurrently.
 */


actual fun < T > CoroutineScope . asyncWithDealy ( delay : Long , block : suspend ( ) -> T ) : Deferred < T >

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

/**
 * JVM actual implementation for `asyncWithDelay`
 */


@ OptIn ( ExperimentalSerializationApi :: class ) <EOL> private fun defer ( deferred : ( ) -> SerialDescriptor ) : SerialDescriptor

= object : SerialDescriptor { <EOL> private val original : SerialDescriptor by lazy ( deferred ) <EOL> override val serialName : String <EOL> get ( ) = original . serialName <EOL> override val kind : SerialKind <EOL> get ( ) = original . kind <EOL> override val elementsCount : Int <EOL> get ( ) = original . elementsCount <EOL> override fun getElementName ( index : Int ) : String = original . getElementName ( index ) <EOL> override fun getElementIndex ( name : String ) : Int = original . getElementIndex ( name ) <EOL> override fun getElementAnnotations ( index : Int ) : List < Annotation > = original . getElementAnnotations ( index ) <EOL> override fun getElementDescriptor ( index : Int ) : SerialDescriptor = original . getElementDescriptor ( index ) <EOL> override fun isElementOptional ( index : Int ) : Boolean = original . isElementOptional ( index ) <EOL> }

/**
 * Returns serial descriptor that delegates all the calls to descriptor returned by [deferred] block.
 * Used to resolve cyclic dependencies between recursive serializable structures.
 */


public fun onPreVisitDirectory ( function : ( directory : Path , attributes : BasicFileAttributes ) -> FileVisitResult ) : Unit

/**
 * Overrides the corresponding function of the built file visitor with the provided [function].
 *
 * By default, [FileVisitor.preVisitDirectory] of the built file visitor returns [FileVisitResult.CONTINUE].
 */


public fun onVisitFile ( function : ( file : Path , attributes : BasicFileAttributes ) -> FileVisitResult ) : Unit

/**
 * Overrides the corresponding function of the built file visitor with the provided [function].
 *
 * By default, [FileVisitor.visitFile] of the built file visitor returns [FileVisitResult.CONTINUE].
 */


public fun onVisitFileFailed ( function : ( file : Path , exception : IOException ) -> FileVisitResult ) : Unit

/**
 * Overrides the corresponding function of the built file visitor with the provided [function].
 *
 * By default, [FileVisitor.visitFileFailed] of the built file visitor re-throws the I/O exception
 * that prevented the file from being visited.
 */


public fun onPostVisitDirectory ( function : ( directory : Path , exception : IOException ? ) -> FileVisitResult ) : Unit

/**
 * Overrides the corresponding function of the built file visitor with the provided [function].
 *
 * By default, if the directory iteration completes without an I/O exception,
 * [FileVisitor.postVisitDirectory] of the built file visitor returns [FileVisitResult.CONTINUE];
 * otherwise it re-throws the I/O exception that caused the iteration of the directory to terminate prematurely.
 */


private fun markInteropDeclaration ( descriptor : DeclarationDescriptor )

{ <EOL> if ( descriptor . isFromInteropLibrary ( ) ) { <EOL> mask = mask or IdSignature . Flags . IS_NATIVE_INTEROP_LIBRARY . encode ( true ) <EOL> } <EOL> }

/**
 * We need a way to distinguish interop declarations from usual ones
 * to be able to link against them. We do it by marking them with
 * [IdSignature.Flags.IS_NATIVE_INTEROP_LIBRARY] flag.
 */


@ DokkatooInternalApi <EOL> fun ObjectFactory . dokkaSourceSetIdSpec ( scopeId : String , sourceSetName : String , ) : DokkaSourceSetIdSpec

= newInstance < DokkaSourceSetIdSpec > ( scopeId , sourceSetName )

/** Utility for creating a new [DokkaSourceSetIdSpec] instance using [ObjectFactory.newInstance] */


fun < T : Any > javaIoSerializable ( clazz : KClass < T > ) : IdeaKotlinExtrasSerializer < T >

{ <EOL> return IdeaKotlinJavaIoSerializableExtrasSerializer ( clazz ) <EOL> }

/**
 * Returns a [IdeaKotlinExtrasSerializer] based upon [java.io.Serializable]
 */


public fun FaceDetectionModelBase < Bitmap > . detectFaces ( imageProxy : ImageProxy , topK : Int = <NUM_LIT:5> , iouThreshold : Float = <NUM_LIT> ) : List < DetectedObject >

{ <EOL> if ( this is CameraXCompatibleModel ) { <EOL> return doWithRotation ( imageProxy . imageInfo . rotationDegrees ) { <EOL> detectFaces ( imageProxy . toBitmap ( ) , topK , iouThreshold ) <EOL> } <EOL> } <EOL> return detectFaces ( imageProxy . toBitmap ( applyRotation = true ) , topK , iouThreshold ) <EOL> }

/**
 * Detects [topK] faces on the given [imageProxy]. If [topK] is negative all detected faces are returned.
 * @param [iouThreshold] threshold IoU value for the non-maximum suppression applied during postprocessing
 */


public fun DokkaConfiguration . toCompactJsonString ( ) : String

= serializeAsCompactJson ( this )

/**
 * Serializes [DokkaConfiguration] as a machine-readable and compact JSON string.
 *
 * The returned string is not very human friendly as it will be difficult to parse by eyes due to it
 * being compact and in one line. If you want to show the output to a human being, see [toPrettyJsonString].
 */


public fun DokkaConfiguration . toPrettyJsonString ( ) : String

= serializeAsPrettyJson ( this )

/**
 * Serializes [DokkaConfiguration] as a human-readable (pretty printed) JSON string.
 *
 * The returned string will have excessive line breaks and indents, which might not be
 * desirable when passing this value between API consumers/producers. If you want
 * a machine-readable and compact json string, see [toCompactJsonString].
 */


public fun < T : ConfigurableBlock > T . toCompactJsonString ( ) : String

= serializeAsCompactJson ( this )

/**
 * Serializes a [ConfigurableBlock] as a machine-readable and compact JSON string.
 *
 * The returned string is not very human friendly as it will be difficult to parse by eyes due to it
 * being compact and in one line. If you want to show the output to a human being, see [toPrettyJsonString].
 */


public fun < T : ConfigurableBlock > T . toPrettyJsonString ( ) : String

= serializeAsCompactJson ( this )

/**
 * Serializes a [ConfigurableBlock] as a human-readable (pretty printed) JSON string.
 *
 * The returned string will have excessive line breaks and indents, which might not be
 * desirable when passing this value between API consumers/producers. If you want
 * a machine-readable and compact json string, see [toCompactJsonString].
 */


internal fun Project . warnAboutDeprecatedProperty ( property : KonanPlugin . ProjectProperty )

= <EOL> property . deprecatedPropertyName ? . let { deprecated -> <EOL> if ( project . hasProperty ( deprecated ) ) { <EOL> logger . warn ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * We use the following properties:
 * org.jetbrains.kotlin.native.home - directory where compiler is located (aka dist in konan project output).
 * org.jetbrains.kotlin.native.version - a konan compiler version for downloading.
 * konan.build.targets - list of targets to build (by default all the declared targets are built).
 * konan.jvmArgs - additional args to be passed to a JVM executing the compiler/cinterop tool.
 */


private fun Project . getOrRegisterTask ( name : String ) : TaskProvider < out Task >

= if ( tasks . names . contains ( name ) ) { <EOL> tasks . named ( name ) <EOL> } else { <EOL> tasks . register ( name , DefaultTask :: class . java ) <EOL> }

/**
 * Looks for task with given name in the given project.
 * If such task isn't found, will register it. Returns registered/found task.
 */


public fun isPublicApi ( symbol : KtSymbolWithVisibility ) : Boolean

= withValidityAssertion { <EOL> analysisSession . visibilityChecker . isPublicApi ( symbol ) <EOL> }

/**
 * Returns true for effectively public symbols, including internal declarations with @PublishedApi annotation.
 * In 'Explicit API' mode explicit visibility modifier and explicit return types are required for such symbols.
 * See FirExplicitApiDeclarationChecker.kt
 */


public fun argB8888ToNCHWArray ( encodedPixels : IntArray , width : Int , height : Int , channels : Int ) : FloatArray

{ <EOL> val output = FloatArray ( width * height * channels ) <EOL> val stride = width * height <EOL> for ( i in <NUM_LIT:0> until width ) { <EOL> for ( j in <NUM_LIT:0> until height ) { <EOL> val idx = height * i + j <EOL> val pixelValue = encodedPixels [ idx ] <EOL> val ( r , g , b ) = decodeARGB8888Pixel ( pixelValue ) <EOL> output [ idx ] = r <EOL> output [ idx + stride ] = g <EOL> output [ idx + stride * <NUM_LIT:2> ] = b <EOL> } <EOL> } <EOL> return output <EOL> }

/**
 * Decodes an ARGB8888 encoded pixel array to a float array containing the red, green, blue components in NCWH layout.
 */


public fun argB8888ToNHWCArray ( encodedPixels : IntArray , width : Int , height : Int , channels : Int ) : FloatArray

{ <EOL> val output = FloatArray ( width * height * channels ) <EOL> var position = <NUM_LIT:0> <EOL> for ( pixelValue in encodedPixels ) { <EOL> val ( r , g , b ) = decodeARGB8888Pixel ( pixelValue ) <EOL> output [ position ++ ] = r <EOL> output [ position ++ ] = g <EOL> output [ position ++ ] = b <EOL> } <EOL> return output <EOL> }

/**
 * Decodes an ARGB8888 encoded pixel array to a float array containing the red, green, blue components in NHWC layout.
 */


public fun decodeARGB8888Pixel ( pixelValue : Int ) : Triple < Float , Float , Float >

{ <EOL> val r = ( pixelValue shr <NUM_LIT:16> and <NUM_LIT> ) . toFloat ( ) <EOL> val g = ( pixelValue shr <NUM_LIT:8> and <NUM_LIT> ) . toFloat ( ) <EOL> val b = ( pixelValue and <NUM_LIT> ) . toFloat ( ) <EOL> return Triple ( r , g , b ) <EOL> }

/**
 * Decodes an ARGB8888 encoded pixel to a red, green, blue components.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < T : Number , D : Dimension > Math . exp ( a : MultiArray < T , D > ) : NDArray < Double , D >

= this . mathEx . exp ( a )

/**
 * Returns a ndarray of Double from the given ndarray to each element of which an exp function has been applied.
 */


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

= this . mathEx . expF ( a )

/**
 * Returns a ndarray of Float from the given ndarray to each element of which an exp function has been applied.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > Math . exp ( a : MultiArray < ComplexFloat , D > ) : NDArray < ComplexFloat , D >

= this . mathEx . expCF ( a )

/**
 * Returns a ndarray of [ComplexFloat] from the given ndarray to each element of which an exp function has been applied.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < D : Dimension > Math . exp ( a : MultiArray < ComplexDouble , D > ) : NDArray < ComplexDouble , D >

= this . mathEx . expCD ( a )

/**
 * Returns a ndarray of [ComplexDouble] from the given ndarray to each element of which an exp function has been applied.
 */


private fun checkUnambiguousClassifiers ( foundClassifierSymbol : FirClassifierSymbol < * > , newClassifierSymbol : FirClassifierSymbol < * > , session : FirSession , ) : CheckUnambiguousClassifiersResult

{ <EOL> val classTypealiasesThatDontCauseAmbiguity = session . platformClassMapper . classTypealiasesThatDontCauseAmbiguity <EOL> if ( foundClassifierSymbol is FirTypeAliasSymbol && newClassifierSymbol is FirRegularClassSymbol && classTypealiasesThatDontCauseAmbiguity [ newClassifierSymbol . classId ] == foundClassifierSymbol . classId ) { <EOL> return CheckUnambiguousClassifiersResult ( shouldReplaceResult = true , isAmbiguousResult = false ) <EOL> } <EOL> if ( newClassifierSymbol is FirTypeAliasSymbol && foundClassifierSymbol is FirRegularClassSymbol && classTypealiasesThatDontCauseAmbiguity [ foundClassifierSymbol . classId ] == newClassifierSymbol . classId ) { <EOL> return CheckUnambiguousClassifiersResult ( shouldReplaceResult = false , isAmbiguousResult = false ) <EOL> } <EOL> return CheckUnambiguousClassifiersResult ( shouldReplaceResult = false , isAmbiguousResult = true ) <EOL> }

/**
 * Handle special cases when classifiers don't cause ambiguity (`Throws`)
 *
 * The following output options are possible:
 * * `shouldReplaceResult = true, isAmbiguousResult = false` means successful disambiguation
 * but the previous result should be replaced with the new one (typically class symbol wins typealias)
 * * `shouldReplaceResult = false, isAmbiguousResult = false` means successful disambiguation
 * but the new result should be discarded
 * * `shouldReplaceResult = false, isAmbiguousResult = true` means unsuccessful disambiguation
 * and both results become irrelevant
 */


private fun convertClass ( clazz : ClassNode , lineMappings : KaptLineMappingCollector , packageFqName : String , isTopLevel : Boolean ) : JCClassDecl ?

{ <EOL> if ( isSynthetic ( clazz . access ) ) return null <EOL> if ( ! checkIfValidTypeName ( clazz , Type . getObjectType ( clazz . name ) ) ) return null <EOL> val descriptor = kaptContext . origins [ clazz ] ? . descriptor ? : return null <EOL> val isNested : Boolean <EOL> val isInner : Boolean <EOL> if ( descriptor is ClassDescriptor ) { <EOL> isNested = descriptor . isNested <EOL> isInner = isNested && descriptor . isInner <EOL> } else { <EOL> isNested = false <EOL> isInner = false <EOL> } <EOL> val flags = getClassAccessFlags ( clazz , descriptor , isInner , isNested ) <EOL> val isEnum = clazz . isEnum ( ) <EOL> val isAnnotation = clazz . isAnnotation ( ) <EOL> val modifiers = convertModifiers ( clazz , flags , if ( isEnum ) ElementKind . ENUM else ElementKind . CLASS , packageFqName , clazz . visibleAnnotations , clazz . invisibleAnnotations , descriptor . annotations ) <EOL> val isDefaultImpls = clazz . name . endsWith ( "<STR_LIT>" ) <EOL> && isPublic ( clazz . access ) && isFinal ( clazz . access ) <EOL> && descriptor is ClassDescriptor <EOL> && descriptor . kind == ClassKind . INTERFACE <EOL> if ( isDefaultImpls && ( isTopLevel || ( clazz . fields . isNullOrEmpty ( ) && clazz . methods . isNullOrEmpty ( ) ) ) ) { <EOL> return null <EOL> } <EOL> val simpleName = getClassName ( clazz , descriptor , isDefaultImpls , packageFqName ) <EOL> if ( ! isValidIdentifier ( simpleName ) ) return null <EOL> val interfaces = mapJList ( clazz . interfaces ) { <EOL> if ( isAnnotation && it == "<STR_LIT>" ) return@mapJList null <EOL> treeMaker . FqName ( treeMaker . getQualifiedName ( it ) ) <EOL> } <EOL> val superClass = treeMaker . FqName ( treeMaker . getQualifiedName ( clazz . superName ) ) <EOL> val genericType = signatureParser . parseClassSignature ( clazz . signature , superClass , interfaces ) <EOL> class EnumValueData ( val field : FieldNode , val innerClass : InnerClassNode ? , val correspondingClass : ClassNode ? ) <EOL> val enumValuesData = clazz . fields . filter { it . isEnumValue ( ) } . map { field -> <EOL> var foundInnerClass : InnerClassNode ? = null <EOL> var correspondingClass : ClassNode ? = null <EOL> for ( innerClass in clazz . innerClasses ) { <EOL> if ( innerClass . innerName != field . name ) continue <EOL> val classNode = compiledClassByName [ innerClass . name ] ? : continue <EOL> if ( classNode . superName != clazz . name ) continue <EOL> correspondingClass = classNode <EOL> foundInnerClass = innerClass <EOL> break <EOL> } <EOL> EnumValueData ( field , foundInnerClass , correspondingClass ) <EOL> } <EOL> val enumValues : JavacList < JCTree > = mapJList ( enumValuesData ) { data -> <EOL> val constructorArguments = Type . getArgumentTypes ( clazz . methods . firstOrNull { <EOL> it . name == "<STR_LIT:<init>>" && Type . getArgumentsAndReturnSizes ( it . desc ) . shr ( <NUM_LIT:2> ) >= <NUM_LIT:2> <EOL> } ? . desc ? : "<STR_LIT>" ) <EOL> val args = mapJList ( constructorArguments . drop ( <NUM_LIT:2> ) ) { convertLiteralExpression ( clazz , getDefaultValue ( it ) ) } <EOL> val def = data . correspondingClass ? . let { convertClass ( it , lineMappings , packageFqName , false ) } <EOL> convertField ( data . field , clazz , lineMappings , packageFqName , treeMaker . NewClass ( null , JavacList . nil ( ) , treeMaker . Ident ( treeMaker . name ( data . field . name ) ) , args , def ) ) <EOL> } <EOL> val fieldsPositions = mutableMapOf < JCTree , MemberData > ( ) <EOL> val fields = mapJList < FieldNode , JCTree > ( clazz . fields ) { fieldNode -> <EOL> if ( fieldNode . isEnumValue ( ) ) { <EOL> null <EOL> } else { <EOL> convertField ( fieldNode , clazz , lineMappings , packageFqName ) ? . also { <EOL> fieldsPositions [ it ] = MemberData ( fieldNode . name , fieldNode . desc , lineMappings . getPosition ( clazz , fieldNode ) ) <EOL> } <EOL> } <EOL> } <EOL> val methodsPositions = mutableMapOf < JCTree , MemberData > ( ) <EOL> val methods = mapJList < MethodNode , JCTree > ( clazz . methods ) { methodNode -> <EOL> if ( isEnum ) { <EOL> if ( methodNode . name == "<STR_LIT>" && methodNode . desc == "<STR_LIT>" ) return@mapJList null <EOL> if ( methodNode . name == "<STR_LIT>" && methodNode . desc == "<STR_LIT>" ) return@mapJList null <EOL> } <EOL> convertMethod ( methodNode , clazz , lineMappings , packageFqName , isInner ) ? . also { <EOL> methodsPositions [ it ] = MemberData ( methodNode . name , methodNode . desc , lineMappings . getPosition ( clazz , methodNode ) ) <EOL> } <EOL> } <EOL> val nestedClasses = mapJList < InnerClassNode , JCTree > ( clazz . innerClasses ) { innerClass -> <EOL> if ( enumValuesData . any { it . innerClass == innerClass } ) return@mapJList null <EOL> if ( innerClass . outerName != clazz . name ) return@mapJList null <EOL> val innerClassNode = compiledClassByName [ innerClass . name ] ? : return@mapJList null <EOL> convertClass ( innerClassNode , lineMappings , packageFqName , false ) <EOL> } <EOL> lineMappings . registerClass ( clazz ) <EOL> val superTypes = calculateSuperTypes ( clazz , genericType ) <EOL> val classPosition = lineMappings . getPosition ( clazz ) <EOL> val sortedFields = JavacList . from ( fields . sortedWith ( MembersPositionComparator ( classPosition , fieldsPositions ) ) ) <EOL> val sortedMethods = JavacList . from ( methods . sortedWith ( MembersPositionComparator ( classPosition , methodsPositions ) ) ) <EOL> return treeMaker . ClassDef ( modifiers , treeMaker . name ( simpleName ) , genericType . typeParameters , superTypes . superClass , superTypes . interfaces , enumValues + sortedFields + sortedMethods + nestedClasses ) . keepKdocCommentsIfNecessary ( clazz ) <EOL> }

/**
 * Returns false for the inner classes or if the origin for the class was not found.
 */


fun contains ( predicate : ( Throwable ) -> Boolean ) : Boolean

{ <EOL> return exceptions . any ( predicate ) <EOL> }

/**
 * Returns true if any of the exceptions in the composite exception match the specified predicate.
 */


{ <EOL> return exceptions . flatMap { it . getCauses ( ) } . distinct ( ) <EOL> }

/**
 * Returns a list of the causes of the exceptions in the composite exception.
 */


fun Throwable . getCauses ( ) : List < Throwable >

{ <EOL> return generateSequence ( cause ) { it . cause } . toList ( ) <EOL> }

/**
 * Returns a list of all the causes of a throwable.
 */


public fun RawSource . buffered ( ) : Source

= RealSource ( this )

/**
 * Returns a new source that buffers reads from the source. The returned source will perform bulk
 * reads into its in-memory buffer. Use this wherever you read a source to get ergonomic and
 * efficient access to data.
 */


public fun RawSink . buffered ( ) : Sink

= RealSink ( this )

/**
 * Returns a new sink that buffers writes to the sink. The returned sink will batch writes to the sink.
 * Use this wherever you write to a sink to get ergonomic and efficient access to data.
 */


= DiscardingSink ( )

/**
 * Returns a sink that discards all data written to it.
 */


public fun < T > yEnd ( column : ColumnReference < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_END , column . name ( ) , null ) <EOL> }

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


public fun < T > yEnd ( column : KProperty < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_END , column . name , null ) <EOL> }

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


public fun yEnd ( column : String ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping ( Y_END , column , null ) <EOL> }

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


public fun < T > yEnd ( values : Iterable < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_END , values . toList ( ) , null , null ) <EOL> }

/**
 * Maps the `yEnd` aesthetic to iterable of values.
 *
 * @param values the iterable of values to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > yEnd ( values : DataColumn < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_END , values , null ) <EOL> }

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


private fun headerContentHandler ( node : ASTNode ) : List < DocTag >

{ <EOL> val trimmedChildren = node . children . trimWhitespaceToken ( ) <EOL> val children = trimmedChildren . evaluateChildren ( ) <EOL> return DocTagsFromIElementFactory . getInstance ( MarkdownElementTypes . PARAGRAPH , children = children ) <EOL> }

/**
 * Handler for [MarkdownTokenTypes.ATX_CONTENT], which is the content of the header
 * elements like [MarkdownElementTypes.ATX_1], [MarkdownElementTypes.ATX_2] and so on.
 *
 * For example, a header line like `# Header text` is expected to be parsed into:
 * - One [MarkdownTokenTypes.ATX_HEADER] with startOffset = 0, endOffset = 1 (only the `#` symbol)
 * - Composite [MarkdownTokenTypes.ATX_CONTENT] with four children: WHITE_SPACE, TEXT, WHITE_SPACE, TEXT.
 */


private fun List < ASTNode > . trimWhitespaceToken ( ) : List < ASTNode >

{ <EOL> val firstNonWhitespaceIndex = this . indexOfFirst { it . type != MarkdownTokenTypes . WHITE_SPACE } <EOL> if ( firstNonWhitespaceIndex == - <NUM_LIT:1> ) { <EOL> return this <EOL> } <EOL> val lastNonWhitespaceIndex = this . indexOfLast { it . type != MarkdownTokenTypes . WHITE_SPACE } <EOL> return this . subList ( firstNonWhitespaceIndex , lastNonWhitespaceIndex + <NUM_LIT:1> ) <EOL> }

/**
 * @return a sublist of [this] list that does not contain
 * leading and trailing [MarkdownTokenTypes.WHITE_SPACE] elements
 */


private fun processMemberDeclaration ( declaration : FirDeclaration , containingClass : FirClass ? , parent : IrDeclarationParent , delegateFieldToPropertyMap : MultiMap < FirProperty , FirField > ? <EOL> )

{ <EOL> @ OptIn ( UnsafeDuringIrConstructionAPI :: class ) <EOL> fun addDeclarationToParentIfNeeded ( irDeclaration : IrDeclaration ) { <EOL> when ( parent ) { <EOL> is IrFile -> parent . declarations += irDeclaration <EOL> is IrClass -> parent . declarations += irDeclaration <EOL> } <EOL> } <EOL> val isInLocalClass = containingClass != null && ( containingClass !is FirRegularClass || containingClass . isLocal ) <EOL> when ( declaration ) { <EOL> is FirRegularClass -> { <EOL> val irClass = classifierStorage . getIrClass ( declaration ) <EOL> addDeclarationToParentIfNeeded ( irClass ) <EOL> processClassMembers ( declaration , irClass ) <EOL> } <EOL> is FirScript -> { <EOL> require ( parent is IrFile ) <EOL> val irScript = declarationStorage . createIrScript ( declaration ) <EOL> addDeclarationToParentIfNeeded ( irScript ) <EOL> declarationStorage . withScope ( irScript . symbol ) { <EOL> irScript . parent = parent <EOL> for ( scriptDeclaration in declaration . declarations . filterIsInstance < FirRegularClass > ( ) ) { <EOL> registerClassAndNestedClasses ( scriptDeclaration , irScript ) <EOL> } <EOL> for ( scriptDeclaration in declaration . declarations ) { <EOL> when ( scriptDeclaration ) { <EOL> is FirRegularClass -> { <EOL> processClassAndNestedClassHeaders ( scriptDeclaration ) <EOL> } <EOL> is FirTypeAlias -> classifierStorage . createAndCacheIrTypeAlias ( scriptDeclaration , irScript ) <EOL> else -> { } <EOL> } <EOL> } <EOL> for ( scriptDeclaration in declaration . declarations ) { <EOL> if ( scriptDeclaration !is FirAnonymousInitializer ) { <EOL> processMemberDeclaration ( scriptDeclaration , containingClass = null , irScript , delegateFieldToPropertyMap = null ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> is FirSimpleFunction -> { <EOL> declarationStorage . createAndCacheIrFunction ( declaration , parent , isLocal = isInLocalClass ) <EOL> } <EOL> is FirProperty -> { <EOL> if ( containingClass == null || ! declaration . isEnumEntries ( containingClass ) || session . languageVersionSettings . supportsFeature ( LanguageFeature . EnumEntries ) ) { <EOL> val irProperty = declarationStorage . createAndCacheIrProperty ( declaration , parent ) <EOL> delegateFieldToPropertyMap ? . remove ( declaration ) ? . let { delegateFields -> <EOL> val backingField = irProperty . backingField ! ! <EOL> for ( delegateField in delegateFields ) { <EOL> declarationStorage . recordDelegateFieldMappedToBackingField ( delegateField , backingField . symbol ) <EOL> delegatedMemberGenerator . generateWithBodiesIfNeeded ( firField = delegateField , irField = backingField , containingClass ! ! , parent as IrClass ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> is FirField -> { <EOL> if ( ! declaration . isSynthetic ) { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> requireNotNull ( containingClass ) <EOL> requireNotNull ( delegateFieldToPropertyMap ) <EOL> require ( parent is IrClass ) <EOL> val correspondingClassProperty = declaration . findCorrespondingDelegateProperty ( containingClass ) <EOL> if ( correspondingClassProperty == null || correspondingClassProperty . isVar ) { <EOL> val irField = declarationStorage . createDelegateIrField ( declaration , parent ) <EOL> delegatedMemberGenerator . generateWithBodiesIfNeeded ( declaration , irField , containingClass , parent ) <EOL> } else { <EOL> delegateFieldToPropertyMap . putValue ( correspondingClassProperty , declaration ) <EOL> } <EOL> } <EOL> is FirConstructor -> if ( ! declaration . isPrimary ) { <EOL> declarationStorage . createAndCacheIrConstructor ( declaration , { parent as IrClass } , isLocal = isInLocalClass ) <EOL> } <EOL> is FirEnumEntry -> { <EOL> classifierStorage . createAndCacheIrEnumEntry ( declaration , parent as IrClass ) <EOL> } <EOL> is FirAnonymousInitializer -> { <EOL> declarationStorage . createIrAnonymousInitializer ( declaration , parent as IrClass ) <EOL> } <EOL> is FirTypeAlias -> { <EOL> classifierStorage . getCachedTypeAlias ( declaration ) ? . let { irTypeAlias -> <EOL> addDeclarationToParentIfNeeded ( irTypeAlias ) <EOL> } <EOL> } <EOL> is FirCodeFragment -> { <EOL> val codeFragmentClass = classifierStorage . getCachedIrCodeFragment ( declaration ) ! ! <EOL> processCodeFragmentMembers ( declaration , codeFragmentClass ) <EOL> addDeclarationToParentIfNeeded ( codeFragmentClass ) <EOL> } <EOL> else -> { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * This function creates IR declarations for callable members without filling their body
 *
 * @param delegateFieldToPropertyMap is needed to avoid problems with delegation to properties from primary constructor.
 * The thing is that FirFields for delegates are declared before properties from the primary constructor, but in IR we don't
 * create separate IrField for such fields and reuse the backing field of corresponding property.
 * So, this map is used to postpone generation of delegated members until IR for corresponding property will be created
 */


private fun checkGap ( timeZone : TimeZone , gapStart : LocalDateTime )

{ <EOL> val instant = gapStart . toInstant ( timeZone ) <EOL> val adjusted = instant . toLocalDateTime ( timeZone ) <EOL> try { <EOL> assertNotEquals ( gapStart , adjusted ) <EOL> assertEquals ( instant . offsetIn ( timeZone ) , instant . plus ( <NUM_LIT:1> , DateTimeUnit . SECOND ) . offsetIn ( timeZone ) ) <EOL> assertEquals ( instant . minus ( <NUM_LIT:1> , DateTimeUnit . SECOND ) . offsetIn ( timeZone ) , instant . minus ( <NUM_LIT:2> , DateTimeUnit . SECOND ) . offsetIn ( timeZone ) ) <EOL> } catch ( e : Throwable ) { <EOL> throw Exception ( "<STR_LIT>" , e ) <EOL> } <EOL> }

/**
 * [gapStart] is the first non-existent moment.
 */


private fun checkOverlap ( timeZone : TimeZone , overlapStart : LocalDateTime )

{ <EOL> val instantStart = overlapStart . plusNominalSeconds ( - <NUM_LIT:1> ) . toInstant ( timeZone ) . plus ( <NUM_LIT:1> , DateTimeUnit . SECOND ) <EOL> val instantEnd = overlapStart . plusNominalSeconds ( <NUM_LIT:1> ) . toInstant ( timeZone ) . minus ( <NUM_LIT:1> , DateTimeUnit . SECOND ) <EOL> try { <EOL> assertNotEquals ( instantStart , instantEnd ) <EOL> assertEquals ( instantStart . minus ( <NUM_LIT:1> , DateTimeUnit . SECOND ) . offsetIn ( timeZone ) , instantStart . minus ( <NUM_LIT:2> , DateTimeUnit . SECOND ) . offsetIn ( timeZone ) ) <EOL> assertEquals ( instantStart . offsetIn ( timeZone ) , instantEnd . offsetIn ( timeZone ) ) <EOL> } catch ( e : Throwable ) { <EOL> throw Exception ( "<STR_LIT>" , e ) <EOL> } <EOL> }

/**
 * [overlapStart] is the first non-ambiguous date-time.
 */


@ Test <EOL> fun testWithContextDispatching ( )

= runTest { <EOL> var counter = <NUM_LIT:0> <EOL> withContext ( Dispatchers . Default ) { <EOL> counter += <NUM_LIT:1> <EOL> } <EOL> assertEquals ( counter , <NUM_LIT:1> ) <EOL> }

/** Tests that [withContext] that sends work to other threads works in [runTest]. */


@ Test <EOL> fun testJoiningForkedJob ( )

= runTest { <EOL> var counter = <NUM_LIT:0> <EOL> val job = GlobalScope . launch { <EOL> counter += <NUM_LIT:1> <EOL> } <EOL> job . join ( ) <EOL> assertEquals ( counter , <NUM_LIT:1> ) <EOL> }

/** Tests that joining [GlobalScope.launch] works in [runTest]. */


@ Test <EOL> fun testSuspendCoroutine ( )

= runTest { <EOL> val answer = suspendCoroutine < Int > { <EOL> it . resume ( <NUM_LIT:42> ) <EOL> } <EOL> assertEquals ( <NUM_LIT:42> , answer ) <EOL> }

/** Tests [suspendCoroutine] not failing [runTest]. */


@ Test <EOL> fun testNestedRunTestForbidden ( )

= runTest { <EOL> assertFailsWith < IllegalStateException > { <EOL> runTest { } <EOL> } <EOL> }

/** Tests that [runTest] attempts to detect it being run inside another [runTest] and failing in such scenarios. */


@ Test <EOL> fun testRunTestWithZeroDispatchTimeoutWithControlledDispatches ( )

= runTest ( dispatchTimeoutMs = <NUM_LIT:0> ) { <EOL> launch { <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> val deferred = async { <EOL> val job = launch ( StandardTestDispatcher ( testScheduler ) ) { <EOL> launch { <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> job . join ( ) <EOL> } <EOL> deferred . await ( ) <EOL> }

/** Tests that even the dispatch timeout of `0` is fine if all the dispatches go through the same scheduler. */


@ Test <EOL> fun testRunTestWithSmallDispatchTimeout ( )

= testResultMap ( { fn -> <EOL> try { <EOL> fn ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : Throwable ) { <EOL> assertIs < UncompletedCoroutinesError > ( e ) <EOL> } <EOL> } ) { <EOL> runTest ( dispatchTimeoutMs = <NUM_LIT:100> ) { <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT> ) <EOL> <NUM_LIT:3> <EOL> } <EOL> fail ( "<STR_LIT>" ) <EOL> } <EOL> }

/** Tests that too low of a dispatch timeout causes crashes. */


@ Test <EOL> fun testRunTestWithSmallTimeout ( )

= testResultMap ( { fn -> <EOL> try { <EOL> fn ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : Throwable ) { <EOL> assertIs < UncompletedCoroutinesError > ( e ) <EOL> } <EOL> } ) { <EOL> runTest ( timeout = <NUM_LIT:100> . milliseconds ) { <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT> ) <EOL> <NUM_LIT:3> <EOL> } <EOL> fail ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Tests that [runTest] times out after the specified time.
 */


@ Test <EOL> fun testRunTestWithSmallTimeoutAndManyDispatches ( )

= testResultMap ( { fn -> <EOL> try { <EOL> fn ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : Throwable ) { <EOL> assertIs < UncompletedCoroutinesError > ( e ) <EOL> } <EOL> } ) { <EOL> runTest ( timeout = <NUM_LIT:100> . milliseconds ) { <EOL> while ( true ) { <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> <NUM_LIT:3> <EOL> } <EOL> } <EOL> } <EOL> }

/** Tests that [runTest] times out after the specified time, even if the test framework always knows the test is
 * still doing something. */


@ Test <EOL> @ NoJs <EOL> @ NoNative <EOL> fun testListingActiveCoroutinesOnTimeout ( ) : TestResult

{ <EOL> val name1 = "<STR_LIT>" <EOL> val name2 = "<STR_LIT>" <EOL> return testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : UncompletedCoroutinesError ) { <EOL> assertContains ( e . message ? : "<STR_LIT>" , name1 ) <EOL> assertFalse ( ( e . message ? : "<STR_LIT>" ) . contains ( name2 ) ) <EOL> } <EOL> } ) { <EOL> runTest ( dispatchTimeoutMs = <NUM_LIT:10> ) { <EOL> launch ( CoroutineName ( name1 ) ) { <EOL> CompletableDeferred < Unit > ( ) . await ( ) <EOL> } <EOL> launch ( CoroutineName ( name2 ) ) { <EOL> } <EOL> } <EOL> } <EOL> }

/** Tests that, on timeout, the names of the active coroutines are listed,
 * whereas the names of the completed ones are not. */


@ Test <EOL> fun testFailureWithPendingCoroutine ( )

= testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : UncompletedCoroutinesError ) { <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_MEMBER>" , "<STR_LIT:INVISIBLE_REFERENCE>" ) <EOL> val suppressed = unwrap ( e ) . suppressedExceptions <EOL> assertEquals ( <NUM_LIT:1> , suppressed . size , "<STR_LIT>" ) <EOL> assertIs < TestException > ( suppressed [ <NUM_LIT:0> ] ) . also { <EOL> assertEquals ( "<STR_LIT:A>" , it . message ) <EOL> } <EOL> } <EOL> } ) { <EOL> runTest ( timeout = <NUM_LIT:10> . milliseconds ) { <EOL> launch ( start = CoroutineStart . UNDISPATCHED ) { <EOL> withContext ( NonCancellable + Dispatchers . Default ) { <EOL> delay ( <NUM_LIT:100> . milliseconds ) <EOL> } <EOL> } <EOL> throw TestException ( "<STR_LIT:A>" ) <EOL> } <EOL> }

/** Tests that the [UncompletedCoroutinesError] suppresses an exception with which the coroutine is completing. */


@ Test <EOL> fun testRunTestWithLargeDispatchTimeout ( )

= runTest ( dispatchTimeoutMs = <NUM_LIT> ) { <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> }

/** Tests that real delays can be accounted for with a large enough dispatch timeout. */


@ Test <EOL> fun testRunTestWithLargeTimeout ( )

= runTest ( timeout = <NUM_LIT> . milliseconds ) { <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> }

/** Tests that delays can be accounted for with a large enough timeout. */


@ Test <EOL> fun testRunTestTimingOutAndThrowing ( )

= testResultMap ( { fn -> <EOL> try { <EOL> fn ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : UncompletedCoroutinesError ) { <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_MEMBER>" , "<STR_LIT:INVISIBLE_REFERENCE>" ) <EOL> val suppressed = unwrap ( e ) . suppressedExceptions <EOL> assertEquals ( <NUM_LIT:1> , suppressed . size , "<STR_LIT>" ) <EOL> assertIs < TestException > ( suppressed [ <NUM_LIT:0> ] ) . also { <EOL> assertEquals ( "<STR_LIT:A>" , it . message ) <EOL> } <EOL> } <EOL> } ) { <EOL> runTest ( timeout = <NUM_LIT:100> . milliseconds ) { <EOL> coroutineContext [ CoroutineExceptionHandler ] ! ! . handleException ( coroutineContext , TestException ( "<STR_LIT:A>" ) ) <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT> ) <EOL> <NUM_LIT:3> <EOL> } <EOL> fail ( "<STR_LIT>" ) <EOL> } <EOL> }

/** Tests uncaught exceptions being suppressed by the dispatch timeout error. */


@ Test <EOL> fun testRunTestWithIllegalContext ( )

{ <EOL> for ( ctx in TestScopeTest . invalidContexts ) { <EOL> assertFailsWith < IllegalArgumentException > { <EOL> runTest ( ctx ) { } <EOL> } <EOL> } <EOL> }

/** Tests that passing invalid contexts to [runTest] causes it to fail (on JS, without forking). */


@ Test <EOL> fun testThrowingInRunTestBody ( )

= testResultMap ( { <EOL> assertFailsWith < RuntimeException > { it ( ) } <EOL> } ) { <EOL> runTest { <EOL> throw RuntimeException ( ) <EOL> } <EOL> }

/** Tests that throwing exceptions in [runTest] fails the test with them. */


@ Test <EOL> fun testThrowingInRunTestPendingTask ( )

= testResultMap ( { <EOL> assertFailsWith < RuntimeException > { it ( ) } <EOL> } ) { <EOL> runTest { <EOL> launch { <EOL> delay ( SLOW ) <EOL> throw RuntimeException ( ) <EOL> } <EOL> } <EOL> }

/** Tests that throwing exceptions in pending tasks [runTest] fails the test with them. */


@ Test <EOL> fun testChildrenCancellationOnTestBodyFailure ( ) : TestResult

{ <EOL> var job : Job ? = null <EOL> return testResultMap ( { <EOL> assertFailsWith < AssertionError > { it ( ) } <EOL> assertTrue ( job ! ! . isCancelled ) <EOL> } ) { <EOL> runTest { <EOL> job = launch { <EOL> while ( true ) { <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> } <EOL> throw AssertionError ( ) <EOL> } <EOL> } <EOL> }

/** Tests that, once the test body has thrown, the child coroutines are cancelled. */


= testResultMap ( { <EOL> assertFailsWith < TimeoutCancellationException > { it ( ) } <EOL> } ) { <EOL> runTest { <EOL> withTimeout ( <NUM_LIT> ) { <EOL> launch { <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> } <EOL> } <EOL> }

/** Tests that [runTest] reports [TimeoutCancellationException]. */


@ Test <EOL> fun testRunTestThrowsRootCause ( )

= testResultMap ( { <EOL> assertFailsWith < TestException > { it ( ) } <EOL> } ) { <EOL> runTest { <EOL> launch { <EOL> throw TestException ( ) <EOL> } <EOL> } <EOL> }

/** Checks that [runTest] throws the root cause and not [JobCancellationException] when a child coroutine throws. */


@ Test <EOL> fun testCompletesOwnJob ( ) : TestResult

{ <EOL> var handlerCalled = false <EOL> return testResultMap ( { <EOL> it ( ) <EOL> assertTrue ( handlerCalled ) <EOL> } ) { <EOL> runTest { <EOL> coroutineContext . job . invokeOnCompletion { <EOL> handlerCalled = true <EOL> } <EOL> } <EOL> } <EOL> }

/** Tests that [runTest] completes its job. */


@ Test <EOL> fun testDoesNotCompleteGivenJob ( ) : TestResult

{ <EOL> var handlerCalled = false <EOL> val job = Job ( ) <EOL> job . invokeOnCompletion { <EOL> handlerCalled = true <EOL> } <EOL> return testResultMap ( { <EOL> it ( ) <EOL> assertFalse ( handlerCalled ) <EOL> assertEquals ( <NUM_LIT:0> , job . children . filter { it . isActive } . count ( ) ) <EOL> } ) { <EOL> runTest ( job ) { <EOL> assertTrue ( coroutineContext . job in job . children ) <EOL> } <EOL> } <EOL> }

/** Tests that [runTest] doesn't complete the job that was passed to it as an argument. */


@ Test <EOL> fun testSuppressedExceptions ( )

= testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : TestException ) { <EOL> assertEquals ( "<STR_LIT>" , e . message ) <EOL> val suppressed = e . suppressedExceptions + <EOL> ( e . suppressedExceptions . firstOrNull ( ) ? . suppressedExceptions ? : emptyList ( ) ) <EOL> assertEquals ( <NUM_LIT:3> , suppressed . size ) <EOL> assertEquals ( "<STR_LIT:x>" , suppressed [ <NUM_LIT:0> ] . message ) <EOL> assertEquals ( "<STR_LIT:y>" , suppressed [ <NUM_LIT:1> ] . message ) <EOL> assertEquals ( "<STR_LIT:z>" , suppressed [ <NUM_LIT:2> ] . message ) <EOL> } <EOL> } ) { <EOL> runTest { <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:x>" ) } <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:y>" ) } <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:z>" ) } <EOL> throw TestException ( "<STR_LIT>" ) <EOL> } <EOL> }

/** Tests that, when the test body fails, the reported exceptions are suppressed. */


@ Test <EOL> fun testScopeRunTestExceptionHandler ( ) : TestResult

{ <EOL> val scope = TestScope ( ) <EOL> return testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : TestException ) { <EOL> } <EOL> } ) { <EOL> scope . runTest { <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:x>" ) } <EOL> } <EOL> } <EOL> }

/** Tests that [TestScope.runTest] does not inherit the exception handler and works. */


@ Test <EOL> fun testCoroutineCompletingWithoutDispatch ( )

= runTest ( timeout = Duration . INFINITE ) { <EOL> launch ( Dispatchers . Default ) { delay ( <NUM_LIT:100> ) } <EOL> }

/**
 * Tests that if the main coroutine is completed without a dispatch, [runTest] will not consider this to be
 * inactivity.
 *
 * The test will hang if this is not the case.
 */


@ Test <EOL> @ Ignore <EOL> fun testExceptionCaptorCleanedUpOnPreliminaryExit ( ) : TestResult

= testResultChain ( { <EOL> println ( "<STR_LIT>" ) <EOL> runTest { } <EOL> } , { <EOL> it . getOrThrow ( ) <EOL> println ( "<STR_LIT>" ) <EOL> createTestResult { <EOL> launch ( NonCancellable ) { throw TestException ( "<STR_LIT:A>" ) } <EOL> } <EOL> } , { <EOL> it . getOrThrow ( ) <EOL> println ( "<STR_LIT>" ) <EOL> try { <EOL> runTest { <EOL> fail ( "<STR_LIT>" ) <EOL> } <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : UncaughtExceptionsBeforeTest ) { <EOL> val cause = e . suppressedExceptions . single ( ) <EOL> assertIs < TestException > ( cause ) <EOL> assertEquals ( "<STR_LIT:A>" , cause . message ) <EOL> } <EOL> println ( "<STR_LIT>" ) <EOL> runTest { <EOL> } <EOL> } , { <EOL> it . getOrThrow ( ) <EOL> println ( "<STR_LIT>" ) <EOL> createTestResult { <EOL> launch ( NonCancellable ) { throw TestException ( "<STR_LIT:B>" ) } <EOL> } <EOL> } , { <EOL> it . getOrThrow ( ) <EOL> println ( "<STR_LIT>" ) <EOL> try { <EOL> runTest { <EOL> fail ( "<STR_LIT>" ) <EOL> } <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : Exception ) { <EOL> val cause = e . suppressedExceptions . single ( ) <EOL> assertIs < TestException > ( cause ) <EOL> assertEquals ( "<STR_LIT:B>" , cause . message ) <EOL> } <EOL> println ( "<STR_LIT>" ) <EOL> runTest { <EOL> } <EOL> } )

/**
 * Tests that [runTest] cleans up the exception handler even if it threw on initialization.
 *
 * This test must be run manually, because it writes garbage to the log.
 *
 * The JVM-only source set contains a test equivalent to this one that isn't ignored.
 */


private fun InternalKotlinSourceSet . configureLegacyMetadataDependenciesConfigurations ( resolvableMetadataConfiguration : Configuration )

{ <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> listOf ( apiMetadataConfigurationName , implementationMetadataConfigurationName , compileOnlyMetadataConfigurationName ) . forEach { configurationName -> <EOL> val configuration = project . configurations . getByName ( configurationName ) <EOL> configuration . extendsFrom ( resolvableMetadataConfiguration ) <EOL> configuration . shouldResolveConsistentlyWith ( resolvableMetadataConfiguration ) <EOL> } <EOL> }

/**
Older IDEs still rely on resolving the metadata configurations explicitly.
Dependencies will be coming from extending the newer 'resolvableMetadataConfiguration'.

the intransitiveMetadataConfigurationName will not extend this mechanism, since it only
relies on dependencies being added explicitly by the Kotlin Gradle Plugin
 */


fun getSimpleName ( call : JsInvocation ) : JsName ?

{ <EOL> val qualifier = call . qualifier <EOL> return ( qualifier as? JsNameRef ) ? . name <EOL> }

/**
 * Gets invocation qualifier name.
 *
 * @returns `f` for `_.foo.f()` call
 */


fun getSimpleIdent ( call : JsInvocation ) : String ?

{ <EOL> var qualifier : JsExpression ? = call . qualifier <EOL> qualifiers @ while ( qualifier != null ) { <EOL> when ( qualifier ) { <EOL> is JsInvocation -> { <EOL> val callableQualifier = qualifier <EOL> qualifier = callableQualifier . qualifier <EOL> if ( isCallInvocation ( callableQualifier ) ) { <EOL> qualifier = ( qualifier as? JsNameRef ) ? . qualifier <EOL> } <EOL> } <EOL> is HasName -> return qualifier . name ? . ident <EOL> else -> break@qualifiers <EOL> } <EOL> } <EOL> return null <EOL> }

/**
 * Tries to get ident for call.
 *
 * @returns first name ident (iterating through qualifier chain)
 */


fun isCallInvocation ( invocation : JsInvocation ) : Boolean

{ <EOL> val qualifier = invocation . qualifier as? JsNameRef <EOL> val arguments = invocation . arguments <EOL> if ( qualifier . name ? . descriptor != null ) return false <EOL> return qualifier ? . ident == Namer . CALL_FUNCTION && arguments . isNotEmpty ( ) && qualifier . qualifier != null <EOL> }

/**
 * Tests if invocation is JavaScript call function
 *
 * @return true if invocation is something like `x.call(thisReplacement)`
 * false otherwise
 */


fun hasCallerQualifier ( invocation : JsInvocation ) : Boolean

{ <EOL> return getCallerQualifierImpl ( invocation ) != null <EOL> }

/**
 * Checks if invocation has qualifier before call.
 *
 * @return true, if invocation is similar to `something.f()`
 * false, if invocation is similar to `f()`
 */


fun getCallerQualifier ( invocation : JsInvocation ) : JsExpression

{ <EOL> return getCallerQualifierImpl ( invocation ) ? : <EOL> throw AssertionError ( "<STR_LIT>" ) <EOL> }

/**
 * Gets qualifier preceding call.
 *
 * @return caller for invocation of type `caller.f()`,
 * where caller is any JsNameRef (for example a.b.c. etc.)
 *
 * @throws AssertionError, if invocation does not have caller qualifier.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Char ( code : UShort ) : Char

{ <EOL> return code . toInt ( ) . toChar ( ) <EOL> }

/**
 * Creates a Char with the specified [code].
 *
 * @sample samples.text.Chars.charFromCode
 */


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CV . ResNet50 ( ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val fileDataLoader = modelType . createPreprocessing ( model ) . fileLoader ( ) <EOL> val imageNetClassLabels = modelHub . loadClassLabels ( ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . MAE , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> it . loadWeights ( hdfFile ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputData = fileDataLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val res = it . predictLabel ( inputData ) <EOL> println ( "<STR_LIT>" ) <EOL> val top5 = it . predictTop5Labels ( inputData , imageNetClassLabels ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> it . save ( File ( PATH_TO_MODEL ) , savingFormat = SavingFormat . JsonConfigCustomVariables ( isKerasFullyCompatible = true ) , writingMode = WritingMode . OVERRIDE ) <EOL> it . save ( File ( PATH_TO_MODEL_2 ) , savingFormat = SavingFormat . TfGraphCustomVariables , writingMode = WritingMode . OVERRIDE ) <EOL> } <EOL> val inferenceModel = TensorFlowInferenceModel . load ( File ( PATH_TO_MODEL_2 ) ) <EOL> inferenceModel . use { <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputData = fileDataLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val res = it . predict ( inputData ) <EOL> println ( "<STR_LIT>" ) <EOL> val top5 = it . predictTop5Labels ( inputData , imageNetClassLabels ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> } <EOL> val model2 = Functional . loadModelConfiguration ( File ( "<STR_LIT>" ) ) <EOL> model2 . use { <EOL> it . compile ( optimizer = RMSProp ( ) , loss = Losses . MAE , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . loadWeights ( File ( PATH_TO_MODEL ) ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputData = fileDataLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val res = it . predictLabel ( inputData ) <EOL> println ( "<STR_LIT>" ) <EOL> val top5 = it . predictTop5Labels ( inputData , imageNetClassLabels ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * This example demonstrates the inference concept on ResNet'50 model and model, model weight export and import back:
 * - 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 ResNet'50 during training on ImageNet dataset) is applied to each image before prediction.
 * - Model is exported in both: Keras-style JSON format and graph .pb format ; weights are exported in custom (TXT) format.
 * - It saves all the data to the project root directory.
 * - The first [TensorFlowInferenceModel] is created via graph and weights loading.
 * - Model again predicts on a few images located in resources.
 * - The second [Functional] model is created via JSON configuration and weights loading.
 * - Model again predicts on a few images located in resources.
 */


open fun shouldProcessNonAload0FieldAccessChains ( ) : Boolean

= false

/**constructors could access outer not through
 * ALOAD 0 //this
 * GETFIELD this$0 //outer
 * GETFIELD this$0 //outer of outer
 * but directly through constructor parameter
 * ALOAD X //outer
 * GETFIELD this$0 //outer of outer
 */


private fun isDefaultValueForType ( type : Type , value : Any ? ) : Boolean

= <EOL> when ( type ) { <EOL> Type . BOOLEAN_TYPE -> value is Boolean && ! value <EOL> Type . CHAR_TYPE -> value is Char && value . code == <NUM_LIT:0> <EOL> Type . BYTE_TYPE , Type . SHORT_TYPE , Type . INT_TYPE , Type . LONG_TYPE -> value is Number && value . toLong ( ) == <NUM_LIT:0L> <EOL> Type . FLOAT_TYPE -> value is Number && value . toFloat ( ) . equals ( <NUM_LIT:0.0f> ) <EOL> Type . DOUBLE_TYPE -> value is Number && value . toDouble ( ) . equals ( <NUM_LIT:0.0> ) <EOL> else -> ! isPrimitive ( type ) && value == null <EOL> }

/**
 * Returns true if the given constant value is the JVM's default value for the given type.
 * See: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.3
 */


fun getKotlinDevRepositoryUrl ( project : Project ) : String ?

{ <EOL> val url = project . rootProject . properties [ "<STR_LIT>" ] as? String <EOL> if ( url != null ) { <EOL> project . logger . info ( """<STR_LIT>""" ) <EOL> } <EOL> return url <EOL> }

/**
 * Kotlin compiler artifacts are expected to be downloaded from maven central by default.
 * In case of compiling with kotlin compiler artifacts that are not published into the MC,
 * a kotlin_repo_url gradle parameter should be specified.
 * To reproduce a build locally, a kotlin/dev repo should be passed.
 *
 * @return an url for a kotlin compiler repository parametrized from command line or gradle.properties,
 * empty string otherwise
 */


fun addDevRepositoryIfEnabled ( repositoryHandler : RepositoryHandler , project : Project )

{ <EOL> val devRepoUrl = getKotlinDevRepositoryUrl ( project ) ? : return <EOL> repositoryHandler . maven { <EOL> url = URI . create ( devRepoUrl ) <EOL> } <EOL> }

/**
 * If the kotlin_repo_url gradle parameter is provided, adds it to the [repositoryHandler].
 */


@ ExperimentalCoroutinesApi <EOL> public actual fun CoroutineScope . newCoroutineContext ( context : CoroutineContext ) : CoroutineContext

{ <EOL> val combined = foldCopies ( coroutineContext , context , true ) <EOL> val debug = if ( DEBUG ) combined + CoroutineId ( COROUTINE_ID . incrementAndGet ( ) ) else combined <EOL> return if ( combined !== Dispatchers . Default && combined [ ContinuationInterceptor ] == null ) <EOL> debug + Dispatchers . Default else debug <EOL> }

/**
 * Creates a context for a new coroutine. It installs [Dispatchers.Default] when no other dispatcher or
 * [ContinuationInterceptor] is specified and adds optional support for debugging facilities (when turned on)
 * and copyable-thread-local facilities on JVM.
 * See [DEBUG_PROPERTY_NAME] for description of debugging facilities on JVM.
 */


@ InternalCoroutinesApi <EOL> public actual fun CoroutineContext . newCoroutineContext ( addedContext : CoroutineContext ) : CoroutineContext

{ <EOL> if ( ! addedContext . hasCopyableElements ( ) ) return this + addedContext <EOL> return foldCopies ( this , addedContext , false ) <EOL> }

/**
 * Creates a context for coroutine builder functions that do not launch a new coroutine, e.g. [withContext].
 * @suppress
 */


private fun foldCopies ( originalContext : CoroutineContext , appendContext : CoroutineContext , isNewCoroutine : Boolean ) : CoroutineContext

{ <EOL> val hasElementsLeft = originalContext . hasCopyableElements ( ) <EOL> val hasElementsRight = appendContext . hasCopyableElements ( ) <EOL> if ( ! hasElementsLeft && ! hasElementsRight ) { <EOL> return originalContext + appendContext <EOL> } <EOL> var leftoverContext = appendContext <EOL> val folded = originalContext . fold < CoroutineContext > ( EmptyCoroutineContext ) { result , element -> <EOL> if ( element !is CopyableThreadContextElement < * > ) return@fold result + element <EOL> val newElement = leftoverContext [ element . key ] <EOL> if ( newElement == null ) { <EOL> return@fold result + if ( isNewCoroutine ) element . copyForChild ( ) else element <EOL> } <EOL> leftoverContext = leftoverContext . minusKey ( element . key ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return@fold result + ( element as CopyableThreadContextElement < Any ? > ) . mergeForChild ( newElement ) <EOL> } <EOL> if ( hasElementsRight ) { <EOL> leftoverContext = leftoverContext . fold < CoroutineContext > ( EmptyCoroutineContext ) { result , element -> <EOL> if ( element is CopyableThreadContextElement < * > ) { <EOL> return@fold result + element . copyForChild ( ) <EOL> } <EOL> return@fold result + element <EOL> } <EOL> } <EOL> return folded + leftoverContext <EOL> }

/**
 * Folds two contexts properly applying [CopyableThreadContextElement] rules when necessary.
 * The rules are the following:
 * - If neither context has CTCE, the sum of two contexts is returned
 * - Every CTCE from the left-hand side context that does not have a matching (by key) element from right-hand side context
 * is [copied][CopyableThreadContextElement.copyForChild] if [isNewCoroutine] is `true`.
 * - Every CTCE from the left-hand side context that has a matching element in the right-hand side context is [merged][CopyableThreadContextElement.mergeForChild]
 * - Every CTCE from the right-hand side context that hasn't been merged is copied
 * - Everything else is added to the resulting context as is.
 */


internal actual inline fun < T > withCoroutineContext ( context : CoroutineContext , countOrElement : Any ? , block : ( ) -> T ) : T

{ <EOL> val oldValue = updateThreadContext ( context , countOrElement ) <EOL> try { <EOL> return block ( ) <EOL> } finally { <EOL> restoreThreadContext ( context , oldValue ) <EOL> } <EOL> }

/**
 * Executes a block using a given coroutine context.
 */


internal actual inline fun < T > withContinuationContext ( continuation : Continuation < * > , countOrElement : Any ? , block : ( ) -> T ) : T

{ <EOL> val context = continuation . context <EOL> val oldValue = updateThreadContext ( context , countOrElement ) <EOL> val undispatchedCompletion = if ( oldValue !== NO_THREAD_ELEMENTS ) { <EOL> continuation . updateUndispatchedCompletion ( context , oldValue ) <EOL> } else { <EOL> null <EOL> } <EOL> try { <EOL> return block ( ) <EOL> } finally { <EOL> if ( undispatchedCompletion == null || undispatchedCompletion . clearThreadContext ( ) ) { <EOL> restoreThreadContext ( context , oldValue ) <EOL> } <EOL> } <EOL> }

/**
 * Executes a block using a context of a given continuation.
 */


internal fun indexSegment ( index : Int , shift : Int ) : Int

= <EOL> ( index shr shift ) and MAX_BRANCHING_FACTOR_MINUS_ONE

/**
 * Gets trie index segment of the specified [index] at the level specified by [shift].
 *
 * `shift` equal to zero corresponds to the root level.
 * For each lower level `shift` increments by [LOG_MAX_BRANCHING_FACTOR].
 */


= dataMap . countOneBits ( )

/** Returns number of entries stored in this trie node (not counting subnodes) */


internal fun hasEntryAt ( positionMask : Int ) : Boolean

{ <EOL> return dataMap and positionMask != <NUM_LIT:0> <EOL> }

/** Returns true if the data bit map has the bit specified by [positionMask] set, indicating there's a data entry in the buffer at that position. */


private fun hasNodeAt ( positionMask : Int ) : Boolean

{ <EOL> return nodeMap and positionMask != <NUM_LIT:0> <EOL> }

/** Returns true if the node bit map has the bit specified by [positionMask] set, indicating there's a subtrie node in the buffer at that position. */


internal fun entryKeyIndex ( positionMask : Int ) : Int

{ <EOL> return ENTRY_SIZE * ( dataMap and ( positionMask - <NUM_LIT:1> ) ) . countOneBits ( ) <EOL> }

/** Gets the index in buffer of the data entry key corresponding to the position specified by [positionMask]. */


internal fun nodeIndex ( positionMask : Int ) : Int

{ <EOL> return buffer . size - <NUM_LIT:1> - ( nodeMap and ( positionMask - <NUM_LIT:1> ) ) . countOneBits ( ) <EOL> }

/** Gets the index in buffer of the subtrie node entry corresponding to the position specified by [positionMask]. */


private fun keyAtIndex ( keyIndex : Int ) : K

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return buffer [ keyIndex ] as K <EOL> }

/** Retrieves the buffer element at the given [keyIndex] as key of a data entry. */


private fun valueAtKeyIndex ( keyIndex : Int ) : V

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return buffer [ keyIndex + <NUM_LIT:1> ] as V <EOL> }

/** Retrieves the buffer element next to the given [keyIndex] as value of a data entry. */


internal fun nodeAtIndex ( nodeIndex : Int ) : TrieNode < K , V >

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return buffer [ nodeIndex ] as TrieNode < K , V > <EOL> }

/** Retrieves the buffer element at the given [nodeIndex] as subtrie node. */


private fun updateNodeAtIndex ( nodeIndex : Int , positionMask : Int , newNode : TrieNode < K , V > ) : TrieNode < K , V >

{ <EOL> val newNodeBuffer = newNode . buffer <EOL> if ( newNodeBuffer . size == <NUM_LIT:2> && newNode . nodeMap == <NUM_LIT:0> ) { <EOL> if ( buffer . size == <NUM_LIT:1> ) { <EOL> newNode . dataMap = nodeMap <EOL> return newNode <EOL> } <EOL> val keyIndex = entryKeyIndex ( positionMask ) <EOL> val newBuffer = buffer . replaceNodeWithEntry ( nodeIndex , keyIndex , newNodeBuffer [ <NUM_LIT:0> ] , newNodeBuffer [ <NUM_LIT:1> ] ) <EOL> return TrieNode ( dataMap xor positionMask , nodeMap xor positionMask , newBuffer ) <EOL> } <EOL> val newBuffer = buffer . copyOf ( buffer . size ) <EOL> newBuffer [ nodeIndex ] = newNode <EOL> return TrieNode ( dataMap , nodeMap , newBuffer ) <EOL> }

/** The given [newNode] must not be a part of any persistent map instance. */


private fun mutableUpdateNodeAtIndex ( nodeIndex : Int , newNode : TrieNode < K , V > , owner : MutabilityOwnership ) : TrieNode < K , V >

{ <EOL> assert ( newNode . ownedBy === owner ) <EOL> if ( buffer . size == <NUM_LIT:1> && newNode . buffer . size == ENTRY_SIZE && newNode . nodeMap == <NUM_LIT:0> ) { <EOL> newNode . dataMap = nodeMap <EOL> return newNode <EOL> } <EOL> if ( ownedBy === owner ) { <EOL> buffer [ nodeIndex ] = newNode <EOL> return this <EOL> } <EOL> val newBuffer = buffer . copyOf ( ) <EOL> newBuffer [ nodeIndex ] = newNode <EOL> return TrieNode ( dataMap , nodeMap , newBuffer , owner ) <EOL> }


private fun makeNode ( keyHash1 : Int , key1 : K , value1 : V , keyHash2 : Int , key2 : K , value2 : V , shift : Int , owner : MutabilityOwnership ? ) : TrieNode < K , V >

{ <EOL> if ( shift > MAX_SHIFT ) { <EOL> return TrieNode ( <NUM_LIT:0> , <NUM_LIT:0> , arrayOf ( key1 , value1 , key2 , value2 ) , owner ) <EOL> } <EOL> val setBit1 = indexSegment ( keyHash1 , shift ) <EOL> val setBit2 = indexSegment ( keyHash2 , shift ) <EOL> if ( setBit1 != setBit2 ) { <EOL> val nodeBuffer = if ( setBit1 < setBit2 ) { <EOL> arrayOf ( key1 , value1 , key2 , value2 ) <EOL> } else { <EOL> arrayOf ( key2 , value2 , key1 , value1 ) <EOL> } <EOL> return TrieNode ( ( <NUM_LIT:1> shl setBit1 ) or ( <NUM_LIT:1> shl setBit2 ) , <NUM_LIT:0> , nodeBuffer , owner ) <EOL> } <EOL> val node = makeNode ( keyHash1 , key1 , value1 , keyHash2 , key2 , value2 , shift + LOG_MAX_BRANCHING_FACTOR , owner ) <EOL> return TrieNode ( <NUM_LIT:0> , <NUM_LIT:1> shl setBit1 , arrayOf < Any ? > ( node ) , owner ) <EOL> }

/** Creates a new TrieNode for holding two given key value entries */


private fun mutablePutAllFromOtherNodeCell ( otherNode : TrieNode < K , V > , positionMask : Int , shift : Int , intersectionCounter : DeltaCounter , mutator : PersistentHashMapBuilder < K , V > ) : TrieNode < K , V >

= when { <EOL> this . hasNodeAt ( positionMask ) -> { <EOL> val targetNode = this . nodeAtIndex ( nodeIndex ( positionMask ) ) <EOL> when { <EOL> otherNode . hasNodeAt ( positionMask ) -> { <EOL> val otherTargetNode = otherNode . nodeAtIndex ( otherNode . nodeIndex ( positionMask ) ) <EOL> targetNode . mutablePutAll ( otherTargetNode , shift + LOG_MAX_BRANCHING_FACTOR , intersectionCounter , mutator ) <EOL> } <EOL> otherNode . hasEntryAt ( positionMask ) -> { <EOL> val keyIndex = otherNode . entryKeyIndex ( positionMask ) <EOL> val key = otherNode . keyAtIndex ( keyIndex ) <EOL> val value = otherNode . valueAtKeyIndex ( keyIndex ) <EOL> val oldSize = mutator . size <EOL> targetNode . mutablePut ( key . hashCode ( ) , key , value , shift + LOG_MAX_BRANCHING_FACTOR , mutator ) . also { <EOL> if ( mutator . size == oldSize ) intersectionCounter . count ++ <EOL> } <EOL> } <EOL> else -> targetNode <EOL> } <EOL> } <EOL> otherNode . hasNodeAt ( positionMask ) -> { <EOL> val otherTargetNode = otherNode . nodeAtIndex ( otherNode . nodeIndex ( positionMask ) ) <EOL> when { <EOL> this . hasEntryAt ( positionMask ) -> { <EOL> val keyIndex = this . entryKeyIndex ( positionMask ) <EOL> val key = this . keyAtIndex ( keyIndex ) <EOL> if ( otherTargetNode . containsKey ( key . hashCode ( ) , key , shift + LOG_MAX_BRANCHING_FACTOR ) ) { <EOL> intersectionCounter . count ++ <EOL> otherTargetNode <EOL> } else { <EOL> val value = this . valueAtKeyIndex ( keyIndex ) <EOL> otherTargetNode . mutablePut ( key . hashCode ( ) , key , value , shift + LOG_MAX_BRANCHING_FACTOR , mutator ) <EOL> } <EOL> } <EOL> else -> otherTargetNode <EOL> } <EOL> } <EOL> else -> { <EOL> val thisKeyIndex = this . entryKeyIndex ( positionMask ) <EOL> val thisKey = this . keyAtIndex ( thisKeyIndex ) <EOL> val thisValue = this . valueAtKeyIndex ( thisKeyIndex ) <EOL> val otherKeyIndex = otherNode . entryKeyIndex ( positionMask ) <EOL> val otherKey = otherNode . keyAtIndex ( otherKeyIndex ) <EOL> val otherValue = otherNode . valueAtKeyIndex ( otherKeyIndex ) <EOL> makeNode ( thisKey . hashCode ( ) , thisKey , thisValue , otherKey . hashCode ( ) , otherKey , otherValue , shift + LOG_MAX_BRANCHING_FACTOR , mutator . ownership ) <EOL> } <EOL> }

/**
 * Updates the cell of this node at [positionMask] with entries from the cell of [otherNode] at [positionMask].
 */


public fun Array < * > . flattenFloats ( ) : FloatArray

{ <EOL> val result = mutableListOf < Float > ( ) <EOL> fun flatten ( array : Any ? ) : Unit = when ( array ) { <EOL> is FloatArray -> array . forEach { result . add ( it ) } <EOL> is Array < * > -> array . forEach { flatten ( it ) } <EOL> else -> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> flatten ( this ) <EOL> return result . toFloatArray ( ) <EOL> }

/**
 * Flattens the given array of float values.
 * @return flattened array
 */


private fun stdlibCommonMainDependency ( kotlin : KotlinMultiplatformExtension )

= <EOL> binaryCoordinates ( "<STR_LIT>" )

/**
 * Refers to the 'commonMain' source set of the kotlin stdlib
 */


internal fun String . indented ( nSpaces : Int = <NUM_LIT:4> , skipFirstLine : Boolean = false ) : String

{ <EOL> val spaces = String ( CharArray ( nSpaces ) { '<CHAR_LIT:U+0020>' } ) <EOL> return lines ( ) <EOL> . withIndex ( ) <EOL> . joinToString ( separator = "<STR_LIT:\n>" ) { ( index , line ) -> <EOL> if ( skipFirstLine && index == <NUM_LIT:0> ) return@joinToString line <EOL> if ( line . isNotBlank ( ) ) "<STR_LIT>" else line <EOL> } <EOL> }

/**
 * @param skipFirstLine if true doesn't indent first line
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override fun start ( ) : Boolean

= false

/**
 * Always returns `false`.
 * @suppress **This an internal API and should not be used from general code.**
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override suspend fun join ( )

{ <EOL> throw UnsupportedOperationException ( "<STR_LIT>" ) <EOL> }

/**
 * Always throws [UnsupportedOperationException].
 * @suppress **This an internal API and should not be used from general code.**
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override fun getCancellationException ( ) : CancellationException

= throw IllegalStateException ( "<STR_LIT>" )

/**
 * Always throws [IllegalStateException].
 * @suppress **This an internal API and should not be used from general code.**
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override fun invokeOnCompletion ( handler : CompletionHandler ) : DisposableHandle

= <EOL> NonDisposableHandle

/**
 * @suppress **This an internal API and should not be used from general code.**
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override fun invokeOnCompletion ( onCancelling : Boolean , invokeImmediately : Boolean , handler : CompletionHandler ) : DisposableHandle

= <EOL> NonDisposableHandle

/**
 * Always returns no-op handle.
 * @suppress **This an internal API and should not be used from general code.**
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override fun cancel ( cause : CancellationException ? )

/**
 * Does nothing.
 * @suppress **This an internal API and should not be used from general code.**
 */


@ Deprecated ( level = DeprecationLevel . HIDDEN , message = "<STR_LIT>" ) <EOL> override fun cancel ( cause : Throwable ? ) : Boolean

= false

/**
 * Always returns `false`.
 * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [cancel].
 */


@ Deprecated ( level = DeprecationLevel . WARNING , message = message ) <EOL> override fun attachChild ( child : ChildJob ) : ChildHandle

= NonDisposableHandle

/**
 * Always returns [NonDisposableHandle] and does not do anything.
 * @suppress **This an internal API and should not be used from general code.**
 */


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


public fun < T : FlatShape < T > > OnnxHighLevelModel < BufferedImage , List < T > > . predictOnCrop ( image : BufferedImage , detectedObject : DetectedObject ) : List < T >

{ <EOL> val objectWidth = detectedObject . xMax - detectedObject . xMin <EOL> val objectHeight = detectedObject . yMax - detectedObject . yMin <EOL> val x1 = ( ( detectedObject . xMin - <NUM_LIT> * objectWidth ) * image . width ) . toInt ( ) . coerceAtLeast ( <NUM_LIT:0> ) <EOL> val y1 = ( ( detectedObject . yMin - <NUM_LIT> * objectHeight ) * image . height ) . toInt ( ) . coerceAtLeast ( <NUM_LIT:0> ) <EOL> val x2 = ( ( detectedObject . xMax + <NUM_LIT> * objectWidth ) * image . width ) . toInt ( ) . coerceAtMost ( image . width ) <EOL> val y2 = ( ( detectedObject . yMax + <NUM_LIT> * objectHeight ) * image . height ) . toInt ( ) . coerceAtMost ( image . height ) <EOL> val cropImage = pipeline < BufferedImage > ( ) . crop { <EOL> left = x1 <EOL> top = y1 <EOL> right = image . width - x2 <EOL> bottom = image . height - y2 <EOL> } . apply ( image ) <EOL> return predict ( cropImage ) . map { shape -> <EOL> shape . map { x , y -> <EOL> ( x1 + x * cropImage . width ) / image . width to <EOL> ( y1 + y * cropImage . height ) / image . height <EOL> } <EOL> } <EOL> }

/**
 * Runs prediction on an image crop, base on the provided [detectedObject]. Could be used for combining several
 * inference models together, for example detecting a face with
 * a [org.jetbrains.kotlinx.dl.onnx.inference.facealignment.FaceDetectionModel], then detecting face landmarks on the face
 * using a [org.jetbrains.kotlinx.dl.onnx.inference.facealignment.Fan2D106FaceAlignmentModel].
 *
 * @param [image] input image
 * @param [detectedObject] object, detected on this image, to run predictions on
 */


public fun invoke ( input : FloatArray ) : FloatArray

/**
 * Invoke some transform for an [input] [FloatArray].
 * @param [input] [FloatArray] to transform.
 * */


public fun denormalizeInplace ( input : FloatArray , scale : Float ) : FloatArray

{ <EOL> input . forEachIndexed { index , value -> input [ index ] = value * scale } <EOL> return input <EOL> }

/**
 * Each array element of an [input] is multiplied in-place by [scale] coefficient.
 * @param [input] [FloatArray] to multiply by [scale].
 * @param [scale] [Float] coefficient.
 */


/**
 * [FooAlias.<caret_1>fooExt]
 *
 * [Foo.<caret_2>fooAliasExt]
 * [FooAlias.<caret_3>fooAliasExt]
 *
 * [FooAlias.<caret_4>anyExt]
 * [FooAlias.<caret_5>otherExt]
 */


@ TemplateTest ( "<STR_LIT>" , [ "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> fun CheckerContext . testAndroidInverseOrder ( )

{ <EOL> subproject ( "<STR_LIT>" ) { <EOL> checkXmlReport ( "<STR_LIT>" ) <EOL> checkXmlReport ( "<STR_LIT>" ) <EOL> checkOutcome ( "<STR_LIT>" , "<STR_LIT:SUCCESS>" ) <EOL> checkOutcome ( "<STR_LIT>" , "<STR_LIT:SUCCESS>" ) <EOL> } <EOL> }

/**
 * A test to verify that the order of application of the Kover plugin does not affect the correct operation.
 * Kover + Kotlin Android Plugin
 */


@ TemplateTest ( "<STR_LIT>" , [ "<STR_LIT>" , "<STR_LIT>" ] ) <EOL> fun CheckerContext . testAndroidMppInverseOrder ( )

{ <EOL> checkXmlReport ( "<STR_LIT>" ) <EOL> checkXmlReport ( "<STR_LIT>" ) <EOL> checkOutcome ( "<STR_LIT>" , "<STR_LIT:SUCCESS>" ) <EOL> checkOutcome ( "<STR_LIT>" , "<STR_LIT:SUCCESS>" ) <EOL> }

/**
 * A test to verify that the order of application of the Kover plugin does not affect the correct operation.
 * Kover + Kotlin Multiplatform Plugin with Android target
 */


fun consume ( parameters : CommonizerParameters , target : CommonizerTarget , moduleResult : ModuleResult )

= Unit

/**
 * Consume a single [ModuleResult] for the specified [CommonizerTarget].
 */


fun targetConsumed ( parameters : CommonizerParameters , target : CommonizerTarget )

= Unit

/**
 * Mark the specified [CommonizerTarget] as fully consumed.
 * It's forbidden to make subsequent [consume] calls for fully consumed targets.
 */


fun allConsumed ( parameters : CommonizerParameters , status : Status )

= Unit

/**
 * Notify that all results have been consumed.
 * It's forbidden to make any subsequent [consume] and [targetConsumed] calls after this call.
 */


private fun isKotlinWithCompatibleAbiVersion ( file : VirtualFile , jvmMetadataVersion : JvmMetadataVersion ) : Boolean

{ <EOL> val clsKotlinBinaryClassCache = ClsKotlinBinaryClassCache . getInstance ( ) <EOL> if ( ! clsKotlinBinaryClassCache . isKotlinJvmCompiledFile ( file ) ) return false <EOL> val kotlinClass = clsKotlinBinaryClassCache . getKotlinBinaryClassHeaderData ( file ) <EOL> return kotlinClass != null && kotlinClass . metadataVersion . isCompatible ( jvmMetadataVersion ) <EOL> }

/**
 * Checks if this file is a compiled Kotlin class file ABI-compatible with the current plugin
 */


/**
 * [ClassWithCompanion.f<caret>oo]
 */


public fun Job . asCompletable ( context : CoroutineContext ) : Completable

= rxCompletable ( context ) { <EOL> this@asCompletable . join ( ) <EOL> }

/**
 * Converts this job to the hot reactive completable that signals
 * with [onCompleted][CompletableObserver.onComplete] when the corresponding job completes.
 *
 * Every subscriber gets the signal at the same time.
 * Unsubscribing from the resulting completable **does not** affect the original job in any way.
 *
 * **Note: This is an experimental api.** Conversion of coroutines primitives to reactive entities may change
 * in the future to account for the concept of structured concurrency.
 *
 * @param context -- the coroutine context from which the resulting completable is going to be signalled
 */


public fun < T > Deferred < T ? > . asMaybe ( context : CoroutineContext ) : Maybe < T >

= rxMaybe ( context ) { <EOL> this@asMaybe . await ( ) <EOL> }

/**
 * Converts this deferred value to the hot reactive maybe that signals
 * [onComplete][MaybeEmitter.onComplete], [onSuccess][MaybeEmitter.onSuccess] or [onError][MaybeEmitter.onError].
 *
 * Every subscriber gets the same completion value.
 * Unsubscribing from the resulting maybe **does not** affect the original deferred value in any way.
 *
 * **Note: This is an experimental api.** Conversion of coroutines primitives to reactive entities may change
 * in the future to account for the concept of structured concurrency.
 *
 * @param context -- the coroutine context from which the resulting maybe is going to be signalled
 */


public fun < T : Any > Deferred < T > . asSingle ( context : CoroutineContext ) : Single < T >

= rxSingle ( context ) { <EOL> this@asSingle . await ( ) <EOL> }

/**
 * Converts this deferred value to the hot reactive single that signals either
 * [onSuccess][SingleObserver.onSuccess] or [onError][SingleObserver.onError].
 *
 * Every subscriber gets the same completion value.
 * Unsubscribing from the resulting single **does not** affect the original deferred value in any way.
 *
 * **Note: This is an experimental api.** Conversion of coroutines primitives to reactive entities may change
 * in the future to account for the concept of structured concurrency.
 *
 * @param context -- the coroutine context from which the resulting single is going to be signalled
 */


public fun < T : Any > ObservableSource < T > . asFlow ( ) : Flow < T >

= callbackFlow { <EOL> val disposableRef = AtomicReference < Disposable > ( ) <EOL> val observer = object : Observer < T > { <EOL> override fun onComplete ( ) { close ( ) } <EOL> override fun onSubscribe ( d : Disposable ) { if ( ! disposableRef . compareAndSet ( null , d ) ) d . dispose ( ) } <EOL> override fun onNext ( t : T ) { <EOL> try { <EOL> trySendBlocking ( t ) <EOL> } catch ( e : InterruptedException ) { <EOL> } <EOL> } <EOL> override fun onError ( e : Throwable ) { close ( e ) } <EOL> } <EOL> subscribe ( observer ) <EOL> awaitClose { disposableRef . getAndSet ( Disposables . disposed ( ) ) ? . dispose ( ) } <EOL> }

/**
 * Transforms given cold [ObservableSource] into cold [Flow].
 *
 * The resulting flow is _cold_, which means that [ObservableSource.subscribe] is called every time a terminal operator
 * is applied to the resulting flow.
 *
 * A channel with the [default][Channel.BUFFERED] buffer size is used. Use the [buffer] operator on the
 * resulting flow to specify a user-defined value and to control what happens when data is produced faster
 * than consumed, i.e. to control the back-pressure behavior. Check [callbackFlow] for more details.
 */


public fun < T : Any > Flow < T > . asObservable ( context : CoroutineContext = EmptyCoroutineContext ) : Observable < T >

= Observable . create { emitter -> <EOL> val job = GlobalScope . launch ( Dispatchers . Unconfined + context , start = CoroutineStart . ATOMIC ) { <EOL> try { <EOL> collect { value -> emitter . onNext ( value ) } <EOL> emitter . onComplete ( ) <EOL> } catch ( e : Throwable ) { <EOL> if ( e !is CancellationException ) { <EOL> if ( ! emitter . tryOnError ( e ) ) { <EOL> handleUndeliverableException ( e , coroutineContext ) <EOL> } <EOL> } else { <EOL> emitter . onComplete ( ) <EOL> } <EOL> } <EOL> } <EOL> emitter . setCancellable ( RxCancellable ( job ) ) <EOL> }

/**
 * Converts the given flow to a cold observable.
 * The original flow is cancelled when the observable subscriber is disposed.
 *
 * An optional [context] can be specified to control the execution context of calls to [Observer] methods.
 * You can set a [CoroutineDispatcher] to confine them to a specific thread and/or various [ThreadContextElement] to
 * inject additional context into the caller thread. By default, the [Unconfined][Dispatchers.Unconfined] dispatcher
 * is used, so calls are performed from an arbitrary thread.
 */


public fun < T : Any > Flow < T > . asFlowable ( context : CoroutineContext = EmptyCoroutineContext ) : Flowable < T >

= <EOL> Flowable . fromPublisher ( asPublisher ( context ) )

/**
 * Converts the given flow to a cold flowable.
 * The original flow is cancelled when the flowable subscriber is disposed.
 *
 * An optional [context] can be specified to control the execution context of calls to [Subscriber] methods.
 * You can set a [CoroutineDispatcher] to confine them to a specific thread and/or various [ThreadContextElement] to
 * inject additional context into the caller thread. By default, the [Unconfined][Dispatchers.Unconfined] dispatcher
 * is used, so calls are performed from an arbitrary thread.
 */


@ Suppress ( "<STR_LIT>" ) <EOL> @ JvmOverloads <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> @ Deprecated ( level = DeprecationLevel . HIDDEN , message = "<STR_LIT>" ) <EOL> public fun < T : Any > Flow < T > . _asFlowable ( context : CoroutineContext = EmptyCoroutineContext ) : Flowable < T >

= <EOL> asFlowable ( context )


@ Suppress ( "<STR_LIT>" ) <EOL> @ JvmOverloads <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> @ Deprecated ( level = DeprecationLevel . HIDDEN , message = "<STR_LIT>" ) <EOL> public fun < T : Any > Flow < T > . _asObservable ( context : CoroutineContext = EmptyCoroutineContext ) : Observable < T >

= asObservable ( context )


@ Deprecated ( message = "<STR_LIT>" , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> fun createKotlinJvmOptions ( ) : KotlinJvmOptionsDeprecated

/**
 * Creates instance of DSL object that should be used to configure JVM/android specific compilation.
 *
 * Note: [CompilerJvmOptions] instance inside [KotlinJvmOptions] is not the same as returned by [createCompilerJvmOptions]
 */


@ Deprecated ( message = "<STR_LIT>" , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> fun registerKotlinJvmCompileTask ( taskName : String ) : TaskProvider < out KotlinJvmCompile >

/**
 * Creates a Kotlin compile task.
 */


fun registerKotlinJvmCompileTask ( taskName : String , moduleName : String ) : TaskProvider < out KotlinJvmCompile >

/**
 * Creates a Kotlin JVM compile task.
 *
 * @param taskName The name of the task to be created.
 * @param moduleName The name of the module for which the task is being created.
 * @return The task provider for the Kotlin JVM compile task.
 */


fun registerKaptGenerateStubsTask ( taskName : String ) : TaskProvider < out KaptGenerateStubs >

/** Creates a stub generation task which creates Java sources stubs from Kotlin sources. */


fun registerKaptTask ( taskName : String ) : TaskProvider < out Kapt >

/** Creates a KAPT task which runs annotation processing. */


fun addCompilerPluginDependency ( dependency : Provider < Any > )

/** Adds a compiler plugin dependency to this project. This can be e.g a Maven coordinate or a project included in the build. */


fun getCompilerPlugins ( ) : FileCollection

/** Returns a [FileCollection] that contains all compiler plugins classpath for this project. */


fun createIfNeeded ( session : FirSession , moduleDataProvider : ModuleDataProvider , kotlinScopeProvider : FirKotlinScopeProvider , packagePartProvider : PackagePartProvider , defaultDeserializationOrigin : FirDeclarationOrigin = FirDeclarationOrigin . Library , ) : OptionalAnnotationClassesProvider ?

{ <EOL> if ( ! packagePartProvider . mayHaveOptionalAnnotationClasses ( ) ) return null <EOL> return OptionalAnnotationClassesProvider ( session , moduleDataProvider , kotlinScopeProvider , packagePartProvider , defaultDeserializationOrigin , ) <EOL> }

/**
 * Creates a new [OptionalAnnotationClassesProvider] if [packagePartProvider] has any optional annotation classes. Otherwise, the
 * symbol provider does not need to be created because it would provide no symbols.
 */


fun isDylib ( file : File , logger : Logger ) : Boolean

{ <EOL> try { <EOL> RandomAccessFile ( file , "<STR_LIT>" ) . use { raf -> <EOL> val magic = raf . readInt ( ) . fromUIntToLong ( ) <EOL> val fileTypeOffset = when ( magic ) { <EOL> MH_CIGAM , MH_CIGAM_64 -> FILE_TYPE_OFFSET <EOL> FAT_MAGIC , FAT_MAGIC_64 -> { <EOL> raf . seek ( FAT_FIRST_MACHO_OFFSET_OFFSET ) <EOL> val firstMachoOffset = raf . readInt ( ) . fromUIntToLong ( ) <EOL> firstMachoOffset + FILE_TYPE_OFFSET <EOL> } <EOL> else -> return false <EOL> } <EOL> raf . seek ( fileTypeOffset ) <EOL> val fileType = raf . readInt ( ) . toLong ( ) <EOL> return fileType == MH_BILYD <EOL> } <EOL> } catch ( e : IOException ) { <EOL> logger . info ( "<STR_LIT>" , e ) <EOL> return false <EOL> } <EOL> }

/**
 * Checks if the [file] is a Mach-O dynamic shared library
 * or a Mach-O fat binary containing a number of dynamic libraries
 */


public fun < T > lower ( column : ColumnReference < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( LOWER , column . name ( ) , null ) <EOL> }

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


public fun < T > lower ( column : KProperty < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( LOWER , column . name , null ) <EOL> }

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


public fun lower ( column : String , ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping ( LOWER , column , null ) <EOL> }

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


public fun < T > lower ( values : Iterable < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( LOWER , values . toList ( ) , null , null ) <EOL> }

/**
 * Maps the `lower` aesthetic to iterable of values.
 *
 * @param values The iterable of values to be mapped.
 * @return A [PositionalMapping] object representing the mapping.
 */


public fun < T > lower ( values : DataColumn < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( LOWER , values , null ) <EOL> }

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


= runTest { <EOL> val d = async { <EOL> delay ( Long . MAX_VALUE ) <EOL> } <EOL> repeat ( n ) { <EOL> val waiter = launch ( start = CoroutineStart . UNDISPATCHED ) { <EOL> val a = ByteArray ( <NUM_LIT> ) <EOL> d . await ( ) <EOL> keepMe ( a ) <EOL> } <EOL> waiter . cancel ( ) <EOL> yield ( ) <EOL> } <EOL> d . cancel ( ) <EOL> }

/**
 * Tests that memory does not leak from cancelled [Deferred.await]
 */


= runTest { <EOL> val j = launch { <EOL> delay ( Long . MAX_VALUE ) <EOL> } <EOL> repeat ( n ) { <EOL> val joiner = launch ( start = CoroutineStart . UNDISPATCHED ) { <EOL> val a = ByteArray ( <NUM_LIT> ) <EOL> j . join ( ) <EOL> keepMe ( a ) <EOL> } <EOL> joiner . cancel ( ) <EOL> yield ( ) <EOL> } <EOL> j . cancel ( ) <EOL> }

/**
 * Tests that memory does not leak from cancelled [Job.join]
 */


public fun < T > slice ( column : ColumnReference < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( SLICE , column . name ( ) , null ) <EOL> }

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


public fun < T > slice ( column : KProperty < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( SLICE , column . name , null ) <EOL> }

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


public fun slice ( column : String , ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping < Any ? > ( SLICE , column , null ) <EOL> }

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


public fun < T > slice ( values : Iterable < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( SLICE , values . toList ( ) , null , null ) <EOL> }

/**
 * Maps the `slice` aesthetic to iterable of values.
 *
 * @param values The iterable of values to be mapped.
 * @return A [PositionalMapping] object representing the mapping.
 */


public fun < T > slice ( values : DataColumn < T > , ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( SLICE , values , null ) <EOL> }

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


fun getModule ( element : PsiElement ) : KtModule

{ <EOL> return ProjectStructureProvider . getModule ( useSiteModule . project , element , useSiteModule ) <EOL> }

/**
 * Returns a [KtModule] for a given [element] in context of the current session.
 *
 * See [ProjectStructureProvider] for more information on contextual modules.
 */


fun trainAndSave ( train : Dataset , test : Dataset , model : Sequential , path : String , accuracyThreshold : Double = <NUM_LIT> )

{ <EOL> model . use { <EOL> it . name = "<STR_LIT>" <EOL> it . compile ( optimizer = SGD ( learningRate = <NUM_LIT> ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . init ( ) <EOL> var accuracy = <NUM_LIT:0.0> <EOL> while ( accuracy < accuracyThreshold ) { <EOL> it . fit ( dataset = train , epochs = <NUM_LIT:1> , batchSize = trainBatchSize , callback = object : Callback ( ) { <EOL> override fun onTrainBatchEnd ( batch : Int , batchSize : Int , event : BatchTrainingEvent , logs : TrainingHistory ) { <EOL> if ( event . metricValues [ <NUM_LIT:0> ] > accuracyThreshold ) { <EOL> println ( "<STR_LIT>" ) <EOL> model . stopTraining = true <EOL> } <EOL> } <EOL> } ) <EOL> accuracy = it . evaluate ( dataset = test , batchSize = testBatchSize ) . metrics [ Metrics . ACCURACY ] ? : <NUM_LIT:0.0> <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> model . save ( modelDirectory = File ( path ) , savingFormat = SavingFormat . JsonConfigCustomVariables ( ) , writingMode = WritingMode . OVERRIDE ) <EOL> } <EOL> }

/**
 * Train [model] on [train] dataset and evaluate accuracy on [test] dataset until [accuracyThreshold] is reached
 * then saves model to the folder [path].
 */


abstract fun lazyResolveToPhase ( element : FirElementWithResolveState , toPhase : FirResolvePhase )

/**
 * @see org.jetbrains.kotlin.fir.symbols.lazyResolveToPhase
 */


abstract fun lazyResolveToPhaseWithCallableMembers ( clazz : FirClass , toPhase : FirResolvePhase )

/**
 * @see org.jetbrains.kotlin.fir.symbols.lazyResolveToPhaseWithCallableMembers
 */


abstract fun lazyResolveToPhaseRecursively ( element : FirElementWithResolveState , toPhase : FirResolvePhase )

/**
 * @see org.jetbrains.kotlin.fir.symbols.lazyResolveToPhaseRecursively
 */


fun FirBasedSymbol < * > . lazyResolveToPhase ( toPhase : FirResolvePhase )

{ <EOL> fir . lazyResolveToPhase ( toPhase ) <EOL> }

/**
 * Lazy resolve [FirBasedSymbol] to [FirResolvePhase].
 *
 * In the case of lazy resolution (inside Analysis API), it checks that the declaration phase `>= toPhase`.
 * If not, it resolves the declaration for the requested phase.
 *
 * If the [lazyResolveToPhase] is called inside a fir transformer,
 * it should always request the phase which is strictly lower than the current transformer phase, otherwise a deadlock/StackOverflow is possible.
 *
 * For the compiler mode, it does nothing, as the compiler is non-lazy.
 *
 * @receiver [FirBasedSymbol] which should be resolved
 * @param toPhase the minimum phase, the declaration should be resolved to after an execution of the [lazyResolveToPhase]
 */


fun FirElementWithResolveState . lazyResolveToPhase ( toPhase : FirResolvePhase )

{ <EOL> invokeLazyResolveToPhase ( toPhase , FirLazyDeclarationResolver :: lazyResolveToPhase ) <EOL> }

/**
 * Lazy resolve [FirElementWithResolveState] to [FirResolvePhase].
 *
 * @see lazyResolveToPhase
 */