Datasets:

Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: Invalid escape character in string. in row 438
Traceback:    Traceback (most recent call last):
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 354, in _generate_tables
                  df = pandas_read_json(f)
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 38, in pandas_read_json
                  return pd.read_json(path_or_buf, **kwargs)
                         ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 815, in read_json
                  return json_reader.read()
                         ~~~~~~~~~~~~~~~~^^
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1014, in read
                  obj = self._get_object_parser(self.data)
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1040, in _get_object_parser
                  obj = FrameParser(json, **kwargs).parse()
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1176, in parse
                  self._parse()
                  ~~~~~~~~~~~^^
                File "/usr/local/lib/python3.14/site-packages/pandas/io/json/_json.py", line 1392, in _parse
                  ujson_loads(json, precise_float=self.precise_float), dtype=None
                  ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
              ValueError: Trailing data
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1835, in _prepare_split_single
                  for key, table in generator:
                                    ^^^^^^^^^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 623, in wrapped
                  for item in generator(*args, **kwargs):
                              ~~~~~~~~~^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 357, in _generate_tables
                  raise e
                File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 295, in _generate_tables
                  pa_table = paj.read_json(
                      io.BytesIO(batch), read_options=paj.ReadOptions(block_size=block_size)
                  )
                File "pyarrow/_json.pyx", line 364, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 155, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 92, in pyarrow.lib.check_status
                  raise convert_status(status)
              pyarrow.lib.ArrowInvalid: JSON parse error: Invalid escape character in string. in row 438
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1382, in compute_config_parquet_and_info_response
                  parquet_operations, partial, estimated_dataset_info = stream_convert_to_parquet(
                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~^
                      builder, max_dataset_size_bytes=max_dataset_size_bytes
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  )
                  ^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 958, in stream_convert_to_parquet
                  builder._prepare_split(split_generator=splits_generators[split], file_format="parquet")
                  ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1702, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                                               ~~~~~~~~~~~~~~~~~~~~~~~~~~^
                      gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  ):
                  ^
                File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1887, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

question
string
answer
string
What is caching and why is it important in IT systems?
Caching stores frequently accessed data in a faster storage layer so future requests are served quicker. It reduces latency, lowers load on databases and backend services, and improves throughput. Common layers include browser cache, CDN edge cache, application-level in-memory cache such as Redis or Memcached, and data...
What is the difference between a cache hit and a cache miss?
A cache hit occurs when the requested data is found in the cache, so the response is fast. A cache miss occurs when the data is absent, forcing the system to fetch it from the origin, store it in the cache, and then return it. Cache hit ratio is the percentage of requests served from cache, and a high ratio is a key pe...
What are common cache eviction policies?
Common eviction policies include LRU (least recently used), LFU (least frequently used), FIFO (first in, first out), and TTL-based expiration. LRU is popular because it approximates real access patterns well, while LFU favors items that are consistently popular. The choice depends on the workload: read-heavy caches oft...
What is cache invalidation and why is it considered difficult?
Cache invalidation is the process of removing or updating stale entries when the underlying data changes. It is difficult because the cache and the origin can drift out of sync, and coordinating invalidation across distributed nodes is complex. Common strategies include TTL expiry, write-through, write-behind, and expl...
What is the difference between write-through, write-back, and write-around caching?
Write-through writes to both cache and origin synchronously, keeping them consistent but adding latency. Write-back writes only to the cache and flushes to the origin later, which is faster but risks data loss on failure. Write-around writes directly to the origin and bypasses the cache, which avoids polluting the cach...
What is a distributed cache and when should you use one?
A distributed cache spreads cached data across multiple nodes, providing capacity and throughput beyond a single machine. It is used when a single-node cache cannot handle the load or when multiple application servers need shared access to the same cached data. Examples include Redis Cluster and Memcached pools. Key co...
What is a message queue and how does it work?
A message queue is a middleware component that stores messages sent by producers until consumers retrieve and process them. It decouples services, absorbs traffic bursts, and enables asynchronous processing. Producers publish messages to a queue or topic, and consumers pull or receive them at their own pace. This patte...
What is the difference between a queue and a publish-subscribe topic?
In a queue, each message is delivered to exactly one consumer, which is ideal for distributing work across workers. In a publish-subscribe topic, each message is delivered to every subscribed consumer, which suits event broadcasting such as cache invalidation or configuration updates. Many brokers, such as Kafka and Ra...
What is at-least-once versus at-most-once versus exactly-once delivery?
At-most-once delivery sends a message once and never retries, so messages can be lost but never duplicated. At-least-once delivery retries until acknowledged, so messages are never lost but may be duplicated. Exactly-once delivery guarantees a single processing, which is the hardest to achieve and typically requires id...
What is idempotency and why does it matter for message processing?
Idempotency means that processing the same message multiple times produces the same result as processing it once. It matters because most queues guarantee at-least-once delivery, so duplicates are expected. Techniques include deduplication keys, unique constraints in the database, and conditional updates. Idempotent co...
What is a dead-letter queue?
A dead-letter queue is a separate queue where messages are routed after repeated processing failures. It prevents poison messages from blocking the main queue and allows engineers to inspect, fix, and replay them later. A typical setup retries a message a few times, then moves it to the dead-letter queue with metadata ...
What is backpressure in a streaming system?
Backpressure is a mechanism that slows down producers when consumers cannot keep up. Without it, fast producers can overwhelm buffers and cause memory exhaustion or dropped messages. Systems implement backpressure through bounded queues, flow control protocols, or adaptive rate limiting. It keeps the pipeline stable an...
What is Kafka and how does it differ from a traditional message queue?
Kafka is a distributed event streaming platform organized as partitioned, replicated logs. Unlike a traditional queue that deletes messages after consumption, Kafka retains messages for a configurable period, and multiple consumer groups can read the same stream independently. This makes Kafka suitable for event sourci...
What is a consumer group in Kafka?
A consumer group is a set of consumers that cooperatively read a topic. Each partition is assigned to exactly one consumer in the group, which enables parallel processing while preserving per-partition ordering. When consumers join or leave, partitions are rebalanced automatically. Different consumer groups can read th...
What is a database index and how does it speed up queries?
A database index is a data structure, usually a B-tree or hash table, that maps column values to row locations. It allows the database to locate rows without scanning the entire table, dramatically reducing query time for lookups, joins, and range queries. Indexes trade extra storage and slower writes for faster reads,...
What is the difference between a clustered and a non-clustered index?
A clustered index determines the physical order of rows in the table, so each table can have only one. A non-clustered index is a separate structure with pointers to the rows, and a table can have many. Clustered indexes are efficient for range scans, while non-clustered indexes speed up specific lookups at the cost of...
What is a composite index and when is it useful?
A composite index covers multiple columns in a defined order, such as (last_name, first_name). It is useful when queries filter or sort by those columns together. The leftmost prefix rule applies: the index helps queries that use the leading column, and additional columns extend its usefulness. Column order should matc...
What is a covering index?
A covering index contains all the columns needed to satisfy a query, so the database can answer it directly from the index without reading the table. This reduces I/O and speeds up read-heavy workloads. Covering indexes are especially valuable for frequent queries on large tables, though they add storage overhead and m...
What is index selectivity and why does it matter?
Index selectivity is the ratio of distinct values to total rows in a column. High selectivity, such as a unique email column, means the index narrows the search quickly. Low selectivity, such as a boolean flag, means the index offers little benefit and the optimizer may ignore it. Selective indexes are more effective f...
What is a full table scan and when is it acceptable?
A full table scan reads every row in a table to satisfy a query. It is acceptable when the table is small, when most rows match the filter, or when no suitable index exists. For large tables, full scans are expensive, so query optimization focuses on adding indexes, rewriting queries, or partitioning data to avoid them...
What is database partitioning and how does it differ from sharding?
Partitioning splits a large table into smaller pieces within the same database instance, often by range, list, or hash, improving manageability and query pruning. Sharding distributes data across multiple independent database instances, each holding a subset of rows. Partitioning is primarily a single-node optimization...
What is a CDN and how does it work?
A content delivery network is a geographically distributed system of edge servers that cache content close to users. When a user requests an asset, DNS or anycast routes them to the nearest edge, which serves cached content or fetches it from the origin and caches it. CDNs reduce latency, absorb traffic spikes, and low...
What is a CDN edge location?
A CDN edge location is a data center positioned close to end users, holding cached copies of content. Edges serve requests directly when they have a fresh copy, and otherwise fetch from the origin or a mid-tier cache. More edge locations generally mean lower latency and better resilience, but the CDN provider balances ...
What is cache-control and how do its directives work?
Cache-Control is an HTTP header that tells browsers and CDNs how to cache a response. Directives include max-age for freshness lifetime, no-cache for revalidation, no-store to prevent caching, public or private for scope, and stale-while-revalidate to serve stale content while refreshing. Correct directives balance per...
What is the difference between ETag and Last-Modified?
ETag is a validator based on a content hash or version identifier, while Last-Modified is a timestamp of the last change. Both enable conditional requests: the client sends If-None-Match or If-Modified-Since, and the server returns 304 Not Modified if the cached copy is still valid. ETags are more precise, while Last-M...
What is Kotlin and how does it relate to Java?
Kotlin is a statically typed programming language that runs on the JVM (Java Virtual Machine), Android, and other platforms. It was developed by JetBrains to address pain points in Java, such as verbosity and null safety issues. Kotlin is fully interoperable with existing Java code, allowing developers to migrate incre...
How does Kotlin handle null safety compared to Java?
Kotlin distinguishes between nullable and non-nullable types at compile time. By default, variables cannot hold null unless explicitly declared with a '?' suffix (e.g., String?). This prevents NullPointerExceptions at runtime by forcing developers to handle potential null values via safe calls (?.), elvis operators (?:...
What is the difference between val and var in Kotlin?
In Kotlin, 'val' declares an immutable reference (read-only), similar to 'final' in Java. Once assigned, it cannot be reassigned. 'var' declares a mutable variable that can be reassigned. Note that 'val' ensures the reference itself is constant, but if the object referenced is mutable (like a List), its contents can st...
Explain the concept of extension functions in Kotlin.
Extension functions allow you to add new functionality to existing classes without inheriting from them or using utility patterns. They are declared outside the class body but behave as if they were members. For example, you can define 'fun String.lastChar(): Char = this[this.length - 1]'. At compile time, these are co...
What are data classes in Kotlin?
Data classes are special classes designed to hold data. When you declare a class with the 'data' keyword, the compiler automatically generates useful boilerplate: equals(), hashCode(), toString(), copy(), and componentN() functions. This eliminates the need to manually write getters/setters or comparison logic, making ...
How do sealed classes work in Kotlin?
Sealed classes restrict inheritance so that all subclasses must be defined within the same file/module. This creates a closed hierarchy, enabling exhaustive when-expressions. The compiler knows all possible subtypes, ensuring that every branch of a when statement is handled or explicitly marked as unreachable. This is ...
What is the purpose of the scope functions let, run, with, apply, and also?
Scope functions execute a block of code within the context of an object. 'let' and 'run' return the result of the lambda; 'apply' and 'also' return the object itself. 'with' is not an extension function but takes the object as a parameter. They reduce repetition by avoiding explicit references to the object inside the ...
How does Kotlin support functional programming?
Kotlin treats functions as first-class citizens. You can pass functions as parameters, return them from other functions, and store them in variables. It supports higher-order functions like map, filter, and reduce. Lambda expressions provide concise syntax for anonymous functions. Additionally, Kotlin offers tail-call ...
What are coroutines in Kotlin?
Coroutines are lightweight threads managed by the Kotlin standard library. Unlike OS threads, coroutines are cooperative multitasking units that suspend execution without blocking the underlying thread. This allows writing asynchronous code in a synchronous style, improving readability and performance for I/O-bound tas...
Explain the difference between launch and async in Kotlin coroutines.
'launch' starts a coroutine and returns a Job object. It is fire-and-forget, suitable for background tasks where no result is needed immediately. 'async' starts a coroutine and returns a Deferred<T> object, which represents a future result. You call '.await()' on Deferred to get the value, handling exceptions explicitl...
What is suspend function in Kotlin?
A suspend function is a function that can pause its execution without blocking the thread. It is called from within a coroutine context. When a suspend function encounters a suspension point (like delay or network I/O), it saves its state and yields control back to the dispatcher. Later, when the operation completes, t...
How does Kotlin handle collection mutability?
Kotlin separates read-only interfaces from mutable ones. Collection<T>, List<T>, Set<T>, and Map<K,V> are read-only views. Their counterparts MutableList<T>, MutableSet<T>, and MutableMap<K,V> allow modifications. This distinction helps enforce immutability contracts at compile time. However, note that a read-only inte...
What is the Elvis operator ?: in Kotlin?
The Elvis operator (?:) provides a default value when the left-hand expression is null. Syntax: 'expression ?: defaultValue'. If 'expression' is not null, its value is returned; otherwise, 'defaultValue' is evaluated and returned. It simplifies null-checking logic, replacing verbose if-else blocks. For example: 'val na...
How do safe calls ?. work in Kotlin?
The safe call operator (?.) accesses properties or methods only if the receiver is not null. If the receiver is null, the entire expression evaluates to null instead of throwing a NullPointerException. Chaining is possible: 'user?.address?.city'. Each step checks for null before proceeding. This drastically reduces the...
What is the !! operator in Kotlin?
The double bang (!! ) asserts that a nullable value is not null. If the value is indeed null, it throws a NullPointerException immediately. It should be used sparingly, typically when you are certain a value cannot be null due to prior logic or external guarantees. Overuse defeats the purpose of Kotlin's null safety sy...
Explain reified type parameters in Kotlin inline functions.
Normally, generic type information is erased at runtime. However, in inline functions, you can mark a type parameter as 'reified', allowing access to the actual type at runtime using 'T::class' or 'is T'. This is useful for serialization frameworks or reflection-based utilities where knowing the concrete type during ex...
What are companion objects in Kotlin?
Companion objects are singleton objects associated with a class. They serve as a replacement for Java's static members. You can define constants, factory methods, or utility functions inside a companion object. Although technically an instance of an anonymous class, they are accessed via the class name (e.g., MyClass.C...
How does Kotlin interoperate with Java generics?
Kotlin maps Java wildcards (?) to projection modifiers: 'out' (producer, covariant) and 'in' (consumer, contravariant). For example, List<? extends Number> becomes List<out Number>. Kotlin enforces stricter variance rules than Java, preventing unsafe casts. Platform types (T!) arise when receiving Java objects, indicat...
What is platform type in Kotlin?
Platform types occur when Kotlin code interacts with Java APIs whose nullability annotations are missing or inconsistent. The compiler infers the type as T! (platform type), meaning it could be null or non-null. Kotlin does not enforce null checks on these types automatically, leaving responsibility to the developer. U...
Describe the when expression in Kotlin.
The 'when' expression is a powerful switch-like construct that can match values against constants, ranges, types, or predicates. Unlike Java's switch, 'when' can be used as an expression returning a value. It supports smart casting: if a branch checks 'x is Int', subsequent code in that branch treats x as Int. Exhausti...
What are destructuring declarations in Kotlin?
Destructuring declarations allow unpacking composite values into individual variables in one line. Commonly used with data classes, pairs, and triples. Example: 'val (name, age) = person'. Behind the scenes, it calls component1(), component2(), etc. This enhances readability when extracting fields from objects or itera...
How do you create singletons in Kotlin?
Use the 'object' keyword to declare a singleton instance. Unlike classes, objects are instantiated eagerly upon first access and exist as a single global instance throughout the application lifecycle. They are ideal for caching, configuration holders, or stateless services. Companion objects also act as singletons tied...
What is the difference between object and companion object?
An 'object' declaration defines a standalone singleton not attached to any class. A 'companion object' is nested within a class and acts as its static counterpart. While both are singletons, companion objects share the class's namespace and can access private members of the outer class. Standalone objects are independe...
Explain delegated properties in Kotlin.
Delegated properties move getter/setter logic to separate handler objects. Built-in delegates include lazy (initialize on first access), observable (notify on change), and vetoable (prevent changes). Custom delegates implement getValue/setValue interfaces. This promotes separation of concerns, allowing reusable propert...
What is lazy initialization in Kotlin?
Lazy delegation ('by lazy { ... }') delays computation of a property until it is first accessed. Subsequent accesses return the cached value. It is thread-safe by default (synchronized) but can be configured for non-thread-safe scenarios using LazyThreadSafetyMode.NONE. Useful for expensive calculations or resources th...
How does Kotlin handle string interpolation?
Kotlin uses '$' for simple variable insertion and '${}' for complex expressions within strings. Example: "Hello, ${user.name.toUpperCase()}!". This replaces concatenation (+) with readable templates. Triple quotes ("""...""") enable multi-line strings preserving formatting and indentation, ideal for SQL queries or JSON...
What are raw strings in Kotlin?
Raw strings are delimited by triple quotes ("""..."""). They preserve whitespace, newlines, and special characters literally, without escaping requirements. Interpolation still works inside them. To remove common leading spaces, use trimIndent() or trimMargin(). This feature simplifies embedding formatted text, HTML, o...
Explain the concept of smart casts in Kotlin.
Smart casts automatically convert a variable to a more specific type after a successful type check (is/as). For example, after 'if (x is String)', the compiler knows x is String in that block, eliminating the need for explicit casting '(x as String)'. This relies on immutability; if the variable is mutable or captured ...
What is the difference between == and === in Kotlin?
== compares structural equality (values/content), delegating to the equals() method. === compares referential identity (memory address), checking if two references point to the exact same object instance. Primitives like Int usually cache small values, so === might sometimes behave unexpectedly, but generally, use == f...
How do you handle exceptions in Kotlin?
Kotlin does not have checked exceptions. All exceptions are unchecked (runtime). You can throw exceptions using 'throw Exception("msg")'. Try-catch-finally blocks work similarly to Java. Since there's no forced handling, APIs are cleaner, but developers must document potential exceptions or rely on testing/static analy...
What is runCatching in Kotlin?
runCatching executes a block and captures any thrown exception into a Result object instead of propagating it. It returns Result.success(value) or Result.failure(exception). This functional approach avoids try-catch boilerplate and allows chaining operations like .map, .recover, or .onFailure, promoting graceful error ...
Explain the Result type in Kotlin.
Result<T> is a sealed class representing either success with a value or failure with an exception. It encapsulates outcomes without throwing exceptions, making control flow explicit. Methods like isSuccess, isFailure, getOrNull, and exceptionOrNull facilitate inspection. It integrates well with functional combinators, ...
What are higher-order functions in Kotlin?
Higher-order functions take other functions as parameters or return them. Examples include map, filter, fold, and custom utilities like retry(times=3, action={}). They enable abstraction of behavior, allowing code reuse across different contexts. Function types are written as (Args) -> ReturnType, supporting nullable r...
How do you define a function type in Kotlin?
Function types specify signature and return type: (Int, String) -> Boolean. Nullable variants add '?': (() -> Unit)?. Suspend functions include 'suspend' modifier: suspend () -> Unit. These types allow storing lambdas in variables, passing callbacks, and creating flexible APIs adaptable to various implementations witho...
What is SAM conversion in Kotlin?
SAM (Single Abstract Method) conversion allows passing Kotlin lambdas wherever Java expects a functional interface (interface with one abstract method). The compiler wraps the lambda in an anonymous class implementing the interface. This facilitates seamless integration with legacy Java libraries requiring listeners/ca...
Explain infix notation in Kotlin.
Infix functions omit parentheses and dots for natural language readability. Declared with 'infix' keyword, they must have exactly one parameter. Example: '1 shl 2' instead of '1.shl(2)'. Common in DSLs (Domain Specific Languages) for building expressive configurations or mathematical expressions, enhancing code fluency...
What are operator overloads in Kotlin?
Kotlin allows defining behavior for standard operators (+, -, *, /, [], etc.) via named functions (plus, minus, times, div, get, set). This enables intuitive usage of custom types, e.g., adding vectors or indexing matrices. Operators must follow semantic consistency to maintain code predictability and readability.
How does Kotlin support DSLs (Domain Specific Languages)?
DSLs leverage type-safe builders, infix functions, and receiver scopes to create mini-languages within Kotlin. Gradle build scripts and Anko UI layouts are examples. By structuring code hierarchically with lambdas having receivers, DSLs offer concise, readable descriptions of complex structures (HTML, SQL, UI trees) wh...
What is the difference between listOf and mutableListOf?
listOf returns a read-only List interface backed by an immutable ArrayList (or empty list optimization). Modifications throw UnsupportedOperationException. mutableListOf returns a MutableList allowing adds/removes. Choose listOf for data integrity and API contracts; use mutableListOf only when dynamic modification is r...
Explain sequence vs iterable in Kotlin.
Iterables process elements eagerly, loading all into memory before transformation. Sequences operate lazily, processing items one-by-one as requested. For large datasets or infinite streams, sequences prevent OutOfMemoryErrors and improve efficiency by short-circuiting operations. Use sequences for chain-heavy transfor...
What is flatMap in Kotlin collections?
flatMap transforms each element into a collection and merges results into a single flattened list. Equivalent to map followed by flatten. Useful for expanding nested structures, e.g., converting List<Order> to List<Item> by extracting items from each order. Reduces nesting depth and simplifies downstream processing.
How do groupBy functions work in Kotlin?
groupBy categorizes elements based on a selector key, producing a Map<Key, List<Value>>. Example: people.groupBy { it.department }. Efficient for aggregating data by attributes without manual loop accumulation. Supports optional value transform for mapping grouped items simultaneously.
What is associateBy in Kotlin?
associateBy creates a Map from a collection using a key selector and optional value transformer. Unlike grouping, it assumes unique keys; duplicates overwrite previous entries. Ideal for quick lookups or deduplication scenarios where last-writer-wins semantics suffice. Provides O(1) access post-construction.
Explain partition in Kotlin collections.
partition splits a collection into two lists based on a predicate: Pair<List<T>, List<T>>. First list contains matches; second contains non-matches. Avoids multiple passes or temporary buffers. Useful for separating valid/invalid inputs or filtering subsets while retaining rejected items for logging/error reporting.
What is zipWithNext in Kotlin?
zipWithNext pairs adjacent elements: (a,b), (b,c)... Producing List<Pair<T,T>>. Handy for detecting transitions, calculating deltas between consecutive metrics, or validating sequential dependencies without index arithmetic. Simplifies sliding window analyses elegantly.
How does chunked work in Kotlin?
chunked divides a collection into fixed-size batches (lists). Last chunk may be smaller. Useful for batching API requests, DB inserts, or parallel processing limits. Prevents overwhelming systems with massive payloads while maintaining order and completeness.
What is windowed in Kotlin?
windowed creates sliding windows over a collection with configurable size, step, and partial window inclusion. Returns List<List<T>>. Essential for moving averages, trend detection, or n-gram generation. Offers precise control over overlap and boundary conditions compared to simple slicing.
Explain scanReduce in Kotlin.
scanReduce accumulates intermediate results alongside final reduction. Instead of just summing numbers, it yields running totals: [1, 3, 6...] for input [1,2,3]. Combines fold/map benefits, useful for tracking progress, cumulative stats, or generating prefix sums efficiently in stream processing.
What is forEachIndexed in Kotlin?
forEachIndexed iterates with both element and position index available in lambda. Eliminates manual counter increments. Cleaner than traditional for-loops when index context matters (e.g., labeling rows, alternating styles). Maintains functional purity while accessing positional metadata.
How do you sort collections in Kotlin?
Use sorted() for natural ordering or sortedBy/sortedDescendingBy for custom comparators. sortBy modifies in-place for mutable lists. Stable sorts guarantee equal elements retain relative order. Comparator chains allow multi-field sorting (e.g., lastName then firstName). Leverages TimSort algorithm internally for optima...
What is distinctBy in Kotlin?
distinctBy removes duplicates based on projected keys rather than full object equality. Example: users.distinctBy { it.email }. Keeps first occurrence per unique email. More efficient than hash-set deduplication when comparing expensive objects or subset fields. Preserves original order.
Explain intersect and subtract in Kotlin sets.
intersect computes common elements between sets (A ∩ B). subtract removes elements present in another set (A - B). Both return new Sets without modifying originals. Critical for permission checks, blacklist filtering, or computing differences in inventory/data sync operations.
What is union in Kotlin sets?
union combines all unique elements from multiple sets (A ∪ B). Duplicates removed automatically. Returns new Set. Useful for merging contact lists, tag clouds, or aggregating disjoint datasets into comprehensive views without redundancy.
How do you convert arrays to lists in Kotlin?
Use toList() for shallow copy or asList() for view-backed wrapper. toMutableList() creates modifiable copy. Be cautious with primitive arrays (IntArray); boxing occurs during conversion unless specialized methods used. Prefer Lists for general-purpose collections due to richer API support.
What is arrayOfNulls in Kotlin?
Creates array filled with null references of specified size/type. Useful when preallocating storage for later population. Type inference requires explicit generic declaration (Array<String?>). Not commonly needed thanks to dynamic collections but valuable in low-memory/performance-sensitive contexts.
Explain byteOrder in Kotlin IO.
ByteOrder determines endianness when reading/writing binary data. BIG_ENDIAN stores MSB first; LITTLE_ENDIAN LSB first. Must match sender/receiver expectations. Incorrect assumption corrupts integers/floating points. Explicit specification avoids ambiguity especially in cross-platform/network communications.
How does BufferedReader improve performance?
Wraps Reader with internal buffer minimizing syscall overhead per character read. Reads chunks into memory, serving subsequent requests locally. Dramatically faster than direct FileReader for large texts. Always close properly or use try-with-resources/auto-closeable patterns to release handles.
What is PrintWriter convenience?
Extends Writer with formatted output methods (printf, println) and auto-flush options. Simplifies console/file logging without managing StringBuilder manually. Locale-aware formatting supported. AutoFlush triggers newline emission ensuring timely visibility in logs/debuggers.
Explain File.walkTopDown in Kotlin.
Recursively traverses directory tree yielding Files/LazySequence. Depth-first search pattern. Stops early if condition met (find). Memory-efficient iterator model vs collecting entire path list upfront. Ideal for searching files, counting extensions, or migrating folder structures safely.
What is Path.resolveSibling?
Constructs sibling path replacing filename portion while keeping parent directory intact. E.g., '/home/user/doc.txt'.resolveSibling('backup.txt') → '/home/user/backup.txt'. Safer than string manipulation for renaming/moving files within same directory structure respecting OS separators.
How do you serialize objects in Kotlin?
Use kotlinx.serialization plugin with @Serializable annotation. Generates serializers automatically handling JSON/XML/etc. Supports polymorphism, defaults, and transient fields. Compile-time validation catches mismatches. Alternative: Gson/Jackson via reflection but slower startup/runtime cost. Native solution preferre...
What is @Transient in serialization?
Marks field excluded from serialized output/input. Used for sensitive data (passwords), computed caches, or runtime-only states. Deserializer ignores missing tagged fields applying default/null values appropriately. Ensures privacy/security compliance without breaking schema compatibility.
Explain Context Receivers proposal status?
Experimental feature allowing implicit availability of outer scopes within inner lambdas/functions. Currently behind compiler flag (-Xcontext-receivers). Solves deeply nested closure problems in DSLs/coroutines. Stability pending feedback; expect breaking changes before GA adoption. Powerful yet risky for production st...
What are Value Classes in Kotlin?
Inline classes wrapping single values without allocation overhead at runtime (mostly). Provide type safety distinguishing semantically similar primitives (UserId vs OrderId). Zero-cost abstraction when JIT optimizes away boxing. Limited capabilities (no init blocks/interfaces initially) evolving towards richer features...
How do Unsigned Types work?
UInt/ULong wrappers enforcing non-negative constraints mathematically. Arithmetic ops respect unsigned boundaries preventing negative surprises. Binary representation identical to signed longs but interpreted differently. Useful for bitfields/hardware registers where sign bits meaningless. Requires explicit conversions...
Explain Duration API improvements?
Standardized time intervals (seconds/nanoseconds) replacing ad-hoc millis/integers. Human-readable construction (1.seconds + 500.milliseconds). Precision preserved across calculations. Integrates seamlessly with coroutines delay/timeouts. Reduces unit confusion errors prevalent in legacy timing codes.
What is Clock interface usage?
Abstraction over time sources enabling testability/injectable fake clocks. RealSystemClock uses system time; TestClock advances manually triggering scheduled events deterministically. Decouples business logic from wall-clock dependency facilitating reliable asynchronous testing simulations.
How do Flow collectors differ from Channels?
Flows represent cold streams recomputed per collector subscription emphasizing reactive/backpressure semantics. Channels are hot queues buffering emissions independently of consumers suited producer-consumer decoupling. Flows favor transformation pipelines; Channels excel at concurrent worker distribution models.
Explain ShareIn operator in Flows?
Converts cold Flow into hot SharedFlow multicast among subscribers. Optional replay cache retains recent emissions late joiners receive instantly. BufferOverflow strategies manage slow consumer impacts. Enables broadcasting server pushes/UI updates efficiently sharing single upstream computation resource.
What is StateFlow versus LiveData?
StateFlow holds current value emitting updates reactively coroutine-native alternative Android Architecture Components LiveData. Lifecycle awareness added externally via collectLatest+lifecycleOwner binding. Pure JVM friendly unlike LiveData tied MainLooper assumptions. Modern stack migration trend favors unifying asyn...
How do Supervised Jobs behave?
Parent coroutine cancels children upon failure/completion ensuring cleanup cascades downward. Children failing propagate upward cancelling siblings too depending scope definition. Structured concurrency guarantees no orphaned tasks lingering consuming CPU/memory indefinitely post-main-work termination.
Explain CoroutineDispatcher.IO significance?
Offloads blocking I/O operations (disk/network/db) off main/UI threads preventing ANRs/jank. Utilizes pooled threads sized dynamically based core count/load balancing demands. Non-CPU intensive workloads benefit greatly avoiding scheduler starvation impacting responsive interactions elsewhere.
What happens if you block inside suspend fun?
Blocking calls defeat coroutine purposes hogging dispatch threads starving others awaiting scheduling slots. Leads degraded throughput increased latency potential deadlocks if pool exhausted. Replace Thread.sleep/File.readSync with delay()/async{} wrappers utilizing suspension mechanics correctly preserving responsiven...
How do Mutex locks compare synchronized?
Mutex suspends caller gracefully releasing thread resources during wait periods unlike synchronized monopolizing OS threads busy-spinning/waiting inefficiently. Compatible exclusively within coroutine contexts avoiding mixing pitfalls causing unpredictable contention behaviors across mixed threading models improperly c...
Что такое Jetpack Compose?
Jetpack Compose — это современный инструментарий для создания нативных пользовательских интерфейсов в Android. Он использует декларативный подход, позволяя описывать UI как функцию состояния. В отличие от традиционного императивного подхода с XML, Compose автоматически обновляет экран при изменении данных, что упрощает...
End of preview.

Description This dataset is intended for Everything.

Important note: This dataset will be regularly updated and expanded. We plan to add new data as it becomes available.

License & Terms of Use This dataset is distributed under the Business Source License 1.1 (BUSL-1.1) with an Additional Use Grant.

Summary of terms:

Non-commercial use: Permitted without restrictions (research, education, personal projects).

Commercial use: Permitted only for organizations or individuals whose total Annual Revenue (including affiliates) for the most recent fiscal year does not exceed $50,000 USD.

If your revenue exceeds $50,000: A separate commercial license is required to use this dataset for commercial purposes. Contact us at: vnillix.nil@gmail.com.

Disclaimer The dataset is provided "as is". We are not liable for any consequences of its use. Please ensure your use complies with the license terms.

Downloads last month
122