function_name stringlengths 1 57 | function_code stringlengths 20 4.99k | documentation stringlengths 50 2k | language stringclasses 5
values | file_path stringlengths 8 166 | line_number int32 4 16.7k | parameters listlengths 0 20 | return_type stringlengths 0 131 | has_type_hints bool 2
classes | complexity int32 1 51 | quality_score float32 6 9.68 | repo_name stringclasses 34
values | repo_stars int32 2.9k 242k | docstring_style stringclasses 7
values | is_async bool 2
classes |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
visitContinueStatement | function visitContinueStatement(node: ContinueStatement): Statement {
if (inStatementContainingYield) {
const label = findContinueTarget(node.label && idText(node.label));
if (label > 0) {
return createInlineBreak(label, /*location*/ node);
}
}
... | Visits an ElementAccessExpression that contains a YieldExpression.
@param node The node to visit. | typescript | src/compiler/transformers/generators.ts | 1,753 | [
"node"
] | true | 4 | 6.08 | microsoft/TypeScript | 107,154 | jsdoc | false | |
_base_dir | def _base_dir(self) -> Path:
"""Get the base directory for cache storage.
Returns:
Path to the cache directory based on the default cache dir
and the specified subdirectory.
"""
from torch._inductor.runtime.runtime_utils import default_cache_dir
return P... | Get the base directory for cache storage.
Returns:
Path to the cache directory based on the default cache dir
and the specified subdirectory. | python | torch/_inductor/runtime/caching/implementations.py | 200 | [
"self"
] | Path | true | 1 | 6.56 | pytorch/pytorch | 96,034 | unknown | false |
random | function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
... | Produces a random number between the inclusive `lower` and `upper` bounds.
If only one argument is provided a number between `0` and the given number
is returned. If `floating` is `true`, or either `lower` or `upper` are
floats, a floating-point number is returned instead of an integer.
**Note:** JavaScript follows the... | javascript | lodash.js | 14,185 | [
"lower",
"upper",
"floating"
] | false | 17 | 6.32 | lodash/lodash | 61,490 | jsdoc | false | |
voidSuccess | public static RequestFuture<Void> voidSuccess() {
RequestFuture<Void> future = new RequestFuture<>();
future.complete(null);
return future;
} | Convert from a request future of one type to another type
@param adapter The adapter which does the conversion
@param <S> The type of the future adapted to
@return The new future | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestFuture.java | 237 | [] | true | 1 | 6.4 | apache/kafka | 31,560 | javadoc | false | |
printSubCommandList | private void printSubCommandList(Consumer<String> println) {
if (subcommands.isEmpty()) {
throw new IllegalStateException("No subcommands configured");
}
println.accept("Commands");
println.accept("--------");
for (Map.Entry<String, Command> subcommand : subcommands.e... | Construct the multi-command with the specified command description and runnable to execute before main is invoked.
@param description the multi-command description | java | libs/cli/src/main/java/org/elasticsearch/cli/MultiCommand.java | 61 | [
"println"
] | void | true | 2 | 6.4 | elastic/elasticsearch | 75,680 | javadoc | false |
checkByteSize | private static void checkByteSize(MemorySegment a, MemorySegment b) {
if (a.byteSize() != b.byteSize()) {
throw new IllegalArgumentException("dimensions differ: " + a.byteSize() + "!=" + b.byteSize());
}
} | Computes the square distance of given float32 vectors.
@param a address of the first vector
@param b address of the second vector
@param elementCount the vector dimensions, number of float32 elements in the segment | java | libs/native/src/main/java/org/elasticsearch/nativeaccess/jdk/JdkVectorLibrary.java | 285 | [
"a",
"b"
] | void | true | 2 | 6.56 | elastic/elasticsearch | 75,680 | javadoc | false |
terminate_job | def terminate_job(self, jobId: str, reason: str) -> dict:
"""
Terminate a Batch job.
:param jobId: a job ID to terminate
:param reason: a reason to terminate job ID
:return: an API response
"""
... | Terminate a Batch job.
:param jobId: a job ID to terminate
:param reason: a reason to terminate job ID
:return: an API response | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/batch_client.py | 134 | [
"self",
"jobId",
"reason"
] | dict | true | 1 | 6.72 | apache/airflow | 43,597 | sphinx | false |
convert_json_field_to_pandas_type | def convert_json_field_to_pandas_type(field) -> str | CategoricalDtype:
"""
Converts a JSON field descriptor into its corresponding NumPy / pandas type
Parameters
----------
field
A JSON field descriptor
Returns
-------
dtype
Raises
------
ValueError
If the... | Converts a JSON field descriptor into its corresponding NumPy / pandas type
Parameters
----------
field
A JSON field descriptor
Returns
-------
dtype
Raises
------
ValueError
If the type of the provided field is unknown or currently unsupported
Examples
--------
>>> convert_json_field_to_pandas_type({"name"... | python | pandas/io/json/_table_schema.py | 157 | [
"field"
] | str | CategoricalDtype | true | 15 | 6.24 | pandas-dev/pandas | 47,362 | numpy | false |
indexOf | public static int indexOf(final float[] array, final float valueToFind, final int startIndex) {
if (isEmpty(array)) {
return INDEX_NOT_FOUND;
}
final boolean searchNaN = Float.isNaN(valueToFind);
for (int i = max0(startIndex); i < array.length; i++) {
final float ... | Finds the index of the given value in the array starting at the given index.
<p>
This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
</p>
<p>
A negative startIndex is treated as zero. A startIndex larger than the array length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
</p>
... | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 2,597 | [
"array",
"valueToFind",
"startIndex"
] | true | 6 | 8.08 | apache/commons-lang | 2,896 | javadoc | false | |
headerNameToString | function headerNameToString (value) {
return typeof value === 'string'
? headerNameLowerCasedRecord[value] ?? value.toLowerCase()
: tree.lookup(value) ?? value.toString('latin1').toLowerCase()
} | Retrieves a header name and returns its lowercase value.
@param {string | Buffer} value Header name
@returns {string} | javascript | deps/undici/src/lib/core/util.js | 400 | [
"value"
] | false | 2 | 6.24 | nodejs/node | 114,839 | jsdoc | false | |
visitFunctionDeclaration | function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
let parameters: NodeArray<ParameterDeclaration>;
const savedLexicalArgumentsBinding = lexicalArgumentsBinding;
lexicalArgumentsBinding = undefined;
const functionFlags = getFunctionFlags(node);
... | Visits a FunctionDeclaration node.
This function will be called when one of the following conditions are met:
- The node is marked async
@param node The node to visit. | typescript | src/compiler/transformers/es2017.ts | 493 | [
"node"
] | true | 3 | 6.88 | microsoft/TypeScript | 107,154 | jsdoc | false | |
reconstructErrorStack | function reconstructErrorStack(err, parentPath, parentSource) {
const errLine = StringPrototypeSplit(
StringPrototypeSlice(err.stack, StringPrototypeIndexOf(
err.stack, ' at ')), '\n', 1)[0];
const { 1: line, 2: col } =
RegExpPrototypeExec(/(\d+):(\d+)\)/, errLine) || [];
if (line && col) {
c... | Get the source code of a module, using cached ones if it's cached. This is used
for TypeScript, JavaScript and JSON loading.
After this returns, mod[kFormat], mod[kModuleSource] and mod[kURL] will be set.
@param {Module} mod Module instance whose source is potentially already cached.
@param {string} filename Absolute p... | javascript | lib/internal/modules/cjs/loader.js | 1,804 | [
"err",
"parentPath",
"parentSource"
] | false | 4 | 6.08 | nodejs/node | 114,839 | jsdoc | false | |
createSegment | Segment<K, V> createSegment(
int initialCapacity, long maxSegmentWeight, StatsCounter statsCounter) {
return new Segment<>(this, initialCapacity, maxSegmentWeight, statsCounter);
} | Returns the segment that should be used for a key with the given hash.
@param hash the hash code for the key
@return the segment | java | android/guava/src/com/google/common/cache/LocalCache.java | 1,760 | [
"initialCapacity",
"maxSegmentWeight",
"statsCounter"
] | true | 1 | 6.64 | google/guava | 51,352 | javadoc | false | |
vector_norm | def vector_norm(x, /, *, axis=None, keepdims=False, ord=2):
"""
Computes the vector norm of a vector (or batch of vectors) ``x``.
This function is Array API compatible.
Parameters
----------
x : array_like
Input array.
axis : {None, int, 2-tuple of ints}, optional
If an int... | Computes the vector norm of a vector (or batch of vectors) ``x``.
This function is Array API compatible.
Parameters
----------
x : array_like
Input array.
axis : {None, int, 2-tuple of ints}, optional
If an integer, ``axis`` specifies the axis (dimension) along which
to compute vector norms. If an n-tuple... | python | numpy/linalg/_linalg.py | 3,503 | [
"x",
"axis",
"keepdims",
"ord"
] | false | 7 | 7.76 | numpy/numpy | 31,054 | numpy | false | |
read | @Override
public int read(ByteBuffer dst, long pos) throws IOException {
if (pos < 0 || pos >= this.size) {
return -1;
}
int lastReadPart = this.lastReadPart;
int partIndex = 0;
long offset = 0;
int result = 0;
if (pos >= this.offsets[lastReadPart]) {
partIndex = lastReadPart;
offset = this.offs... | Set the parts that make up the virtual data block.
@param parts the data block parts
@throws IOException on I/O error | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/VirtualDataBlock.java | 78 | [
"dst",
"pos"
] | true | 9 | 7.04 | spring-projects/spring-boot | 79,428 | javadoc | false | |
writeToString | default String writeToString(@Nullable T instance) {
return write(instance).toJsonString();
} | Write the given instance to a JSON string.
@param instance the instance to write (may be {@code null})
@return the JSON string | java | core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java | 95 | [
"instance"
] | String | true | 1 | 6.64 | spring-projects/spring-boot | 79,428 | javadoc | false |
getSignature | @Override
public Signature getSignature() {
if (this.signature == null) {
this.signature = new MethodSignatureImpl();
}
return this.signature;
} | Returns the Spring AOP target. May be {@code null} if there is no target. | java | spring-aop/src/main/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPoint.java | 122 | [] | Signature | true | 2 | 6.72 | spring-projects/spring-framework | 59,386 | javadoc | false |
detectIfAnsiCapable | private static boolean detectIfAnsiCapable() {
try {
if (Boolean.FALSE.equals(consoleAvailable)) {
return false;
}
if (consoleAvailable == null) {
Console console = System.console();
if (console == null) {
return false;
}
Method isTerminalMethod = ClassUtils.getMethodIfAvailable(Cons... | Create a new ANSI string from the specified elements. Any {@link AnsiElement}s will
be encoded as required.
@param elements the elements to encode
@return a string of the encoded elements | java | core/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiOutput.java | 156 | [] | true | 7 | 7.76 | spring-projects/spring-boot | 79,428 | javadoc | false | |
freshTarget | protected abstract Object freshTarget(); | Obtain a fresh target object.
<p>Only invoked if a refresh check has found that a refresh is required
(that is, {@link #requiresRefresh()} has returned {@code true}).
@return the fresh target object | java | spring-aop/src/main/java/org/springframework/aop/target/dynamic/AbstractRefreshableTargetSource.java | 143 | [] | Object | true | 1 | 6.48 | spring-projects/spring-framework | 59,386 | javadoc | false |
close | @Override
public void close() {
if (resultAlreadyReturned == false) {
Releasables.close(result);
}
} | Sets the given bucket of the negative buckets. If the bucket already exists, it will be replaced.
Buckets may be set in arbitrary order. However, for best performance and minimal allocations,
buckets should be set in order of increasing index and all negative buckets should be set before positive buckets.
@param index ... | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramBuilder.java | 283 | [] | void | true | 2 | 8.24 | elastic/elasticsearch | 75,680 | javadoc | false |
empty | def empty(self) -> bool:
"""
Indicator whether Series/DataFrame is empty.
True if Series/DataFrame is entirely empty (no items), meaning any of the
axes are of length 0.
Returns
-------
bool
If Series/DataFrame is empty, return True, if not return Fa... | Indicator whether Series/DataFrame is empty.
True if Series/DataFrame is entirely empty (no items), meaning any of the
axes are of length 0.
Returns
-------
bool
If Series/DataFrame is empty, return True, if not return False.
See Also
--------
Series.dropna : Return series without null values.
DataFrame.dropna :... | python | pandas/core/generic.py | 1,964 | [
"self"
] | bool | true | 1 | 7.28 | pandas-dev/pandas | 47,362 | unknown | false |
throttleDelayMs | public long throttleDelayMs(Node node, long now) {
return connectionStates.throttleDelayMs(node.idString(), now);
} | Returns the number of milliseconds to wait, based on the connection state, before attempting to send data. When
disconnected, this respects the reconnect backoff time. When connecting or connected, this handles slow/stalled
connections.
@param node The node to check
@param now The current timestamp
@return The number o... | java | clients/src/main/java/org/apache/kafka/clients/NetworkClient.java | 471 | [
"node",
"now"
] | true | 1 | 6.96 | apache/kafka | 31,560 | javadoc | false | |
items | public ConditionMessage items(@Nullable Collection<?> items) {
return items(Style.NORMAL, items);
} | Indicate the items. For example
{@code didNotFind("bean", "beans").items(Collections.singleton("x")} results in
the message "did not find bean x".
@param items the source of the items (may be {@code null})
@return a built {@link ConditionMessage} | java | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java | 371 | [
"items"
] | ConditionMessage | true | 1 | 6.32 | spring-projects/spring-boot | 79,428 | javadoc | false |
scheduleCleanUp | function scheduleCleanUp() {
if (cleanUpIsScheduled === false && size > LIMIT) {
// The cache size exceeds the limit. Schedule a callback to delete the
// least recently used entries.
cleanUpIsScheduled = true;
scheduleCallback(IdlePriority, cleanUp);
}
} | Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@flow | javascript | packages/react-cache/src/LRU.js | 42 | [] | false | 3 | 6.4 | facebook/react | 241,750 | jsdoc | false | |
_critical_section_enqueue_task_instances | def _critical_section_enqueue_task_instances(self, session: Session) -> int:
"""
Enqueues TaskInstances for execution.
There are three steps:
1. Pick TIs by priority with the constraint that they are in the expected states
and that we do not exceed max_active_runs or pool limits... | Enqueues TaskInstances for execution.
There are three steps:
1. Pick TIs by priority with the constraint that they are in the expected states
and that we do not exceed max_active_runs or pool limits.
2. Change the state for the TIs above atomically.
3. Enqueue the TIs in the executor.
HA note: This function is a "cri... | python | airflow-core/src/airflow/jobs/scheduler_job_runner.py | 826 | [
"self",
"session"
] | int | true | 5 | 8.24 | apache/airflow | 43,597 | sphinx | false |
getArrayComponentType | public static Type getArrayComponentType(final Type type) {
if (type instanceof Class<?>) {
final Class<?> cls = (Class<?>) type;
return cls.isArray() ? cls.getComponentType() : null;
}
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).g... | Gets the array component type of {@code type}.
@param type the type to be checked.
@return component type or null if type is not an array type. | java | src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java | 593 | [
"type"
] | Type | true | 4 | 8.08 | apache/commons-lang | 2,896 | javadoc | false |
endsWith | public boolean endsWith(final String str) {
if (str == null) {
return false;
}
final int len = str.length();
if (len == 0) {
return true;
}
if (len > size) {
return false;
}
int pos = size - len;
for (int i = 0; ... | Checks whether this builder ends with the specified string.
<p>
Note that this method handles null input quietly, unlike String.
</p>
@param str the string to search for, null returns false
@return true if the builder ends with the string | java | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | 1,815 | [
"str"
] | true | 6 | 8.08 | apache/commons-lang | 2,896 | javadoc | false | |
arraycopy | public static <T> T arraycopy(final T source, final int sourcePos, final int destPos, final int length, final Function<Integer, T> allocator) {
return arraycopy(source, sourcePos, allocator.apply(length), destPos, length);
} | A fluent version of {@link System#arraycopy(Object, int, Object, int, int)} that returns the destination array.
@param <T> the type.
@param source the source array.
@param sourcePos starting position in the source array.
@param destPos starting position in the destination data.
@param length the number of... | java | src/main/java/org/apache/commons/lang3/ArrayUtils.java | 1,399 | [
"source",
"sourcePos",
"destPos",
"length",
"allocator"
] | T | true | 1 | 6.64 | apache/commons-lang | 2,896 | javadoc | false |
maximumSize | @CanIgnoreReturnValue
public CacheBuilder<K, V> maximumSize(long maximumSize) {
checkState(
this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize);
checkState(
this.maximumWeight == UNSET_INT,
"maximum weight was already set to %s",
this.maximumW... | Specifies the maximum number of entries the cache may contain.
<p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in
the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each
resulting segment inside the cache <i>independently</i> limits its own ... | java | android/guava/src/com/google/common/cache/CacheBuilder.java | 494 | [
"maximumSize"
] | true | 1 | 6.56 | google/guava | 51,352 | javadoc | false | |
skip_if_no | def skip_if_no(package: str, min_version: str | None = None) -> pytest.MarkDecorator:
"""
Generic function to help skip tests when required packages are not
present on the testing system.
This function returns a pytest mark with a skip condition that will be
evaluated during test collection. An att... | Generic function to help skip tests when required packages are not
present on the testing system.
This function returns a pytest mark with a skip condition that will be
evaluated during test collection. An attempt will be made to import the
specified ``package`` and optionally ensure it meets the ``min_version``
The ... | python | pandas/util/_test_decorators.py | 67 | [
"package",
"min_version"
] | pytest.MarkDecorator | true | 2 | 6.72 | pandas-dev/pandas | 47,362 | numpy | false |
toInt | public static int toInt(final String str, final int defaultValue) {
try {
return Integer.parseInt(str);
} catch (final RuntimeException e) {
return defaultValue;
}
} | Converts a {@link String} to an {@code int}, returning a default value if the conversion fails.
<p>
If the string is {@code null}, the default value is returned.
</p>
<pre>
NumberUtils.toInt(null, 1) = 1
NumberUtils.toInt("", 1) = 1
NumberUtils.toInt("1", 0) = 1
</pre>
@param str the string to convert... | java | src/main/java/org/apache/commons/lang3/math/NumberUtils.java | 1,562 | [
"str",
"defaultValue"
] | true | 2 | 8.08 | apache/commons-lang | 2,896 | javadoc | false | |
asMapOfRanges | @Override
public ImmutableMap<Range<K>, V> asMapOfRanges() {
if (ranges.isEmpty()) {
return ImmutableMap.of();
}
RegularImmutableSortedSet<Range<K>> rangeSet =
new RegularImmutableSortedSet<>(ranges, rangeLexOrdering());
return new ImmutableSortedMap<>(rangeSet, values);
} | Guaranteed to throw an exception and leave the {@code RangeMap} unmodified.
@throws UnsupportedOperationException always
@deprecated Unsupported operation.
@since 28.1 | java | guava/src/com/google/common/collect/ImmutableRangeMap.java | 308 | [] | true | 2 | 6.08 | google/guava | 51,352 | javadoc | false | |
sensor | public synchronized Sensor sensor(String name, MetricConfig config, long inactiveSensorExpirationTimeSeconds, Sensor... parents) {
return this.sensor(name, config, inactiveSensorExpirationTimeSeconds, Sensor.RecordingLevel.INFO, parents);
} | Get or create a sensor with the given unique name and zero or more parent sensors. All parent sensors will
receive every value recorded with this sensor. This uses a default recording level of INFO.
@param name The name of the sensor
@param config A default configuration to use for this sensor for metrics that don't ha... | java | clients/src/main/java/org/apache/kafka/common/metrics/Metrics.java | 427 | [
"name",
"config",
"inactiveSensorExpirationTimeSeconds"
] | Sensor | true | 1 | 6.48 | apache/kafka | 31,560 | javadoc | false |
permission_denied | def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
"""
Permission denied (403) handler.
Templates: :template:`403.html`
Context:
exception
The message from the exception which triggered the 403 (if one was
supplied).
If the template do... | Permission denied (403) handler.
Templates: :template:`403.html`
Context:
exception
The message from the exception which triggered the 403 (if one was
supplied).
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 9110 Section 15.5.4) will be returne... | python | django/views/defaults.py | 126 | [
"request",
"exception",
"template_name"
] | false | 2 | 6.24 | django/django | 86,204 | unknown | false | |
is_busday | def is_busday(dates, weekmask="1111100", holidays=None, busdaycal=None, out=None):
"""
is_busday(
dates,
weekmask='1111100',
holidays=None,
busdaycal=None,
out=None,
)
Calculates which of the given dates are valid days, and which are not.
Parameters
----... | is_busday(
dates,
weekmask='1111100',
holidays=None,
busdaycal=None,
out=None,
)
Calculates which of the given dates are valid days, and which are not.
Parameters
----------
dates : array_like of datetime64[D]
The array of dates to process.
weekmask : str or array_like of bool, optional
A ... | python | numpy/_core/multiarray.py | 1,440 | [
"dates",
"weekmask",
"holidays",
"busdaycal",
"out"
] | false | 1 | 6.24 | numpy/numpy | 31,054 | numpy | false | |
create | @Contract("_, _, !null -> !null")
private static @Nullable ConfigurationPropertiesBean create(String name, @Nullable Object instance,
@Nullable Bindable<Object> bindTarget) {
return (bindTarget != null) ? new ConfigurationPropertiesBean(name, instance, bindTarget) : null;
} | Return a {@link ConfigurationPropertiesBean @ConfigurationPropertiesBean} instance
for the given bean details or {@code null} if the bean is not a
{@link ConfigurationProperties @ConfigurationProperties} object. Annotations are
considered both on the bean itself, as well as any factory method (for example a
{@link Bean... | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java | 289 | [
"name",
"instance",
"bindTarget"
] | ConfigurationPropertiesBean | true | 2 | 7.28 | spring-projects/spring-boot | 79,428 | javadoc | false |
add_template_filter | def add_template_filter(
self, f: ft.TemplateFilterCallable, name: str | None = None
) -> None:
"""Register a function to use as a custom Jinja filter.
The :meth:`template_filter` decorator can be used to register a function
by decorating instead.
:param f: The function to ... | Register a function to use as a custom Jinja filter.
The :meth:`template_filter` decorator can be used to register a function
by decorating instead.
:param f: The function to register.
:param name: The name to register the filter as. If not given, uses the
function's name. | python | src/flask/sansio/app.py | 696 | [
"self",
"f",
"name"
] | None | true | 2 | 6.88 | pallets/flask | 70,946 | sphinx | false |
clear_data_home | def clear_data_home(data_home=None):
"""Delete all the content of the data home cache.
Parameters
----------
data_home : str or path-like, default=None
The path to scikit-learn data directory. If `None`, the default path
is `~/scikit_learn_data`.
Examples
--------
>>> from ... | Delete all the content of the data home cache.
Parameters
----------
data_home : str or path-like, default=None
The path to scikit-learn data directory. If `None`, the default path
is `~/scikit_learn_data`.
Examples
--------
>>> from sklearn.datasets import clear_data_home
>>> clear_data_home() # doctest: +S... | python | sklearn/datasets/_base.py | 95 | [
"data_home"
] | false | 1 | 6 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
parse_oss_url | def parse_oss_url(ossurl: str) -> tuple:
"""
Parse the OSS Url into a bucket name and key.
:param ossurl: The OSS Url to parse.
:return: the parsed bucket name and key
"""
parsed_url = urlsplit(ossurl)
if not parsed_url.netloc:
raise AirflowException... | Parse the OSS Url into a bucket name and key.
:param ossurl: The OSS Url to parse.
:return: the parsed bucket name and key | python | providers/alibaba/src/airflow/providers/alibaba/cloud/hooks/oss.py | 98 | [
"ossurl"
] | tuple | true | 2 | 7.92 | apache/airflow | 43,597 | sphinx | false |
concat | public static boolean[] concat(boolean[]... arrays) {
long length = 0;
for (boolean[] array : arrays) {
length += array.length;
}
boolean[] result = new boolean[checkNoOverflow(length)];
int pos = 0;
for (boolean[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.lengt... | Returns the values from each provided array combined into a single array. For example, {@code
concat(new boolean[] {a, b}, new boolean[] {}, new boolean[] {c}} returns the array {@code {a,
b, c}}.
@param arrays zero or more {@code boolean} arrays
@return a single array containing all the values from the source arrays, ... | java | android/guava/src/com/google/common/primitives/Booleans.java | 236 | [] | true | 1 | 6.56 | google/guava | 51,352 | javadoc | false | |
create_url_adapter | def create_url_adapter(self, request: Request | None) -> MapAdapter | None:
"""Creates a URL adapter for the given request. The URL adapter
is created at a point where the request context is not yet set
up so the request is passed explicitly.
.. versionchanged:: 3.1
If :data... | Creates a URL adapter for the given request. The URL adapter
is created at a point where the request context is not yet set
up so the request is passed explicitly.
.. versionchanged:: 3.1
If :data:`SERVER_NAME` is set, it does not restrict requests to
only that domain, for both ``subdomain_matching`` and
`... | python | src/flask/app.py | 508 | [
"self",
"request"
] | MapAdapter | None | true | 7 | 6.88 | pallets/flask | 70,946 | unknown | false |
_update_ctx | def _update_ctx(self, attrs: DataFrame) -> None:
"""
Update the state of the ``Styler`` for data cells.
Collects a mapping of {index_label: [('<property>', '<value>'), ..]}.
Parameters
----------
attrs : DataFrame
should contain strings of '<property>: <valu... | Update the state of the ``Styler`` for data cells.
Collects a mapping of {index_label: [('<property>', '<value>'), ..]}.
Parameters
----------
attrs : DataFrame
should contain strings of '<property>: <value>;<prop2>: <val2>'
Whitespace shouldn't matter and the final trailing ';' shouldn't
matter. | python | pandas/io/formats/style.py | 1,672 | [
"self",
"attrs"
] | None | true | 7 | 6.4 | pandas-dev/pandas | 47,362 | numpy | false |
union | public static ClassFilter union(ClassFilter[] classFilters) {
Assert.notEmpty(classFilters, "ClassFilter array must not be empty");
return new UnionClassFilter(classFilters);
} | Match all classes that <i>either</i> (or all) of the given ClassFilters matches.
@param classFilters the ClassFilters to match
@return a distinct ClassFilter that matches all classes that either
of the given ClassFilter matches | java | spring-aop/src/main/java/org/springframework/aop/support/ClassFilters.java | 61 | [
"classFilters"
] | ClassFilter | true | 1 | 6.48 | spring-projects/spring-framework | 59,386 | javadoc | false |
_as_pairs | def _as_pairs(x, ndim, as_index=False):
"""
Broadcast `x` to an array with the shape (`ndim`, 2).
A helper function for `pad` that prepares and validates arguments like
`pad_width` for iteration in pairs.
Parameters
----------
x : {None, scalar, array-like}
The object to broadcast ... | Broadcast `x` to an array with the shape (`ndim`, 2).
A helper function for `pad` that prepares and validates arguments like
`pad_width` for iteration in pairs.
Parameters
----------
x : {None, scalar, array-like}
The object to broadcast to the shape (`ndim`, 2).
ndim : int
Number of pairs the broadcasted `x`... | python | numpy/lib/_arraypad_impl.py | 471 | [
"x",
"ndim",
"as_index"
] | false | 14 | 6.16 | numpy/numpy | 31,054 | numpy | false | |
ofNonNull | public static <L, R> ImmutablePair<L, R> ofNonNull(final L left, final R right) {
return of(Objects.requireNonNull(left, "left"), Objects.requireNonNull(right, "right"));
} | Creates an immutable pair of two non-null objects inferring the generic types.
@param <L> the left element type.
@param <R> the right element type.
@param left the left element, may not be null.
@param right the right element, may not be null.
@return an immutable formed from the two parameters, not null.
@throws Nu... | java | src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java | 133 | [
"left",
"right"
] | true | 1 | 6.8 | apache/commons-lang | 2,896 | javadoc | false | |
toBooleanObject | public static Boolean toBooleanObject(final Integer value) {
if (value == null) {
return null;
}
return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
} | Converts an Integer to a Boolean using the convention that {@code zero}
is {@code false}, every other numeric value is {@code true}.
<p>{@code null} will be converted to {@code null}.</p>
<p>NOTE: This method may return {@code null} and may throw a {@link NullPointerException}
if unboxed to a {@code boolean}.</p>
<pre>... | java | src/main/java/org/apache/commons/lang3/BooleanUtils.java | 644 | [
"value"
] | Boolean | true | 3 | 7.6 | apache/commons-lang | 2,896 | javadoc | false |
enqueue | void enqueue(Call call, long now) {
if (call.tries > maxRetries) {
log.debug("Max retries {} for {} reached", maxRetries, call);
call.handleTimeoutFailure(time.milliseconds(), new TimeoutException(
"Exceeded maxRetries after " + call.tries + " tries."));
... | Queue a call for sending.
<p>
If the AdminClient thread has exited, this will fail. Otherwise, it will succeed (even
if the AdminClient is shutting down). This function should called when retrying an
existing call.
@param call The new call object.
@param now The current time in milliseconds. | java | clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java | 1,550 | [
"call",
"now"
] | void | true | 5 | 6.88 | apache/kafka | 31,560 | javadoc | false |
get | static ImportPhase get(@Nullable ConfigDataActivationContext activationContext) {
if (activationContext != null && activationContext.getProfiles() != null) {
return AFTER_PROFILE_ACTIVATION;
}
return BEFORE_PROFILE_ACTIVATION;
} | Return the {@link ImportPhase} based on the given activation context.
@param activationContext the activation context
@return the import phase | java | core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java | 535 | [
"activationContext"
] | ImportPhase | true | 3 | 7.28 | spring-projects/spring-boot | 79,428 | javadoc | false |
values | Collection<V> values(); | Returns a collection of all values, which may contain duplicates. Changes to the returned
collection will update the underlying table, and vice versa.
@return collection of values | java | android/guava/src/com/google/common/collect/Table.java | 232 | [] | true | 1 | 6.64 | google/guava | 51,352 | javadoc | false | |
parseUnsignedLong | @CanIgnoreReturnValue
public static long parseUnsignedLong(String string, int radix) {
checkNotNull(string);
if (string.length() == 0) {
throw new NumberFormatException("empty string");
}
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("ill... | Returns the unsigned {@code long} value represented by a string with the given radix.
<p><b>Java 8+ users:</b> use {@link Long#parseUnsignedLong(String, int)} instead.
@param string the string containing the unsigned {@code long} representation to be parsed.
@param radix the radix to use while parsing {@code string}
@t... | java | android/guava/src/com/google/common/primitives/UnsignedLongs.java | 339 | [
"string",
"radix"
] | true | 8 | 6.4 | google/guava | 51,352 | javadoc | false | |
getNameWithoutExtension | public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
} | Returns the file name without its <a
href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
similar to the {@code basename} unix command. The result does not include the '{@code .}'.
@param file The name of the file to trim the extension from. This can be either a fully
qualified... | java | android/guava/src/com/google/common/io/Files.java | 812 | [
"file"
] | String | true | 2 | 8.08 | google/guava | 51,352 | javadoc | false |
collapseOverlappingBucketsForAll | public ZeroBucket collapseOverlappingBucketsForAll(BucketIterator... bucketIterators) {
ZeroBucket current = this;
ZeroBucket previous;
do {
previous = current;
for (BucketIterator buckets : bucketIterators) {
current = current.collapseOverlappingBuckets(b... | Collapses all buckets from the given iterators whose lower boundaries are smaller than the zero threshold.
The iterators are advanced to point at the first, non-collapsed bucket.
@param bucketIterators The iterators whose buckets may be collapsed.
@return A potentially updated {@link ZeroBucket} with the collapsed buck... | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ZeroBucket.java | 215 | [] | ZeroBucket | true | 1 | 6.24 | elastic/elasticsearch | 75,680 | javadoc | false |
rfind | def rfind(a, sub, start=0, end=None):
"""
For each element, return the highest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
... | For each element, return the highest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
... | python | numpy/_core/strings.py | 294 | [
"a",
"sub",
"start",
"end"
] | false | 2 | 7.36 | numpy/numpy | 31,054 | numpy | false | |
get_orm_mapper | def get_orm_mapper():
"""Get the correct ORM mapper for the installed SQLAlchemy version."""
import sqlalchemy.orm.mapper
return sqlalchemy.orm.mapper if is_sqlalchemy_v1() else sqlalchemy.orm.Mapper | Get the correct ORM mapper for the installed SQLAlchemy version. | python | airflow-core/src/airflow/utils/sqlalchemy.py | 471 | [] | false | 2 | 6.16 | apache/airflow | 43,597 | unknown | false | |
translateCellErrorOutput | function translateCellErrorOutput(output: NotebookCellOutput): nbformat.IError {
// it should have at least one output item
const firstItem = output.items[0];
// Bug in VS Code.
if (!firstItem.data) {
return {
output_type: 'error',
ename: '',
evalue: '',
traceback: []
};
}
const originalError: und... | Splits the source of a cell into an array of strings, each representing a line.
Also normalizes line endings to use LF (`\n`) instead of CRLF (`\r\n`).
Same is done in deserializer as well. | typescript | extensions/ipynb/src/serializers.ts | 266 | [
"output"
] | true | 5 | 6 | microsoft/vscode | 179,840 | jsdoc | false | |
toString | @Override
public String toString() {
StringBuilder sb = new StringBuilder("Acknowledgements(");
sb.append(acknowledgements);
sb.append(", acknowledgeException=");
sb.append(acknowledgeException != null ? Errors.forException(acknowledgeException) : "null");
sb.append(", comple... | @return Returns true if the array of acknowledge types in the share fetch batch contains a single acknowledge type
and the array size can be reduced to 1.
Returns false when the array has more than one acknowledge type or is already optimised. | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/Acknowledgements.java | 316 | [] | String | true | 2 | 8.24 | apache/kafka | 31,560 | javadoc | false |
toUnsentRequest | public NetworkClientDelegate.UnsentRequest toUnsentRequest() {
Map<String, Uuid> topicIds = metadata.topicIds();
boolean canUseTopicIds = true;
Map<String, OffsetCommitRequestData.OffsetCommitRequestTopic> requestTopicDataMap = new HashMap<>();
for (Map.Entry<TopicPartiti... | Future containing the offsets that were committed. It completes when a response is
received for the commit request. | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java | 711 | [] | true | 4 | 7.04 | apache/kafka | 31,560 | javadoc | false | |
isInfoEnabled | @Override
public boolean isInfoEnabled() {
synchronized (this.lines) {
return (this.destination == null) || this.destination.isInfoEnabled();
}
} | Create a new {@link DeferredLog} instance managed by a {@link DeferredLogFactory}.
@param destination the switch-over destination
@param lines the lines backing all related deferred logs
@since 2.4.0 | java | core/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java | 79 | [] | true | 2 | 6.4 | spring-projects/spring-boot | 79,428 | javadoc | false | |
withJsonResource | public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream) throws IOException {
return withJsonResource(inputStream, this.defaultCharset);
} | Add the content of a {@link ConfigurationMetadataRepository} defined by the
specified {@link InputStream} JSON document using the default charset. If this
metadata repository holds items that were loaded previously, these are ignored.
<p>
Leaves the stream open when done.
@param inputStream the source input stream
@ret... | java | configuration-metadata/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java | 56 | [
"inputStream"
] | ConfigurationMetadataRepositoryJsonBuilder | true | 1 | 6.64 | spring-projects/spring-boot | 79,428 | javadoc | false |
update | public synchronized void update(int requestVersion, MetadataResponse response, boolean isPartialUpdate, long nowMs) {
Objects.requireNonNull(response, "Metadata response cannot be null");
if (isClosed())
throw new IllegalStateException("Update requested after metadata close");
this.... | Updates the cluster metadata. If topic expiry is enabled, expiry time
is set for topics if required and expired topics are removed from the metadata.
@param requestVersion The request version corresponding to the update response, as provided by
{@link #newMetadataRequestAndVersion(long)}.
@param response metadata r... | java | clients/src/main/java/org/apache/kafka/clients/Metadata.java | 337 | [
"requestVersion",
"response",
"isPartialUpdate",
"nowMs"
] | void | true | 4 | 6.4 | apache/kafka | 31,560 | javadoc | false |
isConfigurationPropertiesBean | private static boolean isConfigurationPropertiesBean(ConfigurableListableBeanFactory beanFactory, String beanName) {
try {
if (beanFactory.getBeanDefinition(beanName).isAbstract()) {
return false;
}
if (beanFactory.findAnnotationOnBean(beanName, ConfigurationProperties.class) != null) {
return true;
... | Return all {@link ConfigurationProperties @ConfigurationProperties} beans contained
in the given application context. Both directly annotated beans, as well as beans
that have {@link ConfigurationProperties @ConfigurationProperties} annotated
factory methods are included.
@param applicationContext the source applicatio... | java | core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java | 174 | [
"beanFactory",
"beanName"
] | true | 4 | 7.28 | spring-projects/spring-boot | 79,428 | javadoc | false | |
in_interactive_session | def in_interactive_session() -> bool:
"""
Check if we're running in an interactive shell.
Returns
-------
bool
True if running under python/ipython interactive shell.
"""
from pandas import get_option
def check_main() -> bool:
try:
import __main__ as main
... | Check if we're running in an interactive shell.
Returns
-------
bool
True if running under python/ipython interactive shell. | python | pandas/io/formats/console.py | 55 | [] | bool | true | 3 | 6.88 | pandas-dev/pandas | 47,362 | unknown | false |
get_scorer | def get_scorer(scoring):
"""Get a scorer from string.
Read more in the :ref:`User Guide <scoring_parameter>`.
:func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names
of all available scorers.
Parameters
----------
scoring : str, callable or None
Scoring method a... | Get a scorer from string.
Read more in the :ref:`User Guide <scoring_parameter>`.
:func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names
of all available scorers.
Parameters
----------
scoring : str, callable or None
Scoring method as string. If callable it is returned as is.
If None, ret... | python | sklearn/metrics/_scorer.py | 426 | [
"scoring"
] | false | 3 | 7.52 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
ofNonNull | public static <L, R> MutablePair<L, R> ofNonNull(final L left, final R right) {
return of(Objects.requireNonNull(left, "left"), Objects.requireNonNull(right, "right"));
} | Creates a mutable pair of two non-null objects inferring the generic types.
@param <L> the left element type.
@param <R> the right element type.
@param left the left element, may not be null.
@param right the right element, may not be null.
@return a mutable pair formed from the two parameters, not null.
@throws Null... | java | src/main/java/org/apache/commons/lang3/tuple/MutablePair.java | 104 | [
"left",
"right"
] | true | 1 | 6.8 | apache/commons-lang | 2,896 | javadoc | false | |
of | static <T> ValueProcessor<T> of(UnaryOperator<@Nullable T> action) {
Assert.notNull(action, "'action' must not be null");
return (name, value) -> action.apply(value);
} | Factory method to crate a new {@link ValueProcessor} that applies the given
action.
@param <T> the value type
@param action the action to apply
@return a new {@link ValueProcessor} instance | java | core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java | 1,057 | [
"action"
] | true | 1 | 6.48 | spring-projects/spring-boot | 79,428 | javadoc | false | |
_fetch_remote | def _fetch_remote(remote, dirname=None, n_retries=3, delay=1):
"""Helper function to download a remote dataset.
Fetch a dataset pointed by remote's url, save into path using remote's
filename and ensure its integrity based on the SHA256 checksum of the
downloaded file.
.. versionchanged:: 1.6
... | Helper function to download a remote dataset.
Fetch a dataset pointed by remote's url, save into path using remote's
filename and ensure its integrity based on the SHA256 checksum of the
downloaded file.
.. versionchanged:: 1.6
If the file already exists locally and the SHA256 checksums match, the
path to th... | python | sklearn/datasets/_base.py | 1,434 | [
"remote",
"dirname",
"n_retries",
"delay"
] | false | 11 | 6 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
adaptJob | protected Job adaptJob(Object jobObject) throws Exception {
if (jobObject instanceof Job job) {
return job;
}
else if (jobObject instanceof Runnable runnable) {
return new DelegatingJob(runnable);
}
else {
throw new IllegalArgumentException(
"Unable to execute job class [" + jobObject.getClass()... | Adapt the given job object to the Quartz Job interface.
<p>The default implementation supports straight Quartz Jobs
as well as Runnables, which get wrapped in a DelegatingJob.
@param jobObject the original instance of the specified job class
@return the adapted Quartz Job instance
@throws Exception if the given job cou... | java | spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java | 73 | [
"jobObject"
] | Job | true | 3 | 7.76 | spring-projects/spring-framework | 59,386 | javadoc | false |
hexRingPosToH3 | public static long hexRingPosToH3(long h3, int ringPos) {
// for pentagons, we skip direction at position 2
final int pos = H3Index.H3_is_pentagon(h3) && ringPos >= 2 ? ringPos + 1 : ringPos;
if (pos < 0 || pos > 5) {
throw new IllegalArgumentException("invalid ring position");
... | Returns the neighbor index at the given position.
@param h3 Origin index
@param ringPos position of the neighbour index
@return the actual neighbour at the given position | java | libs/h3/src/main/java/org/elasticsearch/h3/H3.java | 400 | [
"h3",
"ringPos"
] | true | 5 | 7.92 | elastic/elasticsearch | 75,680 | javadoc | false | |
contains | public abstract boolean contains(CharSequence seq, CharSequence searchSeq); | Tests if CharSequence contains a search CharSequence, handling {@code null}. This method uses {@link String#indexOf(String)} if possible.
<p>
A {@code null} CharSequence will return {@code false}.
</p>
<p>
Case-sensitive examples
</p>
<pre>
Strings.CS.contains(null, *) = false
Strings.CS.contains(*, null) = fal... | java | src/main/java/org/apache/commons/lang3/Strings.java | 517 | [
"seq",
"searchSeq"
] | true | 1 | 6.32 | apache/commons-lang | 2,896 | javadoc | false | |
count | @Override
public int count(@Nullable Object element) {
AtomicInteger existingCounter = safeGet(countMap, element);
return (existingCounter == null) ? 0 : existingCounter.get();
} | Returns the number of occurrences of {@code element} in this multiset.
@param element the element to look for
@return the nonnegative number of occurrences of the element | java | android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java | 152 | [
"element"
] | true | 2 | 7.92 | google/guava | 51,352 | javadoc | false | |
chebfromroots | def chebfromroots(roots):
"""
Generate a Chebyshev series with given roots.
The function returns the coefficients of the polynomial
.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
in Chebyshev form, where the :math:`r_n` are the roots specified in
`roots`. If a zero has multiplicit... | Generate a Chebyshev series with given roots.
The function returns the coefficients of the polynomial
.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
in Chebyshev form, where the :math:`r_n` are the roots specified in
`roots`. If a zero has multiplicity n, then it must appear in `roots`
n times. For inst... | python | numpy/polynomial/chebyshev.py | 512 | [
"roots"
] | false | 1 | 6.32 | numpy/numpy | 31,054 | numpy | false | |
acknowledge | public void acknowledge(final ConsumerRecord<K, V> record, final AcknowledgeType type) {
for (Map.Entry<TopicIdPartition, ShareInFlightBatch<K, V>> tipBatch : batches.entrySet()) {
TopicIdPartition tip = tipBatch.getKey();
if (tip.topic().equals(record.topic()) && (tip.partition() == rec... | Acknowledge a single record in the current batch.
@param record The record to acknowledge
@param type The acknowledge type which indicates whether it was processed successfully | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareFetch.java | 159 | [
"record",
"type"
] | void | true | 3 | 6.88 | apache/kafka | 31,560 | javadoc | false |
updateEstimation | public static float updateEstimation(String topic, CompressionType type, float observedRatio) {
float[] compressionRatioForTopic = getAndCreateEstimationIfAbsent(topic);
float currentEstimation = compressionRatioForTopic[type.id];
synchronized (compressionRatioForTopic) {
if (observe... | Update the compression ratio estimation for a topic and compression type.
@param topic the topic to update compression ratio estimation.
@param type the compression type.
@param observedRatio the observed compression ratio.
@return the compression ratio estimation after the update. | java | clients/src/main/java/org/apache/kafka/common/record/CompressionRatioEstimator.java | 42 | [
"topic",
"type",
"observedRatio"
] | true | 3 | 7.44 | apache/kafka | 31,560 | javadoc | false | |
toBytes | byte[] toBytes() {
Transport.Type protoType = protocol.getType();
boolean hasPort = TRANSPORTS_WITH_PORTS.contains(protoType);
int len = source.getAddress().length + destination.getAddress().length + 2 + (hasPort ? 4 : 0);
ByteBuffer bb = ByteBuffer.allocate(len);
... | @return true iff the source address/port is numerically less than the destination address/port as described
in the <a href="https://github.com/corelight/community-id-spec">Community ID</a> spec. | java | modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/CommunityIdProcessor.java | 371 | [] | true | 13 | 7.76 | elastic/elasticsearch | 75,680 | javadoc | false | |
read_and_validate_value_from_cache | def read_and_validate_value_from_cache(param_name: str, default_param_value: str) -> tuple[bool, str | None]:
"""
Reads and validates value from cache is present and whether its value is valid according to current rules.
It could happen that the allowed values have been modified since the last time cached v... | Reads and validates value from cache is present and whether its value is valid according to current rules.
It could happen that the allowed values have been modified since the last time cached value was set,
so this check is crucial to check outdated values.
If the value is not set or in case the cached value stored is... | python | dev/breeze/src/airflow_breeze/utils/cache.py | 74 | [
"param_name",
"default_param_value"
] | tuple[bool, str | None] | true | 5 | 7.92 | apache/airflow | 43,597 | sphinx | false |
getField | public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
Objects.requireNonNull(cls, "cls");
Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
// FIXME is this workaround still needed? lang requires Java 6
... | Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be
considered.
@param cls
the {@link Class} to reflect, must not be {@code null}.
@param fieldName
the field name to obtain.
@param forceAccess
whether to break scope restrictions using t... | java | src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java | 178 | [
"cls",
"fieldName",
"forceAccess"
] | Field | true | 6 | 7.76 | apache/commons-lang | 2,896 | javadoc | false |
postValidateSaslMechanismConfig | public static void postValidateSaslMechanismConfig(AbstractConfig config) {
SecurityProtocol securityProtocol = SecurityProtocol.forName(config.getString(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG));
String clientSaslMechanism = config.getString(SaslConfigs.SASL_MECHANISM);
if (securityProtoco... | Log warning if the exponential backoff is disabled due to initial backoff value is greater than max backoff value.
@param config The config object. | java | clients/src/main/java/org/apache/kafka/clients/CommonClientConfigs.java | 297 | [
"config"
] | void | true | 5 | 6.56 | apache/kafka | 31,560 | javadoc | false |
trimArrayElements | @SuppressWarnings("NullAway")
private String[] trimArrayElements(String[] array) {
return StringUtils.trimArrayElements(array);
} | Sets the profile name or expression.
@param name the profile name or expression
@return this
@see Profiles#of(String...) | java | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringProfileArbiter.java | 111 | [
"array"
] | true | 1 | 6.8 | spring-projects/spring-boot | 79,428 | javadoc | false | |
describeFeatures | default DescribeFeaturesResult describeFeatures() {
return describeFeatures(new DescribeFeaturesOptions());
} | Describes finalized as well as supported features.
<p>
This is a convenience method for {@link #describeFeatures(DescribeFeaturesOptions)} with default options.
See the overload for more details.
@return the {@link DescribeFeaturesResult} containing the result | java | clients/src/main/java/org/apache/kafka/clients/admin/Admin.java | 1,523 | [] | DescribeFeaturesResult | true | 1 | 6.16 | apache/kafka | 31,560 | javadoc | false |
findInBuffer | private static int findInBuffer(ByteBuffer buffer) {
for (int pos = buffer.limit() - 4; pos >= 0; pos--) {
buffer.position(pos);
if (buffer.getInt() == SIGNATURE) {
return pos;
}
}
return -1;
} | Create a new {@link ZipEndOfCentralDirectoryRecord} instance from the specified
{@link DataBlock} by searching backwards from the end until a valid record is
located.
@param dataBlock the source data block
@return the {@link Located located} {@link ZipEndOfCentralDirectoryRecord}
@throws IOException if the {@link ZipEn... | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipEndOfCentralDirectoryRecord.java | 140 | [
"buffer"
] | true | 3 | 7.28 | spring-projects/spring-boot | 79,428 | javadoc | false | |
getVectorSelectorPositions | function getVectorSelectorPositions(query: string): VectorSelectorPosition[] {
const tree = parser.parse(query);
const positions: VectorSelectorPosition[] = [];
tree.iterate({
enter: ({ to, from, type }): false | void => {
if (type.id === VectorSelector) {
const visQuery = buildVisualQueryFromSt... | Parse the string and get all VectorSelector positions in the query together with parsed representation of the vector
selector.
@param query | typescript | packages/grafana-prometheus/src/add_label_to_query.ts | 44 | [
"query"
] | true | 2 | 6.4 | grafana/grafana | 71,362 | jsdoc | false | |
replaceAdvisor | @Override
public boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException {
Assert.notNull(a, "Advisor a must not be null");
Assert.notNull(b, "Advisor b must not be null");
int index = indexOf(a);
if (index == -1) {
return false;
}
removeAdvisor(index);
addAdvisor(index, b);
return tr... | Remove a proxied interface.
<p>Does nothing if the given interface isn't proxied.
@param ifc the interface to remove from the proxy
@return {@code true} if the interface was removed; {@code false}
if the interface was not found and hence could not be removed | java | spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java | 354 | [
"a",
"b"
] | true | 2 | 8.24 | spring-projects/spring-framework | 59,386 | javadoc | false | |
getPainlessScriptEngine | private static ScriptEngine getPainlessScriptEngine(final Settings settings) throws IOException {
try (PainlessPlugin painlessPlugin = new PainlessPlugin()) {
painlessPlugin.loadExtensions(new ExtensiblePlugin.ExtensionLoader() {
@Override
@SuppressWar... | @param settings the Elasticsearch settings object
@return a {@link ScriptEngine} for painless scripts for use in {@link IngestScript} and
{@link IngestConditionalScript} contexts, including all available {@link PainlessExtension}s.
@throws IOException when the underlying script engine cannot be created | java | libs/logstash-bridge/src/main/java/org/elasticsearch/logstashbridge/script/ScriptServiceBridge.java | 102 | [
"settings"
] | ScriptEngine | true | 2 | 7.28 | elastic/elasticsearch | 75,680 | javadoc | false |
load | public static PemContent load(Path path) throws IOException {
Assert.notNull(path, "'path' must not be null");
try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) {
return load(in);
}
} | Load {@link PemContent} from the given {@link Path}.
@param path a path to load the content from
@return the loaded PEM content
@throws IOException on IO error | java | core/spring-boot/src/main/java/org/springframework/boot/ssl/pem/PemContent.java | 140 | [
"path"
] | PemContent | true | 1 | 6.72 | spring-projects/spring-boot | 79,428 | javadoc | false |
reregister | private void reregister(KafkaMbean mbean) {
unregister(mbean);
try {
ManagementFactory.getPlatformMBeanServer().registerMBean(mbean, mbean.name());
} catch (JMException e) {
throw new KafkaException("Error registering mbean " + mbean.name(), e);
}
} | @param metricName
@return standard JMX MBean name in the following format domainName:type=metricType,key1=val1,key2=val2 | java | clients/src/main/java/org/apache/kafka/common/metrics/JmxReporter.java | 209 | [
"mbean"
] | void | true | 2 | 6.64 | apache/kafka | 31,560 | javadoc | false |
forCertificate | public static PemSslStoreDetails forCertificate(@Nullable String certificate) {
return forCertificates(certificate);
} | Factory method to create a new {@link PemSslStoreDetails} instance for the given
certificate. <b>Note:</b> This method doesn't actually check if the provided value
only contains a single certificate. It is functionally equivalent to
{@link #forCertificates(String)}.
@param certificate the certificate content (either th... | java | core/spring-boot/src/main/java/org/springframework/boot/ssl/pem/PemSslStoreDetails.java | 154 | [
"certificate"
] | PemSslStoreDetails | true | 1 | 6.16 | spring-projects/spring-boot | 79,428 | javadoc | false |
write | private static void write(ByteBuffer buffer,
byte magic,
long timestamp,
ByteBuffer key,
ByteBuffer value,
CompressionType compressionType,
... | Write the header for a compressed record set in-place (i.e. assuming the compressed record data has already
been written at the value offset in a wrapped record). This lets you dynamically create a compressed message
set, and then go back later and fill in its size and CRC, which saves the need for copying to another b... | java | clients/src/main/java/org/apache/kafka/common/record/LegacyRecord.java | 373 | [
"buffer",
"magic",
"timestamp",
"key",
"value",
"compressionType",
"timestampType"
] | void | true | 2 | 6.72 | apache/kafka | 31,560 | javadoc | false |
equals | def equals(self, other) -> bool:
"""
Return if another array is equivalent to this array.
Equivalent means that both arrays have the same shape and dtype, and
all values compare equal. Missing values in the same location are
considered equal (in contrast with normal equality).
... | Return if another array is equivalent to this array.
Equivalent means that both arrays have the same shape and dtype, and
all values compare equal. Missing values in the same location are
considered equal (in contrast with normal equality).
Parameters
----------
other : ExtensionArray
Array to compare to this Arr... | python | pandas/core/arrays/masked.py | 1,434 | [
"self",
"other"
] | bool | true | 4 | 8.48 | pandas-dev/pandas | 47,362 | numpy | false |
run_autotune_in_subprocess | def run_autotune_in_subprocess(
benchmark_request: BenchmarkRequest,
) -> float:
"""
Run autotuning benchmarks in a subprocess.
This function is submitted to AutotuneProcessPool and runs in isolation
to prevent GPU contention with the main compilation process.
Args:
picklable_choices: ... | Run autotuning benchmarks in a subprocess.
This function is submitted to AutotuneProcessPool and runs in isolation
to prevent GPU contention with the main compilation process.
Args:
picklable_choices: List of picklable choice information
Returns:
timing | python | torch/_inductor/autotune_process.py | 1,171 | [
"benchmark_request"
] | float | true | 1 | 6.24 | pytorch/pytorch | 96,034 | google | false |
of | static SslBundle of(@Nullable SslStoreBundle stores) {
return of(stores, null, null);
} | Factory method to create a new {@link SslBundle} instance.
@param stores the stores or {@code null}
@return a new {@link SslBundle} instance | java | core/spring-boot/src/main/java/org/springframework/boot/ssl/SslBundle.java | 98 | [
"stores"
] | SslBundle | true | 1 | 6.64 | spring-projects/spring-boot | 79,428 | javadoc | false |
readMetadata | ConfigurationMetadata readMetadata() {
return readMetadata(METADATA_PATH);
} | Read the existing {@link ConfigurationMetadata} of the current module or
{@code null} if it is not available yet.
@return the metadata or {@code null} if none is present | java | configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java | 74 | [] | ConfigurationMetadata | true | 1 | 6.48 | spring-projects/spring-boot | 79,428 | javadoc | false |
_smallest_admissible_index_dtype | def _smallest_admissible_index_dtype(arrays=(), maxval=None, check_contents=False):
"""Based on input (integer) arrays `a`, determine a suitable index data
type that can hold the data in the arrays.
This function returns `np.int64` if it either required by `maxval` or based on the
largest precision of ... | Based on input (integer) arrays `a`, determine a suitable index data
type that can hold the data in the arrays.
This function returns `np.int64` if it either required by `maxval` or based on the
largest precision of the dtype of the arrays passed as argument, or by their
contents (when `check_contents is True`). If no... | python | sklearn/utils/fixes.py | 254 | [
"arrays",
"maxval",
"check_contents"
] | false | 14 | 6 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
_get_range | def _get_range(self) -> torch.Tensor:
"""
Get a tensor representing the range [0, size) for this dimension.
Returns:
A 1D tensor with values [0, 1, 2, ..., size-1]
"""
if self._range is None:
self._range = torch.arange(self.size)
return self._rang... | Get a tensor representing the range [0, size) for this dimension.
Returns:
A 1D tensor with values [0, 1, 2, ..., size-1] | python | functorch/dim/__init__.py | 929 | [
"self"
] | torch.Tensor | true | 2 | 8.08 | pytorch/pytorch | 96,034 | unknown | false |
get_variable_from_secrets | def get_variable_from_secrets(key: str, team_name: str | None = None) -> str | None:
"""
Get Airflow Variable by iterating over all Secret Backends.
:param key: Variable Key
:param team_name: Team name associated to the task trying to access the variable (if any)
:return: Variab... | Get Airflow Variable by iterating over all Secret Backends.
:param key: Variable Key
:param team_name: Team name associated to the task trying to access the variable (if any)
:return: Variable Value | python | airflow-core/src/airflow/models/variable.py | 489 | [
"key",
"team_name"
] | str | None | true | 4 | 8.08 | apache/airflow | 43,597 | sphinx | false |
throwMissingRequiredFields | private static void throwMissingRequiredFields(List<String[]> requiredFields) {
final StringBuilder message = new StringBuilder();
for (int i = 0; i < requiredFields.size(); i++) {
if (i > 0) {
message.append(" ");
}
message.append("Required one of fie... | Parses a Value from the given {@link XContentParser}
@param parser the parser to build a value from
@param value the value to fill from the parser
@param context a context that is passed along to all declared field parsers
@return the parsed value
@throws IOException if an IOException occurs. | java | libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java | 334 | [
"requiredFields"
] | void | true | 3 | 7.6 | elastic/elasticsearch | 75,680 | javadoc | false |
set | @CanIgnoreReturnValue
public @Nullable V set(int rowIndex, int columnIndex, @Nullable V value) {
// In GWT array access never throws IndexOutOfBoundsException.
checkElementIndex(rowIndex, rowList.size());
checkElementIndex(columnIndex, columnList.size());
V oldValue = array[rowIndex][columnIndex];
... | Associates {@code value} with the specified row and column indices. The logic {@code
put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has the same
behavior, but this method runs more quickly.
@param rowIndex position of the row key in {@link #rowKeyList()}
@param columnIndex position of the row... | java | android/guava/src/com/google/common/collect/ArrayTable.java | 343 | [
"rowIndex",
"columnIndex",
"value"
] | V | true | 1 | 6.88 | google/guava | 51,352 | javadoc | false |
negate | public Fraction negate() {
// the positive range is one smaller than the negative range of an int.
if (numerator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: too large to negate");
}
return new Fraction(-numerator, denominator);
} | Gets a fraction that is the negative (-fraction) of this one.
<p>
The returned fraction is not reduced.
</p>
@return a new fraction instance with the opposite signed numerator | java | src/main/java/org/apache/commons/lang3/math/Fraction.java | 801 | [] | Fraction | true | 2 | 8.4 | apache/commons-lang | 2,896 | javadoc | false |
beans | public GroovyBeanDefinitionReader beans(Closure<?> closure) {
return invokeBeanDefiningClosure(closure);
} | Defines a set of beans for the given block or closure.
@param closure the block or closure
@return this {@code GroovyBeanDefinitionReader} instance | java | spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java | 294 | [
"closure"
] | GroovyBeanDefinitionReader | true | 1 | 6.48 | spring-projects/spring-framework | 59,386 | javadoc | false |
get_class_if_classified_error | def get_class_if_classified_error(e: Exception) -> Optional[str]:
"""
Returns a string case name if the export error e is classified.
Returns None otherwise.
"""
from torch._dynamo.exc import TorchRuntimeError, Unsupported, UserError
ALWAYS_CLASSIFIED = "always_classified"
DEFAULT_CLASS_SI... | Returns a string case name if the export error e is classified.
Returns None otherwise. | python | torch/_export/db/logging.py | 21 | [
"e"
] | Optional[str] | true | 3 | 6 | pytorch/pytorch | 96,034 | unknown | false |
findConfig | private @Nullable String findConfig(String[] locations) {
for (String location : locations) {
ClassPathResource resource = new ClassPathResource(location, this.classLoader);
if (resource.exists()) {
return "classpath:" + location;
}
}
return null;
} | Return any spring specific initialization config that should be applied. By default
this method checks {@link #getSpringConfigLocations()}.
@return the spring initialization config or {@code null} | java | core/spring-boot/src/main/java/org/springframework/boot/logging/AbstractLoggingSystem.java | 111 | [
"locations"
] | String | true | 2 | 6.24 | spring-projects/spring-boot | 79,428 | javadoc | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.