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
updateWith
function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); }
This method is like `_.update` except that it accepts `customizer` which is invoked to produce the objects of `path`. If `customizer` returns `undefined` path creation is handled by the method instead. The `customizer` is invoked with three arguments: (nsValue, key, nsObject). **Note:** This method mutates `object`. @static @memberOf _ @since 4.6.0 @category Object @param {Object} object The object to modify. @param {Array|string} path The path of the property to set. @param {Function} updater The function to produce the updated value. @param {Function} [customizer] The function to customize assigned values. @returns {Object} Returns `object`. @example var object = {}; _.updateWith(object, '[0][1]', _.constant('a'), Object); // => { '0': { '1': 'a' } }
javascript
lodash.js
14,004
[ "object", "path", "updater", "customizer" ]
false
3
7.44
lodash/lodash
61,490
jsdoc
false
hasCachePut
private boolean hasCachePut(CacheOperationContexts contexts) { // Evaluate the conditions *without* the result object because we don't have it yet... Collection<CacheOperationContext> cachePutContexts = contexts.get(CachePutOperation.class); Collection<CacheOperationContext> excluded = new ArrayList<>(1); for (CacheOperationContext context : cachePutContexts) { try { if (!context.isConditionPassing(CacheOperationExpressionEvaluator.RESULT_UNAVAILABLE)) { excluded.add(context); } } catch (VariableNotAvailableException ex) { // Ignoring failure due to missing result, consider the cache put has to proceed } } // Check if all puts have been excluded by condition return (cachePutContexts.size() != excluded.size()); }
Find a cached value only for {@link CacheableOperation} that passes the condition. @param contexts the cacheable operations @return a {@link Cache.ValueWrapper} holding the cached value, or {@code null} if none is found
java
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
639
[ "contexts" ]
true
3
8.08
spring-projects/spring-framework
59,386
javadoc
false
cumsum
def cumsum(self, axis: AxisInt = 0, *args, **kwargs) -> SparseArray: """ Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseArray will preserve the locations of NaN values, but the fill value will be `np.nan` regardless. Parameters ---------- axis : int or None Axis over which to perform the cumulative summation. If None, perform cumulative summation over flattened array. Returns ------- cumsum : SparseArray """ nv.validate_cumsum(args, kwargs) if axis is not None and axis >= self.ndim: # Mimic ndarray behaviour. raise ValueError(f"axis(={axis}) out of bounds") if not self._null_fill_value: return SparseArray(self.to_dense(), fill_value=np.nan).cumsum() return SparseArray( self.sp_values.cumsum(), sparse_index=self.sp_index, fill_value=self.fill_value, )
Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseArray will preserve the locations of NaN values, but the fill value will be `np.nan` regardless. Parameters ---------- axis : int or None Axis over which to perform the cumulative summation. If None, perform cumulative summation over flattened array. Returns ------- cumsum : SparseArray
python
pandas/core/arrays/sparse/array.py
1,549
[ "self", "axis" ]
SparseArray
true
4
6.56
pandas-dev/pandas
47,362
numpy
false
setExternalExecutor
public final synchronized void setExternalExecutor(final ExecutorService externalExecutor) { if (isStarted()) { throw new IllegalStateException("Cannot set ExecutorService after start()!"); } this.externalExecutor = externalExecutor; }
Sets an {@link ExecutorService} to be used by this class. The {@code ExecutorService} passed to this method is used for executing the background task. Thus it is possible to re-use an already existing {@link ExecutorService} or to use a specially configured one. If no {@link ExecutorService} is set, this instance creates a temporary one and destroys it after background initialization is complete. Note that this method must be called before {@link #start()}; otherwise an exception is thrown. @param externalExecutor the {@link ExecutorService} to be used. @throws IllegalStateException if this initializer has already been started.
java
src/main/java/org/apache/commons/lang3/concurrent/BackgroundInitializer.java
377
[ "externalExecutor" ]
void
true
2
6.72
apache/commons-lang
2,896
javadoc
false
visitFunctionExpression
function visitFunctionExpression(node: FunctionExpression): Expression { const ancestorFacts = getEmitFlags(node) & EmitFlags.AsyncFunctionBody ? enterSubtree(HierarchyFacts.AsyncFunctionBodyExcludes, HierarchyFacts.AsyncFunctionBodyIncludes) : enterSubtree(HierarchyFacts.FunctionExcludes, HierarchyFacts.FunctionIncludes); const savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; const parameters = visitParameterList(node.parameters, visitor, context); const body = transformFunctionBody(node); const name = hierarchyFacts & HierarchyFacts.NewTarget ? factory.getLocalName(node) : node.name; exitSubtree(ancestorFacts, HierarchyFacts.FunctionSubtreeExcludes, HierarchyFacts.None); convertedLoopState = savedConvertedLoopState; return factory.updateFunctionExpression( node, /*modifiers*/ undefined, node.asteriskToken, name, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body, ); }
Visits a FunctionExpression node. @param node a FunctionExpression node.
typescript
src/compiler/transformers/es2015.ts
2,449
[ "node" ]
true
3
6.24
microsoft/TypeScript
107,154
jsdoc
false
sequential_split
def sequential_split( gm: torch.fx.GraphModule, node_call_back: Callable[[torch.fx.Node], Union[torch.fx.Node, bool]], ) -> torch.fx.GraphModule: """ sequential_split creates a new graph module that splits the input graph module into multiple submodules based on the node_call_back. It doesn't mutate the input graph module. The node_call_back should return True if the node is a delimiter. Delimiter will be the first node in the next submodule. """ from torch.fx.passes.split_module import split_module split_map = {} split_id = 0 for node in gm.graph.nodes: if node_call_back(node): split_id += 1 split_map[node] = split_id new_gm = split_module( gm, gm, lambda node: split_map[node], keep_original_order=True, keep_original_node_name=True, ) # Keep the codegen from original graph module to preserve e.g. pytree info. new_gm.graph._codegen = gm.graph._codegen new_gm.recompile() return new_gm
sequential_split creates a new graph module that splits the input graph module into multiple submodules based on the node_call_back. It doesn't mutate the input graph module. The node_call_back should return True if the node is a delimiter. Delimiter will be the first node in the next submodule.
python
torch/_export/utils.py
620
[ "gm", "node_call_back" ]
torch.fx.GraphModule
true
3
6
pytorch/pytorch
96,034
unknown
false
field
public XContentBuilder field(String name, Short value) throws IOException { return (value == null) ? nullField(name) : field(name, value.shortValue()); }
@return the value of the "human readable" flag. When the value is equal to true, some types of values are written in a format easier to read for a human.
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java
624
[ "name", "value" ]
XContentBuilder
true
2
6.96
elastic/elasticsearch
75,680
javadoc
false
terminate_job
def terminate_job(self, job_id: str, reason: str) -> dict: """ Terminate a Batch job. :param job_id: a job ID to terminate :param reason: a reason to terminate job ID :return: an API response """ response = self.get_conn().terminate_job(jobId=job_id, reason=reason) self.log.info(response) return response
Terminate a Batch job. :param job_id: a job ID to terminate :param reason: a reason to terminate job ID :return: an API response
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/batch_client.py
242
[ "self", "job_id", "reason" ]
dict
true
1
7.04
apache/airflow
43,597
sphinx
false
runtime_version
def runtime_version() -> str | None: """Get the version string for the detected runtime. Returns: Version string for the current runtime (CUDA or HIP), or None if no supported runtime is detected. """ return { "CUDA": torch.version.cuda, "HIP": torch.version.hip, }.get(_CompileContext.runtime()) # type: ignore[arg-type]
Get the version string for the detected runtime. Returns: Version string for the current runtime (CUDA or HIP), or None if no supported runtime is detected.
python
torch/_inductor/runtime/caching/context.py
178
[]
str | None
true
1
6.72
pytorch/pytorch
96,034
unknown
false
spaceMatcher
public static StrMatcher spaceMatcher() { return SPACE_MATCHER; }
Gets the matcher for the space character. @return the matcher for a space.
java
src/main/java/org/apache/commons/lang3/text/StrMatcher.java
331
[]
StrMatcher
true
1
6.8
apache/commons-lang
2,896
javadoc
false
toArray
@Override @J2ktIncompatible // Incompatible return type change. Use inherited implementation public Object[] toArray() { /* * If we could, we'd declare the no-arg `Collection.toArray()` to return "Object[] but elements * have the same nullness as E." Since we can't, we declare it to return nullable elements, and * we can override it in our non-null-guaranteeing subtypes to present a better signature to * their users. * * However, the checker *we* use has this special knowledge about `Collection.toArray()` anyway, * so in our implementation code, we can rely on that. That's why the expression below * type-checks. */ return super.toArray(); }
Adds the given element to this queue. If the queue is currently full, the element at the head of the queue is evicted to make room. @return {@code true} always
java
android/guava/src/com/google/common/collect/EvictingQueue.java
128
[]
true
1
7.04
google/guava
51,352
javadoc
false
expiredBatches
public List<ProducerBatch> expiredBatches(long now) { List<ProducerBatch> expiredBatches = new ArrayList<>(); for (TopicInfo topicInfo : topicInfoMap.values()) { for (Deque<ProducerBatch> deque : topicInfo.batches.values()) { // expire the batches in the order of sending synchronized (deque) { while (!deque.isEmpty()) { ProducerBatch batch = deque.getFirst(); if (batch.hasReachedDeliveryTimeout(deliveryTimeoutMs, now)) { deque.poll(); batch.abortRecordAppends(); expiredBatches.add(batch); } else { maybeUpdateNextBatchExpiryTime(batch); break; } } } } } return expiredBatches; }
Get a list of batches which have been sitting in the accumulator too long and need to be expired.
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
465
[ "now" ]
true
3
6
apache/kafka
31,560
javadoc
false
isTypeMatch
private boolean isTypeMatch(FactoryBean<?> factoryBean, Class<?> typeToMatch) throws NoSuchBeanDefinitionException { if (factoryBean instanceof SmartFactoryBean<?> smartFactoryBean) { return smartFactoryBean.supportsType(typeToMatch); } Class<?> objectType = factoryBean.getObjectType(); return (objectType != null && typeToMatch.isAssignableFrom(objectType)); }
Add a new singleton bean. <p>Will overwrite any existing instance for the given name. @param name the name of the bean @param bean the bean instance
java
spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java
252
[ "factoryBean", "typeToMatch" ]
true
3
6.88
spring-projects/spring-framework
59,386
javadoc
false
isInstance
public static boolean isInstance(final Object value, final Type type) { if (type == null) { return false; } return value == null ? !(type instanceof Class<?>) || !((Class<?>) type).isPrimitive() : isAssignable(value.getClass(), type, null); }
Tests if the given value can be assigned to the target type following the Java generics rules. @param value the value to be checked. @param type the target type. @return {@code true} if {@code value} is an instance of {@code type}.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
1,275
[ "value", "type" ]
true
4
8.24
apache/commons-lang
2,896
javadoc
false
newLinkedHashSetWithExpectedSize
@SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSetWithExpectedSize( int expectedSize) { return new LinkedHashSet<>(Maps.capacity(expectedSize)); }
Creates a {@code LinkedHashSet} instance, with a high enough "initial capacity" that it <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method isn't inadvertently <i>oversizing</i> the returned set. @param expectedSize the number of elements you expect to add to the returned set @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize} elements without resizing @throws IllegalArgumentException if {@code expectedSize} is negative @since 11.0
java
android/guava/src/com/google/common/collect/Sets.java
360
[ "expectedSize" ]
true
1
6.24
google/guava
51,352
javadoc
false
getShortClassName
public static String getShortClassName(final Class<?> cls) { if (cls == null) { return StringUtils.EMPTY; } return getShortClassName(cls.getName()); }
Gets the class name minus the package name from a {@link Class}. <p> This method simply gets the name using {@code Class.getName()} and then calls {@link #getShortClassName(String)}. See relevant notes there. </p> @param cls the class to get the short name for. @return the class name without the package name or an empty string. If the class is an inner class then the returned value will contain the outer class or classes separated with {@code .} (dot) character.
java
src/main/java/org/apache/commons/lang3/ClassUtils.java
1,019
[ "cls" ]
String
true
2
7.92
apache/commons-lang
2,896
javadoc
false
get_parse_time_mapped_ti_count
def get_parse_time_mapped_ti_count(self) -> int: """ Return the number of mapped task instances that can be created on DAG run creation. This only considers literal mapped arguments, and would return *None* when any non-literal values are used for mapping. :raise NotFullyPopulated: If non-literal mapped arguments are encountered. :raise NotMapped: If the operator is neither mapped, nor has any parent mapped task groups. :return: Total number of mapped TIs this task should have. """ from airflow.exceptions import NotMapped group = self.get_closest_mapped_task_group() if group is None: raise NotMapped() return group.get_parse_time_mapped_ti_count()
Return the number of mapped task instances that can be created on DAG run creation. This only considers literal mapped arguments, and would return *None* when any non-literal values are used for mapping. :raise NotFullyPopulated: If non-literal mapped arguments are encountered. :raise NotMapped: If the operator is neither mapped, nor has any parent mapped task groups. :return: Total number of mapped TIs this task should have.
python
airflow-core/src/airflow/serialization/serialized_objects.py
2,173
[ "self" ]
int
true
2
6.72
apache/airflow
43,597
unknown
false
from
public static <K, V> CacheLoader<K, V> from(Function<K, V> function) { return new FunctionToCacheLoader<>(function); }
Returns a cache loader that uses {@code function} to load keys, and without supporting either reloading or bulk loading. This is most useful when you can pass a lambda expression. Otherwise it is useful mostly when you already have an existing function instance. <p>The returned object is serializable if {@code function} is serializable. @param function the function to be used for loading values; must never return {@code null} @return a cache loader that loads values by passing each key to {@code function}
java
android/guava/src/com/google/common/cache/CacheLoader.java
141
[ "function" ]
true
1
6.96
google/guava
51,352
javadoc
false
throwUnexpectedAbsoluteUrlError
function throwUnexpectedAbsoluteUrlError(path: string, url: string): never { throw new RuntimeError( RuntimeErrorCode.INVALID_LOADER_ARGUMENTS, ngDevMode && `Image loader has detected a \`<img>\` tag with an invalid \`ngSrc\` attribute: ${url}. ` + `This image loader expects \`ngSrc\` to be a relative URL - ` + `however the provided value is an absolute URL. ` + `To fix this, provide \`ngSrc\` as a path relative to the base URL ` + `configured for this loader (\`${path}\`).`, ); }
Internal helper function that makes it easier to introduce custom image loaders for the `NgOptimizedImage` directive. It is enough to specify a URL builder function to obtain full DI configuration for a given loader: a DI token corresponding to the actual loader function, plus DI tokens managing preconnect check functionality. @param buildUrlFn a function returning a full URL based on loader's configuration @param exampleUrls example of full URLs for a given loader (used in error messages) @returns a set of DI providers corresponding to the configured image loader
typescript
packages/common/src/directives/ng_optimized_image/image_loaders/image_loader.ts
131
[ "path", "url" ]
true
2
7.6
angular/angular
99,544
jsdoc
false
addMonths
public static Date addMonths(final Date date, final int amount) { return add(date, Calendar.MONTH, amount); }
Adds a number of months to a date returning a new object. The original {@link Date} is unchanged. @param date the date, not null. @param amount the amount to add, may be negative. @return the new {@link Date} with the amount added. @throws NullPointerException if the date is null.
java
src/main/java/org/apache/commons/lang3/time/DateUtils.java
289
[ "date", "amount" ]
Date
true
1
6.64
apache/commons-lang
2,896
javadoc
false
create
public static AdminClient create(Properties props) { return (AdminClient) Admin.create(props); }
Create a new Admin with the given configuration. @param props The configuration. @return The new KafkaAdminClient.
java
clients/src/main/java/org/apache/kafka/clients/admin/AdminClient.java
38
[ "props" ]
AdminClient
true
1
6.32
apache/kafka
31,560
javadoc
false
setCount
@CanIgnoreReturnValue public Builder<E> setCount(E element, int count) { requireNonNull(contents); // see the comment on the field if (count == 0 && !isLinkedHash) { contents = new ObjectCountLinkedHashMap<E>(contents); isLinkedHash = true; // to preserve insertion order through deletions, we have to switch to an actual linked // implementation at least for now, but this should be a super rare case } else if (buildInvoked) { contents = new ObjectCountHashMap<E>(contents); isLinkedHash = false; } buildInvoked = false; checkNotNull(element); if (count == 0) { contents.remove(element); } else { contents.put(checkNotNull(element), count); } return this; }
Adds or removes the necessary occurrences of an element such that the element attains the desired count. @param element the element to add or remove occurrences of @param count the desired count of the element in this multiset @return this {@code Builder} object @throws NullPointerException if {@code element} is null @throws IllegalArgumentException if {@code count} is negative
java
android/guava/src/com/google/common/collect/ImmutableMultiset.java
569
[ "element", "count" ]
true
5
7.76
google/guava
51,352
javadoc
false
_get_result_dtype
def _get_result_dtype(self, dtype: np.dtype) -> np.dtype: """ Get the desired dtype of a result based on the input dtype and how it was computed. Parameters ---------- dtype : np.dtype Returns ------- np.dtype The desired dtype of the result. """ how = self.how if how in ["sum", "cumsum", "sum", "prod", "cumprod"]: if dtype == np.dtype(bool): return np.dtype(np.int64) elif how in ["mean", "median", "var", "std", "sem"]: if dtype.kind in "fc": return dtype elif dtype.kind in "iub": return np.dtype(np.float64) return dtype
Get the desired dtype of a result based on the input dtype and how it was computed. Parameters ---------- dtype : np.dtype Returns ------- np.dtype The desired dtype of the result.
python
pandas/core/groupby/ops.py
286
[ "self", "dtype" ]
np.dtype
true
6
6.88
pandas-dev/pandas
47,362
numpy
false
determineConstructorsFromBeanPostProcessors
protected Constructor<?> @Nullable [] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException { if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) { Constructor<?>[] ctors = bp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; } } } return null; }
Determine candidate constructors to use for the given bean, checking all registered {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}. @param beanClass the raw class of the bean @param beanName the name of the bean @return the candidate constructors, or {@code null} if none specified @throws org.springframework.beans.BeansException in case of errors @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
1,316
[ "beanClass", "beanName" ]
true
4
7.28
spring-projects/spring-framework
59,386
javadoc
false
group
public String group() { return this.group; }
Get the name of the group. @return the group name; never null
java
clients/src/main/java/org/apache/kafka/common/MetricNameTemplate.java
87
[]
String
true
1
6.64
apache/kafka
31,560
javadoc
false
has_task
def has_task(self, task_instance: TaskInstance) -> bool: """ Check if a task is either queued or running in this executor. :param task_instance: TaskInstance :return: True if the task is known to this executor """ return ( task_instance.id in self.queued_tasks or task_instance.id in self.running or task_instance.key in self.queued_tasks or task_instance.key in self.running )
Check if a task is either queued or running in this executor. :param task_instance: TaskInstance :return: True if the task is known to this executor
python
airflow-core/src/airflow/executors/base_executor.py
237
[ "self", "task_instance" ]
bool
true
4
7.92
apache/airflow
43,597
sphinx
false
getWritableJsonToWrite
private @Nullable WritableJson getWritableJsonToWrite(@Nullable T extracted, JsonValueWriter valueWriter) { BiConsumer<T, BiConsumer<?, ?>> pairs = this.pairs; if (pairs != null) { return (out) -> valueWriter.writePairs((outPairs) -> pairs.accept(extracted, outPairs)); } Members<T> members = this.members; if (members != null) { return (out) -> members.write(extracted, valueWriter); } return null; }
Writes the given instance using details configure by this member. @param instance the instance to write @param valueWriter the JSON value writer to use
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
662
[ "extracted", "valueWriter" ]
WritableJson
true
3
6.72
spring-projects/spring-boot
79,428
javadoc
false
compressLongestRunOfZeroes
private static void compressLongestRunOfZeroes(int[] hextets) { int bestRunStart = -1; int bestRunLength = -1; int runStart = -1; for (int i = 0; i < hextets.length + 1; i++) { if (i < hextets.length && hextets[i] == 0) { if (runStart < 0) { runStart = i; } } else if (runStart >= 0) { int runLength = i - runStart; if (runLength > bestRunLength) { bestRunStart = runStart; bestRunLength = runLength; } runStart = -1; } } if (bestRunLength >= 2) { Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); } }
Identify and mark the longest run of zeroes in an IPv6 address. <p>Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If a qualifying run is found, its hextets are replaced by the sentinel value -1. @param hextets {@code int[]} mutable array of eight 16-bit hextets
java
android/guava/src/com/google/common/net/InetAddresses.java
506
[ "hextets" ]
void
true
8
7.04
google/guava
51,352
javadoc
false
fetchCommittedOffsets
public Map<TopicPartition, OffsetAndMetadata> fetchCommittedOffsets(final Set<TopicPartition> partitions, final Timer timer) { if (partitions.isEmpty()) return Collections.emptyMap(); final Generation generationForOffsetRequest = generationIfStable(); if (pendingCommittedOffsetRequest != null && !pendingCommittedOffsetRequest.sameRequest(partitions, generationForOffsetRequest)) { // if we were waiting for a different request, then just clear it. pendingCommittedOffsetRequest = null; } long attempts = 0L; do { if (!ensureCoordinatorReady(timer)) return null; // contact coordinator to fetch committed offsets final RequestFuture<Map<TopicPartition, OffsetAndMetadata>> future; if (pendingCommittedOffsetRequest != null) { future = pendingCommittedOffsetRequest.response; } else { future = sendOffsetFetchRequest(partitions); pendingCommittedOffsetRequest = new PendingCommittedOffsetRequest(partitions, generationForOffsetRequest, future); } client.poll(future, timer); if (future.isDone()) { pendingCommittedOffsetRequest = null; if (future.succeeded()) { return future.value(); } else if (!future.isRetriable()) { throw future.exception(); } else { timer.sleep(retryBackoff.backoff(attempts++)); } } else { return null; } } while (timer.notExpired()); return null; }
Fetch the current committed offsets from the coordinator for a set of partitions. @param partitions The partitions to fetch offsets for @return A map from partition to the committed offset or null if the operation timed out
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerCoordinator.java
963
[ "partitions", "timer" ]
true
9
8.24
apache/kafka
31,560
javadoc
false
getKnownIndexedChildren
private Set<String> getKnownIndexedChildren(IterableConfigurationPropertySource source, ConfigurationPropertyName root) { Set<String> knownIndexedChildren = new HashSet<>(); for (ConfigurationPropertyName name : source.filter(root::isAncestorOf)) { ConfigurationPropertyName choppedName = name.chop(root.getNumberOfElements() + 1); if (choppedName.isLastElementIndexed()) { knownIndexedChildren.add(choppedName.getLastElement(Form.UNIFORM)); } } return knownIndexedChildren; }
Bind indexed elements to the supplied collection. @param name the name of the property to bind @param target the target bindable @param elementBinder the binder to use for elements @param aggregateType the aggregate type, may be a collection or an array @param elementType the element type @param result the destination for results
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java
129
[ "source", "root" ]
true
2
6.4
spring-projects/spring-boot
79,428
javadoc
false
isNestedType
private boolean isNestedType(String propertyName, Class<?> propertyType) { Class<?> declaringClass = propertyType.getDeclaringClass(); if (declaringClass != null && isNested(declaringClass, this.type)) { return true; } Field field = ReflectionUtils.findField(this.type, propertyName); return (field != null) && MergedAnnotations.from(field).isPresent(Nested.class); }
Specify whether the specified property refer to a nested type. A nested type represents a sub-namespace that need to be fully resolved. Nested types are either inner classes or annotated with {@link NestedConfigurationProperty}. @param propertyName the name of the property @param propertyType the type of the property @return whether the specified {@code propertyType} is a nested type
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/BindableRuntimeHintsRegistrar.java
314
[ "propertyName", "propertyType" ]
true
4
7.76
spring-projects/spring-boot
79,428
javadoc
false
bind
public <T> BindResult<T> bind(String name, Bindable<T> target, @Nullable BindHandler handler) { return bind(ConfigurationPropertyName.of(name), target, handler); }
Bind the specified target {@link Bindable} using this binder's {@link ConfigurationPropertySource property sources}. @param name the configuration property name to bind @param target the target bindable @param handler the bind handler (may be {@code null}) @param <T> the bound type @return the binding result (never {@code null})
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java
273
[ "name", "target", "handler" ]
true
1
6.16
spring-projects/spring-boot
79,428
javadoc
false
filterPropertyDescriptorsForDependencyCheck
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) { List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors())); pds.removeIf(this::isExcludedFromDependencyCheck); return pds.toArray(new PropertyDescriptor[0]); }
Extract a filtered set of PropertyDescriptors from the given BeanWrapper, excluding ignored dependency types or properties defined on ignored dependency interfaces. @param bw the BeanWrapper the bean was created with @return the filtered PropertyDescriptors @see #isExcludedFromDependencyCheck
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
1,602
[ "bw" ]
true
1
6.08
spring-projects/spring-framework
59,386
javadoc
false
words
function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; }
Splits `string` into an array of its words. @static @memberOf _ @since 3.0.0 @category String @param {string} [string=''] The string to inspect. @param {RegExp|string} [pattern] The pattern to match words. @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. @returns {Array} Returns the words of `string`. @example _.words('fred, barney, & pebbles'); // => ['fred', 'barney', 'pebbles'] _.words('fred, barney, & pebbles', /[^, ]+/g); // => ['fred', 'barney', '&', 'pebbles']
javascript
lodash.js
15,329
[ "string", "pattern", "guard" ]
false
5
7.36
lodash/lodash
61,490
jsdoc
false
isCyclical
private static boolean isCyclical(final Class<?> cls) { for (final TypeVariable<?> typeParameter : cls.getTypeParameters()) { for (final Type bound : typeParameter.getBounds()) { if (bound.getTypeName().contains(cls.getName())) { return true; } } } return false; }
Tests whether the class contains a cyclical reference in the qualified name of a class. If any of the type parameters of A class is extending X class which is in scope of A class, then it forms cycle. @param cls the class to test. @return whether the class contains a cyclical reference.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
1,257
[ "cls" ]
true
2
8.24
apache/commons-lang
2,896
javadoc
false
maxValue
@CanIgnoreReturnValue public C maxValue() { throw new NoSuchElementException(); }
Returns the maximum value of type {@code C}, if it has one. The maximum value is the unique value for which {@link Comparable#compareTo(Object)} never returns a negative value for any input of type {@code C}. <p>The default implementation throws {@code NoSuchElementException}. @return the maximum value of type {@code C}; never null @throws NoSuchElementException if the type has no (practical) maximum value; for example, {@link java.math.BigInteger}
java
android/guava/src/com/google/common/collect/DiscreteDomain.java
336
[]
C
true
1
6.48
google/guava
51,352
javadoc
false
parseArray
public static <T, Context> List<T> parseArray(XContentParser parser, Context context, ContextParser<Context, T> itemParser) throws IOException { final XContentParser.Token currentToken = parser.currentToken(); if (currentToken.isValue() || currentToken == XContentParser.Token.VALUE_NULL || currentToken == XContentParser.Token.START_OBJECT) { return Collections.singletonList(itemParser.parse(parser, context)); // single value } final List<T> list = new ArrayList<>(); XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token.isValue() || token == XContentParser.Token.VALUE_NULL || token == XContentParser.Token.START_OBJECT) { list.add(itemParser.parse(parser, context)); } else { throw new IllegalStateException("expected value but got [" + token + "]"); } } return list; }
Declares a set of fields of which at most one must appear for parsing to succeed E.g. <code>declareExclusiveFieldSet("foo", "bar");</code> means that only one of 'foo' or 'bar' must be present, and if both appear then an exception will be thrown. Note that this does not make 'foo' or 'bar' required - see {@link #declareRequiredFieldSet(String...)} for required fields. Multiple exclusive sets may be declared @param exclusiveSet a set of field names, at most one of which must appear
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/AbstractObjectParser.java
414
[ "parser", "context", "itemParser" ]
true
8
6.88
elastic/elasticsearch
75,680
javadoc
false
device
def device(*array_list, remove_none=True, remove_types=(str,)): """Hardware device where the array data resides on. If the hardware device is not the same for all arrays, an error is raised. Parameters ---------- *array_list : arrays List of array instances from NumPy or an array API compatible library. remove_none : bool, default=True Whether to ignore None objects passed in array_list. remove_types : tuple or list, default=(str,) Types to ignore in array_list. Returns ------- out : device `device` object (see the "Device Support" section of the array API spec). """ array_list = _remove_non_arrays( *array_list, remove_none=remove_none, remove_types=remove_types ) if not array_list: return None device_ = _single_array_device(array_list[0]) # Note: here we cannot simply use a Python `set` as it requires # hashable members which is not guaranteed for Array API device # objects. In particular, CuPy devices are not hashable at the # time of writing. for array in array_list[1:]: device_other = _single_array_device(array) if device_ != device_other: raise ValueError( f"Input arrays use different devices: {device_}, {device_other}" ) return device_
Hardware device where the array data resides on. If the hardware device is not the same for all arrays, an error is raised. Parameters ---------- *array_list : arrays List of array instances from NumPy or an array API compatible library. remove_none : bool, default=True Whether to ignore None objects passed in array_list. remove_types : tuple or list, default=(str,) Types to ignore in array_list. Returns ------- out : device `device` object (see the "Device Support" section of the array API spec).
python
sklearn/utils/_array_api.py
170
[ "remove_none", "remove_types" ]
false
4
6.08
scikit-learn/scikit-learn
64,340
numpy
false
create_endpoint
def create_endpoint( self, config: dict, wait_for_completion: bool = True, check_interval: int = 30, max_ingestion_time: int | None = None, ): """ Create an endpoint from configuration. When you create a serverless endpoint, SageMaker provisions and manages the compute resources for you. Then, you can make inference requests to the endpoint and receive model predictions in response. SageMaker scales the compute resources up and down as needed to handle your request traffic. .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.create_endpoint` - :class:`airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.create_endpoint` :param config: the config for endpoint :param wait_for_completion: if the program should keep running until job finishes :param check_interval: the time interval in seconds which the operator will check the status of any SageMaker job :param max_ingestion_time: the maximum ingestion time in seconds. Any SageMaker jobs that run longer than this will fail. Setting this to None implies no timeout for any SageMaker job. :return: A response to endpoint creation """ response = self.get_conn().create_endpoint(**config) if wait_for_completion: self.check_status( config["EndpointName"], "EndpointStatus", self.describe_endpoint, check_interval, max_ingestion_time, non_terminal_states=self.endpoint_non_terminal_states, ) return response
Create an endpoint from configuration. When you create a serverless endpoint, SageMaker provisions and manages the compute resources for you. Then, you can make inference requests to the endpoint and receive model predictions in response. SageMaker scales the compute resources up and down as needed to handle your request traffic. .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.create_endpoint` - :class:`airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.create_endpoint` :param config: the config for endpoint :param wait_for_completion: if the program should keep running until job finishes :param check_interval: the time interval in seconds which the operator will check the status of any SageMaker job :param max_ingestion_time: the maximum ingestion time in seconds. Any SageMaker jobs that run longer than this will fail. Setting this to None implies no timeout for any SageMaker job. :return: A response to endpoint creation
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
493
[ "self", "config", "wait_for_completion", "check_interval", "max_ingestion_time" ]
true
2
7.44
apache/airflow
43,597
sphinx
false
bindProperty
@Nullable Object bindProperty(String propertyName, Bindable<?> target);
Bind the given property. @param propertyName the property name (in lowercase dashed form, e.g. {@code first-name}) @param target the target bindable @return the bound value or {@code null}
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DataObjectPropertyBinder.java
37
[ "propertyName", "target" ]
Object
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
from
static @Nullable Origin from(@Nullable Object source) { if (source instanceof Origin origin) { return origin; } Origin origin = null; if (source instanceof OriginProvider originProvider) { origin = originProvider.getOrigin(); } if (origin == null && source instanceof Throwable throwable) { return from(throwable.getCause()); } return origin; }
Find the {@link Origin} that an object originated from. Checks if the source object is an {@link Origin} or {@link OriginProvider} and also searches exception stacks. @param source the source object or {@code null} @return an {@link Origin} or {@code null}
java
core/spring-boot/src/main/java/org/springframework/boot/origin/Origin.java
61
[ "source" ]
Origin
true
5
7.92
spring-projects/spring-boot
79,428
javadoc
false
loadClass
@Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (!this.hasJarUrls) { return super.loadClass(name, resolve); } Optimizations.enable(true); try { try { definePackageIfNecessary(name); } catch (IllegalArgumentException ex) { tolerateRaceConditionDueToBeingParallelCapable(ex, name); } return super.loadClass(name, resolve); } finally { Optimizations.disable(); } }
Create a new {@link LaunchedClassLoader} instance. @param urls the URLs from which to load classes and resources @param parent the parent class loader for delegation
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarUrlClassLoader.java
94
[ "name", "resolve" ]
true
3
6.72
spring-projects/spring-boot
79,428
javadoc
false
IndexableDisplayName
function IndexableDisplayName({displayName, id}: Props): React.Node { const {searchIndex, searchResults, searchText} = useContext(TreeStateContext); const isSearchResult = useMemo(() => { return searchResults.includes(id); }, [id, searchResults]); const isCurrentResult = searchIndex !== null && id === searchResults[searchIndex]; if (!isSearchResult || displayName === null) { return displayName; } const match = createRegExp(searchText).exec(displayName); if (match === null) { return displayName; } const startIndex = match.index; const stopIndex = startIndex + match[0].length; const children = []; if (startIndex > 0) { children.push(<span key="begin">{displayName.slice(0, startIndex)}</span>); } children.push( <mark key="middle" className={isCurrentResult ? styles.CurrentHighlight : styles.Highlight}> {displayName.slice(startIndex, stopIndex)} </mark>, ); if (stopIndex < displayName.length) { children.push(<span key="end">{displayName.slice(stopIndex)}</span>); } return children; }
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/Components/IndexableDisplayName.js
24
[]
false
8
6.24
facebook/react
241,750
jsdoc
false
apply
R apply(I input) throws T;
Applies this function. @param input the input for the function @return the result of the function @throws T Thrown when the function fails.
java
src/main/java/org/apache/commons/lang3/Functions.java
217
[ "input" ]
R
true
1
6.8
apache/commons-lang
2,896
javadoc
false
generate_client_defaults
def generate_client_defaults(cls) -> dict[str, Any]: """ Generate `client_defaults` section that only includes values differing from schema defaults. This optimizes serialization size by avoiding redundant storage of schema defaults. Uses OPERATOR_DEFAULTS as the source of truth for task default values. :return: client_defaults dictionary with only non-schema values """ # Get schema defaults for comparison schema_defaults = cls.get_schema_defaults("operator") client_defaults = {} # Only include OPERATOR_DEFAULTS values that differ from schema defaults for k, v in OPERATOR_DEFAULTS.items(): if k not in cls.get_serialized_fields(): continue # Exclude values that are None or empty collections if v is None or v in [[], (), set(), {}]: continue # Check schema defaults first with raw value comparison (fast path) if k in schema_defaults and schema_defaults[k] == v: continue # Use the existing serialize method to ensure consistent format serialized_value = cls.serialize(v) # Extract just the value part, consistent with serialize_to_json behavior if isinstance(serialized_value, dict) and Encoding.TYPE in serialized_value: serialized_value = serialized_value[Encoding.VAR] # For cases where raw comparison failed but serialized values might match # (e.g., timedelta vs float), check again with serialized value if k in schema_defaults and schema_defaults[k] == serialized_value: continue client_defaults[k] = serialized_value return client_defaults
Generate `client_defaults` section that only includes values differing from schema defaults. This optimizes serialization size by avoiding redundant storage of schema defaults. Uses OPERATOR_DEFAULTS as the source of truth for task default values. :return: client_defaults dictionary with only non-schema values
python
airflow-core/src/airflow/serialization/serialized_objects.py
1,938
[ "cls" ]
dict[str, Any]
true
11
6.72
apache/airflow
43,597
unknown
false
days
public long days() { return timeUnit.toDays(duration); }
@return the number of {@link #timeUnit()} units this value contains
java
libs/core/src/main/java/org/elasticsearch/core/TimeValue.java
162
[]
true
1
6
elastic/elasticsearch
75,680
javadoc
false
truePredicate
@SuppressWarnings("unchecked") static <E extends Throwable> FailableIntPredicate<E> truePredicate() { return TRUE; }
Gets the TRUE singleton. @param <E> The kind of thrown exception or error. @return The NOP singleton.
java
src/main/java/org/apache/commons/lang3/function/FailableIntPredicate.java
57
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
liftToBlock
function liftToBlock(nodes: readonly Node[]): Statement { Debug.assert(every(nodes, isStatementOrBlock), "Cannot lift nodes to a Block."); return singleOrUndefined(nodes) as Statement || createBlock(nodes as readonly Statement[]); }
Lifts a NodeArray containing only Statement nodes to a block. @param nodes The NodeArray.
typescript
src/compiler/factory/nodeFactory.ts
6,959
[ "nodes" ]
true
2
6.64
microsoft/TypeScript
107,154
jsdoc
false
parseSimple
private static Duration parseSimple(String text, DurationFormat.@Nullable Unit fallbackUnit) { try { Matcher matcher = SIMPLE_PATTERN.matcher(text); Assert.state(matcher.matches(), "Does not match simple duration pattern"); String suffix = matcher.group(2); DurationFormat.Unit parsingUnit = (fallbackUnit == null ? DurationFormat.Unit.MILLIS : fallbackUnit); if (StringUtils.hasLength(suffix)) { parsingUnit = DurationFormat.Unit.fromSuffix(suffix); } return parsingUnit.parse(matcher.group(1)); } catch (Exception ex) { throw new IllegalArgumentException("'" + text + "' is not a valid simple duration", ex); } }
Detect the style then parse the value to return a duration. @param value the value to parse @param unit the duration unit to use if the value doesn't specify one ({@code null} will default to ms) @return the parsed duration @throws IllegalArgumentException if the value is not a known style or cannot be parsed
java
spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java
165
[ "text", "fallbackUnit" ]
Duration
true
4
7.76
spring-projects/spring-framework
59,386
javadoc
false
hashCode
@Override public int hashCode() { int result = partition; result = 31 * result + (leader != null ? leader.hashCode() : 0); result = 31 * result + (replicas != null ? replicas.hashCode() : 0); result = 31 * result + (isr != null ? isr.hashCode() : 0); result = 31 * result + (elr != null ? elr.hashCode() : 0); result = 31 * result + (lastKnownElr != null ? lastKnownElr.hashCode() : 0); return result; }
Return the last known eligible leader replicas of the partition. Note that the ordering of the result is unspecified.
java
clients/src/main/java/org/apache/kafka/common/TopicPartitionInfo.java
140
[]
true
6
6.88
apache/kafka
31,560
javadoc
false
getBeansOfType
@Override @SuppressWarnings("unchecked") public <T> Map<String, T> getBeansOfType( @Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit); Map<String, T> result = CollectionUtils.newLinkedHashMap(beanNames.length); for (String beanName : beanNames) { try { Object beanInstance = (type != null ? getBean(beanName, type) : getBean(beanName)); if (!(beanInstance instanceof NullBean)) { result.put(beanName, (T) beanInstance); } } catch (BeanNotOfRequiredTypeException ex) { // Ignore - probably a NullBean } catch (BeanCreationException ex) { Throwable rootCause = ex.getMostSpecificCause(); if (rootCause instanceof BeanCurrentlyInCreationException bce) { String exBeanName = bce.getBeanName(); if (exBeanName != null && isCurrentlyInCreation(exBeanName)) { if (logger.isTraceEnabled()) { logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " + ex.getMessage()); } onSuppressedException(ex); // Ignore: indicates a circular reference when autowiring constructors. // We want to find matches other than the currently created bean itself. continue; } } throw ex; } } return result; }
Check whether the specified bean would need to be eagerly initialized in order to determine its type. @param factoryBeanName a factory-bean reference that the bean definition defines a factory method for @return whether eager initialization is necessary
java
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
731
[ "type", "includeNonSingletons", "allowEagerInit" ]
true
9
7.76
spring-projects/spring-framework
59,386
javadoc
false
of
public static ConditionMessage of(String message, Object... args) { if (ObjectUtils.isEmpty(args)) { return new ConditionMessage(message); } return new ConditionMessage(String.format(message, args)); }
Factory method to create a new {@link ConditionMessage} with a specific message. @param message the source message (may be a format string if {@code args} are specified) @param args format arguments for the message @return a new {@link ConditionMessage} instance
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java
150
[ "message" ]
ConditionMessage
true
2
7.76
spring-projects/spring-boot
79,428
javadoc
false
records
public Map<TopicPartition, List<ConsumerRecord<K, V>>> records() { return Collections.unmodifiableMap(records); }
@return all of the non-control messages for this fetch, grouped by partition
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetch.java
85
[]
true
1
6.48
apache/kafka
31,560
javadoc
false
getAggregateTemplateLoader
protected @Nullable TemplateLoader getAggregateTemplateLoader(List<TemplateLoader> templateLoaders) { return switch (templateLoaders.size()) { case 0 -> { logger.debug("No FreeMarker TemplateLoaders specified"); yield null; } case 1 -> templateLoaders.get(0); default -> { TemplateLoader[] loaders = templateLoaders.toArray(new TemplateLoader[0]); yield new MultiTemplateLoader(loaders); } }; }
Return a {@link TemplateLoader} based on the given {@code TemplateLoader} list. <p>If more than one TemplateLoader has been registered, a FreeMarker {@link MultiTemplateLoader} will be created. @param templateLoaders the final List of {@code TemplateLoader} instances @return the aggregate TemplateLoader
java
spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java
414
[ "templateLoaders" ]
TemplateLoader
true
1
6.24
spring-projects/spring-framework
59,386
javadoc
false
detectAndParse
public static Duration detectAndParse(String value) { return detectAndParse(value, null); }
Detect the style then parse the value to return a duration. @param value the value to parse @return the parsed duration @throws IllegalArgumentException if the value is not a known style or cannot be parsed
java
spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java
133
[ "value" ]
Duration
true
1
6.64
spring-projects/spring-framework
59,386
javadoc
false
getDescription
@Override protected String getDescription() { Filter filter = getFilter(); Assert.notNull(filter, "'filter' must not be null"); return "filter " + getOrDeduceName(filter); }
Return if filter mappings should be matched after any declared Filter mappings of the ServletContext. @return if filter mappings are matched after
java
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java
223
[]
String
true
1
6.56
spring-projects/spring-boot
79,428
javadoc
false
to_markdown
def to_markdown( self, buf: FilePath | WriteBuffer[str] | None = None, *, mode: str = "wt", index: bool = True, storage_options: StorageOptions | None = None, **kwargs, ) -> str | None: """ Print DataFrame in Markdown-friendly format. Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. mode : str, optional Mode in which file is opened, "wt" by default. index : bool, optional, default True Add index (row) labels. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. **kwargs These parameters will be passed to `tabulate <https://pypi.org/project/tabulate>`_. Returns ------- str DataFrame in Markdown-friendly format. See Also -------- DataFrame.to_html : Render DataFrame to HTML-formatted table. DataFrame.to_latex : Render DataFrame to LaTeX-formatted table. Notes ----- Requires the `tabulate <https://pypi.org/project/tabulate>`_ package. Examples -------- >>> df = pd.DataFrame( ... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]} ... ) >>> print(df.to_markdown()) | | animal_1 | animal_2 | |---:|:-----------|:-----------| | 0 | elk | dog | | 1 | pig | quetzal | Output markdown with a tabulate option. >>> print(df.to_markdown(tablefmt="grid")) +----+------------+------------+ | | animal_1 | animal_2 | +====+============+============+ | 0 | elk | dog | +----+------------+------------+ | 1 | pig | quetzal | +----+------------+------------+ """ if "showindex" in kwargs: raise ValueError("Pass 'index' instead of 'showindex") kwargs.setdefault("headers", "keys") kwargs.setdefault("tablefmt", "pipe") kwargs.setdefault("showindex", index) tabulate = import_optional_dependency("tabulate") result = tabulate.tabulate(self, **kwargs) if buf is None: return result with get_handle(buf, mode, storage_options=storage_options) as handles: handles.handle.write(result) return None
Print DataFrame in Markdown-friendly format. Parameters ---------- buf : str, Path or StringIO-like, optional, default None Buffer to write to. If None, the output is returned as a string. mode : str, optional Mode in which file is opened, "wt" by default. index : bool, optional, default True Add index (row) labels. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib.request.Request`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more details, and for more examples on storage options refer `here <https://pandas.pydata.org/docs/user_guide/io.html? highlight=storage_options#reading-writing-remote-files>`_. **kwargs These parameters will be passed to `tabulate <https://pypi.org/project/tabulate>`_. Returns ------- str DataFrame in Markdown-friendly format. See Also -------- DataFrame.to_html : Render DataFrame to HTML-formatted table. DataFrame.to_latex : Render DataFrame to LaTeX-formatted table. Notes ----- Requires the `tabulate <https://pypi.org/project/tabulate>`_ package. Examples -------- >>> df = pd.DataFrame( ... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]} ... ) >>> print(df.to_markdown()) | | animal_1 | animal_2 | |---:|:-----------|:-----------| | 0 | elk | dog | | 1 | pig | quetzal | Output markdown with a tabulate option. >>> print(df.to_markdown(tablefmt="grid")) +----+------------+------------+ | | animal_1 | animal_2 | +====+============+============+ | 0 | elk | dog | +----+------------+------------+ | 1 | pig | quetzal | +----+------------+------------+
python
pandas/core/frame.py
2,881
[ "self", "buf", "mode", "index", "storage_options" ]
str | None
true
3
7.92
pandas-dev/pandas
47,362
numpy
false
getContent
private FileDataBlock getContent() throws IOException { FileDataBlock content = this.content; if (content == null) { long pos = Integer.toUnsignedLong(this.centralRecord.offsetToLocalHeader()); checkNotZip64Extended(pos); ZipLocalFileHeaderRecord localHeader = ZipLocalFileHeaderRecord.load(ZipContent.this.data, pos); long size = Integer.toUnsignedLong(this.centralRecord.compressedSize()); checkNotZip64Extended(size); content = ZipContent.this.data.slice(pos + localHeader.size(), size); this.content = content; } return content; }
Open a {@link DataBlock} providing access to raw contents of the entry (not including the local file header). <p> To release resources, the {@link #close()} method of the data block should be called explicitly or by try-with-resources. @return the contents of the entry @throws IOException on I/O error
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java
798
[]
FileDataBlock
true
2
7.76
spring-projects/spring-boot
79,428
javadoc
false
getPublicMethod
public static Method getPublicMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) throws NoSuchMethodException { final Method declaredMethod = cls.getMethod(methodName, parameterTypes); if (isPublic(declaredMethod.getDeclaringClass())) { return declaredMethod; } final List<Class<?>> candidateClasses = new ArrayList<>(getAllInterfaces(cls)); candidateClasses.addAll(getAllSuperclasses(cls)); for (final Class<?> candidateClass : candidateClasses) { if (!isPublic(candidateClass)) { continue; } final Method candidateMethod; try { candidateMethod = candidateClass.getMethod(methodName, parameterTypes); } catch (final NoSuchMethodException ex) { continue; } if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) { return candidateMethod; } } throw new NoSuchMethodException("Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes)); }
Gets the desired Method much like {@code Class.getMethod}, however it ensures that the returned Method is from a public class or interface and not from an anonymous inner class. This means that the Method is invokable and doesn't fall foul of Java bug (<a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>). <pre> {@code Set set = Collections.unmodifiableSet(...); Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]); Object result = method.invoke(set, new Object[]);} </pre> @param cls the class to check, not null. @param methodName the name of the method. @param parameterTypes the list of parameters. @return the method. @throws NullPointerException if the class is null. @throws SecurityException if a security violation occurred. @throws NoSuchMethodException if the method is not found in the given class or if the method doesn't conform with the requirements.
java
src/main/java/org/apache/commons/lang3/ClassUtils.java
860
[ "cls", "methodName" ]
Method
true
5
7.6
apache/commons-lang
2,896
javadoc
false
closeInternal
private void closeInternal(final Duration timeout) { long timeoutMs = timeout.toMillis(); log.trace("Signaling the consumer network thread to close in {}ms", timeoutMs); running = false; closeTimeout = timeout; wakeup(); try { join(); } catch (InterruptedException e) { log.error("Interrupted while waiting for consumer network thread to complete", e); } }
Starts the closing process. <p/> This method is called from the application thread, but our resources are owned by the network thread. As such, we don't actually close any of those resources here, immediately, on the application thread. Instead, we just update our internal state on the application thread. When the network thread next {@link #run() executes its loop}, it will notice that state, cease processing any further events, and begin {@link #cleanup() closing its resources}. <p/> This method will wait (i.e. block the application thread) for up to the duration of the given timeout to give the network thread the time to close down cleanly. @param timeout Upper bound of time to wait for the network thread to close its resources
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java
376
[ "timeout" ]
void
true
2
7.04
apache/kafka
31,560
javadoc
false
assert
function assert(...args) { innerOk(assert, ...args); }
Pure assertion tests whether a value is truthy, as determined by !!value. @param {...any} args @returns {void}
javascript
lib/assert.js
185
[]
false
1
6.16
nodejs/node
114,839
jsdoc
false
randomBytes
public byte[] randomBytes(final int count) { Validate.isTrue(count >= 0, "Count cannot be negative."); final byte[] result = new byte[count]; random().nextBytes(result); return result; }
Generates an array of random bytes. @param count the size of the returned array. @return the random byte array. @throws IllegalArgumentException if {@code count} is negative @since 3.16.0
java
src/main/java/org/apache/commons/lang3/RandomUtils.java
315
[ "count" ]
true
1
6.88
apache/commons-lang
2,896
javadoc
false
autodetect_docker_context
def autodetect_docker_context(): """ Auto-detects which docker context to use. :return: name of the docker context to use """ result = run_command( ["docker", "context", "ls", "--format=json"], capture_output=True, check=False, text=True, ) if result.returncode != 0: get_console().print("[warning]Could not detect docker builder. Using default.[/]") return "default" try: context_dicts = json.loads(result.stdout) if isinstance(context_dicts, dict): context_dicts = [context_dicts] except json.decoder.JSONDecodeError: context_dicts = (json.loads(line) for line in result.stdout.splitlines() if line.strip()) known_contexts = {info["Name"]: info for info in context_dicts} if not known_contexts: get_console().print("[warning]Could not detect docker builder. Using default.[/]") return "default" for preferred_context_name in PREFERRED_CONTEXTS: try: context = known_contexts[preferred_context_name] except KeyError: continue # On Windows, some contexts are used for WSL2. We don't want to use those. if context["DockerEndpoint"] == "npipe:////./pipe/dockerDesktopLinuxEngine": continue get_console().print(f"[info]Using {preferred_context_name!r} as context.[/]") return preferred_context_name fallback_context = next(iter(known_contexts)) get_console().print( f"[warning]Could not use any of the preferred docker contexts {PREFERRED_CONTEXTS}.\n" f"Using {fallback_context} as context.[/]" ) return fallback_context
Auto-detects which docker context to use. :return: name of the docker context to use
python
dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
684
[]
false
6
7.6
apache/airflow
43,597
unknown
false
wrapCacheValue
private @Nullable Object wrapCacheValue(Method method, @Nullable Object cacheValue) { if (method.getReturnType() == Optional.class && (cacheValue == null || cacheValue.getClass() != Optional.class)) { return Optional.ofNullable(cacheValue); } return cacheValue; }
Find a cached value only for {@link CacheableOperation} that passes the condition. @param contexts the cacheable operations @return a {@link Cache.ValueWrapper} holding the cached value, or {@code null} if none is found
java
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
627
[ "method", "cacheValue" ]
Object
true
4
7.92
spring-projects/spring-framework
59,386
javadoc
false
min
public static double min(final double a, final double b, final double c) { return min(min(a, b), c); }
Gets the minimum of three {@code double} values. <p>NaN is only returned if all numbers are NaN as per IEEE-754r.</p> @param a value 1 @param b value 2 @param c value 3 @return the smallest of the values
java
src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java
193
[ "a", "b", "c" ]
true
1
6.48
apache/commons-lang
2,896
javadoc
false
get_all_output_and_tangent_nodes
def get_all_output_and_tangent_nodes( g: fx.Graph, ) -> dict[DifferentiableAOTOutput, tuple[fx.Node, Optional[fx.Node]]]: """Get all output nodes and their corresponding tangent nodes from a joint graph. Similar to get_all_input_and_grad_nodes, but returns output nodes paired with their tangent nodes (if they exist). This function traverses the graph to find all differentiable outputs and matches them with their corresponding tangent inputs used in forward-mode autodiff. NB: *all* forward tensor output sare turned, including non-differentiable outputs, so you can use this function to perform operations on all outputs. Args: g: The FX joint graph with descriptors Returns: A dictionary mapping each DifferentiableAOTOutput descriptor to a tuple containing: - The output node itself - The tangent (input) node if it exists, None otherwise Raises: RuntimeError: If the joint graph has subclass tensor inputs/outputs; this is not supported by API as there is not necessarily a 1-1 correspondence between outputs and tangents when subclasses are involved. """ output_index: dict[DifferentiableAOTOutput, tuple[fx.Node, Optional[fx.Node]]] = {} for n in g.nodes: if n.op == "output": desc = n.meta["desc"] for sub_n, sub_d in zip(n.args[0], desc): # Skip outputs that cannot possibly be differentiable if not isinstance(sub_d, DifferentiableAOTOutput): continue if isinstance(sub_d, SubclassGetAttrAOTOutput): _raise_autograd_subclass_not_implemented(sub_n, sub_d) # pyrefly: ignore [unsupported-operation] output_index[sub_d] = (sub_n, None) for n in g.nodes: if n.op == "placeholder": desc = n.meta["desc"] if isinstance(desc, SubclassGetAttrAOTInput): _raise_autograd_subclass_not_implemented(n, desc) if isinstance(desc, TangentAOTInput): out, tangent = output_index[desc.output] assert tangent is None, (n, desc, output_index) output_index[desc.output] = (out, n) return output_index
Get all output nodes and their corresponding tangent nodes from a joint graph. Similar to get_all_input_and_grad_nodes, but returns output nodes paired with their tangent nodes (if they exist). This function traverses the graph to find all differentiable outputs and matches them with their corresponding tangent inputs used in forward-mode autodiff. NB: *all* forward tensor output sare turned, including non-differentiable outputs, so you can use this function to perform operations on all outputs. Args: g: The FX joint graph with descriptors Returns: A dictionary mapping each DifferentiableAOTOutput descriptor to a tuple containing: - The output node itself - The tangent (input) node if it exists, None otherwise Raises: RuntimeError: If the joint graph has subclass tensor inputs/outputs; this is not supported by API as there is not necessarily a 1-1 correspondence between outputs and tangents when subclasses are involved.
python
torch/_functorch/_aot_autograd/fx_utils.py
96
[ "g" ]
dict[DifferentiableAOTOutput, tuple[fx.Node, Optional[fx.Node]]]
true
10
7.92
pytorch/pytorch
96,034
google
false
seq_concat_seq
def seq_concat_seq(a, b): """Concatenate two sequences: ``a + b``. Returns: Sequence: The return value will depend on the largest sequence - if b is larger and is a tuple, the return value will be a tuple. - if a is larger and is a list, the return value will be a list, """ # find the type of the largest sequence prefer = type(max([a, b], key=len)) # convert the smallest list to the type of the largest sequence. if not isinstance(a, prefer): a = prefer(a) if not isinstance(b, prefer): b = prefer(b) return a + b
Concatenate two sequences: ``a + b``. Returns: Sequence: The return value will depend on the largest sequence - if b is larger and is a tuple, the return value will be a tuple. - if a is larger and is a list, the return value will be a list,
python
celery/utils/functional.py
383
[ "a", "b" ]
false
3
7.28
celery/celery
27,741
unknown
false
of
static Options of(Option... values) { return new Options(values); }
Factory method used to create a new {@link Options} instance with specific values. @param values the option values @return a new {@link Options} instance with the given values
java
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/Command.java
254
[]
Options
true
1
6.8
spring-projects/spring-boot
79,428
javadoc
false
configureSocketChannel
private void configureSocketChannel(SocketChannel socketChannel, int sendBufferSize, int receiveBufferSize) throws IOException { socketChannel.configureBlocking(false); Socket socket = socketChannel.socket(); socket.setKeepAlive(true); if (sendBufferSize != Selectable.USE_DEFAULT_BUFFER_SIZE) socket.setSendBufferSize(sendBufferSize); if (receiveBufferSize != Selectable.USE_DEFAULT_BUFFER_SIZE) socket.setReceiveBufferSize(receiveBufferSize); socket.setTcpNoDelay(true); }
Begin connecting to the given address and add the connection to this nioSelector associated with the given id number. <p> Note that this call only initiates the connection, which will be completed on a future {@link #poll(long)} call. Check {@link #connected()} to see which (if any) connections have completed after a given poll call. @param id The id for the new connection @param address The address to connect to @param sendBufferSize The send buffer for the new connection @param receiveBufferSize The receive buffer for the new connection @throws IllegalStateException if there is already a connection for that id @throws IOException if DNS resolution fails on the hostname or if the broker is down
java
clients/src/main/java/org/apache/kafka/common/network/Selector.java
284
[ "socketChannel", "sendBufferSize", "receiveBufferSize" ]
void
true
3
6.72
apache/kafka
31,560
javadoc
false
compare
@Override public int compare(final Object o1, final Object o2) { if (o1 == o2) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } final String string1 = o1.toString(); final String string2 = o2.toString(); // No guarantee that toString() returns a non-null value, despite what Spotbugs thinks. if (string1 == string2) { return 0; } if (string1 == null) { return 1; } if (string2 == null) { return -1; } return string1.compareTo(string2); }
Constructs a new instance. @deprecated Will be private in 4.0.0.
java
src/main/java/org/apache/commons/lang3/compare/ObjectToStringComparator.java
54
[ "o1", "o2" ]
true
7
6
apache/commons-lang
2,896
javadoc
false
_create_join_index
def _create_join_index( self, index: Index, other_index: Index, indexer: npt.NDArray[np.intp] | None, how: JoinHow = "left", ) -> Index: """ Create a join index by rearranging one index to match another Parameters ---------- index : Index index being rearranged other_index : Index used to supply values not found in index indexer : np.ndarray[np.intp] or None how to rearrange index how : str Replacement is only necessary if indexer based on other_index. Returns ------- Index """ if self.how in (how, "outer") and not isinstance(other_index, MultiIndex): # if final index requires values in other_index but not target # index, indexer may hold missing (-1) values, causing Index.take # to take the final value in target index. So, we set the last # element to be the desired fill value. We do not use allow_fill # and fill_value because it throws a ValueError on integer indices mask = indexer == -1 if np.any(mask): fill_value = na_value_for_dtype(index.dtype, compat=False) if not index._can_hold_na: new_index = Index([fill_value]) else: new_index = Index([fill_value], dtype=index.dtype) index = index.append(new_index) if indexer is None: return index.copy() return index.take(indexer)
Create a join index by rearranging one index to match another Parameters ---------- index : Index index being rearranged other_index : Index used to supply values not found in index indexer : np.ndarray[np.intp] or None how to rearrange index how : str Replacement is only necessary if indexer based on other_index. Returns ------- Index
python
pandas/core/reshape/merge.py
1,470
[ "self", "index", "other_index", "indexer", "how" ]
Index
true
7
6.72
pandas-dev/pandas
47,362
numpy
false
equal
def equal(x1, x2): """ Return (x1 == x2) element-wise. Unlike `numpy.equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. Examples -------- >>> import numpy as np >>> y = "aa " >>> x = "aa" >>> np.char.equal(x, y) array(True) See Also -------- not_equal, greater_equal, less_equal, greater, less """ return compare_chararrays(x1, x2, '==', True)
Return (x1 == x2) element-wise. Unlike `numpy.equal`, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray. Parameters ---------- x1, x2 : array_like of str or unicode Input arrays of the same shape. Returns ------- out : ndarray Output array of bools. Examples -------- >>> import numpy as np >>> y = "aa " >>> x = "aa" >>> np.char.equal(x, y) array(True) See Also -------- not_equal, greater_equal, less_equal, greater, less
python
numpy/_core/defchararray.py
62
[ "x1", "x2" ]
false
1
6.32
numpy/numpy
31,054
numpy
false
getChars
public char[] getChars(char[] destination) { final int len = length(); if (destination == null || destination.length < len) { destination = new char[len]; } return ArrayUtils.arraycopy(buffer, 0, destination, 0, len); }
Copies the character array into the specified array. @param destination the destination array, null will cause an array to be created @return the input array, unless that was null or too small
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
1,919
[ "destination" ]
true
3
8.08
apache/commons-lang
2,896
javadoc
false
filter
public FailableStream<T> filter(final FailablePredicate<T, ?> predicate) { assertNotTerminated(); stream = stream.filter(Failable.asPredicate(predicate)); return this; }
Returns a FailableStream consisting of the elements of this stream that match the given FailablePredicate. <p> This is an intermediate operation. </p> @param predicate a non-interfering, stateless predicate to apply to each element to determine if it should be included. @return the new stream
java
src/main/java/org/apache/commons/lang3/stream/Streams.java
363
[ "predicate" ]
true
1
6.72
apache/commons-lang
2,896
javadoc
false
visitVariableStatement
function visitVariableStatement(node: VariableStatement): VisitResult<Statement | undefined> { if (!shouldHoistVariableDeclarationList(node.declarationList)) { return visitNode(node, visitor, isStatement); } let statements: Statement[] | undefined; // `using` and `await using` declarations cannot be hoisted directly, so we will hoist the variable name // as a normal variable, and declare it as a temp variable that remains as a `using` to ensure the correct // lifetime. if (isVarUsing(node.declarationList) || isVarAwaitUsing(node.declarationList)) { const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifierLike); const declarations: VariableDeclaration[] = []; for (const variable of node.declarationList.declarations) { declarations.push(factory.updateVariableDeclaration( variable, factory.getGeneratedNameForNode(variable.name), /*exclamationToken*/ undefined, /*type*/ undefined, transformInitializedVariable(variable, /*isExportedDeclaration*/ false), )); } const declarationList = factory.updateVariableDeclarationList( node.declarationList, declarations, ); statements = append(statements, factory.updateVariableStatement(node, modifiers, declarationList)); } else { let expressions: Expression[] | undefined; const isExportedDeclaration = hasSyntacticModifier(node, ModifierFlags.Export); for (const variable of node.declarationList.declarations) { if (variable.initializer) { expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); } else { hoistBindingElement(variable); } } if (expressions) { statements = append(statements, setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node)); } } statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); return singleOrMany(statements); }
Visits a variable statement, hoisting declared names to the top-level module body. Each declaration is rewritten into an assignment expression. @param node The node to visit.
typescript
src/compiler/transformers/module/system.ts
868
[ "node" ]
true
8
6.88
microsoft/TypeScript
107,154
jsdoc
false
withFrameFilter
public StandardStackTracePrinter withFrameFilter(BiPredicate<Integer, StackTraceElement> predicate) { Assert.notNull(predicate, "'predicate' must not be null"); return new StandardStackTracePrinter(this.options, this.maximumLength, this.lineSeparator, this.filter, this.frameFilter.and(predicate), this.formatter, this.frameFormatter, this.frameHasher); }
Return a new {@link StandardStackTracePrinter} from this one that will only include frames that match the given predicate. @param predicate the predicate used to filter frames @return a new {@link StandardStackTracePrinter} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/StandardStackTracePrinter.java
213
[ "predicate" ]
StandardStackTracePrinter
true
1
6.24
spring-projects/spring-boot
79,428
javadoc
false
create_call_function_ex
def create_call_function_ex( has_kwargs: bool, push_null: bool, ignore_314_kwargs_push: bool = False ) -> list[Instruction]: """ Assumes that in 3.14+, if has_kwargs=False, there is NOT a NULL on the TOS for the kwargs. This utility function will add a PUSH_NULL. If the caller has already pushed a NULL for the kwargs, then set ignore_314_kwargs_push=True so we don't push another NULL for the kwargs. """ if sys.version_info >= (3, 11): output = [] if ( sys.version_info >= (3, 14) and not has_kwargs and not ignore_314_kwargs_push ): output.append(create_instruction("PUSH_NULL")) has_kwargs = True if push_null: output.append(create_instruction("PUSH_NULL")) # 3.13 swapped NULL and callable # if flags == 1, 2 values popped - otherwise if flags == 0, 1 value rots = ( int(has_kwargs) + 2 if sys.version_info >= (3, 13) else int(has_kwargs) + 3 ) output.extend(create_rot_n(rots)) output.append(create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))) return output return [create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))]
Assumes that in 3.14+, if has_kwargs=False, there is NOT a NULL on the TOS for the kwargs. This utility function will add a PUSH_NULL. If the caller has already pushed a NULL for the kwargs, then set ignore_314_kwargs_push=True so we don't push another NULL for the kwargs.
python
torch/_dynamo/bytecode_transformation.py
400
[ "has_kwargs", "push_null", "ignore_314_kwargs_push" ]
list[Instruction]
true
7
6
pytorch/pytorch
96,034
unknown
false
unitIjkToDigit
public int unitIjkToDigit() { // should be call on a normalized object if (Math.min(i, Math.min(j, k)) < 0 || Math.max(i, Math.max(j, k)) > 1) { return Direction.INVALID_DIGIT.digit(); } return i << 2 | j << 1 | k; }
Determines the H3 digit corresponding to a unit vector in ijk coordinates. @return The H3 digit (0-6) corresponding to the ijk unit vector, or INVALID_DIGIT on failure.
java
libs/h3/src/main/java/org/elasticsearch/h3/CoordIJK.java
313
[]
true
3
8.24
elastic/elasticsearch
75,680
javadoc
false
from_env_var
def from_env_var(cls, env_var: str) -> Self: """ Create an in-memory cache from an environment variable. Args: env_var (str): Name of the environment variable containing cache data. Returns: InMemoryCache: An instance populated from the environment variable. Raises: CacheError: If the environment variable is malformed or contains invalid data. """ cache = cls() if (env_val := getenv(env_var)) is None: # env_var doesn't exist = empty cache return cache for kv_pair in env_val.split(";"): # ignore whitespace prefix/suffix kv_pair = kv_pair.strip() if not kv_pair: # kv_pair could be '' if env_val is '' or has ; suffix continue try: # keys and values should be comma separated key_bytes_repr, value_bytes_repr = kv_pair.split(",", 1) except ValueError as err: raise CacheError( f"Malformed kv_pair {kv_pair!r} from env_var {env_var!r}, likely missing comma separator." ) from err # ignore whitespace prefix/suffix, again key_bytes_repr, value_bytes_repr = ( key_bytes_repr.strip(), value_bytes_repr.strip(), ) try: # check that key_bytes_str is an actual, legitimate encoding key_bytes = literal_eval(key_bytes_repr) except (ValueError, SyntaxError) as err: raise CacheError( f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." ) from err try: # check that value_bytes_str is an actual, legitimate encoding value_bytes = literal_eval(value_bytes_repr) except (ValueError, SyntaxError) as err: raise CacheError( f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." ) from err try: key = pickle.loads(key_bytes) except pickle.UnpicklingError as err: raise CacheError( f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." ) from err try: value = pickle.loads(value_bytes) except pickle.UnpicklingError as err: raise CacheError( f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." ) from err # true duplicates, i.e. multiple occurrences of the same key => value # mapping are ok and treated as a no-op; key duplicates with differing # values, i.e. key => value_1 and key => value_2 where value_1 != value_2, # are not okay since we don't allow overwriting cached values (it's bad regardless) if (not cache.insert(key, value)) and (cache.get(key) != value): raise CacheError( f"Multiple values for key {key!r} found, got {cache.get(key)!r} and {value!r}." ) return cache
Create an in-memory cache from an environment variable. Args: env_var (str): Name of the environment variable containing cache data. Returns: InMemoryCache: An instance populated from the environment variable. Raises: CacheError: If the environment variable is malformed or contains invalid data.
python
torch/_inductor/cache.py
106
[ "cls", "env_var" ]
Self
true
6
7.52
pytorch/pytorch
96,034
google
false
iterator
public static Iterator<Calendar> iterator(final Date focus, final int rangeStyle) { return iterator(toCalendar(focus), rangeStyle); }
Constructs an {@link Iterator} over each day in a date range defined by a focus date and range style. <p>For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} will return an {@link Iterator} that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, 2002, returning a Calendar instance for each intermediate day.</p> <p>This method provides an iterator that returns Calendar objects. The days are progressed using {@link Calendar#add(int, int)}.</p> @param focus the date to work with, not null. @param rangeStyle the style constant to use. Must be one of {@link DateUtils#RANGE_MONTH_SUNDAY}, {@link DateUtils#RANGE_MONTH_MONDAY}, {@link DateUtils#RANGE_WEEK_SUNDAY}, {@link DateUtils#RANGE_WEEK_MONDAY}, {@link DateUtils#RANGE_WEEK_RELATIVE}, {@link DateUtils#RANGE_WEEK_CENTER}. @return the date iterator, not null, not null. @throws NullPointerException if the date is {@code null}. @throws IllegalArgumentException if the rangeStyle is invalid.
java
src/main/java/org/apache/commons/lang3/time/DateUtils.java
1,067
[ "focus", "rangeStyle" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
contains
public static boolean contains(final boolean[] array, final boolean valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; }
Checks if the value is in the given array. <p> The method returns {@code false} if a {@code null} array is passed in. </p> @param array the array to search. @param valueToFind the value to find. @return {@code true} if the array contains the object.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
1,575
[ "array", "valueToFind" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
forMethod
public static ResourceElementResolver forMethod(String methodName, Class<?> parameterType) { return new ResourceMethodResolver(defaultResourceNameForMethod(methodName), true, methodName, parameterType); }
Create a new {@link ResourceMethodResolver} for the specified method using a resource name that infers from the method name. @param methodName the method name @param parameterType the parameter type. @return a new {@link ResourceMethodResolver} instance
java
spring-context/src/main/java/org/springframework/context/annotation/ResourceElementResolver.java
89
[ "methodName", "parameterType" ]
ResourceElementResolver
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
_unsafe_acquire_lock_with_timeout
def _unsafe_acquire_lock_with_timeout(lock: Lock, timeout: float | None = None) -> None: """Acquire a threading.Lock with timeout without automatic release (unsafe). This function acquires a lock with timeout support but does NOT automatically release it. The caller is responsible for releasing the lock explicitly. Use this only when you need manual control over lock lifetime. Args: lock: The threading.Lock object to acquire timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT. - Use _BLOCKING (-1.0) for infinite wait - Use _NON_BLOCKING (0.0) for immediate return - Use positive value for finite timeout Raises: LockTimeoutError: If the lock cannot be acquired within the timeout period Warning: This is an "unsafe" function because it does not automatically release the lock. Always call lock.release() when done, preferably in a try/finally block or use the safe _acquire_lock_with_timeout context manager instead. Example: lock = Lock() try: _unsafe_acquire_lock_with_timeout(lock, timeout=30.0) # Critical section - lock is held perform_critical_operation() finally: lock.release() # Must manually release! """ _timeout: float = timeout if timeout is not None else _DEFAULT_TIMEOUT if not lock.acquire(timeout=_timeout): raise exceptions.LockTimeoutError(lock, _timeout)
Acquire a threading.Lock with timeout without automatic release (unsafe). This function acquires a lock with timeout support but does NOT automatically release it. The caller is responsible for releasing the lock explicitly. Use this only when you need manual control over lock lifetime. Args: lock: The threading.Lock object to acquire timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT. - Use _BLOCKING (-1.0) for infinite wait - Use _NON_BLOCKING (0.0) for immediate return - Use positive value for finite timeout Raises: LockTimeoutError: If the lock cannot be acquired within the timeout period Warning: This is an "unsafe" function because it does not automatically release the lock. Always call lock.release() when done, preferably in a try/finally block or use the safe _acquire_lock_with_timeout context manager instead. Example: lock = Lock() try: _unsafe_acquire_lock_with_timeout(lock, timeout=30.0) # Critical section - lock is held perform_critical_operation() finally: lock.release() # Must manually release!
python
torch/_inductor/runtime/caching/locks.py
84
[ "lock", "timeout" ]
None
true
3
8
pytorch/pytorch
96,034
google
false
containsAll
public boolean containsAll(Iterable<? extends C> values) { if (Iterables.isEmpty(values)) { return true; } // this optimizes testing equality of two range-backed sets if (values instanceof SortedSet) { SortedSet<? extends C> set = (SortedSet<? extends C>) values; Comparator<?> comparator = set.comparator(); if (Ordering.natural().equals(comparator) || comparator == null) { return contains(set.first()) && contains(set.last()); } } for (C value : values) { if (!contains(value)) { return false; } } return true; }
Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in this range.
java
android/guava/src/com/google/common/collect/Range.java
428
[ "values" ]
true
7
6
google/guava
51,352
javadoc
false
addError
@Override public void addError(Traceable traceable, Throwable throwable) { final var span = Span.fromContextOrNull(spans.get(traceable.getSpanId())); if (span != null) { span.recordException(throwable); } }
Most of the examples of how to use the OTel API look something like this, where the span context is automatically propagated: <pre>{@code Span span = tracer.spanBuilder("parent").startSpan(); try (Scope scope = parentSpan.makeCurrent()) { // ...do some stuff, possibly creating further spans } finally { span.end(); } }</pre> This typically isn't useful in Elasticsearch, because a {@link Scope} can't be used across threads. However, if a scope is active, then the APM agent can capture additional information, so this method exists to make it possible to use scopes in the few situation where it makes sense. @param traceable provides the ID of a currently-open span for which to open a scope. @return a method to close the scope when you are finished with it.
java
modules/apm/src/main/java/org/elasticsearch/telemetry/apm/internal/tracing/APMTracer.java
348
[ "traceable", "throwable" ]
void
true
2
7.92
elastic/elasticsearch
75,680
javadoc
false
reverse
public static void reverse(final short[] array) { if (array != null) { reverse(array, 0, array.length); } }
Reverses the order of the given array. <p> This method does nothing for a {@code null} input array. </p> @param array the array to reverse, may be {@code null}.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
6,697
[ "array" ]
void
true
2
7.04
apache/commons-lang
2,896
javadoc
false
initialize_auth_manager
def initialize_auth_manager() -> BaseAuthManager: """ Initialize auth manager. * import user manager class * instantiate it and return it """ auth_manager_cls = conf.getimport(section="core", key="auth_manager") if not auth_manager_cls: raise AirflowConfigException( "No auth manager defined in the config. Please specify one using section/key [core/auth_manager]." ) return auth_manager_cls()
Initialize auth manager. * import user manager class * instantiate it and return it
python
airflow-core/src/airflow/configuration.py
874
[]
BaseAuthManager
true
2
6.72
apache/airflow
43,597
unknown
false
copyProperties
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable, String @Nullable ... ignoreProperties) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); if (editable != null) { if (!editable.isInstance(target)) { throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to editable class [" + editable.getName() + "]"); } actualEditable = editable; } PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); Set<String> ignoredProps = (ignoreProperties != null ? new HashSet<>(Arrays.asList(ignoreProperties)) : null); CachedIntrospectionResults sourceResults = (actualEditable != source.getClass() ? CachedIntrospectionResults.forClass(source.getClass()) : null); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); if (writeMethod != null && (ignoredProps == null || !ignoredProps.contains(targetPd.getName()))) { PropertyDescriptor sourcePd = (sourceResults != null ? sourceResults.getPropertyDescriptor(targetPd.getName()) : targetPd); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null) { if (isAssignable(writeMethod, readMethod, sourcePd, targetPd)) { try { ReflectionUtils.makeAccessible(readMethod); Object value = readMethod.invoke(source); ReflectionUtils.makeAccessible(writeMethod); writeMethod.invoke(target, value); } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } } } } }
Copy the property values of the given source bean into the given target bean. <p>Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored. <p>As of Spring Framework 5.3, this method honors generic type information when matching properties in the source and target objects. See the documentation for {@link #copyProperties(Object, Object)} for details. @param source the source bean @param target the target bean @param editable the class (or interface) to restrict property setting to @param ignoreProperties array of property names to ignore @throws BeansException if the copying failed @see BeanWrapper
java
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
796
[ "source", "target", "editable" ]
void
true
13
6.72
spring-projects/spring-framework
59,386
javadoc
false
processAcknowledgements
private PollResult processAcknowledgements(long currentTimeMs) { List<UnsentRequest> unsentRequests = new ArrayList<>(); AtomicBoolean isAsyncSent = new AtomicBoolean(); for (Map.Entry<Integer, Tuple<AcknowledgeRequestState>> requestStates : acknowledgeRequestStates.entrySet()) { int nodeId = requestStates.getKey(); if (!isNodeFree(nodeId)) { log.trace("Skipping acknowledge request because previous request to {} has not been processed, so acks are not sent", nodeId); } else { isAsyncSent.set(false); // First, the acknowledgements from commitAsync are sent. maybeBuildRequest(requestStates.getValue().getAsyncRequest(), currentTimeMs, true, isAsyncSent).ifPresent(unsentRequests::add); // Check to ensure we start processing commitSync/close only if there are no commitAsync requests left to process. if (isAsyncSent.get()) { if (!isNodeFree(nodeId)) { log.trace("Skipping acknowledge request because previous request to {} has not been processed, so acks are not sent", nodeId); continue; } // We try to process the close request only if we have processed the async and the sync requests for the node. if (requestStates.getValue().getSyncRequestQueue() == null) { AcknowledgeRequestState closeRequestState = requestStates.getValue().getCloseRequest(); maybeBuildRequest(closeRequestState, currentTimeMs, false, isAsyncSent).ifPresent(unsentRequests::add); } else { // Processing the acknowledgements from commitSync for (AcknowledgeRequestState acknowledgeRequestState : requestStates.getValue().getSyncRequestQueue()) { if (!isNodeFree(nodeId)) { log.trace("Skipping acknowledge request because previous request to {} has not been processed, so acks are not sent", nodeId); break; } maybeBuildRequest(acknowledgeRequestState, currentTimeMs, false, isAsyncSent).ifPresent(unsentRequests::add); } } } } } PollResult pollResult = null; if (!unsentRequests.isEmpty()) { pollResult = new PollResult(unsentRequests); } else if (checkAndRemoveCompletedAcknowledgements()) { // Return empty result until all the acknowledgement request states are processed pollResult = PollResult.EMPTY; } else if (closing) { if (!closeFuture.isDone()) { closeFuture.complete(null); } pollResult = PollResult.EMPTY; } return pollResult; }
Process acknowledgeRequestStates and prepares a list of acknowledgements to be sent in the poll(). @param currentTimeMs the current time in ms. @return the PollResult containing zero or more acknowledgements.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareConsumeRequestManager.java
348
[ "currentTimeMs" ]
PollResult
true
10
7.76
apache/kafka
31,560
javadoc
false
unescapeEcmaScript
public static final String unescapeEcmaScript(final String input) { return UNESCAPE_ECMASCRIPT.translate(input); }
Unescapes any EcmaScript literals found in the {@link String}. <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'} into a newline character, unless the {@code '\'} is preceded by another {@code '\'}.</p> @see #unescapeJava(String) @param input the {@link String} to unescape, may be null @return A new unescaped {@link String}, {@code null} if null string input @since 3.0
java
src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
696
[ "input" ]
String
true
1
6.8
apache/commons-lang
2,896
javadoc
false
bodyEmpty
static bool bodyEmpty(const ASTContext *Context, const CompoundStmt *Body) { bool Invalid = false; const StringRef Text = Lexer::getSourceText( CharSourceRange::getCharRange(Body->getLBracLoc().getLocWithOffset(1), Body->getRBracLoc()), Context->getSourceManager(), Context->getLangOpts(), &Invalid); return !Invalid && Text.ltrim(" \t\r\n").empty(); }
Returns false if the body has any non-whitespace character.
cpp
clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
201
[]
true
2
6.88
llvm/llvm-project
36,021
doxygen
false
legfromroots
def legfromroots(roots): """ Generate a Legendre series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Legendre form, where the :math:`r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Legendre form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- numpy.polynomial.polynomial.polyfromroots numpy.polynomial.chebyshev.chebfromroots numpy.polynomial.laguerre.lagfromroots numpy.polynomial.hermite.hermfromroots numpy.polynomial.hermite_e.hermefromroots Examples -------- >>> import numpy.polynomial.legendre as L >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis array([ 0. , -0.4, 0. , 0.4]) >>> j = complex(0,1) >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j]) # may vary """ return pu._fromroots(legline, legmul, roots)
Generate a Legendre series with given roots. The function returns the coefficients of the polynomial .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n), in Legendre form, where the :math:`r_n` are the roots specified in `roots`. If a zero has multiplicity n, then it must appear in `roots` n times. For instance, if 2 is a root of multiplicity three and 3 is a root of multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The roots can appear in any order. If the returned coefficients are `c`, then .. math:: p(x) = c_0 + c_1 * L_1(x) + ... + c_n * L_n(x) The coefficient of the last term is not generally 1 for monic polynomials in Legendre form. Parameters ---------- roots : array_like Sequence containing the roots. Returns ------- out : ndarray 1-D array of coefficients. If all roots are real then `out` is a real array, if some of the roots are complex, then `out` is complex even if all the coefficients in the result are real (see Examples below). See Also -------- numpy.polynomial.polynomial.polyfromroots numpy.polynomial.chebyshev.chebfromroots numpy.polynomial.laguerre.lagfromroots numpy.polynomial.hermite.hermfromroots numpy.polynomial.hermite_e.hermefromroots Examples -------- >>> import numpy.polynomial.legendre as L >>> L.legfromroots((-1,0,1)) # x^3 - x relative to the standard basis array([ 0. , -0.4, 0. , 0.4]) >>> j = complex(0,1) >>> L.legfromroots((-j,j)) # x^2 + 1 relative to the standard basis array([ 1.33333333+0.j, 0.00000000+0.j, 0.66666667+0.j]) # may vary
python
numpy/polynomial/legendre.py
267
[ "roots" ]
false
1
6.32
numpy/numpy
31,054
numpy
false
getExistingRootWebApplicationContext
private @Nullable ApplicationContext getExistingRootWebApplicationContext(ServletContext servletContext) { Object context = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (context instanceof ApplicationContext applicationContext) { return applicationContext; } return null; }
Called to run a fully configured {@link SpringApplication}. @param application the application to run @return the {@link WebApplicationContext}
java
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java
208
[ "servletContext" ]
ApplicationContext
true
2
7.28
spring-projects/spring-boot
79,428
javadoc
false
toString
public String toString() { String elrString = elr != null ? elr.stream().map(Node::toString).collect(Collectors.joining(", ")) : "N/A"; String lastKnownElrString = lastKnownElr != null ? lastKnownElr.stream().map(Node::toString).collect(Collectors.joining(", ")) : "N/A"; return "(partition=" + partition + ", leader=" + leader + ", replicas=" + replicas.stream().map(Node::toString).collect(Collectors.joining(", ")) + ", isr=" + isr.stream().map(Node::toString).collect(Collectors.joining(", ")) + ", elr=" + elrString + ", lastKnownElr=" + lastKnownElrString + ")"; }
Return the last known eligible leader replicas of the partition. Note that the ordering of the result is unspecified.
java
clients/src/main/java/org/apache/kafka/common/TopicPartitionInfo.java
117
[]
String
true
3
6.72
apache/kafka
31,560
javadoc
false
randomAlphanumeric
@Deprecated public static String randomAlphanumeric(final int count) { return secure().nextAlphanumeric(count); }
Creates a random string whose length is the number of characters specified. <p> Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9. </p> @param count the length of random string to create. @return the random string. @throws IllegalArgumentException if {@code count} &lt; 0. @deprecated Use {@link #nextAlphanumeric(int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
java
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
459
[ "count" ]
String
true
1
6.48
apache/commons-lang
2,896
javadoc
false
get_choice
def get_choice(self) -> Choice: """ Returns the chosen option based on the value of autoheuristic_use. If self.name is one of the comma separated strings in autoheuristic_use, it queries a learned heuristic to make a decision. Otherwise, it returns the fallback option. """ if not self.satisfies_precondition(): return self.fallback() if torch._inductor.config.use_autoheuristic(self.name): if self.augment_context is not None: self.context.apply_operations(self.augment_context) controller = LearnedHeuristicController( self.metadata, self.context, ) decision = controller.get_decision() if decision not in self.choices: # TODO(AlnisM): We might want to allow this in the future return self.fallback() if decision is not None: return decision return self.fallback()
Returns the chosen option based on the value of autoheuristic_use. If self.name is one of the comma separated strings in autoheuristic_use, it queries a learned heuristic to make a decision. Otherwise, it returns the fallback option.
python
torch/_inductor/autoheuristic/autoheuristic.py
113
[ "self" ]
Choice
true
6
6
pytorch/pytorch
96,034
unknown
false
getInvocationDescription
protected String getInvocationDescription(MethodInvocation invocation) { Object target = invocation.getThis(); Assert.state(target != null, "Target must not be null"); String className = target.getClass().getName(); return "method '" + invocation.getMethod().getName() + "' of class [" + className + "]"; }
Return a description for the given method invocation. @param invocation the invocation to describe @return the description
java
spring-aop/src/main/java/org/springframework/aop/interceptor/SimpleTraceInterceptor.java
78
[ "invocation" ]
String
true
1
6.4
spring-projects/spring-framework
59,386
javadoc
false
getIfAvailable
default @Nullable T getIfAvailable() throws BeansException { try { return getObject(); } catch (NoUniqueBeanDefinitionException ex) { throw ex; } catch (NoSuchBeanDefinitionException ex) { return null; } }
Return an instance (possibly shared or independent) of the object managed by this factory. @return an instance of the bean, or {@code null} if not available @throws BeansException in case of creation errors @see #getObject()
java
spring-beans/src/main/java/org/springframework/beans/factory/ObjectProvider.java
120
[]
T
true
3
7.76
spring-projects/spring-framework
59,386
javadoc
false
addExceptionFiltersMetadata
function addExceptionFiltersMetadata( ...filters: (Function | ExceptionFilter)[] ): MethodDecorator & ClassDecorator { return ( target: any, key?: string | symbol, descriptor?: TypedPropertyDescriptor<any>, ) => { const isFilterValid = <T extends Function | Record<string, any>>( filter: T, ) => filter && (isFunction(filter) || isFunction(filter.catch)); if (descriptor) { validateEach( target.constructor, filters, isFilterValid, '@UseFilters', 'filter', ); extendArrayMetadata( EXCEPTION_FILTERS_METADATA, filters, descriptor.value, ); return descriptor; } validateEach(target, filters, isFilterValid, '@UseFilters', 'filter'); extendArrayMetadata(EXCEPTION_FILTERS_METADATA, filters, target); return target; }; }
Decorator that binds exception filters to the scope of the controller or method, depending on its context. When `@UseFilters` is used at the controller level, the filter will be applied to every handler (method) in the controller. When `@UseFilters` is used at the individual handler level, the filter will apply only to that specific method. @param filters exception filter instance or class, or a list of exception filter instances or classes. @see [Exception filters](https://docs.nestjs.com/exception-filters) @usageNotes Exception filters can also be set up globally for all controllers and routes using `app.useGlobalFilters()`. [See here for details](https://docs.nestjs.com/exception-filters#binding-filters) @publicApi
typescript
packages/common/decorators/core/exception-filters.decorator.ts
32
[ "...filters" ]
true
4
6.24
nestjs/nest
73,973
jsdoc
false
_should_fetch_jwks
def _should_fetch_jwks(self) -> bool: """ Check if we need to fetch the JWKS based on the last fetch time and the refresh interval. If the JWKS URL is local, we only fetch it once. For remote JWKS URLs we fetch it based on the refresh interval if refreshing has been enabled with a minimum interval between attempts. The fetcher functions set the fetched_at timestamp to the current monotonic time when the JWKS is fetched. """ if not self.url.startswith("http"): # Fetch local JWKS only if not already loaded # This could be improved in future by looking at mtime of file. return not self._jwks # For remote fetches we check if the JWKS is not loaded (fetched_at = 0) or if the last fetch was more than # refresh_interval_secs ago and the last fetch attempt was more than refresh_retry_interval_secs ago now = time.monotonic() return self.refresh_jwks and ( not self._jwks or ( self.fetched_at == 0 or ( now - self.fetched_at > self.refresh_interval_secs and now - self.last_fetch_attempt_at > self.refresh_retry_interval_secs ) ) )
Check if we need to fetch the JWKS based on the last fetch time and the refresh interval. If the JWKS URL is local, we only fetch it once. For remote JWKS URLs we fetch it based on the refresh interval if refreshing has been enabled with a minimum interval between attempts. The fetcher functions set the fetched_at timestamp to the current monotonic time when the JWKS is fetched.
python
airflow-core/src/airflow/api_fastapi/auth/tokens.py
174
[ "self" ]
bool
true
6
6
apache/airflow
43,597
unknown
false