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
features
public Map<String, VersionRangeType> features() { return features; }
@param features Map of feature name to SupportedVersionRange. @return Returns a new Features object representing supported features.
java
clients/src/main/java/org/apache/kafka/common/feature/Features.java
63
[]
true
1
6
apache/kafka
31,560
javadoc
false
visitVariableStatement
function visitVariableStatement(node: VariableStatement): Statement | undefined { if (node.transformFlags & TransformFlags.ContainsYield) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } else { // Do not hoist custom prologues. if (getEmitFlags(node) & EmitFlags.CustomPrologue) { return node; } for (const variable of node.declarationList.declarations) { hoistVariableDeclaration(variable.name as Identifier); } const variables = getInitializedVariables(node.declarationList); if (variables.length === 0) { return undefined; } return setSourceMapRange( factory.createExpressionStatement( factory.inlineExpressions( map(variables, transformInitializedVariable), ), ), node, ); } }
Visits a variable statement. This will be called when one of the following conditions are met: - The variable statement is contained within the body of a generator function. @param node The node to visit.
typescript
src/compiler/transformers/generators.ts
726
[ "node" ]
true
5
6.88
microsoft/TypeScript
107,154
jsdoc
false
computeInPlace
public Map<Integer, Double> computeInPlace(double... dataset) { checkArgument(dataset.length > 0, "Cannot calculate quantiles of an empty dataset"); if (containsNaN(dataset)) { Map<Integer, Double> nanMap = new LinkedHashMap<>(); for (int index : indexes) { nanMap.put(index, NaN); } return unmodifiableMap(nanMap); } // Calculate the quotients and remainders in the integer division x = k * (N - 1) / q, i.e. // index * (dataset.length - 1) / scale for each index in indexes. For each, if there is no // remainder, we can just select the value whose index in the sorted dataset equals the // quotient; if there is a remainder, we interpolate between that and the next value. int[] quotients = new int[indexes.length]; int[] remainders = new int[indexes.length]; // The indexes to select. In the worst case, we'll need one each side of each quantile. int[] requiredSelections = new int[indexes.length * 2]; int requiredSelectionsCount = 0; for (int i = 0; i < indexes.length; i++) { // Since index and (dataset.length - 1) are non-negative ints, their product can be // expressed as a long, without risk of overflow: long numerator = (long) indexes[i] * (dataset.length - 1); // Since scale is a positive int, index is in [0, scale], and (dataset.length - 1) is a // non-negative int, we can do long-arithmetic on index * (dataset.length - 1) / scale to // get a rounded ratio and a remainder which can be expressed as ints, without risk of // overflow: int quotient = (int) LongMath.divide(numerator, scale, RoundingMode.DOWN); int remainder = (int) (numerator - (long) quotient * scale); quotients[i] = quotient; remainders[i] = remainder; requiredSelections[requiredSelectionsCount] = quotient; requiredSelectionsCount++; if (remainder != 0) { requiredSelections[requiredSelectionsCount] = quotient + 1; requiredSelectionsCount++; } } sort(requiredSelections, 0, requiredSelectionsCount); selectAllInPlace( requiredSelections, 0, requiredSelectionsCount - 1, dataset, 0, dataset.length - 1); Map<Integer, Double> ret = new LinkedHashMap<>(); for (int i = 0; i < indexes.length; i++) { int quotient = quotients[i]; int remainder = remainders[i]; if (remainder == 0) { ret.put(indexes[i], dataset[quotient]); } else { ret.put( indexes[i], interpolate(dataset[quotient], dataset[quotient + 1], remainder, scale)); } } return unmodifiableMap(ret); }
Computes the quantile values of the given dataset, performing the computation in-place. @param dataset the dataset to do the calculation on, which must be non-empty, and which will be arbitrarily reordered by this method call @return an unmodifiable, ordered map of results: the keys will be the specified quantile indexes, and the values the corresponding quantile values. When iterating, entries in the map are ordered by quantile index in the same order that the indexes were passed to the {@code indexes} method.
java
android/guava/src/com/google/common/math/Quantiles.java
404
[]
true
6
8
google/guava
51,352
javadoc
false
visitForOfStatement
function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult<Statement> { return visitIterationStatementWithFacts( HierarchyFacts.ForInOrForOfStatementExcludes, HierarchyFacts.ForInOrForOfStatementIncludes, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray, ); }
Visits a VariableDeclaration node with a binding pattern. @param node A VariableDeclaration node.
typescript
src/compiler/transformers/es2015.ts
3,011
[ "node", "outermostLabeledStatement" ]
true
2
6.24
microsoft/TypeScript
107,154
jsdoc
false
positionShouldSnapToNode
function positionShouldSnapToNode(sourceFile: SourceFile, pos: number, node: Node) { // Can't use 'ts.positionBelongsToNode()' here because it cleverly accounts // for missing nodes, which can't really be considered when deciding what // to select. Debug.assert(node.pos <= pos); if (pos < node.end) { return true; } const nodeEnd = node.getEnd(); if (nodeEnd === pos) { return getTouchingPropertyName(sourceFile, pos).pos < node.end; } return false; }
Like `ts.positionBelongsToNode`, except positions immediately after nodes count too, unless that position belongs to the next node. In effect, makes selections able to snap to preceding tokens when the cursor is on the tail end of them with only whitespace ahead. @param sourceFile The source file containing the nodes. @param pos The position to check. @param node The candidate node to snap to.
typescript
src/services/smartSelection.ts
191
[ "sourceFile", "pos", "node" ]
false
3
6.24
microsoft/TypeScript
107,154
jsdoc
false
ignoreTypeLocClasses
static void ignoreTypeLocClasses( TypeLoc &Loc, const std::initializer_list<TypeLoc::TypeLocClass> &LocClasses) { while (llvm::is_contained(LocClasses, Loc.getTypeLocClass())) Loc = Loc.getNextTypeLoc(); }
declarations with written non-list initializer for standard iterators.
cpp
clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
337
[]
true
2
6.24
llvm/llvm-project
36,021
doxygen
false
ndenumerate
def ndenumerate(a, compressed=True): """ Multidimensional index iterator. Return an iterator yielding pairs of array coordinates and values, skipping elements that are masked. With `compressed=False`, `ma.masked` is yielded as the value of masked elements. This behavior differs from that of `numpy.ndenumerate`, which yields the value of the underlying data array. Notes ----- .. versionadded:: 1.23.0 Parameters ---------- a : array_like An array with (possibly) masked elements. compressed : bool, optional If True (default), masked elements are skipped. See Also -------- numpy.ndenumerate : Equivalent function ignoring any mask. Examples -------- >>> import numpy as np >>> a = np.ma.arange(9).reshape((3, 3)) >>> a[1, 0] = np.ma.masked >>> a[1, 2] = np.ma.masked >>> a[2, 1] = np.ma.masked >>> a masked_array( data=[[0, 1, 2], [--, 4, --], [6, --, 8]], mask=[[False, False, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> for index, x in np.ma.ndenumerate(a): ... print(index, x) (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 1) 4 (2, 0) 6 (2, 2) 8 >>> for index, x in np.ma.ndenumerate(a, compressed=False): ... print(index, x) (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) -- (1, 1) 4 (1, 2) -- (2, 0) 6 (2, 1) -- (2, 2) 8 """ for it, mask in zip(np.ndenumerate(a), getmaskarray(a).flat): if not mask: yield it elif not compressed: yield it[0], masked
Multidimensional index iterator. Return an iterator yielding pairs of array coordinates and values, skipping elements that are masked. With `compressed=False`, `ma.masked` is yielded as the value of masked elements. This behavior differs from that of `numpy.ndenumerate`, which yields the value of the underlying data array. Notes ----- .. versionadded:: 1.23.0 Parameters ---------- a : array_like An array with (possibly) masked elements. compressed : bool, optional If True (default), masked elements are skipped. See Also -------- numpy.ndenumerate : Equivalent function ignoring any mask. Examples -------- >>> import numpy as np >>> a = np.ma.arange(9).reshape((3, 3)) >>> a[1, 0] = np.ma.masked >>> a[1, 2] = np.ma.masked >>> a[2, 1] = np.ma.masked >>> a masked_array( data=[[0, 1, 2], [--, 4, --], [6, --, 8]], mask=[[False, False, False], [ True, False, True], [False, True, False]], fill_value=999999) >>> for index, x in np.ma.ndenumerate(a): ... print(index, x) (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 1) 4 (2, 0) 6 (2, 2) 8 >>> for index, x in np.ma.ndenumerate(a, compressed=False): ... print(index, x) (0, 0) 0 (0, 1) 1 (0, 2) 2 (1, 0) -- (1, 1) 4 (1, 2) -- (2, 0) 6 (2, 1) -- (2, 2) 8
python
numpy/ma/extras.py
1,800
[ "a", "compressed" ]
false
4
7.6
numpy/numpy
31,054
numpy
false
nextValue
public Object nextValue() throws JSONException { int c = nextCleanInternal(); switch (c) { case -1: throw syntaxError("End of input"); case '{': return readObject(); case '[': return readArray(); case '\'', '"': return nextString((char) c); default: this.pos--; return readLiteral(); } }
Returns the next value from the input. @return a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, Double or {@link JSONObject#NULL}. @throws JSONException if the input is malformed.
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONTokener.java
91
[]
Object
true
1
6.88
spring-projects/spring-boot
79,428
javadoc
false
CommitRanked
function CommitRanked({chartData, commitTree, height, width}: Props) { const [hoveredFiberData, setHoveredFiberData] = useState<TooltipFiberData | null>(null); const {lineHeight} = useContext(SettingsContext); const {selectedFiberID, selectFiber} = useContext(ProfilerContext); const {highlightHostInstance, clearHighlightHostInstance} = useHighlightHostInstance(); const selectedFiberIndex = useMemo( () => getNodeIndex(chartData, selectedFiberID), [chartData, selectedFiberID], ); const handleElementMouseEnter = useCallback( ({id, name}: $FlowFixMe) => { highlightHostInstance(id); // Highlight last hovered element. setHoveredFiberData({id, name}); // Set hovered fiber data for tooltip }, [highlightHostInstance], ); const handleElementMouseLeave = useCallback(() => { clearHighlightHostInstance(); // clear highlighting of element on mouse leave setHoveredFiberData(null); // clear hovered fiber data for tooltip }, [clearHighlightHostInstance]); const itemData = useMemo<ItemData>( () => ({ chartData, onElementMouseEnter: handleElementMouseEnter, onElementMouseLeave: handleElementMouseLeave, scaleX: scale(0, chartData.nodes[selectedFiberIndex].value, 0, width), selectedFiberID, selectedFiberIndex, selectFiber, width, }), [ chartData, handleElementMouseEnter, handleElementMouseLeave, selectedFiberID, selectedFiberIndex, selectFiber, width, ], ); // Tooltip used to show summary of fiber info on hover const tooltipLabel = useMemo( () => hoveredFiberData !== null ? ( <HoveredFiberInfo fiberData={hoveredFiberData} /> ) : null, [hoveredFiberData], ); return ( <Tooltip label={tooltipLabel}> <FixedSizeList height={height} innerElementType="svg" itemCount={chartData.nodes.length} itemData={itemData} itemSize={lineHeight} width={width}> {CommitRankedListItem} </FixedSizeList> </Tooltip> ); }
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-shared/src/devtools/views/Profiler/CommitRanked.js
97
[]
false
2
6.32
facebook/react
241,750
jsdoc
false
compareCaseUpperFirst
function compareCaseUpperFirst(one: string, other: string): number { if (startsWithUpper(one) && startsWithLower(other)) { return -1; } return (startsWithLower(one) && startsWithUpper(other)) ? 1 : 0; }
Compares the case of the provided strings - uppercase before lowercase @returns ```text -1 if one is uppercase and other is lowercase 1 if one is lowercase and other is uppercase 0 otherwise ```
typescript
src/vs/base/common/comparers.ts
258
[ "one", "other" ]
true
5
7.52
microsoft/vscode
179,840
jsdoc
false
xp_assert_less
def xp_assert_less( x: Array, y: Array, *, err_msg: str = "", check_dtype: bool = True, check_shape: bool = True, check_scalar: bool = False, ) -> None: """ Array-API compatible version of `np.testing.assert_array_less`. Parameters ---------- x, y : Array The arrays to compare according to ``x < y`` (elementwise). err_msg : str, optional Error message to display on failure. check_dtype, check_shape : bool, default: True Whether to check agreement between actual and desired dtypes and shapes check_scalar : bool, default: False NumPy only: whether to check agreement between actual and desired types - 0d array vs scalar. See Also -------- xp_assert_close : Similar function for inexact equality checks. numpy.testing.assert_array_equal : Similar function for NumPy arrays. """ xp = _check_ns_shape_dtype(x, y, check_dtype, check_shape, check_scalar) if not _is_materializable(x): return x_np = as_numpy_array(x, xp=xp) y_np = as_numpy_array(y, xp=xp) np.testing.assert_array_less(x_np, y_np, err_msg=err_msg)
Array-API compatible version of `np.testing.assert_array_less`. Parameters ---------- x, y : Array The arrays to compare according to ``x < y`` (elementwise). err_msg : str, optional Error message to display on failure. check_dtype, check_shape : bool, default: True Whether to check agreement between actual and desired dtypes and shapes check_scalar : bool, default: False NumPy only: whether to check agreement between actual and desired types - 0d array vs scalar. See Also -------- xp_assert_close : Similar function for inexact equality checks. numpy.testing.assert_array_equal : Similar function for NumPy arrays.
python
sklearn/externals/array_api_extra/_lib/_testing.py
176
[ "x", "y", "err_msg", "check_dtype", "check_shape", "check_scalar" ]
None
true
2
6.24
scikit-learn/scikit-learn
64,340
numpy
false
acquire
@CanIgnoreReturnValue public double acquire(int permits) { long microsToWait = reserve(permits); stopwatch.sleepMicrosUninterruptibly(microsToWait); return 1.0 * microsToWait / SECONDS.toMicros(1L); }
Acquires the given number of permits from this {@code RateLimiter}, blocking until the request can be granted. Tells the amount of time slept, if any. @param permits the number of permits to acquire @return time spent sleeping to enforce rate, in seconds; 0.0 if not rate-limited @throws IllegalArgumentException if the requested number of permits is negative or zero @since 16.0 (present in 13.0 with {@code void} return type})
java
android/guava/src/com/google/common/util/concurrent/RateLimiter.java
303
[ "permits" ]
true
1
6.88
google/guava
51,352
javadoc
false
isContextualKeywordInAutoImportableExpressionSpace
function isContextualKeywordInAutoImportableExpressionSpace(keyword: string) { return keyword === "abstract" || keyword === "async" || keyword === "await" || keyword === "declare" || keyword === "module" || keyword === "namespace" || keyword === "type" || keyword === "satisfies" || keyword === "as"; }
These are all the contextual keywords that would be valid to auto-import in expression space and also a valid keyword in the same location, depending on what gets typed afterwards. In these cases, we want to offer both the auto-import and the keyword completion. For example, ```ts type ``` may be the beginning of a type alias declaration (keyword completion), or it may be the beginning of ```ts import { type } from "os"; type() === "Darwin" ? doSomething() : doSomethingElse(); ```
typescript
src/services/completions.ts
6,163
[ "keyword" ]
false
9
6
microsoft/TypeScript
107,154
jsdoc
false
getTimeZoneDisplay
static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); // This is a very slow call, so cache the results. return timeZoneDisplayCache.computeIfAbsent(key, k -> tz.getDisplayName(daylight, style, locale)); }
Gets the time zone display name, using a cache for performance. @param tz the zone to query. @param daylight true if daylight savings. @param style the style to use {@link TimeZone#LONG} or {@link TimeZone#SHORT}. @param locale the locale to use. @return the textual name of the time zone.
java
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
1,009
[ "tz", "daylight", "style", "locale" ]
String
true
1
6.88
apache/commons-lang
2,896
javadoc
false
factorize_from_iterable
def factorize_from_iterable(values) -> tuple[np.ndarray, Index]: """ Factorize an input `values` into `categories` and `codes`. Preserves categorical dtype in `categories`. Parameters ---------- values : list-like Returns ------- codes : ndarray categories : Index If `values` has a categorical dtype, then `categories` is a CategoricalIndex keeping the categories and order of `values`. """ from pandas import CategoricalIndex if not is_list_like(values): raise TypeError("Input must be list-like") categories: Index vdtype = getattr(values, "dtype", None) if isinstance(vdtype, CategoricalDtype): values = extract_array(values) # The Categorical we want to build has the same categories # as values but its codes are by def [0, ..., len(n_categories) - 1] cat_codes = np.arange(len(values.categories), dtype=values.codes.dtype) cat = Categorical.from_codes(cat_codes, dtype=values.dtype, validate=False) categories = CategoricalIndex(cat) codes = values.codes else: # The value of ordered is irrelevant since we don't use cat as such, # but only the resulting categories, the order of which is independent # from ordered. Set ordered to False as default. See GH #15457 cat = Categorical(values, ordered=False) categories = cat.categories codes = cat.codes return codes, categories
Factorize an input `values` into `categories` and `codes`. Preserves categorical dtype in `categories`. Parameters ---------- values : list-like Returns ------- codes : ndarray categories : Index If `values` has a categorical dtype, then `categories` is a CategoricalIndex keeping the categories and order of `values`.
python
pandas/core/arrays/categorical.py
3,114
[ "values" ]
tuple[np.ndarray, Index]
true
4
6.4
pandas-dev/pandas
47,362
numpy
false
_property_resolver
def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Foo: ... a = 42 ... b = 3.14 ... c = 'Hey!' >>> _property_resolver('b')(Foo()) 3.14 """ try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in arg or arg[0] == "_": raise AttributeError("Access to private variables is forbidden.") parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): for part in parts: try: value = value[part] except (AttributeError, IndexError, KeyError, TypeError, ValueError): value = getattr(value, part) return value return resolve else: return itemgetter(arg)
When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Foo: ... a = 42 ... b = 3.14 ... c = 'Hey!' >>> _property_resolver('b')(Foo()) 3.14
python
django/template/defaultfilters.py
540
[ "arg" ]
false
5
7.2
django/django
86,204
unknown
false
debugCreate
function debugCreate(namespace: string) { const instanceProps = { color: COLORS[lastColor++ % COLORS.length], enabled: topProps.enabled(namespace), namespace: namespace, log: topProps.log, extend: () => {}, // not implemented } const debugCall = (...args: any[]) => { const { enabled, namespace, color, log } = instanceProps // we push the args to our history of args if (args.length !== 0) { argsHistory.push([namespace, ...args]) } // if it is too big, then we remove some if (argsHistory.length > MAX_ARGS_HISTORY) { argsHistory.shift() } if (topProps.enabled(namespace) || enabled) { const stringArgs = args.map((arg) => { if (typeof arg === 'string') { return arg } return safeStringify(arg) }) const ms = `+${Date.now() - lastTimestamp}ms` lastTimestamp = Date.now() if (globalThis.DEBUG_COLORS) { log(kleur[color](bold(namespace)), ...stringArgs, kleur[color](ms)) } else { log(namespace, ...stringArgs, ms) } } } return new Proxy(debugCall, { get: (_, prop) => instanceProps[prop], set: (_, prop, value) => (instanceProps[prop] = value), }) as typeof debugCall & typeof instanceProps }
Create a new debug instance with the given namespace. @example ```ts import Debug from '@prisma/debug' const debug = Debug('prisma:client') debug('Hello World') ```
typescript
packages/debug/src/index.ts
83
[ "namespace" ]
false
8
6.16
prisma/prisma
44,834
jsdoc
false
setxor1d
def setxor1d(ar1, ar2, assume_unique=False): """ Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setxor1d : ndarray Sorted 1D array of unique values that are in only one of the input arrays. Examples -------- >>> import numpy as np >>> a = np.array([1, 2, 3, 2, 4]) >>> b = np.array([2, 3, 5, 7, 5]) >>> np.setxor1d(a,b) array([1, 4, 5, 7]) """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate((ar1, ar2), axis=None) if aux.size == 0: return aux aux.sort() flag = np.concatenate(([True], aux[1:] != aux[:-1], [True])) return aux[flag[1:] & flag[:-1]]
Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setxor1d : ndarray Sorted 1D array of unique values that are in only one of the input arrays. Examples -------- >>> import numpy as np >>> a = np.array([1, 2, 3, 2, 4]) >>> b = np.array([2, 3, 5, 7, 5]) >>> np.setxor1d(a,b) array([1, 4, 5, 7])
python
numpy/lib/_arraysetops_impl.py
763
[ "ar1", "ar2", "assume_unique" ]
false
3
7.68
numpy/numpy
31,054
numpy
false
createKeyStore
private @Nullable KeyStore createKeyStore(String name, @Nullable JksSslStoreDetails details) { if (details == null || details.isEmpty()) { return null; } try { String type = (!StringUtils.hasText(details.type())) ? KeyStore.getDefaultType() : details.type(); char[] password = (details.password() != null) ? details.password().toCharArray() : null; String location = details.location(); KeyStore store = getKeyStoreInstance(type, details.provider()); if (isHardwareKeystoreType(type)) { loadHardwareKeyStore(store, location, password); } else { loadKeyStore(store, location, password); } return store; } catch (Exception ex) { throw new IllegalStateException("Unable to create %s store: %s".formatted(name, ex.getMessage()), ex); } }
Create a new {@link JksSslStoreBundle} instance. @param keyStoreDetails the key store details @param trustStoreDetails the trust store details @param resourceLoader the resource loader used to load content @since 3.3.5
java
core/spring-boot/src/main/java/org/springframework/boot/ssl/jks/JksSslStoreBundle.java
96
[ "name", "details" ]
KeyStore
true
7
6.4
spring-projects/spring-boot
79,428
javadoc
false
performRequestAsync
public Cancellable performRequestAsync(Request request, ResponseListener responseListener) { try { FailureTrackingResponseListener failureTrackingResponseListener = new FailureTrackingResponseListener(responseListener); InternalRequest internalRequest = new InternalRequest(request); performRequestAsync(nextNodes(), internalRequest, failureTrackingResponseListener); return internalRequest.cancellable; } catch (Exception e) { responseListener.onFailure(e); return Cancellable.NO_OP; } }
Sends a request to the Elasticsearch cluster that the client points to. The request is executed asynchronously and the provided {@link ResponseListener} gets notified upon request completion or failure. Selects a host out of the provided ones in a round-robin fashion. Failing hosts are marked dead and retried after a certain amount of time (minimum 1 minute, maximum 30 minutes), depending on how many times they previously failed (the more failures, the later they will be retried). In case of failures all of the alive nodes (or dead nodes that deserve a retry) are retried until one responds or none of them does, in which case an {@link IOException} will be thrown. @param request the request to perform @param responseListener the {@link ResponseListener} to notify when the request is completed or fails
java
client/rest/src/main/java/org/elasticsearch/client/RestClient.java
378
[ "request", "responseListener" ]
Cancellable
true
2
6.72
elastic/elasticsearch
75,680
javadoc
false
supportsEvent
protected boolean supportsEvent(Class<?> listenerType, ResolvableType eventType) { ResolvableType declaredEventType = GenericApplicationListenerAdapter.resolveDeclaredEventType(listenerType); return (declaredEventType == null || declaredEventType.isAssignableFrom(eventType)); }
Filter a listener early through checking its generically declared event type before trying to instantiate it. <p>If this method returns {@code true} for a given listener as a first pass, the listener instance will get retrieved and fully evaluated through a {@link #supportsEvent(ApplicationListener, ResolvableType, Class)} call afterwards. @param listenerType the listener's type as determined by the BeanFactory @param eventType the event type to check @return whether the given listener should be included in the candidates for the given event type
java
spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java
376
[ "listenerType", "eventType" ]
true
2
7.52
spring-projects/spring-framework
59,386
javadoc
false
ABSL_LOCKS_EXCLUDED
ABSL_LOCKS_EXCLUDED(call_mu_) { grpc::internal::MutexLock l(&call_mu_); if (GPR_UNLIKELY(backlog_.send_initial_metadata_wanted)) { call->SendInitialMetadata(); } if (GPR_UNLIKELY(backlog_.finish_wanted)) { call->Finish(std::move(backlog_.status_wanted)); } // Set call_ last so that other functions can use it lock-free call_.store(call, std::memory_order_release); }
The following notifications are exactly like ServerBidiReactor.
cpp
include/grpcpp/support/server_callback.h
751
[]
true
3
6.08
grpc/grpc
44,113
doxygen
false
endsWith
@Deprecated public static boolean endsWith(final CharSequence str, final CharSequence suffix) { return Strings.CS.endsWith(str, suffix); }
Tests if a CharSequence ends with a specified suffix. <p> {@code null}s are handled without exceptions. Two {@code null} references are considered to be equal. The comparison is case-sensitive. </p> <pre> StringUtils.endsWith(null, null) = true StringUtils.endsWith(null, "def") = false StringUtils.endsWith("abcdef", null) = false StringUtils.endsWith("abcdef", "def") = true StringUtils.endsWith("ABCDEF", "def") = false StringUtils.endsWith("ABCDEF", "cde") = false StringUtils.endsWith("ABCDEF", "") = true </pre> @param str the CharSequence to check, may be null. @param suffix the suffix to find, may be null. @return {@code true} if the CharSequence ends with the suffix, case-sensitive, or both {@code null}. @see String#endsWith(String) @since 2.4 @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence) @deprecated Use {@link Strings#endsWith(CharSequence, CharSequence) Strings.CS.endsWith(CharSequence, CharSequence)}.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
1,703
[ "str", "suffix" ]
true
1
6.48
apache/commons-lang
2,896
javadoc
false
tril_indices_from
def tril_indices_from(arr, k=0): """ Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- arr : array_like The indices will be valid for square arrays whose dimensions are the same as arr. k : int, optional Diagonal offset (see `tril` for details). Examples -------- >>> import numpy as np Create a 4 by 4 array >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Pass the array to get the indices of the lower triangular elements. >>> trili = np.tril_indices_from(a) >>> trili (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) >>> a[trili] array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15]) This is syntactic sugar for tril_indices(). >>> np.tril_indices(a.shape[0]) (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) Use the `k` parameter to return the indices for the lower triangular array up to the k-th diagonal. >>> trili1 = np.tril_indices_from(a, k=1) >>> a[trili1] array([ 0, 1, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15]) See Also -------- tril_indices, tril, triu_indices_from """ if arr.ndim != 2: raise ValueError("input array must be 2-d") return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
Return the indices for the lower-triangle of arr. See `tril_indices` for full details. Parameters ---------- arr : array_like The indices will be valid for square arrays whose dimensions are the same as arr. k : int, optional Diagonal offset (see `tril` for details). Examples -------- >>> import numpy as np Create a 4 by 4 array >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Pass the array to get the indices of the lower triangular elements. >>> trili = np.tril_indices_from(a) >>> trili (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) >>> a[trili] array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15]) This is syntactic sugar for tril_indices(). >>> np.tril_indices(a.shape[0]) (array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3])) Use the `k` parameter to return the indices for the lower triangular array up to the k-th diagonal. >>> trili1 = np.tril_indices_from(a, k=1) >>> a[trili1] array([ 0, 1, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15]) See Also -------- tril_indices, tril, triu_indices_from
python
numpy/lib/_twodim_base_impl.py
997
[ "arr", "k" ]
false
2
7.68
numpy/numpy
31,054
numpy
false
TypedIOBuf
TypedIOBuf(TypedIOBuf&&) = default;
Append multiple elements in a sequence; will call distance().
cpp
folly/io/TypedIOBuf.h
143
[]
true
2
6.64
facebook/folly
30,157
doxygen
false
find_replication_tasks_by_arn
def find_replication_tasks_by_arn(self, replication_task_arn: str, without_settings: bool | None = False): """ Find and describe replication tasks by task ARN. .. seealso:: - :external+boto3:py:meth:`DatabaseMigrationService.Client.describe_replication_tasks` :param replication_task_arn: Replication task arn :param without_settings: Indicates whether to return task information with settings. :return: list of replication tasks that match the ARN """ _, tasks = self.describe_replication_tasks( Filters=[ { "Name": "replication-task-arn", "Values": [replication_task_arn], } ], WithoutSettings=without_settings, ) return tasks
Find and describe replication tasks by task ARN. .. seealso:: - :external+boto3:py:meth:`DatabaseMigrationService.Client.describe_replication_tasks` :param replication_task_arn: Replication task arn :param without_settings: Indicates whether to return task information with settings. :return: list of replication tasks that match the ARN
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/dms.py
72
[ "self", "replication_task_arn", "without_settings" ]
true
1
6.24
apache/airflow
43,597
sphinx
false
stream
def stream(self) -> StructuredLogStream: """ Return the original stream of logs and clean up resources. Important: This method automatically cleans up resources after all logs have been yielded. Make sure to fully consume the returned generator to ensure proper cleanup. Returns: A stream of the captured log messages. """ try: if not self._tmpfile: # if no temporary file was created, return from the buffer yield from self._buffer else: # avoid circular import from airflow.utils.log.file_task_handler import StructuredLogMessage with open(self._tmpfile.name, encoding="utf-8") as f: yield from (StructuredLogMessage.model_validate_json(line.strip()) for line in f) # yield the remaining buffer yield from self._buffer finally: # Ensure cleanup after yielding self._cleanup()
Return the original stream of logs and clean up resources. Important: This method automatically cleans up resources after all logs have been yielded. Make sure to fully consume the returned generator to ensure proper cleanup. Returns: A stream of the captured log messages.
python
airflow-core/src/airflow/utils/log/log_stream_accumulator.py
112
[ "self" ]
StructuredLogStream
true
3
8.08
apache/airflow
43,597
unknown
false
falsePredicate
@SuppressWarnings("unchecked") static <E extends Throwable> FailableIntPredicate<E> falsePredicate() { return FALSE; }
Gets the FALSE singleton. @param <E> The kind of thrown exception or error. @return The NOP singleton.
java
src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java
46
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
_get_default_index_names
def _get_default_index_names( self, names: Hashable | Sequence[Hashable] | None = None, default=None ) -> list[Hashable]: """ Get names of index. Parameters ---------- names : int, str or 1-dimensional list, default None Index names to set. default : str Default name of index. Raises ------ TypeError if names not str or list-like """ from pandas.core.indexes.multi import MultiIndex if names is not None: if isinstance(names, (int, str)): names = [names] if not isinstance(names, list) and names is not None: raise ValueError("Index names must be str or 1-dimensional list") if not names: if isinstance(self, MultiIndex): names = com.fill_missing_names(self.names) else: names = [default] if self.name is None else [self.name] return names
Get names of index. Parameters ---------- names : int, str or 1-dimensional list, default None Index names to set. default : str Default name of index. Raises ------ TypeError if names not str or list-like
python
pandas/core/indexes/base.py
1,850
[ "self", "names", "default" ]
list[Hashable]
true
9
6.88
pandas-dev/pandas
47,362
numpy
false
from
static FileExtensionHint from(String value) { Matcher matcher = PATTERN.matcher(value); return (matcher.matches()) ? new FileExtensionHint(matcher) : NONE; }
Return the {@link FileExtensionHint} from the given value. @param value the source value @return the {@link FileExtensionHint} (never {@code null})
java
core/spring-boot/src/main/java/org/springframework/boot/context/config/FileExtensionHint.java
69
[ "value" ]
FileExtensionHint
true
2
7.36
spring-projects/spring-boot
79,428
javadoc
false
parseComposite
private static Duration parseComposite(String text) { try { Matcher matcher = COMPOSITE_PATTERN.matcher(text); Assert.state(matcher.matches() && matcher.groupCount() > 1, "Does not match composite duration pattern"); String sign = matcher.group(1); boolean negative = sign != null && sign.equals("-"); Duration result = Duration.ZERO; DurationFormat.Unit[] units = DurationFormat.Unit.values(); for (int i = 2; i < matcher.groupCount() + 1; i++) { String segment = matcher.group(i); if (StringUtils.hasText(segment)) { DurationFormat.Unit unit = units[units.length - i + 1]; result = result.plus(unit.parse(segment.replace(unit.asSuffix(), ""))); } } return negative ? result.negated() : result; } catch (Exception ex) { throw new IllegalArgumentException("'" + text + "' is not a valid composite duration", ex); } }
Detect the style then parse the value to return a duration. @param value the value to parse @param unit the duration unit to use if the value doesn't specify one ({@code null} will default to ms) @return the parsed duration @throws IllegalArgumentException if the value is not a known style or cannot be parsed
java
spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java
225
[ "text" ]
Duration
true
7
7.76
spring-projects/spring-framework
59,386
javadoc
false
setCount
@CanIgnoreReturnValue @Override public int setCount(E element, int count) { checkNotNull(element); checkNonnegative(count, "count"); while (true) { AtomicInteger existingCounter = safeGet(countMap, element); if (existingCounter == null) { if (count == 0) { return 0; } else { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through } } while (true) { int oldValue = existingCounter.get(); if (oldValue == 0) { if (count == 0) { return 0; } else { AtomicInteger newCounter = new AtomicInteger(count); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } } break; } else { if (existingCounter.compareAndSet(oldValue, count)) { if (count == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return oldValue; } } } } }
Adds or removes occurrences of {@code element} such that the {@link #count} of the element becomes {@code count}. @return the count of {@code element} in the multiset before this call @throws IllegalArgumentException if {@code count} is negative
java
android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
369
[ "element", "count" ]
true
12
6.72
google/guava
51,352
javadoc
false
sum
def sum( self, axis: AxisInt = 0, min_count: int = 0, skipna: bool = True, *args, **kwargs, ) -> Scalar: """ Sum of non-NA/null values Parameters ---------- axis : int, default 0 Not Used. NumPy compatibility. min_count : int, default 0 The required number of valid values to perform the summation. If fewer than ``min_count`` valid values are present, the result will be the missing value indicator for subarray type. *args, **kwargs Not Used. NumPy compatibility. Returns ------- scalar """ nv.validate_sum(args, kwargs) valid_vals = self._valid_sp_values sp_sum = valid_vals.sum() has_na = self.sp_index.ngaps > 0 and not self._null_fill_value if has_na and not skipna: return na_value_for_dtype(self.dtype.subtype, compat=False) if self._null_fill_value: if check_below_min_count(valid_vals.shape, None, min_count): return na_value_for_dtype(self.dtype.subtype, compat=False) return sp_sum else: nsparse = self.sp_index.ngaps if check_below_min_count(valid_vals.shape, None, min_count - nsparse): return na_value_for_dtype(self.dtype.subtype, compat=False) return sp_sum + self.fill_value * nsparse
Sum of non-NA/null values Parameters ---------- axis : int, default 0 Not Used. NumPy compatibility. min_count : int, default 0 The required number of valid values to perform the summation. If fewer than ``min_count`` valid values are present, the result will be the missing value indicator for subarray type. *args, **kwargs Not Used. NumPy compatibility. Returns ------- scalar
python
pandas/core/arrays/sparse/array.py
1,505
[ "self", "axis", "min_count", "skipna" ]
Scalar
true
8
6.72
pandas-dev/pandas
47,362
numpy
false
hist
def hist( self, by: IndexLabel | None = None, bins: int = 10, **kwargs ) -> PlotAccessor: """ Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one :class:`matplotlib.axes.Axes`. This is useful when the DataFrame's Series are in a similar scale. Parameters ---------- by : str or sequence, optional Column in the DataFrame to group by. bins : int, default 10 Number of histogram bins to be used. **kwargs Additional keyword arguments are documented in :meth:`DataFrame.plot`. Returns ------- :class:`matplotlib.axes.Axes` Return a histogram plot. See Also -------- DataFrame.hist : Draw histograms per DataFrame's Series. Series.hist : Draw a histogram with Series' data. Examples -------- When we roll a die 6000 times, we expect to get each value around 1000 times. But when we roll two dice and sum the result, the distribution is going to be quite different. A histogram illustrates those distributions. .. plot:: :context: close-figs >>> df = pd.DataFrame(np.random.randint(1, 7, 6000), columns=["one"]) >>> df["two"] = df["one"] + np.random.randint(1, 7, 6000) >>> ax = df.plot.hist(bins=12, alpha=0.5) A grouped histogram can be generated by providing the parameter `by` (which can be a column name, or a list of column names): .. plot:: :context: close-figs >>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85] >>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list}) >>> ax = df.plot.hist(column=["age"], by="gender", figsize=(10, 8)) """ return self(kind="hist", by=by, bins=bins, **kwargs)
Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one :class:`matplotlib.axes.Axes`. This is useful when the DataFrame's Series are in a similar scale. Parameters ---------- by : str or sequence, optional Column in the DataFrame to group by. bins : int, default 10 Number of histogram bins to be used. **kwargs Additional keyword arguments are documented in :meth:`DataFrame.plot`. Returns ------- :class:`matplotlib.axes.Axes` Return a histogram plot. See Also -------- DataFrame.hist : Draw histograms per DataFrame's Series. Series.hist : Draw a histogram with Series' data. Examples -------- When we roll a die 6000 times, we expect to get each value around 1000 times. But when we roll two dice and sum the result, the distribution is going to be quite different. A histogram illustrates those distributions. .. plot:: :context: close-figs >>> df = pd.DataFrame(np.random.randint(1, 7, 6000), columns=["one"]) >>> df["two"] = df["one"] + np.random.randint(1, 7, 6000) >>> ax = df.plot.hist(bins=12, alpha=0.5) A grouped histogram can be generated by providing the parameter `by` (which can be a column name, or a list of column names): .. plot:: :context: close-figs >>> age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85] >>> df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list}) >>> ax = df.plot.hist(column=["age"], by="gender", figsize=(10, 8))
python
pandas/plotting/_core.py
1,639
[ "self", "by", "bins" ]
PlotAccessor
true
1
7.12
pandas-dev/pandas
47,362
numpy
false
setupWarningHandler
function setupWarningHandler() { const { onWarning, resetForSerialization, } = require('internal/process/warning'); if (getOptionValue('--warnings') && process.env.NODE_NO_WARNINGS !== '1') { process.on('warning', onWarning); // The code above would add the listener back during deserialization, // if applicable. if (isBuildingSnapshot()) { addSerializeCallback(() => { process.removeListener('warning', onWarning); resetForSerialization(); }); } } }
Patch the process object with legacy properties and normalizations. Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`. Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found. @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of the main entry point. @returns {string}
javascript
lib/internal/process/pre_execution.js
326
[]
false
4
6.96
nodejs/node
114,839
jsdoc
false
secureStrong
public static RandomStringUtils secureStrong() { return SECURE_STRONG; }
Gets the singleton instance based on {@link SecureRandom#getInstanceStrong()} which uses an algorithms/providers specified in the {@code securerandom.strongAlgorithms} {@link Security} property. <p> The method {@link SecureRandom#getInstanceStrong()} is called on-demand. </p> @return the singleton instance based on {@link SecureRandom#getInstanceStrong()}. @see SecureRandom#getInstanceStrong() @since 3.17.0
java
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
654
[]
RandomStringUtils
true
1
6.16
apache/commons-lang
2,896
javadoc
false
faceIjkPentToCellBoundaryClassII
private CellBoundary faceIjkPentToCellBoundaryClassII(int adjRes) { final LatLng[] points = new LatLng[Constants.NUM_PENT_VERTS]; final FaceIJK fijk = new FaceIJK(this.face, new CoordIJK(0, 0, 0)); for (int vert = 0; vert < Constants.NUM_PENT_VERTS; vert++) { // The center point is now in the same substrate grid as the origin // cell vertices. Add the center point substate coordinates // to each vertex to translate the vertices to that cell. fijk.coord.reset( VERTEX_CLASSII[vert][0] + this.coord.i, VERTEX_CLASSII[vert][1] + this.coord.j, VERTEX_CLASSII[vert][2] + this.coord.k ); fijk.coord.ijkNormalize(); fijk.face = this.face; fijk.adjustPentVertOverage(adjRes); points[vert] = fijk.coord.ijkToGeo(fijk.face, adjRes, true); } return new CellBoundary(points, Constants.NUM_PENT_VERTS); }
Computes the cell boundary in spherical coordinates for a pentagonal cell for this FaceIJK address at a specified resolution. @param res The H3 resolution of the cell.
java
libs/h3/src/main/java/org/elasticsearch/h3/FaceIJK.java
439
[ "adjRes" ]
CellBoundary
true
2
6.72
elastic/elasticsearch
75,680
javadoc
false
_fpath_from_key
def _fpath_from_key(self: Self, key: Key) -> Path: """ Get the file path for a given key. Args: key (Key): The key to convert to a file path. Returns: Path: The file path for the key. Raises: CacheError: If the key is not pickle-able. """ try: return self.base_dir / sha256(pickle.dumps(key)).hexdigest()[:32] except (AttributeError, pickle.PicklingError) as err: raise CacheError( f"Failed to get fpath for key {key!r}, key is not pickle-able." ) from err # pyrefly: ignore [bad-argument-type] assert_never(key)
Get the file path for a given key. Args: key (Key): The key to convert to a file path. Returns: Path: The file path for the key. Raises: CacheError: If the key is not pickle-able.
python
torch/_inductor/cache.py
279
[ "self", "key" ]
Path
true
1
6.72
pytorch/pytorch
96,034
google
false
sort
public static char[] sort(final char[] array) { if (array != null) { Arrays.sort(array); } return array; }
Sorts the given array into ascending order and returns it. @param array the array to sort (may be null). @return the given array. @see Arrays#sort(char[])
java
src/main/java/org/apache/commons/lang3/ArraySorter.java
51
[ "array" ]
true
2
8.24
apache/commons-lang
2,896
javadoc
false
getBundles
public List<BundleInfo> getBundles() { return this.sslBundles.getBundleNames() .stream() .map((name) -> new BundleInfo(name, this.sslBundles.getBundle(name))) .toList(); }
Returns information on all SSL bundles. @return information on all SSL bundles
java
core/spring-boot/src/main/java/org/springframework/boot/info/SslInfo.java
79
[]
true
1
6.88
spring-projects/spring-boot
79,428
javadoc
false
trim_front
def trim_front(strings: list[str]) -> list[str]: """ Trims leading spaces evenly among all strings. Examples -------- >>> trim_front([" a", " b"]) ['a', 'b'] >>> trim_front([" a", " "]) ['a', ''] """ if not strings: return strings smallest_leading_space = min(len(x) - len(x.lstrip()) for x in strings) if smallest_leading_space > 0: strings = [x[smallest_leading_space:] for x in strings] return strings
Trims leading spaces evenly among all strings. Examples -------- >>> trim_front([" a", " b"]) ['a', 'b'] >>> trim_front([" a", " "]) ['a', '']
python
pandas/core/indexes/base.py
7,796
[ "strings" ]
list[str]
true
3
7.44
pandas-dev/pandas
47,362
unknown
false
unique_all
def unique_all(x): """ Find the unique elements of an array, and counts, inverse, and indices. This function is an Array API compatible alternative to:: np.unique(x, return_index=True, return_inverse=True, return_counts=True, equal_nan=False, sorted=False) but returns a namedtuple for easier access to each output. .. note:: This function currently always returns a sorted result, however, this could change in any NumPy minor release. Parameters ---------- x : array_like Input array. It will be flattened if it is not already 1-D. Returns ------- out : namedtuple The result containing: * values - The unique elements of an input array. * indices - The first occurring indices for each unique element. * inverse_indices - The indices from the set of unique elements that reconstruct `x`. * counts - The corresponding counts for each unique element. See Also -------- unique : Find the unique elements of an array. Examples -------- >>> import numpy as np >>> x = [1, 1, 2] >>> uniq = np.unique_all(x) >>> uniq.values array([1, 2]) >>> uniq.indices array([0, 2]) >>> uniq.inverse_indices array([0, 0, 1]) >>> uniq.counts array([2, 1]) """ result = unique( x, return_index=True, return_inverse=True, return_counts=True, equal_nan=False, ) return UniqueAllResult(*result)
Find the unique elements of an array, and counts, inverse, and indices. This function is an Array API compatible alternative to:: np.unique(x, return_index=True, return_inverse=True, return_counts=True, equal_nan=False, sorted=False) but returns a namedtuple for easier access to each output. .. note:: This function currently always returns a sorted result, however, this could change in any NumPy minor release. Parameters ---------- x : array_like Input array. It will be flattened if it is not already 1-D. Returns ------- out : namedtuple The result containing: * values - The unique elements of an input array. * indices - The first occurring indices for each unique element. * inverse_indices - The indices from the set of unique elements that reconstruct `x`. * counts - The corresponding counts for each unique element. See Also -------- unique : Find the unique elements of an array. Examples -------- >>> import numpy as np >>> x = [1, 1, 2] >>> uniq = np.unique_all(x) >>> uniq.values array([1, 2]) >>> uniq.indices array([0, 2]) >>> uniq.inverse_indices array([0, 0, 1]) >>> uniq.counts array([2, 1])
python
numpy/lib/_arraysetops_impl.py
441
[ "x" ]
false
1
6.32
numpy/numpy
31,054
numpy
false
qualifiedBeanOfType
private static <T> T qualifiedBeanOfType(ListableBeanFactory beanFactory, Class<T> beanType, String qualifier) { String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, beanType); String matchingBean = null; for (String beanName : candidateBeans) { if (isQualifierMatch(qualifier::equals, beanName, beanFactory)) { if (matchingBean != null) { throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName); } matchingBean = beanName; } } if (matchingBean != null) { return beanFactory.getBean(matchingBean, beanType); } else if (beanFactory.containsBean(qualifier) && beanFactory.isTypeMatch(qualifier, beanType)) { // Fallback: target bean at least found by bean name - probably a manually registered singleton. return beanFactory.getBean(qualifier, beanType); } else { throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() + " bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!"); } }
Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier (for example, {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier). @param beanFactory the factory to get the target bean from @param beanType the type of bean to retrieve @param qualifier the qualifier for selecting between multiple bean matches @return the matching bean of type {@code T} (never {@code null})
java
spring-beans/src/main/java/org/springframework/beans/factory/annotation/BeanFactoryAnnotationUtils.java
119
[ "beanFactory", "beanType", "qualifier" ]
T
true
6
7.76
spring-projects/spring-framework
59,386
javadoc
false
normalize_keyword_aggregation
def normalize_keyword_aggregation( kwargs: dict, ) -> tuple[ MutableMapping[Hashable, list[AggFuncTypeBase]], tuple[str, ...], npt.NDArray[np.intp], ]: """ Normalize user-provided "named aggregation" kwargs. Transforms from the new ``Mapping[str, NamedAgg]`` style kwargs to the old Dict[str, List[scalar]]]. Parameters ---------- kwargs : dict Returns ------- aggspec : dict The transformed kwargs. columns : tuple[str, ...] The user-provided keys. col_idx_order : List[int] List of columns indices. Examples -------- >>> normalize_keyword_aggregation({"output": ("input", "sum")}) (defaultdict(<class 'list'>, {'input': ['sum']}), ('output',), array([0])) """ from pandas.core.indexes.base import Index # Normalize the aggregation functions as Mapping[column, List[func]], # process normally, then fixup the names. # TODO: aggspec type: typing.Dict[str, List[AggScalar]] aggspec = defaultdict(list) order = [] columns = tuple(kwargs.keys()) for column, aggfunc in kwargs.values(): aggspec[column].append(aggfunc) order.append((column, com.get_callable_name(aggfunc) or aggfunc)) # uniquify aggfunc name if duplicated in order list uniquified_order = _make_unique_kwarg_list(order) # GH 25719, due to aggspec will change the order of assigned columns in aggregation # uniquified_aggspec will store uniquified order list and will compare it with order # based on index aggspec_order = [ (column, com.get_callable_name(aggfunc) or aggfunc) for column, aggfuncs in aggspec.items() for aggfunc in aggfuncs ] uniquified_aggspec = _make_unique_kwarg_list(aggspec_order) # get the new index of columns by comparison col_idx_order = Index(uniquified_aggspec).get_indexer(uniquified_order) return aggspec, columns, col_idx_order
Normalize user-provided "named aggregation" kwargs. Transforms from the new ``Mapping[str, NamedAgg]`` style kwargs to the old Dict[str, List[scalar]]]. Parameters ---------- kwargs : dict Returns ------- aggspec : dict The transformed kwargs. columns : tuple[str, ...] The user-provided keys. col_idx_order : List[int] List of columns indices. Examples -------- >>> normalize_keyword_aggregation({"output": ("input", "sum")}) (defaultdict(<class 'list'>, {'input': ['sum']}), ('output',), array([0]))
python
pandas/core/apply.py
1,825
[ "kwargs" ]
tuple[ MutableMapping[Hashable, list[AggFuncTypeBase]], tuple[str, ...], npt.NDArray[np.intp], ]
true
4
8.08
pandas-dev/pandas
47,362
numpy
false
probablySingleElementOf
@SuppressWarnings("NullAway") // See https://github.com/uber/NullAway/issues/1232 private static Elements probablySingleElementOf(CharSequence name) { return elementsOf(name, false, 1); }
Return a {@link ConfigurationPropertyName} for the specified string. @param name the source name @param returnNullIfInvalid if null should be returned if the name is not valid @return a {@link ConfigurationPropertyName} instance @throws InvalidConfigurationPropertyNameException if the name is not valid and {@code returnNullIfInvalid} is {@code false}
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
668
[ "name" ]
Elements
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
negate
function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; }
Creates a function that negates the result of the predicate `func`. The `func` predicate is invoked with the `this` binding and arguments of the created function. @static @memberOf _ @since 3.0.0 @category Function @param {Function} predicate The predicate to negate. @returns {Function} Returns the new negated function. @example function isEven(n) { return n % 2 == 0; } _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); // => [1, 3, 5]
javascript
lodash.js
10,690
[ "predicate" ]
false
2
7.68
lodash/lodash
61,490
jsdoc
false
createImportCallExpressionCommonJS
function createImportCallExpressionCommonJS(arg: Expression | undefined, isInlineable?: boolean): Expression { // import(x) // emit as // Promise.resolve(`${x}`).then((s) => require(s)) /*CommonJs Require*/ // We have to wrap require in then callback so that require is done in asynchronously // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately // If the arg is not inlineable, we have to evaluate and ToString() it in the current scope // Otherwise, we inline it in require() so that it's statically analyzable const needSyncEval = arg && !isSimpleInlineableExpression(arg) && !isInlineable; const promiseResolveCall = factory.createCallExpression( factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ needSyncEval ? languageVersion >= ScriptTarget.ES2015 ? [ factory.createTemplateExpression(factory.createTemplateHead(""), [ factory.createTemplateSpan(arg, factory.createTemplateTail("")), ]), ] : [ factory.createCallExpression( factory.createPropertyAccessExpression(factory.createStringLiteral(""), "concat"), /*typeArguments*/ undefined, [arg], ), ] : [], ); let requireCall: Expression = factory.createCallExpression( factory.createIdentifier("require"), /*typeArguments*/ undefined, needSyncEval ? [factory.createIdentifier("s")] : arg ? [arg] : [], ); if (getESModuleInterop(compilerOptions)) { requireCall = emitHelpers().createImportStarHelper(requireCall); } const parameters = needSyncEval ? [ factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ "s", ), ] : []; let func: FunctionExpression | ArrowFunction; if (languageVersion >= ScriptTarget.ES2015) { func = factory.createArrowFunction( /*modifiers*/ undefined, /*typeParameters*/ undefined, /*parameters*/ parameters, /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, requireCall, ); } else { func = factory.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ parameters, /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)]), ); } const downleveledImport = factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); return downleveledImport; }
Visits the body of a Block to hoist declarations. @param node The node to visit.
typescript
src/compiler/transformers/module/module.ts
1,332
[ "arg", "isInlineable?" ]
true
11
6.64
microsoft/TypeScript
107,154
jsdoc
false
getExitingScheduledExecutorService
@J2ktIncompatible @GwtIncompatible // TODO @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static ScheduledExecutorService getExitingScheduledExecutorService( ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { return new Application() .getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit); }
Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion. <p>This is mainly for fixed thread pools. See {@link Executors#newScheduledThreadPool(int)}. @param executor the executor to modify to make sure it exits when the application is finished @param terminationTimeout how long to wait for the executor to finish before terminating the JVM @param timeUnit unit of time for the time parameter @return an unmodifiable version of the input which will not hang the JVM
java
android/guava/src/com/google/common/util/concurrent/MoreExecutors.java
170
[ "executor", "terminationTimeout", "timeUnit" ]
ScheduledExecutorService
true
1
6.72
google/guava
51,352
javadoc
false
fromBin
double fromBin(int bin);
Determine the value at the upper range of the specified bin. @param bin the 0-based bin number @return the value at the upper end of the bin; or {@link Float#NEGATIVE_INFINITY negative infinity} if the bin number is negative or {@link Float#POSITIVE_INFINITY positive infinity} if the 0-based bin number is greater than or equal to the {@link #bins() number of bins}.
java
clients/src/main/java/org/apache/kafka/common/metrics/stats/Histogram.java
109
[ "bin" ]
true
1
6.48
apache/kafka
31,560
javadoc
false
completeProxiedInterfaces
static Class<?>[] completeProxiedInterfaces(AdvisedSupport advised, boolean decoratingProxy) { Class<?>[] specifiedInterfaces = advised.getProxiedInterfaces(); if (specifiedInterfaces.length == 0) { // No user-specified interfaces: check whether target class is an interface. Class<?> targetClass = advised.getTargetClass(); if (targetClass != null) { if (targetClass.isInterface()) { advised.setInterfaces(targetClass); } else if (Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) { advised.setInterfaces(targetClass.getInterfaces()); } specifiedInterfaces = advised.getProxiedInterfaces(); } } List<Class<?>> proxiedInterfaces = new ArrayList<>(specifiedInterfaces.length + 3); for (Class<?> ifc : specifiedInterfaces) { // Only non-sealed interfaces are actually eligible for JDK proxying (on JDK 17) if (!ifc.isSealed()) { proxiedInterfaces.add(ifc); } } if (!advised.isInterfaceProxied(SpringProxy.class)) { proxiedInterfaces.add(SpringProxy.class); } if (!advised.isOpaque() && !advised.isInterfaceProxied(Advised.class)) { proxiedInterfaces.add(Advised.class); } if (decoratingProxy && !advised.isInterfaceProxied(DecoratingProxy.class)) { proxiedInterfaces.add(DecoratingProxy.class); } return ClassUtils.toClassArray(proxiedInterfaces); }
Determine the complete set of interfaces to proxy for the given AOP configuration. <p>This will always add the {@link Advised} interface unless the AdvisedSupport's {@link AdvisedSupport#setOpaque "opaque"} flag is on. Always adds the {@link org.springframework.aop.SpringProxy} marker interface. @param advised the proxy config @param decoratingProxy whether to expose the {@link DecoratingProxy} interface @return the complete set of interfaces to proxy @since 4.3 @see SpringProxy @see Advised @see DecoratingProxy
java
spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java
163
[ "advised", "decoratingProxy" ]
true
12
7.6
spring-projects/spring-framework
59,386
javadoc
false
create_bw_fn
def create_bw_fn( fn: Callable, args: tuple[Any, ...], return_fw_outputs: bool = False ) -> Callable: """ For a fn that accepts flat inputs and returns flat outputs: fw_out = fn(*args), this function returns: grad_args = bw_fn(*args_and_grad_output) with the following invariants: 1. args + fw_out has an 1-1 correspondence to args_and_grad_output 2. grad_args has an 1-1 corresponsence to args 3. for tensor arg whose requires_grad is False, its corresponding grad in grad_args will be a zero tensor with the same shape. """ from torch._functorch.aot_autograd import AOTConfig, create_joint # pyrefly: ignore [missing-module-attribute] from torch._higher_order_ops.utils import prepare_fw_with_masks_all_requires_grad dummy_aot_config = AOTConfig( fw_compiler=None, # type: ignore[arg-type] bw_compiler=None, # type: ignore[arg-type] partition_fn=None, # type: ignore[arg-type] decompositions={}, num_params_buffers=0, aot_id=0, keep_inference_input_mutations=False, ) n_primals = len(args) bw_fn = create_joint( prepare_fw_with_masks_all_requires_grad(fn), aot_config=dummy_aot_config ) def flat_fn(*args_and_grad_outs): primals = args_and_grad_outs[:n_primals] tangents = args_and_grad_outs[n_primals:] fw_outs, grad_args = bw_fn(primals, tangents) assert len(args) == len(grad_args) # For tensors whose grad is None, create zero tensors as gradients # This invariant is useful for cudagraph. grad_args = [ torch.zeros_like(arg) if isinstance(arg, torch.Tensor) and grad is None else grad for grad, arg in zip(grad_args, primals) ] final_grads = _clone_aliasing_output(args_and_grad_outs, grad_args) if return_fw_outputs: return *fw_outs, *final_grads return final_grads return flat_fn
For a fn that accepts flat inputs and returns flat outputs: fw_out = fn(*args), this function returns: grad_args = bw_fn(*args_and_grad_output) with the following invariants: 1. args + fw_out has an 1-1 correspondence to args_and_grad_output 2. grad_args has an 1-1 corresponsence to args 3. for tensor arg whose requires_grad is False, its corresponding grad in grad_args will be a zero tensor with the same shape.
python
torch/_higher_order_ops/utils.py
811
[ "fn", "args", "return_fw_outputs" ]
Callable
true
4
7.04
pytorch/pytorch
96,034
unknown
false
levels
def levels(self) -> FrozenList: """ Levels of the MultiIndex. Levels refer to the different hierarchical levels or layers in a MultiIndex. In a MultiIndex, each level represents a distinct dimension or category of the index. To access the levels, you can use the levels attribute of the MultiIndex, which returns a tuple of Index objects. Each Index object represents a level in the MultiIndex and contains the unique values found in that specific level. If a MultiIndex is created with levels A, B, C, and the DataFrame using it filters out all rows of the level C, MultiIndex.levels will still return A, B, C. See Also -------- MultiIndex.codes : The codes of the levels in the MultiIndex. MultiIndex.get_level_values : Return vector of label values for requested level. Examples -------- >>> index = pd.MultiIndex.from_product( ... [["mammal"], ("goat", "human", "cat", "dog")], ... names=["Category", "Animals"], ... ) >>> leg_num = pd.DataFrame(data=(4, 2, 4, 4), index=index, columns=["Legs"]) >>> leg_num Legs Category Animals mammal goat 4 human 2 cat 4 dog 4 >>> leg_num.index.levels FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']]) MultiIndex levels will not change even if the DataFrame using the MultiIndex does not contain all them anymore. See how "human" is not in the DataFrame, but it is still in levels: >>> large_leg_num = leg_num[leg_num.Legs > 2] >>> large_leg_num Legs Category Animals mammal goat 4 cat 4 dog 4 >>> large_leg_num.index.levels FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']]) """ # Use cache_readonly to ensure that self.get_locs doesn't repeatedly # create new IndexEngine # https://github.com/pandas-dev/pandas/issues/31648 result = [ x._rename(name=name) for x, name in zip(self._levels, self._names, strict=True) ] for level in result: # disallow midx.levels[0].name = "foo" level._no_setting_name = True return FrozenList(result)
Levels of the MultiIndex. Levels refer to the different hierarchical levels or layers in a MultiIndex. In a MultiIndex, each level represents a distinct dimension or category of the index. To access the levels, you can use the levels attribute of the MultiIndex, which returns a tuple of Index objects. Each Index object represents a level in the MultiIndex and contains the unique values found in that specific level. If a MultiIndex is created with levels A, B, C, and the DataFrame using it filters out all rows of the level C, MultiIndex.levels will still return A, B, C. See Also -------- MultiIndex.codes : The codes of the levels in the MultiIndex. MultiIndex.get_level_values : Return vector of label values for requested level. Examples -------- >>> index = pd.MultiIndex.from_product( ... [["mammal"], ("goat", "human", "cat", "dog")], ... names=["Category", "Animals"], ... ) >>> leg_num = pd.DataFrame(data=(4, 2, 4, 4), index=index, columns=["Legs"]) >>> leg_num Legs Category Animals mammal goat 4 human 2 cat 4 dog 4 >>> leg_num.index.levels FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']]) MultiIndex levels will not change even if the DataFrame using the MultiIndex does not contain all them anymore. See how "human" is not in the DataFrame, but it is still in levels: >>> large_leg_num = leg_num[leg_num.Legs > 2] >>> large_leg_num Legs Category Animals mammal goat 4 cat 4 dog 4 >>> large_leg_num.index.levels FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']])
python
pandas/core/indexes/multi.py
820
[ "self" ]
FrozenList
true
2
7.2
pandas-dev/pandas
47,362
unknown
false
maybe_signature
def maybe_signature(d, app=None, clone=False): """Ensure obj is a signature, or None. Arguments: d (Optional[Union[abstract.CallableSignature, Mapping]]): Signature or dict-serialized signature. app (celery.Celery): App to bind signature to. clone (bool): If d' is already a signature, the signature will be cloned when this flag is enabled. Returns: Optional[abstract.CallableSignature] """ if d is not None: if isinstance(d, abstract.CallableSignature): if clone: d = d.clone() elif isinstance(d, dict): d = signature(d) if app is not None: d._app = app return d
Ensure obj is a signature, or None. Arguments: d (Optional[Union[abstract.CallableSignature, Mapping]]): Signature or dict-serialized signature. app (celery.Celery): App to bind signature to. clone (bool): If d' is already a signature, the signature will be cloned when this flag is enabled. Returns: Optional[abstract.CallableSignature]
python
celery/canvas.py
2,393
[ "d", "app", "clone" ]
false
6
6.64
celery/celery
27,741
google
false
nop
@SuppressWarnings("unchecked") static <T, U, E extends Throwable> FailableToLongBiFunction<T, U, E> nop() { return NOP; }
Gets the NOP singleton. @param <T> the type of the first argument to the function @param <U> the type of the second argument to the function @param <E> The kind of thrown exception or error. @return The NOP singleton.
java
src/main/java/org/apache/commons/lang3/function/FailableToLongBiFunction.java
45
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
containsBean
boolean containsBean(String name);
Does this bean factory contain a bean definition or externally registered singleton instance with the given name? <p>If the given name is an alias, it will be translated back to the corresponding canonical bean name. <p>If this factory is hierarchical, will ask any parent factory if the bean cannot be found in this factory instance. <p>If a bean definition or singleton instance matching the given name is found, this method will return {@code true} whether the named bean definition is concrete or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true} return value from this method does not necessarily indicate that {@link #getBean} will be able to obtain an instance for the same name. @param name the name of the bean to query @return whether a bean with the given name is present
java
spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java
299
[ "name" ]
true
1
6.48
spring-projects/spring-framework
59,386
javadoc
false
equalsAny
public boolean equalsAny(final CharSequence string, final CharSequence... searchStrings) { if (ArrayUtils.isNotEmpty(searchStrings)) { for (final CharSequence next : searchStrings) { if (equals(string, next)) { return true; } } } return false; }
Compares given {@code string} to a CharSequences vararg of {@code searchStrings}, returning {@code true} if the {@code string} is equal to any of the {@code searchStrings}. <p> Case-sensitive examples </p> <pre> Strings.CS.equalsAny(null, (CharSequence[]) null) = false Strings.CS.equalsAny(null, null, null) = true Strings.CS.equalsAny(null, "abc", "def") = false Strings.CS.equalsAny("abc", null, "def") = false Strings.CS.equalsAny("abc", "abc", "def") = true Strings.CS.equalsAny("abc", "ABC", "DEF") = false </pre> <p> Case-insensitive examples </p> <pre> Strings.CI.equalsAny(null, (CharSequence[]) null) = false Strings.CI.equalsAny(null, null, null) = true Strings.CI.equalsAny(null, "abc", "def") = false Strings.CI.equalsAny("abc", null, "def") = false Strings.CI.equalsAny("abc", "abc", "def") = true Strings.CI.equalsAny("abc", "ABC", "DEF") = true </pre> @param string to compare, may be {@code null}. @param searchStrings a vararg of strings, may be {@code null}. @return {@code true} if the string is equal (case-sensitive) to any other element of {@code searchStrings}; {@code false} if {@code searchStrings} is null or contains no matches.
java
src/main/java/org/apache/commons/lang3/Strings.java
757
[ "string" ]
true
3
7.76
apache/commons-lang
2,896
javadoc
false
visitDestructuringAssignment
function visitDestructuringAssignment(node: DestructuringAssignment, valueIsDiscarded: boolean): Expression { if (destructuringNeedsFlattening(node.left)) { return flattenDestructuringAssignment(node, visitor, context, FlattenLevel.All, !valueIsDiscarded, createAllExportExpressions); } return visitEachChild(node, visitor, context); }
Visit nested elements at the top-level of a module. @param node The node to visit.
typescript
src/compiler/transformers/module/module.ts
890
[ "node", "valueIsDiscarded" ]
true
2
6.72
microsoft/TypeScript
107,154
jsdoc
false
noNullElements
public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) { Objects.requireNonNull(iterable, "iterable"); final AtomicInteger ai = new AtomicInteger(); iterable.forEach(e -> { if (e == null) { throw new IllegalArgumentException(getMessage(message, ArrayUtils.addAll(values, ai.getAndIncrement()))); } }); return iterable; }
Validate that the specified argument iterable is neither {@code null} nor contains any elements that are {@code null}; otherwise throwing an exception with the specified message. <pre>Validate.noNullElements(myCollection, "The collection contains null at position %d");</pre> <p>If the iterable is {@code null}, then the message in the exception is &quot;The validated object is null&quot;. <p>If the iterable has a {@code null} element, then the iteration index of the invalid element is appended to the {@code values} argument.</p> @param <T> the iterable type. @param iterable the iterable to check, validated not null by this method. @param message the {@link String#format(String, Object...)} exception message if invalid, not null. @param values the optional values for the formatted exception message, null array not recommended. @return the validated iterable (never {@code null} method for chaining). @throws NullPointerException if the array is {@code null}. @throws IllegalArgumentException if an element is {@code null}. @see #noNullElements(Iterable)
java
src/main/java/org/apache/commons/lang3/Validate.java
692
[ "iterable", "message" ]
T
true
2
7.44
apache/commons-lang
2,896
javadoc
false
prune_deadlines
def prune_deadlines(cls, *, session: Session, conditions: dict[Mapped, Any]) -> int: """ Remove deadlines from the table which match the provided conditions and return the number removed. NOTE: This should only be used to remove deadlines which are associated with successful events (DagRuns, etc). If the deadline was missed, it will be handled by the scheduler. :param conditions: Dictionary of conditions to evaluate against. :param session: Session to use. """ from airflow.models import DagRun # Avoids circular import # Assemble the filter conditions. filter_conditions = [column == value for column, value in conditions.items()] if not filter_conditions: return 0 try: # Get deadlines which match the provided conditions and their associated DagRuns. deadline_dagrun_pairs = session.execute( select(Deadline, DagRun).join(DagRun).where(and_(*filter_conditions)) ).all() except AttributeError as e: logger.exception("Error resolving deadlines: %s", e) raise if not deadline_dagrun_pairs: return 0 deleted_count = 0 dagruns_to_refresh = set() for deadline, dagrun in deadline_dagrun_pairs: if dagrun.end_date <= deadline.deadline_time: # If the DagRun finished before the Deadline: session.delete(deadline) Stats.incr( "deadline_alerts.deadline_not_missed", tags={"dag_id": dagrun.dag_id, "dagrun_id": dagrun.run_id}, ) deleted_count += 1 dagruns_to_refresh.add(dagrun) session.flush() logger.debug("%d deadline records were deleted matching the conditions %s", deleted_count, conditions) # Refresh any affected DAG runs. for dagrun in dagruns_to_refresh: session.refresh(dagrun) return deleted_count
Remove deadlines from the table which match the provided conditions and return the number removed. NOTE: This should only be used to remove deadlines which are associated with successful events (DagRuns, etc). If the deadline was missed, it will be handled by the scheduler. :param conditions: Dictionary of conditions to evaluate against. :param session: Session to use.
python
airflow-core/src/airflow/models/deadline.py
135
[ "cls", "session", "conditions" ]
int
true
6
6.88
apache/airflow
43,597
sphinx
false
containsYield
function containsYield(node: Node | undefined): boolean { return !!node && (node.transformFlags & TransformFlags.ContainsYield) !== 0; }
Visits an ElementAccessExpression that contains a YieldExpression. @param node The node to visit.
typescript
src/compiler/transformers/generators.ts
2,037
[ "node" ]
true
2
6
microsoft/TypeScript
107,154
jsdoc
false
generate
ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException { Log.info("Using service at " + request.getServiceUrl()); InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl()); URI url = request.generateUrl(metadata); ClassicHttpResponse httpResponse = executeProjectGenerationRequest(url); HttpEntity httpEntity = httpResponse.getEntity(); validateResponse(httpResponse, request.getServiceUrl()); return createResponse(httpResponse, httpEntity); }
Generate a project based on the specified {@link ProjectGenerationRequest}. @param request the generation request @return an entity defining the project @throws IOException if generation fails
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java
90
[ "request" ]
ProjectGenerationResponse
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
resolveEntity
@Override public @Nullable InputSource resolveEntity(@Nullable String publicId, @Nullable String systemId) throws SAXException, IOException { InputSource source = super.resolveEntity(publicId, systemId); if (source == null && systemId != null) { String resourcePath = null; try { String decodedSystemId = URLDecoder.decode(systemId, StandardCharsets.UTF_8); String givenUrl = ResourceUtils.toURL(decodedSystemId).toString(); String systemRootUrl = new File("").toURI().toURL().toString(); // Try relative to resource base if currently in system root. if (givenUrl.startsWith(systemRootUrl)) { resourcePath = givenUrl.substring(systemRootUrl.length()); } } catch (Exception ex) { // Typically a MalformedURLException or AccessControlException. if (logger.isDebugEnabled()) { logger.debug("Could not resolve XML entity [" + systemId + "] against system root URL", ex); } // No URL (or no resolvable URL) -> try relative to resource base. resourcePath = systemId; } if (resourcePath != null) { if (logger.isTraceEnabled()) { logger.trace("Trying to locate XML entity [" + systemId + "] as resource [" + resourcePath + "]"); } Resource resource = this.resourceLoader.getResource(resourcePath); source = new InputSource(resource.getInputStream()); source.setPublicId(publicId); source.setSystemId(systemId); if (logger.isDebugEnabled()) { logger.debug("Found XML entity [" + systemId + "]: " + resource); } } else if (systemId.endsWith(DTD_SUFFIX) || systemId.endsWith(XSD_SUFFIX)) { source = resolveSchemaEntity(publicId, systemId); } } return source; }
Create a ResourceEntityResolver for the specified ResourceLoader (usually, an ApplicationContext). @param resourceLoader the ResourceLoader (or ApplicationContext) to load XML entity includes with
java
spring-beans/src/main/java/org/springframework/beans/factory/xml/ResourceEntityResolver.java
74
[ "publicId", "systemId" ]
InputSource
true
11
6.08
spring-projects/spring-framework
59,386
javadoc
false
sum
public ExponentialHistogramBuilder sum(double sum) { this.sum = sum; return this; }
Sets the sum of the histogram values. If not set, the sum will be estimated from the buckets. @param sum the sum value @return the builder
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramBuilder.java
107
[ "sum" ]
ExponentialHistogramBuilder
true
1
6.8
elastic/elasticsearch
75,680
javadoc
false
newIncompleteFuture
@Override public <U> CompletableFuture<U> newIncompleteFuture() { return new KafkaCompletableFuture<>(); }
Completes this future exceptionally. For internal use by the Kafka clients, not by user code. @param throwable the exception. @return {@code true} if this invocation caused this CompletableFuture to transition to a completed state, else {@code false}
java
clients/src/main/java/org/apache/kafka/common/internals/KafkaCompletableFuture.java
72
[]
true
1
6.64
apache/kafka
31,560
javadoc
false
format
@Override public <B extends Appendable> B format(final long millis, final B buf) { return printer.format(millis, buf); }
Formats a millisecond {@code long} value into the supplied {@link StringBuffer}. @param millis the millisecond value to format. @param buf the buffer to format into. @return the specified string buffer. @since 3.5
java
src/main/java/org/apache/commons/lang3/time/FastDateFormat.java
496
[ "millis", "buf" ]
B
true
1
6.64
apache/commons-lang
2,896
javadoc
false
reconciliationInProgress
boolean reconciliationInProgress() { return reconciliationInProgress; }
@return If there is a reconciliation in process now. Note that reconciliation is triggered by a call to {@link #maybeReconcile(boolean)}. Visible for testing.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
1,375
[]
true
1
6.48
apache/kafka
31,560
javadoc
false
and
public FluentBitSet and(final BitSet set) { bitSet.and(set); return this; }
Performs a logical <strong>AND</strong> of this target bit set with the argument bit set. This bit set is modified so that each bit in it has the value {@code true} if and only if it both initially had the value {@code true} and the corresponding bit in the bit set argument also had the value {@code true}. @param set a bit set. @return {@code this} instance.
java
src/main/java/org/apache/commons/lang3/util/FluentBitSet.java
75
[ "set" ]
FluentBitSet
true
1
6.96
apache/commons-lang
2,896
javadoc
false
size
default int size() { return -1; }
Return the size of the content that will be written, or {@code -1} if the size is not known. @return the size of the content
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/EntryWriter.java
43
[]
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
is_file_like
def is_file_like(obj: object) -> bool: """ Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. Parameters ---------- obj : object The object to check for file-like properties. This can be any Python object, and the function will check if it has attributes typically associated with file-like objects (e.g., `read`, `write`, `__iter__`). Returns ------- bool Whether `obj` has file-like properties. See Also -------- api.types.is_dict_like : Check if the object is dict-like. api.types.is_hashable : Return True if hash(obj) will succeed, False otherwise. api.types.is_named_tuple : Check if the object is a named tuple. api.types.is_iterator : Check if the object is an iterator. Examples -------- >>> import io >>> from pandas.api.types import is_file_like >>> buffer = io.StringIO("data") >>> is_file_like(buffer) True >>> is_file_like([1, 2, 3]) False """ if not (hasattr(obj, "read") or hasattr(obj, "write")): return False return bool(hasattr(obj, "__iter__"))
Check if the object is a file-like object. For objects to be considered file-like, they must be an iterator AND have either a `read` and/or `write` method as an attribute. Note: file-like objects must be iterable, but iterable objects need not be file-like. Parameters ---------- obj : object The object to check for file-like properties. This can be any Python object, and the function will check if it has attributes typically associated with file-like objects (e.g., `read`, `write`, `__iter__`). Returns ------- bool Whether `obj` has file-like properties. See Also -------- api.types.is_dict_like : Check if the object is dict-like. api.types.is_hashable : Return True if hash(obj) will succeed, False otherwise. api.types.is_named_tuple : Check if the object is a named tuple. api.types.is_iterator : Check if the object is an iterator. Examples -------- >>> import io >>> from pandas.api.types import is_file_like >>> buffer = io.StringIO("data") >>> is_file_like(buffer) True >>> is_file_like([1, 2, 3]) False
python
pandas/core/dtypes/inference.py
107
[ "obj" ]
bool
true
3
8.32
pandas-dev/pandas
47,362
numpy
false
transformClassLikeDeclarationToExpression
function transformClassLikeDeclarationToExpression(node: ClassExpression | ClassDeclaration): Expression { // [source] // class C extends D { // constructor() {} // method() {} // get prop() {} // set prop(v) {} // } // // [output] // (function (_super) { // __extends(C, _super); // function C() { // } // C.prototype.method = function () {} // Object.defineProperty(C.prototype, "prop", { // get: function() {}, // set: function() {}, // enumerable: true, // configurable: true // }); // return C; // }(D)) if (node.name) { enableSubstitutionsForBlockScopedBindings(); } const extendsClauseElement = getClassExtendsHeritageElement(node); const classFunction = factory.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, createSyntheticSuper())] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement), ); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. setEmitFlags(classFunction, (getEmitFlags(node) & EmitFlags.Indented) | EmitFlags.ReuseTempVariableScope); // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter const inner = factory.createPartiallyEmittedExpression(classFunction); setTextRangeEnd(inner, node.end); setEmitFlags(inner, EmitFlags.NoComments); const outer = factory.createPartiallyEmittedExpression(inner); setTextRangeEnd(outer, skipTrivia(currentText, node.pos)); setEmitFlags(outer, EmitFlags.NoComments); const result = factory.createParenthesizedExpression( factory.createCallExpression( outer, /*typeArguments*/ undefined, extendsClauseElement ? [Debug.checkDefined(visitNode(extendsClauseElement.expression, visitor, isExpression))] : [], ), ); addSyntheticLeadingComment(result, SyntaxKind.MultiLineCommentTrivia, "* @class "); return result; }
Transforms a ClassExpression or ClassDeclaration into an expression. @param node A ClassExpression or ClassDeclaration node.
typescript
src/compiler/transformers/es2015.ts
1,017
[ "node" ]
true
4
6.16
microsoft/TypeScript
107,154
jsdoc
false
wait_for_db_instance_state
def wait_for_db_instance_state( self, db_instance_id: str, target_state: str, check_interval: int = 30, max_attempts: int = 40 ) -> None: """ Poll DB Instances until target_state is reached; raise AirflowException after max_attempts. .. seealso:: - :external+boto3:py:meth:`RDS.Client.describe_db_instances` :param db_instance_id: The ID of the target DB instance. :param target_state: Wait until this state is reached :param check_interval: The amount of time in seconds to wait between attempts :param max_attempts: The maximum number of attempts to be made """ def poke(): return self.get_db_instance_state(db_instance_id) target_state = target_state.lower() if target_state in ("available", "deleted", "stopped"): waiter = self.conn.get_waiter(f"db_instance_{target_state}") # type: ignore wait( waiter=waiter, waiter_delay=check_interval, waiter_max_attempts=max_attempts, args={"DBInstanceIdentifier": db_instance_id}, failure_message=f"Rdb DB instance failed to reach state {target_state}", status_message="Rds DB instance state is", status_args=["DBInstances[0].DBInstanceStatus"], ) else: self._wait_for_state(poke, target_state, check_interval, max_attempts) self.log.info("DB cluster '%s' reached the '%s' state", db_instance_id, target_state)
Poll DB Instances until target_state is reached; raise AirflowException after max_attempts. .. seealso:: - :external+boto3:py:meth:`RDS.Client.describe_db_instances` :param db_instance_id: The ID of the target DB instance. :param target_state: Wait until this state is reached :param check_interval: The amount of time in seconds to wait between attempts :param max_attempts: The maximum number of attempts to be made
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/rds.py
244
[ "self", "db_instance_id", "target_state", "check_interval", "max_attempts" ]
None
true
3
6.4
apache/airflow
43,597
sphinx
false
parseIdRefElement
public @Nullable Object parseIdRefElement(Element ele) { // A generic reference to any name of any bean. String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE); if (!StringUtils.hasLength(refName)) { error("'bean' is required for <idref> element", ele); return null; } if (!StringUtils.hasText(refName)) { error("<idref> element contains empty target attribute", ele); return null; } RuntimeBeanNameReference ref = new RuntimeBeanNameReference(refName); ref.setSource(extractSource(ele)); return ref; }
Return a typed String value Object for the given 'idref' element.
java
spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java
1,045
[ "ele" ]
Object
true
3
6
spring-projects/spring-framework
59,386
javadoc
false
successfulAuthentications
public int successfulAuthentications() { return successfulAuthentications; }
Return the number of times this instance has successfully authenticated. This value can only exceed 1 when re-authentication is enabled and it has succeeded at least once. @return the number of times this instance has successfully authenticated
java
clients/src/main/java/org/apache/kafka/common/network/KafkaChannel.java
508
[]
true
1
6.64
apache/kafka
31,560
javadoc
false
randomInt
public int randomInt(final int startInclusive, final int endExclusive) { Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value."); Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); if (startInclusive == endExclusive) { return startInclusive; } return startInclusive + random().nextInt(endExclusive - startInclusive); }
Generates a random integer within the specified range. @param startInclusive the smallest value that can be returned, must be non-negative. @param endExclusive the upper bound (not included). @throws IllegalArgumentException if {@code startInclusive > endExclusive} or if {@code startInclusive} is negative. @return the random integer. @since 3.16.0
java
src/main/java/org/apache/commons/lang3/RandomUtils.java
399
[ "startInclusive", "endExclusive" ]
true
2
7.44
apache/commons-lang
2,896
javadoc
false
get_cloudwatch_logs
def get_cloudwatch_logs( self, stream_name: str, task_instance: RuntimeTI ) -> Generator[CloudWatchLogEvent, None, None]: """ Return all logs from the given log stream. :param stream_name: name of the Cloudwatch log stream to get all logs from :param task_instance: the task instance to get logs about :return: string of all logs from the given log stream """ stream_name = stream_name.replace(":", "_") # If there is an end_date to the task instance, fetch logs until that date + 30 seconds # 30 seconds is an arbitrary buffer so that we don't miss any logs that were emitted end_time = ( None if (end_date := getattr(task_instance, "end_date", None)) is None else datetime_to_epoch_utc_ms(end_date + timedelta(seconds=30)) ) return self.hook.get_log_events( log_group=self.log_group, log_stream_name=stream_name, end_time=end_time, )
Return all logs from the given log stream. :param stream_name: name of the Cloudwatch log stream to get all logs from :param task_instance: the task instance to get logs about :return: string of all logs from the given log stream
python
providers/amazon/src/airflow/providers/amazon/aws/log/cloudwatch_task_handler.py
196
[ "self", "stream_name", "task_instance" ]
Generator[CloudWatchLogEvent, None, None]
true
2
8.24
apache/airflow
43,597
sphinx
false
doParseTrieToBuilder
private static int doParseTrieToBuilder( Deque<CharSequence> stack, CharSequence encoded, int start, ImmutableMap.Builder<String, PublicSuffixType> builder) { int encodedLen = encoded.length(); int idx = start; char c = '\0'; // Read all the characters for this node. for (; idx < encodedLen; idx++) { c = encoded.charAt(idx); if (c == '&' || c == '?' || c == '!' || c == ':' || c == ',') { break; } } stack.push(reverse(encoded.subSequence(start, idx))); if (c == '!' || c == '?' || c == ':' || c == ',') { // '!' represents an interior node that represents a REGISTRY entry in the map. // '?' represents a leaf node, which represents a REGISTRY entry in map. // ':' represents an interior node that represents a private entry in the map // ',' represents a leaf node, which represents a private entry in the map. String domain = DIRECT_JOINER.join(stack); if (domain.length() > 0) { builder.put(domain, PublicSuffixType.fromCode(c)); } } idx++; if (c != '?' && c != ',') { while (idx < encodedLen) { // Read all the children idx += doParseTrieToBuilder(stack, encoded, idx, builder); if (encoded.charAt(idx) == '?' || encoded.charAt(idx) == ',') { // An extra '?' or ',' after a child node indicates the end of all children of this node. idx++; break; } } } stack.pop(); return idx - start; }
Parses a trie node and returns the number of characters consumed. @param stack The prefixes that precede the characters represented by this node. Each entry of the stack is in reverse order. @param encoded The serialized trie. @param start An index in the encoded serialized trie to begin reading characters from. @param builder A map builder to which all entries will be added. @return The number of characters consumed from {@code encoded}.
java
android/guava/src/com/google/thirdparty/publicsuffix/TrieParser.java
64
[ "stack", "encoded", "start", "builder" ]
true
17
7.04
google/guava
51,352
javadoc
false
nop
static BooleanConsumer nop() { return NOP; }
Gets the NOP singleton. @return The NOP singleton.
java
src/main/java/org/apache/commons/lang3/function/BooleanConsumer.java
40
[]
BooleanConsumer
true
1
6.96
apache/commons-lang
2,896
javadoc
false
postProcessAfterInitialization
@Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (this.advisor == null || bean instanceof AopInfrastructureBean) { // Ignore AOP infrastructure such as scoped proxies. return bean; } if (bean instanceof Advised advised) { if (!advised.isFrozen() && isEligible(AopUtils.getTargetClass(bean))) { // Add our local Advisor to the existing proxy's Advisor chain. if (this.beforeExistingAdvisors) { advised.addAdvisor(0, this.advisor); } else if (advised.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE && advised.getAdvisorCount() > 0) { // No target, leave last Advisor in place and add new Advisor right before. advised.addAdvisor(advised.getAdvisorCount() - 1, this.advisor); return bean; } else { advised.addAdvisor(this.advisor); } return bean; } } if (isEligible(bean, beanName)) { ProxyFactory proxyFactory = prepareProxyFactory(bean, beanName); if (!proxyFactory.isProxyTargetClass() && !proxyFactory.hasUserSuppliedInterfaces()) { evaluateProxyInterfaces(bean.getClass(), proxyFactory); } proxyFactory.addAdvisor(this.advisor); customizeProxyFactory(proxyFactory); proxyFactory.setFrozen(isFrozen()); proxyFactory.setPreFiltered(true); // Use original ClassLoader if bean class not locally loaded in overriding class loader ClassLoader classLoader = getProxyClassLoader(); if (classLoader instanceof SmartClassLoader smartClassLoader && classLoader != bean.getClass().getClassLoader()) { classLoader = smartClassLoader.getOriginalClassLoader(); } return proxyFactory.getProxy(classLoader); } // No proxy needed. return bean; }
Set whether this post-processor's advisor is supposed to apply before existing advisors when encountering a pre-advised object. <p>Default is "false", applying the advisor after existing advisors, i.e. as close as possible to the target method. Switch this to "true" in order for this post-processor's advisor to wrap existing advisors as well. <p>Note: Check the concrete post-processor's javadoc whether it possibly changes this flag by default, depending on the nature of its advisor.
java
spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java
87
[ "bean", "beanName" ]
Object
true
14
6
spring-projects/spring-framework
59,386
javadoc
false
parseFunctionOrConstructorType
function parseFunctionOrConstructorType(): TypeNode { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiersForConstructorType(); const isConstructorType = parseOptional(SyntaxKind.NewKeyword); Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers."); const typeParameters = parseTypeParameters(); const parameters = parseParameters(SignatureFlags.Type); const type = parseReturnType(SyntaxKind.EqualsGreaterThanToken, /*isType*/ false); const node = isConstructorType ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type) : factory.createFunctionTypeNode(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); }
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,508
[]
true
3
6.72
microsoft/TypeScript
107,154
jsdoc
false
rand
def rand(*args): """ Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- out : ndarray The matrix of random values with shape given by `\\*args`. See Also -------- randn, numpy.random.RandomState.rand Examples -------- >>> np.random.seed(123) >>> import numpy.matlib >>> np.matlib.rand(2, 3) matrix([[0.69646919, 0.28613933, 0.22685145], [0.55131477, 0.71946897, 0.42310646]]) >>> np.matlib.rand((2, 3)) matrix([[0.9807642 , 0.68482974, 0.4809319 ], [0.39211752, 0.34317802, 0.72904971]]) If the first argument is a tuple, other arguments are ignored: >>> np.matlib.rand((2, 3), 4) matrix([[0.43857224, 0.0596779 , 0.39804426], [0.73799541, 0.18249173, 0.17545176]]) """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.rand(*args))
Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- out : ndarray The matrix of random values with shape given by `\\*args`. See Also -------- randn, numpy.random.RandomState.rand Examples -------- >>> np.random.seed(123) >>> import numpy.matlib >>> np.matlib.rand(2, 3) matrix([[0.69646919, 0.28613933, 0.22685145], [0.55131477, 0.71946897, 0.42310646]]) >>> np.matlib.rand((2, 3)) matrix([[0.9807642 , 0.68482974, 0.4809319 ], [0.39211752, 0.34317802, 0.72904971]]) If the first argument is a tuple, other arguments are ignored: >>> np.matlib.rand((2, 3), 4) matrix([[0.43857224, 0.0596779 , 0.39804426], [0.73799541, 0.18249173, 0.17545176]])
python
numpy/matlib.py
233
[]
false
2
7.36
numpy/numpy
31,054
numpy
false
isZipArchive
private boolean isZipArchive(ProjectGenerationResponse entity) { if (entity.getContentType() != null) { try { return ZIP_MIME_TYPE.equals(entity.getContentType().getMimeType()); } catch (Exception ex) { // Ignore } } return false; }
Detect if the project should be extracted. @param request the generation request @param response the generation response @return if the project should be extracted
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java
83
[ "entity" ]
true
3
8.24
spring-projects/spring-boot
79,428
javadoc
false
call
void call(Call call, long now) { if (hardShutdownTimeMs.get() != INVALID_SHUTDOWN_TIME) { log.debug("Cannot accept new call {} when AdminClient is closing.", call); call.handleFailure(new IllegalStateException("Cannot accept new calls when AdminClient is closing.")); } else if (metadataManager.usingBootstrapControllers() && (!call.nodeProvider.supportsUseControllers())) { call.fail(now, new UnsupportedEndpointTypeException("This Admin API is not " + "yet supported when communicating directly with the controller quorum.")); } else { enqueue(call, now); } }
Initiate a new call. <p> This will fail if the AdminClient is scheduled to shut down. @param call The new call object. @param now The current time in milliseconds.
java
clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
1,585
[ "call", "now" ]
void
true
4
6.72
apache/kafka
31,560
javadoc
false
getExternalModuleOrNamespaceExportName
function getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression { if (ns && hasSyntacticModifier(node, ModifierFlags.Export)) { return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); } return getExportName(node, allowComments, allowSourceMaps); }
Gets the exported name of a declaration for use in expressions. An exported name will *always* be prefixed with an module or namespace export modifier like "exports." if the name points to an exported symbol. @param ns The namespace identifier. @param node The declaration. @param allowComments A value indicating whether comments may be emitted for the name. @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
typescript
src/compiler/factory/nodeFactory.ts
6,857
[ "ns", "node", "allowComments?", "allowSourceMaps?" ]
true
3
6.72
microsoft/TypeScript
107,154
jsdoc
false
hexToInt
public static int hexToInt(final String src, final int srcPos, final int dstInit, final int dstPos, final int nHex) { if (0 == nHex) { return dstInit; } if ((nHex - 1) * 4 + dstPos >= Integer.SIZE) { throw new IllegalArgumentException("(nHexs - 1) * 4 + dstPos >= 32"); } int out = dstInit; for (int i = 0; i < nHex; i++) { final int shift = i * 4 + dstPos; final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; final int mask = 0xf << shift; out = out & ~mask | bits; } return out; }
Converts an array of char into an int using the default (little-endian, LSB0) byte and bit ordering. @param src the hexadecimal string to convert. @param srcPos the position in {@code src}, in char unit, from where to start the conversion. @param dstInit initial value of the destination int. @param dstPos the position of the LSB, in bits, in the result int. @param nHex the number of chars to convert. @return an int containing the selected bits. @throws IllegalArgumentException if {@code (nHexs - 1) * 4 + dstPos >= 32}.
java
src/main/java/org/apache/commons/lang3/Conversion.java
772
[ "src", "srcPos", "dstInit", "dstPos", "nHex" ]
true
4
8.08
apache/commons-lang
2,896
javadoc
false
getSingletonTarget
public static @Nullable Object getSingletonTarget(Object candidate) { if (candidate instanceof Advised advised) { TargetSource targetSource = advised.getTargetSource(); if (targetSource instanceof SingletonTargetSource singleTargetSource) { return singleTargetSource.getTarget(); } } return null; }
Obtain the singleton target object behind the given proxy, if any. @param candidate the (potential) proxy to check @return the singleton target object managed in a {@link SingletonTargetSource}, or {@code null} in any other case (not a proxy, not an existing singleton target) @since 4.3.8 @see Advised#getTargetSource() @see SingletonTargetSource#getTarget()
java
spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java
62
[ "candidate" ]
Object
true
3
7.44
spring-projects/spring-framework
59,386
javadoc
false
move
public static void move(File from, File to) throws IOException { checkNotNull(from); checkNotNull(to); checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); if (!from.renameTo(to)) { copy(from, to); if (!from.delete()) { if (!to.delete()) { throw new IOException("Unable to delete " + to); } throw new IOException("Unable to delete " + from); } } }
Moves a file from one path to another. This method can rename a file and/or move it to a different directory. In either case {@code to} must be the target path for the file itself; not just the new name for the file or the path to the new parent directory. <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}. @param from the source file @param to the destination file @throws IOException if an I/O error occurs @throws IllegalArgumentException if {@code from.equals(to)}
java
android/guava/src/com/google/common/io/Files.java
491
[ "from", "to" ]
void
true
4
6.88
google/guava
51,352
javadoc
false
join
public String join(String separator) throws JSONException { JSONStringer stringer = new JSONStringer(); stringer.open(JSONStringer.Scope.NULL, ""); for (int i = 0, size = this.values.size(); i < size; i++) { if (i > 0) { stringer.out.append(separator); } stringer.value(this.values.get(i)); } stringer.close(JSONStringer.Scope.NULL, JSONStringer.Scope.NULL, ""); return stringer.out.toString(); }
Returns a new string by alternating this array's values with {@code separator}. This array's string values are quoted and have their special characters escaped. For example, the array containing the strings '12" pizza', 'taco' and 'soda' joined on '+' returns this: <pre>"12\" pizza"+"taco"+"soda"</pre> @param separator the separator to use @return the joined value @throws JSONException if processing of json failed
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java
605
[ "separator" ]
String
true
3
7.76
spring-projects/spring-boot
79,428
javadoc
false
nullToEmpty
public static Float[] nullToEmpty(final Float[] array) { return nullTo(array, EMPTY_FLOAT_OBJECT_ARRAY); }
Defensive programming technique to change a {@code null} reference to an empty one. <p> This method returns an empty array for a {@code null} input array. </p> <p> As a memory optimizing technique an empty array passed in will be overridden with the empty {@code public static} references in this class. </p> @param array the array to check for {@code null} or empty. @return the same array, {@code public static} empty array if {@code null} or empty input. @since 2.5
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
4,470
[ "array" ]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
app_template_global
def app_template_global( self, name: T_template_global | str | None = None ) -> T_template_global | t.Callable[[T_template_global], T_template_global]: """Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. The :meth:`add_app_template_global` method may be used to register a function later rather than decorating. The global is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.template_global`. :param name: The name to register the global as. If not given, uses the function's name. .. versionadded:: 0.10 """ if callable(name): self.add_app_template_global(name) return name def decorator(f: T_template_global) -> T_template_global: self.add_app_template_global(f, name=name) return f return decorator
Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. The :meth:`add_app_template_global` method may be used to register a function later rather than decorating. The global is available in all templates, not only those under this blueprint. Equivalent to :meth:`.Flask.template_global`. :param name: The name to register the global as. If not given, uses the function's name. .. versionadded:: 0.10
python
src/flask/sansio/blueprints.py
562
[ "self", "name" ]
T_template_global | t.Callable[[T_template_global], T_template_global]
true
2
6.72
pallets/flask
70,946
sphinx
false
nextLong
@Deprecated public static long nextLong(final long startInclusive, final long endExclusive) { return secure().randomLong(startInclusive, endExclusive); }
Generates a random long within the specified range. @param startInclusive the smallest value that can be returned, must be non-negative. @param endExclusive the upper bound (not included). @throws IllegalArgumentException if {@code startInclusive > endExclusive} or if {@code startInclusive} is negative. @return the random long. @deprecated Use {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
java
src/main/java/org/apache/commons/lang3/RandomUtils.java
234
[ "startInclusive", "endExclusive" ]
true
1
6.16
apache/commons-lang
2,896
javadoc
false
span
@Override public Range<K> span() { if (ranges.isEmpty()) { throw new NoSuchElementException(); } Range<K> firstRange = ranges.get(0); Range<K> lastRange = ranges.get(ranges.size() - 1); return Range.create(firstRange.lowerBound, lastRange.upperBound); }
A builder for immutable range maps. Overlapping ranges are prohibited. @since 14.0
java
android/guava/src/com/google/common/collect/ImmutableRangeMap.java
216
[]
true
2
6.88
google/guava
51,352
javadoc
false
isSupported
@Deprecated public static boolean isSupported(final String name) { if (name == null) { return false; } try { return Charset.isSupported(name); } catch (final IllegalCharsetNameException ex) { return false; } }
Tests whether the named charset is supported. <p>This is similar to <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#isSupported%28java.lang.String%29"> java.nio.charset.Charset.isSupported(String)</a> but handles more formats</p> @param name the name of the requested charset; may be either a canonical name or an alias, null returns false @return {@code true} if the charset is available in the current Java virtual machine @deprecated Please use {@link Charset#isSupported(String)} instead, although be aware that {@code null} values are not accepted by that method and an {@link IllegalCharsetNameException} may be thrown.
java
src/main/java/org/apache/commons/lang3/CharEncoding.java
99
[ "name" ]
true
3
7.44
apache/commons-lang
2,896
javadoc
false
setUncaughtExceptionHandler
@CanIgnoreReturnValue public ThreadFactoryBuilder setUncaughtExceptionHandler( UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); return this; }
Sets the {@link UncaughtExceptionHandler} for new threads created with this ThreadFactory. <p><b>Java 21+ users:</b> use {@link Thread.Builder#uncaughtExceptionHandler(Thread.UncaughtExceptionHandler)} instead. @param uncaughtExceptionHandler the uncaught exception handler for new Threads created with this ThreadFactory @return this for the builder pattern
java
android/guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
148
[ "uncaughtExceptionHandler" ]
ThreadFactoryBuilder
true
1
6.24
google/guava
51,352
javadoc
false
threadRenaming
@J2ktIncompatible @GwtIncompatible // threads static Runnable threadRenaming(Runnable task, Supplier<String> nameSupplier) { checkNotNull(nameSupplier); checkNotNull(task); return () -> { Thread currentThread = Thread.currentThread(); String oldName = currentThread.getName(); boolean restoreName = trySetName(nameSupplier.get(), currentThread); try { task.run(); } finally { if (restoreName) { boolean unused = trySetName(oldName, currentThread); } } }; }
Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is running with have the given name. @param task The Runnable to wrap @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once for each invocation of the wrapped callable.
java
android/guava/src/com/google/common/util/concurrent/Callables.java
94
[ "task", "nameSupplier" ]
Runnable
true
2
6.72
google/guava
51,352
javadoc
false
onFailedResponse
private void onFailedResponse(final long currentTimeMs, final Throwable exception) { coordinatorRequestState.onFailedAttempt(currentTimeMs); markCoordinatorUnknown("FindCoordinator failed with exception", currentTimeMs); if (exception instanceof RetriableException) { log.debug("FindCoordinator request failed due to retriable exception", exception); return; } if (exception == Errors.GROUP_AUTHORIZATION_FAILED.exception()) { log.debug("FindCoordinator request failed due to authorization error {}", exception.getMessage()); KafkaException groupAuthorizationException = GroupAuthorizationException.forGroupId(this.groupId); fatalError = Optional.of(groupAuthorizationException); return; } log.warn("FindCoordinator request failed due to fatal exception", exception); fatalError = Optional.of(exception); }
Mark the coordinator as "unknown" (i.e. {@code null}) when a disconnect is detected. This detection can occur in one of two paths: <ol> <li>The coordinator was discovered, but then later disconnected</li> <li>The coordinator has not yet been discovered and/or connected</li> </ol> @param cause String explanation of why the coordinator is marked unknown @param currentTimeMs Current time in milliseconds
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CoordinatorRequestManager.java
199
[ "currentTimeMs", "exception" ]
void
true
3
6.24
apache/kafka
31,560
javadoc
false
toString
@Override public String toString() { return super.toString() + " id=" + id; }
@return true if underlying transport has bytes remaining to be read from any underlying intermediate buffers.
java
clients/src/main/java/org/apache/kafka/common/network/KafkaChannel.java
496
[]
String
true
1
6.64
apache/kafka
31,560
javadoc
false
put
@Override public boolean put(@ParametricNullness K key, @ParametricNullness V value) { Collection<V> collection = map.get(key); if (collection == null) { collection = createCollection(key); if (collection.add(value)) { totalSize++; map.put(key, collection); return true; } else { throw new AssertionError("New Collection violated the Collection spec"); } } else if (collection.add(value)) { totalSize++; return true; } else { return false; } }
Creates the collection of values for an explicitly provided key. By default, it simply calls {@link #createCollection()}, which is the correct behavior for most implementations. The {@link LinkedHashMultimap} class overrides it. @param key key to associate with values in the collection @return an empty collection of values
java
android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
187
[ "key", "value" ]
true
4
7.92
google/guava
51,352
javadoc
false
isCyclePresent
private boolean isCyclePresent(Element returnType, Element element) { if (!(element.getEnclosingElement() instanceof TypeElement)) { return false; } if (element.getEnclosingElement().equals(returnType)) { return true; } return isCyclePresent(returnType, element.getEnclosingElement()); }
Return if this property has been explicitly marked as nested (for example using an annotation}. @param environment the metadata generation environment @return if the property has been marked as nested
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptor.java
147
[ "returnType", "element" ]
true
3
7.92
spring-projects/spring-boot
79,428
javadoc
false
intToByteArray
public static byte[] intToByteArray(final int src, final int srcPos, final byte[] dst, final int dstPos, final int nBytes) { if (0 == nBytes) { return dst; } if ((nBytes - 1) * Byte.SIZE + srcPos >= Integer.SIZE) { throw new IllegalArgumentException("(nBytes - 1) * 8 + srcPos >= 32"); } for (int i = 0; i < nBytes; i++) { final int shift = i * Byte.SIZE + srcPos; dst[dstPos + i] = (byte) (0xff & src >> shift); } return dst; }
Converts an int into an array of byte using the default (little-endian, LSB0) byte and bit ordering. @param src the int 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 >= 32}. @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}.
java
src/main/java/org/apache/commons/lang3/Conversion.java
915
[ "src", "srcPos", "dst", "dstPos", "nBytes" ]
true
4
8.08
apache/commons-lang
2,896
javadoc
false
getLoadableFileExtension
private @Nullable String getLoadableFileExtension(PropertySourceLoader loader, String file) { for (String fileExtension : loader.getFileExtensions()) { if (StringUtils.endsWithIgnoreCase(file, fileExtension)) { return fileExtension; } } return null; }
Create a new {@link StandardConfigDataLocationResolver} instance. @param logFactory the factory for loggers to use @param binder a binder backed by the initial {@link Environment} @param resourceLoader a {@link ResourceLoader} used to load resources
java
core/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java
246
[ "loader", "file" ]
String
true
2
6.08
spring-projects/spring-boot
79,428
javadoc
false