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
kafkaCompleteExceptionally
boolean kafkaCompleteExceptionally(Throwable throwable) { return super.completeExceptionally(throwable); }
Completes this future exceptionally. For internal use by the Kafka clients, not by user code. @param throwable the exception. @return {@code true} if this invocation caused this CompletableFuture to transition to a completed state, else {@code false}
java
clients/src/main/java/org/apache/kafka/common/internals/KafkaCompletableFuture.java
48
[ "throwable" ]
true
1
6.64
apache/kafka
31,560
javadoc
false
put
public JSONObject put(String name, boolean value) throws JSONException { this.nameValuePairs.put(checkName(name), value); return this; }
Maps {@code name} to {@code value}, clobbering any existing name/value mapping with the same name. @param name the name of the property @param value the value of the property @return this object. @throws JSONException if an error occurs
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
205
[ "name", "value" ]
JSONObject
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
entryToFunctionCall
function entryToFunctionCall(entry: FindAllReferences.NodeEntry): CallExpression | NewExpression | undefined { if (entry.node.parent) { const functionReference = entry.node; const parent = functionReference.parent; switch (parent.kind) { // foo(...) or super(...) or new Foo(...) case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: const callOrNewExpression = tryCast(parent, isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === functionReference) { return callOrNewExpression; } break; // x.foo(...) case SyntaxKind.PropertyAccessExpression: const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { const callOrNewExpression = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === propertyAccessExpression) { return callOrNewExpression; } } break; // x["foo"](...) case SyntaxKind.ElementAccessExpression: const elementAccessExpression = tryCast(parent, isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { const callOrNewExpression = tryCast(elementAccessExpression.parent, isCallOrNewExpression); if (callOrNewExpression && callOrNewExpression.expression === elementAccessExpression) { return callOrNewExpression; } } break; } } return undefined; }
Gets the symbol for the contextual type of the node if it is not a union or intersection.
typescript
src/services/refactors/convertParamsToDestructuredObject.ts
365
[ "entry" ]
true
14
6
microsoft/TypeScript
107,154
jsdoc
false
get_cdxgen_port_mapping
def get_cdxgen_port_mapping(parallelism: int, pool: Pool) -> dict[str, int]: """ Map processes from pool to port numbers so that there is always the same port used by the same process in the pool - effectively having one multiprocessing process talking to the same cdxgen server :param parallelism: parallelism to use :param pool: pool to map ports for :return: mapping of process name to port """ port_map: dict[str, int] = dict(pool.map(get_port_mapping, range(parallelism))) return port_map
Map processes from pool to port numbers so that there is always the same port used by the same process in the pool - effectively having one multiprocessing process talking to the same cdxgen server :param parallelism: parallelism to use :param pool: pool to map ports for :return: mapping of process name to port
python
dev/breeze/src/airflow_breeze/utils/cdxgen.py
126
[ "parallelism", "pool" ]
dict[str, int]
true
1
6.24
apache/airflow
43,597
sphinx
false
createBatchOffAccumulatorForRecord
private ProducerBatch createBatchOffAccumulatorForRecord(Record record, int batchSize) { int initialSize = Math.max(AbstractRecords.estimateSizeInBytesUpperBound(magic(), recordsBuilder.compression().type(), record.key(), record.value(), record.headers()), batchSize); ByteBuffer buffer = ByteBuffer.allocate(initialSize); // Note that we intentionally do not set producer state (producerId, epoch, sequence, and isTransactional) // for the newly created batch. This will be set when the batch is dequeued for sending (which is consistent // with how normal batches are handled). MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, magic(), recordsBuilder.compression(), TimestampType.CREATE_TIME, 0L); return new ProducerBatch(topicPartition, builder, this.createdMs, true); }
Finalize the state of a batch. Final state, once set, is immutable. This function may be called once or twice on a batch. It may be called twice if 1. An inflight batch expires before a response from the broker is received. The batch's final state is set to FAILED. But it could succeed on the broker and second time around batch.done() may try to set SUCCEEDED final state. 2. If a transaction abortion happens or if the producer is closed forcefully, the final state is ABORTED but again it could succeed if broker responds with a success. Attempted transitions from [FAILED | ABORTED] --> SUCCEEDED are logged. Attempted transitions from one failure state to the same or a different failed state are ignored. Attempted transitions from SUCCEEDED to the same or a failed state throw an exception. @param baseOffset The base offset of the messages assigned by the server @param logAppendTime The log append time or -1 if CreateTime is being used @param topLevelException The exception that occurred (or null if the request was successful) @param recordExceptions Record exception function mapping batchIndex to the respective record exception @return true if the batch was completed successfully and false if the batch was previously aborted
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/ProducerBatch.java
403
[ "record", "batchSize" ]
ProducerBatch
true
1
7.04
apache/kafka
31,560
javadoc
false
categorize_connections
def categorize_connections(self, connection_ids: set) -> tuple[dict, set, set]: """ Categorize the given connection_ids into matched_connection_ids and not_found_connection_ids based on existing connection_ids. Existed connections are returned as a dict of {connection_id : Connection}. :param connection_ids: set of connection_ids :return: tuple of dict of existed connections, set of matched connection_ids, set of not found connection_ids """ existed_connections = self.session.execute( select(Connection).filter(Connection.conn_id.in_(connection_ids)) ).scalars() existed_connections_dict = {conn.conn_id: conn for conn in existed_connections} matched_connection_ids = set(existed_connections_dict.keys()) not_found_connection_ids = connection_ids - matched_connection_ids return existed_connections_dict, matched_connection_ids, not_found_connection_ids
Categorize the given connection_ids into matched_connection_ids and not_found_connection_ids based on existing connection_ids. Existed connections are returned as a dict of {connection_id : Connection}. :param connection_ids: set of connection_ids :return: tuple of dict of existed connections, set of matched connection_ids, set of not found connection_ids
python
airflow-core/src/airflow/api_fastapi/core_api/services/public/connections.py
84
[ "self", "connection_ids" ]
tuple[dict, set, set]
true
1
6.4
apache/airflow
43,597
sphinx
false
pow
public Fraction pow(final int power) { if (power == 1) { return this; } if (power == 0) { return ONE; } if (power < 0) { if (power == Integer.MIN_VALUE) { // MIN_VALUE can't be negated. return invert().pow(2).pow(-(power / 2)); } return invert().pow(-power); } final Fraction f = multiplyBy(this); if (power % 2 == 0) { // if even... return f.pow(power / 2); } return f.pow(power / 2).multiplyBy(this); }
Gets a fraction that is raised to the passed in power. <p> The returned fraction is in reduced form. </p> @param power the power to raise the fraction to @return {@code this} if the power is one, {@link #ONE} if the power is zero (even if the fraction equals ZERO) or a new fraction instance raised to the appropriate power @throws ArithmeticException if the resulting numerator or denominator exceeds {@code Integer.MAX_VALUE}
java
src/main/java/org/apache/commons/lang3/math/Fraction.java
820
[ "power" ]
Fraction
true
6
7.92
apache/commons-lang
2,896
javadoc
false
main
public final int main(String[] args, Terminal terminal, ProcessInfo processInfo) throws IOException { try { mainWithoutErrorHandling(args, terminal, processInfo); } catch (OptionException e) { // print help to stderr on exceptions printHelp(terminal, true); terminal.errorPrintln(Terminal.Verbosity.SILENT, "ERROR: " + e.getMessage()); return ExitCodes.USAGE; } catch (UserException e) { if (e.exitCode == ExitCodes.USAGE) { printHelp(terminal, true); } printUserException(terminal, e); return e.exitCode; } catch (IOException ioe) { terminal.errorPrintln(ioe); return ExitCodes.IO_ERROR; } catch (Throwable t) { // It's acceptable to catch Throwable at this point: // We're about to exit and only want to print the stacktrace with appropriate formatting (e.g. JSON). terminal.errorPrintln(t); return ExitCodes.CODE_ERROR; } return ExitCodes.OK; }
Parses options for this command from args and executes it.
java
libs/cli/src/main/java/org/elasticsearch/cli/Command.java
52
[ "args", "terminal", "processInfo" ]
true
6
6
elastic/elasticsearch
75,680
javadoc
false
wrapRelativePattern
function wrapRelativePattern(parsedPattern: ParsedStringPattern, arg2: string | IRelativePattern, options: IGlobOptionsInternal): ParsedStringPattern { if (typeof arg2 === 'string') { return parsedPattern; } const wrappedPattern: ParsedStringPattern = function (path, basename) { if (!options.isEqualOrParent(path, arg2.base)) { // skip glob matching if `base` is not a parent of `path` return null; } // Given we have checked `base` being a parent of `path`, // we can now remove the `base` portion of the `path` // and only match on the remaining path components // For that we try to extract the portion of the `path` // that comes after the `base` portion. We have to account // for the fact that `base` might end in a path separator // (https://github.com/microsoft/vscode/issues/162498) return parsedPattern(ltrim(path.substring(arg2.base.length), sep), basename); }; // Make sure to preserve associated metadata wrappedPattern.allBasenames = parsedPattern.allBasenames; wrappedPattern.allPaths = parsedPattern.allPaths; wrappedPattern.basenames = parsedPattern.basenames; wrappedPattern.patterns = parsedPattern.patterns; return wrappedPattern; }
Check if a provided parsed pattern or expression is empty - hence it won't ever match anything. See {@link FALSE} and {@link NULL}.
typescript
src/vs/base/common/glob.ts
395
[ "parsedPattern", "arg2", "options" ]
true
3
6
microsoft/vscode
179,840
jsdoc
false
bucket_fsdp_reduce_scatter
def bucket_fsdp_reduce_scatter( gm: torch.fx.GraphModule, bucket_cap_mb_by_bucket_idx: Callable[[int], float] | None = None, mode: BucketMode = "default", ) -> None: """ Bucketing pass for SimpleFSDP reduce_scatter ops. Attributes: gm (torch.fx.GraphModule): Graph module of the graph. bucket_cap_mb_by_bucket_idx (Callable[[int], float] | None): callback function that takes in bucket idx and returns size of a bucket in megabytes. By default torch._inductor.fx_passes.bucketing.bucket_cap_mb_by_bucket_idx_default is used. """ if bucket_cap_mb_by_bucket_idx is None: from torch._inductor.fx_passes.bucketing import ( bucket_cap_mb_by_bucket_idx_default, ) bucket_cap_mb_by_bucket_idx = bucket_cap_mb_by_bucket_idx_default rs_buckets = bucket_reduce_scatter_by_mb( gm, bucket_cap_mb_by_bucket_idx, filter_wait_node=is_fsdp_reduce_scatter_wait, ) if len(rs_buckets) == 0: return merge_reduce_scatter(gm, rs_buckets, mode)
Bucketing pass for SimpleFSDP reduce_scatter ops. Attributes: gm (torch.fx.GraphModule): Graph module of the graph. bucket_cap_mb_by_bucket_idx (Callable[[int], float] | None): callback function that takes in bucket idx and returns size of a bucket in megabytes. By default torch._inductor.fx_passes.bucketing.bucket_cap_mb_by_bucket_idx_default is used.
python
torch/_inductor/fx_passes/fsdp.py
87
[ "gm", "bucket_cap_mb_by_bucket_idx", "mode" ]
None
true
3
6.24
pytorch/pytorch
96,034
unknown
false
addOrMerge
public static void addOrMerge(Map<String, Object> source, MutablePropertySources sources) { if (!CollectionUtils.isEmpty(source)) { Map<String, Object> resultingSource = new HashMap<>(); DefaultPropertiesPropertySource propertySource = new DefaultPropertiesPropertySource(resultingSource); if (sources.contains(NAME)) { mergeIfPossible(source, sources, resultingSource); sources.replace(NAME, propertySource); } else { resultingSource.putAll(source); sources.addLast(propertySource); } } }
Add a new {@link DefaultPropertiesPropertySource} or merge with an existing one. @param source the {@code Map} source @param sources the existing sources @since 2.4.4
java
core/spring-boot/src/main/java/org/springframework/boot/env/DefaultPropertiesPropertySource.java
85
[ "source", "sources" ]
void
true
3
6.88
spring-projects/spring-boot
79,428
javadoc
false
resolve
@Nullable File resolve(String originalName, String newName) throws IOException;
Resolves the given name to a file. @param originalName the original name of the file @param newName the new name of the file @return file where the contents should be written or {@code null} if this name should be skipped @throws IOException if something went wrong
java
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ExtractCommand.java
390
[ "originalName", "newName" ]
File
true
1
6.48
spring-projects/spring-boot
79,428
javadoc
false
toShort
public Short toShort() { return Short.valueOf(shortValue()); }
Gets this mutable as an instance of Short. @return a Short instance containing the value from this mutable, never null.
java
src/main/java/org/apache/commons/lang3/mutable/MutableShort.java
373
[]
Short
true
1
6.96
apache/commons-lang
2,896
javadoc
false
performPendingMetricsOperations
private void performPendingMetricsOperations() { modifyMetricsLock.lock(); try { log.trace("{}: entering performPendingMetricsOperations", suiteName); for (PendingMetricsChange change = pending.pollLast(); change != null; change = pending.pollLast()) { if (change.provider == null) { if (log.isTraceEnabled()) { log.trace("{}: removing metric {}", suiteName, change.metricName); } metrics.removeMetric(change.metricName); } else { if (log.isTraceEnabled()) { log.trace("{}: adding metric {}", suiteName, change.metricName); } metrics.addMetric(change.metricName, change.provider); } } log.trace("{}: leaving performPendingMetricsOperations", suiteName); } finally { modifyMetricsLock.unlock(); } }
Perform pending metrics additions or removals. It is important to perform them in order. For example, we don't want to try to remove a metric that we haven't finished adding yet.
java
clients/src/main/java/org/apache/kafka/common/metrics/internals/IntGaugeSuite.java
211
[]
void
true
5
7.04
apache/kafka
31,560
javadoc
false
resolveScopeName
protected @Nullable String resolveScopeName(String annotationType) { return this.scopeMap.get(annotationType); }
Resolve the given annotation type into a named Spring scope. <p>The default implementation simply checks against registered scopes. Can be overridden for custom mapping rules, for example, naming conventions. @param annotationType the JSR-330 annotation type @return the Spring scope name
java
spring-context/src/main/java/org/springframework/context/annotation/Jsr330ScopeMetadataResolver.java
81
[ "annotationType" ]
String
true
1
6.32
spring-projects/spring-framework
59,386
javadoc
false
hasAllFetchPositions
public synchronized boolean hasAllFetchPositions() { // Since this is in the hot-path for fetching, we do this instead of using java.util.stream API Iterator<TopicPartitionState> it = assignment.stateIterator(); while (it.hasNext()) { if (!it.next().hasValidPosition()) { return false; } } return true; }
Unset the preferred read replica. This causes the fetcher to go back to the leader for fetches. @param tp The topic partition @return the removed preferred read replica if set, Empty otherwise.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
826
[]
true
3
8.4
apache/kafka
31,560
javadoc
false
decorateBeanDefinitionIfRequired
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder originalDef) { return decorateBeanDefinitionIfRequired(ele, originalDef, null); }
Decorate the given bean definition through a namespace handler, if applicable. @param ele the current element @param originalDef the current bean definition @return the decorated bean definition
java
spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java
1,388
[ "ele", "originalDef" ]
BeanDefinitionHolder
true
1
6
spring-projects/spring-framework
59,386
javadoc
false
toArray
@GwtIncompatible // Array.newArray(Class, int) public final E[] toArray(Class<@NonNull E> type) { return Iterables.<E>toArray(getDelegate(), type); }
Returns an array containing all of the elements from this fluent iterable in iteration order. <p><b>{@code Stream} equivalent:</b> if an object array is acceptable, use {@code stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use {@code stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray( len -> (E[]) Array.newInstance(type, len))}. @param type the type of the elements @return a newly-allocated array into which all the elements of this fluent iterable have been copied
java
android/guava/src/com/google/common/collect/FluentIterable.java
785
[ "type" ]
true
1
6.32
google/guava
51,352
javadoc
false
hashMember
private static int hashMember(final String name, final Object value) { final int part1 = name.hashCode() * 127; if (ObjectUtils.isArray(value)) { return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value); } if (value instanceof Annotation) { return part1 ^ hashCode((Annotation) value); } return part1 ^ value.hashCode(); }
Helper method for generating a hash code for a member of an annotation. @param name the name of the member @param value the value of the member @return a hash code for this member
java
src/main/java/org/apache/commons/lang3/AnnotationUtils.java
264
[ "name", "value" ]
true
3
8.24
apache/commons-lang
2,896
javadoc
false
instantiateWithFactoryMethod
public static <T> T instantiateWithFactoryMethod(Method method, Supplier<T> instanceSupplier) { Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get(); try { currentlyInvokedFactoryMethod.set(method); return instanceSupplier.get(); } finally { if (priorInvokedFactoryMethod != null) { currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod); } else { currentlyInvokedFactoryMethod.remove(); } } }
Invoke the given {@code instanceSupplier} with the factory method exposed as being invoked. @param method the factory method to expose @param instanceSupplier the instance supplier @param <T> the type of the instance @return the result of the instance supplier @since 6.2
java
spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java
68
[ "method", "instanceSupplier" ]
T
true
2
7.6
spring-projects/spring-framework
59,386
javadoc
false
setdiff1d
def setdiff1d(ar1, ar2, assume_unique=False): """ Find the set difference of two arrays. Return the unique values in `ar1` that are not in `ar2`. Parameters ---------- ar1 : array_like Input array. ar2 : array_like Input comparison array. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setdiff1d : ndarray 1D array of values in `ar1` that are not in `ar2`. The result is sorted when `assume_unique=False`, but otherwise only sorted if the input is sorted. Examples -------- >>> import numpy as np >>> a = np.array([1, 2, 3, 2, 4, 1]) >>> b = np.array([3, 4, 5, 6]) >>> np.setdiff1d(a, b) array([1, 2]) """ if assume_unique: ar1 = np.asarray(ar1).ravel() else: ar1 = unique(ar1) ar2 = unique(ar2) return ar1[_isin(ar1, ar2, assume_unique=True, invert=True)]
Find the set difference of two arrays. Return the unique values in `ar1` that are not in `ar2`. Parameters ---------- ar1 : array_like Input array. ar2 : array_like Input comparison array. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setdiff1d : ndarray 1D array of values in `ar1` that are not in `ar2`. The result is sorted when `assume_unique=False`, but otherwise only sorted if the input is sorted. Examples -------- >>> import numpy as np >>> a = np.array([1, 2, 3, 2, 4, 1]) >>> b = np.array([3, 4, 5, 6]) >>> np.setdiff1d(a, b) array([1, 2])
python
numpy/lib/_arraysetops_impl.py
1,121
[ "ar1", "ar2", "assume_unique" ]
false
3
7.68
numpy/numpy
31,054
numpy
false
visitExportAssignment
function visitExportAssignment(node: ExportAssignment): VisitResult<ExportAssignment | ExpressionStatement | undefined> { if (node.isExportEquals) { if (getEmitModuleKind(compilerOptions) === ModuleKind.Preserve) { const statement = setOriginalNode( factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression( factory.createIdentifier("module"), "exports", ), node.expression, ), ), node, ); return statement; } // Elide `export=` as it is not legal with --module ES6 return undefined; } return node; }
Visits an ImportEqualsDeclaration node. @param node The node to visit.
typescript
src/compiler/transformers/module/esnextAnd2015.ts
308
[ "node" ]
true
3
6.4
microsoft/TypeScript
107,154
jsdoc
false
convertEnvironment
private ConfigurableEnvironment convertEnvironment(ConfigurableEnvironment environment, Class<? extends ConfigurableEnvironment> type) { ConfigurableEnvironment result = createEnvironment(type); result.setActiveProfiles(environment.getActiveProfiles()); result.setConversionService(environment.getConversionService()); copyPropertySources(environment, result); return result; }
Converts the given {@code environment} to the given {@link StandardEnvironment} type. If the environment is already of the same type, no conversion is performed and it is returned unchanged. @param environment the Environment to convert @param type the type to convert the Environment to @return the converted Environment
java
core/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java
81
[ "environment", "type" ]
ConfigurableEnvironment
true
1
6.4
spring-projects/spring-boot
79,428
javadoc
false
insert
public StrBuilder insert(final int index, final Object obj) { if (obj == null) { return insert(index, nullText); } return insert(index, obj.toString()); }
Inserts the string representation of an object into this builder. Inserting null will use the stored null text value. @param index the index to add at, must be valid @param obj the object to insert @return {@code this} instance. @throws IndexOutOfBoundsException if the index is invalid
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
2,245
[ "index", "obj" ]
StrBuilder
true
2
7.92
apache/commons-lang
2,896
javadoc
false
inclusiveBetween
@SuppressWarnings("boxing") public static void inclusiveBetween(final double start, final double end, final double value) { // TODO when breaking BC, consider returning value if (value < start || value > end) { throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } }
Validate that the specified primitive value falls between the two inclusive values specified; otherwise, throws an exception. <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre> @param start the inclusive start value. @param end the inclusive end value. @param value the value to validate. @throws IllegalArgumentException if the value falls outside the boundaries (inclusive). @since 3.3
java
src/main/java/org/apache/commons/lang3/Validate.java
269
[ "start", "end", "value" ]
void
true
3
6.4
apache/commons-lang
2,896
javadoc
false
collapse_resume_frames
def collapse_resume_frames(stack: StackSummary) -> StackSummary: """ When we graph break, we create a resume function and make a regular Python call to it, which gets intercepted by Dynamo. This behavior is normally shown in the traceback, which can be confusing to a user. So we can filter out resume frames for better traceback clarity. Example: File "..." line 3, in f <line 3> File "..." line 5, in torch_dynamo_resume_in_f_at_80 <line 5> File "..." line 10, in torch_dynamo_resume_in_f_at_120 <line 10> becomes File "..." line 10, in f <line 10> """ new_stack = StackSummary() for frame in stack: if frame.filename is None: continue name = remove_resume_prefix(frame.name) if new_stack and name and new_stack[-1].name == name: new_stack[-1] = frame frame.name = name else: new_stack.append(frame) return new_stack
When we graph break, we create a resume function and make a regular Python call to it, which gets intercepted by Dynamo. This behavior is normally shown in the traceback, which can be confusing to a user. So we can filter out resume frames for better traceback clarity. Example: File "..." line 3, in f <line 3> File "..." line 5, in torch_dynamo_resume_in_f_at_80 <line 5> File "..." line 10, in torch_dynamo_resume_in_f_at_120 <line 10> becomes File "..." line 10, in f <line 10>
python
torch/_dynamo/exc.py
751
[ "stack" ]
StackSummary
true
7
8.48
pytorch/pytorch
96,034
unknown
false
isNaN
function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; }
Checks if `value` is `NaN`. **Note:** This method is based on [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as global [`isNaN`](https://mdn.io/isNaN) which returns `true` for `undefined` and other non-number values. @static @memberOf _ @since 0.1.0 @category Lang @param {*} value The value to check. @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. @example _.isNaN(NaN); // => true _.isNaN(new Number(NaN)); // => true isNaN(undefined); // => true _.isNaN(undefined); // => false
javascript
lodash.js
11,999
[ "value" ]
false
2
7.36
lodash/lodash
61,490
jsdoc
false
lastIndexOf
public static int lastIndexOf(char[] array, char target) { return lastIndexOf(array, target, 0, array.length); }
Returns the index of the last appearance of the value {@code target} in {@code array}. @param array an array of {@code char} values, possibly empty @param target a primitive {@code char} value @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no such index exists.
java
android/guava/src/com/google/common/primitives/Chars.java
201
[ "array", "target" ]
true
1
6.48
google/guava
51,352
javadoc
false
callRunner
private void callRunner(Runner runner, ApplicationArguments args) { if (runner instanceof ApplicationRunner) { callRunner(ApplicationRunner.class, runner, (applicationRunner) -> applicationRunner.run(args)); } if (runner instanceof CommandLineRunner) { callRunner(CommandLineRunner.class, runner, (commandLineRunner) -> commandLineRunner.run(args.getSourceArgs())); } }
Called after the context has been refreshed. @param context the application context @param args the application arguments
java
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
786
[ "runner", "args" ]
void
true
3
6.56
spring-projects/spring-boot
79,428
javadoc
false
byteSize
public abstract int byteSize();
Returns the number of bytes required to encode this TDigest using #asBytes(). @return The number of bytes required.
java
libs/tdigest/src/main/java/org/elasticsearch/tdigest/TDigest.java
175
[]
true
1
6.32
elastic/elasticsearch
75,680
javadoc
false
hsplit
def hsplit(ary, indices_or_sections): """ Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the `split` documentation. `hsplit` is equivalent to `split` with ``axis=1``, the array is always split along the second axis except for 1-D arrays, where it is split at ``axis=0``. See Also -------- split : Split an array into multiple sub-arrays of equal size. Examples -------- >>> import numpy as np >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.hsplit(x, 2) [array([[ 0., 1.], [ 4., 5.], [ 8., 9.], [12., 13.]]), array([[ 2., 3.], [ 6., 7.], [10., 11.], [14., 15.]])] >>> np.hsplit(x, np.array([3, 6])) [array([[ 0., 1., 2.], [ 4., 5., 6.], [ 8., 9., 10.], [12., 13., 14.]]), array([[ 3.], [ 7.], [11.], [15.]]), array([], shape=(4, 0), dtype=float64)] With a higher dimensional array the split is still along the second axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[0., 1.], [2., 3.]], [[4., 5.], [6., 7.]]]) >>> np.hsplit(x, 2) [array([[[0., 1.]], [[4., 5.]]]), array([[[2., 3.]], [[6., 7.]]])] With a 1-D array, the split is along axis 0. >>> x = np.array([0, 1, 2, 3, 4, 5]) >>> np.hsplit(x, 2) [array([0, 1, 2]), array([3, 4, 5])] """ if _nx.ndim(ary) == 0: raise ValueError('hsplit only works on arrays of 1 or more dimensions') if ary.ndim > 1: return split(ary, indices_or_sections, 1) else: return split(ary, indices_or_sections, 0)
Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the `split` documentation. `hsplit` is equivalent to `split` with ``axis=1``, the array is always split along the second axis except for 1-D arrays, where it is split at ``axis=0``. See Also -------- split : Split an array into multiple sub-arrays of equal size. Examples -------- >>> import numpy as np >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.hsplit(x, 2) [array([[ 0., 1.], [ 4., 5.], [ 8., 9.], [12., 13.]]), array([[ 2., 3.], [ 6., 7.], [10., 11.], [14., 15.]])] >>> np.hsplit(x, np.array([3, 6])) [array([[ 0., 1., 2.], [ 4., 5., 6.], [ 8., 9., 10.], [12., 13., 14.]]), array([[ 3.], [ 7.], [11.], [15.]]), array([], shape=(4, 0), dtype=float64)] With a higher dimensional array the split is still along the second axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[0., 1.], [2., 3.]], [[4., 5.], [6., 7.]]]) >>> np.hsplit(x, 2) [array([[[0., 1.]], [[4., 5.]]]), array([[[2., 3.]], [[6., 7.]]])] With a 1-D array, the split is along axis 0. >>> x = np.array([0, 1, 2, 3, 4, 5]) >>> np.hsplit(x, 2) [array([0, 1, 2]), array([3, 4, 5])]
python
numpy/lib/_shape_base_impl.py
864
[ "ary", "indices_or_sections" ]
false
4
7.6
numpy/numpy
31,054
unknown
false
sortAdvisors
protected List<Advisor> sortAdvisors(List<Advisor> advisors) { AnnotationAwareOrderComparator.sort(advisors); return advisors; }
Sort advisors based on ordering. Subclasses may choose to override this method to customize the sorting strategy. @param advisors the source List of Advisors @return the sorted List of Advisors @see org.springframework.core.Ordered @see org.springframework.core.annotation.Order @see org.springframework.core.annotation.AnnotationAwareOrderComparator
java
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java
161
[ "advisors" ]
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
compareTo
@Override public int compareTo(ItemHint other) { return getName().compareTo(other.getName()); }
Return an {@link ItemHint} with the given prefix applied. @param prefix the prefix to apply @return a new {@link ItemHint} with the same of this instance whose property name has the prefix applied to it
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemHint.java
85
[ "other" ]
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
maybeCompleteValidation
public synchronized Optional<LogTruncation> maybeCompleteValidation(TopicPartition tp, FetchPosition requestPosition, EpochEndOffset epochEndOffset) { TopicPartitionState state = assignedStateOrNull(tp); if (state == null) { log.debug("Skipping completed validation for partition {} which is not currently assigned.", tp); } else if (!state.awaitingValidation()) { log.debug("Skipping completed validation for partition {} which is no longer expecting validation.", tp); } else { SubscriptionState.FetchPosition currentPosition = state.position; if (!currentPosition.equals(requestPosition)) { log.debug("Skipping completed validation for partition {} since the current position {} " + "no longer matches the position {} when the request was sent", tp, currentPosition, requestPosition); } else if (epochEndOffset.endOffset() == UNDEFINED_EPOCH_OFFSET || epochEndOffset.leaderEpoch() == UNDEFINED_EPOCH) { if (hasDefaultOffsetResetPolicy()) { log.info("Truncation detected for partition {} at offset {}, resetting offset", tp, currentPosition); requestOffsetReset(tp); } else { log.warn("Truncation detected for partition {} at offset {}, but no reset policy is set", tp, currentPosition); return Optional.of(new LogTruncation(tp, requestPosition, Optional.empty())); } } else if (epochEndOffset.endOffset() < currentPosition.offset) { if (hasDefaultOffsetResetPolicy()) { SubscriptionState.FetchPosition newPosition = new SubscriptionState.FetchPosition( epochEndOffset.endOffset(), Optional.of(epochEndOffset.leaderEpoch()), currentPosition.currentLeader); log.info("Truncation detected for partition {} at offset {}, resetting offset to " + "the first offset known to diverge {}", tp, currentPosition, newPosition); state.seekValidated(newPosition); } else { OffsetAndMetadata divergentOffset = new OffsetAndMetadata(epochEndOffset.endOffset(), Optional.of(epochEndOffset.leaderEpoch()), null); log.warn("Truncation detected for partition {} at offset {} (the end offset from the " + "broker is {}), but no reset policy is set", tp, currentPosition, divergentOffset); return Optional.of(new LogTruncation(tp, requestPosition, Optional.of(divergentOffset))); } } else { state.completeValidation(); } } return Optional.empty(); }
Attempt to complete validation with the end offset returned from the OffsetForLeaderEpoch request. @return Log truncation details if detected and no reset policy is defined.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
568
[ "tp", "requestPosition", "epochEndOffset" ]
true
9
6.4
apache/kafka
31,560
javadoc
false
parseProjectTypes
private MetadataHolder<String, ProjectType> parseProjectTypes(JSONObject root) throws JSONException { MetadataHolder<String, ProjectType> result = new MetadataHolder<>(); if (!root.has(TYPE_EL)) { return result; } JSONObject type = root.getJSONObject(TYPE_EL); JSONArray array = type.getJSONArray(VALUES_EL); String defaultType = (type.has(DEFAULT_ATTRIBUTE) ? type.getString(DEFAULT_ATTRIBUTE) : null); for (int i = 0; i < array.length(); i++) { JSONObject typeJson = array.getJSONObject(i); ProjectType projectType = parseType(typeJson, defaultType); result.getContent().put(projectType.getId(), projectType); if (projectType.isDefaultType()) { result.setDefaultItem(projectType); } } return result; }
Returns the defaults applicable to the service. @return the defaults of the service
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrServiceMetadata.java
144
[ "root" ]
true
5
6.88
spring-projects/spring-boot
79,428
javadoc
false
invokeMethod
public static Object invokeMethod(final Object object, final boolean forceAccess, final String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { return invokeMethod(object, forceAccess, methodName, ArrayUtils.EMPTY_OBJECT_ARRAY, null); }
Invokes a named method without parameters. <p> This is a convenient wrapper for {@link #invokeMethod(Object object, boolean forceAccess, String methodName, Object[] args, Class[] parameterTypes)}. </p> @param object invoke method on this object. @param forceAccess force access to invoke method even if it's not accessible. @param methodName get method with this name. @return The value returned by the invoked method. @throws NoSuchMethodException Thrown if there is no such accessible method. @throws IllegalAccessException Thrown if this found {@code Method} is enforcing Java language access control and the underlying method is inaccessible. @throws IllegalArgumentException Thrown if: <ul> <li>the found {@code Method} is an instance method and the specified {@code object} argument is not an instance of the class or interface declaring the underlying method (or of a subclass or interface implementor);</li> <li>the number of actual and formal parameters differ;</li> <li>an unwrapping conversion for primitive arguments fails; or</li> <li>after possible unwrapping, a parameter value can't be converted to the corresponding formal parameter type by a method invocation conversion.</li> </ul> @throws InvocationTargetException Thrown if the underlying method throws an exception. @throws NullPointerException Thrown if the specified {@code object} is null. @throws ExceptionInInitializerError Thrown if the initialization provoked by this method fails. @see SecurityManager#checkPermission @since 3.5
java
src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
731
[ "object", "forceAccess", "methodName" ]
Object
true
1
6.16
apache/commons-lang
2,896
javadoc
false
any
def any( self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs ) -> np.bool_ | NAType: """ Return whether any element is truthy. Returns False unless there is at least one element that is truthy. By default, NAs are skipped. If ``skipna=False`` is specified and missing values are present, similar :ref:`Kleene logic <boolean.kleene>` is used as for logical operations. Parameters ---------- skipna : bool, default True Exclude NA values. If the entire array is NA and `skipna` is True, then the result will be False, as for an empty array. If `skipna` is False, the result will still be True if there is at least one element that is truthy, otherwise NA will be returned if there are NA's present. axis : int, optional, default 0 **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- bool or :attr:`pandas.NA` See Also -------- numpy.any : Numpy version of this method. BaseMaskedArray.all : Return whether all elements are truthy. Examples -------- The result indicates whether any element is truthy (and by default skips NAs): >>> pd.array([True, False, True]).any() np.True_ >>> pd.array([True, False, pd.NA]).any() np.True_ >>> pd.array([False, False, pd.NA]).any() np.False_ >>> pd.array([], dtype="boolean").any() np.False_ >>> pd.array([pd.NA], dtype="boolean").any() np.False_ >>> pd.array([pd.NA], dtype="Float64").any() np.False_ With ``skipna=False``, the result can be NA if this is logically required (whether ``pd.NA`` is True or False influences the result): >>> pd.array([True, False, pd.NA]).any(skipna=False) np.True_ >>> pd.array([1, 0, pd.NA]).any(skipna=False) np.True_ >>> pd.array([False, False, pd.NA]).any(skipna=False) <NA> >>> pd.array([0, 0, pd.NA]).any(skipna=False) <NA> """ nv.validate_any((), kwargs) values = self._data.copy() np.putmask(values, self._mask, self.dtype._falsey_value) result = values.any() if skipna: return result else: if result or len(self) == 0 or not self._mask.any(): return result else: return self.dtype.na_value
Return whether any element is truthy. Returns False unless there is at least one element that is truthy. By default, NAs are skipped. If ``skipna=False`` is specified and missing values are present, similar :ref:`Kleene logic <boolean.kleene>` is used as for logical operations. Parameters ---------- skipna : bool, default True Exclude NA values. If the entire array is NA and `skipna` is True, then the result will be False, as for an empty array. If `skipna` is False, the result will still be True if there is at least one element that is truthy, otherwise NA will be returned if there are NA's present. axis : int, optional, default 0 **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- bool or :attr:`pandas.NA` See Also -------- numpy.any : Numpy version of this method. BaseMaskedArray.all : Return whether all elements are truthy. Examples -------- The result indicates whether any element is truthy (and by default skips NAs): >>> pd.array([True, False, True]).any() np.True_ >>> pd.array([True, False, pd.NA]).any() np.True_ >>> pd.array([False, False, pd.NA]).any() np.False_ >>> pd.array([], dtype="boolean").any() np.False_ >>> pd.array([pd.NA], dtype="boolean").any() np.False_ >>> pd.array([pd.NA], dtype="Float64").any() np.False_ With ``skipna=False``, the result can be NA if this is logically required (whether ``pd.NA`` is True or False influences the result): >>> pd.array([True, False, pd.NA]).any(skipna=False) np.True_ >>> pd.array([1, 0, pd.NA]).any(skipna=False) np.True_ >>> pd.array([False, False, pd.NA]).any(skipna=False) <NA> >>> pd.array([0, 0, pd.NA]).any(skipna=False) <NA>
python
pandas/core/arrays/masked.py
1,705
[ "self", "skipna", "axis" ]
np.bool_ | NAType
true
7
8.08
pandas-dev/pandas
47,362
numpy
false
mean_gamma_deviance
def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): """Mean Gamma deviance regression loss. Gamma deviance is equivalent to the Tweedie deviance with the power parameter `power=2`. It is invariant to scaling of the target variable, and measures relative errors. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. Requires y_true > 0. y_pred : array-like of shape (n_samples,) Estimated target values. Requires y_pred > 0. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_gamma_deviance >>> y_true = [2, 0.5, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_gamma_deviance(y_true, y_pred) 1.0568... """ return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2)
Mean Gamma deviance regression loss. Gamma deviance is equivalent to the Tweedie deviance with the power parameter `power=2`. It is invariant to scaling of the target variable, and measures relative errors. Read more in the :ref:`User Guide <mean_tweedie_deviance>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. Requires y_true > 0. y_pred : array-like of shape (n_samples,) Estimated target values. Requires y_pred > 0. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- loss : float A non-negative floating point value (the best value is 0.0). Examples -------- >>> from sklearn.metrics import mean_gamma_deviance >>> y_true = [2, 0.5, 1, 4] >>> y_pred = [0.5, 0.5, 2., 2.] >>> mean_gamma_deviance(y_true, y_pred) 1.0568...
python
sklearn/metrics/_regression.py
1,537
[ "y_true", "y_pred", "sample_weight" ]
false
1
6
scikit-learn/scikit-learn
64,340
numpy
false
scale
public ExponentialHistogramBuilder scale(int scale) { this.scale = scale; return this; }
If known, sets the estimated total number of buckets to minimize unnecessary allocations. Only has an effect if invoked before the first call to {@link #setPositiveBucket(long, long)} and {@link #setNegativeBucket(long, long)}. @param totalBuckets the total number of buckets expected to be added @return the builder
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramBuilder.java
92
[ "scale" ]
ExponentialHistogramBuilder
true
1
6
elastic/elasticsearch
75,680
javadoc
false
_decide_split_path
def _decide_split_path(self, indexer, value) -> bool: """ Decide whether we will take a block-by-block path. """ take_split_path = not self.obj._mgr.is_single_block if not take_split_path and isinstance(value, ABCDataFrame): # Avoid cast of values take_split_path = not value._mgr.is_single_block # if there is only one block/type, still have to take split path # unless the block is one-dimensional or it can hold the value if not take_split_path and len(self.obj._mgr.blocks) and self.ndim > 1: # in case of dict, keys are indices val = list(value.values()) if isinstance(value, dict) else value arr = self.obj._mgr.blocks[0].values take_split_path = not can_hold_element( arr, extract_array(val, extract_numpy=True) ) # if we have any multi-indexes that have non-trivial slices # (not null slices) then we must take the split path, xref # GH 10360, GH 27841 if isinstance(indexer, tuple) and len(indexer) == len(self.obj.axes): for i, ax in zip(indexer, self.obj.axes, strict=True): if isinstance(ax, MultiIndex) and not ( is_integer(i) or com.is_null_slice(i) ): take_split_path = True break return take_split_path
Decide whether we will take a block-by-block path.
python
pandas/core/indexing.py
1,806
[ "self", "indexer", "value" ]
bool
true
13
6
pandas-dev/pandas
47,362
unknown
false
visitCommaExpression
function visitCommaExpression(node: BinaryExpression) { // [source] // x = a(), yield, b(); // // [intermediate] // a(); // .yield resumeLabel // .mark resumeLabel // x = %sent%, b(); let pendingExpressions: Expression[] = []; visit(node.left); visit(node.right); return factory.inlineExpressions(pendingExpressions); function visit(node: Expression) { if (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.CommaToken) { visit(node.left); visit(node.right); } else { if (containsYield(node) && pendingExpressions.length > 0) { emitWorker(OpCode.Statement, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]); pendingExpressions = []; } pendingExpressions.push(Debug.checkDefined(visitNode(node, visitor, isExpression))); } } }
Visits a comma expression containing `yield`. @param node The node to visit.
typescript
src/compiler/transformers/generators.ts
879
[ "node" ]
false
6
6.08
microsoft/TypeScript
107,154
jsdoc
false
get_cluster_state
def get_cluster_state(self, clusterName: str) -> ClusterStates: """ Return the current status of a given Amazon EKS Cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_cluster` :param clusterName: The name of the cluster to check. :return: Returns the current status of a given Amazon EKS Cluster. """ eks_client = self.conn try: return ClusterStates(eks_client.describe_cluster(name=clusterName).get("cluster").get("status")) except ClientError as ex: if ex.response.get("Error").get("Code") == "ResourceNotFoundException": return ClusterStates.NONEXISTENT raise
Return the current status of a given Amazon EKS Cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_cluster` :param clusterName: The name of the cluster to check. :return: Returns the current status of a given Amazon EKS Cluster.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/eks.py
393
[ "self", "clusterName" ]
ClusterStates
true
2
7.6
apache/airflow
43,597
sphinx
false
_implementation
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 3.10.3 it will return {'name': 'CPython', 'version': '3.10.3'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == "CPython": implementation_version = platform.python_version() elif implementation == "PyPy": implementation_version = "{}.{}.{}".format( sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro, ) if sys.pypy_version_info.releaselevel != "final": implementation_version = "".join( [implementation_version, sys.pypy_version_info.releaselevel] ) elif implementation == "Jython": implementation_version = platform.python_version() # Complete Guess elif implementation == "IronPython": implementation_version = platform.python_version() # Complete Guess else: implementation_version = "Unknown" return {"name": implementation, "version": implementation_version}
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 3.10.3 it will return {'name': 'CPython', 'version': '3.10.3'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms.
python
src/requests/help.py
34
[]
false
7
6.08
psf/requests
53,586
unknown
false
chebmul
def chebmul(c1, c2): """ Multiply one Chebyshev series by another. Returns the product of two Chebyshev series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their product. See Also -------- chebadd, chebsub, chebmulx, chebdiv, chebpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "reproject" the product onto said basis set, which typically produces "unintuitive live" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) z1 = _cseries_to_zseries(c1) z2 = _cseries_to_zseries(c2) prd = _zseries_mul(z1, z2) ret = _zseries_to_cseries(prd) return pu.trimseq(ret)
Multiply one Chebyshev series by another. Returns the product of two Chebyshev series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Chebyshev series coefficients ordered from low to high. Returns ------- out : ndarray Of Chebyshev series coefficients representing their product. See Also -------- chebadd, chebsub, chebmulx, chebdiv, chebpow Notes ----- In general, the (polynomial) product of two C-series results in terms that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "reproject" the product onto said basis set, which typically produces "unintuitive live" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import chebyshev as C >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> C.chebmul(c1,c2) # multiplication requires "reprojection" array([ 6.5, 12. , 12. , 4. , 1.5])
python
numpy/polynomial/chebyshev.py
698
[ "c1", "c2" ]
false
1
6.48
numpy/numpy
31,054
numpy
false
partition
public static <T extends @Nullable Object> Iterable<List<T>> partition( Iterable<T> iterable, int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; }
Divides an iterable into unmodifiable sublists of the given size (the final iterable may be smaller). For example, partitioning an iterable containing {@code [a, b, c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterable containing two inner lists of three and two elements, all in the original order. <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} method. The returned lists implement {@link RandomAccess}, whether or not the input list does. <p><b>Note:</b> The current implementation eagerly allocates storage for {@code size} elements. As a consequence, passing values like {@code Integer.MAX_VALUE} can lead to {@link OutOfMemoryError}. <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link Lists#partition(List, int)} instead. @param iterable the iterable to return a partitioned view of @param size the desired size of each partition (the last may be smaller) @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided into partitions @throws IllegalArgumentException if {@code size} is nonpositive
java
android/guava/src/com/google/common/collect/Iterables.java
565
[ "iterable", "size" ]
true
1
6.56
google/guava
51,352
javadoc
false
_fix_real_lt_zero
def _fix_real_lt_zero(x): """Convert `x` to complex if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> import numpy as np >>> np.lib.scimath._fix_real_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_real_lt_zero([-1,2]) array([-1.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (x < 0)): x = _tocomplex(x) return x
Convert `x` to complex if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> import numpy as np >>> np.lib.scimath._fix_real_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_real_lt_zero([-1,2]) array([-1.+0.j, 2.+0.j])
python
numpy/lib/_scimath_impl.py
96
[ "x" ]
false
2
7.36
numpy/numpy
31,054
numpy
false
normalize
def normalize(self) -> Self: """ Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``.dt`` accessor, and directly on Datetime Array/Index. Returns ------- DatetimeArray, DatetimeIndex or Series The same type as the original data. Series will have the same name and index. DatetimeIndex will have the same name. See Also -------- floor : Floor the datetimes to the specified freq. ceil : Ceil the datetimes to the specified freq. round : Round the datetimes to the specified freq. Examples -------- >>> idx = pd.date_range( ... start="2014-08-01 10:00", freq="h", periods=3, tz="Asia/Calcutta" ... ) >>> idx DatetimeIndex(['2014-08-01 10:00:00+05:30', '2014-08-01 11:00:00+05:30', '2014-08-01 12:00:00+05:30'], dtype='datetime64[us, Asia/Calcutta]', freq='h') >>> idx.normalize() DatetimeIndex(['2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30'], dtype='datetime64[us, Asia/Calcutta]', freq=None) """ new_values = normalize_i8_timestamps(self.asi8, self.tz, reso=self._creso) dt64_values = new_values.view(self._ndarray.dtype) dta = type(self)._simple_new(dt64_values, dtype=dt64_values.dtype) dta = dta._with_freq("infer") if self.tz is not None: dta = dta.tz_localize(self.tz) return dta
Convert times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases, when the time does not matter. Length is unaltered. The timezones are unaffected. This method is available on Series with datetime values under the ``.dt`` accessor, and directly on Datetime Array/Index. Returns ------- DatetimeArray, DatetimeIndex or Series The same type as the original data. Series will have the same name and index. DatetimeIndex will have the same name. See Also -------- floor : Floor the datetimes to the specified freq. ceil : Ceil the datetimes to the specified freq. round : Round the datetimes to the specified freq. Examples -------- >>> idx = pd.date_range( ... start="2014-08-01 10:00", freq="h", periods=3, tz="Asia/Calcutta" ... ) >>> idx DatetimeIndex(['2014-08-01 10:00:00+05:30', '2014-08-01 11:00:00+05:30', '2014-08-01 12:00:00+05:30'], dtype='datetime64[us, Asia/Calcutta]', freq='h') >>> idx.normalize() DatetimeIndex(['2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30', '2014-08-01 00:00:00+05:30'], dtype='datetime64[us, Asia/Calcutta]', freq=None)
python
pandas/core/arrays/datetimes.py
1,154
[ "self" ]
Self
true
2
8
pandas-dev/pandas
47,362
unknown
false
scanClassAtom
function scanClassAtom(): string { if (charCodeChecked(pos) === CharacterCodes.backslash) { pos++; const ch = charCodeChecked(pos); switch (ch) { case CharacterCodes.b: pos++; return "\b"; case CharacterCodes.minus: pos++; return String.fromCharCode(ch); default: if (scanCharacterClassEscape()) { return ""; } return scanCharacterEscape(/*atomEscape*/ false); } } else { return scanSourceCharacter(); } }
A stack of scopes for named capturing groups. @see {scanGroupName}
typescript
src/compiler/scanner.ts
3,440
[]
true
4
6.4
microsoft/TypeScript
107,154
jsdoc
false
getTargetClass
@Override public synchronized Class<?> getTargetClass() { if (this.targetObject == null) { refresh(); } return this.targetObject.getClass(); }
Set the delay between refresh checks, in milliseconds. Default is -1, indicating no refresh checks at all. <p>Note that an actual refresh will only happen when {@link #requiresRefresh()} returns {@code true}.
java
spring-aop/src/main/java/org/springframework/aop/target/dynamic/AbstractRefreshableTargetSource.java
68
[]
true
2
6.72
spring-projects/spring-framework
59,386
javadoc
false
acquisitionLockTimeoutMs
public Optional<Integer> acquisitionLockTimeoutMs() { return acquisitionLockTimeoutMs; }
@return The most up-to-date value of acquisition lock timeout, if available
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareFetch.java
122
[]
true
1
6.16
apache/kafka
31,560
javadoc
false
withLineSeparator
public StandardStackTracePrinter withLineSeparator(String lineSeparator) { Assert.notNull(lineSeparator, "'lineSeparator' must not be null"); return new StandardStackTracePrinter(this.options, this.maximumLength, lineSeparator, this.filter, this.frameFilter, this.formatter, this.frameFormatter, this.frameHasher); }
Return a new {@link StandardStackTracePrinter} from this one that print the stack trace using the specified line separator. @param lineSeparator the line separator to use @return a new {@link StandardStackTracePrinter} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/StandardStackTracePrinter.java
225
[ "lineSeparator" ]
StandardStackTracePrinter
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
from_custom_template
def from_custom_template( cls, searchpath: Sequence[str], html_table: str | None = None, html_style: str | None = None, ) -> type[Styler]: """ Factory function for creating a subclass of ``Styler``. Uses custom templates and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates. html_table : str Name of your custom template to replace the html_table template. html_style : str Name of your custom template to replace the html_style template. Returns ------- MyStyler : subclass of Styler Has the correct ``env``, ``template_html``, ``template_html_table`` and ``template_html_style`` class attributes set. See Also -------- Styler.export : Export the styles applied to the current Styler. Styler.use : Set the styles on the current Styler. Examples -------- >>> from pandas.io.formats.style import Styler >>> EasyStyler = Styler.from_custom_template( ... "path/to/template", ... "template.tpl", ... ) # doctest: +SKIP >>> df = pd.DataFrame({"A": [1, 2]}) >>> EasyStyler(df) # doctest: +SKIP Please see: `Table Visualization <../../user_guide/style.ipynb>`_ for more examples. """ loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(searchpath), cls.loader]) # mypy doesn't like dynamically-defined classes # error: Variable "cls" is not valid as a type # error: Invalid base class "cls" class MyStyler(cls): # type: ignore[valid-type,misc] env = jinja2.Environment(loader=loader) if html_table: template_html_table = env.get_template(html_table) if html_style: template_html_style = env.get_template(html_style) return MyStyler
Factory function for creating a subclass of ``Styler``. Uses custom templates and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates. html_table : str Name of your custom template to replace the html_table template. html_style : str Name of your custom template to replace the html_style template. Returns ------- MyStyler : subclass of Styler Has the correct ``env``, ``template_html``, ``template_html_table`` and ``template_html_style`` class attributes set. See Also -------- Styler.export : Export the styles applied to the current Styler. Styler.use : Set the styles on the current Styler. Examples -------- >>> from pandas.io.formats.style import Styler >>> EasyStyler = Styler.from_custom_template( ... "path/to/template", ... "template.tpl", ... ) # doctest: +SKIP >>> df = pd.DataFrame({"A": [1, 2]}) >>> EasyStyler(df) # doctest: +SKIP Please see: `Table Visualization <../../user_guide/style.ipynb>`_ for more examples.
python
pandas/io/formats/style.py
3,684
[ "cls", "searchpath", "html_table", "html_style" ]
type[Styler]
true
3
8.16
pandas-dev/pandas
47,362
numpy
false
try_import_cutlass
def try_import_cutlass() -> bool: """ We want to support three ways of passing in CUTLASS: 1. fbcode, handled by the internal build system. 2. User specifies cutlass_dir. The default is ../third_party/cutlass/, which is the directory when developers build from source. """ if config.is_fbcode(): try: import cutlass_cppgen # type: ignore[import-not-found] # noqa: F401 import cutlass_library # type: ignore[import-not-found] except ImportError as e: log.warning( # noqa: G200 "Failed to import CUTLASS packages in fbcode: %s, ignoring the CUTLASS backend.", str(e), ) return False return True # Copy CUTLASS python scripts to a temp dir and add the temp dir to Python search path. # This is a temporary hack to avoid CUTLASS module naming conflicts. # TODO(ipiszy): remove this hack when CUTLASS solves Python scripts packaging structure issues. # TODO(mlazos): epilogue visitor tree currently lives in python/cutlass, # but will be moved to python/cutlass_library in the future (later 2025) def path_join(path0, path1): return os.path.abspath(os.path.join(path0, path1)) # contains both cutlass and cutlass_library # we need cutlass for eVT cutlass_python_path = path_join(config.cuda.cutlass_dir, "python") torch_root = os.path.abspath(os.path.dirname(torch.__file__)) mock_src_path = os.path.join( torch_root, "_inductor", "codegen", "cuda", "cutlass_lib_extensions", "cutlass_mock_imports", ) cutlass_library_src_path = path_join(cutlass_python_path, "cutlass_library") cutlass_cppgen_src_path = path_join(cutlass_python_path, "cutlass_cppgen") pycute_src_path = path_join(cutlass_python_path, "pycute") tmp_cutlass_full_path = os.path.abspath(os.path.join(cache_dir(), "torch_cutlass")) dst_link_library = path_join(tmp_cutlass_full_path, "cutlass_library") dst_link_cutlass_cppgen = path_join(tmp_cutlass_full_path, "cutlass_cppgen") dst_link_pycute = path_join(tmp_cutlass_full_path, "pycute") # mock modules to import cutlass mock_modules = ["cuda", "scipy", "pydot"] if os.path.isdir(cutlass_python_path): if tmp_cutlass_full_path not in sys.path: def link_and_append(dst_link, src_path, parent_dir): if os.path.lexists(dst_link): assert os.path.islink(dst_link), ( f"{dst_link} is not a symlink. Try to remove {dst_link} manually and try again." ) assert os.path.realpath(os.readlink(dst_link)) == os.path.realpath( src_path, ), f"Symlink at {dst_link} does not point to {src_path}" else: os.makedirs(parent_dir, exist_ok=True) os.symlink(src_path, dst_link) if parent_dir not in sys.path: sys.path.append(parent_dir) link_and_append( dst_link_library, cutlass_library_src_path, tmp_cutlass_full_path ) link_and_append( dst_link_cutlass_cppgen, cutlass_cppgen_src_path, tmp_cutlass_full_path ) link_and_append(dst_link_pycute, pycute_src_path, tmp_cutlass_full_path) for module in mock_modules: link_and_append( path_join(tmp_cutlass_full_path, module), # dst_link path_join(mock_src_path, module), # src_path tmp_cutlass_full_path, # parent ) try: import cutlass_cppgen # type: ignore[import-not-found] # noqa: F401, F811 import cutlass_library.generator # noqa: F401 import cutlass_library.library # noqa: F401 import cutlass_library.manifest # noqa: F401 import pycute # type: ignore[import-not-found] # noqa: F401 return True except ImportError as e: log.debug( # noqa: G200 "Failed to import CUTLASS packages: %s, ignoring the CUTLASS backend.", str(e), ) else: log.debug( "Failed to import CUTLASS packages: CUTLASS repo does not exist: %s", cutlass_python_path, ) return False
We want to support three ways of passing in CUTLASS: 1. fbcode, handled by the internal build system. 2. User specifies cutlass_dir. The default is ../third_party/cutlass/, which is the directory when developers build from source.
python
torch/_inductor/codegen/cuda/cutlass_utils.py
70
[]
bool
true
9
6.8
pytorch/pytorch
96,034
unknown
false
apply
public static <I, O, T extends Throwable> O apply(final FailableFunction<I, O, T> function, final I input) { return get(() -> function.apply(input)); }
Applies a function and rethrows any exception as a {@link RuntimeException}. @param function the function to apply @param input the input to apply {@code function} on @param <I> the type of the argument the function accepts @param <O> the return type of the function @param <T> the type of checked exception the function may throw @return the value returned from the function
java
src/main/java/org/apache/commons/lang3/Functions.java
339
[ "function", "input" ]
O
true
1
6.48
apache/commons-lang
2,896
javadoc
false
trySelfParentPath
function trySelfParentPath(parent) { if (!parent) { return false; } if (parent.filename) { return parent.filename; } else if (parent.id === '<repl>' || parent.id === 'internal/preload') { try { return process.cwd() + path.sep; } catch { return false; } } }
Tries to get the absolute file path of the parent module. @param {Module} parent The parent module object. @returns {string|false|void}
javascript
lib/internal/modules/cjs/loader.js
603
[ "parent" ]
false
7
6.24
nodejs/node
114,839
jsdoc
false
reverse
public static void reverse(final boolean[] array) { if (array == null) { return; } reverse(array, 0, array.length); }
Reverses the order of the given array. <p> This method does nothing for a {@code null} input array. </p> @param array the array to reverse, may be {@code null}.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
6,341
[ "array" ]
void
true
2
7.04
apache/commons-lang
2,896
javadoc
false
_called_with_wrong_args
def _called_with_wrong_args(f: t.Callable[..., Flask]) -> bool: """Check whether calling a function raised a ``TypeError`` because the call failed or because something in the factory raised the error. :param f: The function that was called. :return: ``True`` if the call failed. """ tb = sys.exc_info()[2] try: while tb is not None: if tb.tb_frame.f_code is f.__code__: # In the function, it was called successfully. return False tb = tb.tb_next # Didn't reach the function. return True finally: # Delete tb to break a circular reference. # https://docs.python.org/2/library/sys.html#sys.exc_info del tb
Check whether calling a function raised a ``TypeError`` because the call failed or because something in the factory raised the error. :param f: The function that was called. :return: ``True`` if the call failed.
python
src/flask/cli.py
94
[ "f" ]
bool
true
3
8.24
pallets/flask
70,946
sphinx
false
generator
public XContentGenerator generator() { return this.generator; }
Returns a version used for serialising a response. @return a compatible version
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java
1,295
[]
XContentGenerator
true
1
6.64
elastic/elasticsearch
75,680
javadoc
false
asPemSslStoreDetails
private static PemSslStoreDetails asPemSslStoreDetails(PemSslBundleProperties.Store properties) { return new PemSslStoreDetails(properties.getType(), properties.getCertificate(), properties.getPrivateKey(), properties.getPrivateKeyPassword()); }
Get an {@link SslBundle} for the given {@link PemSslBundleProperties}. @param properties the source properties @param resourceLoader the resource loader used to load content @return an {@link SslBundle} instance @since 3.3.5
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/ssl/PropertiesSslBundle.java
146
[ "properties" ]
PemSslStoreDetails
true
1
6.48
spring-projects/spring-boot
79,428
javadoc
false
findCachedValue
private @Nullable Object findCachedValue(CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) { for (CacheOperationContext context : contexts.get(CacheableOperation.class)) { if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) { Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT); Object cached = findInCaches(context, key, invoker, method, contexts); if (cached != null) { if (logger.isTraceEnabled()) { logger.trace("Cache entry for key '" + key + "' found in cache(s) " + context.getCacheNames()); } return cached; } else { if (logger.isTraceEnabled()) { logger.trace("No cache entry for key '" + key + "' in cache(s) " + context.getCacheNames()); } } } } return null; }
Find a cached value only for {@link CacheableOperation} that passes the condition. @param contexts the cacheable operations @return a {@link Cache.ValueWrapper} holding the cached value, or {@code null} if none is found
java
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
509
[ "invoker", "method", "contexts" ]
Object
true
5
7.92
spring-projects/spring-framework
59,386
javadoc
false
get
public static ElasticCommonSchemaProperties get(Environment environment) { return Binder.get(environment) .bind("logging.structured.ecs", ElasticCommonSchemaProperties.class) .orElse(NONE) .withDefaults(environment); }
Return a new {@link ElasticCommonSchemaProperties} from bound from properties in the given {@link Environment}. @param environment the source environment @return a new {@link ElasticCommonSchemaProperties} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/ElasticCommonSchemaProperties.java
65
[ "environment" ]
ElasticCommonSchemaProperties
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
transformAsyncFunctionParameterList
function transformAsyncFunctionParameterList(node: FunctionLikeDeclaration) { if (isSimpleParameterList(node.parameters)) { return visitParameterList(node.parameters, visitor, context); } const newParameters: ParameterDeclaration[] = []; for (const parameter of node.parameters) { if (parameter.initializer || parameter.dotDotDotToken) { // for an arrow function, capture the remaining arguments in a rest parameter. // for any other function/method this isn't necessary as we can just use `arguments`. if (node.kind === SyntaxKind.ArrowFunction) { const restParameter = factory.createParameterDeclaration( /*modifiers*/ undefined, factory.createToken(SyntaxKind.DotDotDotToken), factory.createUniqueName("args", GeneratedIdentifierFlags.ReservedInNestedScopes), ); newParameters.push(restParameter); } break; } // for arrow functions we capture fixed parameters to forward to `__awaiter`. For all other functions // we add fixed parameters to preserve the function's `length` property. const newParameter = factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(parameter.name, GeneratedIdentifierFlags.ReservedInNestedScopes), ); newParameters.push(newParameter); } const newParametersArray = factory.createNodeArray(newParameters); setTextRange(newParametersArray, node.parameters); return newParametersArray; }
Visits an ArrowFunction. This function will be called when one of the following conditions are met: - The node is marked async @param node The node to visit.
typescript
src/compiler/transformers/es2017.ts
702
[ "node" ]
false
5
6.08
microsoft/TypeScript
107,154
jsdoc
false
leastSquaresFit
public LinearTransformation leastSquaresFit() { checkState(count() > 1); if (isNaN(sumOfProductsOfDeltas)) { return LinearTransformation.forNaN(); } double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas(); if (xSumOfSquaresOfDeltas > 0.0) { if (yStats.sumOfSquaresOfDeltas() > 0.0) { return LinearTransformation.mapping(xStats.mean(), yStats.mean()) .withSlope(sumOfProductsOfDeltas / xSumOfSquaresOfDeltas); } else { return LinearTransformation.horizontal(yStats.mean()); } } else { checkState(yStats.sumOfSquaresOfDeltas() > 0.0); return LinearTransformation.vertical(xStats.mean()); } }
Returns a linear transformation giving the best fit to the data according to <a href="http://mathworld.wolfram.com/LeastSquaresFitting.html">Ordinary Least Squares linear regression</a> of {@code y} as a function of {@code x}. The count must be greater than one, and either the {@code x} or {@code y} data must have a non-zero population variance (i.e. {@code xStats().populationVariance() > 0.0 || yStats().populationVariance() > 0.0}). The result is guaranteed to be horizontal if there is variance in the {@code x} data but not the {@code y} data, and vertical if there is variance in the {@code y} data but not the {@code x} data. <p>This fit minimizes the root-mean-square error in {@code y} as a function of {@code x}. This error is defined as the square root of the mean of the squares of the differences between the actual {@code y} values of the data and the values predicted by the fit for the {@code x} values (i.e. it is the square root of the mean of the squares of the vertical distances between the data points and the best fit line). For this fit, this error is a fraction {@code sqrt(1 - R*R)} of the population standard deviation of {@code y}, where {@code R} is the Pearson's correlation coefficient (as given by {@link #pearsonsCorrelationCoefficient()}). <p>The corresponding root-mean-square error in {@code x} as a function of {@code y} is a fraction {@code sqrt(1/(R*R) - 1)} of the population standard deviation of {@code x}. This fit does not normally minimize that error: to do that, you should swap the roles of {@code x} and {@code y}. <h3>Non-finite values</h3> <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link LinearTransformation#forNaN()}. @throws IllegalStateException if the dataset is empty or contains a single pair of values, or both the {@code x} and {@code y} dataset must have zero population variance
java
android/guava/src/com/google/common/math/PairedStats.java
181
[]
LinearTransformation
true
4
6.72
google/guava
51,352
javadoc
false
toString
@Override public String toString() { return getClass().getName() + ": class = " + this.clazz.getName() + "; methodNamePatterns = " + this.methodNamePatterns; }
Determine if the given method name matches the method name pattern. <p>This method is invoked by {@link #isMatch(String, int)}. <p>The default implementation checks for direct equality as well as {@code xxx*}, {@code *xxx}, {@code *xxx*}, and {@code xxx*yyy} matches. <p>Can be overridden in subclasses &mdash; for example, to support a different style of simple pattern matching. @param methodName the method name to check @param methodNamePattern the method name pattern @return {@code true} if the method name matches the pattern @since 6.1 @see #isMatch(String, int) @see PatternMatchUtils#simpleMatch(String, String)
java
spring-aop/src/main/java/org/springframework/aop/support/ControlFlowPointcut.java
250
[]
String
true
1
6.32
spring-projects/spring-framework
59,386
javadoc
false
strip
public static String strip(String str, final String stripChars) { str = stripStart(str, stripChars); return stripEnd(str, stripChars); }
Strips any of a set of characters from the start and end of a String. This is similar to {@link String#trim()} but allows the characters to be stripped to be controlled. <p> A {@code null} input String returns {@code null}. An empty string ("") input returns the empty string. </p> <p> If the stripChars String is {@code null}, whitespace is stripped as defined by {@link Character#isWhitespace(char)}. Alternatively use {@link #strip(String)}. </p> <pre> StringUtils.strip(null, *) = null StringUtils.strip("", *) = "" StringUtils.strip("abc", null) = "abc" StringUtils.strip(" abc", null) = "abc" StringUtils.strip("abc ", null) = "abc" StringUtils.strip(" abc ", null) = "abc" StringUtils.strip(" abcyx", "xyz") = " abc" </pre> @param str the String to remove characters from, may be null. @param stripChars the characters to remove, null treated as whitespace. @return the stripped String, {@code null} if null String input.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
7,831
[ "str", "stripChars" ]
String
true
1
6.64
apache/commons-lang
2,896
javadoc
false
flatnonzero
def flatnonzero(a): """ Return indices that are non-zero in the flattened version of a. This is equivalent to ``np.nonzero(np.ravel(a))[0]``. Parameters ---------- a : array_like Input data. Returns ------- res : ndarray Output array, containing the indices of the elements of ``a.ravel()`` that are non-zero. See Also -------- nonzero : Return the indices of the non-zero elements of the input array. ravel : Return a 1-D array containing the elements of the input array. Examples -------- >>> import numpy as np >>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4]) Use the indices of the non-zero elements as an index array to extract these elements: >>> x.ravel()[np.flatnonzero(x)] array([-2, -1, 1, 2]) """ return np.nonzero(np.ravel(a))[0]
Return indices that are non-zero in the flattened version of a. This is equivalent to ``np.nonzero(np.ravel(a))[0]``. Parameters ---------- a : array_like Input data. Returns ------- res : ndarray Output array, containing the indices of the elements of ``a.ravel()`` that are non-zero. See Also -------- nonzero : Return the indices of the non-zero elements of the input array. ravel : Return a 1-D array containing the elements of the input array. Examples -------- >>> import numpy as np >>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4]) Use the indices of the non-zero elements as an index array to extract these elements: >>> x.ravel()[np.flatnonzero(x)] array([-2, -1, 1, 2])
python
numpy/_core/numeric.py
680
[ "a" ]
false
1
6.32
numpy/numpy
31,054
numpy
false
pollInternal
private PollResult pollInternal(FetchRequestPreparer fetchRequestPreparer, ResponseHandler<ClientResponse> successHandler, ResponseHandler<Throwable> errorHandler) { if (pendingFetchRequestFuture == null) { // If no explicit request for creating fetch requests was issued, just short-circuit. return PollResult.EMPTY; } try { Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = fetchRequestPreparer.prepare(); if (fetchRequests.isEmpty()) { // If there's nothing to fetch, wake up the FetchBuffer so it doesn't needlessly wait for a wakeup // that won't come until the data in the fetch buffer is consumed. fetchBuffer.wakeup(); pendingFetchRequestFuture.complete(null); return PollResult.EMPTY; } List<UnsentRequest> requests = fetchRequests.entrySet().stream().map(entry -> { final Node fetchTarget = entry.getKey(); final FetchSessionHandler.FetchRequestData data = entry.getValue(); final FetchRequest.Builder request = createFetchRequest(fetchTarget, data); final BiConsumer<ClientResponse, Throwable> responseHandler = (clientResponse, error) -> { if (error != null) errorHandler.handle(fetchTarget, data, error); else successHandler.handle(fetchTarget, data, clientResponse); }; return new UnsentRequest(request, Optional.of(fetchTarget)).whenComplete(responseHandler); }).collect(Collectors.toList()); pendingFetchRequestFuture.complete(null); return new PollResult(requests); } catch (Throwable t) { // A "dummy" poll result is returned here rather than rethrowing the error because any error // that is thrown from any RequestManager.poll() method interrupts the polling of the other // request managers. pendingFetchRequestFuture.completeExceptionally(t); return PollResult.EMPTY; } finally { pendingFetchRequestFuture = null; } }
Creates the {@link PollResult poll result} that contains a list of zero or more {@link FetchRequest.Builder fetch requests}. @param fetchRequestPreparer {@link FetchRequestPreparer} to generate a {@link Map} of {@link Node nodes} to their {@link FetchSessionHandler.FetchRequestData} @param successHandler {@link ResponseHandler Handler for successful responses} @param errorHandler {@link ResponseHandler Handler for failure responses} @return {@link PollResult}
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchRequestManager.java
137
[ "fetchRequestPreparer", "successHandler", "errorHandler" ]
PollResult
true
5
7.6
apache/kafka
31,560
javadoc
false
collectAsynchronousDependencies
function collectAsynchronousDependencies(node: SourceFile, includeNonAmdDependencies: boolean): AsynchronousDependencies { // names of modules with corresponding parameter in the factory function const aliasedModuleNames: Expression[] = []; // names of modules with no corresponding parameters in factory function const unaliasedModuleNames: Expression[] = []; // names of the parameters in the factory function; these // parameters need to match the indexes of the corresponding // module names in aliasedModuleNames. const importAliasNames: ParameterDeclaration[] = []; // Fill in amd-dependency tags for (const amdDependency of node.amdDependencies) { if (amdDependency.name) { aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name)); } else { unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path)); } } for (const importNode of currentModuleInfo.externalImports) { // Find the name of the external module const externalModuleName = getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions); // Find the name of the module alias, if there is one const importAliasName = getLocalNameForExternalImport(factory, importNode, currentSourceFile); // It is possible that externalModuleName is undefined if it is not string literal. // This can happen in the invalid import syntax. // E.g : "import * from alias from 'someLib';" if (externalModuleName) { if (includeNonAmdDependencies && importAliasName) { // Set emitFlags on the name of the classDeclaration // This is so that when printer will not substitute the identifier setEmitFlags(importAliasName, EmitFlags.NoSubstitution); aliasedModuleNames.push(externalModuleName); importAliasNames.push(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName)); } else { unaliasedModuleNames.push(externalModuleName); } } } return { aliasedModuleNames, unaliasedModuleNames, importAliasNames }; }
Collect the additional asynchronous dependencies for the module. @param node The source file. @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
typescript
src/compiler/transformers/module/module.ts
554
[ "node", "includeNonAmdDependencies" ]
true
7
6.4
microsoft/TypeScript
107,154
jsdoc
false
power
def power(x, p): """ Return x to the power p, (x**p). If `x` contains negative values, the output is converted to the complex domain. Parameters ---------- x : array_like The input value(s). p : array_like of ints The power(s) to which `x` is raised. If `x` contains multiple values, `p` has to either be a scalar, or contain the same number of values as `x`. In the latter case, the result is ``x[0]**p[0], x[1]**p[1], ...``. Returns ------- out : ndarray or scalar The result of ``x**p``. If `x` and `p` are scalars, so is `out`, otherwise an array is returned. See Also -------- numpy.power Examples -------- >>> import numpy as np >>> np.set_printoptions(precision=4) >>> np.emath.power(2, 2) 4 >>> np.emath.power([2, 4], 2) array([ 4, 16]) >>> np.emath.power([2, 4], -2) array([0.25 , 0.0625]) >>> np.emath.power([-2, 4], 2) array([ 4.-0.j, 16.+0.j]) >>> np.emath.power([2, 4], [2, 4]) array([ 4, 256]) """ x = _fix_real_lt_zero(x) p = _fix_int_lt_zero(p) return nx.power(x, p)
Return x to the power p, (x**p). If `x` contains negative values, the output is converted to the complex domain. Parameters ---------- x : array_like The input value(s). p : array_like of ints The power(s) to which `x` is raised. If `x` contains multiple values, `p` has to either be a scalar, or contain the same number of values as `x`. In the latter case, the result is ``x[0]**p[0], x[1]**p[1], ...``. Returns ------- out : ndarray or scalar The result of ``x**p``. If `x` and `p` are scalars, so is `out`, otherwise an array is returned. See Also -------- numpy.power Examples -------- >>> import numpy as np >>> np.set_printoptions(precision=4) >>> np.emath.power(2, 2) 4 >>> np.emath.power([2, 4], 2) array([ 4, 16]) >>> np.emath.power([2, 4], -2) array([0.25 , 0.0625]) >>> np.emath.power([-2, 4], 2) array([ 4.-0.j, 16.+0.j]) >>> np.emath.power([2, 4], [2, 4]) array([ 4, 256])
python
numpy/lib/_scimath_impl.py
441
[ "x", "p" ]
false
1
6.48
numpy/numpy
31,054
numpy
false
optDouble
public double optDouble(String name) { return optDouble(name, Double.NaN); }
Returns the value mapped by {@code name} if it exists and is a double or can be coerced to a double. Returns {@code NaN} otherwise. @param name the name of the property @return the value or {@code NaN}
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
450
[ "name" ]
true
1
6.48
spring-projects/spring-boot
79,428
javadoc
false
shouldSkip
protected boolean shouldSkip(Class<?> beanClass, String beanName) { return AutoProxyUtils.isOriginalInstance(beanName, beanClass); }
Subclasses should override this method to return {@code true} if the given bean should not be considered for auto-proxying by this post-processor. <p>Sometimes we need to be able to avoid this happening, for example, if it will lead to a circular reference or if the existing target instance needs to be preserved. This implementation returns {@code false} unless the bean name indicates an "original instance" according to {@code AutowireCapableBeanFactory} conventions. @param beanClass the class of the bean @param beanName the name of the bean @return whether to skip the given bean @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#ORIGINAL_INSTANCE_SUFFIX
java
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java
382
[ "beanClass", "beanName" ]
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
is_empty_indexer
def is_empty_indexer(indexer) -> bool: """ Check if we have an empty indexer. Parameters ---------- indexer : object Returns ------- bool """ if is_list_like(indexer) and not len(indexer): return True if not isinstance(indexer, tuple): indexer = (indexer,) return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer)
Check if we have an empty indexer. Parameters ---------- indexer : object Returns ------- bool
python
pandas/core/indexers/utils.py
102
[ "indexer" ]
bool
true
5
6.88
pandas-dev/pandas
47,362
numpy
false
add
public void add(Collection<ConfigurationMetadataSource> sources) { for (ConfigurationMetadataSource source : sources) { String groupId = source.getGroupId(); ConfigurationMetadataGroup group = this.allGroups.computeIfAbsent(groupId, (key) -> new ConfigurationMetadataGroup(groupId)); String sourceType = source.getType(); if (sourceType != null) { addOrMergeSource(group.getSources(), sourceType, source); } } }
Register the specified {@link ConfigurationMetadataSource sources}. @param sources the sources to add
java
configuration-metadata/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/SimpleConfigurationMetadataRepository.java
54
[ "sources" ]
void
true
2
6.08
spring-projects/spring-boot
79,428
javadoc
false
timetz
def timetz(self) -> npt.NDArray[np.object_]: """ Returns numpy array of :class:`datetime.time` objects with timezones. The time part of the Timestamps. See Also -------- DatetimeIndex.time : Returns numpy array of :class:`datetime.time` objects. The time part of the Timestamps. DatetimeIndex.tz : Return the timezone. Examples -------- For Series: >>> s = pd.Series(["1/1/2020 10:00:00+00:00", "2/1/2020 11:00:00+00:00"]) >>> s = pd.to_datetime(s) >>> s 0 2020-01-01 10:00:00+00:00 1 2020-02-01 11:00:00+00:00 dtype: datetime64[us, UTC] >>> s.dt.timetz 0 10:00:00+00:00 1 11:00:00+00:00 dtype: object For DatetimeIndex: >>> idx = pd.DatetimeIndex( ... ["1/1/2020 10:00:00+00:00", "2/1/2020 11:00:00+00:00"] ... ) >>> idx.timetz array([datetime.time(10, 0, tzinfo=datetime.timezone.utc), datetime.time(11, 0, tzinfo=datetime.timezone.utc)], dtype=object) """ return ints_to_pydatetime(self.asi8, self.tz, box="time", reso=self._creso)
Returns numpy array of :class:`datetime.time` objects with timezones. The time part of the Timestamps. See Also -------- DatetimeIndex.time : Returns numpy array of :class:`datetime.time` objects. The time part of the Timestamps. DatetimeIndex.tz : Return the timezone. Examples -------- For Series: >>> s = pd.Series(["1/1/2020 10:00:00+00:00", "2/1/2020 11:00:00+00:00"]) >>> s = pd.to_datetime(s) >>> s 0 2020-01-01 10:00:00+00:00 1 2020-02-01 11:00:00+00:00 dtype: datetime64[us, UTC] >>> s.dt.timetz 0 10:00:00+00:00 1 11:00:00+00:00 dtype: object For DatetimeIndex: >>> idx = pd.DatetimeIndex( ... ["1/1/2020 10:00:00+00:00", "2/1/2020 11:00:00+00:00"] ... ) >>> idx.timetz array([datetime.time(10, 0, tzinfo=datetime.timezone.utc), datetime.time(11, 0, tzinfo=datetime.timezone.utc)], dtype=object)
python
pandas/core/arrays/datetimes.py
1,470
[ "self" ]
npt.NDArray[np.object_]
true
1
6.8
pandas-dev/pandas
47,362
unknown
false
getLast
@ParametricNullness public static <T extends @Nullable Object> T getLast( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { if (iterable instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) iterable; if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { return getLastInNonemptyList((List<? extends T>) iterable); } else if (iterable instanceof SortedSet) { return ((SortedSet<? extends T>) iterable).last(); } } return Iterators.getLast(iterable.iterator(), defaultValue); }
Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty. If {@code iterable} is a {@link List} with {@link RandomAccess} support, then this operation is guaranteed to be {@code O(1)}. <p><b>{@code Stream} equivalent:</b> {@code Streams.findLast(stream).orElse(defaultValue)} <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), consider using {@code collection.getLast()} instead. Note that if the collection is empty, {@code getLast()} throws a {@code NoSuchElementException}, while this method returns the default value. @param defaultValue the value to return if {@code iterable} is empty @return the last element of {@code iterable} or the default value @since 3.0
java
android/guava/src/com/google/common/collect/Iterables.java
886
[ "iterable", "defaultValue" ]
T
true
5
7.6
google/guava
51,352
javadoc
false
addAndGet
public long addAndGet(final long operand) { this.value += operand; return value; }
Increments this instance's value by {@code operand}; this method returns the value associated with the instance immediately after the addition operation. This method is not thread safe. @param operand the quantity to add, not null. @return the value associated with this instance after adding the operand. @since 3.5
java
src/main/java/org/apache/commons/lang3/mutable/MutableLong.java
111
[ "operand" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
loadBeanDefinitions
public int loadBeanDefinitions(EncodedResource encodedResource, @Nullable String prefix) throws BeanDefinitionStoreException { if (logger.isTraceEnabled()) { logger.trace("Loading properties bean definitions from " + encodedResource); } Properties props = new Properties(); try { try (InputStream is = encodedResource.getResource().getInputStream()) { if (encodedResource.getEncoding() != null) { getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding())); } else { getPropertiesPersister().load(props, is); } } int count = registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription()); if (logger.isDebugEnabled()) { logger.debug("Loaded " + count + " bean definitions from " + encodedResource); } return count; } catch (IOException ex) { throw new BeanDefinitionStoreException("Could not parse properties from " + encodedResource.getResource(), ex); } }
Load bean definitions from the specified properties file. @param encodedResource the resource descriptor for the properties file, allowing to specify an encoding to use for parsing the file @param prefix a filter within the keys in the map: for example, 'beans.' (can be empty or {@code null}) @return the number of bean definitions found @throws BeanDefinitionStoreException in case of loading or parsing errors
java
spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java
250
[ "encodedResource", "prefix" ]
true
5
7.76
spring-projects/spring-framework
59,386
javadoc
false
toString
@Override public String toString() { if (count() > 0) { return MoreObjects.toStringHelper(this) .add("count", count) .add("mean", mean) .add("populationStandardDeviation", populationStandardDeviation()) .add("min", min) .add("max", max) .toString(); } else { return MoreObjects.toStringHelper(this).add("count", count).toString(); } }
{@inheritDoc} <p><b>Note:</b> This hash code is consistent with exact equality of the calculated statistics, including the floating point values. See the note on {@link #equals} for details.
java
android/guava/src/com/google/common/math/Stats.java
449
[]
String
true
2
6.24
google/guava
51,352
javadoc
false
invoke
@Override public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable { if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) { if (hasMatchingParametersMethod(method)) { return MethodUtils.invokeMethod(target, methodName, parameters); } return MethodUtils.invokeMethod(target, methodName); } return null; }
Handles a method invocation on the proxy object. @param proxy the proxy instance. @param method the method to be invoked. @param parameters the parameters for the method invocation. @return the result of the method call. @throws SecurityException if an underlying accessible object's method denies the request. @see SecurityManager#checkPermission @throws Throwable if an error occurs
java
src/main/java/org/apache/commons/lang3/event/EventUtils.java
75
[ "proxy", "method", "parameters" ]
Object
true
4
7.44
apache/commons-lang
2,896
javadoc
false
tryAcquire
public boolean tryAcquire() { return tryAcquire(1, 0, MICROSECONDS); }
Acquires a permit from this {@link RateLimiter} if it can be acquired immediately without delay. <p>This method is equivalent to {@code tryAcquire(1)}. @return {@code true} if the permit was acquired, {@code false} otherwise @since 14.0
java
android/guava/src/com/google/common/util/concurrent/RateLimiter.java
380
[]
true
1
6.64
google/guava
51,352
javadoc
false
recordsSize
public static int recordsSize(FetchResponseData.PartitionData partition) { return partition.records() == null ? 0 : partition.records().sizeInBytes(); }
@return The size in bytes of the records. 0 is returned if records of input partition is null.
java
clients/src/main/java/org/apache/kafka/common/requests/FetchResponse.java
225
[ "partition" ]
true
2
6.8
apache/kafka
31,560
javadoc
false
getBuildDateMillis
long getBuildDateMillis() throws IOException { if (buildDate.get() == null) { synchronized (buildDate) { if (buildDate.get() == null) { buildDate.set(loader.get().getMetadata().getBuildDate().getTime()); } } } return buildDate.get(); }
Prepares the database for lookup by incrementing the usage count. If the usage count is already negative, it indicates that the database is being closed, and this method will return false to indicate that no lookup should be performed. @return true if the database is ready for lookup, false if it is being closed
java
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/DatabaseReaderLazyLoader.java
178
[]
true
3
8.08
elastic/elasticsearch
75,680
javadoc
false
valuesSpliterator
@Override @GwtIncompatible("Spliterator") Spliterator<@Nullable V> valuesSpliterator() { return CollectSpliterators.<@Nullable V>indexed(size(), Spliterator.ORDERED, this::getValue); }
Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the table will update the returned collection. <p>The returned collection's iterator traverses the values of the first row key, the values of the second row key, and so on. @return collection of values
java
guava/src/com/google/common/collect/ArrayTable.java
805
[]
true
1
7.04
google/guava
51,352
javadoc
false
beanNamesIncludingAncestors
public static String[] beanNamesIncludingAncestors(ListableBeanFactory lbf) { return beanNamesForTypeIncludingAncestors(lbf, Object.class); }
Return all bean names in the factory, including ancestor factories. @param lbf the bean factory @return the array of matching bean names, or an empty array if none @see #beanNamesForTypeIncludingAncestors
java
spring-beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java
148
[ "lbf" ]
true
1
6.48
spring-projects/spring-framework
59,386
javadoc
false
toHtmlTable
public String toHtmlTable(Map<String, String> dynamicUpdateModes) { boolean hasUpdateModes = !dynamicUpdateModes.isEmpty(); List<ConfigKey> configs = sortedConfigs(); StringBuilder b = new StringBuilder(); b.append("<table class=\"data-table\"><tbody>\n"); b.append("<tr>\n"); // print column headers for (String headerName : headers()) { addHeader(b, headerName); } if (hasUpdateModes) addHeader(b, "Dynamic Update Mode"); b.append("</tr>\n"); for (ConfigKey key : configs) { if (key.internalConfig) { continue; } b.append("<tr>\n"); // print column values for (String headerName : headers()) { addColumnValue(b, getConfigValue(key, headerName)); b.append("</td>"); } if (hasUpdateModes) { String updateMode = dynamicUpdateModes.get(key.name); if (updateMode == null) updateMode = "read-only"; addColumnValue(b, updateMode); } b.append("</tr>\n"); } b.append("</tbody></table>"); return b.toString(); }
Converts this config into an HTML table that can be embedded into docs. If <code>dynamicUpdateModes</code> is non-empty, a "Dynamic Update Mode" column will be included n the table with the value of the update mode. Default mode is "read-only". @param dynamicUpdateModes Config name -&gt; update mode mapping
java
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
1,459
[ "dynamicUpdateModes" ]
String
true
5
6.88
apache/kafka
31,560
javadoc
false
size
@Override public int size() { if (upperBoundWindow.equals(Range.all())) { return rangesByLowerBound.size(); } return Iterators.size(entryIterator()); }
upperBoundWindow represents the headMap/subMap/tailMap view of the entire "ranges by upper bound" map; it's a constraint on the *keys*, and does not affect the values.
java
android/guava/src/com/google/common/collect/TreeRangeSet.java
434
[]
true
2
6.56
google/guava
51,352
javadoc
false
updateMemberEpoch
protected void updateMemberEpoch(int newEpoch) { boolean newEpochReceived = this.memberEpoch != newEpoch; this.memberEpoch = newEpoch; // Simply notify based on epoch changes only, since the member will generate a member ID // at startup, and it will remain unchanged for its entire lifetime. if (newEpochReceived) { if (memberEpoch > 0) { notifyEpochChange(Optional.of(memberEpoch)); } else { notifyEpochChange(Optional.empty()); } } }
Returns the epoch a member uses to leave the group. This is group-type-specific. @return the epoch to leave the group
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
1,300
[ "newEpoch" ]
void
true
3
7.2
apache/kafka
31,560
javadoc
false
compareMethodFit
static int compareMethodFit(final Method left, final Method right, final Class<?>[] actual) { return compareParameterTypes(Executable.of(left), Executable.of(right), actual); }
Compares the relative fitness of two Methods in terms of how well they match a set of runtime parameter types, such that a list ordered by the results of the comparison would return the best match first (least). @param left the "left" Method. @param right the "right" Method. @param actual the runtime parameter types to match against. {@code left}/{@code right}. @return int consistent with {@code compare} semantics.
java
src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java
109
[ "left", "right", "actual" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
getCodeFragments
private BeanRegistrationCodeFragments getCodeFragments(GenerationContext generationContext, BeanRegistrationsCode beanRegistrationsCode) { BeanRegistrationCodeFragments codeFragments = new DefaultBeanRegistrationCodeFragments( beanRegistrationsCode, this.registeredBean, this.methodGeneratorFactory); for (BeanRegistrationAotContribution aotContribution : this.aotContributions) { codeFragments = aotContribution.customizeBeanRegistrationCodeFragments(generationContext, codeFragments); } return codeFragments; }
Return the {@link GeneratedClass} to use for the specified {@code target}. <p>If the target class is an inner class, a corresponding inner class in the original structure is created. @param generationContext the generation context to use @param target the chosen target class name for the bean definition @return the generated class to use
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGenerator.java
147
[ "generationContext", "beanRegistrationsCode" ]
BeanRegistrationCodeFragments
true
1
6.56
spring-projects/spring-framework
59,386
javadoc
false
removeAll
public static String removeAll(final CharSequence text, final Pattern regex) { return replaceAll(text, regex, StringUtils.EMPTY); }
Removes each substring of the text String that matches the given regular expression pattern. This method is a {@code null} safe equivalent to: <ul> <li>{@code pattern.matcher(text).replaceAll(StringUtils.EMPTY)}</li> </ul> <p>A {@code null} reference passed to this method is a no-op.</p> <pre>{@code StringUtils.removeAll(null, *) = null StringUtils.removeAll("any", (Pattern) null) = "any" StringUtils.removeAll("any", Pattern.compile("")) = "any" StringUtils.removeAll("any", Pattern.compile(".*")) = "" StringUtils.removeAll("any", Pattern.compile(".+")) = "" StringUtils.removeAll("abc", Pattern.compile(".?")) = "" StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("<.*>")) = "A\nB" StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("(?s)<.*>")) = "AB" StringUtils.removeAll("A<__>\n<__>B", Pattern.compile("<.*>", Pattern.DOTALL)) = "AB" StringUtils.removeAll("ABCabc123abc", Pattern.compile("[a-z]")) = "ABC123" }</pre> @param text text to remove from, may be null. @param regex the regular expression to which this string is to be matched. @return the text with any removes processed, {@code null} if null String input. @see #replaceAll(CharSequence, Pattern, String) @see java.util.regex.Matcher#replaceAll(String) @see java.util.regex.Pattern @since 3.18.0
java
src/main/java/org/apache/commons/lang3/RegExUtils.java
108
[ "text", "regex" ]
String
true
1
6.16
apache/commons-lang
2,896
javadoc
false
mlockall
int mlockall(int flags);
Lock all the current process's virtual address space into RAM. @param flags flags determining how memory will be locked @return 0 on success, -1 on failure with errno set @see <a href="https://man7.org/linux/man-pages/man2/mlock.2.html">mlockall manpage</a>
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/lib/PosixCLibrary.java
65
[ "flags" ]
true
1
6
elastic/elasticsearch
75,680
javadoc
false
asEnumSet
private EnumSet<Option> asEnumSet(Option @Nullable [] options) { if (options == null || options.length == 0) { return EnumSet.noneOf(Option.class); } return EnumSet.copyOf(Arrays.asList(options)); }
Create a new {@link CommandException} with the specified options. @param cause the underlying cause @param options the exception options
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandException.java
78
[ "options" ]
true
3
6.24
spring-projects/spring-boot
79,428
javadoc
false
doWithMainClasses
static <T> @Nullable T doWithMainClasses(File rootDirectory, MainClassCallback<T> callback) throws IOException { if (!rootDirectory.exists()) { return null; // nothing to do } if (!rootDirectory.isDirectory()) { throw new IllegalArgumentException("Invalid root directory '" + rootDirectory + "'"); } String prefix = rootDirectory.getAbsolutePath() + "/"; Deque<File> stack = new ArrayDeque<>(); stack.push(rootDirectory); while (!stack.isEmpty()) { File file = stack.pop(); if (file.isFile()) { try (InputStream inputStream = new FileInputStream(file)) { ClassDescriptor classDescriptor = createClassDescriptor(inputStream); if (classDescriptor != null && classDescriptor.isMainMethodFound()) { String className = convertToClassName(file.getAbsolutePath(), prefix); T result = callback.doWith(new MainClass(className, classDescriptor.getAnnotationNames())); if (result != null) { return result; } } } } if (file.isDirectory()) { pushAllSorted(stack, file.listFiles(PACKAGE_DIRECTORY_FILTER)); pushAllSorted(stack, file.listFiles(CLASS_FILE_FILTER)); } } return null; }
Perform the given callback operation on all main classes from the given root directory. @param <T> the result type @param rootDirectory the root directory @param callback the callback @return the first callback result or {@code null} @throws IOException in case of I/O errors
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java
127
[ "rootDirectory", "callback" ]
T
true
9
7.76
spring-projects/spring-boot
79,428
javadoc
false
onAcknowledgement
public void onAcknowledgement(RecordMetadata metadata, Exception exception, Headers headers) { for (Plugin<ProducerInterceptor<K, V>> interceptorPlugin : this.interceptorPlugins) { try { interceptorPlugin.get().onAcknowledgement(metadata, exception, headers); } catch (Exception e) { // do not propagate interceptor exceptions, just log log.warn("Error executing interceptor onAcknowledgement callback", e); } } }
This method is called when the record sent to the server has been acknowledged, or when sending the record fails before it gets sent to the server. This method calls {@link ProducerInterceptor#onAcknowledgement(RecordMetadata, Exception, Headers)} method for each interceptor. This method does not throw exceptions. Exceptions thrown by any of interceptor methods are caught and ignored. @param metadata The metadata for the record that was sent (i.e. the partition and offset). If an error occurred, metadata will only contain valid topic and maybe partition. @param exception The exception thrown during processing of this record. Null if no error occurred. @param headers The headers for the record that was sent
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/ProducerInterceptors.java
92
[ "metadata", "exception", "headers" ]
void
true
2
6.88
apache/kafka
31,560
javadoc
false
at
def at(self) -> _AtIndexer: """ Access a single value for a row/column label pair. Similar to ``loc``, in that both provide label-based lookups. Use ``at`` if you only need to get or set a single value in a DataFrame or Series. Raises ------ KeyError If getting a value and 'label' does not exist in a DataFrame or Series. ValueError If row/column label pair is not a tuple or if any label from the pair is not a scalar for DataFrame. If label is list-like (*excluding* NamedTuple) for Series. See Also -------- DataFrame.at : Access a single value for a row/column pair by label. DataFrame.iat : Access a single value for a row/column pair by integer position. DataFrame.loc : Access a group of rows and columns by label(s). DataFrame.iloc : Access a group of rows and columns by integer position(s). Series.at : Access a single value by label. Series.iat : Access a single value by integer position. Series.loc : Access a group of rows by label(s). Series.iloc : Access a group of rows by integer position(s). Notes ----- See :ref:`Fast scalar value getting and setting <indexing.basics.get_value>` for more details. Examples -------- >>> df = pd.DataFrame( ... [[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], ... columns=["A", "B", "C"], ... ) >>> df A B C 4 0 2 3 5 0 4 1 6 10 20 30 Get value at specified row/column pair >>> df.at[4, "B"] np.int64(2) Set value at specified row/column pair >>> df.at[4, "B"] = 10 >>> df.at[4, "B"] np.int64(10) Get value within a Series >>> df.loc[5].at["B"] np.int64(4) """ return _AtIndexer("at", self)
Access a single value for a row/column label pair. Similar to ``loc``, in that both provide label-based lookups. Use ``at`` if you only need to get or set a single value in a DataFrame or Series. Raises ------ KeyError If getting a value and 'label' does not exist in a DataFrame or Series. ValueError If row/column label pair is not a tuple or if any label from the pair is not a scalar for DataFrame. If label is list-like (*excluding* NamedTuple) for Series. See Also -------- DataFrame.at : Access a single value for a row/column pair by label. DataFrame.iat : Access a single value for a row/column pair by integer position. DataFrame.loc : Access a group of rows and columns by label(s). DataFrame.iloc : Access a group of rows and columns by integer position(s). Series.at : Access a single value by label. Series.iat : Access a single value by integer position. Series.loc : Access a group of rows by label(s). Series.iloc : Access a group of rows by integer position(s). Notes ----- See :ref:`Fast scalar value getting and setting <indexing.basics.get_value>` for more details. Examples -------- >>> df = pd.DataFrame( ... [[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], ... columns=["A", "B", "C"], ... ) >>> df A B C 4 0 2 3 5 0 4 1 6 10 20 30 Get value at specified row/column pair >>> df.at[4, "B"] np.int64(2) Set value at specified row/column pair >>> df.at[4, "B"] = 10 >>> df.at[4, "B"] np.int64(10) Get value within a Series >>> df.loc[5].at["B"] np.int64(4)
python
pandas/core/indexing.py
636
[ "self" ]
_AtIndexer
true
1
7.2
pandas-dev/pandas
47,362
unknown
false
reinitialize
@Override protected void reinitialize(LoggingInitializationContext initializationContext) { String currentLocation = getSelfInitializationConfig(); Assert.notNull(currentLocation, "'currentLocation' must not be null"); load(initializationContext, currentLocation, null); }
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
340
[ "initializationContext" ]
void
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
findCandidateAdvisors
@Override protected List<Advisor> findCandidateAdvisors() { // Add all the Spring advisors found according to superclass rules. List<Advisor> advisors = super.findCandidateAdvisors(); // Build Advisors for all AspectJ aspects in the bean factory. if (this.aspectJAdvisorsBuilder != null) { advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors()); } return advisors; }
Set a list of regex patterns, matching eligible @AspectJ bean names. <p>Default is to consider all @AspectJ beans as eligible.
java
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AnnotationAwareAspectJAutoProxyCreator.java
87
[]
true
2
6.72
spring-projects/spring-framework
59,386
javadoc
false
proxy_headers
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) if username: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return headers
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The url of the proxy being used for this request. :rtype: dict
python
src/requests/adapters.py
569
[ "self", "proxy" ]
false
2
6.24
psf/requests
53,586
sphinx
false
getAspectCreationMutex
@Override public @Nullable Object getAspectCreationMutex() { if (this.beanFactory.isSingleton(this.name)) { // Rely on singleton semantics provided by the factory -> no local lock. return null; } else { // No singleton guarantees from the factory -> let's lock locally. return this; } }
Create a BeanFactoryAspectInstanceFactory, providing a type that AspectJ should introspect to create AJType metadata. Use if the BeanFactory may consider the type to be a subclass (as when using CGLIB), and the information should relate to a superclass. @param beanFactory the BeanFactory to obtain instance(s) from @param name the name of the bean @param type the type that should be introspected by AspectJ ({@code null} indicates resolution through {@link BeanFactory#getType} via the bean name)
java
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/BeanFactoryAspectInstanceFactory.java
106
[]
Object
true
2
6.56
spring-projects/spring-framework
59,386
javadoc
false
and
default FailablePredicate<T, E> and(final FailablePredicate<? super T, E> other) { Objects.requireNonNull(other); return t -> test(t) && other.test(t); }
Returns a composed {@link FailablePredicate} like {@link Predicate#and(Predicate)}. @param other a predicate that will be logically-ANDed with this predicate. @return a composed {@link FailablePredicate} like {@link Predicate#and(Predicate)}. @throws NullPointerException if other is null
java
src/main/java/org/apache/commons/lang3/function/FailablePredicate.java
72
[ "other" ]
true
2
7.36
apache/commons-lang
2,896
javadoc
false