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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
column_arrays | def column_arrays(self) -> list[np.ndarray]:
"""
Used in the JSON C code to access column arrays.
This optimizes compared to using `iget_values` by converting each
Warning! This doesn't handle Copy-on-Write, so should be used with
caution (current use case of consuming this in t... | Used in the JSON C code to access column arrays.
This optimizes compared to using `iget_values` by converting each
Warning! This doesn't handle Copy-on-Write, so should be used with
caution (current use case of consuming this in the JSON code is fine). | python | pandas/core/internals/managers.py | 1,208 | [
"self"
] | list[np.ndarray] | true | 5 | 6 | pandas-dev/pandas | 47,362 | unknown | false |
proxiedUserInterfaces | public static Class<?>[] proxiedUserInterfaces(Object proxy) {
Class<?>[] proxyInterfaces = proxy.getClass().getInterfaces();
int nonUserIfcCount = 0;
if (proxy instanceof SpringProxy) {
nonUserIfcCount++;
}
if (proxy instanceof Advised) {
nonUserIfcCount++;
}
if (proxy instanceof DecoratingProxy) {... | Extract the user-specified interfaces that the given proxy implements,
i.e. all non-Advised interfaces that the proxy implements.
@param proxy the proxy to analyze (usually a JDK dynamic proxy)
@return all user-specified interfaces that the proxy implements,
in the original order (never {@code null} or empty)
@see Advi... | java | spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java | 205 | [
"proxy"
] | true | 4 | 8.08 | spring-projects/spring-framework | 59,386 | javadoc | false | |
conformsTo | function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
} | Checks if `object` conforms to `source` by invoking the predicate
properties of `source` with the corresponding property values of `object`.
**Note:** This method is equivalent to `_.conforms` when `source` is
partially applied.
@static
@memberOf _
@since 4.14.0
@category Lang
@param {Object} object The object to inspe... | javascript | lodash.js | 11,255 | [
"object",
"source"
] | false | 2 | 7.44 | lodash/lodash | 61,490 | jsdoc | false | |
length | def length(self) -> Index:
"""
Return an Index with entries denoting the length of each Interval.
The length of an interval is calculated as the difference between
its `right` and `left` bounds. This property is particularly useful
when working with intervals where the size of t... | Return an Index with entries denoting the length of each Interval.
The length of an interval is calculated as the difference between
its `right` and `left` bounds. This property is particularly useful
when working with intervals where the size of the interval is an important
attribute, such as in time-series analysis ... | python | pandas/core/arrays/interval.py | 1,408 | [
"self"
] | Index | true | 1 | 6.64 | pandas-dev/pandas | 47,362 | unknown | false |
runtime | def runtime() -> str | None:
"""Determine the runtime type based on available backends.
Returns:
"CUDA" if CUDA is available, "HIP" if HIP is available, None otherwise.
"""
return "CUDA" if torch.version.cuda else "HIP" if torch.version.hip else None | Determine the runtime type based on available backends.
Returns:
"CUDA" if CUDA is available, "HIP" if HIP is available, None otherwise. | python | torch/_inductor/runtime/caching/context.py | 168 | [] | str | None | true | 3 | 7.6 | pytorch/pytorch | 96,034 | unknown | false |
parseTimeValue | public static TimeValue parseTimeValue(@Nullable String sValue, TimeValue defaultValue, String settingName) {
settingName = Objects.requireNonNull(settingName);
if (sValue == null) {
return defaultValue;
}
final String normalized = sValue.toLowerCase(Locale.ROOT).trim();
... | @param sValue Value to parse, which may be {@code null}.
@param defaultValue Value to return if {@code sValue} is {@code null}.
@param settingName Name of the parameter or setting. On invalid input, this value is included in the exception message. Otherwise,
this parameter is unused.
@return ... | java | libs/core/src/main/java/org/elasticsearch/core/TimeValue.java | 376 | [
"sValue",
"defaultValue",
"settingName"
] | TimeValue | true | 11 | 8.24 | elastic/elasticsearch | 75,680 | javadoc | false |
toString | public static String toString(Readable r) throws IOException {
return toStringBuilder(r).toString();
} | Reads all characters from a {@link Readable} object into a {@link String}. Does not close the
{@code Readable}.
<p><b>Java 25+ users:</b> If the input is a {@link Reader}, prefer {@link
Reader#readAllAsString()}.
@param r the object to read from
@return a string containing all the characters
@throws IOException if an I... | java | android/guava/src/com/google/common/io/CharStreams.java | 162 | [
"r"
] | String | true | 1 | 6.8 | google/guava | 51,352 | javadoc | false |
where | def where(condition, x=None, y=None, /):
"""
where(condition, [x, y], /)
Return elements chosen from `x` or `y` depending on `condition`.
.. note::
When only `condition` is provided, this function is a shorthand for
``np.asarray(condition).nonzero()``. Using `nonzero` directly should b... | where(condition, [x, y], /)
Return elements chosen from `x` or `y` depending on `condition`.
.. note::
When only `condition` is provided, this function is a shorthand for
``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
preferred, as it behaves correctly for subclasses. The rest of ... | python | numpy/_core/multiarray.py | 404 | [
"condition",
"x",
"y"
] | false | 1 | 6.4 | numpy/numpy | 31,054 | numpy | false | |
transformAndEmitBreakStatement | function transformAndEmitBreakStatement(node: BreakStatement): void {
const label = findBreakTarget(node.label ? idText(node.label) : undefined);
if (label > 0) {
emitBreak(label, /*location*/ node);
}
else {
// invalid break without a containing loop, switc... | Visits an ElementAccessExpression that contains a YieldExpression.
@param node The node to visit. | typescript | src/compiler/transformers/generators.ts | 1,764 | [
"node"
] | true | 4 | 6.24 | microsoft/TypeScript | 107,154 | jsdoc | false | |
write_to_cache_file | def write_to_cache_file(param_name: str, param_value: str, check_allowed_values: bool = True) -> None:
"""
Writs value to cache. If asked it can also check if the value is allowed for the parameter. and exit
in case the value is not allowed for that parameter instead of writing it.
:param param_name: na... | Writs value to cache. If asked it can also check if the value is allowed for the parameter. and exit
in case the value is not allowed for that parameter instead of writing it.
:param param_name: name of the parameter
:param param_value: new value for the parameter
:param check_allowed_values: whether to fail if the par... | python | dev/breeze/src/airflow_breeze/utils/cache.py | 51 | [
"param_name",
"param_value",
"check_allowed_values"
] | None | true | 5 | 7.04 | apache/airflow | 43,597 | sphinx | false |
postReadCleanup | void postReadCleanup() {
if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) {
cleanUp();
}
} | Performs routine cleanup following a read. Normally cleanup happens during writes. If cleanup
is not observed after a sufficient number of reads, try cleaning up from the read thread. | java | android/guava/src/com/google/common/cache/LocalCache.java | 3,355 | [] | void | true | 2 | 7.04 | google/guava | 51,352 | javadoc | false |
of | private static <E> Stream<E> of(final Stream<E> stream) {
return stream == null ? Stream.empty() : stream;
} | Returns the stream or {@link Stream#empty()} if the stream is null.
@param <E> the type of elements in the collection.
@param stream the stream to stream or null.
@return the stream or {@link Stream#empty()} if the stream is null.
@since 3.13.0 | java | src/main/java/org/apache/commons/lang3/stream/Streams.java | 723 | [
"stream"
] | true | 2 | 8 | apache/commons-lang | 2,896 | javadoc | false | |
visitExportSpecifier | function visitExportSpecifier(node: ExportSpecifier): VisitResult<ExportSpecifier> | undefined {
// Elide an export specifier if it does not reference a value.
return !node.isTypeOnly && (compilerOptions.verbatimModuleSyntax || resolver.isValueAliasDeclaration(node)) ? node : undefined;
} | Visits an export specifier, eliding it if it does not resolve to a value.
@param node The export specifier node. | typescript | src/compiler/transformers/ts.ts | 2,401 | [
"node"
] | true | 4 | 6.8 | microsoft/TypeScript | 107,154 | jsdoc | false | |
checkAssignmentMatchedSubscription | public synchronized boolean checkAssignmentMatchedSubscription(Collection<TopicPartition> assignments) {
for (TopicPartition topicPartition : assignments) {
if (this.subscribedPattern != null) {
if (!this.subscribedPattern.matcher(topicPartition.topic()).matches()) {
... | Check if an assignment received while using the classic group protocol matches the subscription.
Note that this only considers the subscribedPattern because this functionality is only used under the
classic protocol, where subscribedRe2JPattern is not supported.
@return true if assignments matches subscription, otherwi... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java | 289 | [
"assignments"
] | true | 4 | 6.24 | apache/kafka | 31,560 | javadoc | false | |
maybeLeaderEpoch | private Optional<Integer> maybeLeaderEpoch(final int leaderEpoch) {
return leaderEpoch == RecordBatch.NO_PARTITION_LEADER_EPOCH ? Optional.empty() : Optional.of(leaderEpoch);
} | Scans for the next record in the available batches, skipping control records
@param checkCrcs Whether to check the CRC of fetched records
@return true if the current batch has more records, else false | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareCompletedFetch.java | 388 | [
"leaderEpoch"
] | true | 2 | 7.2 | apache/kafka | 31,560 | javadoc | false | |
stream | @Deprecated
public static <T> FailableStream<T> stream(final Stream<T> stream) {
return failableStream(stream);
} | Converts the given {@link Stream stream} into a {@link FailableStream}. This is basically a simplified, reduced
version of the {@link Stream} class, with the same underlying element stream, except that failable objects, like
{@link FailablePredicate}, {@link FailableFunction}, or {@link FailableConsumer} may be applied... | java | src/main/java/org/apache/commons/lang3/stream/Streams.java | 825 | [
"stream"
] | true | 1 | 6.32 | apache/commons-lang | 2,896 | javadoc | false | |
finalizeDeferredProperties | private void finalizeDeferredProperties() {
for (DeferredProperty dp : this.deferredProperties.values()) {
if (dp.value instanceof List<?> list) {
dp.value = manageListIfNecessary(list);
}
else if (dp.value instanceof Map<?, ?> map) {
dp.value = manageMapIfNecessary(map);
}
dp.apply();
}
th... | This method overrides method invocation to create beans for each method name that
takes a class argument. | java | spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java | 434 | [] | void | true | 3 | 6.88 | spring-projects/spring-framework | 59,386 | javadoc | false |
_get_metadata_for_step | def _get_metadata_for_step(self, *, step_idx, step_params, all_params):
"""Get params (metadata) for step `name`.
This transforms the metadata up to this step if required, which is
indicated by the `transform_input` parameter.
If a param in `step_params` is included in the `transform_i... | Get params (metadata) for step `name`.
This transforms the metadata up to this step if required, which is
indicated by the `transform_input` parameter.
If a param in `step_params` is included in the `transform_input` list,
it will be transformed.
Parameters
----------
step_idx : int
Index of the step in the pipe... | python | sklearn/pipeline.py | 434 | [
"self",
"step_idx",
"step_params",
"all_params"
] | false | 9 | 6.16 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
_get_output_storages | def _get_output_storages(node: fx.Node) -> OrderedSet[StorageKey]:
"""
Get all storages from a node's outputs.
Uses pytree to handle arbitrary nested structures.
"""
val = node.meta.get("val")
if val is None:
return OrderedSet()
storages: OrderedSet[... | Get all storages from a node's outputs.
Uses pytree to handle arbitrary nested structures. | python | torch/_inductor/fx_passes/memory_estimator.py | 97 | [
"node"
] | OrderedSet[StorageKey] | true | 2 | 6 | pytorch/pytorch | 96,034 | unknown | false |
entrySet | @Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> result = entrySet;
return (result == null) ? entrySet = createEntrySet() : result;
} | Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most
once on a given map, at the time when {@code entrySet} is first called. | java | android/guava/src/com/google/common/collect/Maps.java | 3,523 | [] | true | 2 | 6.72 | google/guava | 51,352 | javadoc | false | |
configure | protected void configure(D registration) {
registration.setAsyncSupported(this.asyncSupported);
if (!this.initParameters.isEmpty()) {
registration.setInitParameters(this.initParameters);
}
} | Sets whether registration failures should be ignored. If set to true, a failure
will be logged. If set to false, an {@link IllegalStateException} will be thrown.
@param ignoreRegistrationFailure whether to ignore registration failures
@since 3.1.0 | java | core/spring-boot/src/main/java/org/springframework/boot/web/servlet/DynamicRegistrationBean.java | 145 | [
"registration"
] | void | true | 2 | 6.4 | spring-projects/spring-boot | 79,428 | javadoc | false |
parseKeywordAndNoDot | function parseKeywordAndNoDot(): TypeNode | undefined {
const node = parseTokenNode<TypeNode>();
return token() === SyntaxKind.DotToken ? undefined : node;
} | Reports a diagnostic error for the current token being an invalid name.
@param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName).
@param nameDiagnostic Diagnostic to report for all other cases.
@param tokenIfBlankName Current token if the name was invalid for being... | typescript | src/compiler/parser.ts | 4,523 | [] | true | 2 | 6.64 | microsoft/TypeScript | 107,154 | jsdoc | false | |
timeoutPendingCalls | private void timeoutPendingCalls(TimeoutProcessor processor) {
int numTimedOut = processor.handleTimeouts(pendingCalls, "Timed out waiting for a node assignment.");
if (numTimedOut > 0)
log.debug("Timed out {} pending calls.", numTimedOut);
} | Time out the elements in the pendingCalls list which are expired.
@param processor The timeout processor. | java | clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java | 1,128 | [
"processor"
] | void | true | 2 | 6.72 | apache/kafka | 31,560 | javadoc | false |
render_log_filename | def render_log_filename(
self,
ti: TaskInstance | TaskInstanceHistory,
try_number: int | None = None,
*,
session: Session = NEW_SESSION,
) -> str:
"""
Render the log attachment filename.
:param ti: The task instance
:param try_number: The task... | Render the log attachment filename.
:param ti: The task instance
:param try_number: The task try number | python | airflow-core/src/airflow/utils/log/log_reader.py | 195 | [
"self",
"ti",
"try_number",
"session"
] | str | true | 2 | 7.04 | apache/airflow | 43,597 | sphinx | false |
set | def set(self, immutable=None, **options):
"""Set arbitrary execution options (same as ``.options.update(…)``).
Returns:
Signature: This is a chaining method call
(i.e., it will return ``self``).
"""
if immutable is not None:
self.set_immutable(imm... | Set arbitrary execution options (same as ``.options.update(…)``).
Returns:
Signature: This is a chaining method call
(i.e., it will return ``self``). | python | celery/canvas.py | 538 | [
"self",
"immutable"
] | false | 2 | 6.8 | celery/celery | 27,741 | unknown | false | |
refresh_model_names_and_batch_sizes | def refresh_model_names_and_batch_sizes():
"""
This function reads the HF Fx tracer supported models and finds the largest
batch size that could fit on the GPU with PyTorch eager.
The resulting data is written in huggingface_models_list.txt.
Note - We only need to run this function if we believe t... | This function reads the HF Fx tracer supported models and finds the largest
batch size that could fit on the GPU with PyTorch eager.
The resulting data is written in huggingface_models_list.txt.
Note - We only need to run this function if we believe that HF Fx tracer now
supports more models. | python | benchmarks/dynamo/huggingface.py | 569 | [] | false | 15 | 6.16 | pytorch/pytorch | 96,034 | unknown | false | |
toString | @Override
public String toString() {
return pattern;
} | @return Regular expression pattern compatible with RE2/J. | java | clients/src/main/java/org/apache/kafka/clients/consumer/SubscriptionPattern.java | 44 | [] | String | true | 1 | 6.32 | apache/kafka | 31,560 | javadoc | false |
validIndex | public static <T extends CharSequence> T validIndex(final T chars, final int index) {
return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index));
} | Validates that the index is within the bounds of the argument
character sequence; otherwise throwing an exception.
<pre>Validate.validIndex(myStr, 2);</pre>
<p>If the character sequence is {@code null}, then the message
of the exception is "The validated object is
null".</p>
<p>If the index is invalid, then t... | java | src/main/java/org/apache/commons/lang3/Validate.java | 1,114 | [
"chars",
"index"
] | T | true | 1 | 6.32 | apache/commons-lang | 2,896 | javadoc | false |
createDefaultEditors | private void createDefaultEditors() {
this.defaultEditors = new HashMap<>(64);
// Simple editors, without parameterization capabilities.
// The JDK does not contain a default editor for any of these target types.
this.defaultEditors.put(Charset.class, new CharsetEditor());
this.defaultEditors.put(Class.class... | Actually register the default editors for this registry instance. | java | spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java | 212 | [] | void | true | 2 | 6.48 | spring-projects/spring-framework | 59,386 | javadoc | false |
checkMergedBeanDefinition | protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object @Nullable [] args) {
if (mbd.isAbstract()) {
throw new BeanIsAbstractException(beanName);
}
} | Check the given merged bean definition,
potentially throwing validation exceptions.
@param mbd the merged bean definition to check
@param beanName the name of the bean
@param args the arguments for bean creation, if any | java | spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java | 1,512 | [
"mbd",
"beanName",
"args"
] | void | true | 2 | 6.56 | spring-projects/spring-framework | 59,386 | javadoc | false |
isLeaderKnownToHaveChanged | private boolean isLeaderKnownToHaveChanged(int nodeId, TopicIdPartition topicIdPartition) {
Optional<Node> leaderNode = metadata.currentLeader(topicIdPartition.topicPartition()).leader;
if (leaderNode.isPresent()) {
if (leaderNode.get().id() != nodeId) {
log.debug("Node {} is... | The method checks whether the leader for a topicIdPartition has changed.
@param nodeId The previous leader for the partition.
@param topicIdPartition The TopicIdPartition to check.
@return Returns true if leader information is available and leader has changed.
If the leader information is not available or if the leader... | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareConsumeRequestManager.java | 752 | [
"nodeId",
"topicIdPartition"
] | true | 3 | 7.92 | apache/kafka | 31,560 | javadoc | false | |
afterPropertiesSet | @Override
public void afterPropertiesSet() throws Exception {
prepare();
if (this.singleton) {
this.initialized = true;
this.singletonObject = invokeWithTargetException();
}
} | Set if a singleton should be created, or a new object on each
{@link #getObject()} request otherwise. Default is "true". | java | spring-beans/src/main/java/org/springframework/beans/factory/config/MethodInvokingFactoryBean.java | 103 | [] | void | true | 2 | 6.72 | spring-projects/spring-framework | 59,386 | javadoc | false |
getTypeForFactoryBean | protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
try {
ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
if (result != ResolvableType.NONE) {
return result;
}
}
catch (IllegalArgumentException ex) {
throw new BeanDefinitio... | Determine the bean type for the given FactoryBean definition, as far as possible.
Only called if there is no singleton instance registered for the target bean
already. The implementation is allowed to instantiate the target factory bean if
{@code allowInit} is {@code true} and the type cannot be determined another way;... | java | spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java | 1,730 | [
"beanName",
"mbd",
"allowInit"
] | ResolvableType | true | 9 | 7.6 | spring-projects/spring-framework | 59,386 | javadoc | false |
cjsEmplaceModuleCacheEntry | function cjsEmplaceModuleCacheEntry(filename, parent) {
// TODO: Do we want to keep hitting the user mutable CJS loader here?
let cjsMod = CJSModule._cache[filename];
if (cjsMod) {
return cjsMod;
}
cjsMod = new CJSModule(filename, parent);
cjsMod.filename = filename;
cjsMod.paths = CJSModule._nodeMod... | Get or create an entry in the CJS module cache for the given filename.
@param {string} filename CJS module filename
@param {CJSModule} parent The parent CJS module
@returns {CJSModule} the cached CJS module entry | javascript | lib/internal/modules/esm/translators.js | 379 | [
"filename",
"parent"
] | false | 2 | 6.4 | nodejs/node | 114,839 | jsdoc | false | |
send_email_smtp | def send_email_smtp(
to: str | Iterable[str],
subject: str,
html_content: str,
files: list[str] | None = None,
dryrun: bool = False,
cc: str | Iterable[str] | None = None,
bcc: str | Iterable[str] | None = None,
mime_subtype: str = "mixed",
mime_charset: str = "utf-8",
conn_id: s... | Send an email with html content.
:param to: Recipient email address or list of addresses.
:param subject: Email subject.
:param html_content: Email body in HTML format.
:param files: List of file paths to attach to the email.
:param dryrun: If True, the email will not be sent, but all other actions will be performed.
... | python | airflow-core/src/airflow/utils/email.py | 96 | [
"to",
"subject",
"html_content",
"files",
"dryrun",
"cc",
"bcc",
"mime_subtype",
"mime_charset",
"conn_id",
"from_email",
"custom_headers"
] | None | true | 4 | 8.56 | apache/airflow | 43,597 | sphinx | false |
setFrom | public void setFrom(String from, String personal) throws MessagingException, UnsupportedEncodingException {
Assert.notNull(from, "From address must not be null");
setFrom(getEncoding() != null ?
new InternetAddress(from, personal, getEncoding()) : new InternetAddress(from, personal));
} | Validate all given mail addresses.
<p>The default implementation simply delegates to {@link #validateAddress}
for each address.
@param addresses the addresses to validate
@throws AddressException if validation failed
@see #validateAddress(InternetAddress) | java | spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java | 571 | [
"from",
"personal"
] | void | true | 2 | 6.08 | spring-projects/spring-framework | 59,386 | javadoc | false |
findResources | @Override
public Enumeration<URL> findResources(String name) throws IOException {
if (!this.hasJarUrls) {
return super.findResources(name);
}
Optimizations.enable(false);
try {
return new OptimizedEnumeration(super.findResources(name));
}
finally {
Optimizations.disable();
}
} | Create a new {@link LaunchedClassLoader} instance.
@param urls the URLs from which to load classes and resources
@param parent the parent class loader for delegation | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarUrlClassLoader.java | 80 | [
"name"
] | true | 2 | 6.72 | spring-projects/spring-boot | 79,428 | javadoc | false | |
read | @Override
public int read() throws IOException {
if (finished) {
return -1;
}
if (available() == 0) {
readBlock();
}
if (finished) {
return -1;
}
return decompressedBuffer.get() & 0xFF;
} | Decompresses (if necessary) buffered data, optionally computes and validates a XXHash32 checksum, and writes the
result to a buffer.
@throws IOException | java | clients/src/main/java/org/apache/kafka/common/compress/Lz4BlockInputStream.java | 210 | [] | true | 4 | 6.4 | apache/kafka | 31,560 | javadoc | false | |
_split_by_backtick | def _split_by_backtick(s: str) -> list[tuple[bool, str]]:
"""
Splits a str into substrings along backtick characters (`).
Disregards backticks inside quotes.
Parameters
----------
s : str
The Python source code string.
Returns
-------
substrings: list[tuple[bool, str]]
... | Splits a str into substrings along backtick characters (`).
Disregards backticks inside quotes.
Parameters
----------
s : str
The Python source code string.
Returns
-------
substrings: list[tuple[bool, str]]
List of tuples, where each tuple has two elements:
The first is a boolean indicating if the subst... | python | pandas/core/computation/parsing.py | 145 | [
"s"
] | list[tuple[bool, str]] | true | 15 | 6.8 | pandas-dev/pandas | 47,362 | numpy | false |
nextAlphabetic | public String nextAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) {
return nextAlphabetic(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
} | Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
<p>
Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).
</p>
@param minLengthInclusive the inclusive minimum length of the string to generate.
@param maxLengthExclusive the exclusive maximum le... | java | src/main/java/org/apache/commons/lang3/RandomStringUtils.java | 825 | [
"minLengthInclusive",
"maxLengthExclusive"
] | String | true | 1 | 6.64 | apache/commons-lang | 2,896 | javadoc | false |
getStartClass | private @Nullable Class<?> getStartClass(Enumeration<URL> manifestResources) {
while (manifestResources.hasMoreElements()) {
try (InputStream inputStream = manifestResources.nextElement().openStream()) {
Manifest manifest = new Manifest(inputStream);
String startClass = manifest.getMainAttributes().getValu... | Create a new {@link ApplicationHome} instance for the specified source class.
@param sourceClass the source class or {@code null} | java | core/spring-boot/src/main/java/org/springframework/boot/system/ApplicationHome.java | 77 | [
"manifestResources"
] | true | 4 | 6.88 | spring-projects/spring-boot | 79,428 | javadoc | false | |
topics | public List<String> topics() {
return data.topics()
.stream()
.map(MetadataRequestTopic::name)
.collect(Collectors.toList());
} | @return Builder for metadata request using topic IDs. | java | clients/src/main/java/org/apache/kafka/common/requests/MetadataRequest.java | 118 | [] | true | 1 | 6.88 | apache/kafka | 31,560 | javadoc | false | |
keys | function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
} | Creates an array of the own enumerable property names of `object`.
**Note:** Non-object values are coerced to objects. See the
[ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
for more details.
@static
@since 0.1.0
@memberOf _
@category Object
@param {Object} object The object to query.
@returns {... | javascript | lodash.js | 13,413 | [
"object"
] | false | 2 | 7.44 | lodash/lodash | 61,490 | jsdoc | false | |
records | public Map<TopicPartition, List<ConsumerRecord<K, V>>> records() {
final LinkedHashMap<TopicPartition, List<ConsumerRecord<K, V>>> result = new LinkedHashMap<>();
batches.forEach((tip, batch) -> result.put(tip.topicPartition(), batch.getInFlightRecords()));
return Collections.unmodifiableMap(res... | @return all the non-control messages for this fetch, grouped by partition | java | clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareFetch.java | 83 | [] | true | 1 | 6.4 | apache/kafka | 31,560 | javadoc | false | |
getObjectTransformationCost | private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
if (destClass.isPrimitive()) {
return getPrimitivePromotionCost(srcClass, destClass);
}
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if ... | Gets the number of steps needed to turn the source class into the destination class. This represents the number of steps in the object hierarchy graph.
@param srcClass The source class.
@param destClass The destination class.
@return The cost of transforming an object. | java | src/main/java/org/apache/commons/lang3/reflect/MemberUtils.java | 135 | [
"srcClass",
"destClass"
] | true | 7 | 8.24 | apache/commons-lang | 2,896 | javadoc | false | |
containsAny | private static boolean containsAny(final ToBooleanBiFunction<CharSequence, CharSequence> test, final CharSequence cs,
final CharSequence... searchCharSequences) {
if (StringUtils.isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) {
return false;
}
for (final CharSequ... | Tests if the CharSequence contains any of the CharSequences in the given array.
<p>
A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero length search array will return {@code false}.
</p>
@param cs The CharSequence to check, may be null
@param searchCharSequences Th... | java | src/main/java/org/apache/commons/lang3/Strings.java | 295 | [
"test",
"cs"
] | true | 4 | 7.92 | apache/commons-lang | 2,896 | javadoc | false | |
_is_node_groupable_for_sink_waits | def _is_node_groupable_for_sink_waits(
candidate: BaseSchedulerNode,
) -> tuple[bool, Optional[str]]:
"""
Check if a candidate node can be grouped during sink_waits pass.
Sink Waits traverses waits right to left, so we don't group with
processed waits on the right or with async collectives.
Ar... | Check if a candidate node can be grouped during sink_waits pass.
Sink Waits traverses waits right to left, so we don't group with
processed waits on the right or with async collectives.
Args:
candidate: Node to check for groupability
Returns:
Tuple of (is_groupable, reason_if_not_groupable) | python | torch/_inductor/comms.py | 1,398 | [
"candidate"
] | tuple[bool, Optional[str]] | true | 6 | 8.08 | pytorch/pytorch | 96,034 | google | false |
_where | def _where(self, mask: npt.NDArray[np.bool_], value) -> Self:
"""
Analogue to np.where(mask, self, value)
Parameters
----------
mask : np.ndarray[bool]
value : scalar or listlike
Returns
-------
same type as self
"""
result = self... | Analogue to np.where(mask, self, value)
Parameters
----------
mask : np.ndarray[bool]
value : scalar or listlike
Returns
-------
same type as self | python | pandas/core/arrays/base.py | 2,516 | [
"self",
"mask",
"value"
] | Self | true | 3 | 6.24 | pandas-dev/pandas | 47,362 | numpy | false |
between_time | def between_time(
self,
start_time,
end_time,
inclusive: IntervalClosedType = "both",
axis: Axis | None = None,
) -> Self:
"""
Select values between particular times of the day (e.g., 9:00-9:30 AM).
By setting ``start_time`` to be later than ``end_tim... | Select values between particular times of the day (e.g., 9:00-9:30 AM).
By setting ``start_time`` to be later than ``end_time``,
you can get the times that are *not* between the two times.
Parameters
----------
start_time : datetime.time or str
Initial time as a time filter limit.
end_time : datetime.time or str
... | python | pandas/core/generic.py | 8,617 | [
"self",
"start_time",
"end_time",
"inclusive",
"axis"
] | Self | true | 3 | 8.4 | pandas-dev/pandas | 47,362 | numpy | false |
head | function head(array) {
return (array && array.length) ? array[0] : undefined;
} | Gets the first element of `array`.
@static
@memberOf _
@since 0.1.0
@alias first
@category Array
@param {Array} array The array to query.
@returns {*} Returns the first element of `array`.
@example
_.head([1, 2, 3]);
// => 1
_.head([]);
// => undefined | javascript | lodash.js | 7,526 | [
"array"
] | false | 3 | 7.44 | lodash/lodash | 61,490 | jsdoc | false | |
fix_group_permissions | def fix_group_permissions():
"""Fixes permissions of all the files and directories that have group-write access."""
if get_verbose():
get_console().print("[info]Fixing group permissions[/]")
files_to_fix_result = run_command(["git", "ls-files", "./"], capture_output=True, check=False, text=True)
... | Fixes permissions of all the files and directories that have group-write access. | python | dev/breeze/src/airflow_breeze/utils/run_utils.py | 359 | [] | false | 6 | 6.08 | apache/airflow | 43,597 | unknown | false | |
isDone | @Override
public boolean isDone() {
if (nextRecordMetadata != null)
return nextRecordMetadata.isDone();
return this.result.completed();
} | This method is used when we have to split a large batch in smaller ones. A chained metadata will allow the
future that has already returned to the users to wait on the newly created split batches even after the
old big batch has been deemed as done. | java | clients/src/main/java/org/apache/kafka/clients/producer/internals/FutureRecordMetadata.java | 113 | [] | true | 2 | 7.04 | apache/kafka | 31,560 | javadoc | false | |
get_block_to_lifted_attrs | def get_block_to_lifted_attrs(
graph: torch._C.Graph,
) -> tuple[dict[torch._C.Block, set[str]], dict[str, str]]:
"""
Perform two passes to get a mapping of blocks to a set of FQNs of its lifted attributes.
When a graph has control flow, the graph will be divided into multiple blocks. We want to convert... | Perform two passes to get a mapping of blocks to a set of FQNs of its lifted attributes.
When a graph has control flow, the graph will be divided into multiple blocks. We want to convert
each block to a graph which will be passed into torch.cond. A restriction for torch.cond is that model
parameters/buffers are expecte... | python | torch/_export/converter.py | 265 | [
"graph"
] | tuple[dict[torch._C.Block, set[str]], dict[str, str]] | true | 9 | 8.16 | pytorch/pytorch | 96,034 | unknown | false |
type | public Optional<GroupType> type() {
return type;
} | The type of the consumer group.
@return An Optional containing the type, if available. | java | clients/src/main/java/org/apache/kafka/clients/admin/ConsumerGroupListing.java | 151 | [] | true | 1 | 6.8 | apache/kafka | 31,560 | javadoc | false | |
get_schema_defaults | def get_schema_defaults(cls, object_type: str) -> dict[str, Any]:
"""
Extract default values from JSON schema for any object type.
:param object_type: The object type to get defaults for (e.g., "operator", "dag")
:return: Dictionary of field name -> default value
"""
# L... | Extract default values from JSON schema for any object type.
:param object_type: The object type to get defaults for (e.g., "operator", "dag")
:return: Dictionary of field name -> default value | python | airflow-core/src/airflow/serialization/serialized_objects.py | 944 | [
"cls",
"object_type"
] | dict[str, Any] | true | 5 | 8.4 | apache/airflow | 43,597 | sphinx | false |
_iset_split_block | def _iset_split_block(
self,
blkno_l: int,
blk_locs: np.ndarray | list[int],
value: ArrayLike | None = None,
refs: BlockValuesRefs | None = None,
) -> None:
"""Removes columns from a block by splitting the block.
Avoids copying the whole block through slicing... | Removes columns from a block by splitting the block.
Avoids copying the whole block through slicing and updates the manager
after determining the new block structure. Optionally adds a new block,
otherwise has to be done by the caller.
Parameters
----------
blkno_l: The block number to operate on, relevant for updati... | python | pandas/core/internals/managers.py | 1,385 | [
"self",
"blkno_l",
"blk_locs",
"value",
"refs"
] | None | true | 7 | 7.2 | pandas-dev/pandas | 47,362 | numpy | false |
startupDurations | @J2ObjCIncompatible
// If users use this when they shouldn't, we hope that NewApi will catch subsequent Duration calls
@IgnoreJRERequirement
public ImmutableMap<Service, Duration> startupDurations() {
return ImmutableMap.copyOf(
Maps.<Service, Long, Duration>transformValues(startupTimes(), Duration::o... | Returns the service load times. This value will only return startup times for services that
have finished starting.
@return Map of services and their corresponding startup time, the map entries will be ordered
by startup time.
@since 33.4.0 (but since 31.0 in the JRE flavor) | java | android/guava/src/com/google/common/util/concurrent/ServiceManager.java | 433 | [] | true | 1 | 7.04 | google/guava | 51,352 | javadoc | false | |
setBucket | private void setBucket(long index, long count, boolean isPositive) {
if (count < 1) {
throw new IllegalArgumentException("Bucket count must be at least 1");
}
if (negativeBuckets == null && positiveBuckets == null) {
// so far, all received buckets were in order, try to d... | Sets the given bucket of the negative buckets. If the bucket already exists, it will be replaced.
Buckets may be set in arbitrary order. However, for best performance and minimal allocations,
buckets should be set in order of increasing index and all negative buckets should be set before positive buckets.
@param index ... | java | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramBuilder.java | 160 | [
"index",
"count",
"isPositive"
] | void | true | 10 | 8.4 | elastic/elasticsearch | 75,680 | javadoc | false |
getBeanTypeConverter | protected TypeConverter getBeanTypeConverter() {
BeanFactory beanFactory = getBeanFactory();
if (beanFactory instanceof ConfigurableBeanFactory cbf) {
return cbf.getTypeConverter();
}
else {
return new SimpleTypeConverter();
}
} | Obtain a bean type converter from the BeanFactory that this bean
runs in. This is typically a fresh instance for each call,
since TypeConverters are usually <i>not</i> thread-safe.
<p>Falls back to a SimpleTypeConverter when not running in a BeanFactory.
@see ConfigurableBeanFactory#getTypeConverter()
@see org.springfr... | java | spring-beans/src/main/java/org/springframework/beans/factory/config/AbstractFactoryBean.java | 121 | [] | TypeConverter | true | 2 | 6.24 | spring-projects/spring-framework | 59,386 | javadoc | false |
totalCount | double totalCount() {
long count = 0;
for (Sample sample : samples) {
count += sample.eventCount;
}
return count;
} | Return the computed frequency describing the number of occurrences of the values in the bucket for the given
center point, relative to the total number of occurrences in the samples.
@param config the metric configuration
@param now the current time in milliseconds
@param centerValue the value correspondin... | java | clients/src/main/java/org/apache/kafka/common/metrics/stats/Frequencies.java | 148 | [] | true | 1 | 6.4 | apache/kafka | 31,560 | javadoc | false | |
_accumulate | def _accumulate(
self, name: str, *, skipna: bool = True, **kwargs
) -> ExtensionArray:
"""
Return an ExtensionArray performing an accumulation operation.
The underlying data type might change.
Parameters
----------
name : str
Name of the functio... | Return an ExtensionArray performing an accumulation operation.
The underlying data type might change.
Parameters
----------
name : str
Name of the function, supported values are:
- cummin
- cummax
- cumsum
- cumprod
skipna : bool, default True
If True, skip NA values.
**kwargs
Additional k... | python | pandas/core/arrays/base.py | 2,188 | [
"self",
"name",
"skipna"
] | ExtensionArray | true | 1 | 6.64 | pandas-dev/pandas | 47,362 | numpy | false |
get_session | def get_session():
"""Get the configured Session, raising an error if not configured."""
if Session is None:
raise RuntimeError("Session not configured. Call configure_orm() first.")
return Session | Get the configured Session, raising an error if not configured. | python | airflow-core/src/airflow/settings.py | 149 | [] | false | 2 | 6.08 | apache/airflow | 43,597 | unknown | false | |
hashCode | @Override
public int hashCode() {
final int prime = 31;
int result = prime + topicId.hashCode();
result = prime * result + topicPartition.hashCode();
return result;
} | @return Topic partition representing this instance. | java | clients/src/main/java/org/apache/kafka/common/TopicIdPartition.java | 94 | [] | true | 1 | 6.4 | apache/kafka | 31,560 | javadoc | false | |
values | function values(object) {
return object == null ? [] : baseValues(object, keys(object));
} | Creates an array of the own enumerable string keyed property values of `object`.
**Note:** Non-object values are coerced to objects.
@static
@since 0.1.0
@memberOf _
@category Object
@param {Object} object The object to query.
@returns {Array} Returns the array of property values.
@example
function Foo() {
this.a = 1... | javascript | lodash.js | 14,035 | [
"object"
] | false | 2 | 7.44 | lodash/lodash | 61,490 | jsdoc | false | |
findDimensionFields | private static boolean findDimensionFields(List<String> dimensions, DocumentMapper documentMapper) {
for (var objectMapper : documentMapper.mappers().objectMappers().values()) {
if (objectMapper instanceof PassThroughObjectMapper passThroughObjectMapper) {
if (passThroughObjectMapper... | Finds the dimension fields in the provided document mapper and adds them to the provided list.
@param dimensions the list to which the found dimension fields will be added
@param documentMapper the document mapper from which to extract the dimension fields
@return true if all potential dimension fields can be matched v... | java | modules/data-streams/src/main/java/org/elasticsearch/datastreams/DataStreamIndexSettingsProvider.java | 247 | [
"dimensions",
"documentMapper"
] | true | 5 | 7.92 | elastic/elasticsearch | 75,680 | javadoc | false | |
nameHash | private int nameHash(CharSequence namePrefix, CharSequence name) {
int nameHash = 0;
nameHash = (namePrefix != null) ? ZipString.hash(nameHash, namePrefix, false) : nameHash;
nameHash = ZipString.hash(nameHash, name, true);
return nameHash;
} | Return the entry at the specified index.
@param index the entry index
@return the entry
@throws IndexOutOfBoundsException if the index is out of bounds | java | loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/ZipContent.java | 271 | [
"namePrefix",
"name"
] | true | 2 | 7.76 | spring-projects/spring-boot | 79,428 | javadoc | false | |
nsecToMSec | public static long nsecToMSec(long ns) {
return ns / NSEC_PER_MSEC;
} | @param sValue Value to parse, which may be {@code null}.
@param defaultValue Value to return if {@code sValue} is {@code null}.
@param settingName Name of the parameter or setting. On invalid input, this value is included in the exception message. Otherwise,
this parameter is unused.
@return ... | java | libs/core/src/main/java/org/elasticsearch/core/TimeValue.java | 448 | [
"ns"
] | true | 1 | 6.8 | elastic/elasticsearch | 75,680 | javadoc | false | |
execute_query | def execute_query(
self,
sql: str | list[str],
database: str | None = None,
cluster_identifier: str | None = None,
db_user: str | None = None,
parameters: Iterable | None = None,
secret_arn: str | None = None,
statement_name: str | None = None,
wit... | Execute a statement against Amazon Redshift.
:param sql: the SQL statement or list of SQL statement to run
:param database: the name of the database
:param cluster_identifier: unique identifier of a cluster
:param db_user: the database username
:param parameters: the parameters for the SQL statement
:param secret_arn... | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/redshift_data.py | 79 | [
"self",
"sql",
"database",
"cluster_identifier",
"db_user",
"parameters",
"secret_arn",
"statement_name",
"with_event",
"wait_for_completion",
"poll_interval",
"workgroup_name",
"session_id",
"session_keep_alive_seconds"
] | QueryExecutionOutput | true | 10 | 6.16 | apache/airflow | 43,597 | sphinx | false |
enableSubstitutionForNamespaceExports | function enableSubstitutionForNamespaceExports() {
if ((enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports) === 0) {
enabledSubstitutions |= TypeScriptSubstitutionFlags.NamespaceExports;
// We need to enable substitutions for identifiers and shorthand property assig... | Gets the expression used to refer to a namespace or enum within the body
of its declaration. | typescript | src/compiler/transformers/ts.ts | 2,580 | [] | false | 2 | 6.4 | microsoft/TypeScript | 107,154 | jsdoc | false | |
getLayout | protected final Layout getLayout() {
if (this.layout == null) {
Layout createdLayout = getLayoutFactory().getLayout(this.source);
Assert.state(createdLayout != null, "Unable to detect layout");
this.layout = createdLayout;
}
return this.layout;
} | Return the {@link File} to use to back up the original source.
@return the file to use to back up the original source | java | loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java | 375 | [] | Layout | true | 2 | 8.08 | spring-projects/spring-boot | 79,428 | javadoc | false |
describe_jobs | def describe_jobs(self, jobs: list[str]) -> dict:
"""
Get job descriptions from AWS Batch.
:param jobs: a list of JobId to describe
:return: an API response to describe jobs
"""
... | Get job descriptions from AWS Batch.
:param jobs: a list of JobId to describe
:return: an API response to describe jobs | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/batch_client.py | 61 | [
"self",
"jobs"
] | dict | true | 1 | 6.56 | apache/airflow | 43,597 | sphinx | false |
appendln | public StrBuilder appendln(final long value) {
return append(value).appendNewLine();
} | Appends a long value followed by a new line to the string builder using {@code String.valueOf}.
@param value the value to append
@return {@code this} instance.
@since 2.3 | java | src/main/java/org/apache/commons/lang3/text/StrBuilder.java | 1,015 | [
"value"
] | StrBuilder | true | 1 | 6.8 | apache/commons-lang | 2,896 | javadoc | false |
getCSVInstance | public static StrTokenizer getCSVInstance(final String input) {
final StrTokenizer tok = getCSVClone();
tok.reset(input);
return tok;
} | Gets a new tokenizer instance which parses Comma Separated Value strings
initializing it with the given input. The default for CSV processing
will be trim whitespace from both ends (which can be overridden with
the setTrimmer method).
@param input the text to parse.
@return a new tokenizer instance which parses Comma... | java | src/main/java/org/apache/commons/lang3/text/StrTokenizer.java | 164 | [
"input"
] | StrTokenizer | true | 1 | 6.72 | apache/commons-lang | 2,896 | javadoc | false |
hermadd | def hermadd(c1, c2):
"""
Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, ... | Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coeffici... | python | numpy/polynomial/hermite.py | 312 | [
"c1",
"c2"
] | false | 1 | 6.32 | numpy/numpy | 31,054 | numpy | false | |
asSslStoreBundle | private static SslStoreBundle asSslStoreBundle(JksSslBundleProperties properties, ResourceLoader resourceLoader) {
JksSslStoreDetails keyStoreDetails = asStoreDetails(properties.getKeystore());
JksSslStoreDetails trustStoreDetails = asStoreDetails(properties.getTruststore());
return new JksSslStoreBundle(keyStore... | Get an {@link SslBundle} for the given {@link JksSslBundleProperties}.
@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 | 172 | [
"properties",
"resourceLoader"
] | SslStoreBundle | true | 1 | 6.56 | spring-projects/spring-boot | 79,428 | javadoc | false |
emptyArray | @SuppressWarnings("unchecked")
public static <L, R> ImmutablePair<L, R>[] emptyArray() {
return (ImmutablePair<L, R>[]) EMPTY_ARRAY;
} | Returns the empty array singleton that can be assigned without compiler warning.
@param <L> the left element type
@param <R> the right element type
@return the empty array singleton that can be assigned without compiler warning.
@since 3.10 | java | src/main/java/org/apache/commons/lang3/tuple/ImmutablePair.java | 65 | [] | true | 1 | 6.96 | apache/commons-lang | 2,896 | javadoc | false | |
optInt | public int optInt(String name) {
return optInt(name, 0);
} | Returns the value mapped by {@code name} if it exists and is an int or can be
coerced to an int. Returns 0 otherwise.
@param name the name of the property
@return the value of {@code 0} | java | cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java | 489 | [
"name"
] | true | 1 | 6.8 | spring-projects/spring-boot | 79,428 | javadoc | false | |
arrayToObject | function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
} | Convert an array to an object.
@param {Array<any>} arr - The array to convert to an object.
@returns An object with the same keys and values as the array. | javascript | lib/helpers/formDataToJSON.js | 29 | [
"arr"
] | false | 2 | 6.24 | axios/axios | 108,381 | jsdoc | false | |
format | @Override
public String format(final Calendar calendar) {
return printer.format(calendar);
} | Formats a {@link Calendar} object.
@param calendar the calendar to format.
@return the formatted string. | java | src/main/java/org/apache/commons/lang3/time/FastDateFormat.java | 406 | [
"calendar"
] | String | true | 1 | 6.64 | apache/commons-lang | 2,896 | javadoc | false |
additive_chi2_kernel | def additive_chi2_kernel(X, Y=None):
"""Compute the additive chi-squared kernel between observations in X and Y.
The chi-squared kernel is computed between each pair of rows in X and Y. X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.
The chi-squared kernel is ... | Compute the additive chi-squared kernel between observations in X and Y.
The chi-squared kernel is computed between each pair of rows in X and Y. X
and Y have to be non-negative. This kernel is most commonly applied to
histograms.
The chi-squared kernel is given by:
.. code-block:: text
k(x, y) = -Sum [(x - y)... | python | sklearn/metrics/pairwise.py | 1,753 | [
"X",
"Y"
] | false | 6 | 7.44 | scikit-learn/scikit-learn | 64,340 | numpy | false | |
createImportCallExpressionAMD | function createImportCallExpressionAMD(arg: Expression | undefined, containsLexicalThis: boolean): Expression {
// improt("./blah")
// emit as
// define(["require", "exports", "blah"], function (require, exports) {
// ...
// new Promise(function (_a, _b) { require([x... | Visits the body of a Block to hoist declarations.
@param node The node to visit. | typescript | src/compiler/transformers/module/module.ts | 1,272 | [
"arg",
"containsLexicalThis"
] | true | 6 | 6.64 | microsoft/TypeScript | 107,154 | jsdoc | false | |
trimcoef | def trimcoef(c, tol=0):
"""
Remove "small" "trailing" coefficients from a polynomial.
"Small" means "small in absolute value" and is controlled by the
parameter `tol`; "trailing" means highest order coefficient(s), e.g., in
``[0, 1, 1, 0, 0]`` (which represents ``0 + x + x**2 + 0*x**3 + 0*x**4``)
... | Remove "small" "trailing" coefficients from a polynomial.
"Small" means "small in absolute value" and is controlled by the
parameter `tol`; "trailing" means highest order coefficient(s), e.g., in
``[0, 1, 1, 0, 0]`` (which represents ``0 + x + x**2 + 0*x**3 + 0*x**4``)
both the 3-rd and 4-th order coefficients would b... | python | numpy/polynomial/polyutils.py | 144 | [
"c",
"tol"
] | false | 4 | 7.52 | numpy/numpy | 31,054 | numpy | false | |
partitionLag | public synchronized Long partitionLag(TopicPartition tp, IsolationLevel isolationLevel) {
TopicPartitionState topicPartitionState = assignedState(tp);
if (topicPartitionState.position == null) {
return null;
} else if (isolationLevel == IsolationLevel.READ_COMMITTED) {
re... | 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 | 640 | [
"tp",
"isolationLevel"
] | Long | true | 5 | 6.4 | apache/kafka | 31,560 | javadoc | false |
col | def col(col_name: Hashable) -> Expression:
"""
Generate deferred object representing a column of a DataFrame.
Any place which accepts ``lambda df: df[col_name]``, such as
:meth:`DataFrame.assign` or :meth:`DataFrame.loc`, can also accept
``pd.col(col_name)``.
.. versionadded:: 3.0.0
Param... | Generate deferred object representing a column of a DataFrame.
Any place which accepts ``lambda df: df[col_name]``, such as
:meth:`DataFrame.assign` or :meth:`DataFrame.loc`, can also accept
``pd.col(col_name)``.
.. versionadded:: 3.0.0
Parameters
----------
col_name : Hashable
Column name.
Returns
-------
`pan... | python | pandas/core/col.py | 255 | [
"col_name"
] | Expression | true | 4 | 8 | pandas-dev/pandas | 47,362 | numpy | false |
_optimize | def _optimize(
rebuild_ctx: Callable[[], Union[OptimizeContext, _NullDecorator]],
backend: Union[str, Callable[..., Any]] = "inductor",
*,
nopython: bool = False,
error_on_graph_break: Optional[bool] = None,
guard_export_fn: Optional[Callable[[_guards.GuardsSet], None]] = None,
guard_fail_fn... | The main entrypoint of TorchDynamo. Do graph capture and call
backend() to optimize extracted graphs.
Args:
backend: One of the two things:
- Either, a function/callable taking a torch.fx.GraphModule and
example_inputs and returning a python callable that runs the
graph faster.
One... | python | torch/_dynamo/eval_frame.py | 1,428 | [
"rebuild_ctx",
"backend",
"nopython",
"error_on_graph_break",
"guard_export_fn",
"guard_fail_fn",
"guard_filter_fn",
"disable",
"dynamic",
"package"
] | Union[OptimizeContext, _NullDecorator] | true | 10 | 6.48 | pytorch/pytorch | 96,034 | google | false |
dt64arr_to_periodarr | def dt64arr_to_periodarr(
data, freq, tz=None
) -> tuple[npt.NDArray[np.int64], BaseOffset]:
"""
Convert a datetime-like array to values Period ordinals.
Parameters
----------
data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
freq : Optional[Union[str, Tick]]
... | Convert a datetime-like array to values Period ordinals.
Parameters
----------
data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
freq : Optional[Union[str, Tick]]
Must match the `freq` on the `data` if `data` is a DatetimeIndex
or Series.
tz : Optional[tzinfo]
Returns
-------
ordinals... | python | pandas/core/arrays/period.py | 1,334 | [
"data",
"freq",
"tz"
] | tuple[npt.NDArray[np.int64], BaseOffset] | true | 7 | 6.24 | pandas-dev/pandas | 47,362 | numpy | false |
alterShareGroupOffsets | AlterShareGroupOffsetsResult alterShareGroupOffsets(String groupId, Map<TopicPartition, Long> offsets, AlterShareGroupOffsetsOptions options); | Alters offsets for the specified group. In order to succeed, the group must be empty.
<p>This operation is not transactional, so it may succeed for some partitions while fail for others.
@param groupId The group for which to alter offsets.
@param offsets A map of offsets by partition. Partitions not specified in the ma... | java | clients/src/main/java/org/apache/kafka/clients/admin/Admin.java | 1,955 | [
"groupId",
"offsets",
"options"
] | AlterShareGroupOffsetsResult | true | 1 | 6.48 | apache/kafka | 31,560 | javadoc | false |
beginWaitingFor | @GuardedBy("lock")
private void beginWaitingFor(Guard guard) {
int waiters = guard.waiterCount++;
if (waiters == 0) {
// push guard onto activeGuards
guard.next = activeGuards;
activeGuards = guard;
}
} | Records that the current thread is about to wait on the specified guard. | java | android/guava/src/com/google/common/util/concurrent/Monitor.java | 1,152 | [
"guard"
] | void | true | 2 | 6 | google/guava | 51,352 | javadoc | false |
default_dtypes | def default_dtypes(self, /, *, device: _Device | None = None) -> DefaultDTypes:
"""
The default data types used for new Dask arrays.
For Dask, this always returns the following dictionary:
- **"real floating"**: ``numpy.float64``
- **"complex floating"**: ``numpy.complex128``
... | The default data types used for new Dask arrays.
For Dask, this always returns the following dictionary:
- **"real floating"**: ``numpy.float64``
- **"complex floating"**: ``numpy.complex128``
- **"integral"**: ``numpy.intp``
- **"indexing"**: ``numpy.intp``
Parameters
----------
device : str, optional
The devic... | python | sklearn/externals/array_api_compat/dask/array/_info.py | 172 | [
"self",
"device"
] | DefaultDTypes | true | 2 | 7.84 | scikit-learn/scikit-learn | 64,340 | numpy | false |
get_job_state | def get_job_state(self, job_name: str, run_id: str) -> str:
"""
Get the status of a job run.
:param job_name: The name of the job being processed during this run.
:param run_id: The unique identifier of the job run.
:return: State of the job run.
'STARTING'|'RUNNING'... | Get the status of a job run.
:param job_name: The name of the job being processed during this run.
:param run_id: The unique identifier of the job run.
:return: State of the job run.
'STARTING'|'RUNNING'|'STOPPING'|'STOPPED'|'SUCCEEDED'|'FAILED'|'TIMEOUT' | python | providers/amazon/src/airflow/providers/amazon/aws/hooks/glue_databrew.py | 58 | [
"self",
"job_name",
"run_id"
] | str | true | 1 | 6.56 | apache/airflow | 43,597 | sphinx | false |
isJulUsingASingleConsoleHandlerAtMost | private boolean isJulUsingASingleConsoleHandlerAtMost() {
java.util.logging.Logger rootLogger = java.util.logging.LogManager.getLogManager().getLogger("");
Handler[] handlers = rootLogger.getHandlers();
return handlers.length == 0 || (handlers.length == 1 && handlers[0] instanceof ConsoleHandler);
} | 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 configura... | java | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystem.java | 198 | [] | true | 3 | 7.28 | spring-projects/spring-boot | 79,428 | javadoc | false | |
find_guarded_entry | def find_guarded_entry(
cls: type[GuardedCache[T]],
key: str,
local: bool,
remote_cache: RemoteCache[JsonDataTy] | None,
evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool],
hints: list[int],
) -> tuple[T | None, bytes | None, dict[str, str]]:
... | Find the first cache entry in iterate_over_candidates that passes `evaluate_guards`.
Args:
key: The cache key to look up
local: Whether to check the local cache
remote_cache: The remote cache to check, if any
evaluate_guards: Function that evaluates whether a guard passes the check,
given a lis... | python | torch/_inductor/codecache.py | 1,059 | [
"cls",
"key",
"local",
"remote_cache",
"evaluate_guards",
"hints"
] | tuple[T | None, bytes | None, dict[str, str]] | true | 6 | 7.84 | pytorch/pytorch | 96,034 | google | false |
dotProduct | private static double dotProduct(double x1, double y1, double z1, double x2, double y2, double z2) {
return x1 * x2 + y1 * y2 + z1 * z2;
} | Calculate the dot product between two 3D coordinates.
@param x1 The first 3D coordinate from the first set of coordinates.
@param y1 The second 3D coordinate from the first set of coordinates.
@param z1 The third 3D coordinate from the first set of coordinates.
@param x2 The first 3D coordinate from the second set of c... | java | libs/h3/src/main/java/org/elasticsearch/h3/Vec3d.java | 218 | [
"x1",
"y1",
"z1",
"x2",
"y2",
"z2"
] | true | 1 | 6.72 | elastic/elasticsearch | 75,680 | javadoc | false | |
first | def first(
self, numeric_only: bool = False, min_count: int = -1, skipna: bool = True
) -> NDFrameT:
"""
Compute the first entry of each column within each group.
Defaults to skipping NA elements.
Parameters
----------
numeric_only : bool, default False
... | Compute the first entry of each column within each group.
Defaults to skipping NA elements.
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns.
min_count : int, default -1
The required number of valid values to perform the operation. If fewer
than ``min_count... | python | pandas/core/groupby/groupby.py | 3,255 | [
"self",
"numeric_only",
"min_count",
"skipna"
] | NDFrameT | true | 5 | 8.4 | pandas-dev/pandas | 47,362 | numpy | false |
_get_dag_with_task | def _get_dag_with_task(
dagbag: DagBag, dag_id: str, task_id: str | None = None
) -> tuple[DAG, BaseOperator | MappedOperator | None]:
"""
Retrieve a DAG and optionally a task from the DagBag.
:param dagbag: DagBag to retrieve from
:param dag_id: DAG ID to retrieve
:param task_id: Optional task... | Retrieve a DAG and optionally a task from the DagBag.
:param dagbag: DagBag to retrieve from
:param dag_id: DAG ID to retrieve
:param task_id: Optional task ID to retrieve from the DAG
:return: tuple of (dag, task) where task is None if not requested
:raises ValueError: If DAG or task is not found | python | airflow-core/src/airflow/dag_processing/processor.py | 255 | [
"dagbag",
"dag_id",
"task_id"
] | tuple[DAG, BaseOperator | MappedOperator | None] | true | 3 | 7.92 | apache/airflow | 43,597 | sphinx | false |
_execute_work | def _execute_work(log: Logger, workload: workloads.ExecuteTask, team_conf) -> None:
"""
Execute command received and stores result state in queue.
:param log: Logger instance
:param workload: The workload to execute
:param team_conf: Team-specific executor configuration
"""
from airflow.sdk... | Execute command received and stores result state in queue.
:param log: Logger instance
:param workload: The workload to execute
:param team_conf: Team-specific executor configuration | python | airflow-core/src/airflow/executors/local_executor.py | 111 | [
"log",
"workload",
"team_conf"
] | None | true | 3 | 6.56 | apache/airflow | 43,597 | sphinx | false |
toIntValue | public static int toIntValue(final Character ch) {
return toIntValue(toChar(ch));
} | Converts the character to the Integer it represents, throwing an
exception if the character is not numeric.
<p>This method converts the char '1' to the int 1 and so on.</p>
<pre>
CharUtils.toIntValue('3') = 3
CharUtils.toIntValue(null) throws IllegalArgumentException
CharUtils.toIntValue('A') throws IllegalArgu... | java | src/main/java/org/apache/commons/lang3/CharUtils.java | 431 | [
"ch"
] | true | 1 | 6.16 | apache/commons-lang | 2,896 | javadoc | false | |
checkNoOverflow | private static int checkNoOverflow(long result) {
checkArgument(
result == (int) result,
"the total number of elements (%s) in the arrays must fit in an int",
result);
return (int) result;
} | Returns the values from each provided array combined into a single array. For example, {@code
concat(new boolean[] {a, b}, new boolean[] {}, new boolean[] {c}} returns the array {@code {a,
b, c}}.
@param arrays zero or more {@code boolean} arrays
@return a single array containing all the values from the source arrays, ... | java | android/guava/src/com/google/common/primitives/Booleans.java | 250 | [
"result"
] | true | 1 | 6.56 | google/guava | 51,352 | javadoc | false | |
prod | def prod(
self, numeric_only: bool = False, min_count: int = 0, skipna: bool = True
) -> NDFrameT:
"""
Compute prod of group values.
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns.
.. version... | Compute prod of group values.
Parameters
----------
numeric_only : bool, default False
Include only float, int, boolean columns.
.. versionchanged:: 2.0.0
numeric_only no longer accepts ``None``.
min_count : int, default 0
The required number of valid values to perform the operation. If fewer
... | python | pandas/core/groupby/groupby.py | 3,031 | [
"self",
"numeric_only",
"min_count",
"skipna"
] | NDFrameT | true | 1 | 7.2 | pandas-dev/pandas | 47,362 | numpy | false |
ffill | def ffill(self, limit: int | None = None):
"""
Forward fill the values.
Parameters
----------
limit : int, optional
Limit of how many values to fill.
Returns
-------
Series or DataFrame
Object with missing values filled.
... | Forward fill the values.
Parameters
----------
limit : int, optional
Limit of how many values to fill.
Returns
-------
Series or DataFrame
Object with missing values filled.
See Also
--------
Series.ffill: Returns Series with minimum number of char in object.
DataFrame.ffill: Object with missing values fille... | python | pandas/core/groupby/groupby.py | 4,090 | [
"self",
"limit"
] | true | 1 | 7.04 | pandas-dev/pandas | 47,362 | numpy | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.