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
escape
@Override protected final char @Nullable [] escape(char c) { if (c < replacementsLength) { char[] chars = replacements[c]; if (chars != null) { return chars; } } if (c >= safeMin && c <= safeMax) { return null; } return escapeUnsafe(c); }
Escapes a single character using the replacement array and safe range values. If the given character does not have an explicit replacement and lies outside the safe range then {@link #escapeUnsafe} is called. @return the replacement characters, or {@code null} if no escaping was required
java
android/guava/src/com/google/common/escape/ArrayBasedCharEscaper.java
122
[ "c" ]
true
5
6.56
google/guava
51,352
javadoc
false
set_dag_run_state_to_failed
def set_dag_run_state_to_failed( *, dag: SerializedDAG, run_id: str | None = None, commit: bool = False, session: SASession = NEW_SESSION, ) -> list[TaskInstance]: """ Set the dag run's state to failed. Set for a specific logical date and its task instances to failed. :param dag: the DAG of which to alter state :param run_id: the DAG run_id to start looking from :param commit: commit DAG and tasks to be altered to the database :param session: database session :return: If commit is true, list of tasks that have been updated, otherwise list of tasks that will be updated """ if not dag: return [] if not run_id: raise ValueError(f"Invalid dag_run_id: {run_id}") running_states = ( TaskInstanceState.RUNNING, TaskInstanceState.DEFERRED, TaskInstanceState.UP_FOR_RESCHEDULE, ) # Mark only RUNNING task instances. task_ids = [task.task_id for task in dag.tasks] running_tis: list[TaskInstance] = list( session.scalars( select(TaskInstance).where( TaskInstance.dag_id == dag.dag_id, TaskInstance.run_id == run_id, TaskInstance.task_id.in_(task_ids), TaskInstance.state.in_(running_states), ) ).all() ) # Do not kill teardown tasks task_ids_of_running_tis = {ti.task_id for ti in running_tis if not dag.task_dict[ti.task_id].is_teardown} def _set_runing_task(task: Operator) -> Operator: task.dag = dag return task running_tasks = [_set_runing_task(task) for task in dag.tasks if task.task_id in task_ids_of_running_tis] # Mark non-finished tasks as SKIPPED. pending_tis: list[TaskInstance] = list( session.scalars( select(TaskInstance).filter( TaskInstance.dag_id == dag.dag_id, TaskInstance.run_id == run_id, or_( TaskInstance.state.is_(None), and_( TaskInstance.state.not_in(State.finished), TaskInstance.state.not_in(running_states), ), ), ) ).all() ) # Do not skip teardown tasks pending_normal_tis = [ti for ti in pending_tis if not dag.task_dict[ti.task_id].is_teardown] if commit: for ti in pending_normal_tis: ti.set_state(TaskInstanceState.SKIPPED) # Mark the dag run to failed if there is no pending teardown (else this would not be scheduled later). if not any(dag.task_dict[ti.task_id].is_teardown for ti in (running_tis + pending_tis)): _set_dag_run_state(dag.dag_id, run_id, DagRunState.FAILED, session) return pending_normal_tis + set_state( tasks=running_tasks, run_id=run_id, state=TaskInstanceState.FAILED, commit=commit, session=session, )
Set the dag run's state to failed. Set for a specific logical date and its task instances to failed. :param dag: the DAG of which to alter state :param run_id: the DAG run_id to start looking from :param commit: commit DAG and tasks to be altered to the database :param session: database session :return: If commit is true, list of tasks that have been updated, otherwise list of tasks that will be updated
python
airflow-core/src/airflow/api/common/mark_tasks.py
267
[ "dag", "run_id", "commit", "session" ]
list[TaskInstance]
true
6
8
apache/airflow
43,597
sphinx
false
findMainClass
public static @Nullable String findMainClass(File rootDirectory) throws IOException { return doWithMainClasses(rootDirectory, MainClass::getName); }
Find the main class from a given directory. @param rootDirectory the root directory to search @return the main class or {@code null} @throws IOException if the directory cannot be read
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java
87
[ "rootDirectory" ]
String
true
1
6.48
spring-projects/spring-boot
79,428
javadoc
false
upper
def upper(a): """ Return an array with the elements converted to uppercase. Calls :meth:`str.upper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype Input array. Returns ------- out : ndarray Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype, depending on input types See Also -------- str.upper Examples -------- >>> import numpy as np >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='<U5') >>> np.strings.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='<U5') """ a_arr = np.asarray(a) return _vec_string(a_arr, a_arr.dtype, 'upper')
Return an array with the elements converted to uppercase. Calls :meth:`str.upper` element-wise. For 8-bit strings, this method is locale-dependent. Parameters ---------- a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype Input array. Returns ------- out : ndarray Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype, depending on input types See Also -------- str.upper Examples -------- >>> import numpy as np >>> c = np.array(['a1b c', '1bca', 'bca1']); c array(['a1b c', '1bca', 'bca1'], dtype='<U5') >>> np.strings.upper(c) array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
python
numpy/_core/strings.py
1,086
[ "a" ]
false
1
6
numpy/numpy
31,054
numpy
false
toString
@Override public String toString() { return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; }
Gets a debugging string version of this formatter. @return a debug string.
java
src/main/java/org/apache/commons/lang3/time/FastDateFormat.java
632
[]
String
true
1
6.96
apache/commons-lang
2,896
javadoc
false
getPropertyName
private String getPropertyName(VariableElement parameter, String fallback) { AnnotationMirror nameAnnotation = this.environment.getNameAnnotation(parameter); if (nameAnnotation != null) { return this.environment.getAnnotationElementStringValue(nameAnnotation, "value"); } return fallback; }
Return the {@link PropertyDescriptor} instances that are valid candidates for the specified {@link TypeElement type} based on the specified {@link ExecutableElement factory method}, if any. @param type the target type @param factoryMethod the method that triggered the metadata for that {@code type} or {@code null} @return the candidate properties for metadata generation
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptorResolver.java
106
[ "parameter", "fallback" ]
String
true
2
7.28
spring-projects/spring-boot
79,428
javadoc
false
shouldProxyTargetClass
protected boolean shouldProxyTargetClass(Class<?> beanClass, @Nullable String beanName) { return (this.beanFactory instanceof ConfigurableListableBeanFactory clbf && AutoProxyUtils.shouldProxyTargetClass(clbf, beanName)); }
Determine whether the given bean should be proxied with its target class rather than its interfaces. <p>Checks the {@link AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE "preserveTargetClass" attribute} of the corresponding bean definition. @param beanClass the class of the bean @param beanName the name of the bean @return whether the given bean should be proxied with its target class @see AutoProxyUtils#shouldProxyTargetClass
java
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java
505
[ "beanClass", "beanName" ]
true
2
7.2
spring-projects/spring-framework
59,386
javadoc
false
arrayIncludes
function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; }
A specialized version of `_.includes` for arrays without support for specifying an index to search from. @private @param {Array} [array] The array to inspect. @param {*} target The value to search for. @returns {boolean} Returns `true` if `target` is found, else `false`.
javascript
lodash.js
612
[ "array", "value" ]
false
3
6.16
lodash/lodash
61,490
jsdoc
false
toString
@Override public String toString() { return set.toString(); }
Gets a string representation of the set. @return string representation of the set
java
src/main/java/org/apache/commons/lang3/CharSet.java
278
[]
String
true
1
6.8
apache/commons-lang
2,896
javadoc
false
getNameLabelValue
function getNameLabelValue(promQuery: string, tokens: Array<string | Prism.Token>): string { let nameLabelValue = ''; for (const token of tokens) { if (typeof token === 'string') { nameLabelValue = token; break; } } return nameLabelValue; }
Checks if an error is a cancelled request error. Used to avoid logging cancelled request errors. @param {unknown} error - Error to check @returns {boolean} True if the error is a cancelled request error
typescript
packages/grafana-prometheus/src/language_provider.ts
407
[ "promQuery", "tokens" ]
true
2
7.04
grafana/grafana
71,362
jsdoc
false
buildFlattenedMap
@SuppressWarnings({"rawtypes", "unchecked"}) private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, @Nullable String path) { source.forEach((key, value) -> { if (StringUtils.hasText(path)) { if (key.startsWith("[")) { key = path + key; } else { key = path + '.' + key; } } if (value instanceof String) { result.put(key, value); } else if (value instanceof Map map) { // Need a compound key buildFlattenedMap(result, map, key); } else if (value instanceof Collection collection) { // Need a compound key if (collection.isEmpty()) { result.put(key, ""); } else { int count = 0; for (Object object : collection) { buildFlattenedMap(result, Collections.singletonMap( "[" + (count++) + "]", object), key); } } } else { result.put(key, (value != null ? value : "")); } }); }
Return a flattened version of the given map, recursively following any nested Map or Collection values. Entries from the resulting map retain the same order as the source. When called with the Map from a {@link MatchCallback} the result will contain the same values as the {@link MatchCallback} Properties. @param source the source map @return a flattened map @since 4.1.3
java
spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.java
312
[ "result", "source", "path" ]
void
true
8
8.24
spring-projects/spring-framework
59,386
javadoc
false
tryChangeModuleExportsObject
function tryChangeModuleExportsObject(object: ObjectLiteralExpression, useSitesToUnqualify: Map<Node, Node> | undefined): [readonly Statement[], ModuleExportsChanged] | undefined { const statements = mapAllOrFail(object.properties, prop => { switch (prop.kind) { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. // falls through case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.SpreadAssignment: return undefined; case SyntaxKind.PropertyAssignment: return !isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer, useSitesToUnqualify); case SyntaxKind.MethodDeclaration: return !isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [factory.createToken(SyntaxKind.ExportKeyword)], prop, useSitesToUnqualify); default: Debug.assertNever(prop, `Convert to ES6 got invalid prop kind ${(prop as ObjectLiteralElementLike).kind}`); } }); return statements && [statements, false]; }
Convert `module.exports = { ... }` to individual exports.. We can't always do this if the module has interesting members -- then it will be a default export instead.
typescript
src/services/codefixes/convertToEsModule.ts
349
[ "object", "useSitesToUnqualify" ]
true
4
6
microsoft/TypeScript
107,154
jsdoc
false
estimateSizeInBytes
public static int estimateSizeInBytes(byte magic, long baseOffset, CompressionType compressionType, Iterable<Record> records) { int size = 0; if (magic <= RecordBatch.MAGIC_VALUE_V1) { for (Record record : records) size += Records.LOG_OVERHEAD + LegacyRecord.recordSize(magic, record.key(), record.value()); } else { size = DefaultRecordBatch.sizeInBytes(baseOffset, records); } return estimateCompressedSizeInBytes(size, compressionType); }
Get an iterator over the deep records. @return An iterator over the records
java
clients/src/main/java/org/apache/kafka/common/record/AbstractRecords.java
93
[ "magic", "baseOffset", "compressionType", "records" ]
true
2
6.88
apache/kafka
31,560
javadoc
false
nextBits
public int nextBits(final int bits) { if (bits > MAX_BITS || bits <= 0) { throw new IllegalArgumentException("number of bits must be between 1 and " + MAX_BITS); } int result = 0; int generatedBits = 0; // number of generated bits up to now while (generatedBits < bits) { // Check if we need to refill the cache // Convert bitIndex to byte index by dividing by 8 (right shift by 3) if (bitIndex >> 3 >= cache.length) { // We exhausted the number of bits in the cache // This should only happen if the bitIndex is exactly matching the cache length assert bitIndex == cache.length * BITS_PER_BYTE; random.nextBytes(cache); bitIndex = 0; } // Calculate how many bits we can extract from the current byte // 1. Get current position within byte (0-7) using bitIndex & 0x7 // 2. Calculate remaining bits in byte: 8 - (position within byte) // 3. Take minimum of remaining bits in byte and bits still needed final int generatedBitsInIteration = Math.min( BITS_PER_BYTE - (bitIndex & BIT_INDEX_MASK), bits - generatedBits); // Shift existing result left to make room for new bits result = result << generatedBitsInIteration; // Extract and append new bits: // 1. Get byte from cache (bitIndex >> 3 converts bit index to byte index) // 2. Shift right by bit position within byte (bitIndex & 0x7) // 3. Mask to keep only the bits we want ((1 << generatedBitsInIteration) - 1) result |= cache[bitIndex >> 3] >> (bitIndex & BIT_INDEX_MASK) & ((1 << generatedBitsInIteration) - 1); // Update counters generatedBits += generatedBitsInIteration; bitIndex += generatedBitsInIteration; } return result; }
Generates a random integer with the specified number of bits. <p>This method efficiently generates random bits by using a byte cache and bit manipulation: <ul> <li>Uses a byte array cache to avoid frequent calls to the underlying random number generator</li> <li>Extracts bits from each byte using bit shifting and masking</li> <li>Handles partial bytes to avoid wasting random bits</li> <li>Accumulates bits until the requested number is reached</li> </ul> </p> @param bits number of bits to generate, MUST be between 1 and 32 (inclusive) @return random integer containing exactly the requested number of random bits @throws IllegalArgumentException if bits is not between 1 and 32
java
src/main/java/org/apache/commons/lang3/CachedRandomBits.java
101
[ "bits" ]
true
5
7.76
apache/commons-lang
2,896
javadoc
false
main
def main() -> int: """Start celery umbrella command. This function is the main entrypoint for the CLI. :return: The exit code of the CLI. """ return celery(auto_envvar_prefix="CELERY")
Start celery umbrella command. This function is the main entrypoint for the CLI. :return: The exit code of the CLI.
python
celery/bin/celery.py
220
[]
int
true
1
7.04
celery/celery
27,741
unknown
false
createObjectPool
protected ObjectPool createObjectPool() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(getMaxSize()); config.setMaxIdle(getMaxIdle()); config.setMinIdle(getMinIdle()); config.setMaxWaitMillis(getMaxWait()); config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis()); config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis()); config.setBlockWhenExhausted(isBlockWhenExhausted()); return new GenericObjectPool(this, config); }
Subclasses can override this if they want to return a specific Commons pool. They should apply any configuration properties to the pool here. <p>Default is a GenericObjectPool instance with the given pool size. @return an empty Commons {@code ObjectPool}. @see GenericObjectPool @see #setMaxSize
java
spring-aop/src/main/java/org/springframework/aop/target/CommonsPool2TargetSource.java
213
[]
ObjectPool
true
1
6.72
spring-projects/spring-framework
59,386
javadoc
false
readField
public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException { Objects.requireNonNull(field, "field"); return setAccessible(field, forceAccess).get(target); }
Reads a {@link Field}. @param field the field to use. @param target the object to call on, may be {@code null} for {@code static} fields. @param forceAccess whether to break scope restrictions using the {@link AccessibleObject#setAccessible(boolean)} method. @return the field value @throws NullPointerException if the field is {@code null}. @throws IllegalAccessException if the field is not made accessible. @throws SecurityException if an underlying accessible object's method denies the request. @see SecurityManager#checkPermission @throws SecurityException if an underlying accessible object's method denies the request. @see SecurityManager#checkPermission
java
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
400
[ "field", "target", "forceAccess" ]
Object
true
1
6.16
apache/commons-lang
2,896
javadoc
false
doStart
private void doStart(String beanName, Lifecycle bean) { if (logger.isTraceEnabled()) { logger.trace("Starting bean '" + beanName + "' of type [" + bean.getClass().getName() + "]"); } try { bean.start(); } catch (Throwable ex) { throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex); } if (logger.isDebugEnabled()) { logger.debug("Successfully started bean '" + beanName + "'"); } }
Start the specified bean as part of the given set of Lifecycle beans, making sure that any beans that it depends on are started first. @param lifecycleBeans a Map with bean name as key and Lifecycle instance as value @param beanName the name of the bean to start
java
spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java
415
[ "beanName", "bean" ]
void
true
4
6.72
spring-projects/spring-framework
59,386
javadoc
false
build
abstract Map<String, List<TopicPartition>> build();
Builds the assignment. @return Map from each member to the list of partitions assigned to them.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractStickyAssignor.java
557
[]
true
1
6.8
apache/kafka
31,560
javadoc
false
_enum_to_json
def _enum_to_json(cls, enum_value: Optional[Enum]) -> Optional[str]: """Convert enum value to JSON string. Args: enum_value: Enum value Returns: Optional[str]: JSON string representation or None """ if enum_value is None: return None result = { "type": enum_value.__class__.__name__, "name": enum_value.name, } return json.dumps(result)
Convert enum value to JSON string. Args: enum_value: Enum value Returns: Optional[str]: JSON string representation or None
python
torch/_inductor/codegen/cuda/serialization.py
462
[ "cls", "enum_value" ]
Optional[str]
true
2
7.44
pytorch/pytorch
96,034
google
false
bindSwitchStatement
function bindSwitchStatement(node: SwitchStatement): void { const postSwitchLabel = createBranchLabel(); bind(node.expression); const saveBreakTarget = currentBreakTarget; const savePreSwitchCaseFlow = preSwitchCaseFlow; currentBreakTarget = postSwitchLabel; preSwitchCaseFlow = currentFlow; bind(node.caseBlock); addAntecedent(postSwitchLabel, currentFlow); const hasDefault = forEach(node.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause); // We mark a switch statement as possibly exhaustive if it has no default clause and if all // case clauses have unreachable end points (e.g. they all return). Note, we no longer need // this property in control flow analysis, it's there only for backwards compatibility. node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedent; if (!hasDefault) { addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); } currentBreakTarget = saveBreakTarget; preSwitchCaseFlow = savePreSwitchCaseFlow; currentFlow = finishFlowLabel(postSwitchLabel); }
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @param symbolTable - The symbol table which node will be added to. @param parent - node's parent declaration. @param node - The declaration to be added to the symbol table @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
typescript
src/compiler/binder.ts
1,716
[ "node" ]
true
3
6.88
microsoft/TypeScript
107,154
jsdoc
false
createNotWritablePropertyException
@Override protected NotWritablePropertyException createNotWritablePropertyException(String propertyName) { PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException(getRootClass(), getNestedPath() + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); }
Convert the given value for the specified property to the latter's type. <p>This method is only intended for optimizations in a BeanFactory. Use the {@code convertIfNecessary} methods for programmatic conversion. @param value the value to convert @param propertyName the target property (note that nested or indexed properties are not supported here) @return the new value, possibly the result of type conversion @throws TypeMismatchException if type conversion failed
java
spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
202
[ "propertyName" ]
NotWritablePropertyException
true
1
6.24
spring-projects/spring-framework
59,386
javadoc
false
createIfAbsent
public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init) throws ConcurrentException { if (map == null || init == null) { return null; } final V value = map.get(key); if (value == null) { return putIfAbsent(map, key, init.get()); } return value; }
Checks if a concurrent map contains a key and creates a corresponding value if not. This method first checks the presence of the key in the given map. If it is already contained, its value is returned. Otherwise the {@code get()} method of the passed in {@link ConcurrentInitializer} is called. With the resulting object {@link #putIfAbsent(ConcurrentMap, Object, Object)} is called. This handles the case that in the meantime another thread has added the key to the map. Both the map and the initializer can be <strong>null</strong>; in this case this method simply returns <strong>null</strong>. @param <K> the type of the keys of the map @param <V> the type of the values of the map @param map the map to be modified @param key the key of the value to be added @param init the {@link ConcurrentInitializer} for creating the value @return the value stored in the map after this operation; this may or may not be the object created by the {@link ConcurrentInitializer} @throws ConcurrentException if the initializer throws an exception
java
src/main/java/org/apache/commons/lang3/concurrent/ConcurrentUtils.java
151
[ "map", "key", "init" ]
V
true
4
7.92
apache/commons-lang
2,896
javadoc
false
createOffsetFetchRequest
OffsetFetchRequestState createOffsetFetchRequest(final Set<TopicPartition> partitions, final long deadlineMs) { return jitter.isPresent() ? new OffsetFetchRequestState( partitions, retryBackoffMs, retryBackoffMaxMs, deadlineMs, jitter.getAsDouble(), memberInfo) : new OffsetFetchRequestState( partitions, retryBackoffMs, retryBackoffMaxMs, deadlineMs, memberInfo); }
Enqueue a request to fetch committed offsets, that will be sent on the next call to {@link #poll(long)}. @param partitions Partitions to fetch offsets for. @param deadlineMs Time until which the request should be retried if it fails with expected retriable errors. @return Future that will complete when a successful response is received, or the request fails and cannot be retried. Note that the request is retried whenever it fails with retriable expected error and the retry time hasn't expired.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
526
[ "partitions", "deadlineMs" ]
OffsetFetchRequestState
true
2
8.08
apache/kafka
31,560
javadoc
false
isAfterRange
public boolean isAfterRange(final Range<T> otherRange) { if (otherRange == null) { return false; } return isAfter(otherRange.maximum); }
Checks whether this range is completely after the specified range. <p>This method may fail if the ranges have two different comparators or element types.</p> @param otherRange the range to check, null returns false. @return true if this range is completely after the specified range. @throws RuntimeException if ranges cannot be compared.
java
src/main/java/org/apache/commons/lang3/Range.java
435
[ "otherRange" ]
true
2
8.08
apache/commons-lang
2,896
javadoc
false
endLabeledBlock
function endLabeledBlock() { Debug.assert(peekBlockKind() === CodeBlockKind.Labeled); const block = endBlock() as LabeledBlock; if (!block.isScript) { markLabel(block.breakLabel); } }
Ends a code block that supports `break` statements that are defined in generated code.
typescript
src/compiler/transformers/generators.ts
2,407
[]
false
2
6.24
microsoft/TypeScript
107,154
jsdoc
false
size
@Override public int size() { return valueList.size(); }
A builder for creating immutable sorted map instances, especially {@code public static final} maps ("constant maps"). Example: {@snippet : static final ImmutableSortedMap<Integer, String> INT_TO_WORD = new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural()) .put(1, "one") .put(2, "two") .put(3, "three") .buildOrThrow(); } <p>For <i>small</i> immutable sorted maps, the {@code ImmutableSortedMap.of()} methods are even more convenient. <p>Builder instances can be reused - it is safe to call {@link #buildOrThrow} multiple times to build multiple maps in series. Each map is a superset of the maps created before it. @since 2.0
java
android/guava/src/com/google/common/collect/ImmutableSortedMap.java
828
[]
true
1
6.56
google/guava
51,352
javadoc
false
remove
public static boolean[] remove(final boolean[] array, final int index) { return (boolean[]) remove((Object) array, index); }
Removes the element at the specified position from the specified array. All subsequent elements are shifted to the left (subtracts one from their indices). <p> This method returns a new array with the same elements of the input array except the element on the specified position. The component type of the returned array is always the same as that of the input array. </p> <p> If the input array is {@code null}, an IndexOutOfBoundsException will be thrown, because in that case no valid index can be specified. </p> <pre> ArrayUtils.remove([true], 0) = [] ArrayUtils.remove([true, false], 0) = [false] ArrayUtils.remove([true, false], 1) = [true] ArrayUtils.remove([true, true, false], 1) = [true, false] </pre> @param array the array to remove the element from, may not be {@code null}. @param index the position of the element to be removed. @return A new array containing the existing elements except the element at the specified position. @throws IndexOutOfBoundsException if the index is out of range (index &lt; 0 || index &gt;= array.length), or if the array is {@code null}. @since 2.1
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
4,683
[ "array", "index" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
socketDescription
public String socketDescription() { Socket socket = transportLayer.socketChannel().socket(); if (socket.getInetAddress() == null) return socket.getLocalAddress().toString(); return socket.getInetAddress().toString(); }
Returns the port to which this channel's socket is connected or 0 if the socket has never been connected. If the socket was connected prior to being closed, then this method will continue to return the connected port number after the socket is closed.
java
clients/src/main/java/org/apache/kafka/common/network/KafkaChannel.java
382
[]
String
true
2
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 { boolean isFactoryType = (type != null && FactoryBean.class.isAssignableFrom(type)); Map<String, T> matches = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : this.beans.entrySet()) { String beanName = entry.getKey(); Object beanInstance = entry.getValue(); if (beanInstance instanceof FactoryBean<?> factoryBean && !isFactoryType) { if ((includeNonSingletons || factoryBean.isSingleton()) && (type == null || isTypeMatch(factoryBean, type))) { matches.put(beanName, getBean(beanName, type)); } } else { if (type == null || type.isInstance(beanInstance)) { if (isFactoryType) { beanName = FACTORY_BEAN_PREFIX + beanName; } matches.put(beanName, (T) beanInstance); } } } return matches; }
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
412
[ "type", "includeNonSingletons", "allowEagerInit" ]
true
11
6.88
spring-projects/spring-framework
59,386
javadoc
false
write
void write(@Nullable Object instance, JsonValueWriter valueWriter) { T extracted = this.valueExtractor.extract(instance); if (ValueExtractor.skip(extracted)) { return; } Object value = getValueToWrite(extracted, valueWriter); valueWriter.write(this.name, value); }
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
648
[ "instance", "valueWriter" ]
void
true
2
6.72
spring-projects/spring-boot
79,428
javadoc
false
removeDuplicates
static <K, V> Entry<K, V>[] removeDuplicates( Entry<K, V>[] entries, int n, int newN, IdentityHashMap<Entry<K, V>, Boolean> duplicates) { Entry<K, V>[] newEntries = createEntryArray(newN); for (int in = 0, out = 0; in < n; in++) { Entry<K, V> entry = entries[in]; Boolean status = duplicates.get(entry); // null=>not dup'd; true=>dup'd, first; false=>dup'd, not first if (status != null) { if (status) { duplicates.put(entry, false); } else { continue; // delete this entry; we already copied an earlier one for the same key } } newEntries[out++] = entry; } return newEntries; }
Constructs a new entry array where each duplicated key from the original appears only once, at its first position but with its final value. The {@code duplicates} map is modified. @param entries the original array of entries including duplicates @param n the number of valid entries in {@code entries} @param newN the expected number of entries once duplicates are removed @param duplicates a map of canonical {@link Entry} objects for each duplicate key. This map will be updated by the method, setting each value to false as soon as the {@link Entry} has been included in the new entry array. @return an array of {@code newN} entries where no key appears more than once.
java
guava/src/com/google/common/collect/RegularImmutableMap.java
185
[ "entries", "n", "newN", "duplicates" ]
true
4
8.08
google/guava
51,352
javadoc
false
get_kernel_binary_remote_cache
def get_kernel_binary_remote_cache( caching_enabled: bool, caching_available: bool ) -> Any | None: """ Get or create the class instance of the CUTLASSKernelBinaryRemoteCache. Args: caching_enabled: Whether binary remote caching is enabled caching_available: Whether we're in fbcode environment Returns: CUTLASSKernelBinaryRemoteCache: The class instance of the kernel binary remote cache """ if not caching_enabled: log.debug("CUTLASSKernelBinaryRemoteCache not requested, skipping") return None if not caching_available: return None try: from torch._inductor.fb.kernel_binary_remote_cache import ( CUTLASSKernelBinaryRemoteCache, ) return CUTLASSKernelBinaryRemoteCache() except ImportError: log.debug( "CUTLASSKernelBinaryRemoteCache not available, remote caching disabled" ) return None
Get or create the class instance of the CUTLASSKernelBinaryRemoteCache. Args: caching_enabled: Whether binary remote caching is enabled caching_available: Whether we're in fbcode environment Returns: CUTLASSKernelBinaryRemoteCache: The class instance of the kernel binary remote cache
python
torch/_inductor/codecache.py
4,071
[ "caching_enabled", "caching_available" ]
Any | None
true
3
7.28
pytorch/pytorch
96,034
google
false
deleteIfPossible
private void deleteIfPossible(Path local, Throwable cause) { try { Files.delete(local); } catch (IOException ex) { cause.addSuppressed(ex); } }
Create a new {@link UrlJarFile} or {@link UrlNestedJarFile} instance. @param jarFileUrl the jar file URL @param closeAction the action to call when the file is closed @return a new {@link JarFile} instance @throws IOException on I/O error
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/UrlJarFileFactory.java
110
[ "local", "cause" ]
void
true
2
7.92
spring-projects/spring-boot
79,428
javadoc
false
alterClientQuotas
default AlterClientQuotasResult alterClientQuotas(Collection<ClientQuotaAlteration> entries) { return alterClientQuotas(entries, new AlterClientQuotasOptions()); }
Alters client quota configurations with the specified alterations. <p> This is a convenience method for {@link #alterClientQuotas(Collection, AlterClientQuotasOptions)} with default options. See the overload for more details. <p> This operation is supported by brokers with version 2.6.0 or higher. @param entries the alterations to perform @return the AlterClientQuotasResult containing the result
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
1,396
[ "entries" ]
AlterClientQuotasResult
true
1
6.16
apache/kafka
31,560
javadoc
false
scanIdentifierParts
function scanIdentifierParts(): string { let result = ""; let start = pos; while (pos < end) { let ch = codePointUnchecked(pos); if (isIdentifierPart(ch, languageVersion)) { pos += charSize(ch); } else if (ch === CharacterCodes.backslash) { ch = peekExtendedUnicodeEscape(); if (ch >= 0 && isIdentifierPart(ch, languageVersion)) { result += scanExtendedUnicodeEscape(/*shouldEmitInvalidEscapeError*/ true); start = pos; continue; } ch = peekUnicodeEscape(); if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) { break; } tokenFlags |= TokenFlags.UnicodeEscape; result += text.substring(start, pos); result += utf16EncodeAsString(ch); // Valid Unicode escape is always six characters pos += 6; start = pos; } else { break; } } result += text.substring(start, pos); return result; }
Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or a literal component of a TemplateExpression.
typescript
src/compiler/scanner.ts
1,781
[]
true
10
6.08
microsoft/TypeScript
107,154
jsdoc
false
delete_cluster
def delete_cluster(self, name: str) -> dict: """ Delete the Amazon EKS Cluster control plane. .. seealso:: - :external+boto3:py:meth:`EKS.Client.delete_cluster` :param name: The name of the cluster to delete. :return: Returns descriptive information about the deleted EKS Cluster. """ eks_client = self.conn response = eks_client.delete_cluster(name=name) self.log.info("Deleted Amazon EKS cluster with the name %s.", response.get("cluster").get("name")) return response
Delete the Amazon EKS Cluster control plane. .. seealso:: - :external+boto3:py:meth:`EKS.Client.delete_cluster` :param name: The name of the cluster to delete. :return: Returns descriptive information about the deleted EKS Cluster.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/eks.py
248
[ "self", "name" ]
dict
true
1
6.24
apache/airflow
43,597
sphinx
false
incrementAndGet
public double incrementAndGet() { value++; return value; }
Increments this instance's value by 1; this method returns the value associated with the instance immediately after the increment operation. This method is not thread safe. @return the value associated with the instance after it is incremented. @since 3.5
java
src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java
309
[]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
textCharacters
@Override public char[] textCharacters() throws IOException { try { return parser.getTextCharacters(); } catch (IOException e) { throw handleParserException(e); } }
Handle parser exception depending on type. This converts known exceptions to XContentParseException and rethrows them.
java
libs/x-content/impl/src/main/java/org/elasticsearch/xcontent/provider/json/JsonXContentParser.java
218
[]
true
2
6.08
elastic/elasticsearch
75,680
javadoc
false
getDigits
public static String getDigits(final String str) { if (isEmpty(str)) { return str; } final int len = str.length(); final char[] buffer = new char[len]; int count = 0; for (int i = 0; i < len; i++) { final char tempChar = str.charAt(i); if (Character.isDigit(tempChar)) { buffer[count++] = tempChar; } } return new String(buffer, 0, count); }
Checks if a String {@code str} contains Unicode digits, if yes then concatenate all the digits in {@code str} and return it as a String. <p> An empty ("") String will be returned if no digits found in {@code str}. </p> <pre> StringUtils.getDigits(null) = null StringUtils.getDigits("") = "" StringUtils.getDigits("abc") = "" StringUtils.getDigits("1000$") = "1000" StringUtils.getDigits("1123~45") = "112345" StringUtils.getDigits("(541) 754-3010") = "5417543010" StringUtils.getDigits("\u0967\u0968\u0969") = "\u0967\u0968\u0969" </pre> @param str the String to extract digits from, may be null. @return String with only digits, or an empty ("") String if no digits found, or {@code null} String if {@code str} is null. @since 3.6
java
src/main/java/org/apache/commons/lang3/StringUtils.java
2,042
[ "str" ]
String
true
4
7.76
apache/commons-lang
2,896
javadoc
false
get_variable
def get_variable( self, key: str, team_name: str | None = None, session: Session = NEW_SESSION ) -> str | None: """ Get Airflow Variable from Metadata DB. :param key: Variable Key :param team_name: Team name associated to the task trying to access the variable (if any) :param session: SQLAlchemy Session :return: Variable Value """ from airflow.models import Variable var_value = session.scalar( select(Variable) .where(Variable.key == key, or_(Variable.team_name == team_name, Variable.team_name.is_(None))) .limit(1) ) session.expunge_all() if var_value: return var_value.val return None
Get Airflow Variable from Metadata DB. :param key: Variable Key :param team_name: Team name associated to the task trying to access the variable (if any) :param session: SQLAlchemy Session :return: Variable Value
python
airflow-core/src/airflow/secrets/metastore.py
54
[ "self", "key", "team_name", "session" ]
str | None
true
2
7.92
apache/airflow
43,597
sphinx
false
createFileIfNecessary
private void createFileIfNecessary(File file) throws IOException { if (file.exists()) { return; } File parent = file.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { throw new IllegalStateException( "Cannot create parent directory for '" + this.outputFile.getAbsolutePath() + "'"); } if (!file.createNewFile()) { throw new IllegalStateException("Cannot create target file '" + this.outputFile.getAbsolutePath() + "'"); } }
Creates a new {@code BuildPropertiesWriter} that will write to the given {@code outputFile}. @param outputFile the output file
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/BuildPropertiesWriter.java
62
[ "file" ]
void
true
5
6.4
spring-projects/spring-boot
79,428
javadoc
false
secure
public static RandomStringUtils secure() { return SECURE; }
Gets the singleton instance based on {@link SecureRandom#SecureRandom()} which uses a secure random number generator (RNG) implementing the default random number algorithm. <p> The method {@link SecureRandom#SecureRandom()} is called on-demand. </p> @return the singleton instance based on {@link SecureRandom#SecureRandom()}. @see SecureRandom#SecureRandom() @since 3.16.0
java
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
639
[]
RandomStringUtils
true
1
6.16
apache/commons-lang
2,896
javadoc
false
shouldGenerateIdAsFallback
protected boolean shouldGenerateIdAsFallback() { return false; }
Should an ID be generated instead if the passed in {@link Element} does not specify an "id" attribute explicitly? <p>Disabled by default; subclasses can override this to enable ID generation as fallback: The parser will first check for an "id" attribute in this case, only falling back to a generated ID if no value was specified. @return whether the parser should generate an id if no id was specified
java
spring-beans/src/main/java/org/springframework/beans/factory/xml/AbstractBeanDefinitionParser.java
174
[]
true
1
6.8
spring-projects/spring-framework
59,386
javadoc
false
getDefaultOutcome
protected ConditionOutcome getDefaultOutcome(ConditionContext context, AnnotationAttributes annotationAttributes) { boolean match = Boolean .parseBoolean(context.getEnvironment().getProperty(this.prefix + "defaults.enabled", "true")); return new ConditionOutcome(match, ConditionMessage.forCondition(this.annotationType) .because(this.prefix + "defaults.enabled is considered " + match)); }
Return the default outcome that should be used if property is not set. By default this method will use the {@code <prefix>.defaults.enabled} property, matching if it is {@code true} or if it is not configured. @param context the condition context @param annotationAttributes the annotation attributes @return the default outcome @since 2.6.0
java
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/OnEndpointElementCondition.java
84
[ "context", "annotationAttributes" ]
ConditionOutcome
true
1
6.72
spring-projects/spring-boot
79,428
javadoc
false
chop
public ConfigurationPropertyName chop(int size) { if (size >= getNumberOfElements()) { return this; } return new ConfigurationPropertyName(this.elements.chop(size)); }
Return a new {@link ConfigurationPropertyName} by chopping this name to the given {@code size}. For example, {@code chop(1)} on the name {@code foo.bar} will return {@code foo}. @param size the size to chop @return the chopped name
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
251
[ "size" ]
ConfigurationPropertyName
true
2
8.08
spring-projects/spring-boot
79,428
javadoc
false
findLogger
private @Nullable LoggerConfig findLogger(String name) { Configuration configuration = getLoggerContext().getConfiguration(); if (configuration instanceof AbstractConfiguration abstractConfiguration) { return abstractConfiguration.getLogger(name); } return configuration.getLoggers().get(name); }
Return the configuration location. The result may be: <ul> <li>{@code null}: if DefaultConfiguration is used (no explicit config loaded)</li> <li>A file path: if provided explicitly by the user</li> <li>A URI: if loaded from the classpath default or a custom location</li> </ul> @param configuration the source configuration @return the config location or {@code null}
java
core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java
477
[ "name" ]
LoggerConfig
true
2
7.28
spring-projects/spring-boot
79,428
javadoc
false
getJavaDoc
String getJavaDoc(Element element) { if (element instanceof RecordComponentElement) { return getJavaDoc((RecordComponentElement) element); } String javadoc = (element != null) ? this.env.getElementUtils().getDocComment(element) : null; javadoc = (javadoc != null) ? cleanUpJavaDoc(javadoc) : null; return (javadoc == null || javadoc.isEmpty()) ? null : javadoc; }
Extract the target element type from the specified container type or {@code null} if no element type was found. @param type a type, potentially wrapping an element type @return the element type or {@code null} if no specific type was found
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java
179
[ "element" ]
String
true
6
8.08
spring-projects/spring-boot
79,428
javadoc
false
retainAll
void retainAll(final Set<TopicPartition> partitions) { try { lock.lock(); completedFetches.removeIf(cf -> maybeDrain(partitions, cf)); if (maybeDrain(partitions, nextInLineFetch)) nextInLineFetch = null; } finally { lock.unlock(); } }
Updates the buffer to retain only the fetch data that corresponds to the given partitions. Any previously {@link CompletedFetch fetched data} is removed if its partition is not in the given set of partitions. @param partitions {@link Set} of {@link TopicPartition}s for which any buffered data should be kept
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchBuffer.java
212
[ "partitions" ]
void
true
2
6.56
apache/kafka
31,560
javadoc
false
descendingMultiset
@Override public ImmutableSortedMultiset<E> descendingMultiset() { ImmutableSortedMultiset<E> result = descendingMultiset; if (result == null) { return descendingMultiset = this.isEmpty() ? emptyMultiset(Ordering.from(comparator()).reverse()) : new DescendingImmutableSortedMultiset<E>(this); } return result; }
Returns an immutable sorted multiset containing the elements of a sorted multiset, sorted by the same {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always uses the natural ordering of the elements. <p>Despite the method name, this method attempts to avoid actually copying the data when it is safe to do so. The exact circumstances under which a copy will or will not be performed are undocumented and subject to change. <p>This method is safe to use even when {@code sortedMultiset} is a synchronized or concurrent collection that is currently being modified by another thread. @throws NullPointerException if {@code sortedMultiset} or any of its elements is null
java
android/guava/src/com/google/common/collect/ImmutableSortedMultiset.java
355
[]
true
3
6.56
google/guava
51,352
javadoc
false
adjustYear
private int adjustYear(final int twoDigitYear) { final int trial = century + twoDigitYear; return twoDigitYear >= startYear ? trial : trial + 100; }
Adjusts dates to be within appropriate century @param twoDigitYear The year to adjust @return A value between centuryStart(inclusive) to centuryStart+100(exclusive)
java
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
863
[ "twoDigitYear" ]
true
2
6.72
apache/commons-lang
2,896
javadoc
false
_normalize_json
def _normalize_json( data: Any, key_string: str, normalized_dict: dict[str, Any], separator: str, ) -> dict[str, Any]: """ Main recursive function Designed for the most basic use case of pd.json_normalize(data) intended as a performance improvement, see #15621 Parameters ---------- data : Any Type dependent on types contained within nested Json key_string : str New key (with separator(s) in) for data normalized_dict : dict The new normalized/flattened Json dict separator : str, default '.' Nested records will generate names separated by sep, e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar """ if isinstance(data, dict): for key, value in data.items(): new_key = f"{key_string}{separator}{key}" if not key_string: new_key = new_key.removeprefix(separator) _normalize_json( data=value, key_string=new_key, normalized_dict=normalized_dict, separator=separator, ) else: normalized_dict[key_string] = data return normalized_dict
Main recursive function Designed for the most basic use case of pd.json_normalize(data) intended as a performance improvement, see #15621 Parameters ---------- data : Any Type dependent on types contained within nested Json key_string : str New key (with separator(s) in) for data normalized_dict : dict The new normalized/flattened Json dict separator : str, default '.' Nested records will generate names separated by sep, e.g., for sep='.', { 'foo' : { 'bar' : 0 } } -> foo.bar
python
pandas/io/json/_normalize.py
151
[ "data", "key_string", "normalized_dict", "separator" ]
dict[str, Any]
true
5
6.4
pandas-dev/pandas
47,362
numpy
false
apply_along_fields
def apply_along_fields(func, arr): """ Apply function 'func' as a reduction across fields of a structured array. This is similar to `numpy.apply_along_axis`, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from `numpy.result_type` applied to the field's dtypes. Parameters ---------- func : function Function to apply on the "field" dimension. This function must support an `axis` argument, like `numpy.mean`, `numpy.sum`, etc. arr : ndarray Structured array for which to apply func. Returns ------- out : ndarray Result of the reduction operation Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> rfn.apply_along_fields(np.mean, b) array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) array([ 3. , 5.5, 9. , 11. ]) """ if arr.dtype.names is None: raise ValueError('arr must be a structured array') uarr = structured_to_unstructured(arr) return func(uarr, axis=-1) # works and avoids axis requirement, but very, very slow: #return np.apply_along_axis(func, -1, uarr)
Apply function 'func' as a reduction across fields of a structured array. This is similar to `numpy.apply_along_axis`, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from `numpy.result_type` applied to the field's dtypes. Parameters ---------- func : function Function to apply on the "field" dimension. This function must support an `axis` argument, like `numpy.mean`, `numpy.sum`, etc. arr : ndarray Structured array for which to apply func. Returns ------- out : ndarray Result of the reduction operation Examples -------- >>> import numpy as np >>> from numpy.lib import recfunctions as rfn >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> rfn.apply_along_fields(np.mean, b) array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) array([ 3. , 5.5, 9. , 11. ])
python
numpy/lib/recfunctions.py
1,186
[ "func", "arr" ]
false
2
7.84
numpy/numpy
31,054
numpy
false
isInvalidReadOnlyPropertyType
private boolean isInvalidReadOnlyPropertyType(@Nullable Class<?> returnType, Class<?> beanClass) { return (returnType != null && (ClassLoader.class.isAssignableFrom(returnType) || ProtectionDomain.class.isAssignableFrom(returnType) || (AutoCloseable.class.isAssignableFrom(returnType) && !AutoCloseable.class.isAssignableFrom(beanClass)))); }
Create a new CachedIntrospectionResults instance for the given class. @param beanClass the bean class to analyze @throws BeansException in case of introspection failure
java
spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
362
[ "returnType", "beanClass" ]
true
5
6.24
spring-projects/spring-framework
59,386
javadoc
false
repeat
public static String repeat(final String repeat, final int count) { // Performance tuned for 2.0 (JDK1.4) if (repeat == null) { return null; } if (count <= 0) { return EMPTY; } final int inputLength = repeat.length(); if (count == 1 || inputLength == 0) { return repeat; } if (inputLength == 1 && count <= PAD_LIMIT) { return repeat(repeat.charAt(0), count); } final int outputLength = inputLength * count; switch (inputLength) { case 1: return repeat(repeat.charAt(0), count); case 2: final char ch0 = repeat.charAt(0); final char ch1 = repeat.charAt(1); final char[] output2 = new char[outputLength]; for (int i = count * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default: final StringBuilder buf = new StringBuilder(outputLength); for (int i = 0; i < count; i++) { buf.append(repeat); } return buf.toString(); } }
Repeats a String {@code repeat} times to form a new String. <pre> StringUtils.repeat(null, 2) = null StringUtils.repeat("", 0) = "" StringUtils.repeat("", 2) = "" StringUtils.repeat("a", 3) = "aaa" StringUtils.repeat("ab", 2) = "abab" StringUtils.repeat("a", -2) = "" </pre> @param repeat the String to repeat, may be null. @param count number of times to repeat str, negative treated as zero. @return a new String consisting of the original String repeated, {@code null} if null String input.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
6,064
[ "repeat", "count" ]
String
true
9
8.24
apache/commons-lang
2,896
javadoc
false
extractFromStream
private void extractFromStream(ZipInputStream zipStream, boolean overwrite, File outputDirectory) throws IOException { ZipEntry entry = zipStream.getNextEntry(); String canonicalOutputPath = outputDirectory.getCanonicalPath() + File.separator; while (entry != null) { File file = new File(outputDirectory, entry.getName()); String canonicalEntryPath = file.getCanonicalPath(); if (!canonicalEntryPath.startsWith(canonicalOutputPath)) { throw new ReportableException("Entry '" + entry.getName() + "' would be written to '" + canonicalEntryPath + "'. This is outside the output location of '" + canonicalOutputPath + "'. Verify your target server configuration."); } if (file.exists() && !overwrite) { throw new ReportableException((file.isDirectory() ? "Directory" : "File") + " '" + file.getName() + "' already exists. Use --force if you want to overwrite or " + "specify an alternate location."); } if (!entry.isDirectory()) { FileCopyUtils.copy(StreamUtils.nonClosing(zipStream), new FileOutputStream(file)); } else { file.mkdir(); } zipStream.closeEntry(); entry = zipStream.getNextEntry(); } }
Detect if the project should be extracted. @param request the generation request @param response the generation response @return if the project should be extracted
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/ProjectGenerator.java
111
[ "zipStream", "overwrite", "outputDirectory" ]
void
true
7
8.08
spring-projects/spring-boot
79,428
javadoc
false
isDirective
function isDirective(node: TSESTree.Node, ancestors: TSESTree.Node[]): boolean { const parent = ancestors[ancestors.length - 1], grandparent = ancestors[ancestors.length - 2]; return (parent.type === 'Program' || parent.type === 'BlockStatement' && (/Function/u.test(grandparent.type))) && directives(parent).indexOf(node) >= 0; }
@param node any node @param ancestors the given node's ancestors @returns whether the given node is considered a directive in its current position
typescript
.eslint-plugin-local/code-no-unused-expressions.ts
101
[ "node", "ancestors" ]
true
4
7.6
microsoft/vscode
179,840
jsdoc
false
simplify_index_in_vec_range
def simplify_index_in_vec_range(index: sympy.Expr, var: sympy.Expr, vec_length: int): """ Simplifies the index expression within the range of a vectorized loop. Given a vectorized loop variable `var` in the range of a loop with `vec_length`, this function transforms the `index` into an equivalent form. It handles simplifications for cases where `var` can be expressed as `vec_length * a + b`, where `b` ranges from 0 to `vec_length - 1`. The function reduces occurrences of `FloorDiv` and `ModularIndexing` in the `index` with best-effort optimizations. NOTE: The simplified index expression is intended for analysis purposes only, not for code generation. It replaces `FloorDiv` and `ModularIndexing` with free variables which are not dependent on the loop variable `var` in the vectorized range. Check https://github.com/pytorch/pytorch/pull/117221#discussion_r1449746217 for more details. Examples: 1. If `var` is `x3` and `vec_length` is 16, and `x3 = 16*a + b`, then `FloorDiv(x3, div)` or `ModularIndexing(x3, div, mod)` becomes a free variable when `div` is divisible by 16. 2. `ModularIndexing(x3, 1, mod)` can be simplified to `x3 + c` where `c` is a free variable when `mod` is divisible by 16. """ div_freevar_id = 0 mod_freevar_id = 0 def visit_indexing_div(divisor): nonlocal div_freevar_id result = FloorDiv(var, divisor) if sympy.gcd(divisor, vec_length) == vec_length: result = sympy.Symbol(f"{var}_div_c{div_freevar_id}") div_freevar_id += 1 return result def visit_modular_indexing(divisor, modulus): nonlocal mod_freevar_id result = ModularIndexing(var, divisor, modulus) if sympy.gcd(divisor, vec_length) == vec_length: result = sympy.Symbol(f"{var}_mod_c{mod_freevar_id}") mod_freevar_id += 1 elif divisor == 1 and sympy.gcd(modulus, vec_length) == vec_length: result = var + sympy.Symbol(f"{var}_mod_c{mod_freevar_id}") mod_freevar_id += 1 return result original_index = index div = sympy.Wild("divisor", integer=True) if index.has(FloorDiv): index = index.replace(FloorDiv(var, div), visit_indexing_div) mod = sympy.Wild("modulus", integer=True) if index.has(ModularIndexing): index = index.replace(ModularIndexing(var, div, mod), visit_modular_indexing) index = sympy.simplify(index) if index != original_index: return simplify_index_in_vec_range(index, var, vec_length) return index
Simplifies the index expression within the range of a vectorized loop. Given a vectorized loop variable `var` in the range of a loop with `vec_length`, this function transforms the `index` into an equivalent form. It handles simplifications for cases where `var` can be expressed as `vec_length * a + b`, where `b` ranges from 0 to `vec_length - 1`. The function reduces occurrences of `FloorDiv` and `ModularIndexing` in the `index` with best-effort optimizations. NOTE: The simplified index expression is intended for analysis purposes only, not for code generation. It replaces `FloorDiv` and `ModularIndexing` with free variables which are not dependent on the loop variable `var` in the vectorized range. Check https://github.com/pytorch/pytorch/pull/117221#discussion_r1449746217 for more details. Examples: 1. If `var` is `x3` and `vec_length` is 16, and `x3 = 16*a + b`, then `FloorDiv(x3, div)` or `ModularIndexing(x3, div, mod)` becomes a free variable when `div` is divisible by 16. 2. `ModularIndexing(x3, 1, mod)` can be simplified to `x3 + c` where `c` is a free variable when `mod` is divisible by 16.
python
torch/_inductor/codegen/cpp.py
402
[ "index", "var", "vec_length" ]
true
8
8.32
pytorch/pytorch
96,034
unknown
false
getFirst
@ParametricNullness public static <T extends @Nullable Object> T getFirst( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); }
Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty. The {@link Iterators} analog to this method is {@link Iterators#getNext}. <p>If no default value is desired (and the caller instead wants a {@link NoSuchElementException} to be thrown), it is recommended that {@code iterable.iterator().next()} is used instead. <p>To get the only element in a single-element {@code Iterable}, consider using {@link #getOnlyElement(Iterable)} or {@link #getOnlyElement(Iterable, Object)} instead. <p><b>{@code Stream} equivalent:</b> {@code stream.findFirst().orElse(defaultValue)} <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), consider using {@code collection.getFirst()} instead. Note that if the collection is empty, {@code getFirst()} throws a {@code NoSuchElementException}, while this method returns the default value. @param defaultValue the default value to return if the iterable is empty @return the first element of {@code iterable} or the default value @since 7.0
java
android/guava/src/com/google/common/collect/Iterables.java
836
[ "iterable", "defaultValue" ]
T
true
1
6.24
google/guava
51,352
javadoc
false
tryLockMemory
@Override public void tryLockMemory() { int result = libc.mlockall(MCL_CURRENT); if (result == 0) { isMemoryLocked = true; return; } // mlockall failed for some reason int errno = libc.errno(); String errMsg = libc.strerror(errno); logger.warn("Unable to lock JVM Memory: error={}, reason={}", errno, errMsg); logger.warn("This can result in part of the JVM being swapped out."); if (errno == ENOMEM) { boolean rlimitSuccess = false; long softLimit = 0; long hardLimit = 0; // we only know RLIMIT_MEMLOCK for these two at the moment. var rlimit = libc.newRLimit(); if (libc.getrlimit(constants.RLIMIT_MEMLOCK(), rlimit) == 0) { rlimitSuccess = true; softLimit = rlimit.rlim_cur(); hardLimit = rlimit.rlim_max(); } else { logger.warn("Unable to retrieve resource limits: {}", libc.strerror(libc.errno())); } if (rlimitSuccess) { logger.warn( "Increase RLIMIT_MEMLOCK, soft limit: {}, hard limit: {}", rlimitToString(softLimit), rlimitToString(hardLimit) ); logMemoryLimitInstructions(); } else { logger.warn("Increase RLIMIT_MEMLOCK (ulimit)."); } } }
Return the current rlimit for the given resource. If getrlimit fails, returns {@link ProcessLimits#UNKNOWN}. If the rlimit is unlimited, returns {@link ProcessLimits#UNLIMITED}.
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/PosixNativeAccess.java
86
[]
void
true
5
6.4
elastic/elasticsearch
75,680
javadoc
false
resolveValue
private @Nullable Object resolveValue(RegisteredBean registeredBean, Field field) { String beanName = registeredBean.getBeanName(); Class<?> beanClass = registeredBean.getBeanClass(); ConfigurableBeanFactory beanFactory = registeredBean.getBeanFactory(); DependencyDescriptor descriptor = new DependencyDescriptor(field, this.required); descriptor.setContainingClass(beanClass); if (this.shortcutBeanName != null) { descriptor = new ShortcutDependencyDescriptor(descriptor, this.shortcutBeanName); } Set<String> autowiredBeanNames = new LinkedHashSet<>(1); TypeConverter typeConverter = beanFactory.getTypeConverter(); try { Assert.isInstanceOf(AutowireCapableBeanFactory.class, beanFactory); Object value = ((AutowireCapableBeanFactory) beanFactory).resolveDependency( descriptor, beanName, autowiredBeanNames, typeConverter); registerDependentBeans(beanFactory, beanName, autowiredBeanNames); return value; } catch (BeansException ex) { throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex); } }
Resolve the field value for the specified registered bean and set it using reflection. @param registeredBean the registered bean @param instance the bean instance
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/AutowiredFieldValueResolver.java
169
[ "registeredBean", "field" ]
Object
true
3
6.56
spring-projects/spring-framework
59,386
javadoc
false
getSourceDir
function getSourceDir(): string { const projectDir = process.cwd() const sourceRootFromTsConfig = getSourceDirFromTypeScriptConfig() if (sourceRootFromTsConfig) { return path.join(projectDir, sourceRootFromTsConfig) } // Check common source directories if there's no tsconfig.json for (const dir of ['src', 'lib', 'app']) { const absoluteSourceDir = path.join(projectDir, dir) if (fs.existsSync(absoluteSourceDir)) { return absoluteSourceDir } } // Default fallback if we can't determine anything better return projectDir }
Determines the absolute path to the source directory.
typescript
packages/cli/src/utils/client-output-path.ts
24
[]
true
3
7.04
prisma/prisma
44,834
jsdoc
false
close
@Override public void close() throws IOException { this.internalDelegate.close(); }
@param settings the Elasticsearch settings object @return a {@link ScriptEngine} for painless scripts for use in {@link IngestScript} and {@link IngestConditionalScript} contexts, including all available {@link PainlessExtension}s. @throws IOException when the underlying script engine cannot be created
java
libs/logstash-bridge/src/main/java/org/elasticsearch/logstashbridge/script/ScriptServiceBridge.java
127
[]
void
true
1
6
elastic/elasticsearch
75,680
javadoc
false
simpleQuote
private static StringBuilder simpleQuote(final StringBuilder sb, final String value) { for (int i = 0; i < value.length(); ++i) { final char c = value.charAt(i); switch (c) { case '\\': case '^': case '$': case '.': case '|': case '?': case '*': case '+': case '(': case ')': case '[': case '{': sb.append('\\'); // falls-through default: sb.append(c); } } if (sb.charAt(sb.length() - 1) == '.') { // trailing '.' is optional sb.append('?'); } return sb; }
Gets a cache of Strategies for a particular field @param field The Calendar field @return a cache of Locale to Strategy
java
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
762
[ "sb", "value" ]
StringBuilder
true
3
7.76
apache/commons-lang
2,896
javadoc
false
unique
function unique<I>(list: L.List<I>) { return Array.from(new Set(list)) }
Narrow a list to only have unique values. @param list @returns
typescript
helpers/blaze/unique.ts
8
[ "list" ]
false
1
6.16
prisma/prisma
44,834
jsdoc
false
ensureClassesSensitiveToVerificationAreInitialized
private static void ensureClassesSensitiveToVerificationAreInitialized() { var classesToInitialize = Set.of( "sun.net.www.protocol.http.HttpURLConnection", "sun.nio.ch.DatagramChannelImpl", "sun.nio.ch.ServerSocketChannelImpl" ); for (String className : classesToInitialize) { try { Class.forName(className); } catch (ClassNotFoundException unexpected) { throw new AssertionError(unexpected); } } }
If bytecode verification is enabled, ensure these classes get loaded before transforming/retransforming them. For these classes, the order in which we transform and verify them matters. Verification during class transformation is at least an unforeseen (if not unsupported) scenario: we are loading a class, and while we are still loading it (during transformation) we try to verify it. This in turn leads to more classes loading (for verification purposes), which could turn into those classes to be transformed and undergo verification. In order to avoid circularity errors as much as possible, we force a partial order.
java
libs/entitlement/src/main/java/org/elasticsearch/entitlement/initialization/EntitlementInitialization.java
121
[]
void
true
2
6.88
elastic/elasticsearch
75,680
javadoc
false
geterr
def geterr(): """ Get the current way of handling floating-point errors. Returns ------- res : dict A dictionary with keys "divide", "over", "under", and "invalid", whose values are from the strings "ignore", "print", "log", "warn", "raise", and "call". The keys represent possible floating-point exceptions, and the values define how these exceptions are handled. See Also -------- geterrcall, seterr, seterrcall Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. **Concurrency note:** see :doc:`/reference/routines.err` Examples -------- >>> import numpy as np >>> np.geterr() {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} >>> np.arange(3.) / np.arange(3.) # doctest: +SKIP array([nan, 1., 1.]) RuntimeWarning: invalid value encountered in divide >>> oldsettings = np.seterr(all='warn', invalid='raise') >>> np.geterr() {'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'} >>> np.arange(3.) / np.arange(3.) Traceback (most recent call last): ... FloatingPointError: invalid value encountered in divide >>> oldsettings = np.seterr(**oldsettings) # restore original """ res = _get_extobj_dict() # The "geterr" doesn't include call and bufsize,: res.pop("call", None) res.pop("bufsize", None) return res
Get the current way of handling floating-point errors. Returns ------- res : dict A dictionary with keys "divide", "over", "under", and "invalid", whose values are from the strings "ignore", "print", "log", "warn", "raise", and "call". The keys represent possible floating-point exceptions, and the values define how these exceptions are handled. See Also -------- geterrcall, seterr, seterrcall Notes ----- For complete documentation of the types of floating-point exceptions and treatment options, see `seterr`. **Concurrency note:** see :doc:`/reference/routines.err` Examples -------- >>> import numpy as np >>> np.geterr() {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} >>> np.arange(3.) / np.arange(3.) # doctest: +SKIP array([nan, 1., 1.]) RuntimeWarning: invalid value encountered in divide >>> oldsettings = np.seterr(all='warn', invalid='raise') >>> np.geterr() {'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'} >>> np.arange(3.) / np.arange(3.) Traceback (most recent call last): ... FloatingPointError: invalid value encountered in divide >>> oldsettings = np.seterr(**oldsettings) # restore original
python
numpy/_core/_ufunc_config.py
112
[]
false
1
6.16
numpy/numpy
31,054
unknown
false
getTopicMetadata
public List<PartitionInfo> getTopicMetadata(String topic, boolean allowAutoTopicCreation, Timer timer) { MetadataRequest.Builder request = new MetadataRequest.Builder(Collections.singletonList(topic), allowAutoTopicCreation); Map<String, List<PartitionInfo>> topicMetadata = getTopicMetadata(request, timer); return topicMetadata.get(topic); }
Fetches the {@link PartitionInfo partition information} for the given topic in the cluster, or {@code null}. @param timer Timer bounding how long this method can block @return The {@link List list} of {@link PartitionInfo partition information}, or {@code null} if the topic is unknown
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/TopicMetadataFetcher.java
70
[ "topic", "allowAutoTopicCreation", "timer" ]
true
1
6.56
apache/kafka
31,560
javadoc
false
swap
public static void swap(final boolean[] array, final int offset1, final int offset2) { swap(array, offset1, offset2, 1); }
Swaps two elements in the given boolean array. <p>There is no special handling for multi-dimensional arrays. This method does nothing for a {@code null} or empty input array or for overflow indices. Negative indices are promoted to 0(zero).</p> Examples: <ul> <li>ArrayUtils.swap([1, 2, 3], 0, 2) -&gt; [3, 2, 1]</li> <li>ArrayUtils.swap([1, 2, 3], 0, 0) -&gt; [1, 2, 3]</li> <li>ArrayUtils.swap([1, 2, 3], 1, 0) -&gt; [2, 1, 3]</li> <li>ArrayUtils.swap([1, 2, 3], 0, 5) -&gt; [1, 2, 3]</li> <li>ArrayUtils.swap([1, 2, 3], -1, 1) -&gt; [2, 1, 3]</li> </ul> @param array the array to swap, may be {@code null}. @param offset1 the index of the first element to swap. @param offset2 the index of the second element to swap. @since 3.5
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
8,023
[ "array", "offset1", "offset2" ]
void
true
1
7.2
apache/commons-lang
2,896
javadoc
false
arithmetic_op
def arithmetic_op(left: ArrayLike, right: Any, op): """ Evaluate an arithmetic operation `+`, `-`, `*`, `/`, `//`, `%`, `**`, ... Note: the caller is responsible for ensuring that numpy warnings are suppressed (with np.errstate(all="ignore")) if needed. Parameters ---------- left : np.ndarray or ExtensionArray right : object Cannot be a DataFrame or Index. Series is *not* excluded. op : {operator.add, operator.sub, ...} Or one of the reversed variants from roperator. Returns ------- ndarray or ExtensionArray Or a 2-tuple of these in the case of divmod or rdivmod. """ # NB: We assume that extract_array and ensure_wrapped_if_datetimelike # have already been called on `left` and `right`, # and `maybe_prepare_scalar_for_op` has already been called on `right` # We need to special-case datetime64/timedelta64 dtypes (e.g. because numpy # casts integer dtypes to timedelta64 when operating with timedelta64 - GH#22390) if isinstance(right, list): # GH#62423 right = sanitize_array(right, None) right = ensure_wrapped_if_datetimelike(right) if ( should_extension_dispatch(left, right) or isinstance(right, (Timedelta, BaseOffset, Timestamp)) or right is NaT ): # Timedelta/Timestamp and other custom scalars are included in the check # because numexpr will fail on it, see GH#31457 res_values = op(left, right) else: # TODO we should handle EAs consistently and move this check before the if/else # (https://github.com/pandas-dev/pandas/issues/41165) # error: Argument 2 to "_bool_arith_check" has incompatible type # "Union[ExtensionArray, ndarray[Any, Any]]"; expected "ndarray[Any, Any]" _bool_arith_check(op, left, right) # type: ignore[arg-type] # error: Argument 1 to "_na_arithmetic_op" has incompatible type # "Union[ExtensionArray, ndarray[Any, Any]]"; expected "ndarray[Any, Any]" res_values = _na_arithmetic_op(left, right, op) # type: ignore[arg-type] return res_values
Evaluate an arithmetic operation `+`, `-`, `*`, `/`, `//`, `%`, `**`, ... Note: the caller is responsible for ensuring that numpy warnings are suppressed (with np.errstate(all="ignore")) if needed. Parameters ---------- left : np.ndarray or ExtensionArray right : object Cannot be a DataFrame or Index. Series is *not* excluded. op : {operator.add, operator.sub, ...} Or one of the reversed variants from roperator. Returns ------- ndarray or ExtensionArray Or a 2-tuple of these in the case of divmod or rdivmod.
python
pandas/core/ops/array_ops.py
242
[ "left", "right", "op" ]
true
6
6.72
pandas-dev/pandas
47,362
numpy
false
maybeBindReferencePointcutParameter
private void maybeBindReferencePointcutParameter() { if (this.numberOfRemainingUnboundArguments > 1) { throw new AmbiguousBindingException("Still " + this.numberOfRemainingUnboundArguments + " unbound args at reference pointcut binding stage, with no way to determine between them"); } List<String> varNames = new ArrayList<>(); String[] tokens = StringUtils.tokenizeToStringArray(this.pointcutExpression, " "); for (int i = 0; i < tokens.length; i++) { String toMatch = tokens[i]; if (toMatch.startsWith("!")) { toMatch = toMatch.substring(1); } int firstParenIndex = toMatch.indexOf('('); if (firstParenIndex != -1) { toMatch = toMatch.substring(0, firstParenIndex); } else { if (tokens.length < i + 2) { // no "(" and nothing following continue; } else { String nextToken = tokens[i + 1]; if (nextToken.charAt(0) != '(') { // next token is not "(" either, can't be a pc... continue; } } } // eat the body PointcutBody body = getPointcutBody(tokens, i); i += body.numTokensConsumed; if (!nonReferencePointcutTokens.contains(toMatch)) { // then it could be a reference pointcut String varName = maybeExtractVariableName(body.text); if (varName != null) { varNames.add(varName); } } } if (varNames.size() > 1) { throw new AmbiguousBindingException("Found " + varNames.size() + " candidate reference pointcut variables but only one unbound argument slot"); } else if (varNames.size() == 1) { for (int j = 0; j < this.parameterNameBindings.length; j++) { if (isUnbound(j)) { bindParameterName(j, varNames.get(0)); break; } } } // else varNames.size must be 0 and we have nothing to bind. }
Parse the string pointcut expression looking for this(), target() and args() expressions. If we find one, try and extract a candidate variable name and bind it.
java
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java
531
[]
void
true
13
7.12
spring-projects/spring-framework
59,386
javadoc
false
castPath
function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); }
Casts `value` to a path array if it's not one. @private @param {*} value The value to inspect. @param {Object} [object] The object to query keys on. @returns {Array} Returns the cast property path array.
javascript
lodash.js
4,556
[ "value", "object" ]
false
3
6.24
lodash/lodash
61,490
jsdoc
false
all_py_loaded_overloads
def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]: """ Warning: the set of overloads this will report is very subtle. It is precisely the set of torch.ops functions that have actually been accessed from Python (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT from the set of registered operators, which will in general be a larger set, as this would include all operators which we ran C++ static initializers or Python operator registration on. This does not eagerly populate the list on torch.ops.aten; this list is lazy! In other words, this is good for traversing over everything that has an OpOverload object allocated in Python. We use it for cache invalidation, but don't rely on this list being complete. Note that even if we did report all C++ registered overloads, this isn't guaranteed to be complete either, as a subsequent lazy load of a library which triggers more registrations could add more things to the set. """ for ns in torch.ops: packets = getattr(torch.ops, ns) for op_name in packets: packet = getattr(packets, op_name) for overload in packet: yield getattr(packet, overload)
Warning: the set of overloads this will report is very subtle. It is precisely the set of torch.ops functions that have actually been accessed from Python (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT from the set of registered operators, which will in general be a larger set, as this would include all operators which we ran C++ static initializers or Python operator registration on. This does not eagerly populate the list on torch.ops.aten; this list is lazy! In other words, this is good for traversing over everything that has an OpOverload object allocated in Python. We use it for cache invalidation, but don't rely on this list being complete. Note that even if we did report all C++ registered overloads, this isn't guaranteed to be complete either, as a subsequent lazy load of a library which triggers more registrations could add more things to the set.
python
torch/_dispatch/python.py
29
[]
Iterator[torch._ops.OpOverload]
true
4
6.72
pytorch/pytorch
96,034
unknown
false
hasVolatileName
bool hasVolatileName(const BinaryFunction &BF) { for (const StringRef &Name : BF.getNames()) if (getLTOCommonName(Name)) return true; return false; }
Return true if the function name can change across compilations.
cpp
bolt/lib/Profile/DataReader.cpp
46
[]
true
2
7.04
llvm/llvm-project
36,021
doxygen
false
readEscapeCharacter
private char readEscapeCharacter() throws JSONException { char escaped = this.in.charAt(this.pos++); switch (escaped) { case 'u': if (this.pos + 4 > this.in.length()) { throw syntaxError("Unterminated escape sequence"); } String hex = this.in.substring(this.pos, this.pos + 4); this.pos += 4; return (char) Integer.parseInt(hex, 16); case 't': return '\t'; case 'b': return '\b'; case 'n': return '\n'; case 'r': return '\r'; case 'f': return '\f'; case '\'', '"', '\\': default: return escaped; } }
Unescapes the character identified by the character or characters that immediately follow a backslash. The backslash '\' should have already been read. This supports both unicode escapes "u000A" and two-character escapes "\n". @return the unescaped char @throws NumberFormatException if any unicode escape sequences are malformed. @throws JSONException if processing of json failed
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONTokener.java
235
[]
true
2
7.6
spring-projects/spring-boot
79,428
javadoc
false
toScaledBigDecimal
public static BigDecimal toScaledBigDecimal(final BigDecimal value, final int scale, final RoundingMode roundingMode) { if (value == null) { return BigDecimal.ZERO; } return value.setScale(scale, roundingMode == null ? RoundingMode.HALF_EVEN : roundingMode); }
Converts a {@link BigDecimal} to a {@link BigDecimal} whose scale is the specified value with a {@link RoundingMode} applied. If the input {@code value} is {@code null}, we simply return {@code BigDecimal.ZERO}. @param value the {@link BigDecimal} to convert, may be null. @param scale the number of digits to the right of the decimal point. @param roundingMode a rounding behavior for numerical operations capable of discarding precision. @return the scaled, with appropriate rounding, {@link BigDecimal}. @since 3.8
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
1,643
[ "value", "scale", "roundingMode" ]
BigDecimal
true
3
7.92
apache/commons-lang
2,896
javadoc
false
configure
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder; }
Configure the application. Normally all you would need to do is to add sources (e.g. config classes) because other settings have sensible defaults. You might choose (for instance) to add default command line arguments, or set an active Spring profile. @param builder a builder for the application context @return the application builder @see SpringApplicationBuilder
java
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializer.java
225
[ "builder" ]
SpringApplicationBuilder
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
declareSymbolAndAddToSymbolTable
function declareSymbolAndAddToSymbolTable(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol | undefined { switch (container.kind) { // Modules, source files, and classes need specialized handling for how their // members are declared (for example, a member of a class will go into a specific // symbol table depending on if it is static or not). We defer to specialized // handlers to take care of declaring these child members. case SyntaxKind.ModuleDeclaration: return declareModuleMember(node, symbolFlags, symbolExcludes); case SyntaxKind.SourceFile: return declareSourceFileMember(node, symbolFlags, symbolExcludes); case SyntaxKind.ClassExpression: case SyntaxKind.ClassDeclaration: return declareClassMember(node, symbolFlags, symbolExcludes); case SyntaxKind.EnumDeclaration: return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); case SyntaxKind.TypeLiteral: case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.JsxAttributes: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their // container, and are never in scope otherwise (even inside the body of the // object / type / interface declaring them). An exception is type parameters, // which are in scope without qualification (similar to 'locals'). return declareSymbol(container.symbol.members!, container.symbol, node, symbolFlags, symbolExcludes); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.JSDocSignature: case SyntaxKind.IndexSignature: case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.Constructor: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.JSDocFunctionType: case SyntaxKind.ClassStaticBlockDeclaration: case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.MappedType: // All the children of these container types are never visible through another // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, // they're only accessed 'lexically' (i.e. from code that exists underneath // their container in the tree). To accomplish this, we simply add their declared // symbol to the 'locals' of the container. These symbols can then be found as // the type checker walks up the containers, checking them for matching names. if (container.locals) Debug.assertNode(container, canHaveLocals); return declareSymbol(container.locals!, /*parent*/ undefined, node, symbolFlags, symbolExcludes); } }
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @param symbolTable - The symbol table which node will be added to. @param parent - node's parent declaration. @param node - The declaration to be added to the symbol table @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
typescript
src/compiler/binder.ts
2,263
[ "node", "symbolFlags", "symbolExcludes" ]
true
2
6.8
microsoft/TypeScript
107,154
jsdoc
false
findDefaultScheduler
protected Scheduler findDefaultScheduler() { if (this.beanFactory != null) { return this.beanFactory.getBean(Scheduler.class); } else { throw new IllegalStateException( "No Scheduler specified, and cannot find a default Scheduler without a BeanFactory"); } }
Return the Quartz Scheduler instance that this accessor operates on.
java
spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerAccessorBean.java
115
[]
Scheduler
true
2
6.88
spring-projects/spring-framework
59,386
javadoc
false
collectConditions
List<Condition> collectConditions(@Nullable AnnotatedTypeMetadata metadata) { if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) { return Collections.emptyList(); } List<Condition> conditions = new ArrayList<>(); for (String[] conditionClasses : getConditionClasses(metadata)) { for (String conditionClass : conditionClasses) { Condition condition = getCondition(conditionClass, this.context.getClassLoader()); conditions.add(condition); } } AnnotationAwareOrderComparator.sort(conditions); return conditions; }
Return the {@linkplain Condition conditions} that should be applied when considering the given annotated type. @param metadata the metadata of the annotated type @return the ordered list of conditions for that type
java
spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java
114
[ "metadata" ]
true
3
8.08
spring-projects/spring-framework
59,386
javadoc
false
toString
public static String toString(final URLClassLoader classLoader) { return classLoader != null ? classLoader + Arrays.toString(classLoader.getURLs()) : "null"; }
Converts the given URLClassLoader to a String in the format {@code "URLClassLoader.toString() + [URL1, URL2, ...]"}. @param classLoader to URLClassLoader to convert. @return the formatted string.
java
src/main/java/org/apache/commons/lang3/ClassLoaderUtils.java
77
[ "classLoader" ]
String
true
2
7.52
apache/commons-lang
2,896
javadoc
false
_enqueue_task_instances_with_queued_state
def _enqueue_task_instances_with_queued_state( self, task_instances: list[TI], executor: BaseExecutor, session: Session ) -> None: """ Enqueue task_instances which should have been set to queued with the executor. :param task_instances: TaskInstances to enqueue :param executor: The executor to enqueue tasks for :param session: The session object """ def _get_sentry_integration(executor: BaseExecutor) -> str: try: sentry_integration = executor.sentry_integration except AttributeError: # Old executor interface hard-codes the supports_sentry flag. if getattr(executor, "supports_sentry", False): return "sentry_sdk.integrations.celery.CeleryIntegration" return "" if not isinstance(sentry_integration, str): self.log.warning( "Ignoring invalid sentry_integration on executor", executor=executor, sentry_integration=sentry_integration, ) return "" return sentry_integration # actually enqueue them for ti in task_instances: if ti.dag_run.state in State.finished_dr_states: ti.set_state(None, session=session) continue workload = workloads.ExecuteTask.make( ti, generator=executor.jwt_generator, sentry_integration=_get_sentry_integration(executor), ) executor.queue_workload(workload, session=session)
Enqueue task_instances which should have been set to queued with the executor. :param task_instances: TaskInstances to enqueue :param executor: The executor to enqueue tasks for :param session: The session object
python
airflow-core/src/airflow/jobs/scheduler_job_runner.py
785
[ "self", "task_instances", "executor", "session" ]
None
true
5
6.4
apache/airflow
43,597
sphinx
false
predict_proba
def predict_proba(self, X): """ Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of such arrays The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ check_is_fitted(self) # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here all_proba = [ np.zeros((X.shape[0], j), dtype=np.float64) for j in np.atleast_1d(self.n_classes_) ] lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, require="sharedmem")( delayed(_accumulate_prediction)(e.predict_proba, X, all_proba, lock) for e in self.estimators_ ) for proba in all_proba: proba /= len(self.estimators_) if len(all_proba) == 1: return all_proba[0] else: return all_proba
Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of such arrays The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`.
python
sklearn/ensemble/_forest.py
921
[ "self", "X" ]
false
4
6.08
scikit-learn/scikit-learn
64,340
numpy
false
getSourceArchiveFile
private static File getSourceArchiveFile() { try { ProtectionDomain domain = Context.class.getProtectionDomain(); CodeSource codeSource = (domain != null) ? domain.getCodeSource() : null; URL location = (codeSource != null) ? codeSource.getLocation() : null; File source = (location != null) ? findSource(location) : null; if (source != null && source.exists()) { return source.getAbsoluteFile(); } throw new IllegalStateException("Unable to find source archive"); } catch (Exception ex) { throw new IllegalStateException("Unable to find source archive", ex); } }
Create a new {@link Context} instance with the specified value. @param archiveFile the source archive file @param workingDir the working directory
java
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/Context.java
77
[]
File
true
7
6.24
spring-projects/spring-boot
79,428
javadoc
false
acquisitionLockTimeoutMs
@Override public Optional<Integer> acquisitionLockTimeoutMs() { return delegate.acquisitionLockTimeoutMs(); }
Returns the acquisition lock timeout for the last set of records fetched from the cluster. @return The acquisition lock timeout in milliseconds, or {@code Optional.empty()} if the timeout is not known.
java
clients/src/main/java/org/apache/kafka/clients/consumer/KafkaShareConsumer.java
722
[]
true
1
6.96
apache/kafka
31,560
javadoc
false
longToShortArray
public static short[] longToShortArray(final long src, final int srcPos, final short[] dst, final int dstPos, final int nShorts) { if (0 == nShorts) { return dst; } if ((nShorts - 1) * Short.SIZE + srcPos >= Long.SIZE) { throw new IllegalArgumentException("(nShorts - 1) * 16 + srcPos >= 64"); } for (int i = 0; i < nShorts; i++) { final int shift = i * Short.SIZE + srcPos; dst[dstPos + i] = (short) (0xffff & src >> shift); } return dst; }
Converts a long into an array of short using the default (little-endian, LSB0) byte and bit ordering. @param src the long to convert. @param srcPos the position in {@code src}, in bits, from where to start the conversion. @param dst the destination array. @param dstPos the position in {@code dst} where to copy the result. @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to the width of the input (from srcPos to MSB). @return {@code dst}. @throws NullPointerException if {@code dst} is {@code null}. @throws IllegalArgumentException if {@code (nShorts - 1) * 16 + srcPos >= 64}. @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}.
java
src/main/java/org/apache/commons/lang3/Conversion.java
1,199
[ "src", "srcPos", "dst", "dstPos", "nShorts" ]
true
4
8.08
apache/commons-lang
2,896
javadoc
false
transform
public static <I extends @Nullable Object, O extends @Nullable Object> ListenableFuture<O> transform( ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) { return AbstractTransformFuture.create(input, function, executor); }
Returns a new {@code Future} whose result is derived from the result of the given {@code Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and the function is not invoked). Example usage: {@snippet : ListenableFuture<QueryResult> queryFuture = ...; ListenableFuture<List<Row>> rowsFuture = transform(queryFuture, QueryResult::getRows, executor); } <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See the warnings the {@link MoreExecutors#directExecutor} documentation. <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel the input, and if the input is cancelled, the returned {@code Future} will receive a callback in which it will attempt to cancel itself. <p>An example use of this method is to convert a serializable object returned from an RPC into a POJO. @param input The future to transform @param function A Function to transform the results of the provided future to the results of the returned future. @param executor Executor to run the function in. @return A future that holds result of the transformation. @since 9.0 (in 2.0 as {@code compose})
java
android/guava/src/com/google/common/util/concurrent/Futures.java
488
[ "input", "function", "executor" ]
true
1
6.72
google/guava
51,352
javadoc
false
invokeOnPartitionsRevokedOrLostToReleaseAssignment
private CompletableFuture<Void> invokeOnPartitionsRevokedOrLostToReleaseAssignment() { SortedSet<TopicPartition> droppedPartitions = new TreeSet<>(TOPIC_PARTITION_COMPARATOR); droppedPartitions.addAll(subscriptions.assignedPartitions()); log.info("Member {} is triggering callbacks to release assignment {} and leave group", memberId, droppedPartitions); CompletableFuture<Void> callbackResult; if (droppedPartitions.isEmpty()) { // No assignment to release. callbackResult = CompletableFuture.completedFuture(null); } else { // Release assignment. if (memberEpoch > 0) { // Member is part of the group. Invoke onPartitionsRevoked. callbackResult = revokePartitions(droppedPartitions); } else { // Member is not part of the group anymore. Invoke onPartitionsLost. callbackResult = invokeOnPartitionsLostCallback(droppedPartitions); } } return callbackResult; }
Release member assignment by calling the user defined callbacks for onPartitionsRevoked or onPartitionsLost. <ul> <li>If the member is part of the group (epoch > 0), this will invoke onPartitionsRevoked. This will be the case when releasing assignment because the member is intentionally leaving the group (after a call to unsubscribe)</li> <li>If the member is not part of the group (epoch <=0), this will invoke onPartitionsLost. This will be the case when releasing assignment after being fenced .</li> </ul> @return Future that will complete when the callback execution completes.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerMembershipManager.java
320
[]
true
3
8.08
apache/kafka
31,560
javadoc
false
createLabel
function createLabel(label: Label | undefined): Expression { if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } const expression = factory.createNumericLiteral(Number.MAX_SAFE_INTEGER); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } else { labelExpressions[label].push(expression); } return expression; } return factory.createOmittedExpression(); }
Creates an expression that can be used to indicate the value for a label. @param label A label.
typescript
src/compiler/transformers/generators.ts
2,521
[ "label" ]
true
6
6.72
microsoft/TypeScript
107,154
jsdoc
false
symlinkSync
function symlinkSync(target, path, type) { validateOneOf(type, 'type', ['dir', 'file', 'junction', null, undefined]); if (isWindows && type == null) { const absoluteTarget = pathModule.resolve(`${path}`, '..', `${target}`); if (statSync(absoluteTarget, { throwIfNoEntry: false })?.isDirectory()) { type = 'dir'; } } if (permission.isEnabled()) { // The permission model's security guarantees fall apart in the presence of // relative symbolic links. Thus, we have to prevent their creation. if (BufferIsBuffer(target)) { if (!isAbsolute(BufferToString(target))) { throw new ERR_ACCESS_DENIED('relative symbolic link target'); } } else if (typeof target !== 'string' || !isAbsolute(toPathIfFileURL(target))) { throw new ERR_ACCESS_DENIED('relative symbolic link target'); } } target = getValidatedPath(target, 'target'); path = getValidatedPath(path); binding.symlink( preprocessSymlinkDestination(target, type, path), path, stringToSymlinkType(type), ); }
Synchronously creates the link called `path` pointing to `target`. @param {string | Buffer | URL} target @param {string | Buffer | URL} path @param {string | null} [type] @returns {void}
javascript
lib/fs.js
1,832
[ "target", "path", "type" ]
false
10
6.4
nodejs/node
114,839
jsdoc
false
castSlice
function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); }
Casts `array` to a slice if it's needed. @private @param {Array} array The array to inspect. @param {number} start The start position. @param {number} [end=array.length] The end position. @returns {Array} Returns the cast slice.
javascript
lodash.js
4,583
[ "array", "start", "end" ]
false
4
6.24
lodash/lodash
61,490
jsdoc
false
get_last_lines_of_file
def get_last_lines_of_file(file_name: str, num_lines: int = 2) -> tuple[list[str], list[str]]: """ Get last lines of a file efficiently, without reading the whole file (with some limitations). Assumptions ara that line length not bigger than ~180 chars. :param file_name: name of the file :param num_lines: number of lines to return (max) :return: Tuple - last lines of the file in two variants: original and with removed ansi colours """ # account for EOL max_read = (180 + 2) * num_lines try: seek_size = min(os.stat(file_name).st_size, max_read) except FileNotFoundError: return [], [] with open(file_name, "rb") as temp_f: temp_f.seek(-seek_size, os.SEEK_END) tail = temp_f.read().decode(errors="ignore") last_lines = tail.splitlines()[-num_lines:] last_lines_no_colors = [remove_ansi_colours(line) for line in last_lines] return last_lines, last_lines_no_colors
Get last lines of a file efficiently, without reading the whole file (with some limitations). Assumptions ara that line length not bigger than ~180 chars. :param file_name: name of the file :param num_lines: number of lines to return (max) :return: Tuple - last lines of the file in two variants: original and with removed ansi colours
python
dev/breeze/src/airflow_breeze/utils/parallel.py
90
[ "file_name", "num_lines" ]
tuple[list[str], list[str]]
true
1
7.2
apache/airflow
43,597
sphinx
false
getSingletonFactoryBeanForTypeCheck
private @Nullable FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) { Boolean lockFlag = isCurrentThreadAllowedToHoldSingletonLock(); if (lockFlag == null) { this.singletonLock.lock(); } else { boolean locked = (lockFlag && this.singletonLock.tryLock()); if (!locked) { // Avoid shortcut FactoryBean instance but allow for subsequent type-based resolution. resolveBeanClass(mbd, beanName); return null; } } try { BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName); if (bw != null) { return (FactoryBean<?>) bw.getWrappedInstance(); } Object beanInstance = getSingleton(beanName, false); if (beanInstance instanceof FactoryBean<?> factoryBean) { return factoryBean; } if (isSingletonCurrentlyInCreation(beanName) || (mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) { return null; } Object instance; try { // Mark this bean as currently in creation, even if just partially. beforeSingletonCreation(beanName); // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. instance = resolveBeforeInstantiation(beanName, mbd); if (instance == null) { bw = createBeanInstance(beanName, mbd, null); instance = bw.getWrappedInstance(); this.factoryBeanInstanceCache.put(beanName, bw); } } catch (UnsatisfiedDependencyException ex) { // Don't swallow, probably misconfiguration... throw ex; } catch (BeanCreationException ex) { // Don't swallow a linkage error since it contains a full stacktrace on // first occurrence... and just a plain NoClassDefFoundError afterwards. if (ex.contains(LinkageError.class)) { throw ex; } // Instantiation failure, maybe too early... if (logger.isDebugEnabled()) { logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex); } onSuppressedException(ex); return null; } finally { // Finished partial creation of this bean. afterSingletonCreation(beanName); } return getFactoryBean(beanName, instance); } finally { this.singletonLock.unlock(); } }
Obtain a "shortcut" singleton FactoryBean instance to use for a {@code getObjectType()} call, without full initialization of the FactoryBean. @param beanName the name of the bean @param mbd the bean definition for the bean @return the FactoryBean instance, or {@code null} to indicate that we couldn't obtain a shortcut FactoryBean instance
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
991
[ "beanName", "mbd" ]
true
14
7.68
spring-projects/spring-framework
59,386
javadoc
false
afterPropertiesSet
@Override public void afterPropertiesSet() throws ParseException { Assert.notNull(this.cronExpression, "Property 'cronExpression' is required"); if (this.name == null) { this.name = this.beanName; } if (this.group == null) { this.group = Scheduler.DEFAULT_GROUP; } if (this.jobDetail != null) { this.jobDataMap.put("jobDetail", this.jobDetail); } if (this.startDelay > 0 || this.startTime == null) { this.startTime = new Date(System.currentTimeMillis() + this.startDelay); } if (this.timeZone == null) { this.timeZone = TimeZone.getDefault(); } CronTriggerImpl cti = new CronTriggerImpl(); cti.setName(this.name != null ? this.name : toString()); cti.setGroup(this.group); if (this.jobDetail != null) { cti.setJobKey(this.jobDetail.getKey()); } cti.setJobDataMap(this.jobDataMap); cti.setStartTime(this.startTime); cti.setCronExpression(this.cronExpression); cti.setTimeZone(this.timeZone); cti.setCalendarName(this.calendarName); cti.setPriority(this.priority); cti.setMisfireInstruction(this.misfireInstruction); cti.setDescription(this.description); this.cronTrigger = cti; }
Associate a textual description with this trigger.
java
spring-context-support/src/main/java/org/springframework/scheduling/quartz/CronTriggerFactoryBean.java
235
[]
void
true
9
6.4
spring-projects/spring-framework
59,386
javadoc
false
forciblyCast
@SuppressWarnings("unchecked") public static <T> T forciblyCast(Object argument) { return (T) argument; }
There are some situations where we cannot appease javac's type checking, and we need to forcibly cast an object's type. Please don't use this method unless you have no choice. @param argument the object to cast @param <T> the inferred type to which to cast the argument @return a cast version of the argument
java
libs/core/src/main/java/org/elasticsearch/core/Types.java
27
[ "argument" ]
T
true
1
6.96
elastic/elasticsearch
75,680
javadoc
false
dispose
function dispose() { if (state < TransformationState.Disposed) { // Clean up emit nodes on parse tree for (const node of nodes) { disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node))); } // Release references to external entries for GC purposes. lexicalEnvironmentVariableDeclarations = undefined!; lexicalEnvironmentVariableDeclarationsStack = undefined!; lexicalEnvironmentFunctionDeclarations = undefined!; lexicalEnvironmentFunctionDeclarationsStack = undefined!; onSubstituteNode = undefined!; onEmitNode = undefined!; emitHelpers = undefined; // Prevent further use of the transformation result. state = TransformationState.Disposed; } }
Ends a block scope. The previous set of block hoisted variables are restored. Any hoisted declarations are returned.
typescript
src/compiler/transformer.ts
646
[]
false
2
6.4
microsoft/TypeScript
107,154
jsdoc
false
semaphores
def semaphores(self, min_size: sympy.Expr) -> str: """ Lazily allocate a graph-wide semaphores buffer with at least min_size. This is a single buffer shared by all kernels and zero initialized once at graph start. Each kernel must leave the buffer zeroed on exit. Warning: multiple calls to this function will return the same buffer. Args: min_size: the number of int32 semaphores required Returns: name of the semaphores buffer """ current_device = V.graph.get_current_device_or_throw() arg = WorkspaceArg( count=min_size, zero_mode=WorkspaceZeroMode.ZERO_PER_GRAPH, dtype=torch.uint32, inner_name="sem_ptr", outer_name=f"semaphores_{current_device.type}_{current_device.index}", device=current_device, ) for existing_arg in self.workspace_args: if existing_arg.inner_name == arg.inner_name: assert arg == existing_arg, (arg, existing_arg) self.workspace_args.append(arg) return arg.inner_name
Lazily allocate a graph-wide semaphores buffer with at least min_size. This is a single buffer shared by all kernels and zero initialized once at graph start. Each kernel must leave the buffer zeroed on exit. Warning: multiple calls to this function will return the same buffer. Args: min_size: the number of int32 semaphores required Returns: name of the semaphores buffer
python
torch/_inductor/codegen/common.py
1,625
[ "self", "min_size" ]
str
true
3
7.92
pytorch/pytorch
96,034
google
false
createLauncherManifest
Manifest createLauncherManifest(UnaryOperator<String> libraryTransformer);
Create the {@link Manifest} for the launcher jar, applying the specified operator on each classpath entry. @param libraryTransformer the operator to apply on each classpath entry @return the manifest to use for the launcher jar
java
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/JarStructure.java
57
[ "libraryTransformer" ]
Manifest
true
1
6.32
spring-projects/spring-boot
79,428
javadoc
false
idxmin
def idxmin(self, skipna: bool = True) -> Series: """ Return the row label of the minimum value. If multiple values equal the minimum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA values. Returns ------- Series Indexes of minima in each group. Raises ------ ValueError When there are no valid values for a group. Then can happen if: * There is an unobserved group and ``observed=False``. * All values for a group are NA. * Some values for a group are NA and ``skipna=False``. .. versionchanged:: 3.0.0 Previously if all values for a group are NA or some values for a group are NA and ``skipna=False``, this method would return NA. Now it raises instead. See Also -------- numpy.argmin : Return indices of the minimum values along the given axis. DataFrame.idxmin : Return index of first occurrence of minimum over requested axis. Series.idxmax : Return index *label* of the first occurrence of maximum of values. Examples -------- >>> ser = pd.Series( ... [1, 2, 3, 4], ... index=pd.DatetimeIndex( ... ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"] ... ), ... ) >>> ser 2023-01-01 1 2023-01-15 2 2023-02-01 3 2023-02-15 4 dtype: int64 >>> ser.groupby(["a", "a", "b", "b"]).idxmin() a 2023-01-01 b 2023-02-01 dtype: datetime64[us] """ return self._idxmax_idxmin("idxmin", skipna=skipna)
Return the row label of the minimum value. If multiple values equal the minimum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA values. Returns ------- Series Indexes of minima in each group. Raises ------ ValueError When there are no valid values for a group. Then can happen if: * There is an unobserved group and ``observed=False``. * All values for a group are NA. * Some values for a group are NA and ``skipna=False``. .. versionchanged:: 3.0.0 Previously if all values for a group are NA or some values for a group are NA and ``skipna=False``, this method would return NA. Now it raises instead. See Also -------- numpy.argmin : Return indices of the minimum values along the given axis. DataFrame.idxmin : Return index of first occurrence of minimum over requested axis. Series.idxmax : Return index *label* of the first occurrence of maximum of values. Examples -------- >>> ser = pd.Series( ... [1, 2, 3, 4], ... index=pd.DatetimeIndex( ... ["2023-01-01", "2023-01-15", "2023-02-01", "2023-02-15"] ... ), ... ) >>> ser 2023-01-01 1 2023-01-15 2 2023-02-01 3 2023-02-15 4 dtype: int64 >>> ser.groupby(["a", "a", "b", "b"]).idxmin() a 2023-01-01 b 2023-02-01 dtype: datetime64[us]
python
pandas/core/groupby/generic.py
1,544
[ "self", "skipna" ]
Series
true
1
7.2
pandas-dev/pandas
47,362
numpy
false
disconnect
@Override public void disconnect(String nodeId) { if (connectionStates.isDisconnected(nodeId)) { log.debug("Client requested disconnect from node {}, which is already disconnected", nodeId); return; } log.info("Client requested disconnect from node {}", nodeId); selector.close(nodeId); long now = time.milliseconds(); cancelInFlightRequests(nodeId, now, abortedSends, false); connectionStates.disconnected(nodeId, now); }
Disconnects the connection to a particular node, if there is one. Any pending ClientRequests for this connection will receive disconnections. @param nodeId The id of the node
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
384
[ "nodeId" ]
void
true
2
6.56
apache/kafka
31,560
javadoc
false