private fun IrMemberAccessExpression < * > . simpleBinaryOperatorLhs ( ) : IrExpression ?

{ <EOL> val singleReceiver = ( dispatchReceiver != null ) xor ( extensionReceiver != null ) <EOL> return if ( singleReceiver && valueArgumentsCount == <NUM_LIT:0> ) { <EOL> null <EOL> } else { <EOL> dispatchReceiver <EOL> ? : extensionReceiver <EOL> ? : getValueArgument ( <NUM_LIT:0> ) . takeIf { ( symbol . owner as? IrSimpleFunction ) ? . origin == IrBuiltIns . BUILTIN_OPERATOR } <EOL> } <EOL> }

/**
 * The left-hand side expression of an infix operator/function.
 * For single-value operators returns `null`, for all other infix operators/functions, returns the receiver or the first value argument.
 */


private fun testFileNameFromMappedLocation ( originalFilePath : String , originalFileLineNumber : Int ) : String ?

{ <EOL> val originalFile = File ( originalFilePath ) <EOL> return testServices . moduleStructure . modules . asSequence ( ) . flatMap { module -> module . files . asSequence ( ) . filter { ! it . isAdditional } } <EOL> . findLast { <EOL> it . originalFile . absolutePath == originalFile . absolutePath && it . startLineNumberInOriginalFile <= originalFileLineNumber <EOL> } ? . name <EOL> }

/**
 * An original test file may represent multiple source files (by using the `// FILE: myFile.kt` comments).
 * Sourcemaps contain paths to original test files. However, in test expectations we write names as in the `// FILE:` comments.
 * This function maps a location in the original test file to the name specified in a `// FILE:` comment.
 */


fun < T > run ( body : suspend Context . ( ) -> T )

= inspector . run { <EOL> debugger . enable ( ) <EOL> debugger . setSkipAllPauses ( false ) <EOL> runtime . runIfWaitingForDebugger ( ) <EOL> with ( Context ( this ) ) { <EOL> waitForPauseEvent { it . reason == Debugger . PauseReason . BREAK_ON_START } <EOL> withTimeout ( <NUM_LIT> ) { <EOL> body ( ) <EOL> } <EOL> } <EOL> }

/**
 * By the time [body] is called, the execution is paused, no code is executed yet.
 */


internal inline fun < T > retry ( times : Int , action : ( Int ) -> T , predicate : ( Int , Throwable ) -> Boolean ) : T

{ <EOL> if ( times < <NUM_LIT:1> ) throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> for ( i in <NUM_LIT:1> .. times ) { <EOL> try { <EOL> return action ( i ) <EOL> } catch ( e : Throwable ) { <EOL> if ( i == times || ! predicate ( i , e ) ) throw e <EOL> } <EOL> } <EOL> throw IllegalStateException ( "<STR_LIT>" ) <EOL> }

/**
 * Retries [action] the specified number of [times]. If [action] throws an exception, calls [predicate] to determine if
 * another run should be attempted. If [predicate] returns `false`, rethrows the exception.
 *
 * If after the last attempt results in an exception, rethrows that exception without calling [predicate].
 */


override fun get ( indices : Iterable < Int > ) : ColumnGroup < T >

/**
 * Gets the rows at given indices.
 *
 * NOTE: This doesn't work in the [ColumnsSelectionDsl], use [ColumnsSelectionDsl.cols] to select columns by index.
 */


override fun get ( firstIndex : Int , vararg otherIndices : Int ) : ColumnGroup < T >


override fun get ( range : IntRange ) : ColumnGroup < T >

/**
 * Gets the rows at given range of indices.
 *
 * NOTE: This doesn't work in the [ColumnsSelectionDsl], use [ColumnsSelectionDsl.cols] to select columns by range.
 */


private fun KtTypeReference . getFirBySymbols ( ) : FirElement ?

{ <EOL> val parent = parent <EOL> return when { <EOL> parent is KtParameter && parent . ownerFunction != null && parent . typeReference === this -> <EOL> parent . resolveToFirSymbolOfTypeSafe < FirValueParameterSymbol > ( firResolveSession , FirResolvePhase . TYPES ) ? . fir ? . returnTypeRef <EOL> parent is KtCallableDeclaration && ( parent is KtNamedFunction || parent is KtProperty ) <EOL> && ( parent . receiverTypeReference === this || parent . typeReference === this ) -> { <EOL> val firCallable = parent . resolveToFirSymbolOfTypeSafe < FirCallableSymbol < * > > ( firResolveSession , FirResolvePhase . TYPES ) ? . fir <EOL> if ( parent . receiverTypeReference === this ) { <EOL> firCallable ? . receiverParameter ? . typeRef <EOL> } else firCallable ? . returnTypeRef <EOL> } <EOL> parent is KtConstructorCalleeExpression && parent . parent is KtAnnotationEntry -> { <EOL> fun getFirDeclaration ( annotationEntry : KtAnnotationEntry , ktTypeReference : KtTypeReference ) : FirMemberDeclaration ? { <EOL> if ( annotationEntry . typeReference !== ktTypeReference ) return null <EOL> val declaration = annotationEntry . parent ? . parent as? KtNamedDeclaration ? : return null <EOL> return when { <EOL> declaration is KtClassOrObject -> declaration . resolveToFirSymbolOfTypeSafe < FirClassLikeSymbol < * > > ( firResolveSession , FirResolvePhase . TYPES ) ? . fir <EOL> declaration is KtParameter && declaration . ownerFunction != null -> <EOL> declaration . resolveToFirSymbolOfTypeSafe < FirValueParameterSymbol > ( firResolveSession , FirResolvePhase . TYPES ) ? . fir <EOL> declaration is KtCallableDeclaration && ( declaration is KtNamedFunction || declaration is KtProperty ) -> { <EOL> declaration . resolveToFirSymbolOfTypeSafe < FirCallableSymbol < * > > ( firResolveSession , FirResolvePhase . TYPES ) ? . fir <EOL> } <EOL> else -> return null <EOL> } <EOL> } <EOL> fun FirMemberDeclaration . findAnnotationTypeRef ( annotationEntry : KtAnnotationEntry ) = annotations . find { <EOL> it . psi === annotationEntry <EOL> } ? . annotationTypeRef <EOL> val annotationEntry = parent . parent as KtAnnotationEntry <EOL> val firDeclaration = getFirDeclaration ( annotationEntry , this ) <EOL> if ( firDeclaration != null ) { <EOL> firDeclaration . findAnnotationTypeRef ( annotationEntry ) ? : ( firDeclaration as? FirProperty ) ? . run { <EOL> backingField ? . findAnnotationTypeRef ( annotationEntry ) <EOL> ? : getter ? . findAnnotationTypeRef ( annotationEntry ) <EOL> ? : setter ? . findAnnotationTypeRef ( annotationEntry ) <EOL> } <EOL> } else null <EOL> } <EOL> else -> null <EOL> } <EOL> }

/**
 * Try to get fir element for type reference through symbols.
 * When the type is declared in compiled code this is faster than building FIR from decompiled text.
 */


= Sequential . of ( Input ( IMAGE_SIZE , IMAGE_SIZE , NUM_CHANNELS , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:5> , <NUM_LIT:5> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = kernelInitializer , biasInitializer = biasInitializer , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:5> , <NUM_LIT:5> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = kernelInitializer , biasInitializer = biasInitializer , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , name = "<STR_LIT>" ) , Flatten ( name = "<STR_LIT>" ) , Dense ( outputSize = <NUM_LIT> , activation = Activations . Relu , kernelInitializer = kernelInitializer , biasInitializer = biasInitializer , name = "<STR_LIT>" ) , Dense ( outputSize = <NUM_LIT> , activation = Activations . Relu , kernelInitializer = kernelInitializer , biasInitializer = biasInitializer , name = "<STR_LIT>" ) , Dense ( outputSize = NUMBER_OF_CLASSES , activation = Activations . Linear , kernelInitializer = kernelInitializer , biasInitializer = biasInitializer , name = "<STR_LIT>" ) )

/**
 * Returns classic LeNet-5 model with minor improvements (Sigmoid activation -> ReLU activation, AvgPool layer -> MaxPool layer).
 */


@ JvmName ( "<STR_LIT>" ) <EOL> internal fun Project . isAllowCommonizer ( ) : Boolean

{ <EOL> assert ( state . executed ) { "<STR_LIT>" } <EOL> multiplatformExtensionOrNull ? : return false <EOL> return multiplatformExtension . targets . any { it . platformType == KotlinPlatformType . native } <EOL> && isKotlinGranularMetadataEnabled <EOL> }

/**
 * Function signature needs to be kept stable since this is used during import
 * in IDEs (KotlinCommonizerModelBuilder) < 222
 *
 * IDEs >= will use the [ideaImportDependsOn] infrastructure
 */


= "<STR_LIT>"

/**
 * Returns a string representation of the object.
 */


@ InlineOnly <EOL> public inline fun < T : Closeable ? , R > T . use ( block : ( T ) -> R ) : R

{ <EOL> contract { <EOL> callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> var exception : Throwable ? = null <EOL> try { <EOL> return block ( this ) <EOL> } catch ( e : Throwable ) { <EOL> exception = e <EOL> throw e <EOL> } finally { <EOL> when { <EOL> apiVersionIsAtLeast ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:0> ) -> this . closeFinally ( exception ) <EOL> this == null -> { } <EOL> exception == null -> close ( ) <EOL> else -> <EOL> try { <EOL> close ( ) <EOL> } catch ( closeException : Throwable ) { <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Executes the given [block] function on this resource and then closes it down correctly whether an exception
 * is thrown or not.
 *
 * @param block a function to process this [Closeable] resource.
 * @return the result of [block] function invoked on this resource.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ PublishedApi <EOL> internal fun Closeable ? . closeFinally ( cause : Throwable ? ) : Unit

= when { <EOL> this == null -> { } <EOL> cause == null -> close ( ) <EOL> else -> <EOL> try { <EOL> close ( ) <EOL> } catch ( closeException : Throwable ) { <EOL> cause . addSuppressed ( closeException ) <EOL> } <EOL> }

/**
 * Closes this [Closeable], suppressing possible exception or error thrown by [Closeable.close] function when
 * it's being closed due to some other [cause] exception occurred.
 *
 * The suppressed exception is added to the list of suppressed exceptions of [cause] exception, when it's supported.
 */


fun dependencies ( project : Project ) : Iterable < Any >

/**
 * return anything accepted to be passed to [org.gradle.api.Task.dependsOn]
 *
 * #### Example: Resolver relying on a single task to be executed:
 * ```kotlin
 * object MyResolver : IdeDependencyResolver, WithBuildDependencies {
 * fun resolve(sourceSet: KotlinSourceSet) = // ...
 * fun dependencies(project: Project) = listOf(project.tasks.named("myTask"))
 * }
 * ```
 */


@ ExternalKotlinTargetApi <EOL> fun IdeDependencyResolver ( resolvers : Iterable < IdeDependencyResolver ? > , ) : IdeDependencyResolver

{ <EOL> val resolversList = resolvers . filterNotNull ( ) <EOL> if ( resolversList . isEmpty ( ) ) return IdeDependencyResolver . empty <EOL> return IdeCompositeDependencyResolver ( resolversList ) <EOL> }

/**
 * Creates a composite [IdeDependencyResolver] from the specified [resolvers]
 * Resolvers that are `null` will be ignored.
 * The composite will preserve the order and invoke the [resolvers] in the same order as specified.
 * The resulting set of dependencies will be the superset of all results of individual resolvers.
 */


@ ExternalKotlinTargetApi <EOL> fun IdeDependencyResolver ( vararg resolvers : IdeDependencyResolver ? , ) : IdeDependencyResolver

= IdeDependencyResolver ( resolvers . toList ( ) )


@ OptIn ( ExperimentalContracts :: class ) <EOL> public suspend inline fun < R > selectUnbiased ( crossinline builder : SelectBuilder < R > . ( ) -> Unit ) : R

{ <EOL> contract { <EOL> callsInPlace ( builder , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return UnbiasedSelectImplementation < R > ( coroutineContext ) . run { <EOL> builder ( this ) <EOL> doSelect ( ) <EOL> } <EOL> }

/**
 * Waits for the result of multiple suspending functions simultaneously like [select], but in an _unbiased_
 * way when multiple clauses are selectable at the same time.
 *
 * This unbiased implementation of `select` expression randomly shuffles the clauses before checking
 * if they are selectable, thus ensuring that there is no statistical bias to the selection of the first
 * clauses.
 *
 * See [select] function description for all the other details.
 */


fun < T : Number , E : Number > convolve ( a : KtNDArray < T > , v : KtNDArray < E > , mode : String = "<STR_LIT>" ) : KtNDArray < E >

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

/**
 * Returns the discrete, linear convolution of two one-dimensional sequences.
 */


fun < T : Number > clip ( a : KtNDArray < T > , aMin : T ? , aMax : T ? ) : KtNDArray < T >

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

/**
 * Clip (limit) the values in an array.
 */


fun < T : Number > sqrt ( x : KtNDArray < T > ) : KtNDArray < Double >

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

/**
 * Return the non-negative square-root of an array, element-wise.
 */


fun < T : Number > cbrt ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Return the cube-root of an array, element-wise.
 */


fun < T : Number > square ( x : KtNDArray < T > ) : KtNDArray < T >

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

/**
 * Return the element-wise square of the input.
 */


fun < T : Number > absolute ( x : KtNDArray < T > ) : KtNDArray < T >

/**
 * Calculate the absolute value element-wise.
 */


fun < T : Number > fabs ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Compute the absolute values element-wise.
 */


fun < T : Number > sign ( x : KtNDArray < T > ) : KtNDArray < T >

/**
 * Returns an element-wise indication of the sign of a number.
 */


fun < T : Number , E : Number > heaviside ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x1 , x2 ) , dtype = Double :: class )

/**
 * Compute the Heaviside step function.
 */


fun < T : Number > maximum ( x1 : KtNDArray < T > , x2 : KtNDArray < T > ) : KtNDArray < T >

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

/**
 * Element-wise maximum of array elements.
 */


fun < T : Number > minimum ( x1 : KtNDArray < T > , x2 : KtNDArray < T > ) : KtNDArray < T >

/**
 * Element-wise minimum of array elements.
 */


fun < T : Number , E : Number > fmax ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >


fun < T : Number , E : Number > fmin ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >


fun < T : Number > nanToNum ( x : KtNDArray < T > , nan : Double = <NUM_LIT:0.0> , posinf : Double ? = null , neginf : Double ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x , nan , posinf ? : None . none , neginf ? : None . none ) )

/**
 * Replace NaN with zero and infinity with large finite numbers (default behaviour).
 */


fun < T : Number , E : Number , R : Number > interp ( x : KtNDArray < T > , xp : KtNDArray < E > , fp : KtNDArray < R > , left : Double ? = null , right : Double ? = null , period : Double ? = null ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x , xp , fp , left ? : None . none , right ? : None . none , period ? : None . none ) )

/**
 * One-dimensional linear interpolation.
 */


fun stripMetadata ( logger : Logger , classNamePattern : String , inFile : File , outFile : File , preserveFileTimestamps : Boolean = true )

{ <EOL> val classRegex = classNamePattern . toRegex ( ) <EOL> assert ( inFile . exists ( ) ) { "<STR_LIT>" } <EOL> fun transform ( entryName : String , bytes : ByteArray ) : ByteArray { <EOL> if ( ! entryName . endsWith ( "<STR_LIT>" ) ) return bytes <EOL> if ( ! classRegex . matches ( entryName . removeSuffix ( "<STR_LIT>" ) ) ) return bytes <EOL> var changed = false <EOL> val classWriter = ClassWriter ( <NUM_LIT:0> ) <EOL> val classVisitor = object : ClassVisitor ( Opcodes . API_VERSION , classWriter ) { <EOL> override fun visitAnnotation ( desc : String , visible : Boolean ) : AnnotationVisitor ? { <EOL> if ( Type . getType ( desc ) . internalName == "<STR_LIT>" ) { <EOL> changed = true <EOL> return null <EOL> } <EOL> return super . visitAnnotation ( desc , visible ) <EOL> } <EOL> } <EOL> ClassReader ( bytes ) . accept ( classVisitor , <NUM_LIT:0> ) <EOL> if ( ! changed ) return bytes <EOL> return classWriter . toByteArray ( ) <EOL> } <EOL> ZipOutputStream ( BufferedOutputStream ( FileOutputStream ( outFile ) ) ) . use { outJar -> <EOL> JarFile ( inFile ) . use { inJar -> <EOL> for ( entry in inJar . entries ( ) ) { <EOL> val inBytes = inJar . getInputStream ( entry ) . readBytes ( ) <EOL> val outBytes = transform ( entry . name , inBytes ) <EOL> if ( inBytes . size < outBytes . size ) { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> val newEntry = ZipEntry ( entry . name ) <EOL> if ( ! preserveFileTimestamps ) { <EOL> newEntry . time = CONSTANT_TIME_FOR_ZIP_ENTRIES <EOL> } <EOL> outJar . putNextEntry ( newEntry ) <EOL> outJar . write ( outBytes ) <EOL> outJar . closeEntry ( ) <EOL> } <EOL> } <EOL> } <EOL> logger . info ( "<STR_LIT>" ) <EOL> logger . info ( "<STR_LIT>" ) <EOL> logger . info ( "<STR_LIT>" ) <EOL> logger . info ( "<STR_LIT>" ) <EOL> logger . info ( "<STR_LIT>" ) <EOL> }

/**
 * Removes @kotlin.Metadata annotations from compiled Kotlin classes
 */


@ Suppress ( "<STR_LIT:unused>" ) <EOL> fun embedKernel ( cfgFile : File , resolutionInfoProvider : ResolutionInfoProvider ? , scriptReceivers : List < Any > ? = null , )

{ <EOL> val cp = System . getProperty ( "<STR_LIT>" ) . split ( File . pathSeparator ) . toTypedArray ( ) . map { File ( it ) } <EOL> val kernelConfig = KernelArgs ( cfgFile , cp , null , null , null , null ) . getConfig ( ) <EOL> val replConfig = <EOL> ReplConfig . create ( { httpUtil , _ -> resolutionInfoProvider ? : EmptyResolutionInfoProvider ( httpUtil . libraryInfoCache ) } , homeDir = null , embedded = true , ) <EOL> val replSettings = <EOL> DefaultReplSettings ( kernelConfig , replConfig , DefaultKernelLoggerFactory , scriptReceivers = scriptReceivers . orEmpty ( ) , ) <EOL> kernelServer ( replSettings ) <EOL> }

/**
 * This function is to be run in projects which use kernel as a library,
 * so we don't have a big need in covering it with tests
 *
 * The expected use case for this function is embedded into a Java application that doesn't necessarily support extensions written in Kotlin
 * The signature of this function should thus be simple, and e.g. allow resolutionInfoProvider to be null instead of having to pass EmptyResolutionInfoProvider
 * because EmptyResolutionInfoProvider is a Kotlin singleton object, and it takes a while to understand how to use it from Java code.
 */


public final override fun < T > encodeToString ( serializer : SerializationStrategy < T > , value : T ) : String

{ <EOL> val result = JsonToStringWriter ( ) <EOL> try { <EOL> encodeByWriter ( this @ Json , result , serializer , value ) <EOL> return result . toString ( ) <EOL> } finally { <EOL> result . release ( ) <EOL> } <EOL> }

/**
 * Serializes the [value] into an equivalent JSON using the given [serializer].
 *
 * @throws [SerializationException] if the given value cannot be serialized to JSON.
 */


public inline fun < reified T > decodeFromString ( @ FormatLanguage ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) string : String ) : T

= <EOL> decodeFromString ( serializersModule . serializer ( ) , string )

/**
 * Decodes and deserializes the given JSON [string] to the value of type [T] using deserializer
 * retrieved from the reified type parameter.
 *
 * @throws SerializationException in case of any decoding-specific error
 * @throws IllegalArgumentException if the decoded input is not a valid instance of [T]
 */


public final override fun < T > decodeFromString ( deserializer : DeserializationStrategy < T > , @ FormatLanguage ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) string : String ) : T

{ <EOL> val lexer = StringJsonLexer ( string ) <EOL> val input = StreamingJsonDecoder ( this , WriteMode . OBJ , lexer , deserializer . descriptor , null ) <EOL> val result = input . decodeSerializableValue ( deserializer ) <EOL> lexer . expectEof ( ) <EOL> return result <EOL> }

/**
 * Deserializes the given JSON [string] into a value of type [T] using the given [deserializer].
 *
 * @throws [SerializationException] if the given JSON string is not a valid JSON input for the type [T]
 * @throws [IllegalArgumentException] if the decoded input cannot be represented as a valid instance of type [T]
 */


public fun < T > encodeToJsonElement ( serializer : SerializationStrategy < T > , value : T ) : JsonElement

{ <EOL> return writeJson ( this @ Json , value , serializer ) <EOL> }

/**
 * Serializes the given [value] into an equivalent [JsonElement] using the given [serializer]
 *
 * @throws [SerializationException] if the given value cannot be serialized to JSON
 */


public fun < T > decodeFromJsonElement ( deserializer : DeserializationStrategy < T > , element : JsonElement ) : T

{ <EOL> return readJson ( this @ Json , element , deserializer ) <EOL> }

/**
 * Deserializes the given [element] into a value of type [T] using the given [deserializer].
 *
 * @throws [SerializationException] if the given JSON element is not a valid JSON input for the type [T]
 * @throws [IllegalArgumentException] if the decoded input cannot be represented as a valid instance of type [T]
 */


public fun parseToJsonElement ( @ FormatLanguage ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) string : String ) : JsonElement

{ <EOL> return decodeFromString ( JsonElementSerializer , string ) <EOL> }

/**
 * Deserializes the given JSON [string] into a corresponding [JsonElement] representation.
 *
 * @throws [SerializationException] if the given string is not a valid JSON
 */


public fun Json ( from : Json = Json . Default , builderAction : JsonBuilder . ( ) -> Unit ) : Json

{ <EOL> val builder = JsonBuilder ( from ) <EOL> builder . builderAction ( ) <EOL> val conf = builder . build ( ) <EOL> return JsonImpl ( conf , builder . serializersModule ) <EOL> }

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


public inline fun < reified T > Json . encodeToJsonElement ( value : T ) : JsonElement

{ <EOL> return encodeToJsonElement ( serializersModule . serializer ( ) , value ) <EOL> }

/**
 * Serializes the given [value] into an equivalent [JsonElement] using a serializer retrieved
 * from reified type parameter.
 *
 * @throws [SerializationException] if the given value cannot be serialized to JSON.
 */


public inline fun < reified T > Json . decodeFromJsonElement ( json : JsonElement ) : T

= <EOL> decodeFromJsonElement ( serializersModule . serializer ( ) , json )

/**
 * Deserializes the given [json] element into a value of type [T] using a deserializer retrieved
 * from reified type parameter.
 *
 * @throws [SerializationException] if the given JSON element is not a valid JSON input for the type [T]
 * @throws [IllegalArgumentException] if the decoded input cannot be represented as a valid instance of type [T]
 */


public fun < T > compareValuesBy ( a : T , b : T , vararg selectors : ( T ) -> Comparable < * > ? ) : Int

{ <EOL> require ( selectors . size > <NUM_LIT:0> ) <EOL> return compareValuesByImpl ( a , b , selectors ) <EOL> }

/**
 * Compares two values using the specified functions [selectors] to calculate the result of the comparison.
 * The functions are called sequentially, receive the given values [a] and [b] and return [Comparable]
 * objects. As soon as the [Comparable] instances returned by a function for [a] and [b] values do not
 * compare as equal, the result of that comparison is returned.
 *
 * @sample samples.comparisons.Comparisons.compareValuesByWithSelectors
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > compareValuesBy ( a : T , b : T , selector : ( T ) -> Comparable < * > ? ) : Int

{ <EOL> return compareValues ( selector ( a ) , selector ( b ) ) <EOL> }

/**
 * Compares two values using the specified [selector] function to calculate the result of the comparison.
 * The function is applied to the given values [a] and [b] and return [Comparable] objects.
 * The result of comparison of these [Comparable] instances is returned.
 *
 * @sample samples.comparisons.Comparisons.compareValuesByWithSingleSelector
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T , K > compareValuesBy ( a : T , b : T , comparator : Comparator < in K > , selector : ( T ) -> K ) : Int

{ <EOL> return comparator . compare ( selector ( a ) , selector ( b ) ) <EOL> }

/**
 * Compares two values using the specified [selector] function to calculate the result of the comparison.
 * The function is applied to the given values [a] and [b] and return objects of type K which are then being
 * compared with the given [comparator].
 *
 * @sample samples.comparisons.Comparisons.compareValuesByWithComparator
 */


public fun < T : Comparable < * > > compareValues ( a : T ? , b : T ? ) : Int

{ <EOL> if ( a === b ) return <NUM_LIT:0> <EOL> if ( a == null ) return - <NUM_LIT:1> <EOL> if ( b == null ) return <NUM_LIT:1> <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return ( a as Comparable < Any > ) . compareTo ( b ) <EOL> }

/**
 * Compares two nullable [Comparable] values. Null is considered less than any value.
 *
 * @sample samples.comparisons.Comparisons.compareValues
 */


public fun < T > compareBy ( vararg selectors : ( T ) -> Comparable < * > ? ) : Comparator < T >

{ <EOL> require ( selectors . size > <NUM_LIT:0> ) <EOL> return Comparator { a , b -> compareValuesByImpl ( a , b , selectors ) } <EOL> }

/**
 * Creates a comparator using the sequence of functions to calculate a result of comparison.
 * The functions are called sequentially, receive the given values `a` and `b` and return [Comparable]
 * objects. As soon as the [Comparable] instances returned by a function for `a` and `b` values do not
 * compare as equal, the result of that comparison is returned from the [Comparator].
 *
 * @sample samples.comparisons.Comparisons.compareByWithSelectors
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > compareBy ( crossinline selector : ( T ) -> Comparable < * > ? ) : Comparator < T >

= <EOL> Comparator { a , b -> compareValuesBy ( a , b , selector ) }

/**
 * Creates a comparator using the function to transform value to a [Comparable] instance for comparison.
 *
 * @sample samples.comparisons.Comparisons.compareByWithSingleSelector
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T , K > compareBy ( comparator : Comparator < in K > , crossinline selector : ( T ) -> K ) : Comparator < T >

= <EOL> Comparator { a , b -> compareValuesBy ( a , b , comparator , selector ) }

/**
 * Creates a comparator using the [selector] function to transform values being compared and then applying
 * the specified [comparator] to compare transformed values.
 *
 * @sample samples.comparisons.Comparisons.compareByWithComparator
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > compareByDescending ( crossinline selector : ( T ) -> Comparable < * > ? ) : Comparator < T >

= <EOL> Comparator { a , b -> compareValuesBy ( b , a , selector ) }

/**
 * Creates a descending comparator using the function to transform value to a [Comparable] instance for comparison.
 *
 * @sample samples.comparisons.Comparisons.compareByDescendingWithSingleSelector
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T , K > compareByDescending ( comparator : Comparator < in K > , crossinline selector : ( T ) -> K ) : Comparator < T >

= <EOL> Comparator { a , b -> compareValuesBy ( b , a , comparator , selector ) }

/**
 * Creates a descending comparator using the [selector] function to transform values being compared and then applying
 * the specified [comparator] to compare transformed values.
 *
 * Note that an order of [comparator] is reversed by this wrapper.
 *
 * @sample samples.comparisons.Comparisons.compareByDescendingWithComparator
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > Comparator < T > . thenBy ( crossinline selector : ( T ) -> Comparable < * > ? ) : Comparator < T >

= <EOL> Comparator { a , b -> <EOL> val previousCompare = this@thenBy . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else compareValuesBy ( a , b , selector ) <EOL> }

/**
 * Creates a comparator comparing values after the primary comparator defined them equal. It uses
 * the function to transform value to a [Comparable] instance for comparison.
 *
 * @sample samples.comparisons.Comparisons.thenBy
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T , K > Comparator < T > . thenBy ( comparator : Comparator < in K > , crossinline selector : ( T ) -> K ) : Comparator < T >

= <EOL> Comparator { a , b -> <EOL> val previousCompare = this@thenBy . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else compareValuesBy ( a , b , comparator , selector ) <EOL> }

/**
 * Creates a comparator comparing values after the primary comparator defined them equal. It uses
 * the [selector] function to transform values and then compares them with the given [comparator].
 *
 * @sample samples.comparisons.Comparisons.thenByWithComparator
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > Comparator < T > . thenByDescending ( crossinline selector : ( T ) -> Comparable < * > ? ) : Comparator < T >

= <EOL> Comparator { a , b -> <EOL> val previousCompare = this@thenByDescending . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else compareValuesBy ( b , a , selector ) <EOL> }

/**
 * Creates a descending comparator using the primary comparator and
 * the function to transform value to a [Comparable] instance for comparison.
 *
 * @sample samples.comparisons.Comparisons.thenByDescending
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T , K > Comparator < T > . thenByDescending ( comparator : Comparator < in K > , crossinline selector : ( T ) -> K ) : Comparator < T >

= <EOL> Comparator { a , b -> <EOL> val previousCompare = this@thenByDescending . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else compareValuesBy ( b , a , comparator , selector ) <EOL> }

/**
 * Creates a descending comparator comparing values after the primary comparator defined them equal. It uses
 * the [selector] function to transform values and then compares them with the given [comparator].
 *
 * @sample samples.comparisons.Comparisons.thenByDescendingWithComparator
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T > Comparator < T > . thenComparator ( crossinline comparison : ( a : T , b : T ) -> Int ) : Comparator < T >

= <EOL> Comparator { a , b -> <EOL> val previousCompare = this@thenComparator . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else comparison ( a , b ) <EOL> }

/**
 * Creates a comparator using the primary comparator and function to calculate a result of comparison.
 *
 * @sample samples.comparisons.Comparisons.thenComparator
 */


public infix fun < T > Comparator < T > . then ( comparator : Comparator < in T > ) : Comparator < T >

= <EOL> Comparator { a , b -> <EOL> val previousCompare = this@then . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else comparator . compare ( a , b ) <EOL> }

/**
 * Combines this comparator and the given [comparator] such that the latter is applied only
 * when the former considered values equal.
 *
 * @sample samples.comparisons.Comparisons.then
 */


public infix fun < T > Comparator < T > . thenDescending ( comparator : Comparator < in T > ) : Comparator < T >

= <EOL> Comparator < T > { a , b -> <EOL> val previousCompare = this@thenDescending . compare ( a , b ) <EOL> if ( previousCompare != <NUM_LIT:0> ) previousCompare else comparator . compare ( b , a ) <EOL> }

/**
 * Combines this comparator and the given [comparator] such that the latter is applied only
 * when the former considered values equal.
 *
 * @sample samples.comparisons.Comparisons.thenDescending
 */


public fun < T : Any > nullsFirst ( comparator : Comparator < in T > ) : Comparator < T ? >

= <EOL> Comparator { a , b -> <EOL> when { <EOL> a === b -> <NUM_LIT:0> <EOL> a == null -> - <NUM_LIT:1> <EOL> b == null -> <NUM_LIT:1> <EOL> else -> comparator . compare ( a , b ) <EOL> } <EOL> }

/**
 * Extends the given [comparator] of non-nullable values to a comparator of nullable values
 * considering `null` value less than any other value.
 * Non-null values are compared with the provided [comparator].
 *
 * @sample samples.comparisons.Comparisons.nullsFirstLastWithComparator
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T : Comparable < T > > nullsFirst ( ) : Comparator < T ? >

= nullsFirst ( naturalOrder ( ) )

/**
 * Provides a comparator of nullable [Comparable] values
 * considering `null` value less than any other value.
 * Non-null values are compared according to their [natural order][naturalOrder].
 *
 * @sample samples.comparisons.Comparisons.nullsFirstLastComparator
 */


public fun < T : Any > nullsLast ( comparator : Comparator < in T > ) : Comparator < T ? >

= <EOL> Comparator { a , b -> <EOL> when { <EOL> a === b -> <NUM_LIT:0> <EOL> a == null -> <NUM_LIT:1> <EOL> b == null -> - <NUM_LIT:1> <EOL> else -> comparator . compare ( a , b ) <EOL> } <EOL> }

/**
 * Extends the given [comparator] of non-nullable values to a comparator of nullable values
 * considering `null` value greater than any other value.
 * Non-null values are compared with the provided [comparator].
 *
 * @sample samples.comparisons.Comparisons.nullsFirstLastWithComparator
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun < T : Comparable < T > > nullsLast ( ) : Comparator < T ? >

= nullsLast ( naturalOrder ( ) )

/**
 * Provides a comparator of nullable [Comparable] values
 * considering `null` value greater than any other value.
 * Non-null values are compared according to their [natural order][naturalOrder].
 *
 * @sample samples.comparisons.Comparisons.nullsFirstLastComparator
 */


public fun < T : Comparable < T > > naturalOrder ( ) : Comparator < T >

= @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) ( NaturalOrderComparator as Comparator < T > )

/**
 * Returns a comparator that compares [Comparable] objects in natural order.
 *
 * The natural order of a `Comparable` type here means the order established by its `compareTo` function.
 *
 * @sample samples.comparisons.Comparisons.naturalOrderComparator
 */


public fun < T : Comparable < T > > reverseOrder ( ) : Comparator < T >

= @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) ( ReverseOrderComparator as Comparator < T > )

/**
 * Returns a comparator that compares [Comparable] objects in reversed natural order.
 *
 * The natural order of a `Comparable` type here means the order established by its `compareTo` function.
 *
 * @sample samples.comparisons.Comparisons.nullsFirstLastWithComparator
 */


@ Suppress ( "<STR_LIT>" ) <EOL> public fun < T > Comparator < T > . reversed ( ) : Comparator < T >

= when ( this ) { <EOL> is ReversedComparator -> this . comparator <EOL> NaturalOrderComparator -> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) ( ReverseOrderComparator as Comparator < T > ) <EOL> ReverseOrderComparator -> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) ( NaturalOrderComparator as Comparator < T > ) <EOL> else -> ReversedComparator ( this ) <EOL> }

/**
 * Returns a comparator that imposes the reverse ordering of this comparator.
 *
 * @sample samples.comparisons.Comparisons.reversed
 */


@ GradleTest <EOL> fun `test - sample0 - buildId buildPath buildName` ( gradleVersion : GradleVersion )

{ <EOL> val producer = project ( "<STR_LIT>" , gradleVersion ) <EOL> project ( "<STR_LIT>" , gradleVersion ) { <EOL> settingsGradleKts . toFile ( ) . replaceText ( "<STR_LIT>" , producer . projectPath . toUri ( ) . path ) <EOL> resolveIdeDependencies ( "<STR_LIT>" ) { dependencies -> <EOL> val dependency = dependencies [ "<STR_LIT:commonMain>" ] . getOrFail ( regularSourceDependency ( "<STR_LIT>" ) ) <EOL> assertIs < IdeaKotlinSourceDependency > ( dependency ) <EOL> val projectCoordinates = dependency . coordinates . project <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> assertEquals ( "<STR_LIT>" , projectCoordinates . buildId ) <EOL> assertEquals ( "<STR_LIT>" , projectCoordinates . buildName ) <EOL> assertEquals ( "<STR_LIT>" , projectCoordinates . buildPath ) <EOL> assertEquals ( "<STR_LIT>" , projectCoordinates . projectPath ) <EOL> assertEquals ( "<STR_LIT>" , projectCoordinates . projectName ) <EOL> } <EOL> } <EOL> }

/**
 * Test that verifies that after moving to 'buildPath' and 'buildName' in project coordinates (1.9.20),
 * the shape of the resolved coordinate are the same across different versions of Gradle.
 */


internal fun getDType ( ) : Class < Float >

{ <EOL> return Float :: class . javaObjectType <EOL> }

/** Returns DType. In existing solution it works with Float only. */


@ Throws ( IOException :: class ) <EOL> public fun detectObjects ( imageFile : File , topK : Int = <NUM_LIT:5> ) : List < DetectedObject >

{ <EOL> return detectObjects ( ImageConverter . toBufferedImage ( imageFile ) , topK ) <EOL> }

/**
 * Returns the top N detected object for the given image file sorted by the score.
 *
 * NOTE: this method includes the SSD-related preprocessing.
 *
 * @param [imageFile] File, should be an image.
 * @param [topK] The number of the detected objects with the highest score to be returned.
 * @return List of [DetectedObject] sorted by score.
 */


public fun reshape ( vararg dims : Long )

{ <EOL> inputShape = longArrayOf ( * dims ) <EOL> }

/**
 * Setter for input shape of the internal model. Images are going to be resized to this shape.
 *
 * @param dims The input shape.
 */


public fun apply ( fanIn : Int , fanOut : Int , tf : Ops , input : Operand < Float > , name : String ) : InitializerOperation

{ <EOL> val initialize = initialize ( fanIn , fanOut , tf , shapeOperand ( tf , input . asOutput ( ) . shape ( ) ) , defaultInitializerOpName ( name ) ) <EOL> return InitializerOperation ( tf . withName ( defaultAssignOpName ( name ) ) . assign ( input , initialize ) , initialize ) <EOL> }

/**
 * Adds an `Assign` Op to the graph to initialize
 * a tensorflow variable as specified by the initializer.
 *
 * @param [fanIn] The maximum number of inputs that an initializer can accept.
 * @param [fanOut] The maximum number of inputs that the output of an initializer can feed to other steps.
 * @param [tf] Tensorflow Ops Accessor
 * @param [input] Variable to initialize
 * @return initializer operation.
 * @see InitializerOperation
 */


public abstract fun initialize ( fanIn : Int , fanOut : Int , tf : Ops , shape : Operand < Int > , name : String ) : Operand < Float >

/**
 * Returns a Tensor object initialized as specified by the initializer.
 *
 * @param [fanIn] The maximum number of inputs that an initializer can accept.
 * @param [fanOut] The maximum number of inputs that the output of an initializer can feed to other steps.
 * @param [tf] Tensorflow Ops Accessor.
 * @param [shape] Shape of the tensor.
 * @param [name] Initializer name.
 */


fun makeFlattenedGetterExpressions ( scope : IrBlockBuilder , currentClass : IrClass , registerPossibleExtraBoxCreation : ( ) -> Unit ) : List < IrExpression >

/**
 * Make expressions corresponding to the flattened representation of the [MfvcNodeInstance].
 */


fun makeGetterExpression ( scope : IrBuilderWithScope , currentClass : IrClass , registerPossibleExtraBoxCreation : ( ) -> Unit ) : IrExpression

/**
 * Make expression that corresponds to read access of the instance
 */


operator fun get ( name : Name ) : MfvcNodeInstance ?

/**
 * Get child [MfvcNodeInstance] by [name]
 */


fun makeSetterStatements ( scope : IrBuilderWithScope , values : List < IrExpression > ) : List < IrStatement >

/**
 * Make setter statements corresponding assignments to the [values] of the given flattened representation.
 */


fun MfvcNodeInstance . addSetterStatements ( scope : IrBlockBuilder , values : List < IrExpression > )

= with ( scope ) { <EOL> for ( statement in makeSetterStatements ( this , values ) ) { <EOL> + statement <EOL> } <EOL> }

/**
 * Make and add setter statements corresponding assignments to the [values] of the given flattened representation.
 */


fun MfvcNodeInstance . makeSetterExpressions ( scope : IrBuilderWithScope , values : List < IrExpression > ) : IrExpression

= scope . irBlock { <EOL> addSetterStatements ( this , values ) <EOL> }

/**
 * Make a block of setter statements corresponding assignments to the [values] of the given flattened representation.
 */


fun IrBuilderWithScope . savableStandaloneVariable ( type : IrType , name : String ? = null , isVar : Boolean , origin : IrDeclarationOrigin , isTemporary : Boolean = origin == IrDeclarationOrigin . IR_TEMPORARY_VARIABLE || origin == JvmLoweredDeclarationOrigin . TEMPORARY_MULTI_FIELD_VALUE_CLASS_VARIABLE || origin == JvmLoweredDeclarationOrigin . TEMPORARY_MULTI_FIELD_VALUE_CLASS_PARAMETER , saveVariable : ( IrVariable ) -> Unit , ) : IrVariable

{ <EOL> val variable = if ( isTemporary || name == null ) scope . createTemporaryVariableDeclaration ( type , name , isVar , startOffset = startOffset , endOffset = endOffset , origin = origin , ) else IrVariableImpl ( startOffset = startOffset , endOffset = endOffset , origin = origin , symbol = IrVariableSymbolImpl ( ) , name = Name . identifier ( name ) , type = type , isVar = isVar , isConst = false , isLateinit = false ) . apply { <EOL> parent = this@savableStandaloneVariable . scope . getLocalDeclarationParent ( ) <EOL> } <EOL> saveVariable ( variable ) <EOL> return variable <EOL> }

/**
 * Creates a variable and doesn't add it to a container. It saves the variable with given saveVariable.
 *
 * It may be used when the variable will be used outside the current container so the declaration is added later when all usages are known.
 */


fun < T : IrElement > IrStatementsBuilder < T > . savableStandaloneVariableWithSetter ( expression : IrExpression , name : String ? = null , isMutable : Boolean = false , origin : IrDeclarationOrigin , isTemporary : Boolean = origin == IrDeclarationOrigin . IR_TEMPORARY_VARIABLE , saveVariable : ( IrVariable ) -> Unit , )

= savableStandaloneVariable ( expression . type , name , isMutable , origin , isTemporary , saveVariable ) . also { <EOL> + irSet ( it , expression ) <EOL> }

/**
 * Creates a variable and doesn't add it to a container. It saves the variable with given saveVariable. It adds irSet-based initialization.
 *
 * It may be used when the variable will be used outside the current container so the declaration is added later when all usages are known.
 */


internal fun getSourceFilePaths ( compilerConfig : CompilerConfiguration , includeDirectoryRoot : Boolean = false , ) : Set < Path >

{ <EOL> return buildSet { <EOL> compilerConfig . javaSourceRoots . forEach { srcRoot -> <EOL> val path = Paths . get ( srcRoot ) <EOL> if ( Files . isDirectory ( path ) ) { <EOL> addAll ( collectSourceFilePaths ( path ) ) <EOL> if ( includeDirectoryRoot ) { <EOL> add ( path ) <EOL> } <EOL> } else { <EOL> add ( path ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Collect source file path as [String] from the given source roots in [compilerConfig].
 *
 * Such source roots are either [KotlinSourceRoot] or [JavaSourceRoot], and thus
 * this util collects all `.kt` and `.java` files under source roots.
 */


internal fun collectSourceFilePaths ( root : Path ) : List < Path >

{ <EOL> val result = mutableListOf < Path > ( ) <EOL> Files . walkFileTree ( root , object : SimpleFileVisitor < Path > ( ) { <EOL> override fun preVisitDirectory ( dir : Path , attrs : BasicFileAttributes ) : FileVisitResult { <EOL> return if ( Files . isReadable ( dir ) ) <EOL> FileVisitResult . CONTINUE <EOL> else <EOL> FileVisitResult . SKIP_SUBTREE <EOL> } <EOL> override fun visitFile ( file : Path , attrs : BasicFileAttributes ) : FileVisitResult { <EOL> if ( ! Files . isRegularFile ( file ) || ! Files . isReadable ( file ) ) <EOL> return FileVisitResult . CONTINUE <EOL> if ( file . hasSuitableExtensionToAnalyse ( ) ) { <EOL> result . add ( file ) <EOL> } <EOL> return FileVisitResult . CONTINUE <EOL> } <EOL> override fun visitFileFailed ( file : Path , exc : IOException ? ) : FileVisitResult { <EOL> return FileVisitResult . CONTINUE <EOL> } <EOL> } ) <EOL> return result <EOL> }

/**
 * Collect source file path from the given [root]
 *
 * E.g., for `project/app/src` as a [root], this will walk the file tree and
 * collect all `.kt`, `.kts`, and `.java` files under that folder.
 *
 * Note that this util gracefully skips [IOException] during file tree traversal.
 */


public expect fun todo ( block : ( ) -> Unit )

/**
 * Takes the given [block] of test code and _doesn't_ execute it.
 *
 * This keeps the code under test referenced, but doesn't actually test it until it is implemented.
 */


@ PublishedApi <EOL> internal expect fun < T : Throwable > checkResultIsFailure ( exceptionClass : KClass < T > , message : String ? , blockResult : Result < Unit > ) : T

/** Asserts that a [blockResult] is a failure with the specific exception type being thrown. */


private fun createDependencyCollector ( ) : AnnotationProcessorDependencyCollector

{ <EOL> val type = if ( kind == DeclaredProcType . DYNAMIC ) { <EOL> val fromOptions = supportedOptions . singleOrNull { it . startsWith ( "<STR_LIT>" ) } <EOL> if ( fromOptions == null ) { <EOL> RuntimeProcType . NON_INCREMENTAL <EOL> } else { <EOL> val declaredType = fromOptions . drop ( "<STR_LIT>" . length ) . uppercase ( ) <EOL> if ( ALLOWED_RUNTIME_TYPES . contains ( declaredType ) ) { <EOL> enumValueOf ( declaredType ) <EOL> } else { <EOL> RuntimeProcType . NON_INCREMENTAL <EOL> } <EOL> } <EOL> } else { <EOL> kind . toRuntimeType ( ) <EOL> } <EOL> return AnnotationProcessorDependencyCollector ( type ) { s -> logger . warn ( "<STR_LIT>" ) } <EOL> }

/** This has to invoked only once the processors has been initialized, because this accesses Processor.getSupportedOptions(). */


fun getGeneratedToSources ( ) : Map < File , String ? >

= dependencyCollector . value . getGeneratedToSources ( )

/** Mapping from generated file to type that were used as originating elements. For aggregating APs types will be [null]. */


= dependencyCollector . value . getAggregatedTypes ( )

/** All top-level types that were processed by aggregating APs. */


fun getGeneratedClassFilesToTypes ( ) : Map < File , String >

= dependencyCollector . value . getGeneratedClassFilesToTypes ( )

/** Mapping from generated class file to type defined in that file. */


internal fun getGeneratedToSources ( ) : Map < File , String ? >

= if ( isFullRebuild ) emptyMap ( ) else generatedToSource

/** Mapping from generated files to top level class names that cause that file generation. */


@ OptIn ( DfaInternals :: class ) <EOL> fun isAccessToUnstableLocalVariable ( fir : FirElement , targetType : ConeKotlinType ? , session : FirSession ) : Boolean

{ <EOL> if ( assignedLocalVariablesByDeclaration == null ) return false <EOL> val realFir = fir . unwrapElement ( ) as? FirQualifiedAccessExpression ? : return false <EOL> val property = realFir . calleeReference . toResolvedPropertySymbol ( ) ? . fir ? : return false <EOL> return ! isStableType ( scopes . top ( ) . second [ property ] , targetType , session ) || postponedLambdas . all ( ) . any { lambdas -> <EOL> lambdas . any { ( lambda , dataFlowOnly ) -> dataFlowOnly && property in lambda . assignedInside } <EOL> } <EOL> }

/** Checks whether the given access is an unstable access to a local variable at this moment. */


abstract fun check ( context : CheckerContext , rawReport : ( Boolean , String ) -> Unit )

/**
 * This API allows us to check language version settings independently of particular code pieces.
 *
 * [rawReport] allows to report a diagnostic directly to a message collector.
 * This function accepts isError: Boolean and message: String as parameters.
 */


{ <EOL> synchronized ( this ) { <EOL> keys . forEach { remove ( it ) } <EOL> } <EOL> }


{ <EOL> synchronized ( this ) { <EOL> check ( IOUtil . deleteAllFilesStartingWith ( storageFile ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> }

/**
 * Deletes [storageFile] or a group of files associated with [storageFile] (e.g., an implementation of [PersistentStorage] may use a
 * [com.intellij.util.io.PersistentHashMap], which creates files such as "storageFile.tab", "storageFile.tab.len", etc.).
 *
 * Make sure the storage has been closed first before calling this method.
 */


{ <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = ONNXModels . ObjectDetection . SSD <EOL> val model = modelHub . loadModel ( modelType ) <EOL> model . printSummary ( ) <EOL> model . use { <EOL> println ( it ) <EOL> val preprocessing = pipeline < BufferedImage > ( ) <EOL> . resize { <EOL> outputHeight = <NUM_LIT> <EOL> outputWidth = <NUM_LIT> <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . call ( modelType . preprocessor ) <EOL> . fileLoader ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:6> ) { <EOL> val inputData = preprocessing . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val start = System . currentTimeMillis ( ) <EOL> val yhat = it . predict ( inputData ) { output -> output . getFloatArray ( <NUM_LIT:0> ) } <EOL> val end = System . currentTimeMillis ( ) <EOL> println ( "<STR_LIT>" ) <EOL> println ( yhat . contentToString ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * This examples demonstrates the inference concept on SSD model:
 * - Model is obtained from [ONNXModelHub].
 * - Model predicts on a few images located in resources.
 * - Special preprocessing is applied to each image before prediction.
 */


= ssd ( )


fun < T > runSafe ( action : ( ) -> T ) : T ?

/**
 * This method shall be used for any [action] used to build arguments, that could potentially throw an exception
 * (like resolving dependencies). There are some scenarios (like IDE import), where we want to be lenient
 * and provide arguments on a 'best effort bases'.
 */


{ <EOL> val image = ImageConverter . toBufferedImage ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val detectionModel = ONNXModels . FaceDetection . UltraFace320 . pretrainedModel ( modelHub ) <EOL> detectionModel . printSummary ( ) <EOL> val faces = detectionModel . use { it . detectFaces ( image ) } <EOL> val alignmentModel = ONNXModels . FaceAlignment . Fan2d106 . pretrainedModel ( modelHub ) <EOL> alignmentModel . printSummary ( ) <EOL> val facesToLandmarks = alignmentModel . use { <EOL> faces . associateWith { face -> alignmentModel . predictOnCrop ( image , face ) } <EOL> } <EOL> val resize = pipeline < BufferedImage > ( ) . resize { <EOL> outputWidth = WIDTH <EOL> outputHeight = WIDTH * image . height / image . width <EOL> } <EOL> showFrame ( "<STR_LIT>" + ( if ( facesToLandmarks . size == <NUM_LIT:1> ) "<STR_LIT>" else "<STR_LIT:s>" ) , createDetectedLandmarksPanel ( resize . apply ( image ) , facesToLandmarks . values . flatten ( ) ) ) <EOL> }

/**
 * This example demonstrates how to combine Fan2d106 face alignment model and UltraFace320 face detection model to
 * find face landmarks on the image. The face alignment model works well only when the face has a certain size and location,
 * so for other cases it is necessary to find the face location first with a face detection model
 * and only then apply face alignment model to detect landmarks on the face crop.
 */


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> private fun IrExpression . uncheckedCast ( type : IrType ) : IrExpression

{ <EOL> return this <EOL> }

/**
 * Casts this expression to `type` without changing its representation in generated code.
 */


fun mapJavaToKotlin ( fqName : FqName ) : ClassId ?

{ <EOL> return javaToKotlin [ fqName . toUnsafe ( ) ] <EOL> }

/**
 * E.g.
 * - java.lang.String -> kotlin.String
 * - java.lang.Integer -> kotlin.Int
 * - kotlin.jvm.internal.IntCompanionObject -> kotlin.Int.Companion
 * - java.util.List -> kotlin.List
 * - java.util.Map.Entry -> kotlin.Map.Entry
 * - java.lang.Void -> null
 * - kotlin.jvm.functions.Function3 -> kotlin.Function3
 * - kotlin.jvm.functions.FunctionN -> null // Without a type annotation like @Arity(n), it's impossible to find out arity
 */


fun mapKotlinToJava ( kotlinFqName : FqNameUnsafe ) : ClassId ?

= when { <EOL> isKotlinFunctionWithBigArity ( kotlinFqName , NUMBERED_FUNCTION_PREFIX ) -> FUNCTION_N_CLASS_ID <EOL> isKotlinFunctionWithBigArity ( kotlinFqName , NUMBERED_SUSPEND_FUNCTION_PREFIX ) -> FUNCTION_N_CLASS_ID <EOL> isKotlinFunctionWithBigArity ( kotlinFqName , NUMBERED_K_FUNCTION_PREFIX ) -> K_FUNCTION_CLASS_ID <EOL> isKotlinFunctionWithBigArity ( kotlinFqName , NUMBERED_K_SUSPEND_FUNCTION_PREFIX ) -> K_FUNCTION_CLASS_ID <EOL> else -> kotlinToJava [ kotlinFqName ] <EOL> }

/**
 * E.g.
 * - kotlin.Throwable -> java.lang.Throwable
 * - kotlin.Int -> java.lang.Integer
 * - kotlin.Int.Companion -> kotlin.jvm.internal.IntCompanionObject
 * - kotlin.Nothing -> java.lang.Void
 * - kotlin.IntArray -> null
 * - kotlin.Function3 -> kotlin.jvm.functions.Function3
 * - kotlin.coroutines.SuspendFunction3 -> kotlin.jvm.functions.Function4
 * - kotlin.Function42 -> kotlin.jvm.functions.FunctionN
 * - kotlin.coroutines.SuspendFunction42 -> kotlin.jvm.functions.FunctionN
 * - kotlin.reflect.KFunction3 -> kotlin.reflect.KFunction
 * - kotlin.reflect.KSuspendFunction3 -> kotlin.reflect.KFunction
 * - kotlin.reflect.KFunction42 -> kotlin.reflect.KFunction
 * - kotlin.reflect.KSuspendFunction42 -> kotlin.reflect.KFunction
 */


internal fun Char . getCategoryValue ( ) : Int

{ <EOL> val ch = this . code <EOL> val index = binarySearchRange ( rangeStart , ch ) <EOL> val start = rangeStart [ index ] <EOL> val code = rangeCategory [ index ] <EOL> val value = categoryValueFrom ( code , ch - start ) <EOL> return if ( value == <NUM_LIT> ) CharCategory . UNASSIGNED . value else value <EOL> }

/**
 * Returns the Unicode general category of this character as an Int.
 */


fun containsKlibDirectory ( path : String ) : Boolean

{ <EOL> val pathToTheManifestFile = ensureValidZipDirectoryPath ( path ) + "<STR_LIT>" <EOL> return zip . getEntry ( pathToTheManifestFile ) != null <EOL> }

/**
 * Check if the underlying [zip] file contains klib at [path].
 * Note: This check also works for zip files that did not include any klibs.
 * This will return true, if any other zip-entry is placed inside this directory [path]
 */


fun hasBackingField ( property : FirProperty , session : FirSession ) : Boolean

/**
 * Platform-dependent logic to determine whether a backing field is required for [property].
 * Should be called instead of [FirProperty.hasBackingField] to decide whether to create a backing field.
 * The implementation should return `true` in case a platform-dependent condition for backing field existence is met,
 * otherwise it should return the result of [Fir2IrExtensions.Default.hasBackingField].
 */


fun isTrueStatic ( declaration : FirCallableDeclaration , session : FirSession ) : Boolean

/**
 * Whether this declaration is forcibly made static in the sense that it has no dispatch receiver.
 *
 * For example, on JVM this corresponds to the [JvmStatic] annotation.
 */


/**
 * [Any.<caret_1>anyExt]
 * [Base.<caret_2>anyExt]
 * [Child.<caret_3>anyExt]
 *
 * [Any.<caret_4>baseExt]
 * [Base.<caret_5>baseExt]
 * [Child.<caret_6>baseExt]
 *
 * [Any.<caret_7>childExt]
 * [Base.<caret_8>childExt]
 * [Child.<caret_9>childExt]
 */


fun markExportedDeclarations ( context : WasmBackendContext , irFile : IrFile , exportedFqNames : Set < FqName > )

{ <EOL> val exportConstructor = when ( context . isWasmJsTarget ) { <EOL> true -> context . wasmSymbols . jsRelatedSymbols . jsExportConstructor <EOL> else -> context . wasmSymbols . wasmExportConstructor <EOL> } <EOL> for ( declaration in irFile . declarations ) { <EOL> if ( declaration is IrFunction && declaration . fqNameWhenAvailable in exportedFqNames ) { <EOL> val builder = context . createIrBuilder ( irFile . symbol ) <EOL> declaration . annotations += <EOL> builder . irCallConstructor ( exportConstructor , typeArguments = emptyList ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * Mark declarations from [exportedFqNames] with @JsExport annotation
 */


fun < T : Number > sinh ( x : KtNDArray < T > ) : KtNDArray < Double >

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

/**
 * Hyperbolic sine, element-wise.
 */


fun < T : Number > cosh ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Hyperbolic cosine, element-wise.
 */


fun < T : Number > tanh ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Compute hyperbolic tangent element-wise.
 */


fun < T : Number > arcsinh ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Inverse hyperbolic sine element-wise.
 */


fun < T : Number > arccosh ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Inverse hyperbolic cosine, element-wise.
 */


fun < T : Number > arctanh ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Inverse hyperbolic tangent element-wise.
 */


@ Test <EOL> fun `schema extracted via readFromDB method is resolved` ( )

{ <EOL> val result = KspCompilationTestRunner . compile ( TestCompilationParameters ( sources = listOf ( SourceFile . kotlin ( "<STR_LIT>" , """<STR_LIT>""" . trimIndent ( ) ) ) ) ) <EOL> result . successfulCompilation shouldBe true <EOL> }

/**
 * Test code is copied from h2Test `read from table` test.
 */


fun getBuiltinsModule ( platform : TargetPlatform ) : KtBuiltinsModule

= <EOL> builtinsModules . getOrPut ( platform ) { KtBuiltinsModule ( platform , platform . getAnalyzerServices ( ) , project ) }

/**
 * Returns the [platform]'s [KtBuiltinsModule]. [getBuiltinsModule] should be used instead of [getBuiltinsSession] when a
 * [KtBuiltinsModule] is needed as a dependency for other [KtModule]s. This is because during project structure creation, we have to
 * avoid the creation of the builtins *session*, as not all services might have been registered at that point.
 */


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

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


fun doesJavaOverrideHaveIncompatibleValueParameterKinds ( superDescriptor : CallableDescriptor , subDescriptor : CallableDescriptor ) : Boolean

{ <EOL> if ( subDescriptor !is JavaMethodDescriptor || superDescriptor !is FunctionDescriptor ) return false <EOL> assert ( subDescriptor . valueParameters . size == superDescriptor . valueParameters . size ) { <EOL> "<STR_LIT>" <EOL> } <EOL> for ( ( subParameter , superParameter ) in subDescriptor . original . valueParameters . zip ( superDescriptor . original . valueParameters ) ) { <EOL> val isSubPrimitive = mapValueParameterType ( subDescriptor , subParameter ) is JvmType . Primitive <EOL> val isSuperPrimitive = mapValueParameterType ( superDescriptor , superParameter ) is JvmType . Primitive <EOL> if ( isSubPrimitive != isSuperPrimitive ) { <EOL> return true <EOL> } <EOL> } <EOL> return false <EOL> }

/**
 * Checks if any pair of corresponding value parameters has different type kinds, e.g. one is primitive and another is not
 *
 * As it comes from it's name it only checks overrides in Java classes
 */


{ <EOL> val ( train , test ) = mnist ( ) <EOL> val sampleIndex = <NUM_LIT:42> <EOL> val x = test . getX ( sampleIndex ) <EOL> val y = test . getY ( sampleIndex ) . toInt ( ) <EOL> lenet5 ( ) . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = TEST_BATCH_SIZE ) <EOL> val numbersPlots = List ( <NUM_LIT:3> ) { imageIndex -> <EOL> flattenImagePlot ( imageIndex , test , it :: predictLabel ) <EOL> } <EOL> columnPlot ( numbersPlots , <NUM_LIT:3> , <NUM_LIT> ) . show ( ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> val fstConv2D = it . layers [ <NUM_LIT:1> ] as Conv2D <EOL> val sndConv2D = it . layers [ <NUM_LIT:3> ] as Conv2D <EOL> filtersPlot ( fstConv2D , columns = <NUM_LIT:16> ) . show ( ) <EOL> filtersPlot ( sndConv2D , columns = <NUM_LIT:16> ) . show ( ) <EOL> drawFilters ( fstConv2D . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] , colorCoefficient = <NUM_LIT> ) <EOL> drawFilters ( sndConv2D . weights . values . toTypedArray ( ) [ <NUM_LIT:0> ] , colorCoefficient = <NUM_LIT> ) <EOL> val layersActivations = modelActivationOnLayersPlot ( it , x ) <EOL> val ( prediction , activations ) = it . predictAndGetActivations ( x ) <EOL> println ( "<STR_LIT>" ) <EOL> println ( "<STR_LIT>" ) <EOL> layersActivations [ <NUM_LIT:0> ] . show ( ) <EOL> layersActivations [ <NUM_LIT:1> ] . show ( ) <EOL> drawActivations ( activations ) <EOL> } <EOL> }

/**
 * This examples demonstrates model activations and Conv2D filters visualisation.
 *
 * Model is trained on Mnist dataset.
 */


internal fun Char . isLetterImpl ( ) : Boolean

{ <EOL> return getLetterType ( ) != <NUM_LIT:0> <EOL> }

/**
 * Returns `true` if this character is a letter.
 */


internal fun Char . isLowerCaseImpl ( ) : Boolean

{ <EOL> return getLetterType ( ) == <NUM_LIT:1> || code . isOtherLowercase ( ) <EOL> }

/**
 * Returns `true` if this character is a lower case letter, or it has contributory property `Other_Lowercase`.
 */


internal fun Char . isUpperCaseImpl ( ) : Boolean

{ <EOL> return getLetterType ( ) == <NUM_LIT:2> || code . isOtherUppercase ( ) <EOL> }

/**
 * Returns `true` if this character is an upper case letter, or it has contributory property `Other_Uppercase`.
 */


private fun Char . getLetterType ( ) : Int

{ <EOL> val ch = this . code <EOL> val index = binarySearchRange ( rangeStart , ch ) <EOL> val rangeStart = rangeStart [ index ] <EOL> val rangeEnd = rangeStart + rangeLength [ index ] - <NUM_LIT:1> <EOL> val code = rangeCategory [ index ] <EOL> if ( ch > rangeEnd ) { <EOL> return <NUM_LIT:0> <EOL> } <EOL> val lastTwoBits = code and <NUM_LIT> <EOL> if ( lastTwoBits == <NUM_LIT:0> ) { <EOL> var shift = <NUM_LIT:2> <EOL> var threshold = rangeStart <EOL> for ( i in <NUM_LIT:0> .. <NUM_LIT:1> ) { <EOL> threshold += ( code shr shift ) and <NUM_LIT> <EOL> if ( threshold > ch ) { <EOL> return <NUM_LIT:3> <EOL> } <EOL> shift += <NUM_LIT:7> <EOL> threshold += ( code shr shift ) and <NUM_LIT> <EOL> if ( threshold > ch ) { <EOL> return <NUM_LIT:0> <EOL> } <EOL> shift += <NUM_LIT:7> <EOL> } <EOL> return <NUM_LIT:3> <EOL> } <EOL> if ( code <= <NUM_LIT> ) { <EOL> return lastTwoBits <EOL> } <EOL> val distance = ( ch - rangeStart ) <EOL> val shift = if ( code <= <NUM_LIT> ) distance % <NUM_LIT:2> else distance <EOL> return ( code shr ( <NUM_LIT:2> * shift ) ) and <NUM_LIT> <EOL> }

/**
 * Returns
 * - `1` if the character is a lower case letter,
 * - `2` if the character is an upper case letter,
 * - `3` if the character is a letter but not a lower or upper case letter,
 * - `0` otherwise.
 */


public fun StandaloneAnalysisAPISession . getAllLibraryModules ( ) : Sequence < KtLibraryModule >

{ <EOL> val projectStructureProvider = project . getService ( ProjectStructureProvider :: class . java ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> if ( projectStructureProvider !is KtStaticProjectStructureProvider ) { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> return projectStructureProvider . allKtModules <EOL> . withClosureSequence < KtModule > { module -> module . allDirectDependencies ( ) . asIterable ( ) } <EOL> . filterIsInstance < KtLibraryModule > ( ) <EOL> }

/**
 * Returns all registered [KtLibraryModule] in this [StandaloneAnalysisAPISession].
 * Note: If a library module is not added as a dependency of another module, make sure to add the module directly as in:
 * ```kotlin
 * buildKtModuleProvider {
 * addModule( // <- !! addModule !!
 * buildKtLibraryModule {
 * addBinaryRoot(myKlibRootPath)
 * libraryName = myLibraryName
 * // ...
 * }
 * )
 * }
 * ```
 */


@ InternalCoroutinesApi <EOL> public fun processNextEventInCurrentThread ( ) : Long

= <EOL> ThreadLocalEventLoop . currentOrNull ( ) ? . processNextEvent ( ) ? : Long . MAX_VALUE

/**
 * Processes next event in the current thread's event loop.
 *
 * The result of this function is to be interpreted like this:
 * - `<= 0` -- there are potentially more events for immediate processing;
 * - `> 0` -- a number of nanoseconds to wait for the next scheduled event;
 * - [Long.MAX_VALUE] -- no more events or no thread-local event loop.
 *
 * Sample usage of this function:
 *
 * ```
 * while (waitingCondition) {
 * val time = processNextEventInCurrentThread()
 * LockSupport.parkNanos(time)
 * }
 * ```
 *
 * @suppress **This an internal API and should not be used from general code.**
 */


@ InternalCoroutinesApi <EOL> @ DelicateCoroutinesApi <EOL> @ PublishedApi <EOL> internal fun runSingleTaskFromCurrentSystemDispatcher ( ) : Long

{ <EOL> val thread = Thread . currentThread ( ) <EOL> if ( thread !is CoroutineScheduler . Worker ) throw IllegalStateException ( "<STR_LIT>" ) <EOL> return thread . runSingleTask ( ) <EOL> }

/**
 * Retrieves and executes a single task from the current system dispatcher ([Dispatchers.Default] or [Dispatchers.IO]).
 * Returns `0` if any task was executed, `>= 0` for number of nanoseconds to wait until invoking this method again
 * (implying that there will be a task to steal in N nanoseconds), `-1` if there is no tasks in the corresponding dispatcher at all.
 *
 * ### Invariants
 *
 * - When invoked from [Dispatchers.Default] **thread** (even if the actual context is different dispatcher,
 * [CoroutineDispatcher.limitedParallelism] or any in-place wrapper), it runs an arbitrary task that ended
 * up being scheduled to [Dispatchers.Default] or its counterpart. Tasks scheduled to [Dispatchers.IO]
 * **are not** executed[1].
 * - When invoked from [Dispatchers.IO] thread, the same rules apply, but for blocking tasks only.
 *
 * [1] -- this is purely technical limitation: the scheduler does not have "notify me when CPU token is available" API,
 * and we cannot leave this method without leaving thread in its original state.
 *
 * ### Rationale
 *
 * This is an internal API that is intended to replace IDEA's core FJP decomposition.
 * The following API is provided by IDEA core:
 * ```
 * runDecomposedTaskAndJoinIt { // <- non-suspending call
 * // spawn as many tasks as needed
 * // these tasks can also invoke 'runDecomposedTaskAndJoinIt'
 * }
 * ```
 * The key observation here is that 'runDecomposedTaskAndJoinIt' can be invoked from `Dispatchers.Default` itself,
 * thus blocking at least one thread. To avoid deadlocks and starvation during large hierarchical decompositions,
 * 'runDecomposedTaskAndJoinIt' should not just block but also **help** execute the task or other tasks
 * until an arbitrary condition is satisfied.
 *
 * See #3439 for additional details.
 *
 * ### Limitations and caveats
 *
 * - Executes tasks in-place, thus potentially leaking irrelevant thread-locals from the current thread
 * - Is not 100% effective, because the caller should somehow "wait" (or do other work) for [Long] returned nanoseconds
 * even when work arrives immediately after returning from this method.
 * - When there is no more work, it's up to the caller to decide what to do. It's important to remember that
 * work to current dispatcher may arrive **later** from external sources [1]
 *
 * [1] -- this is also a technicality that can be solved in kotlinx.coroutines itself, but unfortunately requires
 * a tremendous effort.
 *
 * @throws IllegalStateException if the current thread is not system dispatcher thread
 */


@ InternalCoroutinesApi <EOL> @ DelicateCoroutinesApi <EOL> @ PublishedApi <EOL> internal fun Thread . isIoDispatcherThread ( ) : Boolean

{ <EOL> if ( this !is CoroutineScheduler . Worker ) return false <EOL> return isIo ( ) <EOL> }

/**
 * Checks whether the given thread belongs to Dispatchers.IO.
 * Note that feature "is part of the Dispatchers.IO" is *dynamic*, meaning that the thread
 * may change this status when switching between tasks.
 *
 * This function is inteded to be used on the result of `Thread.currentThread()` for diagnostic
 * purposes, and is declared as an extension only to avoid top-level scope pollution.
 */


= classIdIfNonLocal ? . hashCode ( ) ? : symbolHashCode ( )

/**
 * All kinds of non-local named class or object symbols must have the same kind of hash code. The class ID is the best option, as the
 * same class/object may be represented by multiple different symbols.
 */


abstract fun computePackageNamesWithTopLevelClassifiers ( ) : Set < String > ?

/**
 * This function is only called if [hasSpecificClassifierPackageNamesComputation] is `true`. Otherwise, the classifier package set will
 * be taken from the cached general package names to avoid building duplicate sets.
 */


abstract fun computePackageNamesWithTopLevelCallables ( ) : Set < String > ?

/**
 * This function is only called if [hasSpecificCallablePackageNamesComputation] is `true`. Otherwise, the callable package set will be
 * taken from the cached general package names to avoid building duplicate sets.
 */


fun buildFakeOverridesForClass ( clazz : IrClass , oldSignatures : Boolean )

{ <EOL> strategy . inFile ( clazz . fileOrNull ) { <EOL> val ( staticMembers , instanceMembers ) = <EOL> clazz . declarations . filterIsInstance < IrOverridableMember > ( ) . partition { it . isStaticMember } <EOL> buildFakeOverridesForClassImpl ( clazz , instanceMembers , oldSignatures , clazz . superTypes , isStaticMembers = false ) <EOL> val superClass = clazz . superTypes . filter { it . classOrFail . owner . isClass } <EOL> buildFakeOverridesForClassImpl ( clazz , staticMembers , oldSignatures , superClass , isStaticMembers = true ) <EOL> } <EOL> }

/**
 * This function builds all fake overrides for [clazz] and computes overridden symbols for all its members.
 */


fun buildFakeOverridesForClassUsingOverriddenSymbols ( clazz : IrClass , implementedMembers : List < IrOverridableMember > = emptyList ( ) , compatibilityMode : Boolean , ignoredParentSymbols : List < IrSymbol > = emptyList ( ) ) : List < IrOverridableMember >

{ <EOL> val overriddenMembers = ( clazz . declarations . filterIsInstance < IrOverridableMember > ( ) + implementedMembers ) <EOL> . flatMap { member -> member . overriddenSymbols . map { it . owner } } <EOL> . toSet ( ) <EOL> val unoverriddenSuperMembers = clazz . superTypes . flatMap { superType -> <EOL> val superClass = superType . getClass ( ) ? : error ( "<STR_LIT>" ) <EOL> superClass . declarations <EOL> . filterIsInstanceAnd < IrOverridableMember > { <EOL> it !in overriddenMembers && it . symbol !in ignoredParentSymbols && ! it . isStaticMember <EOL> } <EOL> . mapNotNull { overriddenMember -> <EOL> val fakeOverride = strategy . fakeOverrideMember ( superType , overriddenMember , clazz ) ? : return@mapNotNull null <EOL> FakeOverride ( fakeOverride , overriddenMember ) <EOL> } <EOL> } <EOL> val unoverriddenSuperMembersGroupedByName = unoverriddenSuperMembers . groupBy { it . override . name } <EOL> val fakeOverrides = mutableListOf < IrOverridableMember > ( ) <EOL> for ( group in unoverriddenSuperMembersGroupedByName . values ) { <EOL> createAndBindFakeOverrides ( clazz , group , fakeOverrides , compatibilityMode ) <EOL> } <EOL> return fakeOverrides <EOL> }

/**
 * This function builds all missing fake overrides, assuming that already existing members have correct overriden symbols.
 *
 * In particular, if a member of super class can be overridden, but none of the members have it in their overriddenSymbols,
 * fake override would be created.
 */


private fun filterOutCustomizedFakeOverrides ( overridableMembers : Collection < FakeOverride > ) : Collection < FakeOverride >

{ <EOL> if ( overridableMembers . size < <NUM_LIT:2> ) return overridableMembers <EOL> val ( trueFakeOverrides , customizedFakeOverrides ) = overridableMembers . partition { it . override . origin == IrDeclarationOrigin . FAKE_OVERRIDE } <EOL> return trueFakeOverrides . ifEmpty { customizedFakeOverrides } <EOL> }

/**
 * If there is a mix of [IrOverridableMember]s with origin=[IrDeclarationOrigin.FAKE_OVERRIDE]s (true "fake overrides")
 * and [IrOverridableMember]s that were customized with the help of [IrUnimplementedOverridesStrategy] (customized "fake overrides"),
 * then leave only true ones. Rationale: They should point to non-abstract callable members in one of super classes, so
 * effectively they are implemented in the current class.
 */


private fun String . renumberObjects ( ) : String

{ <EOL> val ids = HashMap < String , String > ( ) <EOL> fun newId ( objectId : String ) : String { <EOL> return ids . getOrPut ( objectId , { "<STR_LIT:@>" + ids . size } ) <EOL> } <EOL> val m = Pattern . compile ( "<STR_LIT>" ) . matcher ( this ) <EOL> val sb = StringBuffer ( ) <EOL> while ( m . find ( ) ) { <EOL> m . appendReplacement ( sb , newId ( m . group ( <NUM_LIT:0> ) ) ) <EOL> } <EOL> m . appendTail ( sb ) <EOL> return sb . toString ( ) <EOL> }

/**
 * Replaces ids in the given string so that they increase
 * Example:
 * input = "A@21 B@6"
 * output = "A@0 B@1"
 */


@ Test <EOL> fun transferToReadsOneSegmentAtATime ( )

{ <EOL> val write1 = Buffer ( ) . also { it . writeString ( "<STR_LIT:a>" . repeat ( Segment . SIZE ) ) } <EOL> val write2 = Buffer ( ) . also { it . writeString ( "<STR_LIT:b>" . repeat ( Segment . SIZE ) ) } <EOL> val write3 = Buffer ( ) . also { it . writeString ( "<STR_LIT:c>" . repeat ( Segment . SIZE ) ) } <EOL> val source = Buffer ( ) <EOL> source . writeString ( "<STR_LIT>" ) <EOL> val mockSink = MockSink ( ) <EOL> val bufferedSource = ( source as RawSource ) . buffered ( ) <EOL> assertEquals ( Segment . SIZE . toLong ( ) * <NUM_LIT:3L> , bufferedSource . transferTo ( mockSink ) ) <EOL> mockSink . assertLog ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) <EOL> }

/**
 * We don't want transferTo to buffer an unbounded amount of data. Instead it
 * should buffer a segment, write it, and repeat.
 */


private fun forceResolveTypeContents ( type : KotlinType )

{ <EOL> type . annotations <EOL> if ( type . isFlexible ( ) ) { <EOL> forceResolveTypeContents ( type . asFlexibleType ( ) . lowerBound ) <EOL> forceResolveTypeContents ( type . asFlexibleType ( ) . upperBound ) <EOL> } else { <EOL> type . constructor <EOL> for ( projection in type . arguments ) { <EOL> if ( ! projection . isStarProjection ) { <EOL> forceResolveTypeContents ( projection . type ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * This function is light version of ForceResolveUtil.forceResolveAllContents
 * We can't use ForceResolveUtil.forceResolveAllContents here because it runs ForceResolveUtil.forceResolveAllContents(getConstructor()),
 * which is unsafe for some cyclic cases. For Example:
 * class A: List<A.B> {
 * class B
 * }
 * Here when we resolve class B, we should resolve supertype for A and we shouldn't start resolve for class B,
 * otherwise it would be a cycle.
 * Now there is no cycle here because member scope for A is very clever and can get lazy descriptor for class B without resolving it.
 *
 * todo: find another way after release
 */


private fun canBeUsedAsBareType ( descriptor : TypeAliasDescriptor ) : Boolean

{ <EOL> val expandedType = descriptor . expandedType <EOL> if ( expandedType . isError ) return false <EOL> val classDescriptor = descriptor . classDescriptor ? : return false <EOL> if ( ! isPossibleToSpecifyTypeArgumentsFor ( classDescriptor ) ) return false <EOL> val usedTypeParameters = linkedSetOf < TypeParameterDescriptor > ( ) <EOL> for ( argument in expandedType . arguments ) { <EOL> if ( argument . isStarProjection ) continue <EOL> if ( argument . projectionKind != INVARIANT ) return false <EOL> val argumentTypeDescriptor = argument . type . constructor . declarationDescriptor as? TypeParameterDescriptor ? : return false <EOL> if ( argumentTypeDescriptor . containingDeclaration != descriptor ) return false <EOL> if ( usedTypeParameters . contains ( argumentTypeDescriptor ) ) return false <EOL> usedTypeParameters . add ( argumentTypeDescriptor ) <EOL> } <EOL> return true <EOL> }

/**
 * Type alias can be used as bare type (after is/as, e.g., 'x is List')
 * iff all type arguments of the corresponding expanded type are either star projections
 * or type parameters of the given type alias in invariant projection,
 * and each of the type parameters is mentioned no more than once.
 *
 * E.g.:
 * ```
 * typealias HashMap<K, V> = java.util.HashMap<K, V> // can be used as bare type
 * typealias MyList<T, X> = List<X> // can be used as bare type
 * typealias StarMap<T> = Map<T, *> // can be used as bare type
 * typealias MyMap<T> = Map<T, T> // CAN NOT be used as bare type: type parameter 'T' is used twice
 * typealias StringMap<T> = Map<String, T> // CAN NOT be used as bare type: type argument 'String' is not a type parameter
 * ```
 */


private fun collectArgumentsForClassifierTypeConstructor ( c : TypeResolutionContext , classifierDescriptor : ClassifierDescriptorWithTypeParameters , qualifierParts : List < QualifiedExpressionResolver . ExpressionQualifierPart > ) : Pair < List < KtTypeProjection > , List < TypeProjection > ? > ?

{ <EOL> val classifierDescriptorChain = classifierDescriptor . classifierDescriptorsFromInnerToOuter ( ) <EOL> val reversedQualifierParts = qualifierParts . asReversed ( ) <EOL> var wasStatic = false <EOL> val result = SmartList < KtTypeProjection > ( ) <EOL> val classifierChainLastIndex = min ( classifierDescriptorChain . size , reversedQualifierParts . size ) - <NUM_LIT:1> <EOL> for ( index in <NUM_LIT:0> .. classifierChainLastIndex ) { <EOL> val qualifierPart = reversedQualifierParts [ index ] <EOL> val currentArguments = qualifierPart . typeArguments ? . arguments . orEmpty ( ) <EOL> val declaredTypeParameters = classifierDescriptorChain [ index ] . declaredTypeParameters <EOL> val currentParameters = if ( wasStatic ) emptyList ( ) else declaredTypeParameters <EOL> if ( wasStatic && currentArguments . isNotEmpty ( ) && declaredTypeParameters . isNotEmpty ( ) ) { <EOL> c . trace . report ( TYPE_ARGUMENTS_FOR_OUTER_CLASS_WHEN_NESTED_REFERENCED . on ( qualifierPart . typeArguments ! ! ) ) <EOL> return null <EOL> } <EOL> if ( currentArguments . size != currentParameters . size ) { <EOL> c . trace . report ( WRONG_NUMBER_OF_TYPE_ARGUMENTS . on ( qualifierPart . typeArguments ? : qualifierPart . expression , currentParameters . size , classifierDescriptorChain [ index ] ) ) <EOL> return null <EOL> } <EOL> result . addAll ( currentArguments ) <EOL> wasStatic = wasStatic || ! classifierDescriptorChain [ index ] . isInner <EOL> } <EOL> val nonClassQualifierParts = <EOL> reversedQualifierParts . subList ( min ( classifierChainLastIndex + <NUM_LIT:1> , reversedQualifierParts . size ) , reversedQualifierParts . size ) <EOL> for ( ( _ , _ , typeArguments ) in nonClassQualifierParts ) { <EOL> if ( typeArguments != null ) { <EOL> c . trace . report ( TYPE_ARGUMENTS_NOT_ALLOWED . on ( typeArguments , "<STR_LIT>" ) ) <EOL> return null <EOL> } <EOL> } <EOL> val parameters = classifierDescriptor . typeConstructor . parameters <EOL> if ( result . size < parameters . size ) { <EOL> val nextParameterOwner = <EOL> parameters [ result . size ] . original . containingDeclaration as? ClassDescriptor <EOL> ? : return Pair ( result , null ) <EOL> val restArguments = c . scope . findImplicitOuterClassArguments ( nextParameterOwner ) <EOL> val restParameters = parameters . subList ( result . size , parameters . size ) <EOL> val typeArgumentsCanBeSpecifiedCount = <EOL> classifierDescriptor . classifierDescriptorsFromInnerToOuter ( ) . sumOf { it . declaredTypeParameters . size } <EOL> if ( restArguments == null && typeArgumentsCanBeSpecifiedCount > result . size ) { <EOL> c . trace . report ( OUTER_CLASS_ARGUMENTS_REQUIRED . on ( qualifierParts . first ( ) . expression , nextParameterOwner ) ) <EOL> return null <EOL> } else if ( restArguments == null ) { <EOL> assert ( typeArgumentsCanBeSpecifiedCount == result . size ) { <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> } <EOL> return Pair ( result , null ) <EOL> } else { <EOL> assert ( restParameters . size == restArguments . size ) { <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> } <EOL> return Pair ( result , restArguments ) <EOL> } <EOL> } <EOL> return Pair ( result , null ) <EOL> }

/**
 * @return yet unresolved KtTypeProjection arguments and already resolved ones relevant to an outer class
 * @return null if error was reported
 *
 * If second component is null then rest of the arguments should be appended using default types of relevant parameters
 */


private fun appendDefaultArgumentsForLocalClassifier ( fromIndex : Int , constructorParameters : List < TypeParameterDescriptor > )

= constructorParameters . subList ( fromIndex , constructorParameters . size ) . map { <EOL> TypeProjectionImpl ( it . original . defaultType ) <EOL> }

/**
 * For cases like:
 * fun <E> foo() {
 * class Local<F>
 * val x: Local<Int> <-- resolve this type
 * }
 *
 * type constructor for `Local` captures type parameter E from containing outer function
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun CharSequence . elementAt ( index : Int ) : Char

{ <EOL> return get ( index ) <EOL> }

/**
 * Returns a character at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this char sequence.
 *
 * @sample samples.collections.Collections.Elements.elementAt
 */


@ Test <EOL> fun `test - simple class` ( )

{ <EOL> val module = createModuleDescriptor ( "<STR_LIT>" ) <EOL> val foo = module . findClassAcrossModuleDependencies ( ClassId . fromString ( "<STR_LIT:Foo>" ) ) ! ! <EOL> assertNull ( createObjCExportMapper ( ) . getCustomTypeMapper ( foo ) ) <EOL> }

/**
 * No 'type mapper' expected for a simple Kotlin class like 'Foo'.
 * Only well known standard types (List, ...) will get mapped to their corresponding
 * ObjC counterpart (NSArray, ...)
 */


@ Test <EOL> fun `test - List of int` ( )

{ <EOL> val module = createModuleDescriptor ( "<STR_LIT>" ) <EOL> val objcExportMapper = createObjCExportMapper ( ) <EOL> val objcExportNamer = createObjCExportNamer ( mapper = objcExportMapper ) <EOL> val objcExportTranslator = ObjCExportTranslatorImpl ( generator = ObjCExportHeaderGeneratorImpl ( moduleDescriptors = listOf ( module ) , mapper = objcExportMapper , namer = objcExportNamer , problemCollector = ObjCExportProblemCollector . SILENT , objcGenerics = true , shouldExportKDoc = false , additionalImports = emptyList ( ) ) , mapper = objcExportMapper , namer = objcExportNamer , problemCollector = ObjCExportProblemCollector . SILENT , objcGenerics = true ) <EOL> val listClassDescriptor = module . findClassAcrossModuleDependencies ( ClassId . fromString ( "<STR_LIT>" ) ) ! ! <EOL> val intClassDescriptor = module . findClassAcrossModuleDependencies ( ClassId . fromString ( "<STR_LIT>" ) ) ! ! <EOL> val listOfIntType = KotlinTypeFactory . simpleNotNullType ( TypeAttributes . Empty , listClassDescriptor , listOf ( TypeProjectionImpl ( KotlinTypeFactory . simpleNotNullType ( TypeAttributes . Empty , intClassDescriptor , emptyList ( ) ) ) ) ) <EOL> val typeMapper = assertNotNull ( objcExportMapper . getCustomTypeMapper ( listClassDescriptor ) ) <EOL> assertEquals ( ClassId . fromString ( "<STR_LIT>" ) , typeMapper . mappedClassId ) <EOL> val listOfIntMapped = typeMapper . mapType ( listOfIntType , objcExportTranslator , objCExportScope = ObjCRootExportScope ) <EOL> assertEquals ( ObjCClassType ( "<STR_LIT>" , typeArguments = listOf ( ObjCClassType ( "<STR_LIT:Int>" ) ) ) , listOfIntMapped ) <EOL> assertEquals ( "<STR_LIT>" , listOfIntMapped . toString ( ) ) <EOL> }

/**
 * Will test ObjC type mapping from List<Int> to NSArray<Int *> *
 */


@ ExperimentalStdlibApi <EOL> public fun ByteString . toHexString ( format : HexFormat = HexFormat . Default ) : String

{ <EOL> return getBackingArrayReference ( ) . toHexString ( <NUM_LIT:0> , getBackingArrayReference ( ) . size , format ) <EOL> }

/**
 * Formats bytes in this byte string using the specified [format].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.BytesHexFormat] affect formatting.
 *
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if the result length is more than [String] maximum capacity.
 */


@ ExperimentalStdlibApi <EOL> public fun ByteString . toHexString ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = size , format : HexFormat = HexFormat . Default ) : String

{ <EOL> return getBackingArrayReference ( ) . toHexString ( startIndex , endIndex , format ) <EOL> }

/**
 * Formats bytes in this byte string using the specified [HexFormat].
 *
 * Note that only [HexFormat.upperCase] and [HexFormat.BytesHexFormat] affect formatting.
 *
 * @param startIndex the beginning (inclusive) of the subrange to format, 0 by default.
 * @param endIndex the end (exclusive) of the subrange to format, size of this byte string by default.
 * @param format the [HexFormat] to use for formatting, [HexFormat.Default] by default.
 *
 * @throws IndexOutOfBoundsException when [startIndex] or [endIndex] is out of range of this byte string indices.
 * @throws IllegalArgumentException when `startIndex > endIndex`.
 * @throws IllegalArgumentException if the result length is more than [String] maximum capacity.
 */


@ ExperimentalStdlibApi <EOL> public fun String . hexToByteString ( format : HexFormat = HexFormat . Default ) : ByteString

{ <EOL> return ByteString . wrap ( hexToByteArray ( format ) ) <EOL> }

/**
 * Parses bytes from this string using the specified [HexFormat].
 *
 * Note that only [HexFormat.BytesHexFormat] affects parsing,
 * and parsing is performed in case-insensitive manner.
 * Also, any of the char sequences CRLF, LF and CR is considered a valid line separator.
 *
 * @param format the [HexFormat] to use for parsing, [HexFormat.Default] by default.
 *
 * @throws IllegalArgumentException if this string does not comply with the specified [format].
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> inline fun < reified T : Annotation > KAnnotatedElement . findAnnotation ( ) : T ?

= <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> annotations . firstOrNull { it is T } as T ?

/**
 * Returns an annotation of the given type on this element.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_MEMBER>" , "<STR_LIT:INVISIBLE_REFERENCE>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> inline fun < reified T : Annotation > KAnnotatedElement . hasAnnotation ( ) : Boolean

= <EOL> findAnnotation < T > ( ) != null

/**
 * Returns true if this element is annotated with an annotation of type [T].
 */


@ SinceKotlin ( "<STR_LIT:1.7>" ) <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_REFERENCE>" , "<STR_LIT:INVISIBLE_MEMBER>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> inline fun < reified T : Annotation > KAnnotatedElement . findAnnotations ( ) : List < T >

= <EOL> findAnnotations ( T :: class )

/**
 * Returns all annotations of the given type on this element, including individually applied annotations
 * as well as repeated annotations.
 *
 * In case the annotation is repeated, instances are extracted from the container annotation class similarly to how it happens
 * in Java reflection ([java.lang.reflect.AnnotatedElement.getAnnotationsByType]). This is supported both for Kotlin-repeatable
 * ([kotlin.annotation.Repeatable]) and Java-repeatable ([java.lang.annotation.Repeatable]) annotation classes.
 */


@ SinceKotlin ( "<STR_LIT:1.7>" ) <EOL> @ Suppress ( "<STR_LIT:INVISIBLE_REFERENCE>" , "<STR_LIT:INVISIBLE_MEMBER>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> fun < T : Annotation > KAnnotatedElement . findAnnotations ( klass : KClass < T > ) : List < T >

{ <EOL> val filtered = annotations . filterIsInstance ( klass . java ) <EOL> if ( filtered . isNotEmpty ( ) ) return filtered <EOL> val containerClass = Java8RepeatableContainerLoader . loadRepeatableContainer ( klass . java ) <EOL> if ( containerClass != null ) { <EOL> val container = annotations . firstOrNull { it . annotationClass . java == containerClass } <EOL> if ( container != null ) { <EOL> val valueMethod = container :: class . java . getMethod ( "<STR_LIT:value>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return ( valueMethod ( container ) as Array < T > ) . asList ( ) <EOL> } <EOL> } <EOL> return emptyList ( ) <EOL> }


private fun specialDoubleToULong ( v : Double ) : ULong

{ <EOL> require ( v >= <NUM_LIT:2.0> . pow ( <NUM_LIT> ) ) <EOL> require ( v < <NUM_LIT:2.0> . pow ( <NUM_LIT> ) ) <EOL> val bits = v . toBits ( ) . toULong ( ) <EOL> return ( <NUM_LIT> shl <NUM_LIT> ) + ( ( bits and ( <NUM_LIT> shl <NUM_LIT> ) - <NUM_LIT:1u> ) shl <NUM_LIT:11> ) <EOL> }

/** Creates an ULong value directly from mantissa bits of Double that is in range [2^63, 2^64). */


public fun loadModel ( modelType : OnnxModelType < * > , vararg executionProviders : ExecutionProvider = arrayOf ( ExecutionProvider . CPU ( ) ) ) : OnnxInferenceModel

{ <EOL> val modelResourceId = context . resources . getIdentifier ( modelType . modelRelativePath , "<STR_LIT>" , context . packageName ) <EOL> val inferenceModel = OnnxInferenceModel { <EOL> context . resources . openRawResource ( modelResourceId ) . use { it . readBytes ( ) } <EOL> } <EOL> inferenceModel . initializeWith ( * executionProviders ) <EOL> return inferenceModel <EOL> }

/**
 * Loads ONNX model from android resources.
 * By default, the model is initialized with [ExecutionProvider.CPU] execution provider.
 *
 * @param [modelType] model type from [ONNXModels]
 * @param [executionProviders] execution providers for model initialization.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> override fun < T : InferenceModel < * > , U > loadModel ( modelType : ModelType < T , U > , loadingMode : LoadingMode , ) : T

{ <EOL> return loadModel ( modelType as OnnxModelType < * > ) as T <EOL> }

/**
 * It's equivalent to [loadModel] with [ExecutionProvider.CPU] execution provider.
 *
 * @param [modelType] model type from [ONNXModels]
 * @param [loadingMode] it's ignored
 */


internal suspend fun Project . findCInteropCommonizerGroup ( dependent : CInteropCommonizerDependent ) : CInteropCommonizerGroup ?

{ <EOL> val suitableGroups = kotlinCInteropGroups . await ( ) . filter { group -> <EOL> group . interops . containsAll ( dependent . interops ) && group . targets . contains ( dependent . target ) <EOL> } <EOL> assert ( suitableGroups . size <= <NUM_LIT:1> ) { <EOL> "<STR_LIT>" <EOL> } <EOL> return suitableGroups . firstOrNull ( ) <EOL> }

/**
 * Utility function that allows to find the corresponding [CInteropCommonizerGroup] for a given [CInteropCommonizerDependent]
 */


/**
 * [<caret_1>one]
 *
 * [<caret_2>one.two]
 * [one.<caret_3>two]
 *
 * [<caret_4>one.two.three]
 * [one.<caret_5>two.three]
 * [one.two.<caret_6>three]
 *
 * [<caret_7>one.two.three.Four.Five]
 * [one.<caret_8>two.three.Four.Five]
 * [one.two.<caret_9>three.Four.Five]
 */


public fun ObjectDetectionModelBase < Bitmap > . detectObjects ( imageProxy : ImageProxy , topK : Int = <NUM_LIT:3> ) : List < DetectedObject >

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

/**
 * Returns the detected object for the given image sorted by the score.
 * Internal preprocessing is updated to rotate image to match target orientation.
 * After prediction, internal preprocessing is restored to the original state.
 *
 * @param [imageProxy] Input image.
 * @param [topK] The number of the detected objects with the highest score to be returned.
 * @return List of [DetectedObject] sorted by score.
 */


private fun IrConstructor . countContextTypeParameters ( ) : Int

{ <EOL> fun countImpl ( container : IrDeclarationParent ) : Int { <EOL> return when ( container ) { <EOL> is IrClass -> container . typeParameters . size + container . run { if ( isInner ) countImpl ( container . parent ) else <NUM_LIT:0> } <EOL> is IrFunction -> container . typeParameters . size + countImpl ( container . parent ) <EOL> is IrProperty -> ( container . run { getter ? : setter } ? . typeParameters ? . size ? : <NUM_LIT:0> ) + countImpl ( container . parent ) <EOL> is IrDeclaration -> countImpl ( container . parent ) <EOL> else -> <NUM_LIT:0> <EOL> } <EOL> } <EOL> return countImpl ( parent ) <EOL> }

/**
 inner class IN<IT> {
 private fun <T> foo() {
 class CC<TT>(t: T, tt: TT, ttt: IT)
 }
 }
 */


fun applyProperty ( receiver : StackValue , resolvedCall : ResolvedCall < * > , c : Context ) : StackValue ?

= null

/**
 * Used for generating custom byte code for the property value obtain. This function has lazy semantics.
 * Returns new stack value.
 */


fun applyFunction ( receiver : StackValue , resolvedCall : ResolvedCall < * > , c : Context ) : StackValue ?

= null

/**
 * Used for generating custom byte code for the function call. This function has lazy semantics.
 * Returns new stack value.
 */


inline fun < reified T > List < T > . toDS ( ) : Dataset < T >

= toDS ( spark )

/** Utility method to create dataset from list. */


inline fun < reified T > List < T > . toDF ( vararg colNames : String ) : Dataset < Row >

= toDF ( spark , * colNames )

/** Utility method to create dataframe from list. */


inline fun < reified T > Array < T > . toDS ( ) : Dataset < T >

= toDS ( spark )

/** Utility method to create dataset from [Array]. */


inline fun < reified T > Array < T > . toDF ( vararg colNames : String ) : Dataset < Row >

= toDF ( spark , * colNames )

/** Utility method to create dataframe from [Array]. */


inline fun < reified T > dsOf ( vararg arg : T ) : Dataset < T >

= spark . dsOf ( * arg )

/** Utility method to create dataset from vararg arguments. */


inline fun < reified T > emptyDataset ( ) : Dataset < T >

= spark . emptyDataset ( encoder < T > ( ) )

/** Creates new empty dataset of type [T]. */


inline fun < reified T > dfOf ( vararg arg : T ) : Dataset < Row >

= spark . dfOf ( * arg )

/** Utility method to create dataframe from *array or vararg arguments */


inline fun < reified T > dfOf ( colNames : Array < String > , vararg arg : T ) : Dataset < Row >

= spark . dfOf ( colNames , * arg )

/**Utility method to create dataframe from *array or vararg arguments with given column names */


inline fun < reified T > RDD < T > . toDS ( ) : Dataset < T >

= toDS ( spark )

/** Utility method to create dataset from Scala [RDD]. */


inline fun < reified T > JavaRDDLike < T , * > . toDS ( ) : Dataset < T >

= toDS ( spark )

/** Utility method to create dataset from [JavaRDDLike]. */


inline fun < reified T > RDD < T > . toDF ( vararg colNames : String ) : Dataset < Row >

= toDF ( spark , * colNames )

/**
 * Utility method to create Dataset<Row> (Dataframe) from RDD.
 * NOTE: [T] must be [Serializable].
 */


inline fun < reified T > JavaRDDLike < T , * > . toDF ( vararg colNames : String ) : Dataset < Row >

= toDF ( spark , * colNames )

/**
 * Utility method to create Dataset<Row> (Dataframe) from JavaRDD.
 * NOTE: [T] must be [Serializable].
 */


fun < T > List < T > . toRDD ( numSlices : Int = sc . defaultParallelism ( ) ) : JavaRDD < T >

= <EOL> sc . toRDD ( this , numSlices )

/**
 * Utility method to create an RDD from a list.
 * NOTE: [T] must be [Serializable].
 */


fun < T > rddOf ( vararg elements : T , numSlices : Int = sc . defaultParallelism ( ) ) : JavaRDD < T >

= <EOL> sc . toRDD ( elements . toList ( ) , numSlices )


fun setRunAfterStart ( block : KSparkStreamingSession . ( ) -> Unit )

{ <EOL> runAfterStart = block <EOL> }

/** [block] will be run after the streaming session has started from a new context (so not when loading from a checkpoint)
 * and before it's terminated. */


fun getSpark ( sc : SparkConf ) : SparkSession

= <EOL> SparkSession <EOL> . builder ( ) <EOL> . config ( sc ) <EOL> . getOrCreate ( )

/** Creates new spark session from given [sc]. */


fun getSpark ( rddForConf : JavaRDDLike < * , * > ) : SparkSession

= getSpark ( rddForConf . context ( ) . conf )

/** Creates new spark session from context of given JavaRDD, [rddForConf]. */


fun getSpark ( sscForConf : JavaStreamingContext ) : SparkSession

= getSpark ( sscForConf . sparkContext ( ) . conf )

/** Creates new spark session from context of given JavaStreamingContext, [sscForConf] */


fun < T > withSpark ( sc : SparkConf , func : KSparkSession . ( ) -> T ) : T

= <EOL> KSparkSession ( getSpark ( sc ) ) . func ( )

/**
 * Helper function to enter Spark scope from [sc] like
 * ```kotlin
 * withSpark(sc) { // this: KSparkSession
 *
 * }
 * ```
 */


fun < T > withSpark ( rddForConf : JavaRDDLike < * , * > , func : KSparkSession . ( ) -> T ) : T

= <EOL> KSparkSession ( getSpark ( rddForConf ) ) . func ( )

/**
 * Helper function to enter Spark scope from a provided like
 * when using the `foreachRDD` function.
 * ```kotlin
 * withSpark(rdd) { // this: KSparkSession
 *
 * }
 * ```
 */


fun < T > withSpark ( sscForConf : JavaStreamingContext , func : KSparkSession . ( ) -> T ) : T

= <EOL> KSparkSession ( getSpark ( sscForConf ) ) . func ( )

/**
 * Helper function to enter Spark scope from [sscForConf] like
 * ```kotlin
 * withSpark(ssc) { // this: KSparkSession
 *
 * }
 * ```
 */


fun SparkContext . setLogLevel ( level : SparkLogLevel ) : Unit

= setLogLevel ( level . name )

/**
 * Control our logLevel. This overrides any user-defined log settings.
 * @param level The desired log level as [SparkLogLevel].
 */