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
fromSpringFactories
static LoggingSystemFactory fromSpringFactories() { return new DelegatingLoggingSystemFactory( (classLoader) -> SpringFactoriesLoader.loadFactories(LoggingSystemFactory.class, classLoader)); }
Return a {@link LoggingSystemFactory} backed by {@code spring.factories}. @return a {@link LoggingSystemFactory} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemFactory.java
44
[]
LoggingSystemFactory
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
of
@Contract("null -> null; !null -> !null") static @Nullable SimpleCacheResolver of(@Nullable CacheManager cacheManager) { return (cacheManager != null ? new SimpleCacheResolver(cacheManager) : null); }
Return a {@code SimpleCacheResolver} for the given {@link CacheManager}. @param cacheManager the CacheManager (potentially {@code null}) @return the SimpleCacheResolver ({@code null} if the CacheManager was {@code null}) @since 5.1
java
spring-context/src/main/java/org/springframework/cache/interceptor/SimpleCacheResolver.java
67
[ "cacheManager" ]
SimpleCacheResolver
true
2
7.2
spring-projects/spring-framework
59,386
javadoc
false
countMatches
public static int countMatches(final CharSequence str, final CharSequence sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) { count++; idx += sub.length(); } return count; }
Counts how many times the substring appears in the larger string. Note that the code only counts non-overlapping matches. <p> A {@code null} or empty ("") String input returns {@code 0}. </p> <pre> StringUtils.countMatches(null, *) = 0 StringUtils.countMatches("", *) = 0 StringUtils.countMatches("abba", null) = 0 StringUtils.countMatches("abba", "") = 0 StringUtils.countMatches("abba", "a") = 2 StringUtils.countMatches("abba", "ab") = 1 StringUtils.countMatches("abba", "xxx") = 0 StringUtils.countMatches("ababa", "aba") = 1 </pre> @param str the CharSequence to check, may be null. @param sub the substring to count, may be null. @return the number of occurrences, 0 if either CharSequence is {@code null}. @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence)
java
src/main/java/org/apache/commons/lang3/StringUtils.java
1,494
[ "str", "sub" ]
true
4
7.76
apache/commons-lang
2,896
javadoc
false
__contains__
def __contains__(self, key: Any) -> bool: """ Return a boolean indicating whether the provided key is in the index. Parameters ---------- key : label The key to check if it is present in the index. Returns ------- bool Whether the key search is in the index. Raises ------ TypeError If the key is not hashable. See Also -------- Index.isin : Returns an ndarray of boolean dtype indicating whether the list-like key is in the index. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Index([1, 2, 3, 4], dtype='int64') >>> 2 in idx True >>> 6 in idx False """ hash(key) try: self.get_loc(key) except (KeyError, TypeError, ValueError, InvalidIndexError): return False return True
Return a boolean indicating whether the provided key is in the index. Parameters ---------- key : label The key to check if it is present in the index. Returns ------- bool Whether the key search is in the index. Raises ------ TypeError If the key is not hashable. See Also -------- Index.isin : Returns an ndarray of boolean dtype indicating whether the list-like key is in the index. Examples -------- >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Index([1, 2, 3, 4], dtype='int64') >>> 2 in idx True >>> 6 in idx False
python
pandas/core/indexes/datetimelike.py
275
[ "self", "key" ]
bool
true
1
7.28
pandas-dev/pandas
47,362
numpy
false
parseToken
protected String parseToken(final String pattern, final int[] indexRef) { final StringBuilder buf = new StringBuilder(); int i = indexRef[0]; final int length = pattern.length(); char c = pattern.charAt(i); final char c1 = c; if (CharUtils.isAsciiAlpha(c1)) { // Scan a run of the same character, which indicates a time // pattern. buf.append(c); while (i + 1 < length) { final char peek = pattern.charAt(i + 1); if (peek != c) { break; } buf.append(c); i++; } } else { // This will identify token as text. buf.append('\''); boolean inLiteral = false; for (; i < length; i++) { c = pattern.charAt(i); if (c == '\'') { if (i + 1 < length && pattern.charAt(i + 1) == '\'') { // '' is treated as escaped ' i++; buf.append(c); } else { inLiteral = !inLiteral; } } else { final char c2 = c; if (!inLiteral && CharUtils.isAsciiAlpha(c2)) { i--; break; } buf.append(c); } } } indexRef[0] = i; return buf.toString(); }
Performs the parsing of tokens. @param pattern the pattern. @param indexRef index references. @return parsed token.
java
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
1,479
[ "pattern", "indexRef" ]
String
true
10
7.76
apache/commons-lang
2,896
javadoc
false
getAnnotation
public ConfigurationProperties getAnnotation() { ConfigurationProperties annotation = this.bindTarget.getAnnotation(ConfigurationProperties.class); Assert.state(annotation != null, "'annotation' must not be null"); return annotation; }
Return the {@link ConfigurationProperties} annotation for the bean. The annotation may be defined on the bean itself or from the factory method that create the bean (usually a {@link Bean @Bean} method). @return the configuration properties annotation
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBean.java
114
[]
ConfigurationProperties
true
1
6.4
spring-projects/spring-boot
79,428
javadoc
false
main
public static void main(String[] args) { System.out.println(toHtml()); }
Check if a Throwable is a commonly wrapped exception type (e.g. `CompletionException`) and return the cause if so. This is useful to handle cases where exceptions may be raised from a future or a completion stage (as might be the case for requests sent to the controller in `ControllerApis`). @param t The Throwable to check @return The throwable itself or its cause if it is an instance of a commonly wrapped exception type
java
clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
578
[ "args" ]
void
true
1
6.8
apache/kafka
31,560
javadoc
false
Synchronized
Synchronized(Synchronized&& rhs, const LockedPtr& /*guard*/) noexcept( nxMoveCtor) : datum_(std::move(rhs.datum_)) {}
Helper constructors to enable Synchronized for non-default constructible types T. Guards are created in actual public constructors and are alive for the time required to construct the object
cpp
folly/Synchronized.h
963
[]
true
2
6.8
facebook/folly
30,157
doxygen
false
sendListOffsetRequest
private RequestFuture<ListOffsetResult> sendListOffsetRequest(final Node node, final Map<TopicPartition, ListOffsetsPartition> timestampsToSearch, boolean requireTimestamp) { ListOffsetsRequest.Builder builder = ListOffsetsRequest.Builder .forConsumer(requireTimestamp, isolationLevel) .setTargetTimes(ListOffsetsRequest.toListOffsetsTopics(timestampsToSearch)) .setTimeoutMs(requestTimeoutMs); log.debug("Sending ListOffsetRequest {} to broker {}", builder, node); return client.send(node, builder) .compose(new RequestFutureAdapter<>() { @Override public void onSuccess(ClientResponse response, RequestFuture<ListOffsetResult> future) { ListOffsetsResponse lor = (ListOffsetsResponse) response.responseBody(); log.trace("Received ListOffsetResponse {} from broker {}", lor, node); handleListOffsetResponse(lor, future); } }); }
Send the ListOffsetRequest to a specific broker for the partitions and target timestamps. @param node The node to send the ListOffsetRequest to. @param timestampsToSearch The mapping from partitions to the target timestamps. @param requireTimestamp True if we require a timestamp in the response. @return A response which can be polled to obtain the corresponding timestamps and offsets.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetFetcher.java
393
[ "node", "timestampsToSearch", "requireTimestamp" ]
true
1
6.72
apache/kafka
31,560
javadoc
false
parseType
public static Object parseType(String name, Object value, Type type) { try { if (value == null) return null; String trimmed = null; if (value instanceof String) trimmed = ((String) value).trim(); switch (type) { case BOOLEAN: if (value instanceof String) { if (trimmed.equalsIgnoreCase("true")) return true; else if (trimmed.equalsIgnoreCase("false")) return false; else throw new ConfigException(name, value, "Expected value to be either true or false"); } else if (value instanceof Boolean) return value; else throw new ConfigException(name, value, "Expected value to be either true or false"); case PASSWORD: if (value instanceof Password) return value; else if (value instanceof String) return new Password(trimmed); else throw new ConfigException(name, value, "Expected value to be a string, but it was a " + value.getClass().getName()); case STRING: if (value instanceof String) return trimmed; else throw new ConfigException(name, value, "Expected value to be a string, but it was a " + value.getClass().getName()); case INT: if (value instanceof Integer) { return value; } else if (value instanceof String) { return Integer.parseInt(trimmed); } else { throw new ConfigException(name, value, "Expected value to be a 32-bit integer, but it was a " + value.getClass().getName()); } case SHORT: if (value instanceof Short) { return value; } else if (value instanceof String) { return Short.parseShort(trimmed); } else { throw new ConfigException(name, value, "Expected value to be a 16-bit integer (short), but it was a " + value.getClass().getName()); } case LONG: if (value instanceof Integer) return ((Integer) value).longValue(); if (value instanceof Long) return value; else if (value instanceof String) return Long.parseLong(trimmed); else throw new ConfigException(name, value, "Expected value to be a 64-bit integer (long), but it was a " + value.getClass().getName()); case DOUBLE: if (value instanceof Number) return ((Number) value).doubleValue(); else if (value instanceof String) return Double.parseDouble(trimmed); else throw new ConfigException(name, value, "Expected value to be a double, but it was a " + value.getClass().getName()); case LIST: if (value instanceof List) return value; else if (value instanceof String) if (trimmed.isEmpty()) return Collections.emptyList(); else return Arrays.asList(COMMA_WITH_WHITESPACE.split(trimmed, -1)); else throw new ConfigException(name, value, "Expected a comma separated list."); case CLASS: if (value instanceof Class) return value; else if (value instanceof String) { return Utils.loadClass(trimmed, Object.class); } else throw new ConfigException(name, value, "Expected a Class instance or class name."); default: throw new IllegalStateException("Unknown type."); } } catch (NumberFormatException e) { throw new ConfigException(name, value, "Not a number of type " + type); } catch (ClassNotFoundException e) { throw new ConfigException(name, value, "Class " + value + " could not be found."); } }
Parse a value according to its expected type. @param name The config name @param value The config value @param type The expected type @return The parsed object
java
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
701
[ "name", "value", "type" ]
Object
true
26
6.96
apache/kafka
31,560
javadoc
false
to_key_val_list
def to_key_val_list(value): """Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list """ if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError("cannot encode objects that are not 2-tuples") if isinstance(value, Mapping): value = value.items() return list(value)
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list('string') Traceback (most recent call last): ... ValueError: cannot encode objects that are not 2-tuples :rtype: list
python
src/requests/utils.py
335
[ "value" ]
false
4
7.68
psf/requests
53,586
unknown
false
nop
@SuppressWarnings("unchecked") static <R, E extends Throwable> FailableDoubleFunction<R, E> nop() { return NOP; }
Gets the NOP singleton. @param <R> Return type. @param <E> The kind of thrown exception or error. @return The NOP singleton.
java
src/main/java/org/apache/commons/lang3/function/FailableDoubleFunction.java
43
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
advance
@Override public void advance() { assertEndNotReached(); hasNextValue = delegate.hasNext(); if (hasNextValue == false) { return; } currentIndex = adjustScale(delegate.peekIndex(), delegate.scale(), scaleAdjustment); currentCount = delegate.peekCount(); delegate.advance(); while (delegate.hasNext() && adjustScale(delegate.peekIndex(), delegate.scale(), scaleAdjustment) == currentIndex) { currentCount += delegate.peekCount(); delegate.advance(); } }
Creates a new scale-adjusting iterator. @param delegate the iterator to wrap @param targetScale the target scale for the new iterator
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ScaleAdjustingBucketIterator.java
69
[]
void
true
4
6.56
elastic/elasticsearch
75,680
javadoc
false
prepareRefresh
protected void prepareRefresh() { // Switch to active. this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) { logger.trace("Refreshing " + this); } else { logger.debug("Refreshing " + getDisplayName()); } } // Initialize any placeholder property sources in the context environment. initPropertySources(); // Validate that all properties marked as required are resolvable: // see ConfigurablePropertyResolver#setRequiredProperties getEnvironment().validateRequiredProperties(); // Store pre-refresh ApplicationListeners... if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } // Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<>(); }
Prepare this context for refreshing, setting its startup date and active flag as well as performing any initialization of property sources.
java
spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
666
[]
void
true
4
6.88
spring-projects/spring-framework
59,386
javadoc
false
decrementAndGet
public float decrementAndGet() { value--; return value; }
Decrements this instance's value by 1; this method returns the value associated with the instance immediately after the decrement operation. This method is not thread safe. @return the value associated with the instance after it is decremented. @since 3.5
java
src/main/java/org/apache/commons/lang3/mutable/MutableFloat.java
159
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
bindExportsPropertyAssignment
function bindExportsPropertyAssignment(node: BindableStaticPropertyAssignmentExpression) { // When we create a property via 'exports.foo = bar', the 'exports.foo' property access // expression is the declaration if (!setCommonJsModuleIndicator(node)) { return; } const symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, (id, symbol) => { if (symbol) { addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment); } return symbol; }); if (symbol) { const isAlias = isAliasableExpression(node.right) && (isExportsIdentifier(node.left.expression) || isModuleExportsAccessExpression(node.left.expression)); const flags = isAlias ? SymbolFlags.Alias : SymbolFlags.Property | SymbolFlags.ExportValue; setParent(node.left, node); declareSymbol(symbol.exports!, symbol, node.left, flags, SymbolFlags.None); } }
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @param symbolTable - The symbol table which node will be added to. @param parent - node's parent declaration. @param node - The declaration to be added to the symbol table @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
typescript
src/compiler/binder.ts
3,216
[ "node" ]
false
7
6.08
microsoft/TypeScript
107,154
jsdoc
false
join
public static String join(final Object[] array, final char delimiter, final int startIndex, final int endIndex) { return join(array, String.valueOf(delimiter), startIndex, endIndex); }
Joins the elements of the provided array into a single String containing the provided list of elements. <p> No delimiter is added before or after the list. Null objects or empty strings within the array are represented by empty strings. </p> <pre> StringUtils.join(null, *) = null StringUtils.join([], *) = "" StringUtils.join([null], *) = "" StringUtils.join(["a", "b", "c"], ';') = "a;b;c" StringUtils.join(["a", "b", "c"], null) = "abc" StringUtils.join([null, "", "a"], ';') = ";;a" </pre> @param array the array of values to join together, may be null. @param delimiter the separator character to use. @param startIndex the first index to start joining from. It is an error to pass in a start index past the end of the array. @param endIndex the index to stop joining from (exclusive). It is an error to pass in an end index past the end of the array. @return the joined String, {@code null} if null array input. @since 2.0
java
src/main/java/org/apache/commons/lang3/StringUtils.java
4,536
[ "array", "delimiter", "startIndex", "endIndex" ]
String
true
1
6.8
apache/commons-lang
2,896
javadoc
false
acceptClassLoader
public static void acceptClassLoader(@Nullable ClassLoader classLoader) { if (classLoader != null) { acceptedClassLoaders.add(classLoader); } }
Accept the given ClassLoader as cache-safe, even if its classes would not qualify as cache-safe in this CachedIntrospectionResults class. <p>This configuration method is only relevant in scenarios where the Spring classes reside in a 'common' ClassLoader (for example, the system ClassLoader) whose lifecycle is not coupled to the application. In such a scenario, CachedIntrospectionResults would by default not cache any of the application's classes, since they would create a leak in the common ClassLoader. <p>Any {@code acceptClassLoader} call at application startup should be paired with a {@link #clearClassLoader} call at application shutdown. @param classLoader the ClassLoader to accept
java
spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
118
[ "classLoader" ]
void
true
2
6.24
spring-projects/spring-framework
59,386
javadoc
false
exceptionStr
fbstring exceptionStr(std::exception_ptr const& ep) { if (auto ex = exception_ptr_get_object<std::exception>(ep)) { return exceptionStr(*ex); } return exception_string_type(exception_ptr_get_type(ep)); }
Debug string for an exception: include type and what(), if defined.
cpp
folly/ExceptionString.cpp
44
[]
true
2
6.8
facebook/folly
30,157
doxygen
false
benchmark_cpu
def benchmark_cpu( self: Self, _callable: Callable[[], Any], warmup: int = 20, rep: int = 100 ) -> float: """Benchmark the CPU callable, `_callable`, and return the median runtime, in milliseconds. Arguments: - _callable: The CPU callable to benchmark. Keyword Arguments: - warmup: Optionally, the duration, in milliseconds, to run `_callable` before benchmarking starts. - rep: Optionally, the duration, in milliseconds, to run `_callable` during benchmarking. Returns: - The median runtime of `_callable`, in milliseconds. """ def run_for(ms: int) -> list[float]: timings = [] run_start_t = time.perf_counter() while True: start_t = time.perf_counter() _callable() end_t = time.perf_counter() timings.append((end_t - start_t) * MILLISECONDS_PER_SECOND) if ((end_t - run_start_t) * MILLISECONDS_PER_SECOND) > ms: break return timings run_for(warmup) return median(run_for(rep))
Benchmark the CPU callable, `_callable`, and return the median runtime, in milliseconds. Arguments: - _callable: The CPU callable to benchmark. Keyword Arguments: - warmup: Optionally, the duration, in milliseconds, to run `_callable` before benchmarking starts. - rep: Optionally, the duration, in milliseconds, to run `_callable` during benchmarking. Returns: - The median runtime of `_callable`, in milliseconds.
python
torch/_inductor/runtime/benchmarking.py
210
[ "self", "_callable", "warmup", "rep" ]
float
true
3
7.76
pytorch/pytorch
96,034
google
false
_python_apply_general
def _python_apply_general( self, f: Callable, data: DataFrame | Series, not_indexed_same: bool | None = None, is_transform: bool = False, is_agg: bool = False, ) -> NDFrameT: """ Apply function f in python space Parameters ---------- f : callable Function to apply data : Series or DataFrame Data to apply f to not_indexed_same: bool, optional When specified, overrides the value of not_indexed_same. Apply behaves differently when the result index is equal to the input index, but this can be coincidental leading to value-dependent behavior. is_transform : bool, default False Indicator for whether the function is actually a transform and should not have group keys prepended. is_agg : bool, default False Indicator for whether the function is an aggregation. When the result is empty, we don't want to warn for this case. See _GroupBy._python_agg_general. Returns ------- Series or DataFrame data after applying f """ values, mutated = self._grouper.apply_groupwise(f, data) if not_indexed_same is None: not_indexed_same = mutated return self._wrap_applied_output( data, values, not_indexed_same, is_transform, )
Apply function f in python space Parameters ---------- f : callable Function to apply data : Series or DataFrame Data to apply f to not_indexed_same: bool, optional When specified, overrides the value of not_indexed_same. Apply behaves differently when the result index is equal to the input index, but this can be coincidental leading to value-dependent behavior. is_transform : bool, default False Indicator for whether the function is actually a transform and should not have group keys prepended. is_agg : bool, default False Indicator for whether the function is an aggregation. When the result is empty, we don't want to warn for this case. See _GroupBy._python_agg_general. Returns ------- Series or DataFrame data after applying f
python
pandas/core/groupby/groupby.py
1,673
[ "self", "f", "data", "not_indexed_same", "is_transform", "is_agg" ]
NDFrameT
true
2
6.72
pandas-dev/pandas
47,362
numpy
false
escapeHtml4
public static final String escapeHtml4(final String input) { return ESCAPE_HTML4.translate(input); }
Escapes the characters in a {@link String} using HTML entities. <p> For example: </p> <p>{@code "bread" &amp; "butter"}</p> becomes: <p> {@code &amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;}. </p> <p>Supports all known HTML 4.0 entities, including funky accents. Note that the commonly used apostrophe escape character (&amp;apos;) is not a legal entity and so is not supported).</p> @param input the {@link String} to escape, may be null @return a new escaped {@link String}, {@code null} if null string input @see <a href="https://web.archive.org/web/20060225074150/https://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a> @see <a href="https://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a> @see <a href="https://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a> @see <a href="https://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a> @see <a href="https://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a> @since 3.0
java
src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
499
[ "input" ]
String
true
1
6.48
apache/commons-lang
2,896
javadoc
false
do_teardown_request
def do_teardown_request( self, ctx: AppContext, exc: BaseException | None = None ) -> None: """Called after the request is dispatched and the response is finalized, right before the request context is popped. Called by :meth:`.AppContext.pop`. This calls all functions decorated with :meth:`teardown_request`, and :meth:`Blueprint.teardown_request` if a blueprint handled the request. Finally, the :data:`request_tearing_down` signal is sent. :param exc: An unhandled exception raised while dispatching the request. Passed to each teardown function. .. versionchanged:: 0.9 Added the ``exc`` argument. """ for name in chain(ctx.request.blueprints, (None,)): if name in self.teardown_request_funcs: for func in reversed(self.teardown_request_funcs[name]): self.ensure_sync(func)(exc) request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
Called after the request is dispatched and the response is finalized, right before the request context is popped. Called by :meth:`.AppContext.pop`. This calls all functions decorated with :meth:`teardown_request`, and :meth:`Blueprint.teardown_request` if a blueprint handled the request. Finally, the :data:`request_tearing_down` signal is sent. :param exc: An unhandled exception raised while dispatching the request. Passed to each teardown function. .. versionchanged:: 0.9 Added the ``exc`` argument.
python
src/flask/app.py
1,408
[ "self", "ctx", "exc" ]
None
true
4
6.4
pallets/flask
70,946
sphinx
false
visitClassExpression
function visitClassExpression(node: ClassExpression): Expression { let modifiers = visitNodes(node.modifiers, modifierElidingVisitor, isModifierLike); if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { modifiers = injectClassTypeMetadata(modifiers, node); } return factory.updateClassExpression( node, modifiers, node.name, /*typeParameters*/ undefined, visitNodes(node.heritageClauses, visitor, isHeritageClause), transformClassMembers(node), ); }
Branching visitor, visits a TypeScript syntax node. @param node The node to visit.
typescript
src/compiler/transformers/ts.ts
1,027
[ "node" ]
true
2
6.88
microsoft/TypeScript
107,154
jsdoc
false
peek
@ParametricNullness public final T peek() { if (!hasNext()) { throw new NoSuchElementException(); } // Safe because hasNext() ensures that tryToComputeNext() has put a T into `next`. return uncheckedCastNullableTToT(next); }
Returns the next element in the iteration without advancing the iteration, according to the contract of {@link PeekingIterator#peek()}. <p>Implementations of {@code AbstractIterator} that wish to expose this functionality should implement {@code PeekingIterator}.
java
android/guava/src/com/google/common/collect/AbstractIterator.java
170
[]
T
true
2
6.24
google/guava
51,352
javadoc
false
visitVariableDeclaration
function visitVariableDeclaration(node: VariableDeclaration) { const updated = factory.updateVariableDeclaration( node, Debug.checkDefined(visitNode(node.name, visitor, isBindingName)), /*exclamationToken*/ undefined, /*type*/ undefined, visitNode(node.initializer, visitor, isExpression), ); if (node.type) { setTypeNode(updated.name, node.type); } return updated; }
Determines whether to emit an accessor declaration. We should not emit the declaration if it does not have a body and is abstract. @param node The declaration node.
typescript
src/compiler/transformers/ts.ts
1,673
[ "node" ]
false
2
6.08
microsoft/TypeScript
107,154
jsdoc
false
inclusiveBetween
@SuppressWarnings("boxing") public static void inclusiveBetween(final long start, final long end, final long value) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
Validate that the specified primitive value falls between the two inclusive values specified; otherwise, throws an exception. <pre>Validate.inclusiveBetween(0, 2, 1);</pre> @param start the inclusive start value. @param end the inclusive end value. @param value the value to validate. @throws IllegalArgumentException if the value falls outside the boundaries (inclusive). @since 3.3
java
src/main/java/org/apache/commons/lang3/Validate.java
310
[ "start", "end", "value" ]
void
true
3
6.4
apache/commons-lang
2,896
javadoc
false
toString
@Override public String toString() { if (iToString == null) { final StringBuilder buf = new StringBuilder(4); if (isNegated()) { buf.append('^'); } buf.append(start); if (start != end) { buf.append('-'); buf.append(end); } iToString = buf.toString(); } return iToString; }
Gets a string representation of the character range. @return string representation of this range.
java
src/main/java/org/apache/commons/lang3/CharRange.java
351
[]
String
true
4
7.76
apache/commons-lang
2,896
javadoc
false
descendingEntryIterator
@Override Iterator<Entry<Cut<C>, Range<C>>> descendingEntryIterator() { /* * firstComplementRangeUpperBound is the upper bound of the last complement range with lower * bound inside complementLowerBoundWindow. * * positiveItr starts at the first positive range with upper bound less than * firstComplementRangeUpperBound. (Positive range upper bounds correspond to complement range * lower bounds.) */ Cut<C> startingPoint = complementLowerBoundWindow.hasUpperBound() ? complementLowerBoundWindow.upperEndpoint() : Cut.aboveAll(); boolean inclusive = complementLowerBoundWindow.hasUpperBound() && complementLowerBoundWindow.upperBoundType() == BoundType.CLOSED; PeekingIterator<Range<C>> positiveItr = peekingIterator( positiveRangesByUpperBound .headMap(startingPoint, inclusive) .descendingMap() .values() .iterator()); Cut<C> cut; if (positiveItr.hasNext()) { cut = (positiveItr.peek().upperBound == Cut.<C>aboveAll()) ? positiveItr.next().lowerBound : positiveRangesByLowerBound.higherKey(positiveItr.peek().upperBound); } else if (!complementLowerBoundWindow.contains(Cut.belowAll()) || positiveRangesByLowerBound.containsKey(Cut.belowAll())) { return emptyIterator(); } else { cut = positiveRangesByLowerBound.higherKey(Cut.belowAll()); } Cut<C> firstComplementRangeUpperBound = firstNonNull(cut, Cut.aboveAll()); return new AbstractIterator<Entry<Cut<C>, Range<C>>>() { Cut<C> nextComplementRangeUpperBound = firstComplementRangeUpperBound; @Override protected @Nullable Entry<Cut<C>, Range<C>> computeNext() { if (nextComplementRangeUpperBound == Cut.<C>belowAll()) { return endOfData(); } else if (positiveItr.hasNext()) { Range<C> positiveRange = positiveItr.next(); Range<C> negativeRange = Range.create(positiveRange.upperBound, nextComplementRangeUpperBound); nextComplementRangeUpperBound = positiveRange.lowerBound; if (complementLowerBoundWindow.lowerBound.isLessThan(negativeRange.lowerBound)) { return immutableEntry(negativeRange.lowerBound, negativeRange); } } else if (complementLowerBoundWindow.lowerBound.isLessThan(Cut.belowAll())) { Range<C> negativeRange = Range.create(Cut.belowAll(), nextComplementRangeUpperBound); nextComplementRangeUpperBound = Cut.belowAll(); return immutableEntry(Cut.belowAll(), negativeRange); } return endOfData(); } }; }
complementLowerBoundWindow represents the headMap/subMap/tailMap view of the entire "complement ranges by lower bound" map; it's a constraint on the *keys*, and does not affect the values.
java
android/guava/src/com/google/common/collect/TreeRangeSet.java
561
[]
true
11
6.16
google/guava
51,352
javadoc
false
exception
public ApiException exception(String message) { if (message == null) { // If no error message was specified, return an exception with the default error message. return exception; } // Return an exception with the given error message. return builder.apply(message); }
Create an instance of the ApiException that contains the given error message. @param message The message string to set. @return The exception.
java
clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
462
[ "message" ]
ApiException
true
2
8.24
apache/kafka
31,560
javadoc
false
trySetAccessible
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception public final boolean trySetAccessible() { // We can't call accessibleObject.trySetAccessible since that was added in Java 9 and this code // should work on Java 8. So we emulate it this way. try { accessibleObject.setAccessible(true); return true; } catch (Exception e) { // sneaky checked exception return false; } }
See {@link java.lang.reflect.AccessibleObject#trySetAccessible()}.
java
android/guava/src/com/google/common/reflect/Invokable.java
116
[]
true
2
6.24
google/guava
51,352
javadoc
false
sum
def sum(self, numeric_only: bool = False, **kwargs): """ Calculate the rolling weighted window sum. Parameters ---------- numeric_only : bool, default False Include only float, int, boolean columns. **kwargs Keyword arguments to configure the ``SciPy`` weighted window type. Returns ------- Series or DataFrame Return type is the same as the original object with ``np.float64`` dtype. See Also -------- Series.rolling : Calling rolling with Series data. DataFrame.rolling : Calling rolling with DataFrames. Series.sum : Aggregating sum for Series. DataFrame.sum : Aggregating sum for DataFrame. Examples -------- >>> ser = pd.Series([0, 1, 5, 2, 8]) To get an instance of :class:`~pandas.core.window.rolling.Window` we need to pass the parameter `win_type`. >>> type(ser.rolling(2, win_type="gaussian")) <class 'pandas.api.typing.Window'> In order to use the `SciPy` Gaussian window we need to provide the parameters `M` and `std`. The parameter `M` corresponds to 2 in our example. We pass the second parameter `std` as a parameter of the following method (`sum` in this case): >>> ser.rolling(2, win_type="gaussian").sum(std=3) 0 NaN 1 0.986207 2 5.917243 3 6.903450 4 9.862071 dtype: float64 """ window_func = window_aggregations.roll_weighted_sum # error: Argument 1 to "_apply" of "Window" has incompatible type # "Callable[[ndarray, ndarray, int], ndarray]"; expected # "Callable[[ndarray, int, int], ndarray]" return self._apply( window_func, # type: ignore[arg-type] name="sum", numeric_only=numeric_only, **kwargs, )
Calculate the rolling weighted window sum. Parameters ---------- numeric_only : bool, default False Include only float, int, boolean columns. **kwargs Keyword arguments to configure the ``SciPy`` weighted window type. Returns ------- Series or DataFrame Return type is the same as the original object with ``np.float64`` dtype. See Also -------- Series.rolling : Calling rolling with Series data. DataFrame.rolling : Calling rolling with DataFrames. Series.sum : Aggregating sum for Series. DataFrame.sum : Aggregating sum for DataFrame. Examples -------- >>> ser = pd.Series([0, 1, 5, 2, 8]) To get an instance of :class:`~pandas.core.window.rolling.Window` we need to pass the parameter `win_type`. >>> type(ser.rolling(2, win_type="gaussian")) <class 'pandas.api.typing.Window'> In order to use the `SciPy` Gaussian window we need to provide the parameters `M` and `std`. The parameter `M` corresponds to 2 in our example. We pass the second parameter `std` as a parameter of the following method (`sum` in this case): >>> ser.rolling(2, win_type="gaussian").sum(std=3) 0 NaN 1 0.986207 2 5.917243 3 6.903450 4 9.862071 dtype: float64
python
pandas/core/window/rolling.py
1,299
[ "self", "numeric_only" ]
true
1
6.96
pandas-dev/pandas
47,362
numpy
false
formatUTC
public static String formatUTC(final Date date, final String pattern, final Locale locale) { return format(date, pattern, UTC_TIME_ZONE, locale); }
Formats a date/time into a specific pattern using the UTC time zone. @param date the date to format, not null. @param pattern the pattern to use to format the date, not null. @param locale the locale to use, may be {@code null}. @return the formatted date.
java
src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java
375
[ "date", "pattern", "locale" ]
String
true
1
6.96
apache/commons-lang
2,896
javadoc
false
_graph_is_connected
def _graph_is_connected(graph): """Return whether the graph is connected (True) or Not (False). Parameters ---------- graph : {array-like, sparse matrix} of shape (n_samples, n_samples) Adjacency matrix of the graph, non-zero weight means an edge between the nodes. Returns ------- is_connected : bool True means the graph is fully connected and False means not. """ if sparse.issparse(graph): # Before Scipy 1.11.3, `connected_components` only supports 32-bit indices. # PR: https://github.com/scipy/scipy/pull/18913 # First integration in 1.11.3: https://github.com/scipy/scipy/pull/19279 # TODO(jjerphan): Once SciPy 1.11.3 is the minimum supported version, use # `accept_large_sparse=True`. accept_large_sparse = sp_version >= parse_version("1.11.3") graph = check_array( graph, accept_sparse=True, accept_large_sparse=accept_large_sparse ) # sparse graph, find all the connected components n_connected_components, _ = connected_components(graph) return n_connected_components == 1 else: # dense graph, find all connected components start from node 0 return _graph_connected_component(graph, 0).sum() == graph.shape[0]
Return whether the graph is connected (True) or Not (False). Parameters ---------- graph : {array-like, sparse matrix} of shape (n_samples, n_samples) Adjacency matrix of the graph, non-zero weight means an edge between the nodes. Returns ------- is_connected : bool True means the graph is fully connected and False means not.
python
sklearn/manifold/_spectral_embedding.py
72
[ "graph" ]
false
3
6.24
scikit-learn/scikit-learn
64,340
numpy
false
resolveInstantiationDescriptor
public InstantiationDescriptor resolveInstantiationDescriptor() { Executable executable = resolveConstructorOrFactoryMethod(); if (executable instanceof Method method && !Modifier.isStatic(method.getModifiers())) { String factoryBeanName = getMergedBeanDefinition().getFactoryBeanName(); if (factoryBeanName != null && this.beanFactory.containsBean(factoryBeanName)) { return new InstantiationDescriptor(executable, this.beanFactory.getMergedBeanDefinition(factoryBeanName).getResolvableType().toClass()); } } return new InstantiationDescriptor(executable, executable.getDeclaringClass()); }
Resolve the {@linkplain InstantiationDescriptor descriptor} to use to instantiate this bean. It defines the {@link java.lang.reflect.Constructor} or {@link java.lang.reflect.Method} to use as well as additional metadata. @since 6.1.7
java
spring-beans/src/main/java/org/springframework/beans/factory/support/RegisteredBean.java
226
[]
InstantiationDescriptor
true
5
6.24
spring-projects/spring-framework
59,386
javadoc
false
getProperties
protected PropertiesHolder getProperties(String filename) { PropertiesHolder propHolder = this.cachedProperties.get(filename); long originalTimestamp = -2; if (propHolder != null) { originalTimestamp = propHolder.getRefreshTimestamp(); if (originalTimestamp == -1 || originalTimestamp > System.currentTimeMillis() - getCacheMillis()) { // Up to date return propHolder; } } else { propHolder = new PropertiesHolder(); PropertiesHolder existingHolder = this.cachedProperties.putIfAbsent(filename, propHolder); if (existingHolder != null) { propHolder = existingHolder; } } // At this point, we need to refresh... if (this.concurrentRefresh && propHolder.getRefreshTimestamp() >= 0) { // A populated but stale holder -> could keep using it. if (!propHolder.refreshLock.tryLock()) { // Getting refreshed by another thread already -> // let's return the existing properties for the time being. return propHolder; } } else { propHolder.refreshLock.lock(); } try { PropertiesHolder existingHolder = this.cachedProperties.get(filename); if (existingHolder != null && existingHolder.getRefreshTimestamp() > originalTimestamp) { return existingHolder; } return refreshProperties(filename, propHolder); } finally { propHolder.refreshLock.unlock(); } }
Get a PropertiesHolder for the given filename, either from the cache or freshly loaded. @param filename the bundle filename (basename + Locale) @return the current PropertiesHolder for the bundle
java
spring-context/src/main/java/org/springframework/context/support/ReloadableResourceBundleMessageSource.java
407
[ "filename" ]
PropertiesHolder
true
10
7.92
spring-projects/spring-framework
59,386
javadoc
false
afterPropertiesSet
@Override public void afterPropertiesSet() { Assert.notNull(this.jobClass, "Property 'jobClass' is required"); if (this.name == null) { this.name = this.beanName; } if (this.group == null) { this.group = Scheduler.DEFAULT_GROUP; } if (this.applicationContextJobDataKey != null) { if (this.applicationContext == null) { throw new IllegalStateException( "JobDetailBean needs to be set up in an ApplicationContext " + "to be able to handle an 'applicationContextJobDataKey'"); } getJobDataMap().put(this.applicationContextJobDataKey, this.applicationContext); } JobDetailImpl jdi = new JobDetailImpl(); jdi.setName(this.name != null ? this.name : toString()); jdi.setGroup(this.group); jdi.setJobClass(this.jobClass); jdi.setJobDataMap(this.jobDataMap); jdi.setDurability(this.durability); jdi.setRequestsRecovery(this.requestsRecovery); jdi.setDescription(this.description); this.jobDetail = jdi; }
Set the key of an ApplicationContext reference to expose in the JobDataMap, for example "applicationContext". Default is none. Only applicable when running in a Spring ApplicationContext. <p>In case of a QuartzJobBean, the reference will be applied to the Job instance as bean property. An "applicationContext" attribute will correspond to a "setApplicationContext" method in that scenario. <p>Note that BeanFactory callback interfaces like ApplicationContextAware are not automatically applied to Quartz Job instances, because Quartz itself is responsible for the lifecycle of its Jobs. <p><b>Note: When using persistent job stores where JobDetail contents will be kept in the database, do not put an ApplicationContext reference into the JobDataMap but rather into the SchedulerContext.</b> @see org.springframework.scheduling.quartz.SchedulerFactoryBean#setApplicationContextSchedulerContextKey @see org.springframework.context.ApplicationContext
java
spring-context-support/src/main/java/org/springframework/scheduling/quartz/JobDetailFactoryBean.java
181
[]
void
true
6
6.24
spring-projects/spring-framework
59,386
javadoc
false
copyStandardPrologue
function copyStandardPrologue(source: readonly Statement[], target: Statement[], statementOffset = 0, ensureUseStrict?: boolean): number { Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); let foundUseStrict = false; const numStatements = source.length; while (statementOffset < numStatements) { const statement = source[statementOffset]; if (isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { foundUseStrict = true; } target.push(statement); } else { break; } statementOffset++; } if (ensureUseStrict && !foundUseStrict) { target.push(createUseStrictPrologue()); } return statementOffset; }
Copies only the standard (string-expression) prologue-directives into the target statement-array. @param source origin statements array @param target result statements array @param statementOffset The offset at which to begin the copy. @param ensureUseStrict boolean determining whether the function need to add prologue-directives @returns Count of how many directive statements were copied.
typescript
src/compiler/factory/nodeFactory.ts
6,892
[ "source", "target", "statementOffset", "ensureUseStrict?" ]
true
7
7.44
microsoft/TypeScript
107,154
jsdoc
false
strftime
def strftime(self, date_format: str) -> npt.NDArray[np.object_]: """ Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in `python string format doc <https://docs.python.org/3/library/datetime.html #strftime-and-strptime-behavior>`__. Formats supported by the C `strftime` API but not by the python string format doc (such as `"%R"`, `"%r"`) are not officially supported and should be preferably replaced with their supported equivalents (such as `"%H:%M"`, `"%I:%M:%S %p"`). Note that `PeriodIndex` support additional directives, detailed in `Period.strftime`. Parameters ---------- date_format : str Date format string (e.g. "%%Y-%%m-%%d"). Returns ------- ndarray[object] NumPy ndarray of formatted strings. See Also -------- to_datetime : Convert the given argument to datetime. DatetimeIndex.normalize : Return DatetimeIndex with times to midnight. DatetimeIndex.round : Round the DatetimeIndex to the specified freq. DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq. Timestamp.strftime : Format a single Timestamp. Period.strftime : Format a single Period. Examples -------- >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), periods=3, freq="s") >>> rng.strftime("%B %d, %Y, %r") Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM', 'March 10, 2018, 09:00:02 AM'], dtype='str') """ result = self._format_native_types(date_format=date_format, na_rep=np.nan) if using_string_dtype(): from pandas import StringDtype return pd_array(result, dtype=StringDtype(na_value=np.nan)) # type: ignore[return-value] return result.astype(object, copy=False)
Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in `python string format doc <https://docs.python.org/3/library/datetime.html #strftime-and-strptime-behavior>`__. Formats supported by the C `strftime` API but not by the python string format doc (such as `"%R"`, `"%r"`) are not officially supported and should be preferably replaced with their supported equivalents (such as `"%H:%M"`, `"%I:%M:%S %p"`). Note that `PeriodIndex` support additional directives, detailed in `Period.strftime`. Parameters ---------- date_format : str Date format string (e.g. "%%Y-%%m-%%d"). Returns ------- ndarray[object] NumPy ndarray of formatted strings. See Also -------- to_datetime : Convert the given argument to datetime. DatetimeIndex.normalize : Return DatetimeIndex with times to midnight. DatetimeIndex.round : Round the DatetimeIndex to the specified freq. DatetimeIndex.floor : Floor the DatetimeIndex to the specified freq. Timestamp.strftime : Format a single Timestamp. Period.strftime : Format a single Period. Examples -------- >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), periods=3, freq="s") >>> rng.strftime("%B %d, %Y, %r") Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM', 'March 10, 2018, 09:00:02 AM'], dtype='str')
python
pandas/core/arrays/datetimelike.py
1,780
[ "self", "date_format" ]
npt.NDArray[np.object_]
true
2
8.16
pandas-dev/pandas
47,362
numpy
false
map
public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException { checkArgument(size >= 0, "size (%s) may not be negative", size); return mapInternal(file, mode, size); }
Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link MapMode}. <p>Files are mapped from offset 0 to {@code size}. <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created with the requested {@code size}. Thus this method is useful for creating memory mapped files which do not yet exist. <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. @param file the file to map @param mode the mode to use when mapping {@code file} @return a buffer reflecting {@code file} @throws IOException if an I/O error occurs @see FileChannel#map(MapMode, long, long) @since 2.0
java
android/guava/src/com/google/common/io/Files.java
690
[ "file", "mode", "size" ]
MappedByteBuffer
true
1
6.8
google/guava
51,352
javadoc
false
toBooleanObject
public static Boolean toBooleanObject(final Integer value, final Integer trueValue, final Integer falseValue, final Integer nullValue) { if (value == null) { if (trueValue == null) { return Boolean.TRUE; } if (falseValue == null) { return Boolean.FALSE; } if (nullValue == null) { return null; } } else if (value.equals(trueValue)) { return Boolean.TRUE; } else if (value.equals(falseValue)) { return Boolean.FALSE; } else if (value.equals(nullValue)) { return null; } throw new IllegalArgumentException("The Integer did not match any specified value"); }
Converts an Integer to a Boolean specifying the conversion values. <p>NOTE: This method may return {@code null} and may throw a {@link NullPointerException} if unboxed to a {@code boolean}.</p> <p>The checks are done first for the {@code trueValue}, then for the {@code falseValue} and finally for the {@code nullValue}.</p> * <pre> BooleanUtils.toBooleanObject(Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(2), Integer.valueOf(3)) = Boolean.TRUE BooleanUtils.toBooleanObject(Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(3)) = Boolean.TRUE BooleanUtils.toBooleanObject(Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)) = Boolean.TRUE BooleanUtils.toBooleanObject(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)) = Boolean.FALSE BooleanUtils.toBooleanObject(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(2)) = Boolean.FALSE BooleanUtils.toBooleanObject(Integer.valueOf(3), Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)) = null </pre> @param value the Integer to convert @param trueValue the value to match for {@code true}, may be {@code null} @param falseValue the value to match for {@code false}, may be {@code null} @param nullValue the value to match for {@code null}, may be {@code null} @return Boolean.TRUE, Boolean.FALSE, or {@code null} @throws IllegalArgumentException if no match
java
src/main/java/org/apache/commons/lang3/BooleanUtils.java
676
[ "value", "trueValue", "falseValue", "nullValue" ]
Boolean
true
8
7.28
apache/commons-lang
2,896
javadoc
false
_generate_trimmed_row
def _generate_trimmed_row(self, max_cols: int) -> list: """ When a render has too many rows we generate a trimming row containing "..." Parameters ---------- max_cols : int Number of permissible columns Returns ------- list of elements """ index_headers = [ _element( "th", ( f"{self.css['row_heading']} {self.css['level']}{c} " f"{self.css['row_trim']}" ), "...", not self.hide_index_[c], attributes="", ) for c in range(self.data.index.nlevels) ] data: list = [] visible_col_count: int = 0 for c, _ in enumerate(self.columns): data_element_visible = c not in self.hidden_columns if data_element_visible: visible_col_count += 1 if self._check_trim( visible_col_count, max_cols, data, "td", f"{self.css['data']} {self.css['row_trim']} {self.css['col_trim']}", ): break data.append( _element( "td", f"{self.css['data']} {self.css['col']}{c} {self.css['row_trim']}", "...", data_element_visible, attributes="", ) ) return index_headers + data
When a render has too many rows we generate a trimming row containing "..." Parameters ---------- max_cols : int Number of permissible columns Returns ------- list of elements
python
pandas/io/formats/style_render.py
711
[ "self", "max_cols" ]
list
true
4
6.4
pandas-dev/pandas
47,362
numpy
false
instantiateClass
@SuppressWarnings("unchecked") public static <T> T instantiateClass(Class<?> clazz, Class<T> assignableTo) throws BeanInstantiationException { Assert.isAssignable(assignableTo, clazz); return (T) instantiateClass(clazz); }
Instantiate a class using its no-arg constructor and return the new instance as the specified assignable type. <p>Useful in cases where the type of the class to instantiate (clazz) is not available, but the type desired (assignableTo) is known. <p>Note that this method tries to set the constructor accessible if given a non-accessible (that is, non-public) constructor. @param clazz class to instantiate @param assignableTo type that clazz must be assignableTo @return the new instance @throws BeanInstantiationException if the bean cannot be instantiated @see Constructor#newInstance
java
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
165
[ "clazz", "assignableTo" ]
T
true
1
6.72
spring-projects/spring-framework
59,386
javadoc
false
innerCaptures
private Map<String, Object> innerCaptures( String text, Function<GrokCaptureConfig, Function<Consumer<Object>, GrokCaptureExtracter>> getExtracter ) { byte[] utf8Bytes = text.getBytes(StandardCharsets.UTF_8); GrokCaptureExtracter.MapExtracter extracter = new GrokCaptureExtracter.MapExtracter(captureConfig, getExtracter); if (match(utf8Bytes, 0, utf8Bytes.length, extracter)) { return extracter.result(); } return null; }
Matches and returns the ranges of any named captures. @param text the text to match and extract values from. @return a map containing field names and their respective ranges that matched or null if the pattern didn't match
java
libs/grok/src/main/java/org/elasticsearch/grok/Grok.java
212
[ "text", "getExtracter" ]
true
2
8.24
elastic/elasticsearch
75,680
javadoc
false
compose
public static <A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) { return new FunctionComposition<>(g, f); }
Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}. <p><b>JRE users and Android users who opt in to library desugaring:</b> use {@code g.compose(f)} or (probably clearer) {@code f.andThen(g)} instead. Note that it is not serializable. @param g the second function to apply @param f the first function to apply @return the composition of {@code f} and {@code g} @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a>
java
android/guava/src/com/google/common/base/Functions.java
249
[ "g", "f" ]
true
1
6.64
google/guava
51,352
javadoc
false
linesIterator
private Iterator<String> linesIterator() { return new AbstractIterator<String>() { final Iterator<String> lines = LINE_SPLITTER.split(seq).iterator(); @Override protected @Nullable String computeNext() { if (lines.hasNext()) { String next = lines.next(); // skip last line if it's empty if (lines.hasNext() || !next.isEmpty()) { return next; } } return endOfData(); } }; }
Returns an iterator over the lines in the string. If the string ends in a newline, a final empty string is not included, to match the behavior of BufferedReader/LineReader.readLine().
java
android/guava/src/com/google/common/io/CharSource.java
581
[]
true
4
6.88
google/guava
51,352
javadoc
false
generateNewInstanceCodeForMethod
private CodeBlock generateNewInstanceCodeForMethod(@Nullable String factoryBeanName, Class<?> targetClass, String factoryMethodName, CodeBlock args) { if (factoryBeanName == null) { return CodeBlock.of("$T.$L($L)", targetClass, factoryMethodName, args); } return CodeBlock.of("$L.getBeanFactory().getBean(\"$L\", $T.class).$L($L)", REGISTERED_BEAN_PARAMETER_NAME, factoryBeanName, targetClass, factoryMethodName, args); }
Generate the instance supplier code. @param registeredBean the bean to handle @param instantiationDescriptor the executable to use to create the bean @return the generated code @since 6.1.7
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java
354
[ "factoryBeanName", "targetClass", "factoryMethodName", "args" ]
CodeBlock
true
2
7.44
spring-projects/spring-framework
59,386
javadoc
false
addSub
private Fraction addSub(final Fraction fraction, final boolean isAdd) { Objects.requireNonNull(fraction, "fraction"); // zero is identity for addition. if (numerator == 0) { return isAdd ? fraction : fraction.negate(); } if (fraction.numerator == 0) { return this; } // if denominators are randomly distributed, d1 will be 1 about 61% // of the time. final int d1 = greatestCommonDivisor(denominator, fraction.denominator); if (d1 == 1) { // result is ((u*v' +/- u'v) / u'v') final int uvp = mulAndCheck(numerator, fraction.denominator); final int upv = mulAndCheck(fraction.numerator, denominator); return new Fraction(isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv), mulPosAndCheck(denominator, fraction.denominator)); } // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 // exercise 7. we're going to use a BigInteger. // t = u(v'/d1) +/- v(u'/d1) final BigInteger uvp = BigInteger.valueOf(numerator).multiply(BigInteger.valueOf(fraction.denominator / d1)); final BigInteger upv = BigInteger.valueOf(fraction.numerator).multiply(BigInteger.valueOf(denominator / d1)); final BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); // but d2 doesn't need extra precision because // d2 = gcd(t,d1) = gcd(t mod d1, d1) final int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); final int d2 = tmodd1 == 0 ? d1 : greatestCommonDivisor(tmodd1, d1); // result is (t/d2) / (u'/d1)(v'/d2) final BigInteger w = t.divide(BigInteger.valueOf(d2)); if (w.bitLength() > 31) { throw new ArithmeticException("overflow: numerator too large after multiply"); } return new Fraction(w.intValue(), mulPosAndCheck(denominator / d1, fraction.denominator / d2)); }
Implements add and subtract using the algorithm described in <a href="https://www-cs-faculty.stanford.edu/~knuth/taocp.html"> The Art of Computer Programming (TAOCP)</a> 4.5.1 by Donald Knuth. @param fraction the fraction to subtract, must not be {@code null} @param isAdd true to add, false to subtract @return a {@link Fraction} instance with the resulting values @throws IllegalArgumentException if the fraction is {@code null} @throws ArithmeticException if the resulting numerator or denominator cannot be represented in an {@code int}.
java
src/main/java/org/apache/commons/lang3/math/Fraction.java
538
[ "fraction", "isAdd" ]
Fraction
true
9
7.6
apache/commons-lang
2,896
javadoc
false
insert
def insert(self: Self, key: Key, value: Value) -> bool: """ Insert a value into the cache. Args: key (Key): The key to insert. value (Value): The value to associate with the key. Returns: bool: True if the value was inserted, False if the key already exists. Raises: CacheError: If the value is not pickle-able. Side Effects: Creates the cache directory if it does not exist. """ fpath = self._fpath_from_key(key) flock = self._flock_from_fpath(fpath) fpath.parent.mkdir(parents=True, exist_ok=True) try: # "x" mode is exclusive creation, meaning the file will be created # iff the file does not already exist (atomic w/o overwrite); use # flock for added atomicity guarantee and to prevent partial writes with flock as _, open(fpath, "xb") as fp: fp.write(self.version_prefix) pickle.dump(value, fp) except pickle.PicklingError as err: raise CacheError( f"Failed to insert key {key!r} with value {value!r}, value is not pickle-able." ) from err except FileExistsError: return False return True
Insert a value into the cache. Args: key (Key): The key to insert. value (Value): The value to associate with the key. Returns: bool: True if the value was inserted, False if the key already exists. Raises: CacheError: If the value is not pickle-able. Side Effects: Creates the cache directory if it does not exist.
python
torch/_inductor/cache.py
365
[ "self", "key", "value" ]
bool
true
1
7.04
pytorch/pytorch
96,034
google
false
create
@SuppressWarnings("unchecked") public static <E extends @Nullable Object> TreeMultiset<E> create( @Nullable Comparator<? super E> comparator) { return (comparator == null) ? new TreeMultiset<E>((Comparator) Ordering.natural()) : new TreeMultiset<E>(comparator); }
Creates a new, empty multiset, sorted according to the specified comparator. All elements inserted into the multiset must be <i>mutually comparable</i> by the specified comparator: {@code comparator.compare(e1, e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the user attempts to add an element to the multiset that violates this constraint, the {@code add(Object)} call will throw a {@code ClassCastException}. @param comparator the comparator that will be used to sort this multiset. A null value indicates that the elements' <i>natural ordering</i> should be used.
java
android/guava/src/com/google/common/collect/TreeMultiset.java
91
[ "comparator" ]
true
2
6.56
google/guava
51,352
javadoc
false
CommitFlamegraph
function CommitFlamegraph({chartData, commitTree, height, width}: Props) { const [hoveredFiberData, setHoveredFiberData] = useState<TooltipFiberData | null>(null); const {lineHeight} = useContext(SettingsContext); const {selectFiber, selectedFiberID} = useContext(ProfilerContext); const {highlightHostInstance, clearHighlightHostInstance} = useHighlightHostInstance(); const selectedChartNodeIndex = useMemo<number>(() => { if (selectedFiberID === null) { return 0; } // The selected node might not be in the tree for this commit, // so it's important that we have a fallback plan. const depth = chartData.idToDepthMap.get(selectedFiberID); return depth !== undefined ? depth - 1 : 0; }, [chartData, selectedFiberID]); const selectedChartNode = useMemo(() => { if (selectedFiberID !== null) { return ( chartData.rows[selectedChartNodeIndex].find( chartNode => chartNode.id === selectedFiberID, ) || null ); } return null; }, [chartData, selectedFiberID, selectedChartNodeIndex]); 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, selectedChartNode !== null ? selectedChartNode.treeBaseDuration : chartData.baseDuration, 0, width, ), selectedChartNode, selectedChartNodeIndex, selectFiber, width, }), [ chartData, handleElementMouseEnter, handleElementMouseLeave, selectedChartNode, selectedChartNodeIndex, 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={InnerElementType} itemCount={chartData.depth} itemData={itemData} itemSize={lineHeight} width={width}> {CommitFlamegraphListItem} </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/CommitFlamegraph.js
99
[]
false
7
6.32
facebook/react
241,750
jsdoc
false
asInterfaceInstance
public static <T> T asInterfaceInstance(final Class<T> interfaceClass, final Method method) { return MethodHandleProxies.asInterfaceInstance(Objects.requireNonNull(interfaceClass, "interfaceClass"), unreflectUnchecked(method)); }
Produces an instance of the given single-method interface which redirects its calls to the given method. <p> For the definition of "single-method", see {@link MethodHandleProxies#asInterfaceInstance(Class, MethodHandle)}. </p> @param <T> The interface type. @param interfaceClass a class object representing {@code T}. @param method the method to invoke. @return a correctly-typed wrapper for the given target. @see MethodHandleProxies#asInterfaceInstance(Class, MethodHandle)
java
src/main/java/org/apache/commons/lang3/function/MethodInvokers.java
209
[ "interfaceClass", "method" ]
T
true
1
6.16
apache/commons-lang
2,896
javadoc
false
send_message
def send_message( self, queue_url: str, message_body: str, delay_seconds: int = 0, message_attributes: dict | None = None, message_group_id: str | None = None, message_deduplication_id: str | None = None, ) -> dict: """ Send message to the queue. .. seealso:: - :external+boto3:py:meth:`SQS.Client.send_message` :param queue_url: queue url :param message_body: the contents of the message :param delay_seconds: seconds to delay the message :param message_attributes: additional attributes for the message (default: None) :param message_group_id: This applies only to FIFO (first-in-first-out) queues. (default: None) :param message_deduplication_id: This applies only to FIFO (first-in-first-out) queues. :return: dict with the information about the message sent """ params = self._build_msg_params( queue_url=queue_url, message_body=message_body, delay_seconds=delay_seconds, message_attributes=message_attributes, message_group_id=message_group_id, message_deduplication_id=message_deduplication_id, ) return self.get_conn().send_message(**params)
Send message to the queue. .. seealso:: - :external+boto3:py:meth:`SQS.Client.send_message` :param queue_url: queue url :param message_body: the contents of the message :param delay_seconds: seconds to delay the message :param message_attributes: additional attributes for the message (default: None) :param message_group_id: This applies only to FIFO (first-in-first-out) queues. (default: None) :param message_deduplication_id: This applies only to FIFO (first-in-first-out) queues. :return: dict with the information about the message sent
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/sqs.py
76
[ "self", "queue_url", "message_body", "delay_seconds", "message_attributes", "message_group_id", "message_deduplication_id" ]
dict
true
1
6.4
apache/airflow
43,597
sphinx
false
raise
public void raise(RuntimeException e) { try { if (e == null) throw new IllegalArgumentException("The exception passed to raise must not be null"); if (!result.compareAndSet(INCOMPLETE_SENTINEL, e)) throw new IllegalStateException("Invalid attempt to complete a request future which is already complete"); fireFailure(); } finally { completedLatch.countDown(); } }
Raise an exception. The request will be marked as failed, and the caller can either handle the exception or throw it. @param e corresponding exception to be passed to caller @throws IllegalStateException if the future has already been completed
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestFuture.java
141
[ "e" ]
void
true
3
6.56
apache/kafka
31,560
javadoc
false
stmt_for_task_instance
def stmt_for_task_instance( cls, ti: TaskInstance, *, descending: bool = False, ) -> Select: """ Statement for task reschedules for a given task instance. :param ti: the task instance to find task reschedules for :param descending: If True then records are returned in descending order :meta private: """ return select(cls).where(cls.ti_id == ti.id).order_by(desc(cls.id) if descending else asc(cls.id))
Statement for task reschedules for a given task instance. :param ti: the task instance to find task reschedules for :param descending: If True then records are returned in descending order :meta private:
python
airflow-core/src/airflow/models/taskreschedule.py
81
[ "cls", "ti", "descending" ]
Select
true
2
7.04
apache/airflow
43,597
sphinx
false
splitPrefix
inline size_t splitPrefix(StringPiece& in, StringPiece& prefix, MixedNewlines) { const auto kCRLF = "\r\n"; const size_t kLenCRLF = 2; auto p = in.find_first_of(kCRLF); if (p != std::string::npos) { const auto in_start = in.data(); size_t delim_len = 1; in.advance(p); // Either remove an MS-DOS CR-LF 2-byte newline, or eat 1 byte at a time. if (in.removePrefix(kCRLF)) { delim_len = kLenCRLF; } else { in.advance(delim_len); } prefix.assign(in_start, in.data()); return delim_len; } prefix.clear(); return 0; }
As above, but splits by any of the EOL terms: \r, \n, or \r\n.
cpp
folly/gen/String-inl.h
69
[]
true
4
6.88
facebook/folly
30,157
doxygen
false
shutdown
public synchronized void shutdown() { if (!shutdown) { if (ownExecutor) { // if the executor was created by this instance, it has // to be shutdown getExecutorService().shutdownNow(); } if (task != null) { task.cancel(false); } shutdown = true; } }
Initializes a shutdown. After that the object cannot be used anymore. This method can be invoked an arbitrary number of times. All invocations after the first one do not have any effect.
java
src/main/java/org/apache/commons/lang3/concurrent/TimedSemaphore.java
446
[]
void
true
4
7.2
apache/commons-lang
2,896
javadoc
false
filterOnTransactionalIdPattern
public ListTransactionsOptions filterOnTransactionalIdPattern(String pattern) { this.filteredTransactionalIdPattern = pattern; return this; }
Filter only the transactions that match with the given transactional ID pattern. If the filter is null or if the passed string is empty, then all the transactions will be returned. @param pattern the transactional ID regular expression pattern to filter by @return this object
java
clients/src/main/java/org/apache/kafka/clients/admin/ListTransactionsOptions.java
82
[ "pattern" ]
ListTransactionsOptions
true
1
6.8
apache/kafka
31,560
javadoc
false
getTypeUseAnnotation
private AnnotationMirror getTypeUseAnnotation(Element element, String type) { if (element != null) { for (AnnotationMirror annotation : element.asType().getAnnotationMirrors()) { if (type.equals(annotation.getAnnotationType().toString())) { return annotation; } } } return null; }
Resolve the {@link SourceMetadata} for the specified property. @param field the field of the property (can be {@code null}) @param getter the getter of the property (can be {@code null}) @return the {@link SourceMetadata} for the specified property
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java
269
[ "element", "type" ]
AnnotationMirror
true
3
7.76
spring-projects/spring-boot
79,428
javadoc
false
clear
@Override public void clear() { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void afterCommit() { targetCache.clear(); } }); } else { this.targetCache.clear(); } }
Return the target Cache that this Cache should delegate to.
java
spring-context-support/src/main/java/org/springframework/cache/transaction/TransactionAwareCacheDecorator.java
145
[]
void
true
2
7.04
spring-projects/spring-framework
59,386
javadoc
false
allNotNull
public static boolean allNotNull(final Object... values) { return values != null && Stream.of(values).noneMatch(Objects::isNull); }
Tests if all values in the array are not {@code nulls}. <p> If any value is {@code null} or the array is {@code null} then {@code false} is returned. If all elements in array are not {@code null} or the array is empty (contains no elements) {@code true} is returned. </p> <pre> ObjectUtils.allNotNull(*) = true ObjectUtils.allNotNull(*, *) = true ObjectUtils.allNotNull(null) = false ObjectUtils.allNotNull(null, null) = false ObjectUtils.allNotNull(null, *) = false ObjectUtils.allNotNull(*, null) = false ObjectUtils.allNotNull(*, *, null, *) = false </pre> @param values the values to test, may be {@code null} or empty. @return {@code false} if there is at least one {@code null} value in the array or the array is {@code null}, {@code true} if all values in the array are not {@code null}s or array contains no elements. @since 3.5
java
src/main/java/org/apache/commons/lang3/ObjectUtils.java
144
[]
true
2
8
apache/commons-lang
2,896
javadoc
false
enterWhen
@SuppressWarnings({ "GoodTime", // should accept a java.time.Duration "LabelledBreakTarget", // TODO(b/345814817): Maybe fix. }) public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { long timeoutNanos = toSafeNanos(time, unit); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } ReentrantLock lock = this.lock; boolean reentrant = lock.isHeldByCurrentThread(); long startTime = 0L; locked: { if (!fair) { // Check interrupt status to get behavior consistent with fair case. if (Thread.interrupted()) { throw new InterruptedException(); } if (lock.tryLock()) { break locked; } } startTime = initNanoTime(timeoutNanos); if (!lock.tryLock(time, unit)) { return false; } } boolean satisfied = false; boolean threw = true; try { satisfied = guard.isSatisfied() || awaitNanos( guard, (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos), reentrant); threw = false; return satisfied; } finally { if (!satisfied) { try { // Don't need to signal if timed out, but do if interrupted if (threw && !reentrant) { signalNextWaiter(); } } finally { lock.unlock(); } } } }
Enters this monitor when the guard is satisfied. Blocks at most the given time, including both the time to acquire the lock and the time to wait for the guard to be satisfied, and may be interrupted. @return whether the monitor was entered, which guarantees that the guard is now satisfied @throws InterruptedException if interrupted while waiting
java
android/guava/src/com/google/common/util/concurrent/Monitor.java
519
[ "guard", "time", "unit" ]
true
11
6.64
google/guava
51,352
javadoc
false
getExportNode
function getExportNode(parent: Node, node: Node): Node | undefined { const declaration = isVariableDeclaration(parent) ? parent : isBindingElement(parent) ? walkUpBindingElementsAndPatterns(parent) : undefined; if (declaration) { return (parent as VariableDeclaration | BindingElement).name !== node ? undefined : isCatchClause(declaration.parent) ? undefined : isVariableStatement(declaration.parent.parent) ? declaration.parent.parent : undefined; } else { return parent; } }
Given a local reference, we might notice that it's an import/export and recursively search for references of that. If at an import, look locally for the symbol it imports. If at an export, look for all imports of it. This doesn't handle export specifiers; that is done in `getReferencesAtExportSpecifier`. @param comingFromExport If we are doing a search for all exports, don't bother looking backwards for the imported symbol, since that's the reason we're here. @internal
typescript
src/services/importTracker.ts
722
[ "parent", "node" ]
true
8
6.4
microsoft/TypeScript
107,154
jsdoc
false
safe_sort_index
def safe_sort_index(index: Index) -> Index: """ Returns the sorted index We keep the dtypes and the name attributes. Parameters ---------- index : an Index Returns ------- Index """ if index.is_monotonic_increasing: return index try: array_sorted = safe_sort(index) except TypeError: pass else: if isinstance(array_sorted, Index): return array_sorted array_sorted = cast(np.ndarray, array_sorted) if isinstance(index, MultiIndex): index = MultiIndex.from_tuples(array_sorted, names=index.names) else: index = Index(array_sorted, name=index.name, dtype=index.dtype) return index
Returns the sorted index We keep the dtypes and the name attributes. Parameters ---------- index : an Index Returns ------- Index
python
pandas/core/indexes/api.py
151
[ "index" ]
Index
true
6
6.88
pandas-dev/pandas
47,362
numpy
false
toBoundingBox
public static Rectangle toBoundingBox(final String geohash) { // bottom left is the coordinate Point bottomLeft = toPoint(geohash); int len = Math.min(12, geohash.length()); long ghLong = longEncode(geohash, len); // shift away the level ghLong >>>= 4; // deinterleave long lon = BitUtil.deinterleave(ghLong >>> 1); long lat = BitUtil.deinterleave(ghLong); final int shift = (12 - len) * 5 + 2; if (lat < MAX_LAT_BITS) { // add 1 to lat and lon to get topRight ghLong = BitUtil.interleave((int) (lat + 1), (int) (lon + 1)) << 4 | len; final long mortonHash = BitUtil.flipFlop((ghLong >>> 4) << shift); Point topRight = new Point(decodeLongitude(mortonHash), decodeLatitude(mortonHash)); return new Rectangle(bottomLeft.getX(), topRight.getX(), topRight.getY(), bottomLeft.getY()); } else { // We cannot go north of north pole, so just using 90 degrees instead of calculating it using // add 1 to lon to get lon of topRight, we are going to use 90 for lat ghLong = BitUtil.interleave((int) lat, (int) (lon + 1)) << 4 | len; final long mortonHash = BitUtil.flipFlop((ghLong >>> 4) << shift); Point topRight = new Point(decodeLongitude(mortonHash), decodeLatitude(mortonHash)); return new Rectangle(bottomLeft.getX(), topRight.getX(), 90D, bottomLeft.getY()); } }
Computes the bounding box coordinates from a given geohash @param geohash Geohash of the defined cell @return GeoRect rectangle defining the bounding box
java
libs/geo/src/main/java/org/elasticsearch/geometry/utils/Geohash.java
106
[ "geohash" ]
Rectangle
true
2
7.28
elastic/elasticsearch
75,680
javadoc
false
fill
public static boolean[] fill(final boolean[] a, final boolean val) { if (a != null) { Arrays.fill(a, val); } return a; }
Fills and returns the given array, assigning the given {@code boolean} value to each element of the array. @param a the array to be filled (may be null). @param val the value to be stored in all elements of the array. @return the given array. @see Arrays#fill(boolean[],boolean) @since 3.18.0
java
src/main/java/org/apache/commons/lang3/ArrayFill.java
41
[ "a", "val" ]
true
2
8.08
apache/commons-lang
2,896
javadoc
false
isProcessorWithOnFailureGeoIpProcessor
@SuppressWarnings("unchecked") private static boolean isProcessorWithOnFailureGeoIpProcessor( Map<String, Object> processor, boolean downloadDatabaseOnPipelineCreation, Map<String, PipelineConfiguration> pipelineConfigById, Map<String, Boolean> pipelineHasGeoProcessorById ) { // note: this loop is unrolled rather than streaming-style because it's hot enough to show up in a flamegraph for (Object value : processor.values()) { if (value instanceof Map && hasAtLeastOneGeoipProcessor( ((Map<String, List<Map<String, Object>>>) value).get("on_failure"), downloadDatabaseOnPipelineCreation, pipelineConfigById, pipelineHasGeoProcessorById )) { return true; } } return false; }
Check if a processor config has an on_failure clause containing at least a geoip processor. @param processor Processor config. @param downloadDatabaseOnPipelineCreation Should the download_database_on_pipeline_creation of the geoip processor be true or false. @param pipelineConfigById A Map of pipeline id to PipelineConfiguration @param pipelineHasGeoProcessorById A Map of pipeline id to Boolean, indicating whether the pipeline references a geoip processor (true), does not reference a geoip processor (false), or we are currently trying to figure that out (null). @return true if a geoip processor is found in the processor list.
java
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpDownloaderTaskExecutor.java
427
[ "processor", "downloadDatabaseOnPipelineCreation", "pipelineConfigById", "pipelineHasGeoProcessorById" ]
true
3
7.76
elastic/elasticsearch
75,680
javadoc
false
joining
private <V> BiConsumer<String, V> joining(BiConsumer<String, V> pairs) { return (name, value) -> { name = this.joiner.join(ContextPairs.this.prefix, (name != null) ? name : ""); if (StringUtils.hasLength(name)) { pairs.accept(name, value); } }; }
Add pairs using the given callback. @param <V> the value type @param pairs callback provided with the item and consumer that can be called to actually add the pairs
java
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/ContextPairs.java
214
[ "pairs" ]
true
3
7.04
spring-projects/spring-boot
79,428
javadoc
false
cumprod
def cumprod(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT: """ Cumulative product for each group. Parameters ---------- numeric_only : bool, default False Include only float, int, boolean columns. *args : tuple Positional arguments to be passed to `func`. **kwargs : dict Additional/specific keyword arguments to be passed to the function, such as `numeric_only` and `skipna`. Returns ------- Series or DataFrame Cumulative product for each group. Same object type as the caller. %(see_also)s Examples -------- For SeriesGroupBy: >>> lst = ["a", "a", "b"] >>> ser = pd.Series([6, 2, 0], index=lst) >>> ser a 6 a 2 b 0 dtype: int64 >>> ser.groupby(level=0).cumprod() a 6 a 12 b 0 dtype: int64 For DataFrameGroupBy: >>> data = [[1, 8, 2], [1, 2, 5], [2, 6, 9]] >>> df = pd.DataFrame( ... data, columns=["a", "b", "c"], index=["cow", "horse", "bull"] ... ) >>> df a b c cow 1 8 2 horse 1 2 5 bull 2 6 9 >>> df.groupby("a").groups {1: ['cow', 'horse'], 2: ['bull']} >>> df.groupby("a").cumprod() b c cow 8 2 horse 16 10 bull 6 9 """ nv.validate_groupby_func("cumprod", args, kwargs, ["skipna"]) return self._cython_transform("cumprod", numeric_only, **kwargs)
Cumulative product for each group. Parameters ---------- numeric_only : bool, default False Include only float, int, boolean columns. *args : tuple Positional arguments to be passed to `func`. **kwargs : dict Additional/specific keyword arguments to be passed to the function, such as `numeric_only` and `skipna`. Returns ------- Series or DataFrame Cumulative product for each group. Same object type as the caller. %(see_also)s Examples -------- For SeriesGroupBy: >>> lst = ["a", "a", "b"] >>> ser = pd.Series([6, 2, 0], index=lst) >>> ser a 6 a 2 b 0 dtype: int64 >>> ser.groupby(level=0).cumprod() a 6 a 12 b 0 dtype: int64 For DataFrameGroupBy: >>> data = [[1, 8, 2], [1, 2, 5], [2, 6, 9]] >>> df = pd.DataFrame( ... data, columns=["a", "b", "c"], index=["cow", "horse", "bull"] ... ) >>> df a b c cow 1 8 2 horse 1 2 5 bull 2 6 9 >>> df.groupby("a").groups {1: ['cow', 'horse'], 2: ['bull']} >>> df.groupby("a").cumprod() b c cow 8 2 horse 16 10 bull 6 9
python
pandas/core/groupby/groupby.py
4,853
[ "self", "numeric_only" ]
NDFrameT
true
1
7.2
pandas-dev/pandas
47,362
numpy
false
executeProjectGenerationRequest
private ClassicHttpResponse executeProjectGenerationRequest(URI url) { return execute(new HttpGet(url), url, "generate project"); }
Request the creation of the project using the specified URL. @param url the URL @return the response
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java
169
[ "url" ]
ClassicHttpResponse
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
hashCode
@Override public int hashCode() { int result = 1; result = 31 * result + ObjectUtils.nullSafeHashCode(this.resource); result = 31 * result + ObjectUtils.nullSafeHashCode(this.location); return result; }
Return the location of the property within the source (if known). @return the location or {@code null}
java
core/spring-boot/src/main/java/org/springframework/boot/origin/TextResourceOrigin.java
87
[]
true
1
7.04
spring-projects/spring-boot
79,428
javadoc
false
run
protected ExitStatus run(String... args) throws Exception { if (args.length == 0) { throw new NoArgumentsException(); } String commandName = args[0]; String[] commandArguments = Arrays.copyOfRange(args, 1, args.length); Command command = findCommand(commandName); if (command == null) { throw new NoSuchCommandException(commandName); } beforeRun(command); try { return command.run(commandArguments); } finally { afterRun(command); } }
Parse the arguments and run a suitable command. @param args the arguments @return the outcome of the command @throws Exception if the command fails
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java
209
[]
ExitStatus
true
3
8.24
spring-projects/spring-boot
79,428
javadoc
false
isEmpty
boolean isEmpty() { try { lock.lock(); return completedFetches.isEmpty(); } finally { lock.unlock(); } }
Returns {@code true} if there are no completed fetches pending to return to the user. @return {@code true} if the buffer is empty, {@code false} otherwise
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchBuffer.java
74
[]
true
1
7.04
apache/kafka
31,560
javadoc
false
action_logging
def action_logging(f: T) -> T: """ Decorate function to execute function at the same time submitting action_logging but in CLI context. It will call action logger callbacks twice, one for pre-execution and the other one for post-execution. Action logger will be called with below keyword parameters: sub_command : name of sub-command start_datetime : start datetime instance by utc end_datetime : end datetime instance by utc full_command : full command line arguments user : current user log : airflow.models.log.Log ORM instance dag_id : dag id (optional) task_id : task_id (optional) logical_date : logical date (optional) error : exception instance if there's an exception :param f: function instance :return: wrapped function """ @functools.wraps(f) def wrapper(*args, **kwargs): """ Wrap cli functions; assume Namespace instance as first positional argument. :param args: Positional argument. It assumes to have Namespace instance at 1st positional argument :param kwargs: A passthrough keyword argument """ _check_cli_args(args) metrics = _build_metrics(f.__name__, args[0]) cli_action_loggers.on_pre_execution(**metrics) verbose = getattr(args[0], "verbose", False) root_logger = logging.getLogger() if verbose: root_logger.setLevel(logging.DEBUG) for handler in root_logger.handlers: handler.setLevel(logging.DEBUG) try: # Check and run migrations if necessary if check_db: from airflow.configuration import conf from airflow.utils.db import check_and_run_migrations, synchronize_log_template if conf.getboolean("database", "check_migrations"): check_and_run_migrations() synchronize_log_template() return f(*args, **kwargs) except Exception as e: metrics["error"] = e raise finally: metrics["end_datetime"] = timezone.utcnow() cli_action_loggers.on_post_execution(**metrics) return cast("T", wrapper)
Decorate function to execute function at the same time submitting action_logging but in CLI context. It will call action logger callbacks twice, one for pre-execution and the other one for post-execution. Action logger will be called with below keyword parameters: sub_command : name of sub-command start_datetime : start datetime instance by utc end_datetime : end datetime instance by utc full_command : full command line arguments user : current user log : airflow.models.log.Log ORM instance dag_id : dag id (optional) task_id : task_id (optional) logical_date : logical date (optional) error : exception instance if there's an exception :param f: function instance :return: wrapped function
python
airflow-core/src/airflow/utils/cli.py
64
[ "f" ]
T
true
5
7.84
apache/airflow
43,597
sphinx
false
random_state
def random_state(state: RandomState | None = None): """ Helper function for processing random_state arguments. Parameters ---------- state : int, array-like, BitGenerator, Generator, np.random.RandomState, None. If receives an int, array-like, or BitGenerator, passes to np.random.RandomState() as seed. If receives an np.random RandomState or Generator, just returns that unchanged. If receives `None`, returns np.random. If receives anything else, raises an informative ValueError. Default None. Returns ------- np.random.RandomState or np.random.Generator. If state is None, returns np.random """ if is_integer(state) or isinstance(state, (np.ndarray, np.random.BitGenerator)): return np.random.RandomState(state) elif isinstance(state, np.random.RandomState): return state elif isinstance(state, np.random.Generator): return state elif state is None: return np.random else: raise ValueError( "random_state must be an integer, array-like, a BitGenerator, Generator, " "a numpy RandomState, or None" )
Helper function for processing random_state arguments. Parameters ---------- state : int, array-like, BitGenerator, Generator, np.random.RandomState, None. If receives an int, array-like, or BitGenerator, passes to np.random.RandomState() as seed. If receives an np.random RandomState or Generator, just returns that unchanged. If receives `None`, returns np.random. If receives anything else, raises an informative ValueError. Default None. Returns ------- np.random.RandomState or np.random.Generator. If state is None, returns np.random
python
pandas/core/common.py
434
[ "state" ]
true
7
6.24
pandas-dev/pandas
47,362
numpy
false
createTrustManager
@Override public X509ExtendedTrustManager createTrustManager() { try { return KeyStoreUtil.createTrustManager(getSystemTrustStore(), TrustManagerFactory.getDefaultAlgorithm()); } catch (GeneralSecurityException e) { throw new SslConfigException("failed to initialize a TrustManager for the system keystore", e); } }
@param trustStorePassword the password for the truststore. It applies only when PKCS#11 tokens are used, is null otherwise
java
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DefaultJdkTrustConfig.java
63
[]
X509ExtendedTrustManager
true
2
6.4
elastic/elasticsearch
75,680
javadoc
false
findDeclaredMethod
public static @Nullable Method findDeclaredMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) { try { return clazz.getDeclaredMethod(methodName, paramTypes); } catch (NoSuchMethodException ex) { if (clazz.getSuperclass() != null) { return findDeclaredMethod(clazz.getSuperclass(), methodName, paramTypes); } return null; } }
Find a method with the given method name and the given parameter types, declared on the given class or one of its superclasses. Will return a public, protected, package access, or private method. <p>Checks {@code Class.getDeclaredMethod}, cascading upwards to all superclasses. @param clazz the class to check @param methodName the name of the method to find @param paramTypes the parameter types of the method to find @return the Method object, or {@code null} if not found @see Class#getDeclaredMethod
java
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
333
[ "clazz", "methodName" ]
Method
true
3
7.92
spring-projects/spring-framework
59,386
javadoc
false
collidesWithParameterName
function collidesWithParameterName({ name }: VariableDeclaration | BindingElement): boolean { if (isIdentifier(name)) { return enclosingFunctionParameterNames.has(name.escapedText); } else { for (const element of name.elements) { if (!isOmittedExpression(element) && collidesWithParameterName(element)) { return true; } } } return false; }
Visits an ArrowFunction. This function will be called when one of the following conditions are met: - The node is marked async @param node The node to visit.
typescript
src/compiler/transformers/es2017.ts
635
[ "{ name }" ]
true
5
6.72
microsoft/TypeScript
107,154
jsdoc
false
transformInitializedVariable
function transformInitializedVariable(node: InitializedVariableDeclaration): Expression { if (isBindingPattern(node.name)) { return flattenDestructuringAssignment( visitNode(node, visitor, isInitializedVariable), visitor, context, FlattenLevel.All, /*needsValue*/ false, createAllExportExpressions, ); } else { return factory.createAssignment( setTextRange( factory.createPropertyAccessExpression( factory.createIdentifier("exports"), node.name, ), /*location*/ node.name, ), node.initializer ? visitNode(node.initializer, visitor, isExpression) : factory.createVoidZero(), ); } }
Transforms an exported variable with an initializer into an expression. @param node The node to transform.
typescript
src/compiler/transformers/module/module.ts
1,926
[ "node" ]
true
4
6.72
microsoft/TypeScript
107,154
jsdoc
false
initWithPartitionOffsetsIfNeeded
private CompletableFuture<Void> initWithPartitionOffsetsIfNeeded(Set<TopicPartition> initializingPartitions) { CompletableFuture<Void> result = new CompletableFuture<>(); try { // Mark partitions that need reset, using the configured reset strategy. If no // strategy is defined, this will raise a NoOffsetForPartitionException exception. subscriptionState.resetInitializingPositions(initializingPartitions::contains); } catch (Exception e) { result.completeExceptionally(e); return result; } // For partitions awaiting reset, generate a ListOffset request to retrieve the partition // offsets according to the strategy (ex. earliest, latest), and update the positions. return resetPositionsIfNeeded(); }
If there are partitions still needing a position and a reset policy is defined, request reset using the default policy. @param initializingPartitions Set of partitions that should be initialized. This won't reset positions for partitions that may have been added to the subscription state, but that are not included in this set. @return Future that will complete when the reset operation completes retrieving the offsets and setting positions in the subscription state using them. @throws NoOffsetForPartitionException If no reset strategy is configured.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java
337
[ "initializingPartitions" ]
true
2
7.92
apache/kafka
31,560
javadoc
false
inverse_transform
def inverse_transform(self, X): """Return terms per document with nonzero entries in X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Document-term matrix. Returns ------- X_original : list of arrays of shape (n_samples,) List of arrays of terms. """ self._check_vocabulary() # We need CSR format for fast row manipulations. X = check_array(X, accept_sparse="csr") n_samples = X.shape[0] terms = np.array(list(self.vocabulary_.keys())) indices = np.array(list(self.vocabulary_.values())) inverse_vocabulary = terms[np.argsort(indices)] if sp.issparse(X): return [ inverse_vocabulary[X[i, :].nonzero()[1]].ravel() for i in range(n_samples) ] else: return [ inverse_vocabulary[np.flatnonzero(X[i, :])].ravel() for i in range(n_samples) ]
Return terms per document with nonzero entries in X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Document-term matrix. Returns ------- X_original : list of arrays of shape (n_samples,) List of arrays of terms.
python
sklearn/feature_extraction/text.py
1,436
[ "self", "X" ]
false
3
6.08
scikit-learn/scikit-learn
64,340
numpy
false
getCounts
private static ArrayList<Long> getCounts( String mappedFieldName, XContentParser parser, BiFunction<XContentLocation, String, RuntimeException> documentParsingExceptionProvider, ParsingExceptionProvider parsingExceptionProvider ) throws IOException { ArrayList<Long> counts; XContentParser.Token token; token = parser.nextToken(); // should be an array ensureExpectedToken(XContentParser.Token.START_ARRAY, token, parser, parsingExceptionProvider); counts = new ArrayList<>(); token = parser.nextToken(); while (token != XContentParser.Token.END_ARRAY) { // should be a number ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser, parsingExceptionProvider); long count = parser.longValue(); if (count < 0) { throw documentParsingExceptionProvider.apply( parser.getTokenLocation(), "error parsing field [" + mappedFieldName + "], [" + COUNTS_FIELD + "] elements must be >= 0 but got " + count ); } counts.add(count); token = parser.nextToken(); } return counts; }
Parses an XContent object into a histogram. The parser is expected to point at the next token after {@link XContentParser.Token#START_OBJECT}. @param mappedFieldName the name of the field being parsed, used for error messages @param parser the parser to use @param documentParsingExceptionProvider factory function for generating document parsing exceptions. Required for visibility. @return the parsed histogram
java
libs/tdigest/src/main/java/org/elasticsearch/tdigest/parsing/TDigestParser.java
187
[ "mappedFieldName", "parser", "documentParsingExceptionProvider", "parsingExceptionProvider" ]
true
3
7.6
elastic/elasticsearch
75,680
javadoc
false
flatten_dtype
def flatten_dtype(ndtype, flatten_base=False): """ Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : bool, optional If True, transform a field with a shape into several fields. Default is False. Examples -------- >>> import numpy as np >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ... ('block', int, (2, 3))]) >>> np.lib._iotools.flatten_dtype(dt) [dtype('S4'), dtype('float64'), dtype('float64'), dtype('int64')] >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) [dtype('S4'), dtype('float64'), dtype('float64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64')] """ names = ndtype.names if names is None: if flatten_base: return [ndtype.base] * int(np.prod(ndtype.shape)) return [ndtype.base] else: types = [] for field in names: info = ndtype.fields[field] flat_dt = flatten_dtype(info[0], flatten_base) types.extend(flat_dt) return types
Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : bool, optional If True, transform a field with a shape into several fields. Default is False. Examples -------- >>> import numpy as np >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ... ('block', int, (2, 3))]) >>> np.lib._iotools.flatten_dtype(dt) [dtype('S4'), dtype('float64'), dtype('float64'), dtype('int64')] >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) [dtype('S4'), dtype('float64'), dtype('float64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64')]
python
numpy/lib/_iotools.py
85
[ "ndtype", "flatten_base" ]
false
5
7.2
numpy/numpy
31,054
numpy
false
reap
public long reap(long currentTimeMs) { int count = 0; Iterator<CompletableEvent<?>> iterator = tracked.iterator(); while (iterator.hasNext()) { CompletableEvent<?> event = iterator.next(); if (event.future().isDone()) { // Remove any events that are already complete. iterator.remove(); continue; } long deadlineMs = event.deadlineMs(); long pastDueMs = currentTimeMs - deadlineMs; if (pastDueMs < 0) continue; TimeoutException error = new TimeoutException(String.format("%s was %s ms past its expiration of %s", event.getClass().getSimpleName(), pastDueMs, deadlineMs)); // Complete (exceptionally) any events that have passed their deadline AND aren't already complete. if (event.future().completeExceptionally(error)) { log.debug("Event {} completed exceptionally since its expiration of {} passed {} ms ago", event, deadlineMs, pastDueMs); } else { log.trace("Event {} not completed exceptionally since it was previously completed", event); } count++; // Remove the events so that we don't hold a reference to it. iterator.remove(); } return count; }
This method performs a two-step process to "complete" {@link CompletableEvent events} that have either expired or completed normally: <ol> <li> For each tracked event which has exceeded its {@link CompletableEvent#deadlineMs() deadline}, an instance of {@link TimeoutException} is created and passed to {@link CompletableFuture#completeExceptionally(Throwable)}. </li> <li> For each tracked event of which its {@link CompletableEvent#future() future} is already in the {@link CompletableFuture#isDone() done} state, it will be removed from the list of tracked events. </li> </ol> <p/> This method should be called at regular intervals, based upon the needs of the resource that owns the reaper. @param currentTimeMs <em>Current</em> time with which to compare against the <em>{@link CompletableEvent#deadlineMs() expiration time}</em> @return The number of events that were expired
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableEventReaper.java
86
[ "currentTimeMs" ]
true
5
7.6
apache/kafka
31,560
javadoc
false
workspace
def workspace( self, nelem: sympy.Expr, zero_fill: bool, dtype: torch.dtype = torch.uint8 ) -> tuple[str, str, int]: """ Allocate or extend a workspace buffer of nelem elements. This function manages the allocation of a workspace buffer. It either creates a new WorkspaceArg or extends an existing one. Note: - Calling this function will in-place mutate the args by adding or updating a WorkspaceArg. - The codegen for generating the Python argdefs and call_defs will check this field and allocate the buffer accordingly. - A new argument "ws_ptr" will be present in the generated code. Args: nelem (sympy.Expr): The number of elements to allocate. zero_fill (bool): Whether to initialize the buffer to zero. dtype (torch.dtype): the dtype of the workspace tensor Returns: Tuple[str, str, int]: A tuple containing: - "ws_ptr": A string identifier for the workspace pointer. - "workspace_{i}": agraph level unique identifier for the workspace tensor. - offset: An integer representing the item offset in the workspace. """ arg = WorkspaceArg( count=nelem, zero_mode=WorkspaceZeroMode.from_bool(zero_fill), device=V.graph.get_current_device_or_throw(), outer_name=WorkspaceArg.unique_name(), dtype=dtype, ) for i, existing_arg in enumerate(self.workspace_args): if WorkspaceArg.can_join(existing_arg, arg): offset = existing_arg.count self.workspace_args[i] = WorkspaceArg.join(existing_arg, arg) return existing_arg.inner_name, existing_arg.outer_name, offset assert ( existing_arg.inner_name != arg.inner_name and existing_arg.outer_name != arg.outer_name ), existing_arg self.workspace_args.append(arg) return arg.inner_name, arg.outer_name, 0
Allocate or extend a workspace buffer of nelem elements. This function manages the allocation of a workspace buffer. It either creates a new WorkspaceArg or extends an existing one. Note: - Calling this function will in-place mutate the args by adding or updating a WorkspaceArg. - The codegen for generating the Python argdefs and call_defs will check this field and allocate the buffer accordingly. - A new argument "ws_ptr" will be present in the generated code. Args: nelem (sympy.Expr): The number of elements to allocate. zero_fill (bool): Whether to initialize the buffer to zero. dtype (torch.dtype): the dtype of the workspace tensor Returns: Tuple[str, str, int]: A tuple containing: - "ws_ptr": A string identifier for the workspace pointer. - "workspace_{i}": agraph level unique identifier for the workspace tensor. - offset: An integer representing the item offset in the workspace.
python
torch/_inductor/codegen/common.py
1,578
[ "self", "nelem", "zero_fill", "dtype" ]
tuple[str, str, int]
true
4
7.92
pytorch/pytorch
96,034
google
false
maybeTerminateRequestWithError
private boolean maybeTerminateRequestWithError(TxnRequestHandler requestHandler) { if (hasError()) { if (hasAbortableError() && requestHandler instanceof FindCoordinatorHandler) // No harm letting the FindCoordinator request go through if we're expecting to abort return false; requestHandler.fail(lastError); return true; } return false; }
Check if the transaction is in the prepared state. @return true if the current state is PREPARED_TRANSACTION
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
1,176
[ "requestHandler" ]
true
4
7.2
apache/kafka
31,560
javadoc
false
asImmutableList
static <E> ImmutableList<E> asImmutableList(@Nullable Object[] elements, int length) { switch (length) { case 0: return of(); case 1: /* * requireNonNull is safe because the callers promise to put non-null objects in the first * `length` array elements. */ @SuppressWarnings("unchecked") // our callers put only E instances into the array E onlyElement = (E) requireNonNull(elements[0]); return of(onlyElement); default: /* * The suppression is safe because the callers promise to put non-null objects in the first * `length` array elements. */ @SuppressWarnings("nullness") Object[] elementsWithoutTrailingNulls = length < elements.length ? Arrays.copyOf(elements, length) : elements; return new RegularImmutableList<>(elementsWithoutTrailingNulls); } }
Views the array as an immutable list. Copies if the specified range does not cover the complete array. Does not check for nulls.
java
guava/src/com/google/common/collect/ImmutableList.java
368
[ "elements", "length" ]
true
2
6
google/guava
51,352
javadoc
false
splitAndReenqueue
public int splitAndReenqueue(ProducerBatch bigBatch) { // Reset the estimated compression ratio to the initial value or the big batch compression ratio, whichever // is bigger. There are several different ways to do the reset. We chose the most conservative one to ensure // the split doesn't happen too often. CompressionRatioEstimator.setEstimation(bigBatch.topicPartition.topic(), compression.type(), Math.max(1.0f, (float) bigBatch.compressionRatio())); int targetSplitBatchSize = this.batchSize; if (bigBatch.isSplitBatch()) { targetSplitBatchSize = Math.max(bigBatch.maxRecordSize, bigBatch.estimatedSizeInBytes() / 2); } Deque<ProducerBatch> dq = bigBatch.split(targetSplitBatchSize); int numSplitBatches = dq.size(); Deque<ProducerBatch> partitionDequeue = getOrCreateDeque(bigBatch.topicPartition); while (!dq.isEmpty()) { ProducerBatch batch = dq.pollLast(); incomplete.add(batch); // We treat the newly split batches as if they are not even tried. synchronized (partitionDequeue) { if (transactionManager != null) { // We should track the newly created batches since they already have assigned sequences. transactionManager.addInFlightBatch(batch); insertInSequenceOrder(partitionDequeue, batch); } else { partitionDequeue.addFirst(batch); } } } return numSplitBatches; }
Split the big batch that has been rejected and reenqueue the split batches in to the accumulator. @return the number of split batches.
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
511
[ "bigBatch" ]
true
4
7.2
apache/kafka
31,560
javadoc
false
format
String format(E event);
Formats the given log event to a String. @param event the log event to write @return the formatted log event String
java
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/StructuredLogFormatter.java
53
[ "event" ]
String
true
1
6.8
spring-projects/spring-boot
79,428
javadoc
false
getDefaultEncoding
protected @Nullable String getDefaultEncoding(MimeMessage mimeMessage) { if (mimeMessage instanceof SmartMimeMessage smartMimeMessage) { return smartMimeMessage.getDefaultEncoding(); } return null; }
Determine the default encoding for the given MimeMessage. @param mimeMessage the passed-in MimeMessage @return the default encoding associated with the MimeMessage, or {@code null} if none found
java
spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java
426
[ "mimeMessage" ]
String
true
2
7.44
spring-projects/spring-framework
59,386
javadoc
false
convertClassNamesToClasses
public static List<Class<?>> convertClassNamesToClasses(final List<String> classNames) { if (classNames == null) { return null; } final List<Class<?>> classes = new ArrayList<>(classNames.size()); classNames.forEach(className -> { try { classes.add(Class.forName(className)); } catch (final Exception ex) { classes.add(null); } }); return classes; }
Given a {@link List} of class names, this method converts them into classes. <p> A new {@link List} is returned. If the class name cannot be found, {@code null} is stored in the {@link List}. If the class name in the {@link List} is {@code null}, {@code null} is stored in the output {@link List}. </p> @param classNames the classNames to change. @return a {@link List} of Class objects corresponding to the class names, {@code null} if null input. @throws ClassCastException if classNames contains a non String entry.
java
src/main/java/org/apache/commons/lang3/ClassUtils.java
221
[ "classNames" ]
true
3
7.92
apache/commons-lang
2,896
javadoc
false
invoke_lambda
def invoke_lambda( self, *, function_name: str, invocation_type: str | None = None, log_type: str | None = None, client_context: str | None = None, payload: bytes | str | None = None, qualifier: str | None = None, ): """ Invoke Lambda Function. .. seealso:: - :external+boto3:py:meth:`Lambda.Client.invoke` :param function_name: AWS Lambda Function Name :param invocation_type: AWS Lambda Invocation Type (RequestResponse, Event etc) :param log_type: Set to Tail to include the execution log in the response. Applies to synchronously invoked functions only. :param client_context: Up to 3,583 bytes of base64-encoded data about the invoking client to pass to the function in the context object. :param payload: The JSON that you want to provide to your Lambda function as input. :param qualifier: AWS Lambda Function Version or Alias Name """ if isinstance(payload, str): payload = payload.encode() invoke_args = { "FunctionName": function_name, "InvocationType": invocation_type, "LogType": log_type, "ClientContext": client_context, "Payload": payload, "Qualifier": qualifier, } return self.conn.invoke(**trim_none_values(invoke_args))
Invoke Lambda Function. .. seealso:: - :external+boto3:py:meth:`Lambda.Client.invoke` :param function_name: AWS Lambda Function Name :param invocation_type: AWS Lambda Invocation Type (RequestResponse, Event etc) :param log_type: Set to Tail to include the execution log in the response. Applies to synchronously invoked functions only. :param client_context: Up to 3,583 bytes of base64-encoded data about the invoking client to pass to the function in the context object. :param payload: The JSON that you want to provide to your Lambda function as input. :param qualifier: AWS Lambda Function Version or Alias Name
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/lambda_function.py
47
[ "self", "function_name", "invocation_type", "log_type", "client_context", "payload", "qualifier" ]
true
2
6.4
apache/airflow
43,597
sphinx
false
toString
@Override public String toString() { return "(" + getLeft() + ',' + getRight() + ')'; }
Returns a String representation of this pair using the format {@code (left,right)}. @return a string describing this object, not null.
java
src/main/java/org/apache/commons/lang3/tuple/Pair.java
243
[]
String
true
1
6.96
apache/commons-lang
2,896
javadoc
false
_check_key_async
async def _check_key_async( self, client: AioBaseClient, bucket_val: str, wildcard_match: bool, key: str, use_regex: bool = False, ) -> bool: """ Get a list of files that a key matching a wildcard expression or get the head object. If wildcard_match is True get list of files that a key matching a wildcard expression exists in a bucket asynchronously and return the boolean value. If wildcard_match is False get the head object from the bucket and return the boolean value. :param client: aiobotocore client :param bucket_val: the name of the bucket :param key: S3 keys that will point to the file :param wildcard_match: the path to the key :param use_regex: whether to use regex to check bucket """ bucket_name, key = self.get_s3_bucket_key(bucket_val, key, "bucket_name", "bucket_key") if wildcard_match: async for k in self.get_file_metadata_async(client, bucket_name, key): if fnmatch.fnmatch(k["Key"], key): return True return False if use_regex: async for k in self.get_file_metadata_async(client, bucket_name): if re.match(pattern=key, string=k["Key"]): return True return False return bool(await self.get_head_object_async(client, key, bucket_name))
Get a list of files that a key matching a wildcard expression or get the head object. If wildcard_match is True get list of files that a key matching a wildcard expression exists in a bucket asynchronously and return the boolean value. If wildcard_match is False get the head object from the bucket and return the boolean value. :param client: aiobotocore client :param bucket_val: the name of the bucket :param key: S3 keys that will point to the file :param wildcard_match: the path to the key :param use_regex: whether to use regex to check bucket
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py
530
[ "self", "client", "bucket_val", "wildcard_match", "key", "use_regex" ]
bool
true
7
7.04
apache/airflow
43,597
sphinx
false
remove
@CanIgnoreReturnValue @Nullable V remove( @CompatibleWith("R") @Nullable Object rowKey, @CompatibleWith("C") @Nullable Object columnKey);
Removes the mapping, if any, associated with the given keys. @param rowKey row key of mapping to be removed @param columnKey column key of mapping to be removed @return the value previously associated with the keys, or {@code null} if no such value existed
java
android/guava/src/com/google/common/collect/Table.java
170
[ "rowKey", "columnKey" ]
V
true
1
6.48
google/guava
51,352
javadoc
false
createHashTableOrThrow
static @Nullable Object createHashTableOrThrow( @Nullable Object[] alternatingKeysAndValues, int n, int tableSize, int keyOffset) { Object hashTablePlus = createHashTable(alternatingKeysAndValues, n, tableSize, keyOffset); if (hashTablePlus instanceof Object[]) { Object[] hashTableAndSizeAndDuplicate = (Object[]) hashTablePlus; Builder.DuplicateKey duplicateKey = (Builder.DuplicateKey) hashTableAndSizeAndDuplicate[2]; throw duplicateKey.exception(); } return hashTablePlus; }
Returns a hash table for the specified keys and values, and ensures that neither keys nor values are null. This method may update {@code alternatingKeysAndValues} if there are duplicate keys. If so, the return value will indicate how many entries are still valid, and will also include a {@link Builder.DuplicateKey} in case duplicate keys are not allowed now or will not be allowed on a later {@link Builder#buildOrThrow()} call. @param keyOffset 1 if this is the reverse direction of a BiMap, 0 otherwise. @return an {@code Object} that is a {@code byte[]}, {@code short[]}, or {@code int[]}, the smallest possible to fit {@code tableSize}; or an {@code Object[]} where [0] is one of these; [1] indicates how many element pairs in {@code alternatingKeysAndValues} are valid; and [2] is a {@link Builder.DuplicateKey} for the first duplicate key encountered.
java
android/guava/src/com/google/common/collect/RegularImmutableMap.java
282
[ "alternatingKeysAndValues", "n", "tableSize", "keyOffset" ]
Object
true
2
8.08
google/guava
51,352
javadoc
false
maybeThrottle
private void maybeThrottle(AbstractResponse response, short apiVersion, String nodeId, long now) { int throttleTimeMs = response.throttleTimeMs(); if (throttleTimeMs > 0 && response.shouldClientThrottle(apiVersion)) { inFlightRequests.incrementThrottleTime(nodeId, throttleTimeMs); connectionStates.throttle(nodeId, now + throttleTimeMs); log.trace("Connection to node {} is throttled for {} ms until timestamp {}", nodeId, throttleTimeMs, now + throttleTimeMs); } }
If a response from a node includes a non-zero throttle delay and client-side throttling has been enabled for the connection to the node, throttle the connection for the specified delay. @param response the response @param apiVersion the API version of the response @param nodeId the id of the node @param now The current time
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
978
[ "response", "apiVersion", "nodeId", "now" ]
void
true
3
6.56
apache/kafka
31,560
javadoc
false
real
def real(val): """ Return the real part of the complex argument. Parameters ---------- val : array_like Input array. Returns ------- out : ndarray or scalar The real component of the complex argument. If `val` is real, the type of `val` is used for the output. If `val` has complex elements, the returned type is float. See Also -------- real_if_close, imag, angle Examples -------- >>> import numpy as np >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.real array([1., 3., 5.]) >>> a.real = 9 >>> a array([9.+2.j, 9.+4.j, 9.+6.j]) >>> a.real = np.array([9, 8, 7]) >>> a array([9.+2.j, 8.+4.j, 7.+6.j]) >>> np.real(1 + 1j) 1.0 """ try: return val.real except AttributeError: return asanyarray(val).real
Return the real part of the complex argument. Parameters ---------- val : array_like Input array. Returns ------- out : ndarray or scalar The real component of the complex argument. If `val` is real, the type of `val` is used for the output. If `val` has complex elements, the returned type is float. See Also -------- real_if_close, imag, angle Examples -------- >>> import numpy as np >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.real array([1., 3., 5.]) >>> a.real = 9 >>> a array([9.+2.j, 9.+4.j, 9.+6.j]) >>> a.real = np.array([9, 8, 7]) >>> a array([9.+2.j, 8.+4.j, 7.+6.j]) >>> np.real(1 + 1j) 1.0
python
numpy/lib/_type_check_impl.py
85
[ "val" ]
false
1
6.48
numpy/numpy
31,054
numpy
false
parse
public static Duration parse(String value, DurationFormat.Style style, DurationFormat.@Nullable Unit unit) { Assert.hasText(value, () -> "Value must not be empty"); return switch (style) { case ISO8601 -> parseIso8601(value); case SIMPLE -> parseSimple(value, unit); case COMPOSITE -> parseComposite(value); }; }
Parse the given value to a duration. @param value the value to parse @param style the style in which to parse @param unit the duration unit to use if the value doesn't specify one ({@code null} will default to ms) @return a duration
java
spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java
96
[ "value", "style", "unit" ]
Duration
true
1
7.04
spring-projects/spring-framework
59,386
javadoc
false
isRunning
@Override public boolean isRunning() throws SchedulingException { if (this.scheduler != null) { try { return !this.scheduler.isInStandbyMode(); } catch (SchedulerException ex) { return false; } } return false; }
Start the Quartz Scheduler, respecting the "startupDelay" setting. @param scheduler the Scheduler to start @param startupDelay the number of seconds to wait before starting the Scheduler asynchronously
java
spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java
810
[]
true
3
6.24
spring-projects/spring-framework
59,386
javadoc
false