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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
checkTypeArgument
|
private void checkTypeArgument(Object formatter) {
Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(formatter.getClass(),
StructuredLogFormatter.class);
Assert.state(this.logEventType.equals(typeArgument),
() -> "Type argument of %s must be %s but was %s".formatted(formatter.getClass().getName(),
this.logEventType.getName(), (typeArgument != null) ? typeArgument.getName() : "null"));
}
|
Get a new {@link StructuredLogFormatter} instance for the specified format.
@param format the format requested (either a {@link CommonStructuredLogFormat} ID
or a fully-qualified class name)
@return a new {@link StructuredLogFormatter} instance
@throws IllegalArgumentException if the format is unknown
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/StructuredLogFormatterFactory.java
| 145
|
[
"formatter"
] |
void
| true
| 2
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
systemPropertiesLookup
|
public static StrLookup<String> systemPropertiesLookup() {
return SYSTEM_PROPERTIES_LOOKUP;
}
|
Returns a new lookup which uses a copy of the current
{@link System#getProperties() System properties}.
<p>
If a security manager blocked access to system properties, then null will
be returned from every lookup.
</p>
<p>
If a null key is used, this lookup will throw a NullPointerException.
</p>
@return a lookup using system properties, not null.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrLookup.java
| 147
|
[] | true
| 1
| 6.64
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
addAttachment
|
public void addAttachment(
String attachmentFilename, InputStreamSource inputStreamSource, String contentType)
throws MessagingException {
Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
if (inputStreamSource instanceof Resource resource && resource.isOpen()) {
throw new IllegalArgumentException(
"Passed-in Resource contains an open stream: invalid argument. " +
"JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
}
DataSource dataSource = createDataSource(inputStreamSource, contentType, attachmentFilename);
addAttachment(attachmentFilename, dataSource);
}
|
Add an attachment to the MimeMessage, taking the content from an
{@code org.springframework.core.io.InputStreamResource}.
<p>Note that the InputStream returned by the InputStreamSource
implementation needs to be a <i>fresh one on each call</i>, as
JavaMail will invoke {@code getInputStream()} multiple times.
@param attachmentFilename the name of the attachment as it will
appear in the mail
@param inputStreamSource the resource to take the content from
(all of Spring's Resource implementations can be passed in here)
@param contentType the content type to use for the element
@throws MessagingException in case of errors
@see #addAttachment(String, java.io.File)
@see #addAttachment(String, jakarta.activation.DataSource)
@see org.springframework.core.io.Resource
|
java
|
spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java
| 1,186
|
[
"attachmentFilename",
"inputStreamSource",
"contentType"
] |
void
| true
| 3
| 6.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
prepare_performance_dag_columns
|
def prepare_performance_dag_columns(
performance_dag_conf: dict[str, str],
) -> OrderedDict:
"""
Prepare dict containing DAG env variables.
Prepare an OrderedDict containing chosen performance dag environment variables
that will serve as columns for the results dataframe.
:param performance_dag_conf: dict with environment variables as keys and their values as values
:return: a dict with a subset of environment variables
in order in which they should appear in the results dataframe
:rtype: OrderedDict
"""
max_runs = get_performance_dag_environment_variable(performance_dag_conf, "PERF_MAX_RUNS")
# TODO: if PERF_MAX_RUNS is missing from configuration, then PERF_SCHEDULE_INTERVAL must
# be '@once'; this is an equivalent of PERF_MAX_RUNS being '1', which will be the default value
# once PERF_START_AGO and PERF_SCHEDULE_INTERVAL are removed
# TODO: we should not ban PERF_SCHEDULE_INTERVAL completely because we will make it impossible
# to run time-based tests (where you run dags constantly for 1h for example). I think we should
# allow setting of only one of them.
# If PERF_MAX_RUNS is set, then PERF_SCHEDULE_INTERVAL should be ignored - default value of 1h
# should be used combined with PERF_START_AGO so that expected number of runs can be created immediately
# If PERF_SCHEDULE_INTERVAL is set and PERF_MAX_RUNS is not, then PERF_START_AGO should be set
# to current date so that dag runs start creating now instead of creating multiple runs from the
# past - but it will be rather hard taking into account time of environment creation. Wasn't
# there some dag option to NOT create past runs? -> catchup
# ALSO either PERF_MAX_RUNS or PERF_SCHEDULE_INTERVAL OR both should be included in results file
if max_runs is None:
max_runs = 1
else:
max_runs = int(max_runs)
performance_dag_columns = OrderedDict(
[
(
"PERF_DAG_FILES_COUNT",
int(get_performance_dag_environment_variable(performance_dag_conf, "PERF_DAG_FILES_COUNT")),
),
(
"PERF_DAGS_COUNT",
int(get_performance_dag_environment_variable(performance_dag_conf, "PERF_DAGS_COUNT")),
),
(
"PERF_TASKS_COUNT",
int(get_performance_dag_environment_variable(performance_dag_conf, "PERF_TASKS_COUNT")),
),
("PERF_MAX_RUNS", max_runs),
(
"PERF_SCHEDULE_INTERVAL",
get_performance_dag_environment_variable(performance_dag_conf, "PERF_SCHEDULE_INTERVAL"),
),
(
"PERF_SHAPE",
get_performance_dag_environment_variable(performance_dag_conf, "PERF_SHAPE"),
),
(
"PERF_SLEEP_TIME",
float(get_performance_dag_environment_variable(performance_dag_conf, "PERF_SLEEP_TIME")),
),
(
"PERF_OPERATOR_TYPE",
get_performance_dag_environment_variable(performance_dag_conf, "PERF_OPERATOR_TYPE"),
),
]
)
add_performance_dag_configuration_type(performance_dag_columns)
return performance_dag_columns
|
Prepare dict containing DAG env variables.
Prepare an OrderedDict containing chosen performance dag environment variables
that will serve as columns for the results dataframe.
:param performance_dag_conf: dict with environment variables as keys and their values as values
:return: a dict with a subset of environment variables
in order in which they should appear in the results dataframe
:rtype: OrderedDict
|
python
|
performance/src/performance_dags/performance_dag/performance_dag_utils.py
| 506
|
[
"performance_dag_conf"
] |
OrderedDict
| true
| 3
| 7.68
|
apache/airflow
| 43,597
|
sphinx
| false
|
mat1mat2
|
def mat1mat2(self) -> tuple[Any, Any]:
"""
Get the mat1 and mat2 nodes.
Returns:
A tuple of (mat1, mat2) nodes
"""
nodes = self.nodes()
return nodes[self._mat1_idx], nodes[self._mat2_idx]
|
Get the mat1 and mat2 nodes.
Returns:
A tuple of (mat1, mat2) nodes
|
python
|
torch/_inductor/kernel_inputs.py
| 306
|
[
"self"
] |
tuple[Any, Any]
| true
| 1
| 6.4
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
adjoin
|
def adjoin(space: int, *lists: list[str], **kwargs: Any) -> str:
"""
Glues together two sets of strings using the amount of space requested.
The idea is to prettify.
----------
space : int
number of spaces for padding
lists : str
list of str which being joined
strlen : callable
function used to calculate the length of each str. Needed for unicode
handling.
justfunc : callable
function used to justify str. Needed for unicode handling.
"""
strlen = kwargs.pop("strlen", len)
justfunc = kwargs.pop("justfunc", _adj_justify)
newLists = []
lengths = [max(map(strlen, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
maxLen = max(map(len, lists))
for i, lst in enumerate(lists):
nl = justfunc(lst, lengths[i], mode="left")
nl = ([" " * lengths[i]] * (maxLen - len(lst))) + nl
newLists.append(nl)
toJoin = zip(*newLists, strict=True)
return "\n".join("".join(lines) for lines in toJoin)
|
Glues together two sets of strings using the amount of space requested.
The idea is to prettify.
----------
space : int
number of spaces for padding
lists : str
list of str which being joined
strlen : callable
function used to calculate the length of each str. Needed for unicode
handling.
justfunc : callable
function used to justify str. Needed for unicode handling.
|
python
|
pandas/io/formats/printing.py
| 35
|
[
"space"
] |
str
| true
| 2
| 7.04
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
compare
|
@SuppressWarnings("InlineMeInliner") // Integer.compare unavailable under GWT+J2CL
public static int compare(int a, int b) {
return Ints.compare(flip(a), flip(b));
}
|
Compares the two specified {@code int} values, treating them as unsigned values between {@code
0} and {@code 2^32 - 1} inclusive.
<p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the
equivalent {@link Integer#compareUnsigned(int, int)} method instead.
@param a the first unsigned {@code int} to compare
@param b the second unsigned {@code int} to compare
@return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
greater than {@code b}; or zero if they are equal
|
java
|
android/guava/src/com/google/common/primitives/UnsignedInts.java
| 69
|
[
"a",
"b"
] | true
| 1
| 6.48
|
google/guava
| 51,352
|
javadoc
| false
|
|
isFullMatch
|
public boolean isFullMatch() {
for (ConditionAndOutcome conditionAndOutcomes : this) {
if (!conditionAndOutcomes.getOutcome().isMatch()) {
return false;
}
}
return true;
}
|
Return {@code true} if all outcomes match.
@return {@code true} if a full match
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionEvaluationReport.java
| 235
|
[] | true
| 2
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
uncapitalize
|
public static String uncapitalize(final String str) {
final int strLen = length(str);
if (strLen == 0) {
return str;
}
final int firstCodePoint = str.codePointAt(0);
final int newCodePoint = Character.toLowerCase(firstCodePoint);
if (firstCodePoint == newCodePoint) {
// already uncapitalized
return str;
}
final int[] newCodePoints = str.codePoints().toArray();
newCodePoints[0] = newCodePoint; // copy the first code point
return new String(newCodePoints, 0, newCodePoints.length);
}
|
Uncapitalizes a String, changing the first character to lower case as per {@link Character#toLowerCase(int)}. No other characters are changed.
<p>
For a word based algorithm, see {@link org.apache.commons.text.WordUtils#uncapitalize(String)}. A {@code null} input String returns {@code null}.
</p>
<pre>
StringUtils.uncapitalize(null) = null
StringUtils.uncapitalize("") = ""
StringUtils.uncapitalize("cat") = "cat"
StringUtils.uncapitalize("Cat") = "cat"
StringUtils.uncapitalize("CAT") = "cAT"
</pre>
@param str the String to uncapitalize, may be null.
@return the uncapitalized String, {@code null} if null String input.
@see org.apache.commons.text.WordUtils#uncapitalize(String)
@see #capitalize(String)
@since 2.0
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 8,906
|
[
"str"
] |
String
| true
| 3
| 7.6
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
noop
|
static MatcherWatchdog noop() {
return Noop.INSTANCE;
}
|
@return A noop implementation that does not interrupt threads and is useful for testing and pre-defined grok expressions.
|
java
|
libs/grok/src/main/java/org/elasticsearch/grok/MatcherWatchdog.java
| 75
|
[] |
MatcherWatchdog
| true
| 1
| 6.8
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
getAndAdd
|
public int getAndAdd(final int operand) {
final int last = value;
this.value += operand;
return last;
}
|
Increments this instance's value by {@code operand}; this method returns the value associated with the instance
immediately prior to the addition operation. This method is not thread safe.
@param operand the quantity to add, not null.
@return the value associated with this instance immediately before the operand was added.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableInt.java
| 206
|
[
"operand"
] | true
| 1
| 6.88
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
_simple_json_normalize
|
def _simple_json_normalize(
ds: dict | list[dict],
sep: str = ".",
) -> dict | list[dict] | Any:
"""
An optimized basic json_normalize
Converts a nested dict into a flat dict ("record"), unlike
json_normalize and nested_to_record it doesn't do anything clever.
But for the most basic use cases it enhances performance.
E.g. pd.json_normalize(data)
Parameters
----------
ds : dict or list of dicts
sep : str, default '.'
Nested records will generate names separated by sep,
e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
Returns
-------
frame : DataFrame
d - dict or list of dicts, matching `normalized_json_object`
Examples
--------
>>> _simple_json_normalize(
... {
... "flat1": 1,
... "dict1": {"c": 1, "d": 2},
... "nested": {"e": {"c": 1, "d": 2}, "d": 2},
... }
... )
{\
'flat1': 1, \
'dict1.c': 1, \
'dict1.d': 2, \
'nested.e.c': 1, \
'nested.e.d': 2, \
'nested.d': 2\
}
"""
normalized_json_object = {}
# expect a dictionary, as most jsons are. However, lists are perfectly valid
if isinstance(ds, dict):
normalized_json_object = _normalize_json_ordered(data=ds, separator=sep)
elif isinstance(ds, list):
normalized_json_list = [_simple_json_normalize(row, sep=sep) for row in ds]
return normalized_json_list
return normalized_json_object
|
An optimized basic json_normalize
Converts a nested dict into a flat dict ("record"), unlike
json_normalize and nested_to_record it doesn't do anything clever.
But for the most basic use cases it enhances performance.
E.g. pd.json_normalize(data)
Parameters
----------
ds : dict or list of dicts
sep : str, default '.'
Nested records will generate names separated by sep,
e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
Returns
-------
frame : DataFrame
d - dict or list of dicts, matching `normalized_json_object`
Examples
--------
>>> _simple_json_normalize(
... {
... "flat1": 1,
... "dict1": {"c": 1, "d": 2},
... "nested": {"e": {"c": 1, "d": 2}, "d": 2},
... }
... )
{\
'flat1': 1, \
'dict1.c': 1, \
'dict1.d': 2, \
'nested.e.c': 1, \
'nested.e.d': 2, \
'nested.d': 2\
}
|
python
|
pandas/io/json/_normalize.py
| 217
|
[
"ds",
"sep"
] |
dict | list[dict] | Any
| true
| 3
| 8.64
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
is_period_dtype
|
def is_period_dtype(arr_or_dtype) -> bool:
"""
Check whether an array-like or dtype is of the Period dtype.
.. deprecated:: 2.2.0
Use isinstance(dtype, pd.PeriodDtype) instead.
Parameters
----------
arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the Period dtype.
See Also
--------
api.types.is_timedelta64_ns_dtype : Check whether the provided array or dtype is
of the timedelta64[ns] dtype.
api.types.is_timedelta64_dtype: Check whether an array-like or dtype
is of the timedelta64 dtype.
Examples
--------
>>> from pandas.api.types import is_period_dtype
>>> is_period_dtype(object)
False
>>> is_period_dtype(pd.PeriodDtype(freq="D"))
True
>>> is_period_dtype([1, 2, 3])
False
>>> is_period_dtype(pd.Period("2017-01-01"))
False
>>> is_period_dtype(pd.PeriodIndex([], freq="Y"))
True
"""
warnings.warn(
"is_period_dtype is deprecated and will be removed in a future version. "
"Use `isinstance(dtype, pd.PeriodDtype)` instead",
Pandas4Warning,
stacklevel=2,
)
if isinstance(arr_or_dtype, ExtensionDtype):
# GH#33400 fastpath for dtype object
return arr_or_dtype.type is Period
if arr_or_dtype is None:
return False
return PeriodDtype.is_dtype(arr_or_dtype)
|
Check whether an array-like or dtype is of the Period dtype.
.. deprecated:: 2.2.0
Use isinstance(dtype, pd.PeriodDtype) instead.
Parameters
----------
arr_or_dtype : array-like or dtype
The array-like or dtype to check.
Returns
-------
boolean
Whether or not the array-like or dtype is of the Period dtype.
See Also
--------
api.types.is_timedelta64_ns_dtype : Check whether the provided array or dtype is
of the timedelta64[ns] dtype.
api.types.is_timedelta64_dtype: Check whether an array-like or dtype
is of the timedelta64 dtype.
Examples
--------
>>> from pandas.api.types import is_period_dtype
>>> is_period_dtype(object)
False
>>> is_period_dtype(pd.PeriodDtype(freq="D"))
True
>>> is_period_dtype([1, 2, 3])
False
>>> is_period_dtype(pd.Period("2017-01-01"))
False
>>> is_period_dtype(pd.PeriodIndex([], freq="Y"))
True
|
python
|
pandas/core/dtypes/common.py
| 436
|
[
"arr_or_dtype"
] |
bool
| true
| 3
| 8
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
max
|
@ParametricNullness
public <E extends T> E max(@ParametricNullness E a, @ParametricNullness E b) {
return (compare(a, b) >= 0) ? a : b;
}
|
Returns the greater of the two values according to this ordering. If the values compare as 0,
the first is returned.
<p><b>Implementation note:</b> this method is invoked by the default implementations of the
other {@code max} overloads, so overriding it will affect their behavior.
<p><b>Note:</b> Consider using {@code Comparators.max(a, b, thisComparator)} instead. If {@code
thisComparator} is {@link Ordering#natural}, then use {@code Comparators.max(a, b)}.
@param a value to compare, returned if greater than or equal to b.
@param b value to compare.
@throws ClassCastException if the parameters are not <i>mutually comparable</i> under this
ordering.
|
java
|
android/guava/src/com/google/common/collect/Ordering.java
| 698
|
[
"a",
"b"
] |
E
| true
| 2
| 6.32
|
google/guava
| 51,352
|
javadoc
| false
|
randomNumeric
|
@Deprecated
public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextNumeric(minLengthInclusive, maxLengthExclusive);
}
|
Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
<p>
Characters will be chosen from the set of \p{Digit} characters.
</p>
@param minLengthInclusive the inclusive minimum length of the string to generate.
@param maxLengthExclusive the exclusive maximum length of the string to generate.
@return the random string.
@since 3.5
@deprecated Use {@link #nextNumeric(int, int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
|
java
|
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
| 586
|
[
"minLengthInclusive",
"maxLengthExclusive"
] |
String
| true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
indexOf
|
public int indexOf(final char ch, int startIndex) {
startIndex = Math.max(startIndex, 0);
if (startIndex >= size) {
return -1;
}
final char[] thisBuf = buffer;
for (int i = startIndex; i < size; i++) {
if (thisBuf[i] == ch) {
return i;
}
}
return -1;
}
|
Searches the string builder to find the first reference to the specified char.
@param ch the character to find
@param startIndex the index to start at, invalid index rounded to edge
@return the first index of the character, or -1 if not found
|
java
|
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
| 2,000
|
[
"ch",
"startIndex"
] | true
| 4
| 7.92
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
removeIf
|
@CanIgnoreReturnValue
public static <T extends @Nullable Object> boolean removeIf(
Iterator<T> removeFrom, Predicate<? super T> predicate) {
checkNotNull(predicate);
boolean modified = false;
while (removeFrom.hasNext()) {
if (predicate.apply(removeFrom.next())) {
removeFrom.remove();
modified = true;
}
}
return modified;
}
|
Removes every element that satisfies the provided predicate from the iterator. The iterator
will be left exhausted: its {@code hasNext()} method will return {@code false}.
@param removeFrom the iterator to (potentially) remove elements from
@param predicate a predicate that determines whether an element should be removed
@return {@code true} if any elements were removed from the iterator
@since 2.0
|
java
|
android/guava/src/com/google/common/collect/Iterators.java
| 227
|
[
"removeFrom",
"predicate"
] | true
| 3
| 7.76
|
google/guava
| 51,352
|
javadoc
| false
|
|
requiresRefresh
|
protected boolean requiresRefresh() {
return true;
}
|
Determine whether a refresh is required.
Invoked for each refresh check, after the refresh check delay has elapsed.
<p>The default implementation always returns {@code true}, triggering
a refresh every time the delay has elapsed. To be overridden by subclasses
with an appropriate check of the underlying target resource.
@return whether a refresh is required
|
java
|
spring-aop/src/main/java/org/springframework/aop/target/dynamic/AbstractRefreshableTargetSource.java
| 133
|
[] | true
| 1
| 6.96
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
mean
|
@Deprecated
// com.google.common.math.DoubleUtils
@GwtIncompatible
public static double mean(Iterator<? extends Number> values) {
checkArgument(values.hasNext(), "Cannot take mean of 0 values");
long count = 1;
double mean = checkFinite(values.next().doubleValue());
while (values.hasNext()) {
double value = checkFinite(values.next().doubleValue());
count++;
// Art of Computer Programming vol. 2, Knuth, 4.2.2, (15)
mean += (value - mean) / count;
}
return mean;
}
|
Returns the <a href="http://en.wikipedia.org/wiki/Arithmetic_mean">arithmetic mean</a> of
{@code values}.
<p>If these values are a sample drawn from a population, this is also an unbiased estimator of
the arithmetic mean of the population.
@param values a nonempty series of values, which will be converted to {@code double} values
(this may cause loss of precision)
@throws IllegalArgumentException if {@code values} is empty or contains any non-finite value
@deprecated Use {@link Stats#meanOf} instead, noting the less strict handling of non-finite
values.
|
java
|
android/guava/src/com/google/common/math/DoubleMath.java
| 508
|
[
"values"
] | true
| 2
| 6.56
|
google/guava
| 51,352
|
javadoc
| false
|
|
any
|
def any(self, *, skipna: bool = True, **kwargs) -> bool | NAType:
"""
Return whether any element is truthy.
Returns False unless there is at least one element that is truthy.
By default, NAs are skipped. If ``skipna=False`` is specified and
missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
is used as for logical operations.
Parameters
----------
skipna : bool, default True
Exclude NA values. If the entire array is NA and `skipna` is
True, then the result will be False, as for an empty array.
If `skipna` is False, the result will still be True if there is
at least one element that is truthy, otherwise NA will be returned
if there are NA's present.
Returns
-------
bool or :attr:`pandas.NA`
See Also
--------
ArrowExtensionArray.all : Return whether all elements are truthy.
Examples
--------
The result indicates whether any element is truthy (and by default
skips NAs):
>>> pd.array([True, False, True], dtype="boolean[pyarrow]").any()
True
>>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any()
True
>>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any()
False
>>> pd.array([], dtype="boolean[pyarrow]").any()
False
>>> pd.array([pd.NA], dtype="boolean[pyarrow]").any()
False
>>> pd.array([pd.NA], dtype="float64[pyarrow]").any()
False
With ``skipna=False``, the result can be NA if this is logically
required (whether ``pd.NA`` is True or False influences the result):
>>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
True
>>> pd.array([1, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
True
>>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
<NA>
>>> pd.array([0, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
<NA>
"""
return self._reduce("any", skipna=skipna, **kwargs)
|
Return whether any element is truthy.
Returns False unless there is at least one element that is truthy.
By default, NAs are skipped. If ``skipna=False`` is specified and
missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
is used as for logical operations.
Parameters
----------
skipna : bool, default True
Exclude NA values. If the entire array is NA and `skipna` is
True, then the result will be False, as for an empty array.
If `skipna` is False, the result will still be True if there is
at least one element that is truthy, otherwise NA will be returned
if there are NA's present.
Returns
-------
bool or :attr:`pandas.NA`
See Also
--------
ArrowExtensionArray.all : Return whether all elements are truthy.
Examples
--------
The result indicates whether any element is truthy (and by default
skips NAs):
>>> pd.array([True, False, True], dtype="boolean[pyarrow]").any()
True
>>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any()
True
>>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any()
False
>>> pd.array([], dtype="boolean[pyarrow]").any()
False
>>> pd.array([pd.NA], dtype="boolean[pyarrow]").any()
False
>>> pd.array([pd.NA], dtype="float64[pyarrow]").any()
False
With ``skipna=False``, the result can be NA if this is logically
required (whether ``pd.NA`` is True or False influences the result):
>>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
True
>>> pd.array([1, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
True
>>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
<NA>
>>> pd.array([0, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
<NA>
|
python
|
pandas/core/arrays/arrow/array.py
| 1,153
|
[
"self",
"skipna"
] |
bool | NAType
| true
| 1
| 6.96
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
fixWindowsLocationPath
|
private static String fixWindowsLocationPath(String locationPath) {
// Same logic as Java's internal WindowsUriSupport class
if (locationPath.length() > 2 && locationPath.charAt(2) == ':') {
return locationPath.substring(1);
}
// Deal with Jetty's org.eclipse.jetty.util.URIUtil#correctURI(URI)
if (locationPath.startsWith("///") && locationPath.charAt(4) == ':') {
return locationPath.substring(3);
}
return locationPath;
}
|
Create a new {@link NestedLocation} from the given URI.
@param uri the nested URI
@return a new {@link NestedLocation} instance
@throws IllegalArgumentException if the URI is not valid
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/nested/NestedLocation.java
| 117
|
[
"locationPath"
] |
String
| true
| 5
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
loadAgent
|
@SuppressForbidden(reason = "The VirtualMachine API is the only way to attach a java agent dynamically")
static void loadAgent(String agentPath, String entitlementInitializationClassName) {
try {
VirtualMachine vm = VirtualMachine.attach(Long.toString(ProcessHandle.current().pid()));
try {
vm.loadAgent(agentPath, entitlementInitializationClassName);
} finally {
vm.detach();
}
} catch (AttachNotSupportedException | IOException | AgentLoadException | AgentInitializationException e) {
throw new IllegalStateException("Unable to attach entitlement agent [" + agentPath + "]", e);
}
}
|
Main entry point that activates entitlement checking. Once this method returns,
calls to methods protected by entitlements from classes without a valid
policy will throw {@link org.elasticsearch.entitlement.runtime.api.NotEntitledException}.
@param serverPolicyPatch additional entitlements to patch the embedded server layer policy
@param pluginPolicies maps each plugin name to the corresponding {@link Policy}
@param scopeResolver a functor to map a Java Class to the component and module it belongs to.
@param settingResolver a functor to resolve a setting name pattern for one or more Elasticsearch settings.
@param dataDirs data directories for Elasticsearch
@param sharedDataDir shared data directory for Elasticsearch (deprecated)
@param sharedRepoDirs shared repository directories for Elasticsearch
@param configDir the config directory for Elasticsearch
@param libDir the lib directory for Elasticsearch
@param modulesDir the directory where Elasticsearch modules are
@param pluginsDir the directory where plugins are installed for Elasticsearch
@param pluginSourcePaths maps each plugin name to the location of that plugin's code
@param tempDir the temp directory for Elasticsearch
@param logsDir the log directory for Elasticsearch
@param pidFile path to a pid file for Elasticsearch, or {@code null} if one was not specified
@param suppressFailureLogPackages packages for which we do not need or want to log Entitlements failures
|
java
|
libs/entitlement/src/main/java/org/elasticsearch/entitlement/bootstrap/EntitlementBootstrap.java
| 118
|
[
"agentPath",
"entitlementInitializationClassName"
] |
void
| true
| 2
| 6.24
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
endOffsets
|
@Override
public Map<TopicPartition, Long> endOffsets(Collection<TopicPartition> partitions) {
return delegate.endOffsets(partitions);
}
|
Get the end offsets for the given partitions. In the default {@code read_uncommitted} isolation level, the end
offset is the high watermark (that is, the offset of the last successfully replicated message plus one). For
{@code read_committed} consumers, the end offset is the last stable offset (LSO), which is the minimum of
the high watermark and the smallest offset of any open transaction. Finally, if the partition has never been
written to, the end offset is 0.
<p>
This method does not change the current consumer position of the partitions.
@see #seekToEnd(Collection)
@param partitions the partitions to get the end offsets.
@return The end offsets for the given partitions.
@throws org.apache.kafka.common.errors.AuthenticationException if authentication fails. See the exception for more details
@throws org.apache.kafka.common.errors.AuthorizationException if not authorized to the topic(s). See the exception for more details
@throws org.apache.kafka.common.errors.TimeoutException if the offset metadata could not be fetched before
the amount of time allocated by {@code default.api.timeout.ms} expires
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java
| 1,677
|
[
"partitions"
] | true
| 1
| 6.16
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
on
|
public static Splitter on(char separator) {
return on(CharMatcher.is(separator));
}
|
Returns a splitter that uses the given single-character separator. For example, {@code
Splitter.on(',').split("foo,,bar")} returns an iterable containing {@code ["foo", "", "bar"]}.
@param separator the character to recognize as a separator
@return a splitter, with default settings, that recognizes that separator
|
java
|
android/guava/src/com/google/common/base/Splitter.java
| 126
|
[
"separator"
] |
Splitter
| true
| 1
| 6.48
|
google/guava
| 51,352
|
javadoc
| false
|
register_task
|
def register_task(self, task, **options):
"""Utility for registering a task-based class.
Note:
This is here for compatibility with old Celery 1.0
style task classes, you should not need to use this for
new projects.
"""
task = inspect.isclass(task) and task() or task
if not task.name:
task_cls = type(task)
task.name = self.gen_task_name(
task_cls.__name__, task_cls.__module__)
add_autoretry_behaviour(task, **options)
self.tasks[task.name] = task
task._app = self
task.bind(self)
return task
|
Utility for registering a task-based class.
Note:
This is here for compatibility with old Celery 1.0
style task classes, you should not need to use this for
new projects.
|
python
|
celery/app/base.py
| 609
|
[
"self",
"task"
] | false
| 4
| 6.08
|
celery/celery
| 27,741
|
unknown
| false
|
|
createStrictDateTimeFormatter
|
static DateTimeFormatter createStrictDateTimeFormatter(String pattern) {
// Using strict resolution to align with standard DateFormat behavior:
// otherwise, an overflow like, for example, Feb 29 for a non-leap-year wouldn't get rejected.
// However, with strict resolution, a year digit needs to be specified as 'u'...
String patternToUse = StringUtils.replace(pattern, "yy", "uu");
return DateTimeFormatter.ofPattern(patternToUse).withResolverStyle(ResolverStyle.STRICT);
}
|
Create a {@link DateTimeFormatter} for the supplied pattern, configured with
{@linkplain ResolverStyle#STRICT strict} resolution.
<p>Note that the strict resolution does not affect the parsing.
@param pattern the pattern to use
@return a new {@code DateTimeFormatter}
@see ResolverStyle#STRICT
|
java
|
spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterUtils.java
| 40
|
[
"pattern"
] |
DateTimeFormatter
| true
| 1
| 6.4
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
visitPropertyNameOfClassElement
|
function visitPropertyNameOfClassElement(member: ClassElement): PropertyName {
const name = member.name!;
// Computed property names need to be transformed into a hoisted variable when they are used more than once.
// The names are used more than once when the property has a decorator.
if (legacyDecorators && isComputedPropertyName(name) && hasDecorators(member)) {
const expression = visitNode(name.expression, visitor, isExpression);
Debug.assert(expression);
const innerExpression = skipPartiallyEmittedExpressions(expression);
if (!isSimpleInlineableExpression(innerExpression)) {
const generatedName = factory.getGeneratedNameForNode(name);
hoistVariableDeclaration(generatedName);
return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
}
}
return Debug.checkDefined(visitNode(name, visitor, isPropertyName));
}
|
Visits the property name of a class element, for use when emitting property
initializers. For a computed property on a node with decorators, a temporary
value is stored for later use.
@param member The member whose name should be visited.
|
typescript
|
src/compiler/transformers/ts.ts
| 1,237
|
[
"member"
] | true
| 5
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
asStdFunction
|
std::function<typename Traits::NonConstSignature> asStdFunction() && {
return std::move(*this).asSharedProxy();
}
|
Construct a `std::function` by moving in the contents of this `Function`.
Note that the returned `std::function` will share its state (i.e. captured
data) across all copies you make of it, so be very careful when copying.
|
cpp
|
folly/Function.h
| 927
|
[] | true
| 2
| 6.96
|
facebook/folly
| 30,157
|
doxygen
| false
|
|
getOverride
|
public @Nullable MethodOverride getOverride(Method method) {
MethodOverride match = null;
for (MethodOverride candidate : this.overrides) {
if (candidate.matches(method)) {
match = candidate;
}
}
return match;
}
|
Return the override for the given method, if any.
@param method the method to check for overrides for
@return the method override, or {@code null} if none
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/MethodOverrides.java
| 93
|
[
"method"
] |
MethodOverride
| true
| 2
| 8.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
getTimeZone
|
public static TimeZone getTimeZone(@Nullable LocaleContext localeContext) {
if (localeContext instanceof TimeZoneAwareLocaleContext timeZoneAware) {
TimeZone timeZone = timeZoneAware.getTimeZone();
if (timeZone != null) {
return timeZone;
}
}
return (defaultTimeZone != null ? defaultTimeZone : TimeZone.getDefault());
}
|
Return the TimeZone associated with the given user context, if any,
or the system default TimeZone otherwise. This is effectively a
replacement for {@link java.util.TimeZone#getDefault()},
able to optionally respect a user-level TimeZone setting.
@param localeContext the user-level locale context to check
@return the current TimeZone, or the system default TimeZone if no
specific TimeZone has been associated with the current thread
@since 5.0
@see #getTimeZone()
@see TimeZoneAwareLocaleContext#getTimeZone()
@see #setDefaultTimeZone(TimeZone)
@see java.util.TimeZone#getDefault()
|
java
|
spring-context/src/main/java/org/springframework/context/i18n/LocaleContextHolder.java
| 324
|
[
"localeContext"
] |
TimeZone
| true
| 4
| 7.44
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
truncate
|
public static String truncate(final String str, final int maxWidth) {
return truncate(str, 0, maxWidth);
}
|
Truncates a String. This will turn "Now is the time for all good men" into "Now is the time for".
<p>
Specifically:
</p>
<ul>
<li>If {@code str} is less than {@code maxWidth} characters long, return it.</li>
<li>Else truncate it to {@code substring(str, 0, maxWidth)}.</li>
<li>If {@code maxWidth} is less than {@code 0}, throw an {@link IllegalArgumentException}.</li>
<li>In no case will it return a String of length greater than {@code maxWidth}.</li>
</ul>
<pre>
StringUtils.truncate(null, 0) = null
StringUtils.truncate(null, 2) = null
StringUtils.truncate("", 4) = ""
StringUtils.truncate("abcdefg", 4) = "abcd"
StringUtils.truncate("abcdefg", 6) = "abcdef"
StringUtils.truncate("abcdefg", 7) = "abcdefg"
StringUtils.truncate("abcdefg", 8) = "abcdefg"
StringUtils.truncate("abcdefg", -1) = throws an IllegalArgumentException
</pre>
@param str the String to truncate, may be null.
@param maxWidth maximum length of result String, must be positive.
@return truncated String, {@code null} if null String input.
@throws IllegalArgumentException If {@code maxWidth} is less than {@code 0}.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 8,807
|
[
"str",
"maxWidth"
] |
String
| true
| 1
| 6.48
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
replace
|
private static String replace(Map<String, Map<String, Map<String, String>>> lookupsByProvider,
String value,
Pattern pattern) {
if (value == null) {
return null;
}
Matcher matcher = pattern.matcher(value);
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
ConfigVariable configVar = new ConfigVariable(matcher);
Map<String, Map<String, String>> lookupsByPath = lookupsByProvider.get(configVar.providerName);
if (lookupsByPath != null) {
Map<String, String> keyValues = lookupsByPath.get(configVar.path);
String replacement = keyValues.get(configVar.variable);
builder.append(value, i, matcher.start());
if (replacement == null) {
// No replacements will be performed; just return the original value
builder.append(matcher.group(0));
} else {
builder.append(replacement);
}
i = matcher.end();
}
}
builder.append(value, i, value.length());
return builder.toString();
}
|
Transforms the given configuration data by using the {@link ConfigProvider} instances to
look up values to replace the variables in the pattern.
@param configs the configuration values to be transformed
@return an instance of {@link ConfigTransformerResult}
|
java
|
clients/src/main/java/org/apache/kafka/common/config/ConfigTransformer.java
| 133
|
[
"lookupsByProvider",
"value",
"pattern"
] |
String
| true
| 5
| 7.44
|
apache/kafka
| 31,560
|
javadoc
| false
|
wrapperReverse
|
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}
|
This method is the wrapper version of `_.reverse`.
**Note:** This method mutates the wrapped array.
@name reverse
@memberOf _
@since 0.1.0
@category Seq
@returns {Object} Returns the new `lodash` wrapper instance.
@example
var array = [1, 2, 3];
_(array).reverse().value()
// => [3, 2, 1]
console.log(array);
// => [3, 2, 1]
|
javascript
|
lodash.js
| 9,120
|
[] | false
| 3
| 8.72
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
apply
|
@SuppressWarnings("unchecked")
private <R> @Nullable R apply(@Nullable T value, Extractor<T, R> extractor) {
if (skip(value)) {
return (R) SKIP;
}
return (value != null) ? extractor.extract(value) : null;
}
|
Adapt the extracted value.
@param <R> the result type
@param extractor the extractor to use
@return a new {@link ValueExtractor}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
| 731
|
[
"value",
"extractor"
] |
R
| true
| 3
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
_check_pos_label_consistency
|
def _check_pos_label_consistency(pos_label, y_true):
"""Check if `pos_label` need to be specified or not.
In binary classification, we fix `pos_label=1` if the labels are in the set
{-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the
`pos_label` parameters.
Parameters
----------
pos_label : int, float, bool, str or None
The positive label.
y_true : ndarray of shape (n_samples,)
The target vector.
Returns
-------
pos_label : int, float, bool or str
If `pos_label` can be inferred, it will be returned.
Raises
------
ValueError
In the case that `y_true` does not have label in {-1, 1} or {0, 1},
it will raise a `ValueError`.
"""
# ensure binary classification if pos_label is not specified
# classes.dtype.kind in ('O', 'U', 'S') is required to avoid
# triggering a FutureWarning by calling np.array_equal(a, b)
# when elements in the two arrays are not comparable.
if pos_label is None:
# Compute classes only if pos_label is not specified:
xp, _, device = get_namespace_and_device(y_true)
classes = xp.unique_values(y_true)
if (
(_is_numpy_namespace(xp) and classes.dtype.kind in "OUS")
or classes.shape[0] > 2
or not (
xp.all(classes == xp.asarray([0, 1], device=device))
or xp.all(classes == xp.asarray([-1, 1], device=device))
or xp.all(classes == xp.asarray([0], device=device))
or xp.all(classes == xp.asarray([-1], device=device))
or xp.all(classes == xp.asarray([1], device=device))
)
):
classes = _convert_to_numpy(classes, xp=xp)
classes_repr = ", ".join([repr(c) for c in classes.tolist()])
raise ValueError(
f"y_true takes value in {{{classes_repr}}} and pos_label is not "
"specified: either make y_true take value in {0, 1} or "
"{-1, 1} or pass pos_label explicitly."
)
pos_label = 1
return pos_label
|
Check if `pos_label` need to be specified or not.
In binary classification, we fix `pos_label=1` if the labels are in the set
{-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the
`pos_label` parameters.
Parameters
----------
pos_label : int, float, bool, str or None
The positive label.
y_true : ndarray of shape (n_samples,)
The target vector.
Returns
-------
pos_label : int, float, bool or str
If `pos_label` can be inferred, it will be returned.
Raises
------
ValueError
In the case that `y_true` does not have label in {-1, 1} or {0, 1},
it will raise a `ValueError`.
|
python
|
sklearn/utils/validation.py
| 2,541
|
[
"pos_label",
"y_true"
] | false
| 10
| 6.24
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
|
mapShortIDs
|
private static boolean mapShortIDs() {
return SystemProperties.getBoolean(TimeZones.class, "mapShortIDs", () -> true);
}
|
Delegates to {@link TimeZone#getTimeZone(String)}, on Java 25 and up, maps an ID if it's a key in {@link ZoneId#SHORT_IDS}.
<p>
On Java 25, calling {@link TimeZone#getTimeZone(String)} with an ID in {@link ZoneId#SHORT_IDS} writes a message to {@link System#err} in the form:
</p>
<pre>
WARNING: Use of the three-letter time zone ID "the-short-id" is deprecated and it will be removed in a future release
</pre>
<p>
You can disable mapping from {@link ZoneId#SHORT_IDS} by setting the system property {@code "TimeZones.mapShortIDs=false"}.
</p>
@param id Same as {@link TimeZone#getTimeZone(String)}.
@return Same as {@link TimeZone#getTimeZone(String)}.
@since 3.20.0
|
java
|
src/main/java/org/apache/commons/lang3/time/TimeZones.java
| 70
|
[] | true
| 1
| 6.32
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
getProvider
|
public @Nullable TemplateAvailabilityProvider getProvider(String view, ApplicationContext applicationContext) {
Assert.notNull(applicationContext, "'applicationContext' must not be null");
ClassLoader classLoader = applicationContext.getClassLoader();
Assert.state(classLoader != null, "'classLoader' must not be null");
return getProvider(view, applicationContext.getEnvironment(), classLoader, applicationContext);
}
|
Get the provider that can be used to render the given view.
@param view the view to render
@param applicationContext the application context
@return a {@link TemplateAvailabilityProvider} or null
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProviders.java
| 119
|
[
"view",
"applicationContext"
] |
TemplateAvailabilityProvider
| true
| 1
| 6.56
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
obtainInstanceFromSupplier
|
protected @Nullable Object obtainInstanceFromSupplier(Supplier<?> supplier, String beanName, RootBeanDefinition mbd)
throws Exception {
if (supplier instanceof ThrowingSupplier<?> throwingSupplier) {
return throwingSupplier.getWithException();
}
return supplier.get();
}
|
Obtain a bean instance from the given supplier.
@param supplier the configured supplier
@param beanName the corresponding bean name
@param mbd the bean definition for the bean
@return the bean instance (possibly {@code null})
@since 6.0.7
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
| 1,279
|
[
"supplier",
"beanName",
"mbd"
] |
Object
| true
| 2
| 7.92
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
equals
|
@Override
public boolean equals(final Object obj) {
if (obj instanceof MutableByte) {
return value == ((MutableByte) obj).byteValue();
}
return false;
}
|
Compares this object to the specified object. The result is {@code true} if and only if the argument is
not {@code null} and is a {@link MutableByte} object that contains the same {@code byte} value
as this object.
@param obj the object to compare with, null returns false.
@return {@code true} if the objects are the same; {@code false} otherwise.
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableByte.java
| 191
|
[
"obj"
] | true
| 2
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
above
|
public static JavaUnicodeEscaper above(final int codePoint) {
return outsideOf(0, codePoint);
}
|
Constructs a {@link JavaUnicodeEscaper} above the specified value (exclusive).
@param codePoint
above which to escape.
@return the newly created {@link UnicodeEscaper} instance.
|
java
|
src/main/java/org/apache/commons/lang3/text/translate/JavaUnicodeEscaper.java
| 37
|
[
"codePoint"
] |
JavaUnicodeEscaper
| true
| 1
| 6.16
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
jsonNodeToByte
|
public static byte jsonNodeToByte(JsonNode node, String about) {
int value = jsonNodeToInt(node, about);
if (value > Byte.MAX_VALUE) {
if (value <= 256) {
// It's more traditional to refer to bytes as unsigned,
// so we support that here.
value -= 128;
} else {
throw new RuntimeException(about + ": value " + value +
" does not fit in an 8-bit signed integer.");
}
}
if (value < Byte.MIN_VALUE) {
throw new RuntimeException(about + ": value " + value +
" does not fit in an 8-bit signed integer.");
}
return (byte) value;
}
|
Copy a byte buffer into an array. This will not affect the buffer's
position or mark.
|
java
|
clients/src/main/java/org/apache/kafka/common/protocol/MessageUtil.java
| 67
|
[
"node",
"about"
] | true
| 4
| 6
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
hasCause
|
public static boolean hasCause(Throwable chain,
final Class<? extends Throwable> type) {
if (chain instanceof UndeclaredThrowableException) {
chain = chain.getCause();
}
return type.isInstance(chain);
}
|
Tests if the throwable's causal chain have an immediate or wrapped exception
of the given type?
@param chain
The root of a Throwable causal chain.
@param type
The exception type to test.
@return true, if chain is an instance of type or is an
UndeclaredThrowableException wrapping a cause.
@since 3.5
@see #wrapAndThrow(Throwable)
|
java
|
src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
| 558
|
[
"chain",
"type"
] | true
| 2
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
getProperty
|
@Override
public Object getProperty(List<String> path) {
if (path.isEmpty()) {
return this;
} else if (path.size() == 1 && "value".equals(path.get(0))) {
return value();
} else if (path.size() == 1 && "normalized_value".equals(path.get(0))) {
return normalizedValue();
} else {
throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path);
}
}
|
Returns the normalized value. If no normalised factor has been specified
this method will return {@link #value()}
@return the normalized value
|
java
|
modules/aggregations/src/main/java/org/elasticsearch/aggregations/pipeline/Derivative.java
| 68
|
[
"path"
] |
Object
| true
| 6
| 6.56
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
cancelRemainingTasksOnClose
|
public SimpleAsyncTaskExecutorBuilder cancelRemainingTasksOnClose(boolean cancelRemainingTasksOnClose) {
return new SimpleAsyncTaskExecutorBuilder(this.virtualThreads, this.threadNamePrefix,
cancelRemainingTasksOnClose, this.rejectTasksWhenLimitReached, this.concurrencyLimit,
this.taskDecorator, this.customizers, this.taskTerminationTimeout);
}
|
Set whether to cancel remaining tasks on close. By default {@code false} not
tracking active threads at all or just interrupting any remaining threads that
still have not finished after the specified
{@link #taskTerminationTimeout(Duration) taskTerminationTimeout}. Switch this to
{@code true} for immediate interruption on close, either in combination with a
subsequent termination timeout or without any waiting at all, depending on whether
a {@code taskTerminationTimeout} has been specified as well.
@param cancelRemainingTasksOnClose whether to cancel remaining tasks on close
@return a new builder instance
@since 4.0.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/task/SimpleAsyncTaskExecutorBuilder.java
| 119
|
[
"cancelRemainingTasksOnClose"
] |
SimpleAsyncTaskExecutorBuilder
| true
| 1
| 6.24
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
nunique
|
def nunique(x: Array, /, *, xp: ModuleType | None = None) -> Array:
"""
Count the number of unique elements in an array.
Compatible with JAX and Dask, whose laziness would be otherwise
problematic.
Parameters
----------
x : Array
Input array.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
array: 0-dimensional integer array
The number of unique elements in `x`. It can be lazy.
"""
if xp is None:
xp = array_namespace(x)
if is_jax_array(x):
# size= is JAX-specific
# https://github.com/data-apis/array-api/issues/883
_, counts = xp.unique_counts(x, size=_compat.size(x))
return (counts > 0).sum()
# There are 3 general use cases:
# 1. backend has unique_counts and it returns an array with known shape
# 2. backend has unique_counts and it returns a None-sized array;
# e.g. Dask, ndonnx
# 3. backend does not have unique_counts; e.g. wrapped JAX
if capabilities(xp, device=_compat.device(x))["data-dependent shapes"]:
# xp has unique_counts; O(n) complexity
_, counts = xp.unique_counts(x)
n = _compat.size(counts)
if n is None:
return xp.sum(xp.ones_like(counts))
return xp.asarray(n, device=_compat.device(x))
# xp does not have unique_counts; O(n*logn) complexity
x = xp.reshape(x, (-1,))
x = xp.sort(x)
mask = x != xp.roll(x, -1)
default_int = default_dtype(xp, "integral", device=_compat.device(x))
return xp.maximum(
# Special cases:
# - array is size 0
# - array has all elements equal to each other
xp.astype(xp.any(~mask), default_int),
xp.sum(xp.astype(mask, default_int)),
)
|
Count the number of unique elements in an array.
Compatible with JAX and Dask, whose laziness would be otherwise
problematic.
Parameters
----------
x : Array
Input array.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
array: 0-dimensional integer array
The number of unique elements in `x`. It can be lazy.
|
python
|
sklearn/externals/array_api_extra/_lib/_funcs.py
| 782
|
[
"x",
"xp"
] |
Array
| true
| 5
| 6.72
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
get_or_create_worker
|
def get_or_create_worker(self, hostname, **kwargs):
"""Get or create worker by hostname.
Returns:
Tuple: of ``(worker, was_created)`` pairs.
"""
try:
worker = self.workers[hostname]
if kwargs:
worker.update(kwargs)
return worker, False
except KeyError:
worker = self.workers[hostname] = self.Worker(
hostname, **kwargs)
return worker, True
|
Get or create worker by hostname.
Returns:
Tuple: of ``(worker, was_created)`` pairs.
|
python
|
celery/events/state.py
| 477
|
[
"self",
"hostname"
] | false
| 2
| 6.64
|
celery/celery
| 27,741
|
unknown
| false
|
|
_copy_metadata_to_bw_nodes_in_subgraph
|
def _copy_metadata_to_bw_nodes_in_subgraph(
fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node]
) -> None:
"""Copy metadata from forward nodes to backward nodes in a single subgraph."""
for node in fx_g.graph.nodes:
annotation_log.debug("node: %s", node.name)
seq_nr = node.meta.get("seq_nr")
annotation_log.debug("seq_nr: %s", seq_nr)
if not _is_backward_node_with_seq_nr(node):
continue
# We exclude gradient accumulation nodes from copying tags
if node.meta.get("is_gradient_acc", False):
annotation_log.debug("is_gradient_acc")
continue
# fwd_node should always exist, but handle non-existence just in case
fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"])
if fwd_node is not None:
node.meta["fwd_nn_module_stack"] = fwd_node.meta.get("nn_module_stack")
node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack")
# TODO: better to change to a specific field of custom?
custom = fwd_node.meta.get("custom")
if custom is not None:
node.meta["custom"] = copy.deepcopy(custom)
|
Copy metadata from forward nodes to backward nodes in a single subgraph.
|
python
|
torch/_functorch/_aot_autograd/utils.py
| 579
|
[
"fx_g",
"fwd_seq_nr_to_node"
] |
None
| true
| 6
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
lazyUv
|
function lazyUv() {
uvBinding ??= internalBinding('uv');
return uvBinding;
}
|
This function removes unnecessary frames from Node.js core errors.
@template {(...args: unknown[]) => unknown} T
@param {T} fn
@returns {T}
|
javascript
|
lib/internal/errors.js
| 622
|
[] | false
| 1
| 6
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
readLine
|
@CanIgnoreReturnValue // to skip a line
public @Nullable String readLine() throws IOException {
while (lines.peek() == null) {
Java8Compatibility.clear(cbuf);
// The default implementation of Reader#read(CharBuffer) allocates a
// temporary char[], so we call Reader#read(char[], int, int) instead.
int read = (reader != null) ? reader.read(buf, 0, buf.length) : readable.read(cbuf);
if (read == -1) {
lineBuf.finish();
break;
}
lineBuf.add(buf, 0, read);
}
return lines.poll();
}
|
Reads a line of text. A line is considered to be terminated by any one of a line feed ({@code
'\n'}), a carriage return ({@code '\r'}), or a carriage return followed immediately by a
linefeed ({@code "\r\n"}).
@return a {@code String} containing the contents of the line, not including any
line-termination characters, or {@code null} if the end of the stream has been reached.
@throws IOException if an I/O error occurs
|
java
|
android/guava/src/com/google/common/io/LineReader.java
| 70
|
[] |
String
| true
| 4
| 8.24
|
google/guava
| 51,352
|
javadoc
| false
|
asMap
|
public Map<K, Long> asMap() {
Map<K, Long> result = asMap;
return (result == null) ? asMap = createAsMap() : result;
}
|
Returns a live, read-only view of the map backing this {@code AtomicLongMap}.
|
java
|
android/guava/src/com/google/common/util/concurrent/AtomicLongMap.java
| 332
|
[] | true
| 2
| 6.64
|
google/guava
| 51,352
|
javadoc
| false
|
|
putIfAbsent
|
@Override
public @Nullable ValueWrapper putIfAbsent(Object key, @Nullable Object value) {
Object previous = this.cache.invoke(key, PutIfAbsentEntryProcessor.INSTANCE, toStoreValue(value));
return (previous != null ? toValueWrapper(previous) : null);
}
|
Create a {@code JCacheCache} instance.
@param jcache backing JCache Cache instance
@param allowNullValues whether to accept and convert null values for this cache
|
java
|
spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java
| 102
|
[
"key",
"value"
] |
ValueWrapper
| true
| 2
| 6.4
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
computeCostFor
|
unsigned computeCostFor(const BinaryFunction &BF,
const PredicateTy &SkipPredicate,
const SchedulingPolicy &SchedPolicy) {
if (SchedPolicy == SchedulingPolicy::SP_TRIVIAL)
return 1;
if (SkipPredicate && SkipPredicate(BF))
return 0;
switch (SchedPolicy) {
case SchedulingPolicy::SP_CONSTANT:
return 1;
case SchedulingPolicy::SP_INST_LINEAR:
return BF.getSize();
case SchedulingPolicy::SP_INST_QUADRATIC:
return BF.getSize() * BF.getSize();
case SchedulingPolicy::SP_BB_LINEAR:
return BF.size();
case SchedulingPolicy::SP_BB_QUADRATIC:
return BF.size() * BF.size();
default:
llvm_unreachable("unsupported scheduling policy");
}
}
|
A single thread pool that is used to run parallel tasks
|
cpp
|
bolt/lib/Core/ParallelUtilities.cpp
| 54
|
[] | true
| 10
| 6.4
|
llvm/llvm-project
| 36,021
|
doxygen
| false
|
|
make_report
|
def make_report() -> list[Query]:
"""
Returns a list of Query objects that are expected to be run during the performance run.
"""
queries = []
with open(LOG_FILE, "r+") as f:
raw_queries = [line for line in f.readlines() if is_query(line)]
for query in raw_queries:
time, info, stack, sql = query.replace("@SQLALCHEMY ", "").split("|$")
func, file, loc = info.split(":")
file_name = file.rpartition("/")[-1]
queries.append(
Query(
function=func.strip(),
file=file_name.strip(),
location=int(loc.strip()),
sql=sql.strip(),
stack=stack.strip(),
time=float(time.strip()),
)
)
return queries
|
Returns a list of Query objects that are expected to be run during the performance run.
|
python
|
dev/airflow_perf/sql_queries.py
| 142
|
[] |
list[Query]
| true
| 2
| 7.04
|
apache/airflow
| 43,597
|
unknown
| false
|
appendExportsOfDeclaration
|
function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, excludeName?: string): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
const name = factory.getDeclarationName(decl);
const exportSpecifiers = moduleInfo.exportSpecifiers.get(name);
if (exportSpecifiers) {
for (const exportSpecifier of exportSpecifiers) {
if (moduleExportNameTextUnescaped(exportSpecifier.name) !== excludeName) {
statements = appendExportStatement(statements, exportSpecifier.name, name);
}
}
}
return statements;
}
|
Appends the exports of a declaration to a statement list, returning the statement list.
@param statements A statement list to which the down-level export statements are to be
appended. If `statements` is `undefined`, a new array is allocated if statements are
appended.
@param decl The declaration to export.
@param excludeName An optional name to exclude from exports.
|
typescript
|
src/compiler/transformers/module/system.ts
| 1,160
|
[
"statements",
"decl",
"excludeName?"
] | true
| 4
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
visitTopLevelImportDeclaration
|
function visitTopLevelImportDeclaration(node: ImportDeclaration): VisitResult<Statement | undefined> {
let statements: Statement[] | undefined;
const namespaceDeclaration = getNamespaceDeclarationNode(node) as NamespaceImport | undefined;
if (moduleKind !== ModuleKind.AMD) {
if (!node.importClause) {
// import "mod";
return setOriginalNode(setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
}
else {
const variables: VariableDeclaration[] = [];
if (namespaceDeclaration && !isDefaultImport(node)) {
// import * as n from "mod";
variables.push(
factory.createVariableDeclaration(
factory.cloneNode(namespaceDeclaration.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
getHelperExpressionForImport(node, createRequireCall(node)),
),
);
}
else {
// import d from "mod";
// import { x, y } from "mod";
// import d, { x, y } from "mod";
// import d, * as n from "mod";
variables.push(
factory.createVariableDeclaration(
factory.getGeneratedNameForNode(node),
/*exclamationToken*/ undefined,
/*type*/ undefined,
getHelperExpressionForImport(node, createRequireCall(node)),
),
);
if (namespaceDeclaration && isDefaultImport(node)) {
variables.push(
factory.createVariableDeclaration(
factory.cloneNode(namespaceDeclaration.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.getGeneratedNameForNode(node),
),
);
}
}
statements = append(
statements,
setOriginalNode(
setTextRange(
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList(
variables,
languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None,
),
),
/*location*/ node,
),
/*original*/ node,
),
);
}
}
else if (namespaceDeclaration && isDefaultImport(node)) {
// import d, * as n from "mod";
statements = append(
statements,
factory.createVariableStatement(
/*modifiers*/ undefined,
factory.createVariableDeclarationList(
[
setOriginalNode(
setTextRange(
factory.createVariableDeclaration(
factory.cloneNode(namespaceDeclaration.name),
/*exclamationToken*/ undefined,
/*type*/ undefined,
factory.getGeneratedNameForNode(node),
),
/*location*/ node,
),
/*original*/ node,
),
],
languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None,
),
),
);
}
statements = appendExportsOfImportDeclaration(statements, node);
return singleOrMany(statements);
}
|
Visits an ImportDeclaration node.
@param node The node to visit.
|
typescript
|
src/compiler/transformers/module/module.ts
| 1,437
|
[
"node"
] | true
| 14
| 6.64
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
thresholdMapper
|
private @Nullable String thresholdMapper(@Nullable String input) {
// YAML converts an unquoted OFF to false
if ("false".equals(input)) {
return "OFF";
}
return input;
}
|
Returns the default file charset.
@return the default file charset
@since 3.5.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java
| 206
|
[
"input"
] |
String
| true
| 2
| 7.2
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
handleChannelMuteEvent
|
public void handleChannelMuteEvent(ChannelMuteEvent event) {
boolean stateChanged = false;
switch (event) {
case REQUEST_RECEIVED:
if (muteState == ChannelMuteState.MUTED) {
muteState = ChannelMuteState.MUTED_AND_RESPONSE_PENDING;
stateChanged = true;
}
break;
case RESPONSE_SENT:
if (muteState == ChannelMuteState.MUTED_AND_RESPONSE_PENDING) {
muteState = ChannelMuteState.MUTED;
stateChanged = true;
}
if (muteState == ChannelMuteState.MUTED_AND_THROTTLED_AND_RESPONSE_PENDING) {
muteState = ChannelMuteState.MUTED_AND_THROTTLED;
stateChanged = true;
}
break;
case THROTTLE_STARTED:
if (muteState == ChannelMuteState.MUTED_AND_RESPONSE_PENDING) {
muteState = ChannelMuteState.MUTED_AND_THROTTLED_AND_RESPONSE_PENDING;
stateChanged = true;
}
break;
case THROTTLE_ENDED:
if (muteState == ChannelMuteState.MUTED_AND_THROTTLED) {
muteState = ChannelMuteState.MUTED;
stateChanged = true;
}
if (muteState == ChannelMuteState.MUTED_AND_THROTTLED_AND_RESPONSE_PENDING) {
muteState = ChannelMuteState.MUTED_AND_RESPONSE_PENDING;
stateChanged = true;
}
}
if (!stateChanged) {
throw new IllegalStateException("Cannot transition from " + muteState.name() + " for " + event.name());
}
}
|
Unmute the channel. The channel can be unmuted only if it is in the MUTED state. For other muted states
(MUTED_AND_*), this is a no-op.
@return Whether or not the channel is in the NOT_MUTED state after the call
|
java
|
clients/src/main/java/org/apache/kafka/common/network/KafkaChannel.java
| 274
|
[
"event"
] |
void
| true
| 8
| 7.04
|
apache/kafka
| 31,560
|
javadoc
| false
|
fchown
|
function fchown(fd, uid, gid, callback) {
validateInteger(uid, 'uid', -1, kMaxUserId);
validateInteger(gid, 'gid', -1, kMaxUserId);
callback = makeCallback(callback);
if (permission.isEnabled()) {
callback(new ERR_ACCESS_DENIED('fchown API is disabled when Permission Model is enabled.'));
return;
}
const req = new FSReqCallback();
req.oncomplete = callback;
binding.fchown(fd, uid, gid, req);
}
|
Sets the owner of the file.
@param {number} fd
@param {number} uid
@param {number} gid
@param {(err?: Error) => any} callback
@returns {void}
|
javascript
|
lib/fs.js
| 2,072
|
[
"fd",
"uid",
"gid",
"callback"
] | false
| 2
| 6.08
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
listPartitionReassignments
|
default ListPartitionReassignmentsResult listPartitionReassignments(
Set<TopicPartition> partitions,
ListPartitionReassignmentsOptions options) {
return listPartitionReassignments(Optional.of(partitions), options);
}
|
List the current reassignments for the given partitions
<p>The following exceptions can be anticipated when calling {@code get()} on the futures obtained from
the returned {@code ListPartitionReassignmentsResult}:</p>
<ul>
<li>{@link org.apache.kafka.common.errors.ClusterAuthorizationException}
If the authenticated user doesn't have alter access to the cluster.</li>
<li>{@link org.apache.kafka.common.errors.UnknownTopicOrPartitionException}
If a given topic or partition does not exist.</li>
<li>{@link org.apache.kafka.common.errors.TimeoutException}
If the request timed out before the controller could list the current reassignments.</li>
</ul>
@param partitions The topic partitions to list reassignments for.
@param options The options to use.
@return The result.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 1,223
|
[
"partitions",
"options"
] |
ListPartitionReassignmentsResult
| true
| 1
| 6.24
|
apache/kafka
| 31,560
|
javadoc
| false
|
_with_freq
|
def _with_freq(self, freq) -> Self:
"""
Helper to get a view on the same data, with a new freq.
Parameters
----------
freq : DateOffset, None, or "infer"
Returns
-------
Same type as self
"""
# GH#29843
if freq is None:
# Always valid
pass
elif len(self) == 0 and isinstance(freq, BaseOffset):
# Always valid. In the TimedeltaArray case, we require a Tick offset
if self.dtype.kind == "m" and not isinstance(freq, (Tick, Day)):
raise TypeError("TimedeltaArray/Index freq must be a Tick")
else:
# As an internal method, we can ensure this assertion always holds
assert freq == "infer"
freq = to_offset(self.inferred_freq)
arr = self.view()
arr._freq = freq
return arr
|
Helper to get a view on the same data, with a new freq.
Parameters
----------
freq : DateOffset, None, or "infer"
Returns
-------
Same type as self
|
python
|
pandas/core/arrays/datetimelike.py
| 2,441
|
[
"self",
"freq"
] |
Self
| true
| 7
| 6.88
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
resolve
|
Stream<PropertyDescriptor> resolve(TypeElement type, ExecutableElement factoryMethod) {
TypeElementMembers members = new TypeElementMembers(this.environment, type);
if (factoryMethod != null) {
return resolveJavaBeanProperties(type, members, factoryMethod);
}
return resolve(Bindable.of(type, this.environment), members);
}
|
Return the {@link PropertyDescriptor} instances that are valid candidates for the
specified {@link TypeElement type} based on the specified {@link ExecutableElement
factory method}, if any.
@param type the target type
@param factoryMethod the method that triggered the metadata for that {@code type}
or {@code null}
@return the candidate properties for metadata generation
|
java
|
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java
| 61
|
[
"type",
"factoryMethod"
] | true
| 2
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
timeToNextHeartbeat
|
protected synchronized long timeToNextHeartbeat(long now) {
// if we have not joined the group or we are preparing rebalance,
// we don't need to send heartbeats
if (state.hasNotJoinedGroup())
return Long.MAX_VALUE;
if (heartbeatThread != null && heartbeatThread.isFailed()) {
// if an exception occurs in the heartbeat thread, raise it.
throw heartbeatThread.failureCause();
}
return heartbeat.timeToNextHeartbeat(now);
}
|
Check the status of the heartbeat thread (if it is active) and indicate the liveness
of the client. This must be called periodically after joining with {@link #ensureActiveGroup()}
to ensure that the member stays in the group. If an interval of time longer than the
provided rebalance timeout expires without calling this method, then the client will proactively
leave the group.
@param now current time in milliseconds
@throws RuntimeException for unexpected errors raised from the heartbeat thread
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractCoordinator.java
| 385
|
[
"now"
] | true
| 4
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
format
|
public static String format(final long millis, final String pattern) {
return format(new Date(millis), pattern, null, null);
}
|
Formats a date/time into a specific pattern.
@param millis the date to format expressed in milliseconds.
@param pattern the pattern to use to format the date, not null.
@return the formatted date.
|
java
|
src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java
| 315
|
[
"millis",
"pattern"
] |
String
| true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
trimResults
|
public Splitter trimResults() {
return trimResults(CharMatcher.whitespace());
}
|
Returns a splitter that behaves equivalently to {@code this} splitter, but automatically
removes leading and trailing {@linkplain CharMatcher#whitespace whitespace} from each returned
substring; equivalent to {@code trimResults(CharMatcher.whitespace())}. For example, {@code
Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable containing {@code ["a",
"b", "c"]}.
@return a splitter with the desired configuration
|
java
|
android/guava/src/com/google/common/base/Splitter.java
| 340
|
[] |
Splitter
| true
| 1
| 6.16
|
google/guava
| 51,352
|
javadoc
| false
|
name
|
def name(self) -> Hashable:
"""
Return the name of the Series.
The name of a Series becomes its index or column name if it is used
to form a DataFrame. It is also used whenever displaying the Series
using the interpreter.
Returns
-------
label (hashable object)
The name of the Series, also the column name if part of a DataFrame.
See Also
--------
Series.rename : Sets the Series name when given a scalar input.
Index.name : Corresponding Index property.
Examples
--------
The Series name can be set initially when calling the constructor.
>>> s = pd.Series([1, 2, 3], dtype=np.int64, name="Numbers")
>>> s
0 1
1 2
2 3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0 1
1 2
2 3
Name: Integers, dtype: int64
The name of a Series within a DataFrame is its column name.
>>> df = pd.DataFrame(
... [[1, 2], [3, 4], [5, 6]], columns=["Odd Numbers", "Even Numbers"]
... )
>>> df
Odd Numbers Even Numbers
0 1 2
1 3 4
2 5 6
>>> df["Even Numbers"].name
'Even Numbers'
"""
return self._name
|
Return the name of the Series.
The name of a Series becomes its index or column name if it is used
to form a DataFrame. It is also used whenever displaying the Series
using the interpreter.
Returns
-------
label (hashable object)
The name of the Series, also the column name if part of a DataFrame.
See Also
--------
Series.rename : Sets the Series name when given a scalar input.
Index.name : Corresponding Index property.
Examples
--------
The Series name can be set initially when calling the constructor.
>>> s = pd.Series([1, 2, 3], dtype=np.int64, name="Numbers")
>>> s
0 1
1 2
2 3
Name: Numbers, dtype: int64
>>> s.name = "Integers"
>>> s
0 1
1 2
2 3
Name: Integers, dtype: int64
The name of a Series within a DataFrame is its column name.
>>> df = pd.DataFrame(
... [[1, 2], [3, 4], [5, 6]], columns=["Odd Numbers", "Even Numbers"]
... )
>>> df
Odd Numbers Even Numbers
0 1 2
1 3 4
2 5 6
>>> df["Even Numbers"].name
'Even Numbers'
|
python
|
pandas/core/series.py
| 695
|
[
"self"
] |
Hashable
| true
| 1
| 7.28
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
setLogLevel
|
private void setLogLevel(@Nullable String loggerName, @Nullable Level level) {
LoggerConfig logger = getLogger(loggerName);
if (level == null) {
clearLogLevel(loggerName, logger);
}
else {
setLogLevel(loggerName, logger, level);
}
getLoggerContext().updateLoggers();
}
|
Return the configuration location. The result may be:
<ul>
<li>{@code null}: if DefaultConfiguration is used (no explicit config loaded)</li>
<li>A file path: if provided explicitly by the user</li>
<li>A URI: if loaded from the classpath default or a custom location</li>
</ul>
@param configuration the source configuration
@return the config location or {@code null}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java
| 357
|
[
"loggerName",
"level"
] |
void
| true
| 2
| 7.28
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
createProperties
|
protected Properties createProperties() throws IOException {
return mergeProperties();
}
|
Template method that subclasses may override to construct the object
returned by this factory. The default implementation returns the
plain merged Properties instance.
<p>Invoked on initialization of this FactoryBean in case of a
shared singleton; else, on each {@link #getObject()} call.
@return the object returned by this factory
@throws IOException if an exception occurred during properties loading
@see #mergeProperties()
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/config/PropertiesFactoryBean.java
| 103
|
[] |
Properties
| true
| 1
| 6.16
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
zeros_like
|
def zeros_like(
a, dtype=None, order='K', subok=True, shape=None, *, device=None
):
"""
Return an array of zeros with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
order : {'C', 'F', 'A', or 'K'}, optional
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible.
subok : bool, optional.
If True, then the newly created array will use the sub-class
type of `a`, otherwise it will be a base-class array. Defaults
to True.
shape : int or sequence of ints, optional.
Overrides the shape of the result. If order='K' and the number of
dimensions is unchanged, will try to keep order, otherwise,
order='C' is implied.
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
Array of zeros with the same shape and type as `a`.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
full_like : Return a new array with shape of input filled with value.
zeros : Return a new array setting values to zero.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.zeros_like(x)
array([[0, 0, 0],
[0, 0, 0]])
>>> y = np.arange(3, dtype=np.float64)
>>> y
array([0., 1., 2.])
>>> np.zeros_like(y)
array([0., 0., 0.])
"""
res = empty_like(
a, dtype=dtype, order=order, subok=subok, shape=shape, device=device
)
# needed instead of a 0 to get same result as zeros for string dtypes
z = zeros(1, dtype=res.dtype)
multiarray.copyto(res, z, casting='unsafe')
return res
|
Return an array of zeros with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
order : {'C', 'F', 'A', or 'K'}, optional
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible.
subok : bool, optional.
If True, then the newly created array will use the sub-class
type of `a`, otherwise it will be a base-class array. Defaults
to True.
shape : int or sequence of ints, optional.
Overrides the shape of the result. If order='K' and the number of
dimensions is unchanged, will try to keep order, otherwise,
order='C' is implied.
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
Array of zeros with the same shape and type as `a`.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
full_like : Return a new array with shape of input filled with value.
zeros : Return a new array setting values to zero.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.zeros_like(x)
array([[0, 0, 0],
[0, 0, 0]])
>>> y = np.arange(3, dtype=np.float64)
>>> y
array([0., 1., 2.])
>>> np.zeros_like(y)
array([0., 0., 0.])
|
python
|
numpy/_core/numeric.py
| 98
|
[
"a",
"dtype",
"order",
"subok",
"shape",
"device"
] | false
| 1
| 6.56
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
_get_libstdcxx_args
|
def _get_libstdcxx_args() -> tuple[list[str], list[str]]:
"""
For fbcode cpu case, we should link stdc++ instead assuming the binary where dlopen is executed is built with dynamic stdc++.
"""
lib_dir_paths: list[str] = []
libs: list[str] = []
if config.is_fbcode():
lib_dir_paths = [sysconfig.get_config_var("LIBDIR")]
libs.append("stdc++")
return lib_dir_paths, libs
|
For fbcode cpu case, we should link stdc++ instead assuming the binary where dlopen is executed is built with dynamic stdc++.
|
python
|
torch/_inductor/cpp_builder.py
| 1,413
|
[] |
tuple[list[str], list[str]]
| true
| 2
| 6.88
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
evalTypeScriptModuleEntryPoint
|
function evalTypeScriptModuleEntryPoint(source, print) {
if (print) {
throw new ERR_EVAL_ESM_CANNOT_PRINT();
}
RegExpPrototypeExec(/^/, ''); // Necessary to reset RegExp statics before user code runs.
return require('internal/modules/run_main').runEntryPointWithESMLoader(
async (loader) => {
const url = getEvalModuleUrl();
let moduleWrap;
try {
// Compile the module to check for syntax errors.
moduleWrap = loader.createModuleWrap(source, url);
} catch (originalError) {
try {
const strippedSource = stripTypeScriptModuleTypes(source, kEvalTag);
// If the moduleWrap was successfully created, execute the module job.
// outside the try-catch block to avoid catching runtime errors.
moduleWrap = loader.createModuleWrap(strippedSource, url);
} catch (tsError) {
// If it's invalid or unsupported TypeScript syntax, rethrow the original error
// with the TypeScript error message added to the stack.
if (tsError.code === 'ERR_INVALID_TYPESCRIPT_SYNTAX' ||
tsError.code === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX') {
originalError.stack = `${tsError.message}\n\n${originalError.stack}`;
throw originalError;
}
throw tsError;
}
}
// If the moduleWrap was successfully created either with by just compiling
// or after transpilation, execute the module job.
return loader.executeModuleJob(url, moduleWrap, true);
},
);
}
|
Wrapper of evalModuleEntryPoint
This function wraps the compilation of the source code in a try-catch block.
If the source code fails to be compiled, it will retry transpiling the source code
with the TypeScript parser.
@param {string} source The source code to evaluate
@param {boolean} print If the result should be printed
@returns {Promise} The module evaluation promise
|
javascript
|
lib/internal/process/execution.js
| 308
|
[
"source",
"print"
] | false
| 6
| 6.08
|
nodejs/node
| 114,839
|
jsdoc
| true
|
|
parse
|
@Override
public Value parse(XContentParser parser, Context context) throws IOException {
return parse(parser, valueBuilder.apply(context), context);
}
|
Parses a Value from the given {@link XContentParser}
@param parser the parser to build a value from
@param context context needed for parsing
@return a new value instance drawn from the provided value supplier on {@link #ObjectParser(String, Supplier)}
@throws IOException if an IOException occurs.
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java
| 258
|
[
"parser",
"context"
] |
Value
| true
| 1
| 6.32
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
stableSort
|
public static void stableSort(TDigestIntArray order, TDigestDoubleArray values, int n) {
for (int i = 0; i < n; i++) {
order.set(i, i);
}
stableQuickSort(order, values, 0, n, 64);
stableInsertionSort(order, values, 0, n, 64);
}
|
Single-key stabilized quick sort on using an index array
@param order Indexes into values
@param values The values to sort.
@param n The number of values to sort
|
java
|
libs/tdigest/src/main/java/org/elasticsearch/tdigest/Sort.java
| 42
|
[
"order",
"values",
"n"
] |
void
| true
| 2
| 6.72
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
round_
|
def round_(a, decimals=0, out=None):
"""
Return a copy of a, rounded to 'decimals' places.
When 'decimals' is negative, it specifies the number of positions
to the left of the decimal point. The real and imaginary parts of
complex numbers are rounded separately. Nothing is done if the
array is not of float type and 'decimals' is greater than or equal
to 0.
Parameters
----------
decimals : int
Number of decimals to round to. May be negative.
out : array_like
Existing array to use for output.
If not given, returns a default copy of a.
Notes
-----
If out is given and does not have a mask attribute, the mask of a
is lost!
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x)
masked_array(data=[11.0, -4.0, 1.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round(masked_x, decimals=1)
masked_array(data=[11.2, -4.0, 0.8, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x, decimals=-1)
masked_array(data=[10.0, -0.0, 0.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
"""
if out is None:
return np.round(a, decimals, out)
else:
np.round(getdata(a), decimals, out)
if hasattr(out, '_mask'):
out._mask = getmask(a)
return out
|
Return a copy of a, rounded to 'decimals' places.
When 'decimals' is negative, it specifies the number of positions
to the left of the decimal point. The real and imaginary parts of
complex numbers are rounded separately. Nothing is done if the
array is not of float type and 'decimals' is greater than or equal
to 0.
Parameters
----------
decimals : int
Number of decimals to round to. May be negative.
out : array_like
Existing array to use for output.
If not given, returns a default copy of a.
Notes
-----
If out is given and does not have a mask attribute, the mask of a
is lost!
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x)
masked_array(data=[11.0, -4.0, 1.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round(masked_x, decimals=1)
masked_array(data=[11.2, -4.0, 0.8, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x, decimals=-1)
masked_array(data=[10.0, -0.0, 0.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
|
python
|
numpy/ma/core.py
| 8,081
|
[
"a",
"decimals",
"out"
] | false
| 4
| 7.68
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
poll
|
@Override
public ConsumerRecords<K, V> poll(Duration timeout) {
return delegate.poll(timeout);
}
|
Deliver records for the topics specified using {@link #subscribe(Collection)}. It is an error to not have
subscribed to any topics before polling for data.
<p>
This method returns immediately if there are records available. Otherwise, it will await the passed timeout.
If the timeout expires, an empty record set will be returned.
@param timeout The maximum time to block (must not be greater than {@link Long#MAX_VALUE} milliseconds)
@return map of topic to records
@throws AuthenticationException if authentication fails. See the exception for more details
@throws AuthorizationException if caller lacks Read access to any of the subscribed
topics or to the share group. See the exception for more details
@throws IllegalArgumentException if the timeout value is negative
@throws IllegalStateException if the consumer is not subscribed to any topics, or it is using
explicit acknowledgement and has not acknowledged all records previously delivered
@throws ArithmeticException if the timeout is greater than {@link Long#MAX_VALUE} milliseconds.
@throws InvalidTopicException if the current subscription contains any invalid
topic (per {@link org.apache.kafka.common.internals.Topic#validate(String)})
@throws WakeupException if {@link #wakeup()} is called before or while this method is called
@throws InterruptException if the calling thread is interrupted before or while this method is called
@throws KafkaException for any other unrecoverable errors
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/KafkaShareConsumer.java
| 554
|
[
"timeout"
] | true
| 1
| 6.16
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
encode_log_result
|
def encode_log_result(log_result: str, *, keep_empty_lines: bool = True) -> list[str] | None:
"""
Encode execution log from the response and return list of log records.
Returns ``None`` on error, e.g. invalid base64-encoded string
:param log_result: base64-encoded string which contain Lambda execution Log.
:param keep_empty_lines: Whether or not keep empty lines.
"""
encoded_log_result = base64.b64decode(log_result.encode("ascii")).decode()
return [log_row for log_row in encoded_log_result.splitlines() if keep_empty_lines or log_row]
|
Encode execution log from the response and return list of log records.
Returns ``None`` on error, e.g. invalid base64-encoded string
:param log_result: base64-encoded string which contain Lambda execution Log.
:param keep_empty_lines: Whether or not keep empty lines.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/lambda_function.py
| 199
|
[
"log_result",
"keep_empty_lines"
] |
list[str] | None
| true
| 2
| 6.72
|
apache/airflow
| 43,597
|
sphinx
| false
|
failure_message_from_response
|
def failure_message_from_response(response: dict[str, Any]) -> str | None:
"""
Get failure message from response dictionary.
:param response: response from AWS API
:return: failure message
"""
cluster_status = response["Cluster"]["Status"]
state_change_reason = cluster_status.get("StateChangeReason")
if state_change_reason:
return (
f"for code: {state_change_reason.get('Code', 'No code')} "
f"with message {state_change_reason.get('Message', 'Unknown')}"
)
return None
|
Get failure message from response dictionary.
:param response: response from AWS API
:return: failure message
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py
| 501
|
[
"response"
] |
str | None
| true
| 2
| 7.76
|
apache/airflow
| 43,597
|
sphinx
| false
|
contains
|
public static boolean contains(boolean[] array, boolean target) {
for (boolean value : array) {
if (value == target) {
return true;
}
}
return false;
}
|
Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
<p><b>Note:</b> consider representing the array as a {@link java.util.BitSet} instead,
replacing {@code Booleans.contains(array, true)} with {@code !bitSet.isEmpty()} and {@code
Booleans.contains(array, false)} with {@code bitSet.nextClearBit(0) == sizeOfBitSet}.
@param array an array of {@code boolean} values, possibly empty
@param target a primitive {@code boolean} value
@return {@code true} if {@code array[i] == target} for some value of {@code i}
|
java
|
android/guava/src/com/google/common/primitives/Booleans.java
| 141
|
[
"array",
"target"
] | true
| 2
| 7.6
|
google/guava
| 51,352
|
javadoc
| false
|
|
noneMatcher
|
public static StrMatcher noneMatcher() {
return NONE_MATCHER;
}
|
Gets the matcher for no characters.
@return the matcher that matches nothing.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrMatcher.java
| 304
|
[] |
StrMatcher
| true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
trySubstituteClassAlias
|
function trySubstituteClassAlias(node: Identifier): Expression | undefined {
if (enabledSubstitutions & ClassPropertySubstitutionFlags.ClassAliases) {
if (resolver.hasNodeCheckFlag(node, NodeCheckFlags.ConstructorReference)) {
// Due to the emit for class decorators, any reference to the class from inside of the class body
// must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
// behavior of class names in ES6.
// Also, when emitting statics for class expressions, we must substitute a class alias for
// constructor references in static property initializers.
const declaration = resolver.getReferencedValueDeclaration(node);
if (declaration) {
const classAlias = classAliases[declaration.id!]; // TODO: GH#18217
if (classAlias) {
const clone = factory.cloneNode(classAlias);
setSourceMapRange(clone, node);
setCommentRange(clone, node);
return clone;
}
}
}
}
return undefined;
}
|
Hooks node substitutions.
@param hint The context for the emitter.
@param node The node to substitute.
|
typescript
|
src/compiler/transformers/classFields.ts
| 3,293
|
[
"node"
] | true
| 5
| 7.04
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
addAndGet
|
public <T> T addAndGet(final CompletableApplicationEvent<T> event) {
Objects.requireNonNull(event, "CompletableApplicationEvent provided to addAndGet must be non-null");
add(event);
// Check if the thread was interrupted before we start waiting, to ensure that we
// propagate the exception even if we end up not having to wait (the event could complete
// between the time it's added and the time we attempt to getResult)
if (Thread.interrupted()) {
throw new InterruptException("Interrupted waiting for results for application event " + event);
}
return ConsumerUtils.getResult(event.future());
}
|
Add a {@link CompletableApplicationEvent} to the handler. The method blocks waiting for the result, and will
return the result value upon successful completion; otherwise throws an error.
<p/>
See {@link ConsumerUtils#getResult(Future)} for more details.
@param event A {@link CompletableApplicationEvent} created by the polling thread
@return Value that is the result of the event
@param <T> Type of return value of the event
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventHandler.java
| 135
|
[
"event"
] |
T
| true
| 2
| 8.08
|
apache/kafka
| 31,560
|
javadoc
| false
|
_fix_int_lt_zero
|
def _fix_int_lt_zero(x):
"""Convert `x` to double if it has real, negative components.
Otherwise, output is just the array version of the input (via asarray).
Parameters
----------
x : array_like
Returns
-------
array
Examples
--------
>>> import numpy as np
>>> np.lib.scimath._fix_int_lt_zero([1,2])
array([1, 2])
>>> np.lib.scimath._fix_int_lt_zero([-1,2])
array([-1., 2.])
"""
x = asarray(x)
if any(isreal(x) & (x < 0)):
x = x * 1.0
return x
|
Convert `x` to double if it has real, negative components.
Otherwise, output is just the array version of the input (via asarray).
Parameters
----------
x : array_like
Returns
-------
array
Examples
--------
>>> import numpy as np
>>> np.lib.scimath._fix_int_lt_zero([1,2])
array([1, 2])
>>> np.lib.scimath._fix_int_lt_zero([-1,2])
array([-1., 2.])
|
python
|
numpy/lib/_scimath_impl.py
| 125
|
[
"x"
] | false
| 2
| 7.36
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
upperCase
|
Alphabet upperCase() {
if (!hasLowerCase()) {
return this;
}
checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet");
char[] upperCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
upperCased[i] = Ascii.toUpperCase(chars[i]);
}
Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased);
return ignoreCase ? upperCase.ignoreCase() : upperCase;
}
|
Returns an equivalent {@code Alphabet} except it ignores case.
|
java
|
android/guava/src/com/google/common/io/BaseEncoding.java
| 566
|
[] |
Alphabet
| true
| 4
| 6.4
|
google/guava
| 51,352
|
javadoc
| false
|
getAndAdd
|
public double getAndAdd(final Number operand) {
final double last = value;
this.value += operand.doubleValue();
return last;
}
|
Increments this instance's value by {@code operand}; this method returns the value associated with the instance
immediately prior to the addition operation. This method is not thread safe.
@param operand the quantity to add, not null.
@throws NullPointerException if {@code operand} is null.
@return the value associated with this instance immediately before the operand was added.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java
| 238
|
[
"operand"
] | true
| 1
| 6.56
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
forLogLevel
|
public static ConditionEvaluationReportLoggingListener forLogLevel(LogLevel logLevelForReport) {
return new ConditionEvaluationReportLoggingListener(logLevelForReport);
}
|
Static factory method that creates a
{@link ConditionEvaluationReportLoggingListener} which logs the report at the
specified log level.
@param logLevelForReport the log level to log the report at
@return a {@link ConditionEvaluationReportLoggingListener} instance.
@since 3.0.0
|
java
|
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListener.java
| 78
|
[
"logLevelForReport"
] |
ConditionEvaluationReportLoggingListener
| true
| 1
| 6.16
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
containsValue
|
@Override
public boolean containsValue(@Nullable Object value) {
return seekByValue(value, smearedHash(value)) != null;
}
|
Returns {@code true} if this BiMap contains an entry whose value is equal to {@code value} (or,
equivalently, if this inverse view contains a key that is equal to {@code value}).
<p>Due to the property that values in a BiMap are unique, this will tend to execute in
faster-than-linear time.
@param value the object to search for in the values of this BiMap
@return true if a mapping exists from a key to the specified value
|
java
|
guava/src/com/google/common/collect/HashBiMap.java
| 305
|
[
"value"
] | true
| 1
| 6.64
|
google/guava
| 51,352
|
javadoc
| false
|
|
isStaticSymbol
|
function isStaticSymbol(symbol: Symbol): boolean {
if (!symbol.valueDeclaration) return false;
const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration);
return !!(modifierFlags & ModifierFlags.Static);
}
|
Find symbol of the given property-name and add the symbol to the given result array
@param symbol a symbol to start searching for the given propertyName
@param propertyName a name of property to search for
@param result an array of symbol of found property symbols
@param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol.
The value of previousIterationSymbol is undefined when the function is first called.
|
typescript
|
src/services/findAllReferences.ts
| 2,695
|
[
"symbol"
] | true
| 2
| 6.4
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
join
|
function join(head: IMatch, tail: IMatch[]): IMatch[] {
if (tail.length === 0) {
tail = [head];
} else if (head.end === tail[0].start) {
tail[0].start = head.start;
} else {
tail.unshift(head);
}
return tail;
}
|
Gets alternative codes to the character code passed in. This comes in the
form of an array of character codes, all of which must match _in order_ to
successfully match.
@param code The character code to check.
|
typescript
|
src/vs/base/common/filters.ts
| 193
|
[
"head",
"tail"
] | true
| 5
| 7.04
|
microsoft/vscode
| 179,840
|
jsdoc
| false
|
|
check_docker_context_files
|
def check_docker_context_files(install_distributions_from_context: bool):
"""
Quick check - if we want to install from docker-context-files we expect some packages there but if
we don't - we don't expect them, and they might invalidate Docker cache.
This method exits with an error if what we see is unexpected for given operation.
:param install_distributions_from_context: whether we want to install from docker-context-files
"""
context_file = DOCKER_CONTEXT_PATH.rglob("*")
any_context_files = any(
context.is_file()
and context.name not in (".README.md", ".DS_Store")
and not context.parent.name.startswith("constraints")
for context in context_file
)
if not any_context_files and install_distributions_from_context:
get_console().print("[warning]\nERROR! You want to install packages from docker-context-files")
get_console().print("[warning]\n but there are no packages to install in this folder.")
sys.exit(1)
elif any_context_files and not install_distributions_from_context:
get_console().print(
"[warning]\n ERROR! There are some extra files in docker-context-files except README.md"
)
get_console().print("[warning]\nAnd you did not choose --install-distributions-from-context flag")
get_console().print(
"[warning]\nThis might result in unnecessary cache invalidation and long build times"
)
get_console().print("[warning]Please restart the command with --cleanup-context switch\n")
sys.exit(1)
|
Quick check - if we want to install from docker-context-files we expect some packages there but if
we don't - we don't expect them, and they might invalidate Docker cache.
This method exits with an error if what we see is unexpected for given operation.
:param install_distributions_from_context: whether we want to install from docker-context-files
|
python
|
dev/breeze/src/airflow_breeze/commands/production_image_commands.py
| 822
|
[
"install_distributions_from_context"
] | true
| 7
| 6.88
|
apache/airflow
| 43,597
|
sphinx
| false
|
|
detect
|
public static DurationStyle detect(String value) {
Assert.notNull(value, "'value' must not be null");
for (DurationStyle candidate : values()) {
if (candidate.matches(value)) {
return candidate;
}
}
throw new IllegalArgumentException("'" + value + "' is not a valid duration");
}
|
Detect the style from the given source value.
@param value the source value
@return the duration style
@throws IllegalArgumentException if the value is not a known style
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/convert/DurationStyle.java
| 166
|
[
"value"
] |
DurationStyle
| true
| 2
| 7.92
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
getClassEntries
|
private static List<JarEntry> getClassEntries(JarFile source, @Nullable String classesLocation) {
classesLocation = (classesLocation != null) ? classesLocation : "";
Enumeration<JarEntry> sourceEntries = source.entries();
List<JarEntry> classEntries = new ArrayList<>();
while (sourceEntries.hasMoreElements()) {
JarEntry entry = sourceEntries.nextElement();
if (entry.getName().startsWith(classesLocation) && entry.getName().endsWith(DOT_CLASS)) {
classEntries.add(entry);
}
}
return classEntries;
}
|
Perform the given callback operation on all main classes from the given jar.
@param <T> the result type
@param jarFile the jar file to search
@param classesLocation the location within the jar containing classes
@param callback the callback
@return the first callback result or {@code null}
@throws IOException in case of I/O errors
|
java
|
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java
| 248
|
[
"source",
"classesLocation"
] | true
| 5
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
onTasksRevokedCallbackCompleted
|
public void onTasksRevokedCallbackCompleted(final StreamsOnTasksRevokedCallbackCompletedEvent event) {
Optional<KafkaException> error = event.error();
CompletableFuture<Void> future = event.future();
if (error.isPresent()) {
Exception e = error.get();
log.warn("The onTasksRevoked callback completed with an error ({}); " +
"signaling to continue to the next phase of rebalance", e.getMessage());
future.completeExceptionally(e);
} else {
log.debug("The onTasksRevoked callback completed successfully; signaling to continue to the next phase of rebalance");
future.complete(null);
}
}
|
Completes the future that marks the completed execution of the onTasksRevoked callback.
@param event The event containing the future sent from the application thread to the network thread to
confirm the execution of the callback.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
| 1,299
|
[
"event"
] |
void
| true
| 2
| 6.56
|
apache/kafka
| 31,560
|
javadoc
| false
|
readAdditionalMetadata
|
ConfigurationMetadata readAdditionalMetadata(TypeElement typeElement) {
return readAdditionalMetadata(ADDITIONAL_SOURCE_METADATA_PATH.apply(typeElement, this.typeUtils));
}
|
Read additional {@link ConfigurationMetadata} for the {@link TypeElement} or
{@code null}.
@param typeElement the type to get additional metadata for
@return additional metadata for the given type or {@code null} if none is present
|
java
|
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataStore.java
| 146
|
[
"typeElement"
] |
ConfigurationMetadata
| true
| 1
| 6.32
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
clearMergedBeanDefinition
|
@Override
protected void clearMergedBeanDefinition(String beanName) {
super.clearMergedBeanDefinition(beanName);
this.mergedBeanDefinitionHolders.remove(beanName);
}
|
Determine whether the specified bean definition qualifies as an autowire candidate,
to be injected into other beans which declare a dependency of matching type.
@param beanName the name of the bean definition to check
@param mbd the merged bean definition to check
@param descriptor the descriptor of the dependency to resolve
@param resolver the AutowireCandidateResolver to use for the actual resolution algorithm
@return whether the bean should be considered as autowire candidate
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
| 984
|
[
"beanName"
] |
void
| true
| 1
| 6.4
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
appendExportsOfVariableDeclarationList
|
function appendExportsOfVariableDeclarationList(statements: Statement[] | undefined, node: VariableDeclarationList, isForInOrOfInitializer: boolean): Statement[] | undefined {
if (currentModuleInfo.exportEquals) {
return statements;
}
for (const decl of node.declarations) {
statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer);
}
return statements;
}
|
Appends the exports of a VariableDeclarationList to a statement list, returning the statement
list.
@param statements A statement list to which the down-level export statements are to be
appended. If `statements` is `undefined`, a new array is allocated if statements are
appended.
@param node The VariableDeclarationList whose exports are to be recorded.
|
typescript
|
src/compiler/transformers/module/module.ts
| 2,033
|
[
"statements",
"node",
"isForInOrOfInitializer"
] | true
| 2
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
getSharedStyleSheet
|
function getSharedStyleSheet(): HTMLStyleElement {
if (!_sharedStyleSheet) {
_sharedStyleSheet = createStyleSheet();
}
return _sharedStyleSheet;
}
|
A version of createStyleSheet which has a unified API to initialize/set the style content.
|
typescript
|
src/vs/base/browser/domStylesheets.ts
| 115
|
[] | true
| 2
| 6.56
|
microsoft/vscode
| 179,840
|
jsdoc
| false
|
|
lazyGetProceedingJoinPoint
|
protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) {
return new MethodInvocationProceedingJoinPoint(rmi);
}
|
Return the ProceedingJoinPoint for the current invocation,
instantiating it lazily if it hasn't been bound to the thread already.
@param rmi the current Spring AOP ReflectiveMethodInvocation,
which we'll use for attribute binding
@return the ProceedingJoinPoint to make available to advice methods
|
java
|
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAroundAdvice.java
| 80
|
[
"rmi"
] |
ProceedingJoinPoint
| true
| 1
| 6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
isNested
|
private static boolean isNested(Class<?> type, Class<?> candidate) {
if (type.isAssignableFrom(candidate)) {
return true;
}
return (candidate.getDeclaringClass() != null && isNested(type, candidate.getDeclaringClass()));
}
|
Specify whether the specified property refer to a nested type. A nested type
represents a sub-namespace that need to be fully resolved. Nested types are
either inner classes or annotated with {@link NestedConfigurationProperty}.
@param propertyName the name of the property
@param propertyType the type of the property
@return whether the specified {@code propertyType} is a nested type
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java
| 323
|
[
"type",
"candidate"
] | true
| 3
| 7.76
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
serialize_hoo_outputs
|
def serialize_hoo_outputs(self, node: torch.fx.Node) -> list[Argument]:
"""
For serializing HOO outputs since HOOs do not have a schema.
"""
meta_val = node.meta["val"]
if isinstance(meta_val, tuple):
outputs = []
for i, element_meta_val in enumerate(meta_val):
user_node = self._output_node_at_index(node, i)
if isinstance(element_meta_val, list):
# e.g "-> Tensor[]"
assert user_node is not None
tensors = []
for j, m in enumerate(element_meta_val):
if not isinstance(m, torch.Tensor):
raise SerializeError(
f"Serialize list output with type {type(m)} nyi"
)
name = self._output_node_name_at_index(user_node, j)
tensors.append(self.serialize_tensor_output(name, m))
outputs.append(Argument.create(as_tensors=tensors))
else:
name = (
user_node.name
if user_node is not None
else f"{node.name}_unused_{i}"
)
outputs.append(self.serialize_output(name, element_meta_val))
return outputs
elif isinstance(meta_val, dict):
tensor_args = []
# use the dict key as the idx
for idx, meta in meta_val.items():
if not isinstance(meta, torch.Tensor):
raise SerializeError(
f"Serialize list output with type {type(meta)} nyi"
)
name = self._output_node_name_at_index(node, idx)
tensor_args.append(self.serialize_tensor_output(name, meta))
return [Argument.create(as_tensors=tensor_args)]
else:
return [self.serialize_output(node.name, meta_val)]
|
For serializing HOO outputs since HOOs do not have a schema.
|
python
|
torch/_export/serde/serialize.py
| 1,738
|
[
"self",
"node"
] |
list[Argument]
| true
| 12
| 6
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
getObject
|
@Override
default T getObject() throws BeansException {
Iterator<T> it = iterator();
if (!it.hasNext()) {
throw new NoSuchBeanDefinitionException(Object.class);
}
T result = it.next();
if (it.hasNext()) {
throw new NoUniqueBeanDefinitionException(Object.class, 2, "more than 1 matching bean");
}
return result;
}
|
A predicate for unfiltered type matches, including non-default candidates
but still excluding non-autowire candidates when used on injection points.
@since 6.2.3
@see #stream(Predicate)
@see #orderedStream(Predicate)
@see org.springframework.beans.factory.config.BeanDefinition#isAutowireCandidate()
@see org.springframework.beans.factory.support.AbstractBeanDefinition#isDefaultCandidate()
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/ObjectProvider.java
| 85
|
[] |
T
| true
| 3
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
on_chord_header_start
|
def on_chord_header_start(self, sig, **header) -> dict:
"""Method that is called on сhord header stamping start.
Arguments:
sig (chord): chord that is stamped.
headers (Dict): Partial headers that could be merged with existing headers.
Returns:
Dict: headers to update.
"""
if not isinstance(sig.tasks, group):
sig.tasks = group(sig.tasks)
return self.on_group_start(sig.tasks, **header)
|
Method that is called on сhord header stamping start.
Arguments:
sig (chord): chord that is stamped.
headers (Dict): Partial headers that could be merged with existing headers.
Returns:
Dict: headers to update.
|
python
|
celery/canvas.py
| 175
|
[
"self",
"sig"
] |
dict
| true
| 2
| 8.08
|
celery/celery
| 27,741
|
google
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.