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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
report_exportability
|
def report_exportability(
mod: torch.nn.Module,
args: tuple[Any, ...],
kwargs: Optional[dict[str, Any]] = None,
*,
strict: bool = True,
pre_dispatch: bool = False,
) -> dict[str, Optional[Exception]]:
"""
Report exportability issues for a module in one-shot.
Args:
mod: root module.
args: args to the root module.
kwargs: kwargs to the root module.
Returns:
A dict that maps from submodule name to the exception that was raised when trying to export it.
`None` means the module is exportable without issue.
Sample output:
{
'': UnsupportedOperatorException(func=<OpOverload(op='testlib.op_missing_meta', overload='default')>),
'submod_1': UnsupportedOperatorException(func=<OpOverload(op='testlib.op_missing_meta', overload='default')>),
'submod_2': None
}
"""
log_export_usage(event="export.report_exportability")
kwargs = kwargs or {}
all_submod_names = [name for name, _ in mod.named_modules() if name != ""]
submod_inputs = _generate_inputs_for_submodules(mod, all_submod_names, args, kwargs)
tried_module_types = set()
report: dict[str, Optional[Exception]] = {}
def try_export(module, module_name, args, kwargs):
nonlocal submod_inputs, report, strict, pre_dispatch, tried_module_types
if type(module) in tried_module_types:
return
tried_module_types.add(type(module))
if args is not None or kwargs is not None:
try:
torch.export._trace._export(
module,
args,
kwargs,
strict=strict,
pre_dispatch=pre_dispatch,
)
report[module_name] = None
log.info("Successfully exported `%s`", module_name)
return
except Exception as e:
short_msg = repr(e).split("\n")[0]
log.warning(
"Failed exporting `%s` with exception: %s", module_name, short_msg
)
report[module_name] = e
for name, submod in module.named_children():
sub_module_name = name if module_name == "" else f"{module_name}.{name}"
submod_args, submod_kwargs = submod_inputs.get(
sub_module_name, (None, None)
)
try_export(submod, sub_module_name, submod_args, submod_kwargs)
return
try_export(mod, "", args, kwargs)
unique_issues = set()
for exception in report.values():
if exception is not None:
key = repr(exception).split("\\n")[0]
unique_issues.add(key)
log.warning("Found %d export issues:", len(unique_issues))
for issue in unique_issues:
log.warning(issue)
return report
|
Report exportability issues for a module in one-shot.
Args:
mod: root module.
args: args to the root module.
kwargs: kwargs to the root module.
Returns:
A dict that maps from submodule name to the exception that was raised when trying to export it.
`None` means the module is exportable without issue.
Sample output:
{
'': UnsupportedOperatorException(func=<OpOverload(op='testlib.op_missing_meta', overload='default')>),
'submod_1': UnsupportedOperatorException(func=<OpOverload(op='testlib.op_missing_meta', overload='default')>),
'submod_2': None
}
|
python
|
torch/_export/tools.py
| 63
|
[
"mod",
"args",
"kwargs",
"strict",
"pre_dispatch"
] |
dict[str, Optional[Exception]]
| true
| 10
| 7.36
|
pytorch/pytorch
| 96,034
|
google
| false
|
transformFinally
|
function transformFinally(node: PromiseReturningCallExpression<"finally">, onFinally: Expression | undefined, transformer: Transformer, hasContinuation: boolean, continuationArgName?: SynthBindingName): readonly Statement[] {
if (!onFinally || isNullOrUndefined(transformer, onFinally)) {
// Ignore this call as it has no effect on the result
return transformExpression(/* returnContextNode */ node, node.expression.expression, transformer, hasContinuation, continuationArgName);
}
const possibleNameForVarDecl = getPossibleNameForVarDecl(node, transformer, continuationArgName);
// Transform the left-hand-side of `.finally` into an array of inlined statements. We pass `true` for hasContinuation as `node` is the outer continuation.
const inlinedLeftHandSide = transformExpression(/*returnContextNode*/ node, node.expression.expression, transformer, /*hasContinuation*/ true, possibleNameForVarDecl);
if (hasFailed()) return silentFail(); // shortcut out of more work
// Transform the callback argument into an array of inlined statements. We pass whether we have an outer continuation here
// as that indicates whether `return` is valid.
const inlinedCallback = transformCallbackArgument(onFinally, hasContinuation, /*continuationArgName*/ undefined, /*inputArgName*/ undefined, node, transformer);
if (hasFailed()) return silentFail(); // shortcut out of more work
const tryBlock = factory.createBlock(inlinedLeftHandSide);
const finallyBlock = factory.createBlock(inlinedCallback);
const tryStatement = factory.createTryStatement(tryBlock, /*catchClause*/ undefined, finallyBlock);
return finishCatchOrFinallyTransform(node, transformer, tryStatement, possibleNameForVarDecl, continuationArgName);
}
|
@param hasContinuation Whether another `then`, `catch`, or `finally` continuation follows this continuation.
@param continuationArgName The argument name for the continuation that follows this call.
|
typescript
|
src/services/codefixes/convertToAsyncFunction.ts
| 494
|
[
"node",
"onFinally",
"transformer",
"hasContinuation",
"continuationArgName?"
] | true
| 5
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
adapt
|
public static ConfigurationPropertyName adapt(CharSequence name, char separator) {
return adapt(name, separator, null);
}
|
Create a {@link ConfigurationPropertyName} by adapting the given source. See
{@link #adapt(CharSequence, char, Function)} for details.
@param name the name to parse
@param separator the separator used to split the name
@return a {@link ConfigurationPropertyName}
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
| 719
|
[
"name",
"separator"
] |
ConfigurationPropertyName
| true
| 1
| 6.16
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
groupMembershipOperation
|
public GroupMembershipOperation groupMembershipOperation() {
return operation;
}
|
Fluent method to set the group membership operation upon shutdown.
@param operation the group membership operation to apply. Must be one of {@code LEAVE_GROUP}, {@code REMAIN_IN_GROUP}, or {@code DEFAULT}.
@return this {@code CloseOptions} instance.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/CloseOptions.java
| 105
|
[] |
GroupMembershipOperation
| true
| 1
| 6.32
|
apache/kafka
| 31,560
|
javadoc
| false
|
get_tag_date
|
def get_tag_date(tag: str) -> str | None:
"""
Returns UTC timestamp of the tag in the repo in iso time format 8601
:param tag: tag to get date for
:return: iso time format 8601 of the tag date
"""
from git import Repo
repo = Repo(AIRFLOW_ROOT_PATH)
try:
tag_object = repo.tags[tag].object
except IndexError:
get_console().print(f"[warning]Tag {tag} not found in the repository")
return None
timestamp: int = (
tag_object.committed_date if hasattr(tag_object, "committed_date") else tag_object.tagged_date
)
return datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
Returns UTC timestamp of the tag in the repo in iso time format 8601
:param tag: tag to get date for
:return: iso time format 8601 of the tag date
|
python
|
dev/breeze/src/airflow_breeze/utils/github.py
| 226
|
[
"tag"
] |
str | None
| true
| 2
| 7.76
|
apache/airflow
| 43,597
|
sphinx
| false
|
isetitem
|
def isetitem(self, loc, value) -> None:
"""
Set the given value in the column with position `loc`.
This is a positional analogue to ``__setitem__``.
Parameters
----------
loc : int or sequence of ints
Index position for the column.
value : scalar or arraylike
Value(s) for the column.
See Also
--------
DataFrame.iloc : Purely integer-location based indexing for selection by
position.
Notes
-----
``frame.isetitem(loc, value)`` is an in-place method as it will
modify the DataFrame in place (not returning a new object). In contrast to
``frame.iloc[:, i] = value`` which will try to update the existing values in
place, ``frame.isetitem(loc, value)`` will not update the values of the column
itself in place, it will instead insert a new array.
In cases where ``frame.columns`` is unique, this is equivalent to
``frame[frame.columns[i]] = value``.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
>>> df.isetitem(1, [5, 6])
>>> df
A B
0 1 5
1 2 6
"""
if isinstance(value, DataFrame):
if is_integer(loc):
loc = [loc]
if len(loc) != len(value.columns):
raise ValueError(
f"Got {len(loc)} positions but value has {len(value.columns)} "
f"columns."
)
for i, idx in enumerate(loc):
arraylike, refs = self._sanitize_column(value.iloc[:, i])
self._iset_item_mgr(idx, arraylike, inplace=False, refs=refs)
return
arraylike, refs = self._sanitize_column(value)
self._iset_item_mgr(loc, arraylike, inplace=False, refs=refs)
|
Set the given value in the column with position `loc`.
This is a positional analogue to ``__setitem__``.
Parameters
----------
loc : int or sequence of ints
Index position for the column.
value : scalar or arraylike
Value(s) for the column.
See Also
--------
DataFrame.iloc : Purely integer-location based indexing for selection by
position.
Notes
-----
``frame.isetitem(loc, value)`` is an in-place method as it will
modify the DataFrame in place (not returning a new object). In contrast to
``frame.iloc[:, i] = value`` which will try to update the existing values in
place, ``frame.isetitem(loc, value)`` will not update the values of the column
itself in place, it will instead insert a new array.
In cases where ``frame.columns`` is unique, this is equivalent to
``frame[frame.columns[i]] = value``.
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
>>> df.isetitem(1, [5, 6])
>>> df
A B
0 1 5
1 2 6
|
python
|
pandas/core/frame.py
| 4,311
|
[
"self",
"loc",
"value"
] |
None
| true
| 5
| 8.48
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
tz_to_dtype
|
def tz_to_dtype(
tz: tzinfo | None, unit: TimeUnit = "ns"
) -> np.dtype[np.datetime64] | DatetimeTZDtype:
"""
Return a datetime64[ns] dtype appropriate for the given timezone.
Parameters
----------
tz : tzinfo or None
unit : str, default "ns"
Returns
-------
np.dtype or Datetime64TZDType
"""
if tz is None:
return np.dtype(f"M8[{unit}]")
else:
return DatetimeTZDtype(tz=tz, unit=unit)
|
Return a datetime64[ns] dtype appropriate for the given timezone.
Parameters
----------
tz : tzinfo or None
unit : str, default "ns"
Returns
-------
np.dtype or Datetime64TZDType
|
python
|
pandas/core/arrays/datetimes.py
| 117
|
[
"tz",
"unit"
] |
np.dtype[np.datetime64] | DatetimeTZDtype
| true
| 3
| 6.64
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
abs
|
public Fraction abs() {
if (numerator >= 0) {
return this;
}
return negate();
}
|
Gets a fraction that is the positive equivalent of this one.
<p>
More precisely: {@code (fraction >= 0 ? this : -fraction)}
</p>
<p>
The returned fraction is not reduced.
</p>
@return {@code this} if it is positive, or a new positive fraction instance with the opposite signed numerator
|
java
|
src/main/java/org/apache/commons/lang3/math/Fraction.java
| 506
|
[] |
Fraction
| true
| 2
| 8.24
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
withLogger
|
public SELF withLogger(Log logger) {
Assert.notNull(logger, "'logger' must not be null");
this.logger = logger;
return self();
}
|
Use the specified logger to report any lambda failures.
@param logger the logger to use
@return this instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/util/LambdaSafe.java
| 138
|
[
"logger"
] |
SELF
| true
| 1
| 7.04
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
insert
|
public StrBuilder insert(final int index, String str) {
validateIndex(index);
if (str == null) {
str = nullText;
}
if (str != null) {
final int strLen = str.length();
if (strLen > 0) {
final int newSize = size + strLen;
ensureCapacity(newSize);
System.arraycopy(buffer, index, buffer, index + strLen, size - index);
size = newSize;
str.getChars(0, strLen, buffer, index);
}
}
return this;
}
|
Inserts the string into this builder.
Inserting null will use the stored null text value.
@param index the index to add at, must be valid
@param str the string to insert
@return {@code this} instance.
@throws IndexOutOfBoundsException if the index is invalid
|
java
|
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
| 2,261
|
[
"index",
"str"
] |
StrBuilder
| true
| 4
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
addCallback
|
public final void addCallback(FutureCallback<? super V> callback, Executor executor) {
Futures.addCallback(this, callback, executor);
}
|
Registers separate success and failure callbacks to be run when this {@code Future}'s
computation is {@linkplain java.util.concurrent.Future#isDone() complete} or, if the
computation is already complete, immediately.
<p>The callback is run on {@code executor}. There is no guaranteed ordering of execution of
callbacks, but any callback added through this method is guaranteed to be called once the
computation is complete.
<p>Example:
{@snippet :
future.addCallback(
new FutureCallback<QueryResult>() {
public void onSuccess(QueryResult result) {
storeInCache(result);
}
public void onFailure(Throwable t) {
reportError(t);
}
}, executor);
}
<p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
the discussion in the {@link #addListener} documentation. All its warnings about heavyweight
listeners are also applicable to heavyweight callbacks passed to this method.
<p>For a more general interface to attach a completion listener, see {@link #addListener}.
<p>This method is similar to {@link java.util.concurrent.CompletableFuture#whenComplete} and
{@link java.util.concurrent.CompletableFuture#whenCompleteAsync}. It also serves the use case
of {@link java.util.concurrent.CompletableFuture#thenAccept} and {@link
java.util.concurrent.CompletableFuture#thenAcceptAsync}.
@param callback The callback to invoke when this {@code Future} is completed.
@param executor The executor to run {@code callback} when the future completes.
|
java
|
android/guava/src/com/google/common/util/concurrent/FluentFuture.java
| 416
|
[
"callback",
"executor"
] |
void
| true
| 1
| 6.56
|
google/guava
| 51,352
|
javadoc
| false
|
update
|
def update(self, other: Series | Sequence | Mapping) -> None:
"""
Modify Series in place using values from passed Series.
Uses non-NA values from passed Series to make updates. Aligns
on index.
Parameters
----------
other : Series, or object coercible into Series
Other Series that provides values to update the current Series.
See Also
--------
Series.combine : Perform element-wise operation on two Series
using a given function.
Series.transform: Modify a Series using a function.
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6]))
>>> s
0 4
1 5
2 6
dtype: int64
>>> s = pd.Series(["a", "b", "c"])
>>> s.update(pd.Series(["d", "e"], index=[0, 2]))
>>> s
0 d
1 b
2 e
dtype: object
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6, 7, 8]))
>>> s
0 4
1 5
2 6
dtype: int64
If ``other`` contains NaNs the corresponding values are not updated
in the original Series.
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, np.nan, 6]))
>>> s
0 4
1 2
2 6
dtype: int64
``other`` can also be a non-Series object type
that is coercible into a Series
>>> s = pd.Series([1, 2, 3])
>>> s.update([4, np.nan, 6])
>>> s
0 4
1 2
2 6
dtype: int64
>>> s = pd.Series([1, 2, 3])
>>> s.update({1: 9})
>>> s
0 1
1 9
2 3
dtype: int64
"""
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(
self
) <= REF_COUNT_METHOD and not com.is_local_in_caller_frame(self):
warnings.warn(
_chained_assignment_method_msg,
ChainedAssignmentError,
stacklevel=2,
)
if not isinstance(other, Series):
other = Series(other)
other = other.reindex_like(self)
mask = notna(other)
self._mgr = self._mgr.putmask(mask=mask, new=other)
|
Modify Series in place using values from passed Series.
Uses non-NA values from passed Series to make updates. Aligns
on index.
Parameters
----------
other : Series, or object coercible into Series
Other Series that provides values to update the current Series.
See Also
--------
Series.combine : Perform element-wise operation on two Series
using a given function.
Series.transform: Modify a Series using a function.
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6]))
>>> s
0 4
1 5
2 6
dtype: int64
>>> s = pd.Series(["a", "b", "c"])
>>> s.update(pd.Series(["d", "e"], index=[0, 2]))
>>> s
0 d
1 b
2 e
dtype: object
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, 5, 6, 7, 8]))
>>> s
0 4
1 5
2 6
dtype: int64
If ``other`` contains NaNs the corresponding values are not updated
in the original Series.
>>> s = pd.Series([1, 2, 3])
>>> s.update(pd.Series([4, np.nan, 6]))
>>> s
0 4
1 2
2 6
dtype: int64
``other`` can also be a non-Series object type
that is coercible into a Series
>>> s = pd.Series([1, 2, 3])
>>> s.update([4, np.nan, 6])
>>> s
0 4
1 2
2 6
dtype: int64
>>> s = pd.Series([1, 2, 3])
>>> s.update({1: 9})
>>> s
0 1
1 9
2 3
dtype: int64
|
python
|
pandas/core/series.py
| 3,346
|
[
"self",
"other"
] |
None
| true
| 5
| 8.4
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
transitionToUninitialized
|
public synchronized void transitionToUninitialized(RuntimeException exception) {
transitionTo(State.UNINITIALIZED);
if (pendingTransition != null) {
pendingTransition.result.fail(exception);
}
lastError = null;
}
|
Returns the first inflight sequence for a given partition. This is the base sequence of an inflight batch with
the lowest sequence number.
@return the lowest inflight sequence if the transaction manager is tracking inflight requests for this partition.
If there are no inflight requests being tracked for this partition, this method will return
RecordBatch.NO_SEQUENCE.
|
java
|
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
| 758
|
[
"exception"
] |
void
| true
| 2
| 6.72
|
apache/kafka
| 31,560
|
javadoc
| false
|
get
|
public static Origin get(PropertySource<?> propertySource, String name) {
Origin origin = OriginLookup.getOrigin(propertySource, name);
return (origin instanceof PropertySourceOrigin) ? origin
: new PropertySourceOrigin(propertySource, name, origin);
}
|
Get an {@link Origin} for the given {@link PropertySource} and
{@code propertyName}. Will either return an {@link OriginLookup} result or a
{@link PropertySourceOrigin}.
@param propertySource the origin property source
@param name the property name
@return the property origin
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/origin/PropertySourceOrigin.java
| 108
|
[
"propertySource",
"name"
] |
Origin
| true
| 2
| 7.44
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
build
|
public ThreadFactory build() {
return doBuild(this);
}
|
Returns a new thread factory using the options supplied during the building process. After
building, it is still possible to change the options used to build the ThreadFactory and/or
build again. State is not shared amongst built instances.
<p><b>Java 21+ users:</b> use {@link Thread.Builder#factory()} instead.
@return the fully constructed {@link ThreadFactory}
|
java
|
android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
| 179
|
[] |
ThreadFactory
| true
| 1
| 6.32
|
google/guava
| 51,352
|
javadoc
| false
|
purge_inactive_dag_warnings
|
def purge_inactive_dag_warnings(cls, session: Session = NEW_SESSION) -> None:
"""
Deactivate DagWarning records for inactive dags.
:return: None
"""
if get_dialect_name(session) == "sqlite":
dag_ids_stmt = select(DagModel.dag_id).where(DagModel.is_stale == true())
query = delete(cls).where(cls.dag_id.in_(dag_ids_stmt.scalar_subquery()))
else:
query = delete(cls).where(cls.dag_id == DagModel.dag_id, DagModel.is_stale == true())
session.execute(query.execution_options(synchronize_session=False))
session.commit()
|
Deactivate DagWarning records for inactive dags.
:return: None
|
python
|
airflow-core/src/airflow/models/dagwarning.py
| 80
|
[
"cls",
"session"
] |
None
| true
| 3
| 6.08
|
apache/airflow
| 43,597
|
unknown
| false
|
buildHooks
|
function buildHooks(hooks, name, defaultStep, validate, mergedContext) {
let lastRunIndex = hooks.length;
/**
* Helper function to wrap around invocation of user hook or the default step
* in order to fill in missing arguments or check returned results.
* Due to the merging of the context, this must be a closure.
* @param {number} index Index in the chain. Default step is 0, last added hook is 1,
* and so on.
* @param {Function} userHookOrDefault Either the user hook or the default step to invoke.
* @param {Function|undefined} next The next wrapped step. If this is the default step, it's undefined.
* @returns {Function} Wrapped hook or default step.
*/
function wrapHook(index, userHookOrDefault, next) {
return function nextStep(arg0, context) {
lastRunIndex = index;
if (context && context !== mergedContext) {
ObjectAssign(mergedContext, context);
}
const hookResult = userHookOrDefault(arg0, mergedContext, next);
if (lastRunIndex > 0 && lastRunIndex === index && !hookResult.shortCircuit) {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE('true', name, 'shortCircuit',
hookResult.shortCircuit);
}
return validate(arg0, mergedContext, hookResult);
};
}
const chain = [wrapHook(0, defaultStep)];
for (let i = 0; i < hooks.length; ++i) {
const wrappedHook = wrapHook(i + 1, hooks[i][name], chain[i]);
ArrayPrototypePush(chain, wrappedHook);
}
return chain[chain.length - 1];
}
|
Convert a list of hooks into a function that can be used to do an operation through
a chain of hooks. If any of the hook returns without calling the next hook, it
must return shortCircuit: true to stop the chain from continuing to avoid
forgetting to invoke the next hook by mistake.
@param {ModuleHooks[]} hooks A list of hooks whose last argument is `nextHook`.
@param {'load'|'resolve'} name Name of the hook in ModuleHooks.
@param {Function} defaultStep The default step in the chain.
@param {Function} validate A function that validates and sanitize the result returned by the chain.
@param {object} mergedContext
@returns {any}
|
javascript
|
lib/internal/modules/customization_hooks.js
| 171
|
[
"hooks",
"name",
"defaultStep",
"validate",
"mergedContext"
] | false
| 7
| 6.24
|
nodejs/node
| 114,839
|
jsdoc
| false
|
|
injectProxy
|
function injectProxy({target}: {target: any}) {
// Firefox's behaviour for injecting this content script can be unpredictable
// While navigating the history, some content scripts might not be re-injected and still be alive
if (!window.__REACT_DEVTOOLS_PROXY_INJECTED__) {
window.__REACT_DEVTOOLS_PROXY_INJECTED__ = true;
connectPort();
sayHelloToBackendManager();
// The backend waits to install the global hook until notified by the content script.
// In the event of a page reload, the content script might be loaded before the backend manager is injected.
// Because of this we need to poll the backend manager until it has been initialized.
const intervalID: IntervalID = setInterval(() => {
if (backendInitialized) {
clearInterval(intervalID);
} else {
sayHelloToBackendManager();
}
}, 500);
}
}
|
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
@flow
|
javascript
|
packages/react-devtools-extensions/src/contentScripts/proxy.js
| 13
|
[] | false
| 4
| 6.4
|
facebook/react
| 241,750
|
jsdoc
| false
|
|
postProcessBeanDefinition
|
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
beanDefinition.applyDefaults(this.beanDefinitionDefaults);
if (this.autowireCandidatePatterns != null) {
beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
}
}
|
Apply further settings to the given bean definition,
beyond the contents retrieved from scanning the component class.
@param beanDefinition the scanned bean definition
@param beanName the generated bean name for the given bean
|
java
|
spring-context/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java
| 305
|
[
"beanDefinition",
"beanName"
] |
void
| true
| 2
| 6.4
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
view
|
def view(self, dtype: Dtype | None = None) -> ArrayLike:
"""
Return a view on the array.
Parameters
----------
dtype : str, np.dtype, or ExtensionDtype, optional
Default None.
Returns
-------
ExtensionArray or np.ndarray
A view on the :class:`ExtensionArray`'s data.
See Also
--------
api.extensions.ExtensionArray.ravel: Return a flattened view on input array.
Index.view: Equivalent function for Index.
ndarray.view: New view of array with the same data.
Examples
--------
This gives view on the underlying data of an ``ExtensionArray`` and is not a
copy. Modifications on either the view or the original ``ExtensionArray``
will be reflected on the underlying data:
>>> arr = pd.array([1, 2, 3])
>>> arr2 = arr.view()
>>> arr[0] = 2
>>> arr2
<IntegerArray>
[2, 2, 3]
Length: 3, dtype: Int64
"""
# NB:
# - This must return a *new* object referencing the same data, not self.
# - The only case that *must* be implemented is with dtype=None,
# giving a view with the same dtype as self.
if dtype is not None:
raise NotImplementedError(dtype)
return self[:]
|
Return a view on the array.
Parameters
----------
dtype : str, np.dtype, or ExtensionDtype, optional
Default None.
Returns
-------
ExtensionArray or np.ndarray
A view on the :class:`ExtensionArray`'s data.
See Also
--------
api.extensions.ExtensionArray.ravel: Return a flattened view on input array.
Index.view: Equivalent function for Index.
ndarray.view: New view of array with the same data.
Examples
--------
This gives view on the underlying data of an ``ExtensionArray`` and is not a
copy. Modifications on either the view or the original ``ExtensionArray``
will be reflected on the underlying data:
>>> arr = pd.array([1, 2, 3])
>>> arr2 = arr.view()
>>> arr[0] = 2
>>> arr2
<IntegerArray>
[2, 2, 3]
Length: 3, dtype: Int64
|
python
|
pandas/core/arrays/base.py
| 1,947
|
[
"self",
"dtype"
] |
ArrayLike
| true
| 2
| 8.48
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
onEmitNode
|
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
const superContainerFlags = (resolver.hasNodeCheckFlag(node, NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) ? NodeCheckFlags.MethodWithSuperPropertyAccessInAsync : 0) | (resolver.hasNodeCheckFlag(node, NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) ? NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync : 0);
if (superContainerFlags !== enclosingSuperContainerFlags) {
const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
enclosingSuperContainerFlags = superContainerFlags;
previousOnEmitNode(hint, node, emitCallback);
enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
return;
}
}
// Disable substitution in the generated super accessor itself.
else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) {
const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
enclosingSuperContainerFlags = 0;
previousOnEmitNode(hint, node, emitCallback);
enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
return;
}
previousOnEmitNode(hint, node, emitCallback);
}
|
Hook for node emit.
@param hint A hint as to the intended usage of the node.
@param node The node to emit.
@param emit A callback used to emit the node in the printer.
|
typescript
|
src/compiler/transformers/es2017.ts
| 926
|
[
"hint",
"node",
"emitCallback"
] | true
| 9
| 6.72
|
microsoft/TypeScript
| 107,154
|
jsdoc
| true
|
|
standardPollFirstEntry
|
protected @Nullable Entry<E> standardPollFirstEntry() {
Iterator<Entry<E>> entryIterator = entrySet().iterator();
if (!entryIterator.hasNext()) {
return null;
}
Entry<E> entry = entryIterator.next();
entry = Multisets.immutableEntry(entry.getElement(), entry.getCount());
entryIterator.remove();
return entry;
}
|
A sensible definition of {@link #pollFirstEntry()} in terms of {@code entrySet().iterator()}.
<p>If you override {@link #entrySet()}, you may wish to override {@link #pollFirstEntry()} to
forward to this implementation.
|
java
|
android/guava/src/com/google/common/collect/ForwardingSortedMultiset.java
| 163
|
[] | true
| 2
| 6.24
|
google/guava
| 51,352
|
javadoc
| false
|
|
beginBlock
|
function beginBlock(block: CodeBlock): number {
if (!blocks) {
blocks = [];
blockActions = [];
blockOffsets = [];
blockStack = [];
}
const index = blockActions!.length;
blockActions![index] = BlockAction.Open;
blockOffsets![index] = operations ? operations.length : 0;
blocks[index] = block;
blockStack!.push(block);
return index;
}
|
Begins a block operation (With, Break/Continue, Try/Catch/Finally)
@param block Information about the block.
|
typescript
|
src/compiler/transformers/generators.ts
| 2,133
|
[
"block"
] | true
| 3
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
createStarted
|
public static StopWatch createStarted() {
final StopWatch sw = new StopWatch();
sw.start();
return sw;
}
|
Creates and starts a StopWatch.
@return StopWatch a started StopWatch.
@since 3.5
|
java
|
src/main/java/org/apache/commons/lang3/time/StopWatch.java
| 242
|
[] |
StopWatch
| true
| 1
| 6.88
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
createDouble
|
public static Double createDouble(final String str) {
if (str == null) {
return null;
}
return Double.valueOf(str);
}
|
Creates a {@link Double} from a {@link String}.
<p>
Returns {@code null} if the string is {@code null}.
</p>
@param str a {@link String} to convert, may be null.
@return converted {@link Double} (or null if the input is null).
@throws NumberFormatException if the value cannot be converted.
|
java
|
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
| 223
|
[
"str"
] |
Double
| true
| 2
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
toByteArray
|
default byte[] toByteArray() {
return toByteArray(StandardCharsets.UTF_8);
}
|
Write the JSON to a UTF-8 encoded byte array.
@return the JSON bytes
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/json/WritableJson.java
| 68
|
[] | true
| 1
| 6.8
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
nop
|
@SuppressWarnings("unchecked")
static <T, R, E extends Throwable> FailableFunction<T, R, E> nop() {
return NOP;
}
|
Gets the NOP singleton.
@param <T> Consumed type.
@param <R> Return type.
@param <E> The type of thrown exception or error.
@return The NOP singleton.
|
java
|
src/main/java/org/apache/commons/lang3/function/FailableFunction.java
| 71
|
[] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
wait_for_cluster_instance_availability
|
def wait_for_cluster_instance_availability(
self, cluster_id: str, delay: int = 30, max_attempts: int = 60
) -> None:
"""
Wait for Neptune instances in a cluster to be available.
:param cluster_id: The cluster ID of the instances to wait for.
:param delay: Time in seconds to delay between polls.
:param max_attempts: Maximum number of attempts to poll for completion.
:return: The status of the instances.
"""
filters = [{"Name": "db-cluster-id", "Values": [cluster_id]}]
self.log.info("Waiting for instances in cluster %s.", cluster_id)
self.get_waiter("db_instance_available").wait(
Filters=filters, WaiterConfig={"Delay": delay, "MaxAttempts": max_attempts}
)
self.log.info("Finished waiting for instances in cluster %s.", cluster_id)
|
Wait for Neptune instances in a cluster to be available.
:param cluster_id: The cluster ID of the instances to wait for.
:param delay: Time in seconds to delay between polls.
:param max_attempts: Maximum number of attempts to poll for completion.
:return: The status of the instances.
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/hooks/neptune.py
| 104
|
[
"self",
"cluster_id",
"delay",
"max_attempts"
] |
None
| true
| 1
| 7.04
|
apache/airflow
| 43,597
|
sphinx
| false
|
decode
|
public static String decode(String source) {
return decode(source, StandardCharsets.UTF_8);
}
|
Decode the given encoded URI component value by replacing each "<i>{@code %xy}</i>"
sequence with a hexadecimal representation of the character in
{@link StandardCharsets#UTF_8 UTF-8}, leaving other characters unmodified.
@param source the encoded URI component value
@return the decoded value
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/util/UrlDecoder.java
| 43
|
[
"source"
] |
String
| true
| 1
| 6
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
reorder_levels
|
def reorder_levels(self, order: Sequence[int | str], axis: Axis = 0) -> DataFrame:
"""
Rearrange index or column levels using input ``order``.
May not drop or duplicate levels.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
axis : {0 or 'index', 1 or 'columns'}, default 0
Where to reorder levels.
Returns
-------
DataFrame
DataFrame with indices or columns with reordered levels.
See Also
--------
DataFrame.swaplevel : Swap levels i and j in a MultiIndex.
Examples
--------
>>> data = {
... "class": ["Mammals", "Mammals", "Reptiles"],
... "diet": ["Omnivore", "Carnivore", "Carnivore"],
... "species": ["Humans", "Dogs", "Snakes"],
... }
>>> df = pd.DataFrame(data, columns=["class", "diet", "species"])
>>> df = df.set_index(["class", "diet"])
>>> df
species
class diet
Mammals Omnivore Humans
Carnivore Dogs
Reptiles Carnivore Snakes
Let's reorder the levels of the index:
>>> df.reorder_levels(["diet", "class"])
species
diet class
Omnivore Mammals Humans
Carnivore Mammals Dogs
Reptiles Snakes
"""
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
raise TypeError("Can only reorder levels on a hierarchical axis.")
result = self.copy(deep=False)
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.reorder_levels(order)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.reorder_levels(order)
return result
|
Rearrange index or column levels using input ``order``.
May not drop or duplicate levels.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
axis : {0 or 'index', 1 or 'columns'}, default 0
Where to reorder levels.
Returns
-------
DataFrame
DataFrame with indices or columns with reordered levels.
See Also
--------
DataFrame.swaplevel : Swap levels i and j in a MultiIndex.
Examples
--------
>>> data = {
... "class": ["Mammals", "Mammals", "Reptiles"],
... "diet": ["Omnivore", "Carnivore", "Carnivore"],
... "species": ["Humans", "Dogs", "Snakes"],
... }
>>> df = pd.DataFrame(data, columns=["class", "diet", "species"])
>>> df = df.set_index(["class", "diet"])
>>> df
species
class diet
Mammals Omnivore Humans
Carnivore Dogs
Reptiles Carnivore Snakes
Let's reorder the levels of the index:
>>> df.reorder_levels(["diet", "class"])
species
diet class
Omnivore Mammals Humans
Carnivore Mammals Dogs
Reptiles Snakes
|
python
|
pandas/core/frame.py
| 8,598
|
[
"self",
"order",
"axis"
] |
DataFrame
| true
| 4
| 8.24
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
getManifest
|
@Override
public Manifest getManifest() throws IOException {
Object manifest = this.manifest;
if (manifest == null) {
manifest = loadManifest();
this.manifest = manifest;
}
return (manifest != NO_MANIFEST) ? (Manifest) manifest : null;
}
|
Create a new {@link ExplodedArchive} instance.
@param rootDirectory the root directory
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/launch/ExplodedArchive.java
| 66
|
[] |
Manifest
| true
| 3
| 6.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
_convert_to_fill
|
def _convert_to_fill(cls, fill_dict: dict[str, Any]) -> Fill:
"""
Convert ``fill_dict`` to an openpyxl v2 Fill object.
Parameters
----------
fill_dict : dict
A dict with one or more of the following keys (or their synonyms),
'fill_type' ('patternType', 'patterntype')
'start_color' ('fgColor', 'fgcolor')
'end_color' ('bgColor', 'bgcolor')
or one or more of the following keys (or their synonyms).
'type' ('fill_type')
'degree'
'left'
'right'
'top'
'bottom'
'stop'
Returns
-------
fill : openpyxl.styles.Fill
"""
from openpyxl.styles import (
GradientFill,
PatternFill,
)
_pattern_fill_key_map = {
"patternType": "fill_type",
"patterntype": "fill_type",
"fgColor": "start_color",
"fgcolor": "start_color",
"bgColor": "end_color",
"bgcolor": "end_color",
}
_gradient_fill_key_map = {"fill_type": "type"}
pfill_kwargs = {}
gfill_kwargs = {}
for k, v in fill_dict.items():
pk = _pattern_fill_key_map.get(k)
gk = _gradient_fill_key_map.get(k)
if pk in ["start_color", "end_color"]:
v = cls._convert_to_color(v)
if gk == "stop":
v = cls._convert_to_stop(v)
if pk:
pfill_kwargs[pk] = v
elif gk:
gfill_kwargs[gk] = v
else:
pfill_kwargs[k] = v
gfill_kwargs[k] = v
try:
return PatternFill(**pfill_kwargs)
except TypeError:
return GradientFill(**gfill_kwargs)
|
Convert ``fill_dict`` to an openpyxl v2 Fill object.
Parameters
----------
fill_dict : dict
A dict with one or more of the following keys (or their synonyms),
'fill_type' ('patternType', 'patterntype')
'start_color' ('fgColor', 'fgcolor')
'end_color' ('bgColor', 'bgcolor')
or one or more of the following keys (or their synonyms).
'type' ('fill_type')
'degree'
'left'
'right'
'top'
'bottom'
'stop'
Returns
-------
fill : openpyxl.styles.Fill
|
python
|
pandas/io/excel/_openpyxl.py
| 250
|
[
"cls",
"fill_dict"
] |
Fill
| true
| 7
| 6.16
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
groups
|
public List<String> groups() {
return groups;
}
|
Get the groups for the configuration
@return a list of group names
|
java
|
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
| 485
|
[] | true
| 1
| 6.48
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
pad
|
def pad(
x: Array,
pad_width: int | tuple[int, int] | Sequence[tuple[int, int]],
mode: Literal["constant"] = "constant",
*,
constant_values: complex = 0,
xp: ModuleType | None = None,
) -> Array:
"""
Pad the input array.
Parameters
----------
x : array
Input array.
pad_width : int or tuple of ints or sequence of pairs of ints
Pad the input array with this many elements from each side.
If a sequence of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``,
each pair applies to the corresponding axis of ``x``.
A single tuple, ``(before, after)``, is equivalent to a list of ``x.ndim``
copies of this tuple.
mode : str, optional
Only "constant" mode is currently supported, which pads with
the value passed to `constant_values`.
constant_values : python scalar, optional
Use this value to pad the input. Default is zero.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
array
The input array,
padded with ``pad_width`` elements equal to ``constant_values``.
"""
xp = array_namespace(x) if xp is None else xp
if mode != "constant":
msg = "Only `'constant'` mode is currently supported"
raise NotImplementedError(msg)
if (
is_numpy_namespace(xp)
or is_cupy_namespace(xp)
or is_jax_namespace(xp)
or is_pydata_sparse_namespace(xp)
):
return xp.pad(x, pad_width, mode, constant_values=constant_values)
# https://github.com/pytorch/pytorch/blob/cf76c05b4dc629ac989d1fb8e789d4fac04a095a/torch/_numpy/_funcs_impl.py#L2045-L2056
if is_torch_namespace(xp):
pad_width = xp.asarray(pad_width)
pad_width = xp.broadcast_to(pad_width, (x.ndim, 2))
pad_width = xp.flip(pad_width, axis=(0,)).flatten()
return xp.nn.functional.pad(x, tuple(pad_width), value=constant_values) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
return _funcs.pad(x, pad_width, constant_values=constant_values, xp=xp)
|
Pad the input array.
Parameters
----------
x : array
Input array.
pad_width : int or tuple of ints or sequence of pairs of ints
Pad the input array with this many elements from each side.
If a sequence of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``,
each pair applies to the corresponding axis of ``x``.
A single tuple, ``(before, after)``, is equivalent to a list of ``x.ndim``
copies of this tuple.
mode : str, optional
Only "constant" mode is currently supported, which pads with
the value passed to `constant_values`.
constant_values : python scalar, optional
Use this value to pad the input. Default is zero.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
array
The input array,
padded with ``pad_width`` elements equal to ``constant_values``.
|
python
|
sklearn/externals/array_api_extra/_delegation.py
| 272
|
[
"x",
"pad_width",
"mode",
"constant_values",
"xp"
] |
Array
| true
| 8
| 6.8
|
scikit-learn/scikit-learn
| 64,340
|
numpy
| false
|
wait
|
def wait(
waiter: Waiter,
waiter_delay: int,
waiter_max_attempts: int,
args: dict[str, Any],
failure_message: str,
status_message: str,
status_args: list[str],
) -> None:
"""
Use a boto waiter to poll an AWS service for the specified state.
Although this function uses boto waiters to poll the state of the
service, it logs the response of the service after every attempt,
which is not currently supported by boto waiters.
:param waiter: The boto waiter to use.
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param args: The arguments to pass to the waiter.
:param failure_message: The message to log if a failure state is reached.
:param status_message: The message logged when printing the status of the service.
:param status_args: A list containing the JMESPath queries to retrieve status information from
the waiter response.
e.g.
response = {"Cluster": {"state": "CREATING"}}
status_args = ["Cluster.state"]
response = {
"Clusters": [{"state": "CREATING", "details": "User initiated."},]
}
status_args = ["Clusters[0].state", "Clusters[0].details"]
"""
log = logging.getLogger(__name__)
for attempt in range(waiter_max_attempts):
if attempt:
time.sleep(waiter_delay)
try:
waiter.wait(**args, WaiterConfig={"MaxAttempts": 1})
except NoCredentialsError as error:
log.info(str(error))
except WaiterError as error:
error_reason = str(error)
last_response = error.last_response
if "terminal failure" in error_reason:
log.error("%s: %s", failure_message, _LazyStatusFormatter(status_args, last_response))
raise AirflowException(f"{failure_message}: {error}")
if (
"An error occurred" in error_reason
and isinstance(last_response.get("Error"), dict)
and "Code" in last_response.get("Error")
):
raise AirflowException(f"{failure_message}: {error}")
log.info("%s: %s", status_message, _LazyStatusFormatter(status_args, last_response))
else:
break
else:
raise AirflowException("Waiter error: max attempts reached")
|
Use a boto waiter to poll an AWS service for the specified state.
Although this function uses boto waiters to poll the state of the
service, it logs the response of the service after every attempt,
which is not currently supported by boto waiters.
:param waiter: The boto waiter to use.
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param args: The arguments to pass to the waiter.
:param failure_message: The message to log if a failure state is reached.
:param status_message: The message logged when printing the status of the service.
:param status_args: A list containing the JMESPath queries to retrieve status information from
the waiter response.
e.g.
response = {"Cluster": {"state": "CREATING"}}
status_args = ["Cluster.state"]
response = {
"Clusters": [{"state": "CREATING", "details": "User initiated."},]
}
status_args = ["Clusters[0].state", "Clusters[0].details"]
|
python
|
providers/amazon/src/airflow/providers/amazon/aws/utils/waiter_with_logging.py
| 34
|
[
"waiter",
"waiter_delay",
"waiter_max_attempts",
"args",
"failure_message",
"status_message",
"status_args"
] |
None
| true
| 9
| 6.64
|
apache/airflow
| 43,597
|
sphinx
| false
|
appendln
|
public StrBuilder appendln(final StrBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
}
|
Appends part of a string builder followed by a new line to this string builder.
Appending null will call {@link #appendNull()}.
@param str the string to append
@param startIndex the start index, inclusive, must be valid
@param length the length to append, must be valid
@return {@code this} instance.
@since 2.3
|
java
|
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
| 1,053
|
[
"str",
"startIndex",
"length"
] |
StrBuilder
| true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
initializeBean
|
@SuppressWarnings("deprecation")
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
// Skip initialization of a NullBean
if (bean.getClass() == NullBean.class) {
return bean;
}
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null), beanName, ex.getMessage(), ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
|
Initialize the given bean instance, applying factory callbacks
as well as init methods and bean post processors.
<p>Called from {@link #createBean} for traditionally defined beans,
and from {@link #initializeBean} for existing bean instances.
@param beanName the bean name in the factory (for debugging purposes)
@param bean the new bean instance we may need to initialize
@param mbd the bean definition that the bean was created with
(can also be {@code null}, if given an existing bean instance)
@return the initialized bean instance (potentially wrapped)
@see BeanNameAware
@see BeanClassLoaderAware
@see BeanFactoryAware
@see #applyBeanPostProcessorsBeforeInitialization
@see #invokeInitMethods
@see #applyBeanPostProcessorsAfterInitialization
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
| 1,798
|
[
"beanName",
"bean",
"mbd"
] |
Object
| true
| 8
| 7.44
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
register
|
Cleanable register(Object obj, Runnable action);
|
Registers an object and the clean action to run when the object becomes phantom
reachable.
@param obj the object to monitor
@param action the cleanup action to run
@return a {@link Cleanable} instance
@see java.lang.ref.Cleaner#register(Object, Runnable)
|
java
|
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/ref/Cleaner.java
| 43
|
[
"obj",
"action"
] |
Cleanable
| true
| 1
| 6.48
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
onResponse
|
private void onResponse(
final long currentTimeMs,
final FindCoordinatorResponse response
) {
// handles Runtime exception
Optional<FindCoordinatorResponseData.Coordinator> coordinator = response.coordinatorByKey(this.groupId);
if (coordinator.isEmpty()) {
String msg = String.format("Response did not contain expected coordinator section for groupId: %s", this.groupId);
onFailedResponse(currentTimeMs, new IllegalStateException(msg));
return;
}
FindCoordinatorResponseData.Coordinator node = coordinator.get();
if (node.errorCode() != Errors.NONE.code()) {
onFailedResponse(currentTimeMs, Errors.forCode(node.errorCode()).exception());
return;
}
onSuccessfulResponse(currentTimeMs, node);
}
|
Handles the response upon completing the {@link FindCoordinatorRequest} if the
future returned successfully. This method must still unwrap the response object
to check for protocol errors.
@param currentTimeMs current time in ms.
@param response the response for finding the coordinator. null if an exception is thrown.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CoordinatorRequestManager.java
| 227
|
[
"currentTimeMs",
"response"
] |
void
| true
| 3
| 6.88
|
apache/kafka
| 31,560
|
javadoc
| false
|
h3ToFaceIjkWithInitializedFijk
|
private static boolean h3ToFaceIjkWithInitializedFijk(long h, FaceIJK fijk) {
final int res = H3Index.H3_get_resolution(h);
// center base cell hierarchy is entirely on this face
final boolean possibleOverage = BaseCells.isBaseCellPentagon(H3_get_base_cell(h))
|| (res != 0 && (fijk.coord.i != 0 || fijk.coord.j != 0 || fijk.coord.k != 0));
for (int r = 1; r <= res; r++) {
if (isResolutionClassIII(r)) {
// Class III == rotate ccw
fijk.coord.downAp7();
} else {
// Class II == rotate cw
fijk.coord.downAp7r();
}
fijk.coord.neighbor(H3_get_index_digit(h, r));
}
return possibleOverage;
}
|
Convert an H3Index to the FaceIJK address on a specified icosahedral face.
@param h The H3Index.
@param fijk The FaceIJK address, initialized with the desired face
and normalized base cell coordinates.
@return Returns true if the possibility of overage exists, otherwise false.
|
java
|
libs/h3/src/main/java/org/elasticsearch/h3/H3Index.java
| 266
|
[
"h",
"fijk"
] | true
| 7
| 8.08
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
|
numAssignedPartitions
|
public synchronized int numAssignedPartitions() {
return this.assignment.size();
}
|
Provides the number of assigned partitions in a thread safe manner.
@return the number of assigned partitions.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
| 481
|
[] | true
| 1
| 6.8
|
apache/kafka
| 31,560
|
javadoc
| false
|
|
downgrade
|
def downgrade():
"""Unapply Update dag_run_note.user_id and task_instance_note.user_id columns to String."""
# Handle the case where user_id contains string values that cannot be converted to integer
# This is necessary because the migration from 2.11.0 -> 3.0.0 changed user_id from Integer to String
# and when downgrading, we need to safely handle cases where string user_ids like "admin" exist
dialect_name = op.get_bind().dialect.name
# Clean up non-numeric user_id values before type conversion to prevent errors
if dialect_name == "postgresql":
# For PostgreSQL, use regex to identify non-integer values and set them to NULL
op.execute(
text("""
UPDATE dag_run_note
SET user_id = NULL
WHERE user_id IS NOT NULL
AND user_id !~ '^[0-9]+$'
""")
)
op.execute(
text("""
UPDATE task_instance_note
SET user_id = NULL
WHERE user_id IS NOT NULL
AND user_id !~ '^[0-9]+$'
""")
)
elif dialect_name == "mysql":
# For MySQL, use REGEXP to identify non-integer values
op.execute(
text("""
UPDATE dag_run_note
SET user_id = NULL
WHERE user_id IS NOT NULL
AND user_id NOT REGEXP '^[0-9]+$'
""")
)
op.execute(
text("""
UPDATE task_instance_note
SET user_id = NULL
WHERE user_id IS NOT NULL
AND user_id NOT REGEXP '^[0-9]+$'
""")
)
elif dialect_name == "sqlite":
# SQLite doesn't have regex, so use GLOB pattern matching
op.execute(
text("""
UPDATE dag_run_note
SET user_id = NULL
WHERE user_id IS NOT NULL
AND (user_id = '' OR user_id GLOB '*[^0-9]*')
""")
)
op.execute(
text("""
UPDATE task_instance_note
SET user_id = NULL
WHERE user_id IS NOT NULL
AND (user_id = '' OR user_id GLOB '*[^0-9]*')
""")
)
# Now alter the column types back to Integer
with op.batch_alter_table("dag_run_note") as batch_op:
if dialect_name == "postgresql":
batch_op.alter_column("user_id", type_=sa.Integer(), postgresql_using="user_id::integer")
else:
batch_op.alter_column("user_id", type_=sa.Integer())
with op.batch_alter_table("task_instance_note") as batch_op:
if dialect_name == "postgresql":
batch_op.alter_column("user_id", type_=sa.Integer(), postgresql_using="user_id::integer")
else:
batch_op.alter_column("user_id", type_=sa.Integer())
|
Unapply Update dag_run_note.user_id and task_instance_note.user_id columns to String.
|
python
|
airflow-core/src/airflow/migrations/versions/0035_3_0_0_update_user_id_type.py
| 49
|
[] | false
| 8
| 6
|
apache/airflow
| 43,597
|
unknown
| false
|
|
loadIndex
|
public static @Nullable CandidateComponentsIndex loadIndex(@Nullable ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = CandidateComponentsIndexLoader.class.getClassLoader();
}
return cache.computeIfAbsent(classLoaderToUse, CandidateComponentsIndexLoader::doLoadIndex);
}
|
Load and instantiate the {@link CandidateComponentsIndex} from
{@value #COMPONENTS_RESOURCE_LOCATION}, using the given class loader. If no
index is available, return {@code null}.
@param classLoader the ClassLoader to use for loading (can be {@code null} to use the default)
@return the index to use or {@code null} if no index was found
@throws IllegalArgumentException if any module index cannot
be loaded or if an error occurs while creating {@link CandidateComponentsIndex}
|
java
|
spring-context/src/main/java/org/springframework/context/index/CandidateComponentsIndexLoader.java
| 84
|
[
"classLoader"
] |
CandidateComponentsIndex
| true
| 2
| 7.6
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
listdir
|
def listdir(self):
"""
List files in the source Repository.
Returns
-------
files : list of str or pathlib.Path
List of file names (not containing a directory part).
Notes
-----
Does not currently work for remote repositories.
"""
if self._isurl(self._baseurl):
raise NotImplementedError(
"Directory listing of URLs, not supported yet.")
else:
return os.listdir(self._baseurl)
|
List files in the source Repository.
Returns
-------
files : list of str or pathlib.Path
List of file names (not containing a directory part).
Notes
-----
Does not currently work for remote repositories.
|
python
|
numpy/lib/_datasource.py
| 682
|
[
"self"
] | false
| 3
| 6.08
|
numpy/numpy
| 31,054
|
unknown
| false
|
|
keys
|
@SuppressWarnings("rawtypes")
public Iterator keys() {
return this.nameValuePairs.keySet().iterator();
}
|
Returns an iterator of the {@code String} names in this object. The returned
iterator supports {@link Iterator#remove() remove}, which will remove the
corresponding mapping from this object. If this object is modified after the
iterator is returned, the iterator's behavior is undefined. The order of the keys
is undefined.
@return the keys
|
java
|
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
| 678
|
[] |
Iterator
| true
| 1
| 6.96
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
extractSource
|
public @Nullable Object extractSource(Object sourceCandidate) {
return this.sourceExtractor.extractSource(sourceCandidate, this.resource);
}
|
Call the source extractor for the given source object.
@param sourceCandidate the original source object
@return the source object to store, or {@code null} for none.
@see #getSourceExtractor()
@see SourceExtractor#extractSource
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/parsing/ReaderContext.java
| 207
|
[
"sourceCandidate"
] |
Object
| true
| 1
| 6.16
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
if
|
FOLLY_GCC_DISABLE_NEW_SHADOW_WARNINGS \
if (bool SYNCHRONIZED_VAR(state) = false) { \
(void)::folly::detail::SYNCHRONIZED_macro_is_deprecated{}; \
}
|
NOTE: This API is deprecated. Use lock(), wlock(), rlock() or the withLock
functions instead. In the future it will be marked with a deprecation
attribute to emit build-time warnings, and then it will be removed entirely.
SYNCHRONIZED is the main facility that makes Synchronized<T>
helpful. It is a pseudo-statement that introduces a scope where the
object is locked. Inside that scope you get to access the unadorned
datum.
Example:
Synchronized<vector<int>> svector;
...
SYNCHRONIZED (svector) { ... use svector as a vector<int> ... }
or
SYNCHRONIZED (v, svector) { ... use v as a vector<int> ... }
Refer to folly/docs/Synchronized.md for a detailed explanation and more
examples.
|
cpp
|
folly/Synchronized.h
| 1,792
|
[] | true
| 1
| 7.04
|
facebook/folly
| 30,157
|
doxygen
| false
|
|
lastIndexOfAny
|
public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
int ret = INDEX_NOT_FOUND;
int tmp;
for (final CharSequence search : searchStrs) {
if (search == null) {
continue;
}
tmp = CharSequenceUtils.lastIndexOf(str, search, str.length());
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
|
Finds the latest index of any substring in a set of potential substrings.
<p>
A {@code null} CharSequence will return {@code -1}. A {@code null} search array will return {@code -1}. A {@code null} or zero length search array entry
will be ignored, but a search array containing "" will return the length of {@code str} if {@code str} is not null. This method uses
{@link String#indexOf(String)} if possible
</p>
<pre>
StringUtils.lastIndexOfAny(null, *) = -1
StringUtils.lastIndexOfAny(*, null) = -1
StringUtils.lastIndexOfAny(*, []) = -1
StringUtils.lastIndexOfAny(*, [null]) = -1
StringUtils.lastIndexOfAny("zzabyycdxx", ["ab", "cd"]) = 6
StringUtils.lastIndexOfAny("zzabyycdxx", ["cd", "ab"]) = 6
StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", "op"]) = -1
StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", "op"]) = -1
StringUtils.lastIndexOfAny("zzabyycdxx", ["mn", ""]) = 10
</pre>
@param str the CharSequence to check, may be null.
@param searchStrs the CharSequences to search for, may be null.
@return the last index of any of the CharSequences, -1 if no match.
@since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence)
|
java
|
src/main/java/org/apache/commons/lang3/StringUtils.java
| 4,917
|
[
"str"
] | true
| 5
| 7.6
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
getbufsize
|
def getbufsize():
"""
Return the size of the buffer used in ufuncs.
Returns
-------
getbufsize : int
Size of ufunc buffer in bytes.
Notes
-----
**Concurrency note:** see :doc:`/reference/routines.err`
Examples
--------
>>> import numpy as np
>>> np.getbufsize()
8192
"""
return _get_extobj_dict()["bufsize"]
|
Return the size of the buffer used in ufuncs.
Returns
-------
getbufsize : int
Size of ufunc buffer in bytes.
Notes
-----
**Concurrency note:** see :doc:`/reference/routines.err`
Examples
--------
>>> import numpy as np
>>> np.getbufsize()
8192
|
python
|
numpy/_core/_ufunc_config.py
| 208
|
[] | false
| 1
| 6.32
|
numpy/numpy
| 31,054
|
unknown
| false
|
|
_splitlines
|
def _splitlines(a, keepends=None):
"""
For each element in `a`, return a list of the lines in the
element, breaking at line boundaries.
Calls :meth:`str.splitlines` element-wise.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
keepends : bool, optional
Line breaks are not included in the resulting list unless
keepends is given and true.
Returns
-------
out : ndarray
Array of list objects
See Also
--------
str.splitlines
Examples
--------
>>> np.char.splitlines("first line\\nsecond line")
array(list(['first line', 'second line']), dtype=object)
>>> a = np.array(["first\\nsecond", "third\\nfourth"])
>>> np.char.splitlines(a)
array([list(['first', 'second']), list(['third', 'fourth'])], dtype=object)
"""
return _vec_string(
a, np.object_, 'splitlines', _clean_args(keepends))
|
For each element in `a`, return a list of the lines in the
element, breaking at line boundaries.
Calls :meth:`str.splitlines` element-wise.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
keepends : bool, optional
Line breaks are not included in the resulting list unless
keepends is given and true.
Returns
-------
out : ndarray
Array of list objects
See Also
--------
str.splitlines
Examples
--------
>>> np.char.splitlines("first line\\nsecond line")
array(list(['first line', 'second line']), dtype=object)
>>> a = np.array(["first\\nsecond", "third\\nfourth"])
>>> np.char.splitlines(a)
array([list(['first', 'second']), list(['third', 'fourth'])], dtype=object)
|
python
|
numpy/_core/strings.py
| 1,495
|
[
"a",
"keepends"
] | false
| 1
| 6
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
between
|
public static NumericEntityEscaper between(final int codePointLow, final int codePointHigh) {
return new NumericEntityEscaper(codePointLow, codePointHigh, true);
}
|
Constructs a {@link NumericEntityEscaper} between the specified values (inclusive).
@param codePointLow above which to escape.
@param codePointHigh below which to escape.
@return the newly created {@link NumericEntityEscaper} instance.
|
java
|
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityEscaper.java
| 58
|
[
"codePointLow",
"codePointHigh"
] |
NumericEntityEscaper
| true
| 1
| 6.16
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
describeDelegationToken
|
default DescribeDelegationTokenResult describeDelegationToken() {
return describeDelegationToken(new DescribeDelegationTokenOptions());
}
|
Describe the Delegation Tokens.
<p>
This is a convenience method for {@link #describeDelegationToken(DescribeDelegationTokenOptions)} with default options.
This will return all the user owned tokens and tokens where user have Describe permission. See the overload for more details.
@return The DescribeDelegationTokenResult.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 832
|
[] |
DescribeDelegationTokenResult
| true
| 1
| 6.16
|
apache/kafka
| 31,560
|
javadoc
| false
|
_set_names
|
def _set_names(self, values, *, level=None) -> None:
"""
Set new names on index. Each name has to be a hashable type.
Parameters
----------
values : str or sequence
name(s) to set
level : int, level name, or sequence of int/level names (default None)
If the index is a MultiIndex (hierarchical), level(s) to set (None
for all levels). Otherwise level must be None
Raises
------
TypeError if each name is not hashable.
"""
if not is_list_like(values):
raise ValueError("Names must be a list-like")
if len(values) != 1:
raise ValueError(f"Length of new names must be 1, got {len(values)}")
# GH 20527
# All items in 'name' need to be hashable:
validate_all_hashable(*values, error_name=f"{type(self).__name__}.name")
self._name = values[0]
|
Set new names on index. Each name has to be a hashable type.
Parameters
----------
values : str or sequence
name(s) to set
level : int, level name, or sequence of int/level names (default None)
If the index is a MultiIndex (hierarchical), level(s) to set (None
for all levels). Otherwise level must be None
Raises
------
TypeError if each name is not hashable.
|
python
|
pandas/core/indexes/base.py
| 1,920
|
[
"self",
"values",
"level"
] |
None
| true
| 3
| 7.04
|
pandas-dev/pandas
| 47,362
|
numpy
| false
|
_replace_nan
|
def _replace_nan(a, val):
"""
If `a` is of inexact type, make a copy of `a`, replace NaNs with
the `val` value, and return the copy together with a boolean mask
marking the locations where NaNs were present. If `a` is not of
inexact type, do nothing and return `a` together with a mask of None.
Note that scalars will end up as array scalars, which is important
for using the result as the value of the out argument in some
operations.
Parameters
----------
a : array-like
Input array.
val : float
NaN values are set to val before doing the operation.
Returns
-------
y : ndarray
If `a` is of inexact type, return a copy of `a` with the NaNs
replaced by the fill value, otherwise return `a`.
mask: {bool, None}
If `a` is of inexact type, return a boolean mask marking locations of
NaNs, otherwise return None.
"""
a = np.asanyarray(a)
if a.dtype == np.object_:
# object arrays do not support `isnan` (gh-9009), so make a guess
mask = np.not_equal(a, a, dtype=bool)
elif issubclass(a.dtype.type, np.inexact):
mask = np.isnan(a)
else:
mask = None
if mask is not None:
a = np.array(a, subok=True, copy=True)
np.copyto(a, val, where=mask)
return a, mask
|
If `a` is of inexact type, make a copy of `a`, replace NaNs with
the `val` value, and return the copy together with a boolean mask
marking the locations where NaNs were present. If `a` is not of
inexact type, do nothing and return `a` together with a mask of None.
Note that scalars will end up as array scalars, which is important
for using the result as the value of the out argument in some
operations.
Parameters
----------
a : array-like
Input array.
val : float
NaN values are set to val before doing the operation.
Returns
-------
y : ndarray
If `a` is of inexact type, return a copy of `a` with the NaNs
replaced by the fill value, otherwise return `a`.
mask: {bool, None}
If `a` is of inexact type, return a boolean mask marking locations of
NaNs, otherwise return None.
|
python
|
numpy/lib/_nanfunctions_impl.py
| 70
|
[
"a",
"val"
] | false
| 5
| 6.24
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
getStrategy
|
private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) {
switch (f) {
case 'D':
return DAY_OF_YEAR_STRATEGY;
case 'E':
return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar);
case 'F':
return DAY_OF_WEEK_IN_MONTH_STRATEGY;
case 'G':
return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
case 'H': // Hour in day (0-23)
return HOUR_OF_DAY_STRATEGY;
case 'K': // Hour in am/pm (0-11)
return HOUR_STRATEGY;
case 'M':
case 'L':
return width >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY;
case 'S':
return MILLISECOND_STRATEGY;
case 'W':
return WEEK_OF_MONTH_STRATEGY;
case 'a':
return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
case 'd':
return DAY_OF_MONTH_STRATEGY;
case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0
return HOUR12_STRATEGY;
case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0
return HOUR24_OF_DAY_STRATEGY;
case 'm':
return MINUTE_STRATEGY;
case 's':
return SECOND_STRATEGY;
case 'u':
return DAY_OF_WEEK_STRATEGY;
case 'w':
return WEEK_OF_YEAR_STRATEGY;
case 'y':
case 'Y':
return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY;
case 'X':
return ISO8601TimeZoneStrategy.getStrategy(width);
case 'Z':
if (width == 2) {
return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY;
}
// falls-through
case 'z':
return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar);
default:
throw new IllegalArgumentException("Format '" + f + "' not supported");
}
}
|
Gets a Strategy given a field from a SimpleDateFormat pattern
@param f A sub-sequence of the SimpleDateFormat pattern
@param width formatting width
@param definingCalendar The calendar to obtain the short and long values
@return The Strategy that will handle parsing for the field
|
java
|
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
| 923
|
[
"f",
"width",
"definingCalendar"
] |
Strategy
| true
| 4
| 7.2
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
background
|
public static Ansi8BitColor background(int code) {
return new Ansi8BitColor("48;5;", code);
}
|
Return a background ANSI color code instance for the given code.
@param code the color code
@return an ANSI color code instance
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/ansi/Ansi8BitColor.java
| 84
|
[
"code"
] |
Ansi8BitColor
| true
| 1
| 6.96
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
deleteAcls
|
DeleteAclsResult deleteAcls(Collection<AclBindingFilter> filters, DeleteAclsOptions options);
|
Deletes access control lists (ACLs) according to the supplied filters.
<p>
This operation is not transactional so it may succeed for some ACLs while fail for others.
<p>
This operation is supported by brokers with version 0.11.0.0 or higher.
@param filters The filters to use.
@param options The options to use when deleting the ACLs.
@return The DeleteAclsResult.
|
java
|
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
| 437
|
[
"filters",
"options"
] |
DeleteAclsResult
| true
| 1
| 6.48
|
apache/kafka
| 31,560
|
javadoc
| false
|
leastLoadedNode
|
public Node leastLoadedNode() {
lock.lock();
try {
return client.leastLoadedNode(time.milliseconds()).node();
} finally {
lock.unlock();
}
}
|
Send a new request. Note that the request is not actually transmitted on the
network until one of the {@link #poll(Timer)} variants is invoked. At this
point the request will either be transmitted successfully or will fail.
Use the returned future to obtain the result of the send. Note that there is no
need to check for disconnects explicitly on the {@link ClientResponse} object;
instead, the future will be failed with a {@link DisconnectException}.
@param node The destination of the request
@param requestBuilder A builder for the request payload
@param requestTimeoutMs Maximum time in milliseconds to await a response before disconnecting the socket and
cancelling the request. The request may be cancelled sooner if the socket disconnects
for any reason.
@return A future which indicates the result of the send.
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkClient.java
| 140
|
[] |
Node
| true
| 1
| 6.72
|
apache/kafka
| 31,560
|
javadoc
| false
|
selectNumberRule
|
protected NumberRule selectNumberRule(final int field, final int padding) {
switch (padding) {
case 1:
return new UnpaddedNumberField(field);
case 2:
return new TwoDigitNumberField(field);
default:
return new PaddedNumberField(field, padding);
}
}
|
Gets an appropriate rule for the padding required.
@param field the field to get a rule for.
@param padding the padding required.
@return a new rule with the correct padding.
|
java
|
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
| 1,545
|
[
"field",
"padding"
] |
NumberRule
| true
| 1
| 7.04
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
iterator
|
CopyableBucketIterator iterator();
|
@return a {@link BucketIterator} for the populated buckets of this bucket range.
The {@link BucketIterator#scale()} of the returned iterator must be the same as {@link #scale()}.
|
java
|
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogram.java
| 135
|
[] |
CopyableBucketIterator
| true
| 1
| 6.32
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
of
|
public static <L, M, R> MutableTriple<L, M, R> of(final L left, final M middle, final R right) {
return new MutableTriple<>(left, middle, right);
}
|
Obtains a mutable triple of three objects inferring the generic types.
@param <L> the left element type.
@param <M> the middle element type.
@param <R> the right element type.
@param left the left element, may be null.
@param middle the middle element, may be null.
@param right the right element, may be null.
@return a mutable triple formed from the three parameters, not null.
|
java
|
src/main/java/org/apache/commons/lang3/tuple/MutableTriple.java
| 71
|
[
"left",
"middle",
"right"
] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
get_param_and_grad_nodes
|
def get_param_and_grad_nodes(
graph: fx.Graph,
) -> dict[ParamAOTInput, tuple[fx.Node, Optional[fx.Node]]]:
"""Get parameter nodes and their corresponding gradient nodes from a joint graph.
Args:
graph: The FX joint graph with descriptors
Returns:
A dictionary mapping each ParamAOTInput descriptor to a tuple containing:
- The parameter input node
- The gradient (output) node if it exists, None otherwise
"""
return {
desc: (n, g)
for desc, (n, g) in get_all_input_and_grad_nodes(graph).items()
if isinstance(desc, ParamAOTInput)
}
|
Get parameter nodes and their corresponding gradient nodes from a joint graph.
Args:
graph: The FX joint graph with descriptors
Returns:
A dictionary mapping each ParamAOTInput descriptor to a tuple containing:
- The parameter input node
- The gradient (output) node if it exists, None otherwise
|
python
|
torch/_functorch/_aot_autograd/fx_utils.py
| 147
|
[
"graph"
] |
dict[ParamAOTInput, tuple[fx.Node, Optional[fx.Node]]]
| true
| 1
| 6.4
|
pytorch/pytorch
| 96,034
|
google
| false
|
handleCommittedResponse
|
private void handleCommittedResponse(HttpServletRequest request, @Nullable Throwable ex) {
if (isClientAbortException(ex)) {
return;
}
String message = "Cannot forward to error page for request " + getDescription(request)
+ " as the response has already been"
+ " committed. As a result, the response may have the wrong status"
+ " code. If your application is running on WebSphere Application"
+ " Server you may be able to resolve this problem by setting"
+ " com.ibm.ws.webcontainer.invokeFlushAfterService to false";
if (ex == null) {
logger.error(message);
}
else {
// User might see the error page without all the data here but throwing the
// exception isn't going to help anyone (we'll log it to be on the safe side)
logger.error(message, ex);
}
}
|
Return the description for the given request. By default this method will return a
description based on the request {@code servletPath} and {@code pathInfo}.
@param request the source request
@return the description
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java
| 206
|
[
"request",
"ex"
] |
void
| true
| 3
| 8.08
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
visitObjectLiteralExpression
|
function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression {
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
// spread elements emit like so:
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
// { a, ...o, b } => __assign(__assign({a}, o), {b});
// If the first element is a spread element, then the first argument to __assign is {}:
// { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
//
// We cannot call __assign with more than two elements, since any element could cause side effects. For
// example:
// var k = { a: 1, b: 2 };
// var o = { a: 3, ...k, b: k.a++ };
// // expected: { a: 1, b: 1 }
// If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
// `k` is spread and we end up with `{ a: 2, b: 1 }`.
//
// This also occurs for spread elements, not just property assignments:
// var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
// var l = { c: 3 };
// var o = { ...k, ...l };
// // expected: { a: 1, b: 2, z: 9 }
// If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
// end up with `{ a: 1, b: 2, c: 3 }`
const objects = chunkObjectLiteralElements(node.properties);
if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) {
objects.unshift(factory.createObjectLiteralExpression());
}
let expression: Expression = objects[0];
if (objects.length > 1) {
for (let i = 1; i < objects.length; i++) {
expression = emitHelpers().createAssignHelper([expression, objects[i]]);
}
return expression;
}
else {
return emitHelpers().createAssignHelper(objects);
}
}
return visitEachChild(node, visitor, context);
}
|
@param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
expression of an `ExpressionStatement`).
|
typescript
|
src/compiler/transformers/es2018.ts
| 510
|
[
"node"
] | true
| 7
| 6.88
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
asEnum
|
private static <E extends Enum<E>> Class<E> asEnum(final Class<E> enumClass) {
Objects.requireNonNull(enumClass, ENUM_CLASS_MUST_BE_DEFINED);
Validate.isTrue(enumClass.isEnum(), S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE, enumClass);
return enumClass;
}
|
Validate {@code enumClass}.
@param <E> the type of the enumeration.
@param enumClass to check.
@return {@code enumClass}.
@throws NullPointerException if {@code enumClass} is {@code null}.
@throws IllegalArgumentException if {@code enumClass} is not an enum class.
@since 3.2
|
java
|
src/main/java/org/apache/commons/lang3/EnumUtils.java
| 57
|
[
"enumClass"
] | true
| 1
| 6.56
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
indexOf
|
int indexOf(Advice advice);
|
Return the index (from 0) of the given AOP Alliance Advice,
or -1 if no such advice is an advice for this proxy.
<p>The return value of this method can be used to index into
the advisors array.
@param advice the AOP Alliance advice to search for
@return index from 0 of this advice, or -1 if there's no such advice
|
java
|
spring-aop/src/main/java/org/springframework/aop/framework/Advised.java
| 226
|
[
"advice"
] | true
| 1
| 6.8
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
bind
|
public <T> BindResult<T> bind(String name, Class<T> target) {
return bind(name, Bindable.of(target));
}
|
Bind the specified target {@link Class} using this binder's
{@link ConfigurationPropertySource property sources}.
@param name the configuration property name to bind
@param target the target class
@param <T> the bound type
@return the binding result (never {@code null})
@see #bind(ConfigurationPropertyName, Bindable, BindHandler)
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java
| 234
|
[
"name",
"target"
] | true
| 1
| 6
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
|
broadcast_shapes
|
def broadcast_shapes(*args):
"""
Broadcast the input shapes into a single shape.
:ref:`Learn more about broadcasting here <basics.broadcasting>`.
.. versionadded:: 1.20.0
Parameters
----------
*args : tuples of ints, or ints
The shapes to be broadcast against each other.
Returns
-------
tuple
Broadcasted shape.
Raises
------
ValueError
If the shapes are not compatible and cannot be broadcast according
to NumPy's broadcasting rules.
See Also
--------
broadcast
broadcast_arrays
broadcast_to
Examples
--------
>>> import numpy as np
>>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
(3, 2)
>>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
(5, 6, 7)
"""
arrays = [np.empty(x, dtype=_size0_dtype) for x in args]
return _broadcast_shape(*arrays)
|
Broadcast the input shapes into a single shape.
:ref:`Learn more about broadcasting here <basics.broadcasting>`.
.. versionadded:: 1.20.0
Parameters
----------
*args : tuples of ints, or ints
The shapes to be broadcast against each other.
Returns
-------
tuple
Broadcasted shape.
Raises
------
ValueError
If the shapes are not compatible and cannot be broadcast according
to NumPy's broadcasting rules.
See Also
--------
broadcast
broadcast_arrays
broadcast_to
Examples
--------
>>> import numpy as np
>>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
(3, 2)
>>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
(5, 6, 7)
|
python
|
numpy/lib/_stride_tricks_impl.py
| 467
|
[] | false
| 1
| 6.48
|
numpy/numpy
| 31,054
|
numpy
| false
|
|
resolveArguments
|
private AutowiredArguments resolveArguments(RegisteredBean registeredBean, Executable executable) {
int parameterCount = executable.getParameterCount();
@Nullable Object[] resolved = new Object[parameterCount];
Assert.isTrue(this.shortcutBeanNames == null || this.shortcutBeanNames.length == resolved.length,
() -> "'shortcuts' must contain " + resolved.length + " elements");
ValueHolder[] argumentValues = resolveArgumentValues(registeredBean, executable);
Set<String> autowiredBeanNames = new LinkedHashSet<>(resolved.length * 2);
int startIndex = (executable instanceof Constructor<?> constructor &&
ClassUtils.isInnerClass(constructor.getDeclaringClass())) ? 1 : 0;
for (int i = startIndex; i < parameterCount; i++) {
MethodParameter parameter = getMethodParameter(executable, i);
DependencyDescriptor descriptor = new DependencyDescriptor(parameter, true);
String shortcut = (this.shortcutBeanNames != null ? this.shortcutBeanNames[i] : null);
if (shortcut != null) {
descriptor = new ShortcutDependencyDescriptor(descriptor, shortcut);
}
ValueHolder argumentValue = argumentValues[i];
resolved[i] = resolveAutowiredArgument(
registeredBean, descriptor, argumentValue, autowiredBeanNames);
}
registerDependentBeans(registeredBean.getBeanFactory(), registeredBean.getBeanName(), autowiredBeanNames);
return AutowiredArguments.of(resolved);
}
|
Resolve arguments for the specified registered bean.
@param registeredBean the registered bean
@return the resolved constructor or factory method arguments
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanInstanceSupplier.java
| 244
|
[
"registeredBean",
"executable"
] |
AutowiredArguments
| true
| 7
| 7.28
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
contains
|
public static boolean contains(final int[] array, final int valueToFind) {
return indexOf(array, valueToFind) != INDEX_NOT_FOUND;
}
|
Checks if the value is in the given array.
<p>
The method returns {@code false} if a {@code null} array is passed in.
</p>
<p>
If the {@code array} elements you are searching implement {@link Comparator}, consider whether it is worth using
{@link Arrays#sort(int[])} and {@link Arrays#binarySearch(int[], int)}.
</p>
@param array the array to search.
@param valueToFind the value to find.
@return {@code true} if the array contains the object.
|
java
|
src/main/java/org/apache/commons/lang3/ArrayUtils.java
| 1,688
|
[
"array",
"valueToFind"
] | true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
asBiPredicate
|
public static <T, U> BiPredicate<T, U> asBiPredicate(final FailableBiPredicate<T, U, ?> predicate) {
return (input1, input2) -> test(predicate, input1, input2);
}
|
Converts the given {@link FailableBiPredicate} into a standard {@link BiPredicate}.
@param <T> the type of the first argument used by the predicates
@param <U> the type of the second argument used by the predicates
@param predicate a {@link FailableBiPredicate}
@return a standard {@link BiPredicate}
|
java
|
src/main/java/org/apache/commons/lang3/function/Failable.java
| 317
|
[
"predicate"
] | true
| 1
| 6.48
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
toString
|
@Override
public String toString() {
return super.toString() + ' ' + Arrays.toString(chars);
}
|
Tests whether or not the given text matches the stored string.
@param buffer the text content to match against, do not change.
@param pos the starting position for the match, valid for buffer.
@param bufferStart the first active index in the buffer, valid for buffer.
@param bufferEnd the end index of the active buffer, valid for buffer.
@return the number of matching characters, zero for no match.
|
java
|
src/main/java/org/apache/commons/lang3/text/StrMatcher.java
| 165
|
[] |
String
| true
| 1
| 6.8
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
log
|
public void log(@Nullable Log logger, Object message, @Nullable Throwable cause) {
if (logger != null && this.logMethod != null) {
this.logMethod.log(logger, message, cause);
}
}
|
Log a message to the given logger at this level.
@param logger the logger
@param message the message to log
@param cause the cause to log
@since 3.1.0
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/logging/LogLevel.java
| 67
|
[
"logger",
"message",
"cause"
] |
void
| true
| 3
| 7.04
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
xContentType
|
@Deprecated
public static XContentType xContentType(CharSequence content) {
int length = content.length() < GUESS_HEADER_LENGTH ? content.length() : GUESS_HEADER_LENGTH;
if (length == 0) {
return null;
}
char first = content.charAt(0);
if (JsonXContent.jsonXContent.detectContent(content)) {
return XContentType.JSON;
}
// Should we throw a failure here? Smile idea is to use it in bytes....
if (SmileXContent.smileXContent.detectContent(content)) {
return XContentType.SMILE;
}
if (YamlXContent.yamlXContent.detectContent(content)) {
return XContentType.YAML;
}
// CBOR is not supported
// fallback for JSON
for (int i = 0; i < length; i++) {
char c = content.charAt(i);
if (c == '{') {
return XContentType.JSON;
}
if (Character.isWhitespace(c) == false) {
break;
}
}
return null;
}
|
Guesses the content type based on the provided char sequence.
@deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
This method is deprecated to prevent usages of it from spreading further without specific reasons.
|
java
|
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentFactory.java
| 138
|
[
"content"
] |
XContentType
| true
| 9
| 6
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
factoriesAndBeans
|
public static Loader factoriesAndBeans(SpringFactoriesLoader springFactoriesLoader, ListableBeanFactory beanFactory) {
Assert.notNull(beanFactory, "'beanFactory' must not be null");
Assert.notNull(springFactoriesLoader, "'springFactoriesLoader' must not be null");
return new Loader(springFactoriesLoader, beanFactory);
}
|
Create a new {@link Loader} that will obtain AOT services from the given
{@link SpringFactoriesLoader} and {@link ListableBeanFactory}.
@param springFactoriesLoader the spring factories loader
@param beanFactory the bean factory
@return a new {@link Loader} instance
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/aot/AotServices.java
| 132
|
[
"springFactoriesLoader",
"beanFactory"
] |
Loader
| true
| 1
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
setResolvedFactoryMethod
|
public void setResolvedFactoryMethod(@Nullable Method method) {
this.factoryMethodToIntrospect = method;
if (method != null) {
setUniqueFactoryMethodName(method.getName());
}
}
|
Set a resolved Java Method for the factory method on this bean definition.
@param method the resolved factory method, or {@code null} to reset it
@since 5.2
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java
| 424
|
[
"method"
] |
void
| true
| 2
| 7.04
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
indexOf
|
private static int indexOf(boolean[] array, boolean target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
|
Returns the index of the first appearance of the value {@code target} in {@code array}.
<p><b>Note:</b> consider representing the array as a {@link java.util.BitSet} instead, and
using {@link java.util.BitSet#nextSetBit(int)} or {@link java.util.BitSet#nextClearBit(int)}.
@param array an array of {@code boolean} values, possibly empty
@param target a primitive {@code boolean} value
@return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
such index exists.
|
java
|
android/guava/src/com/google/common/primitives/Booleans.java
| 166
|
[
"array",
"target",
"start",
"end"
] | true
| 3
| 7.6
|
google/guava
| 51,352
|
javadoc
| false
|
|
parseNameOfParameter
|
function parseNameOfParameter(modifiers: NodeArray<ModifierLike> | undefined) {
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
if (getFullWidth(name) === 0 && !some(modifiers) && isModifierKind(token())) {
// in cases like
// 'use strict'
// function foo(static)
// isParameter('static') === true, because of isModifier('static')
// however 'static' is not a legal identifier in a strict mode.
// so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
// and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
// to avoid this we'll advance cursor to the next token.
nextToken();
}
return name;
}
|
Reports a diagnostic error for the current token being an invalid name.
@param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
@param nameDiagnostic Diagnostic to report for all other cases.
@param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
|
typescript
|
src/compiler/parser.ts
| 4,001
|
[
"modifiers"
] | false
| 4
| 6.08
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
equals
|
private static boolean equals(final Type[] type1, final Type[] type2) {
if (type1.length == type2.length) {
for (int i = 0; i < type1.length; i++) {
if (!equals(type1[i], type2[i])) {
return false;
}
}
return true;
}
return false;
}
|
Tests whether the given type arrays are equal.
@param type1 LHS.
@param type2 RHS.
@return Whether the given type arrays are equal.
|
java
|
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
| 509
|
[
"type1",
"type2"
] | true
| 4
| 8.24
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
lock
|
public static Striped<Lock> lock(int stripes) {
return custom(stripes, PaddedLock::new);
}
|
Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks. Every lock
is reentrant.
@param stripes the minimum number of stripes (locks) required
@return a new {@code Striped<Lock>}
|
java
|
android/guava/src/com/google/common/util/concurrent/Striped.java
| 208
|
[
"stripes"
] | true
| 1
| 6.48
|
google/guava
| 51,352
|
javadoc
| false
|
|
asEmbeddedStatement
|
function asEmbeddedStatement<T extends Node>(statement: T | undefined): T | EmptyStatement | undefined {
return statement && isNotEmittedStatement(statement) ? setTextRange(setOriginal(createEmptyStatement(), statement), statement) : statement;
}
|
Lifts a NodeArray containing only Statement nodes to a block.
@param nodes The NodeArray.
|
typescript
|
src/compiler/factory/nodeFactory.ts
| 7,163
|
[
"statement"
] | true
| 3
| 6.48
|
microsoft/TypeScript
| 107,154
|
jsdoc
| false
|
|
resetBeanDefinition
|
protected void resetBeanDefinition(String beanName) {
// Remove the merged bean definition for the given bean, if already created.
clearMergedBeanDefinition(beanName);
// Remove corresponding bean from singleton cache, if any. Shouldn't usually
// be necessary, rather just meant for overriding a context's default beans
// (for example, the default StaticMessageSource in a StaticApplicationContext).
destroySingleton(beanName);
// Remove a cached primary marker for the given bean.
this.primaryBeanNamesWithType.remove(beanName);
// Notify all post-processors that the specified bean definition has been reset.
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
processor.resetBeanDefinition(beanName);
}
// Reset all bean definitions that have the given bean as parent (recursively).
for (String bdName : this.beanDefinitionNames) {
if (!beanName.equals(bdName)) {
BeanDefinition bd = this.beanDefinitionMap.get(bdName);
// Ensure bd is non-null due to potential concurrent modification of beanDefinitionMap.
if (bd != null && beanName.equals(bd.getParentName())) {
resetBeanDefinition(bdName);
}
}
}
}
|
Reset all bean definition caches for the given bean,
including the caches of beans that are derived from it.
<p>Called after an existing bean definition has been replaced or removed,
triggering {@link #clearMergedBeanDefinition}, {@link #destroySingleton}
and {@link MergedBeanDefinitionPostProcessor#resetBeanDefinition} on the
given bean and on all bean definitions that have the given bean as parent.
@param beanName the name of the bean to reset
@see #registerBeanDefinition
@see #removeBeanDefinition
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
| 1,405
|
[
"beanName"
] |
void
| true
| 4
| 6.24
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
setdiff1d
|
def setdiff1d(ar1, ar2, assume_unique=False):
"""
Set difference of 1D arrays with unique elements.
The output is always a masked array. See `numpy.setdiff1d` for more
details.
See Also
--------
numpy.setdiff1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
>>> np.ma.setdiff1d(x, [1, 2])
masked_array(data=[3, --],
mask=[False, True],
fill_value=999999)
"""
if assume_unique:
ar1 = ma.asarray(ar1).ravel()
else:
ar1 = unique(ar1)
ar2 = unique(ar2)
return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]
|
Set difference of 1D arrays with unique elements.
The output is always a masked array. See `numpy.setdiff1d` for more
details.
See Also
--------
numpy.setdiff1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
>>> np.ma.setdiff1d(x, [1, 2])
masked_array(data=[3, --],
mask=[False, True],
fill_value=999999)
|
python
|
numpy/ma/extras.py
| 1,487
|
[
"ar1",
"ar2",
"assume_unique"
] | false
| 3
| 6.32
|
numpy/numpy
| 31,054
|
unknown
| false
|
|
map
|
public <R> FailableStream<R> map(final FailableFunction<O, R, ?> mapper) {
assertNotTerminated();
return new FailableStream<>(stream.map(Functions.asFunction(mapper)));
}
|
Returns a stream consisting of the results of applying the given
function to the elements of this stream.
<p>
This is an intermediate operation.
</p>
@param <R> The element type of the new stream.
@param mapper A non-interfering, stateless function to apply to each element.
@return the new stream.
|
java
|
src/main/java/org/apache/commons/lang3/Streams.java
| 387
|
[
"mapper"
] | true
| 1
| 6.96
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
build
|
public SimpleAsyncTaskScheduler build() {
return configure(new SimpleAsyncTaskScheduler());
}
|
Build a new {@link SimpleAsyncTaskScheduler} instance and configure it using this
builder.
@return a configured {@link SimpleAsyncTaskScheduler} instance.
@see #configure(SimpleAsyncTaskScheduler)
|
java
|
core/spring-boot/src/main/java/org/springframework/boot/task/SimpleAsyncTaskSchedulerBuilder.java
| 191
|
[] |
SimpleAsyncTaskScheduler
| true
| 1
| 6
|
spring-projects/spring-boot
| 79,428
|
javadoc
| false
|
setConstructorArguments
|
public void setConstructorArguments(Object @Nullable [] constructorArgs, Class<?> @Nullable [] constructorArgTypes) {
if (constructorArgs == null || constructorArgTypes == null) {
throw new IllegalArgumentException("Both 'constructorArgs' and 'constructorArgTypes' need to be specified");
}
if (constructorArgs.length != constructorArgTypes.length) {
throw new IllegalArgumentException("Number of 'constructorArgs' (" + constructorArgs.length +
") must match number of 'constructorArgTypes' (" + constructorArgTypes.length + ")");
}
this.constructorArgs = constructorArgs;
this.constructorArgTypes = constructorArgTypes;
}
|
Set constructor arguments to use for creating the proxy.
@param constructorArgs the constructor argument values
@param constructorArgTypes the constructor argument types
|
java
|
spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java
| 146
|
[
"constructorArgs",
"constructorArgTypes"
] |
void
| true
| 4
| 6.08
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
unwrap
|
public final TypeToken<T> unwrap() {
if (isWrapper()) {
@SuppressWarnings("unchecked") // this is a wrapper class
Class<T> type = (Class<T>) runtimeType;
return of(Primitives.unwrap(type));
}
return this;
}
|
Returns the corresponding primitive type if this is a wrapper type; otherwise returns {@code
this} itself. Idempotent.
@since 15.0
|
java
|
android/guava/src/com/google/common/reflect/TypeToken.java
| 572
|
[] | true
| 2
| 7.04
|
google/guava
| 51,352
|
javadoc
| false
|
|
lazyReverse
|
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
|
Reverses the direction of lazy iteration.
@private
@name reverse
@memberOf LazyWrapper
@returns {Object} Returns the new reversed `LazyWrapper` object.
|
javascript
|
lodash.js
| 1,864
|
[] | false
| 3
| 6.48
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
using
|
static <T> InstanceSupplier<T> using(@Nullable Method factoryMethod, ThrowingSupplier<T> supplier) {
Assert.notNull(supplier, "Supplier must not be null");
if (supplier instanceof InstanceSupplier<T> instanceSupplier &&
instanceSupplier.getFactoryMethod() == factoryMethod) {
return instanceSupplier;
}
return new InstanceSupplier<>() {
@Override
public T get(RegisteredBean registeredBean) throws Exception {
return supplier.getWithException();
}
@Override
public @Nullable Method getFactoryMethod() {
return factoryMethod;
}
};
}
|
Factory method to create an {@link InstanceSupplier} from a
{@link ThrowingSupplier}.
@param <T> the type of instance supplied by this supplier
@param factoryMethod the factory method being used
@param supplier the source supplier
@return a new {@link InstanceSupplier}
|
java
|
spring-beans/src/main/java/org/springframework/beans/factory/support/InstanceSupplier.java
| 115
|
[
"factoryMethod",
"supplier"
] | true
| 3
| 7.28
|
spring-projects/spring-framework
| 59,386
|
javadoc
| false
|
|
shortToByteArray
|
public static byte[] shortToByteArray(final short src, final int srcPos, final byte[] dst, final int dstPos, final int nBytes) {
if (0 == nBytes) {
return dst;
}
if ((nBytes - 1) * Byte.SIZE + srcPos >= Short.SIZE) {
throw new IllegalArgumentException("(nBytes - 1) * 8 + srcPos >= 16");
}
for (int i = 0; i < nBytes; i++) {
final int shift = i * Byte.SIZE + srcPos;
dst[dstPos + i] = (byte) (0xff & src >> shift);
}
return dst;
}
|
Converts a short into an array of byte using the default (little-endian, LSB0) byte and bit ordering.
@param src the short to convert.
@param srcPos the position in {@code src}, in bits, from where to start the conversion.
@param dst the destination array.
@param dstPos the position in {@code dst} where to copy the result.
@param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the width of the input (from srcPos to MSB).
@return {@code dst}.
@throws NullPointerException if {@code dst} is {@code null}.
@throws IllegalArgumentException if {@code (nBytes - 1) * 8 + srcPos >= 16}.
@throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}.
|
java
|
src/main/java/org/apache/commons/lang3/Conversion.java
| 1,314
|
[
"src",
"srcPos",
"dst",
"dstPos",
"nBytes"
] | true
| 4
| 8.08
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
|
startsWithLower
|
function startsWithLower(string: string) {
const character = string.charAt(0);
return (character.toLocaleUpperCase() !== character) ? true : false;
}
|
@returns `true` if the string is starts with a lowercase letter. Otherwise, `false`.
|
typescript
|
src/vs/base/common/comparers.ts
| 218
|
[
"string"
] | false
| 2
| 6.16
|
microsoft/vscode
| 179,840
|
jsdoc
| false
|
|
fill_value
|
def fill_value(self):
"""
Elements in `data` that are `fill_value` are not stored.
For memory savings, this should be the most common value in the array.
See Also
--------
SparseDtype : Dtype for data stored in :class:`SparseArray`.
Series.value_counts : Return a Series containing counts of unique values.
Series.fillna : Fill NA/NaN in a Series with a specified value.
Examples
--------
>>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]")
>>> ser.sparse.fill_value
0
>>> spa_dtype = pd.SparseDtype(dtype=np.int32, fill_value=2)
>>> ser = pd.Series([0, 0, 2, 2, 2], dtype=spa_dtype)
>>> ser.sparse.fill_value
2
"""
return self.dtype.fill_value
|
Elements in `data` that are `fill_value` are not stored.
For memory savings, this should be the most common value in the array.
See Also
--------
SparseDtype : Dtype for data stored in :class:`SparseArray`.
Series.value_counts : Return a Series containing counts of unique values.
Series.fillna : Fill NA/NaN in a Series with a specified value.
Examples
--------
>>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]")
>>> ser.sparse.fill_value
0
>>> spa_dtype = pd.SparseDtype(dtype=np.int32, fill_value=2)
>>> ser = pd.Series([0, 0, 2, 2, 2], dtype=spa_dtype)
>>> ser.sparse.fill_value
2
|
python
|
pandas/core/arrays/sparse/array.py
| 683
|
[
"self"
] | false
| 1
| 6.32
|
pandas-dev/pandas
| 47,362
|
unknown
| false
|
|
randomUUID
|
function randomUUID() {
let uuid = '';
const chars = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
for (let i = 0; i < chars.length; i++) {
const randomValue = (Math.random() * 16) | 0; // Generate random value (0-15)
if (chars[i] === 'x') {
uuid += randomValue.toString(16); // Replace 'x' with random hex value
} else if (chars[i] === 'y') {
uuid += ((randomValue & 0x3) | 0x8).toString(16); // Replace 'y' with a value between 8 and 11
} else {
uuid += chars[i]; // Preserve the dashes and '4' in the template
}
}
return uuid;
}
|
@license
Copyright Google LLC All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE file at https://angular.dev/license
|
typescript
|
modules/ssr-benchmarks/test-data.ts
| 16
|
[] | false
| 6
| 6.24
|
angular/angular
| 99,544
|
jsdoc
| false
|
|
get_components
|
def get_components(principal) -> list[str] | None:
"""
Split the kerberos principal string into parts.
:return: *None* if the principal is empty. Otherwise split the value into
parts. Assuming the principal string is valid, the return value should
contain three components: short name, instance (FQDN), and realm.
"""
if not principal:
return None
return re.split(r"[/@]", str(principal))
|
Split the kerberos principal string into parts.
:return: *None* if the principal is empty. Otherwise split the value into
parts. Assuming the principal string is valid, the return value should
contain three components: short name, instance (FQDN), and realm.
|
python
|
airflow-core/src/airflow/security/utils.py
| 43
|
[
"principal"
] |
list[str] | None
| true
| 2
| 6.88
|
apache/airflow
| 43,597
|
unknown
| false
|
timeUnit
|
public TimeUnit timeUnit() {
return timeUnit;
}
|
@return the unit used for the this time value, see {@link #duration()}
|
java
|
libs/core/src/main/java/org/elasticsearch/core/TimeValue.java
| 103
|
[] |
TimeUnit
| true
| 1
| 6.48
|
elastic/elasticsearch
| 75,680
|
javadoc
| false
|
setShareFetchAction
|
public void setShareFetchAction(final ShareFetchBuffer fetchBuffer) {
final AtomicBoolean throwWakeupException = new AtomicBoolean(false);
pendingTask.getAndUpdate(task -> {
if (task == null) {
return new ShareFetchAction(fetchBuffer);
} else if (task instanceof WakeupFuture) {
throwWakeupException.set(true);
return null;
} else if (task instanceof DisabledWakeups) {
return task;
}
// last active state is still active
throw new IllegalStateException("Last active task is still active");
});
if (throwWakeupException.get()) {
throw new WakeupException();
}
}
|
If there is no pending task, set the pending task active.
If wakeup was called before setting an active task, the current task will complete exceptionally with
WakeupException right away.
If there is an active task, throw exception.
@param currentTask
@param <T>
@return
|
java
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/WakeupTrigger.java
| 111
|
[
"fetchBuffer"
] |
void
| true
| 5
| 8.24
|
apache/kafka
| 31,560
|
javadoc
| false
|
strides_hinted
|
def strides_hinted(self) -> tuple[tuple[int, ...], ...]:
"""
Get the size hints for strides of all input nodes.
Returns:
A tuple of stride tuples with integer hints for each input node
"""
return tuple(
V.graph.sizevars.size_hints(
node.get_stride(),
fallback=torch._inductor.config.unbacked_symint_fallback,
)
for node in self._input_nodes
)
|
Get the size hints for strides of all input nodes.
Returns:
A tuple of stride tuples with integer hints for each input node
|
python
|
torch/_inductor/kernel_inputs.py
| 141
|
[
"self"
] |
tuple[tuple[int, ...], ...]
| true
| 1
| 6.56
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
main
|
def main() -> None:
"""
Main function to orchestrate the patch download and application process.
Steps:
1. Parse command-line arguments to get the PR number, optional target directory, and strip count.
2. Retrieve the local PyTorch installation path or use the provided target directory.
3. Download the patch for the provided PR number.
4. Apply the patch to the specified directory with the given strip count.
"""
args = parse_arguments()
pr_number = args.PR_NUMBER
custom_target_dir = args.directory
strip_count = args.strip
if custom_target_dir:
if not os.path.isdir(custom_target_dir):
print(
f"Error: The specified target directory '{custom_target_dir}' does not exist."
)
sys.exit(1)
target_dir = custom_target_dir
print(f"Using custom target directory: {target_dir}")
else:
target_dir = get_pytorch_path()
repo_url = "https://github.com/pytorch/pytorch"
with tempfile.TemporaryDirectory() as tmpdirname:
patch_file = download_patch(pr_number, repo_url, tmpdirname)
apply_patch(patch_file, target_dir, strip_count)
|
Main function to orchestrate the patch download and application process.
Steps:
1. Parse command-line arguments to get the PR number, optional target directory, and strip count.
2. Retrieve the local PyTorch installation path or use the provided target directory.
3. Download the patch for the provided PR number.
4. Apply the patch to the specified directory with the given strip count.
|
python
|
tools/nightly_hotpatch.py
| 186
|
[] |
None
| true
| 4
| 6.72
|
pytorch/pytorch
| 96,034
|
unknown
| false
|
isFunction
|
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
|
Checks if `value` is classified as a `Function` object.
@static
@memberOf _
@since 0.1.0
@category Lang
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is a function, else `false`.
@example
_.isFunction(_);
// => true
_.isFunction(/abc/);
// => false
|
javascript
|
lodash.js
| 11,754
|
[
"value"
] | false
| 5
| 7.68
|
lodash/lodash
| 61,490
|
jsdoc
| false
|
|
readDeclaredField
|
public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
Objects.requireNonNull(target, "target");
final Class<?> cls = target.getClass();
final Field field = getDeclaredField(cls, fieldName, forceAccess);
Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls, fieldName);
// already forced access above, don't repeat it here:
return readField(field, target, false);
}
|
Gets a {@link Field} value by name. Only the class of the specified object will be considered.
@param target
the object to reflect, must not be {@code null}.
@param fieldName
the field name to obtain.
@param forceAccess
whether to break scope restrictions using the
{@link AccessibleObject#setAccessible(boolean)} method. {@code false} will only
match public fields.
@return the Field object.
@throws NullPointerException
if {@code target} is {@code null}.
@throws IllegalArgumentException
if {@code fieldName} is {@code null}, blank or empty, or could not be found.
@throws IllegalAccessException
if the field is not made accessible.
@throws SecurityException if an underlying accessible object's method denies the request.
@see SecurityManager#checkPermission
|
java
|
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
| 302
|
[
"target",
"fieldName",
"forceAccess"
] |
Object
| true
| 1
| 6.56
|
apache/commons-lang
| 2,896
|
javadoc
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.