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
loadBeanDefinitions
@Override public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException { Assert.notNull(locations, "Location array must not be null"); int count = 0; for (String location : locations) { count += loadBeanDefinitions(location); } return count; }
Load bean definitions from the specified resource location. <p>The location can also be a location pattern, provided that the ResourceLoader of this bean definition reader is a ResourcePatternResolver. @param location the resource location, to be loaded with the ResourceLoader (or ResourcePatternResolver) of this bean definition reader @param actualResources a Set to be filled with the actual Resource objects that have been resolved during the loading process. May be {@code null} to indicate that the caller is not interested in those Resource objects. @return the number of bean definitions found @throws BeanDefinitionStoreException in case of loading or parsing errors @see #getResourceLoader() @see #loadBeanDefinitions(org.springframework.core.io.Resource) @see #loadBeanDefinitions(org.springframework.core.io.Resource[])
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinitionReader.java
244
[]
true
1
6.24
spring-projects/spring-framework
59,386
javadoc
false
detect_quorum_queues
def detect_quorum_queues(app, driver_type: str) -> tuple[bool, str]: """Detect if any of the queues are quorum queues. Returns: tuple[bool, str]: A tuple containing a boolean indicating if any of the queues are quorum queues and the name of the first quorum queue found or an empty string if no quorum queues were found. """ is_rabbitmq_broker = driver_type == 'amqp' if is_rabbitmq_broker: queues = app.amqp.queues for qname in queues: qarguments = queues[qname].queue_arguments or {} if qarguments.get("x-queue-type") == "quorum": return True, qname return False, ""
Detect if any of the queues are quorum queues. Returns: tuple[bool, str]: A tuple containing a boolean indicating if any of the queues are quorum queues and the name of the first quorum queue found or an empty string if no quorum queues were found.
python
celery/utils/quorum_queues.py
4
[ "app", "driver_type" ]
tuple[bool, str]
true
5
7.92
celery/celery
27,741
unknown
false
bumpIdempotentEpochAndResetIdIfNeeded
synchronized void bumpIdempotentEpochAndResetIdIfNeeded() { if (!isTransactional()) { if (clientSideEpochBumpRequired) { bumpIdempotentProducerEpoch(); } if (currentState != State.INITIALIZING && !hasProducerId()) { transitionTo(State.INITIALIZING); InitProducerIdRequestData requestData = new InitProducerIdRequestData() .setTransactionalId(null) .setTransactionTimeoutMs(Integer.MAX_VALUE); InitProducerIdHandler handler = new InitProducerIdHandler(new InitProducerIdRequest.Builder(requestData), false); enqueueRequest(handler); } } }
This method is used to trigger an epoch bump for non-transactional idempotent producers.
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
665
[]
void
true
5
6.72
apache/kafka
31,560
javadoc
false
writeRecords
@Override public void writeRecords(BaseRecords records) { if (records instanceof MemoryRecords) { flushPendingBuffer(); addBuffer(((MemoryRecords) records).buffer()); } else if (records instanceof UnalignedMemoryRecords) { flushPendingBuffer(); addBuffer(((UnalignedMemoryRecords) records).buffer()); } else { flushPendingSend(); addSend(records.toSend()); } }
Write a record set. The underlying record data will be retained in the result of {@link #build()}. See {@link BaseRecords#toSend()}. @param records the records to write
java
clients/src/main/java/org/apache/kafka/common/protocol/SendBuilder.java
136
[ "records" ]
void
true
3
6.88
apache/kafka
31,560
javadoc
false
format
<B extends Appendable> B format(long millis, B buf);
Formats a millisecond {@code long} value into the supplied {@link Appendable}. @param millis the millisecond value to format. @param buf the buffer to format into. @param <B> the Appendable class type, usually StringBuilder or StringBuffer. @return the specified string buffer. @since 3.5
java
src/main/java/org/apache/commons/lang3/time/DatePrinter.java
128
[ "millis", "buf" ]
B
true
1
6.48
apache/commons-lang
2,896
javadoc
false
cat_core
def cat_core(list_of_columns: list, sep: str): """ Auxiliary function for :meth:`str.cat` Parameters ---------- list_of_columns : list of numpy arrays List of arrays to be concatenated with sep; these arrays may not contain NaNs! sep : string The separator string for concatenating the columns. Returns ------- nd.array The concatenation of list_of_columns with sep. """ if sep == "": # no need to interleave sep if it is empty arr_of_cols = np.asarray(list_of_columns, dtype=object) return np.sum(arr_of_cols, axis=0) list_with_sep = [sep] * (2 * len(list_of_columns) - 1) list_with_sep[::2] = list_of_columns arr_with_sep = np.asarray(list_with_sep, dtype=object) return np.sum(arr_with_sep, axis=0)
Auxiliary function for :meth:`str.cat` Parameters ---------- list_of_columns : list of numpy arrays List of arrays to be concatenated with sep; these arrays may not contain NaNs! sep : string The separator string for concatenating the columns. Returns ------- nd.array The concatenation of list_of_columns with sep.
python
pandas/core/strings/accessor.py
3,897
[ "list_of_columns", "sep" ]
true
2
6.56
pandas-dev/pandas
47,362
numpy
false
items
public ConditionMessage items(Style style, @Nullable Collection<?> items) { Assert.notNull(style, "'style' must not be null"); StringBuilder message = new StringBuilder(this.reason); items = style.applyTo(items); if ((this.condition == null || items == null || items.size() <= 1) && StringUtils.hasLength(this.singular)) { message.append(" ").append(this.singular); } else if (StringUtils.hasLength(this.plural)) { message.append(" ").append(this.plural); } if (!CollectionUtils.isEmpty(items)) { message.append(" ").append(StringUtils.collectionToDelimitedString(items, ", ")); } return this.condition.because(message.toString()); }
Indicate the items with a {@link Style}. For example {@code didNotFind("bean", "beans").items(Style.QUOTE, Collections.singleton("x")} results in the message "did not find bean 'x'". @param style the render style @param items the source of the items (may be {@code null}) @return a built {@link ConditionMessage}
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java
383
[ "style", "items" ]
ConditionMessage
true
7
7.76
spring-projects/spring-boot
79,428
javadoc
false
stringValueOf
static String stringValueOf(@Nullable Object o) { return String.valueOf(o); }
Returns the string if it is not empty, or a null string otherwise. @param string the string to test and possibly return @return {@code string} if it is not empty; {@code null} otherwise
java
android/guava/src/com/google/common/base/Platform.java
85
[ "o" ]
String
true
1
6.96
google/guava
51,352
javadoc
false
_read
def _read(self, ti, try_number, metadata=None): """ Read logs of given task instance and try_number from OSS remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param metadata: log metadata, can be used for steaming log reading and auto-tailing. """ # Explicitly getting log relative path is necessary as the given # task instance might be different from task instance passed in # set_context method. log_relative_path = self._render_filename(ti, try_number) remote_loc = log_relative_path if not self.oss_log_exists(remote_loc): return super()._read(ti, try_number, metadata) # If OSS remote file exists, we do not fetch logs from task instance # local machine even if there are errors reading remote logs, as # returned remote_log will contain error messages. remote_log = self.oss_read(remote_loc, return_error=True) log = f"*** Reading remote log from {remote_loc}.\n{remote_log}\n" return log, {"end_of_log": True}
Read logs of given task instance and try_number from OSS remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param metadata: log metadata, can be used for steaming log reading and auto-tailing.
python
providers/alibaba/src/airflow/providers/alibaba/cloud/log/oss_task_handler.py
231
[ "self", "ti", "try_number", "metadata" ]
false
2
6.24
apache/airflow
43,597
sphinx
false
addMinutes
public static Date addMinutes(final Date date, final int amount) { return add(date, Calendar.MINUTE, amount); }
Adds a number of minutes to a date returning a new object. The original {@link Date} is unchanged. @param date the date, not null. @param amount the amount to add, may be negative. @return the new {@link Date} with the amount added. @throws NullPointerException if the date is null.
java
src/main/java/org/apache/commons/lang3/time/DateUtils.java
276
[ "date", "amount" ]
Date
true
1
6.8
apache/commons-lang
2,896
javadoc
false
getConfiguredCertificates
public Collection<? extends StoredCertificate> getConfiguredCertificates() { List<StoredCertificate> certificates = new ArrayList<>(); certificates.addAll(keyConfig.getConfiguredCertificates()); certificates.addAll(trustConfig.getConfiguredCertificates()); return certificates; }
@return A collection of {@link StoredCertificate certificates} that are used by this SSL configuration. This includes certificates used for identity (with a private key) and those used for trust, but excludes certificates that are provided by the JRE.
java
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfiguration.java
118
[]
true
1
6.56
elastic/elasticsearch
75,680
javadoc
false
duplicate
Message duplicate();
Make a deep copy of the message. @return A copy of the message which does not share any mutable fields.
java
clients/src/main/java/org/apache/kafka/common/protocol/Message.java
103
[]
Message
true
1
6.48
apache/kafka
31,560
javadoc
false
findRecursiveTypes
private static int[] findRecursiveTypes(final ParameterizedType parameterizedType) { final Type[] filteredArgumentTypes = Arrays.copyOf(parameterizedType.getActualTypeArguments(), parameterizedType.getActualTypeArguments().length); int[] indexesToRemove = {}; for (int i = 0; i < filteredArgumentTypes.length; i++) { if (filteredArgumentTypes[i] instanceof TypeVariable<?> && containsVariableTypeSameParametrizedTypeBound((TypeVariable<?>) filteredArgumentTypes[i], parameterizedType)) { indexesToRemove = ArrayUtils.add(indexesToRemove, i); } } return indexesToRemove; }
Helper method to establish the formal parameters for a parameterized type. @param mappings map containing the assignments. @param variables expected map keys. @return array of map values corresponding to specified keys.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
554
[ "parameterizedType" ]
true
4
7.76
apache/commons-lang
2,896
javadoc
false
firstNonBlank
@SafeVarargs public static <T extends CharSequence> T firstNonBlank(final T... values) { if (values != null) { for (final T val : values) { if (isNotBlank(val)) { return val; } } } return null; }
Returns the first value in the array which is not empty (""), {@code null} or whitespace only. <p> Whitespace is defined by {@link Character#isWhitespace(char)}. </p> <p> If all values are blank or the array is {@code null} or empty then {@code null} is returned. </p> <pre> StringUtils.firstNonBlank(null, null, null) = null StringUtils.firstNonBlank(null, "", " ") = null StringUtils.firstNonBlank("abc") = "abc" StringUtils.firstNonBlank(null, "xyz") = "xyz" StringUtils.firstNonBlank(null, "", " ", "xyz") = "xyz" StringUtils.firstNonBlank(null, "xyz", "abc") = "xyz" StringUtils.firstNonBlank() = null </pre> @param <T> the specific kind of CharSequence. @param values the values to test, may be {@code null} or empty. @return the first value from {@code values} which is not blank, or {@code null} if there are no non-blank values. @since 3.8
java
src/main/java/org/apache/commons/lang3/StringUtils.java
1,895
[]
T
true
3
7.76
apache/commons-lang
2,896
javadoc
false
equals
@Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ConditionMessage other) { return ObjectUtils.nullSafeEquals(other.message, this.message); } return false; }
Return {@code true} if the message is empty. @return if the message is empty
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java
65
[ "obj" ]
true
3
7.04
spring-projects/spring-boot
79,428
javadoc
false
generateReturnStatement
private CodeBlock generateReturnStatement(GeneratedMethod generatedMethod) { return generatedMethod.toMethodReference().toInvokeCodeBlock( ArgumentCodeGenerator.none(), this.className); }
Generate the instance supplier code. @param registeredBean the bean to handle @param instantiationDescriptor the executable to use to create the bean @return the generated code @since 6.1.7
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java
364
[ "generatedMethod" ]
CodeBlock
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
isVisible
private boolean isVisible(Member member, Class<?> targetClass) { AccessControl classAccessControl = AccessControl.forClass(targetClass); AccessControl memberAccessControl = AccessControl.forMember(member); Visibility visibility = AccessControl.lowest(classAccessControl, memberAccessControl).getVisibility(); return (visibility == Visibility.PUBLIC || (visibility != Visibility.PRIVATE && member.getDeclaringClass().getPackageName().equals(this.className.packageName()))); }
Generate the instance supplier code. @param registeredBean the bean to handle @param instantiationDescriptor the executable to use to create the bean @return the generated code @since 6.1.7
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java
381
[ "member", "targetClass" ]
true
3
7.44
spring-projects/spring-framework
59,386
javadoc
false
allEqual
public static Ordering<@Nullable Object> allEqual() { return AllEqualOrdering.INSTANCE; }
Returns an ordering which treats all values as equal, indicating "no ordering." Passing this ordering to any <i>stable</i> sort algorithm results in no change to the order of elements. Note especially that {@link #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the returned instance these are implemented by simply copying the source list. <p>Example: {@snippet : Ordering.allEqual().nullsLast().sortedCopy( asList(t, null, e, s, null, t, null)) } <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns {@code [t, e, s, t, null, null, null]} regardless of the true comparison order of those three values (which might not even implement {@link Comparable} at all). <p><b>Warning:</b> by definition, this comparator is not <i>consistent with equals</i> (as defined {@linkplain Comparator here}). Avoid its use in APIs, such as {@link TreeSet#TreeSet(Comparator)}, where such consistency is expected. <p>The returned comparator is serializable. <p><b>Java 8+ users:</b> Use the lambda expression {@code (a, b) -> 0} instead (in certain cases you may need to cast that to {@code Comparator<YourType>}). @since 13.0
java
android/guava/src/com/google/common/collect/Ordering.java
290
[]
true
1
7.04
google/guava
51,352
javadoc
false
nextNumeric
public String nextNumeric(final int count) { return next(count, false, true); }
Creates a random string whose length is the number of characters specified. <p> Characters will be chosen from the set of numeric characters. </p> @param count the length of random string to create. @return the random string. @throws IllegalArgumentException if {@code count} &lt; 0.
java
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
937
[ "count" ]
String
true
1
6.8
apache/commons-lang
2,896
javadoc
false
toString
@Override public String toString() { return this.topicIdPartitions.toString(); }
@return Set of topic partitions (with topic name and partition number)
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/TopicIdPartitionSet.java
119
[]
String
true
1
6.32
apache/kafka
31,560
javadoc
false
isAllEmpty
public static boolean isAllEmpty(final CharSequence... css) { if (ArrayUtils.isEmpty(css)) { return true; } for (final CharSequence cs : css) { if (isNotEmpty(cs)) { return false; } } return true; }
Tests if all of the CharSequences are empty ("") or null. <pre> StringUtils.isAllEmpty(null) = true StringUtils.isAllEmpty(null, "") = true StringUtils.isAllEmpty(new String[] {}) = true StringUtils.isAllEmpty(null, "foo") = false StringUtils.isAllEmpty("", "bar") = false StringUtils.isAllEmpty("bob", "") = false StringUtils.isAllEmpty(" bob ", null) = false StringUtils.isAllEmpty(" ", "bar") = false StringUtils.isAllEmpty("foo", "bar") = false </pre> @param css the CharSequences to check, may be null or empty. @return {@code true} if all of the CharSequences are empty or null. @since 3.6
java
src/main/java/org/apache/commons/lang3/StringUtils.java
3,160
[]
true
3
7.76
apache/commons-lang
2,896
javadoc
false
setCurrentlyInCreation
public void setCurrentlyInCreation(String beanName, boolean inCreation) { Assert.notNull(beanName, "Bean name must not be null"); if (!inCreation) { this.inCreationCheckExclusions.add(beanName); } else { this.inCreationCheckExclusions.remove(beanName); } }
Remove the bean with the given name from the singleton registry, either on regular destruction or on cleanup after early exposure when creation failed. @param beanName the name of the bean
java
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java
505
[ "beanName", "inCreation" ]
void
true
2
6.56
spring-projects/spring-framework
59,386
javadoc
false
principal
@Override public KafkaPrincipal principal() { InetAddress clientAddress = transportLayer.socketChannel().socket().getInetAddress(); // listenerName should only be null in Client mode where principal() should not be called if (listenerName == null) throw new IllegalStateException("Unexpected call to principal() when listenerName is null"); SslAuthenticationContext context = new SslAuthenticationContext( transportLayer.sslSession(), clientAddress, listenerName.value()); return principalBuilder.build(context); }
Constructs Principal using configured principalBuilder. @return the built principal
java
clients/src/main/java/org/apache/kafka/common/network/SslChannelBuilder.java
150
[]
KafkaPrincipal
true
2
7.44
apache/kafka
31,560
javadoc
false
floatValue
@Override public float floatValue() { return value; }
Returns the value of this MutableByte as a float. @return the numeric value represented by this object after conversion to type float.
java
src/main/java/org/apache/commons/lang3/mutable/MutableByte.java
204
[]
true
1
6.48
apache/commons-lang
2,896
javadoc
false
get_knee_point_memory_budget
def get_knee_point_memory_budget( self, knapsack_algo: Callable[ [list[float], list[float], float], tuple[float, list[int], list[int]] ], max_mem_budget: float = 0.1, min_mem_budget: float = 0.001, iterations: int = 100, ) -> float: """ Finds the memory budget at the knee point in the Pareto frontier. The knee point is defined as the point where the trade-off between runtime and memory usage is optimal. Args: knapsack_algo (callable): Knapsack algorithm to use for evaluation. max_mem_budget (float, optional): Maximum memory budget. Defaults to 0.1. min_mem_budget (float, optional): Minimum memory budget. Defaults to 0.001. iterations (int, optional): Number of memory budgets to evaluate. Defaults to 100. Returns: float: Memory budget at the knee point. """ results = self.evaluate_distribution_of_results_for_knapsack_algo( knapsack_algo=knapsack_algo, memory_budget_values=[ min_mem_budget + i * (max_mem_budget - min_mem_budget) / (iterations - 1) for i in range(iterations) ], ) runtime_values = [ result["percentage_of_theoretical_peak_runtime"] for result in results ] memory_values = [ result["percentage_of_theoretical_peak_memory"] for result in results ] runtime_range = max(runtime_values) - min(runtime_values) memory_range = max(memory_values) - min(memory_values) if runtime_range == 0 or memory_range == 0: return max_mem_budget # Normalize values runtime_min = min(runtime_values) memory_min = min(memory_values) runtime_norm = [ (value - runtime_min) / runtime_range for value in runtime_values ] memory_norm = [(value - memory_min) / memory_range for value in memory_values] # Calculate Euclidean distance distances = [ (runtime_norm[i] ** 2 + memory_norm[i] ** 2) ** 0.5 for i in range(len(runtime_norm)) ] # Find the knee point(shortest distance from the origin) knee_index = distances.index(min(distances)) return results[knee_index]["memory_budget"]
Finds the memory budget at the knee point in the Pareto frontier. The knee point is defined as the point where the trade-off between runtime and memory usage is optimal. Args: knapsack_algo (callable): Knapsack algorithm to use for evaluation. max_mem_budget (float, optional): Maximum memory budget. Defaults to 0.1. min_mem_budget (float, optional): Minimum memory budget. Defaults to 0.001. iterations (int, optional): Number of memory budgets to evaluate. Defaults to 100. Returns: float: Memory budget at the knee point.
python
torch/_functorch/_activation_checkpointing/knapsack_evaluator.py
216
[ "self", "knapsack_algo", "max_mem_budget", "min_mem_budget", "iterations" ]
float
true
3
8
pytorch/pytorch
96,034
google
false
runOnDemand
private void runOnDemand() { if (isCancelled() || isCompleted()) { logger.debug("Not running downloader on demand because task is cancelled or completed"); return; } // Capture the current queue size, so that if another run is requested while we're running, we'll know at the end of this method // whether we need to run again. final int currentQueueSize = queuedRuns.get(); logger.trace("Running downloader on demand"); try { runDownloader(); logger.trace("Downloader completed successfully"); } finally { // If any exception was thrown during runDownloader, we still want to check queuedRuns. // Subtract this "batch" of runs from queuedRuns. // If queuedRuns is still > 0, then a run was requested while we were running, so we need to run again. if (queuedRuns.addAndGet(-currentQueueSize) > 0) { logger.debug("Downloader on demand requested again while running, scheduling another run"); threadPool.generic().submit(this::runOnDemand); } } }
Runs the downloader on the latest cluster state. {@link #queuedRuns} protects against multiple concurrent runs and ensures that if a run is requested while this method is running, then another run will be scheduled to run as soon as this method finishes.
java
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/AbstractGeoIpDownloader.java
129
[]
void
true
4
6.72
elastic/elasticsearch
75,680
javadoc
false
initializeDeprecations
function initializeDeprecations() { const pendingDeprecation = getOptionValue('--pending-deprecation'); // DEP0103: access to `process.binding('util').isX` type checkers // TODO(addaleax): Turn into a full runtime deprecation. const utilBinding = internalBinding('util'); const types = require('internal/util/types'); for (const name of [ 'isArrayBuffer', 'isArrayBufferView', 'isAsyncFunction', 'isDataView', 'isDate', 'isExternal', 'isMap', 'isMapIterator', 'isNativeError', 'isPromise', 'isRegExp', 'isSet', 'isSetIterator', 'isTypedArray', 'isUint8Array', 'isAnyArrayBuffer', ]) { utilBinding[name] = pendingDeprecation ? deprecate(types[name], 'Accessing native typechecking bindings of Node ' + 'directly is deprecated. ' + `Please use \`util.types.${name}\` instead.`, 'DEP0103') : types[name]; } // TODO(joyeecheung): this is a legacy property exposed to process. // Now that we use the config binding to carry this information, remove // it from the process. We may consider exposing it properly in // process.features. const { noBrowserGlobals } = internalBinding('config'); if (noBrowserGlobals) { ObjectDefineProperty(process, '_noBrowserGlobals', { __proto__: null, writable: false, enumerable: true, configurable: true, value: noBrowserGlobals, }); } if (pendingDeprecation) { process.binding = deprecate(process.binding, 'process.binding() is deprecated. ' + 'Please use public APIs instead.', 'DEP0111'); process._tickCallback = deprecate(process._tickCallback, 'process._tickCallback() is deprecated', 'DEP0134'); } }
Patch the process object with legacy properties and normalizations. Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`. Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found. @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of the main entry point. @returns {string}
javascript
lib/internal/process/pre_execution.js
518
[]
false
4
6.88
nodejs/node
114,839
jsdoc
false
isEmpty
public boolean isEmpty() { for (Deque<NetworkClient.InFlightRequest> deque : this.requests.values()) { if (!deque.isEmpty()) return false; } return true; }
Return true if there is no in-flight request and false otherwise
java
clients/src/main/java/org/apache/kafka/clients/InFlightRequests.java
130
[]
true
2
6.56
apache/kafka
31,560
javadoc
false
stringify
function stringify(body) { if (typeof body === 'string') { return body; } assertBufferSource(body, false, 'load'); const { TextDecoder } = require('internal/encoding'); DECODER = DECODER === null ? new TextDecoder() : DECODER; return DECODER.decode(body); }
Converts a buffer or buffer-like object to a string. @param {string | ArrayBuffer | ArrayBufferView} body - The buffer or buffer-like object to convert to a string. @returns {string} The resulting string.
javascript
lib/internal/modules/helpers.js
396
[ "body" ]
false
3
6.08
nodejs/node
114,839
jsdoc
false
get_installation_airflow_sources
def get_installation_airflow_sources() -> Path | None: """ Retrieves the Root of the Airflow Sources where Breeze was installed from. :return: the Path for Airflow sources. """ return search_upwards_for_airflow_root_path(Path(__file__).resolve().parent)
Retrieves the Root of the Airflow Sources where Breeze was installed from. :return: the Path for Airflow sources.
python
dev/breeze/src/airflow_breeze/utils/path_utils.py
161
[]
Path | None
true
1
6.88
apache/airflow
43,597
unknown
false
refreshCommittedOffsets
public static void refreshCommittedOffsets(final Map<TopicPartition, OffsetAndMetadata> offsetsAndMetadata, final ConsumerMetadata metadata, final SubscriptionState subscriptions) { for (final Map.Entry<TopicPartition, OffsetAndMetadata> entry : offsetsAndMetadata.entrySet()) { final TopicPartition tp = entry.getKey(); final OffsetAndMetadata offsetAndMetadata = entry.getValue(); if (offsetAndMetadata != null) { // first update the epoch if necessary entry.getValue().leaderEpoch().ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(entry.getKey(), epoch)); // it's possible that the partition is no longer assigned when the response is received, // so we need to ignore seeking if that's the case if (subscriptions.isAssigned(tp)) { final ConsumerMetadata.LeaderAndEpoch leaderAndEpoch = metadata.currentLeader(tp); final SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetAndMetadata.offset(), offsetAndMetadata.leaderEpoch(), leaderAndEpoch); subscriptions.seekUnvalidated(tp, position); log.info("Setting offset for partition {} to the committed offset {}", tp, position); } else { log.info("Ignoring the returned {} since its partition {} is no longer assigned", offsetAndMetadata, tp); } } } }
Update subscription state and metadata using the provided committed offsets: <li>Update partition offsets with the committed offsets</li> <li>Update the metadata with any newer leader epoch discovered in the committed offsets metadata</li> </p> This will ignore any partition included in the <code>offsetsAndMetadata</code> parameter that may no longer be assigned. @param offsetsAndMetadata Committed offsets and metadata to be used for updating the subscription state and metadata object. @param metadata Metadata object to update with a new leader epoch if discovered in the committed offsets' metadata. @param subscriptions Subscription state to update, setting partitions' offsets to the committed offsets.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerUtils.java
190
[ "offsetsAndMetadata", "metadata", "subscriptions" ]
void
true
3
6.4
apache/kafka
31,560
javadoc
false
compress
@Override public void compress() { if (needsCompression == false) { return; } needsCompression = false; try (AVLGroupTree centroids = summary) { this.summary = AVLGroupTree.create(arrays); final int[] nodes = new int[centroids.size()]; nodes[0] = centroids.first(); for (int i = 1; i < nodes.length; ++i) { nodes[i] = centroids.next(nodes[i - 1]); assert nodes[i] != IntAVLTree.NIL; } assert centroids.next(nodes[nodes.length - 1]) == IntAVLTree.NIL; for (int i = centroids.size() - 1; i > 0; --i) { final int other = gen.nextInt(i + 1); final int tmp = nodes[other]; nodes[other] = nodes[i]; nodes[i] = tmp; } for (int node : nodes) { add(centroids.mean(node), centroids.count(node)); } } }
Sets the seed for the RNG. In cases where a predictable tree should be created, this function may be used to make the randomness in this AVLTree become more deterministic. @param seed The random seed to use for RNG purposes
java
libs/tdigest/src/main/java/org/elasticsearch/tdigest/AVLTreeDigest.java
169
[]
void
true
4
7.04
elastic/elasticsearch
75,680
javadoc
false
buildKeyedPropertyName
private @Nullable String buildKeyedPropertyName(@Nullable String propertyName, Object key) { return (propertyName != null ? propertyName + PropertyAccessor.PROPERTY_KEY_PREFIX + key + PropertyAccessor.PROPERTY_KEY_SUFFIX : null); }
Convert the given text value using the given property editor. @param oldValue the previous value, if available (may be {@code null}) @param newTextValue the proposed text value @param editor the PropertyEditor to use @return the converted value
java
spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
632
[ "propertyName", "key" ]
String
true
2
7.6
spring-projects/spring-framework
59,386
javadoc
false
toString
@Override public String toString() { return "ReplicaState(" + "replicaId=" + replicaId + ", replicaDirectoryId=" + replicaDirectoryId + ", logEndOffset=" + logEndOffset + ", lastFetchTimestamp=" + lastFetchTimestamp + ", lastCaughtUpTimestamp=" + lastCaughtUpTimestamp + ')'; }
Return the last millisecond timestamp at which this replica was known to be caught up with the leader. @return The value of the lastCaughtUpTime if known, empty otherwise
java
clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java
193
[]
String
true
1
6.56
apache/kafka
31,560
javadoc
false
electLeaders
ElectLeadersResult electLeaders( ElectionType electionType, Set<TopicPartition> partitions, ElectLeadersOptions options);
Elect a replica as leader for the given {@code partitions}, or for all partitions if the argument to {@code partitions} is null. <p> This operation is not transactional so it may succeed for some partitions while fail for others. <p> It may take several seconds after this method returns success for all the brokers in the cluster to become aware that the partitions have new leaders. During this time, {@link #describeTopics(Collection)} may not return information about the partitions' new leaders. <p> This operation is supported by brokers with version 2.2.0 or later if preferred election is use; otherwise the brokers most be 2.4.0 or higher. <p> The following exceptions can be anticipated when calling {@code get()} on the future obtained from the returned {@link ElectLeadersResult}: <ul> <li>{@link org.apache.kafka.common.errors.ClusterAuthorizationException} if the authenticated user didn't have alter access to the cluster.</li> <li>{@link org.apache.kafka.common.errors.UnknownTopicOrPartitionException} if the topic or partition did not exist within the cluster.</li> <li>{@link org.apache.kafka.common.errors.InvalidTopicException} if the topic was already queued for deletion.</li> <li>{@link org.apache.kafka.common.errors.NotControllerException} if the request was sent to a broker that was not the controller for the cluster.</li> <li>{@link org.apache.kafka.common.errors.TimeoutException} if the request timed out before the election was complete.</li> <li>{@link org.apache.kafka.common.errors.LeaderNotAvailableException} if the preferred leader was not alive or not in the ISR.</li> </ul> @param electionType The type of election to conduct. @param partitions The topics and partitions for which to conduct elections. @param options The options to use when electing the leaders. @return The ElectLeadersResult.
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
1,132
[ "electionType", "partitions", "options" ]
ElectLeadersResult
true
1
6.16
apache/kafka
31,560
javadoc
false
request_is_alias
def request_is_alias(item): """Check if an item is a valid string alias for a metadata. Values in ``VALID_REQUEST_VALUES`` are not considered aliases in this context. Only a string which is a valid identifier is. Parameters ---------- item : object The given item to be checked if it can be an alias for the metadata. Returns ------- result : bool Whether the given item is a valid alias. """ if item in VALID_REQUEST_VALUES: return False # item is only an alias if it's a valid identifier return isinstance(item, str) and item.isidentifier()
Check if an item is a valid string alias for a metadata. Values in ``VALID_REQUEST_VALUES`` are not considered aliases in this context. Only a string which is a valid identifier is. Parameters ---------- item : object The given item to be checked if it can be an alias for the metadata. Returns ------- result : bool Whether the given item is a valid alias.
python
sklearn/utils/_metadata_requests.py
283
[ "item" ]
false
3
6.08
scikit-learn/scikit-learn
64,340
numpy
false
bind
public <T> BindResult<T> bind(ConfigurationPropertyName name, Bindable<T> target, @Nullable BindHandler handler) { T bound = bind(name, target, handler, false); return BindResult.of(bound); }
Bind the specified target {@link Bindable} using this binder's {@link ConfigurationPropertySource property sources}. @param name the configuration property name to bind @param target the target bindable @param handler the bind handler (may be {@code null}) @param <T> the bound type @return the binding result (never {@code null})
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java
286
[ "name", "target", "handler" ]
true
1
6.16
spring-projects/spring-boot
79,428
javadoc
false
responseContentTypeHeader
public String responseContentTypeHeader(Map<String, String> params) { return mediaTypeWithoutParameters() + formatParameters(params); }
Resolves this instance to a MediaType instance defined in given MediaTypeRegistry. Performs validation against parameters. @param mediaTypeRegistry a registry where a mapping between a raw media type to an instance MediaType is defined @return a MediaType instance or null if no media type could be found or if a known parameter do not passes validation
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/ParsedMediaType.java
162
[ "params" ]
String
true
1
6.32
elastic/elasticsearch
75,680
javadoc
false
exceptionName
public String exceptionName() { return exception == null ? null : exception.getClass().getName(); }
Returns the class name of the exception or null if this is {@code Errors.NONE}.
java
clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
474
[]
String
true
2
6.8
apache/kafka
31,560
javadoc
false
meta_namespace
def meta_namespace( *arrays: Array | complex | None, xp: ModuleType | None = None ) -> ModuleType: """ Get the namespace of Dask chunks. On all other backends, just return the namespace of the arrays. Parameters ---------- *arrays : Array | int | float | complex | bool | None Input arrays. xp : array_namespace, optional The standard-compatible namespace for the input arrays. Default: infer. Returns ------- array_namespace If xp is Dask, the namespace of the Dask chunks; otherwise, the namespace of the arrays. """ xp = array_namespace(*arrays) if xp is None else xp if not is_dask_namespace(xp): return xp # Quietly skip scalars and None's metas = [cast(Array | None, getattr(a, "_meta", None)) for a in arrays] return array_namespace(*metas)
Get the namespace of Dask chunks. On all other backends, just return the namespace of the arrays. Parameters ---------- *arrays : Array | int | float | complex | bool | None Input arrays. xp : array_namespace, optional The standard-compatible namespace for the input arrays. Default: infer. Returns ------- array_namespace If xp is Dask, the namespace of the Dask chunks; otherwise, the namespace of the arrays.
python
sklearn/externals/array_api_extra/_lib/_utils/_helpers.py
275
[ "xp" ]
ModuleType
true
3
6.88
scikit-learn/scikit-learn
64,340
numpy
false
determineTypeArguments
public static Map<TypeVariable<?>, Type> determineTypeArguments(final Class<?> cls, final ParameterizedType superParameterizedType) { Objects.requireNonNull(cls, "cls"); Objects.requireNonNull(superParameterizedType, "superParameterizedType"); final Class<?> superClass = getRawType(superParameterizedType); // compatibility check if (!isAssignable(cls, superClass)) { return null; } if (cls.equals(superClass)) { return getTypeArguments(superParameterizedType, superClass, null); } // get the next class in the inheritance hierarchy final Type midType = getClosestParentType(cls, superClass); // can only be a class or a parameterized type if (midType instanceof Class<?>) { return determineTypeArguments((Class<?>) midType, superParameterizedType); } final ParameterizedType midParameterizedType = (ParameterizedType) midType; final Class<?> midClass = getRawType(midParameterizedType); // get the type variables of the mid class that map to the type // arguments of the super class final Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(midClass, superParameterizedType); // map the arguments of the mid type to the class type variables mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns); return typeVarAssigns; }
Tries to determine the type arguments of a class/interface based on a super parameterized type's type arguments. This method is the inverse of {@link #getTypeArguments(Type, Class)} which gets a class/interface's type arguments based on a subtype. It is far more limited in determining the type arguments for the subject class's type variables in that it can only determine those parameters that map from the subject {@link Class} object to the supertype. <p> Example: {@link java.util.TreeSet TreeSet} sets its parameter as the parameter for {@link java.util.NavigableSet NavigableSet}, which in turn sets the parameter of {@link java.util.SortedSet}, which in turn sets the parameter of {@link Set}, which in turn sets the parameter of {@link java.util.Collection}, which in turn sets the parameter of {@link Iterable}. Since {@link TreeSet}'s parameter maps (indirectly) to {@link Iterable}'s parameter, it will be able to determine that based on the super type {@code Iterable<? extends Map<Integer, ? extends Collection<?>>>}, the parameter of {@link TreeSet} is {@code ? extends Map<Integer, ? extends Collection<?>>}. </p> @param cls the class whose type parameters are to be determined, not {@code null}. @param superParameterizedType the super type from which {@code cls}'s type arguments are to be determined, not {@code null}. @return a {@link Map} of the type assignments that could be determined for the type variables in each type in the inheritance hierarchy from {@code type} to {@code toClass} inclusive. @throws NullPointerException if either {@code cls} or {@code superParameterizedType} is {@code null}.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
423
[ "cls", "superParameterizedType" ]
true
4
9.68
apache/commons-lang
2,896
javadoc
false
intersection
public static ClassFilter intersection(ClassFilter cf1, ClassFilter cf2) { Assert.notNull(cf1, "First ClassFilter must not be null"); Assert.notNull(cf2, "Second ClassFilter must not be null"); return new IntersectionClassFilter(new ClassFilter[] {cf1, cf2}); }
Match all classes that <i>both</i> of the given ClassFilters match. @param cf1 the first ClassFilter @param cf2 the second ClassFilter @return a distinct ClassFilter that matches all classes that both of the given ClassFilter match
java
spring-aop/src/main/java/org/springframework/aop/support/ClassFilters.java
73
[ "cf1", "cf2" ]
ClassFilter
true
1
6.72
spring-projects/spring-framework
59,386
javadoc
false
copyRelevantMergedBeanDefinitionCaches
private void copyRelevantMergedBeanDefinitionCaches(RootBeanDefinition previous, RootBeanDefinition mbd) { if (ObjectUtils.nullSafeEquals(mbd.getBeanClassName(), previous.getBeanClassName()) && ObjectUtils.nullSafeEquals(mbd.getFactoryBeanName(), previous.getFactoryBeanName()) && ObjectUtils.nullSafeEquals(mbd.getFactoryMethodName(), previous.getFactoryMethodName())) { ResolvableType targetType = mbd.targetType; ResolvableType previousTargetType = previous.targetType; if (targetType == null || targetType.equals(previousTargetType)) { mbd.targetType = previousTargetType; mbd.isFactoryBean = previous.isFactoryBean; mbd.resolvedTargetType = previous.resolvedTargetType; mbd.factoryMethodReturnType = previous.factoryMethodReturnType; mbd.factoryMethodToIntrospect = previous.factoryMethodToIntrospect; } if (previous.hasMethodOverrides()) { mbd.setMethodOverrides(new MethodOverrides(previous.getMethodOverrides())); } } }
Return a RootBeanDefinition for the given bean, by merging with the parent if the given bean's definition is a child bean definition. @param beanName the name of the bean definition @param bd the original bean definition (Root/ChildBeanDefinition) @param containingBd the containing bean definition in case of inner bean, or {@code null} in case of a top-level bean @return a (potentially merged) RootBeanDefinition for the given bean @throws BeanDefinitionStoreException in case of an invalid bean definition
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
1,474
[ "previous", "mbd" ]
void
true
7
7.6
spring-projects/spring-framework
59,386
javadoc
false
available
public ConditionMessage available(String item) { return because(item + " is available"); }
Indicates something is available. For example {@code available("money")} results in the message "money is available". @param item the item that is available @return a built {@link ConditionMessage}
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java
281
[ "item" ]
ConditionMessage
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
parseJSDocFunctionType
function parseJSDocFunctionType(): JSDocFunctionType | TypeReferenceNode { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); if (tryParse(nextTokenIsOpenParen)) { const parameters = parseParameters(SignatureFlags.Type | SignatureFlags.JSDoc); const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc); } return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos); }
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 blank (not provided / skipped).
typescript
src/compiler/parser.ts
3,878
[]
true
2
6.72
microsoft/TypeScript
107,154
jsdoc
false
maybeThrowFatalException
protected synchronized void maybeThrowFatalException() { KafkaException metadataException = this.fatalException; if (metadataException != null) { fatalException = null; throw metadataException; } }
If any fatal exceptions were encountered during metadata update, throw the exception. This is used by the producer to abort waiting for metadata if there were fatal exceptions (e.g. authentication failures) in the last metadata update.
java
clients/src/main/java/org/apache/kafka/clients/Metadata.java
618
[]
void
true
2
7.04
apache/kafka
31,560
javadoc
false
_materialize_cpp_cia_ops
def _materialize_cpp_cia_ops() -> None: """ Utility function to query C++ dispatcher to get the all possible CIA ops and populate them into torch.ops namespace """ cia_ops = torch._C._dispatch_get_registrations_for_dispatch_key( "CompositeImplicitAutograd" ) # Materialize all CIA ops for op in cia_ops: namespace, op_name = tuple(op.split("::")) split_list = op_name.split(".") # Sometime overload could be missing assert len(split_list) == 1 or len(split_list) == 2 op_name = split_list[0] op_overload_name = "default" if len(split_list) == 2: op_overload_name = split_list[1] _ = getattr(getattr(getattr(torch.ops, namespace), op_name), op_overload_name)
Utility function to query C++ dispatcher to get the all possible CIA ops and populate them into torch.ops namespace
python
torch/_export/utils.py
1,257
[]
None
true
4
6.56
pytorch/pytorch
96,034
unknown
false
stripBOM
function stripBOM(content) { if (StringPrototypeCharCodeAt(content) === 0xFEFF) { content = StringPrototypeSlice(content, 1); } return content; }
Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) because the buffer-to-string conversion in `fs.readFileSync()` translates it to FEFF, the UTF-16 BOM. @param {string} content @returns {string}
javascript
lib/internal/modules/helpers.js
197
[ "content" ]
false
2
6.08
nodejs/node
114,839
jsdoc
false
initializeSystem
private void initializeSystem(ConfigurableEnvironment environment, LoggingSystem system, @Nullable LogFile logFile) { String logConfig = environment.getProperty(CONFIG_PROPERTY); if (StringUtils.hasLength(logConfig)) { logConfig = logConfig.strip(); } try { LoggingInitializationContext initializationContext = new LoggingInitializationContext(environment); if (ignoreLogConfig(logConfig)) { system.initialize(initializationContext, null, logFile); } else { system.initialize(initializationContext, logConfig, logFile); } } catch (Throwable ex) { Throwable exceptionToReport = ex; while (exceptionToReport != null && !(exceptionToReport instanceof FileNotFoundException)) { exceptionToReport = exceptionToReport.getCause(); } exceptionToReport = (exceptionToReport != null) ? exceptionToReport : ex; // NOTE: We can't use the logger here to report the problem System.err.println("Logging system failed to initialize using configuration from '" + logConfig + "'"); exceptionToReport.printStackTrace(System.err); throw new IllegalStateException(ex); } }
Initialize the logging system according to preferences expressed through the {@link Environment} and the classpath. @param environment the environment @param classLoader the classloader
java
core/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java
328
[ "environment", "system", "logFile" ]
void
true
7
6.24
spring-projects/spring-boot
79,428
javadoc
false
startsWithAny
public boolean startsWithAny(final CharSequence sequence, final CharSequence... searchStrings) { if (StringUtils.isEmpty(sequence) || ArrayUtils.isEmpty(searchStrings)) { return false; } for (final CharSequence searchString : searchStrings) { if (startsWith(sequence, searchString)) { return true; } } return false; }
Tests if a CharSequence starts with any of the provided prefixes. <p> Case-sensitive examples </p> <pre> Strings.CS.startsWithAny(null, null) = false Strings.CS.startsWithAny(null, new String[] {"abc"}) = false Strings.CS.startsWithAny("abcxyz", null) = false Strings.CS.startsWithAny("abcxyz", new String[] {""}) = true Strings.CS.startsWithAny("abcxyz", new String[] {"abc"}) = true Strings.CS.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true Strings.CS.startsWithAny("abcxyz", null, "xyz", "ABCX") = false Strings.CS.startsWithAny("ABCXYZ", null, "xyz", "abc") = false </pre> <p> Case-insensitive examples </p> <pre> Strings.CI.startsWithAny(null, null) = false Strings.CI.startsWithAny(null, new String[] {"aBc"}) = false Strings.CI.startsWithAny("AbCxYz", null) = false Strings.CI.startsWithAny("AbCxYz", new String[] {""}) = true Strings.CI.startsWithAny("AbCxYz", new String[] {"aBc"}) = true Strings.CI.startsWithAny("AbCxYz", new String[] {null, "XyZ", "aBc"}) = true Strings.CI.startsWithAny("abcxyz", null, "xyz", "ABCX") = true Strings.CI.startsWithAny("ABCXYZ", null, "xyz", "abc") = true </pre> @param sequence the CharSequence to check, may be null @param searchStrings the CharSequence prefixes, may be empty or contain {@code null} @see Strings#startsWith(CharSequence, CharSequence) @return {@code true} if the input {@code sequence} is {@code null} AND no {@code searchStrings} are provided, or the input {@code sequence} begins with any of the provided {@code searchStrings}.
java
src/main/java/org/apache/commons/lang3/Strings.java
1,453
[ "sequence" ]
true
4
7.76
apache/commons-lang
2,896
javadoc
false
get_task_status
def get_task_status(self, replication_task_arn: str) -> str | None: """ Retrieve task status. :param replication_task_arn: Replication task ARN :return: Current task status """ replication_tasks = self.find_replication_tasks_by_arn( replication_task_arn=replication_task_arn, without_settings=True, ) if len(replication_tasks) == 1: status = replication_tasks[0]["Status"] self.log.info('Replication task with ARN(%s) has status "%s".', replication_task_arn, status) return status self.log.info("Replication task with ARN(%s) is not found.", replication_task_arn) return None
Retrieve task status. :param replication_task_arn: Replication task ARN :return: Current task status
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/dms.py
95
[ "self", "replication_task_arn" ]
str | None
true
2
7.6
apache/airflow
43,597
sphinx
false
get
JarFile get(URL jarFileUrl) { JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl); synchronized (this) { return this.jarFileUrlToJarFile.get(urlKey); } }
Get a {@link JarFile} from the cache given a jar file URL. @param jarFileUrl the jar file URL @return the cached {@link JarFile} or {@code null}
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/UrlJarFiles.java
156
[ "jarFileUrl" ]
JarFile
true
1
6.4
spring-projects/spring-boot
79,428
javadoc
false
get_tags
def get_tags(estimator) -> Tags: """Get estimator tags. :class:`~sklearn.BaseEstimator` provides the estimator tags machinery. For scikit-learn built-in estimators, we should still rely on `self.__sklearn_tags__()`. `get_tags(est)` should be used when we are not sure where `est` comes from: typically `get_tags(self.estimator)` where `self` is a meta-estimator, or in the common checks. .. versionadded:: 1.6 Parameters ---------- estimator : estimator object The estimator from which to get the tag. Returns ------- tags : :class:`~.sklearn.utils.Tags` The estimator tags. """ try: tags = estimator.__sklearn_tags__() except AttributeError as exc: if "object has no attribute '__sklearn_tags__'" in str(exc): # Happens when `__sklearn_tags__` is implemented by calling # `super().__sklearn_tags__()` but there is no `__sklearn_tags__` # method in the base class. Typically happens when only inheriting # from Mixins. raise AttributeError( f"The following error was raised: {exc}. It seems that " "there are no classes that implement `__sklearn_tags__` " "in the MRO and/or all classes in the MRO call " "`super().__sklearn_tags__()`. Make sure to inherit from " "`BaseEstimator` which implements `__sklearn_tags__` (or " "alternatively define `__sklearn_tags__` but we don't recommend " "this approach). Note that `BaseEstimator` needs to be on the " "right side of other Mixins in the inheritance order." ) else: raise return tags
Get estimator tags. :class:`~sklearn.BaseEstimator` provides the estimator tags machinery. For scikit-learn built-in estimators, we should still rely on `self.__sklearn_tags__()`. `get_tags(est)` should be used when we are not sure where `est` comes from: typically `get_tags(self.estimator)` where `self` is a meta-estimator, or in the common checks. .. versionadded:: 1.6 Parameters ---------- estimator : estimator object The estimator from which to get the tag. Returns ------- tags : :class:`~.sklearn.utils.Tags` The estimator tags.
python
sklearn/utils/_tags.py
250
[ "estimator" ]
Tags
true
3
6.56
scikit-learn/scikit-learn
64,340
numpy
false
duration_expression_update
def duration_expression_update( cls, end_date: datetime, query: Update, bind: Engine | SAConnection ) -> Update: """Return a SQL expression for calculating the duration of this TI, based on the start and end date columns.""" # TODO: Compare it with self._set_duration method if bind.dialect.name == "sqlite": return query.values( { "end_date": end_date, "duration": ( (func.strftime("%s", end_date) - func.strftime("%s", cls.start_date)) + func.round((func.strftime("%f", end_date) - func.strftime("%f", cls.start_date)), 3) ), } ) if bind.dialect.name == "postgresql": return query.values( { "end_date": end_date, "duration": extract("EPOCH", end_date - cls.start_date), } ) return query.values( { "end_date": end_date, "duration": ( func.timestampdiff(text("MICROSECOND"), cls.start_date, end_date) # Turn microseconds into floating point seconds. / 1_000_000 ), } )
Return a SQL expression for calculating the duration of this TI, based on the start and end date columns.
python
airflow-core/src/airflow/models/taskinstance.py
2,112
[ "cls", "end_date", "query", "bind" ]
Update
true
3
6
apache/airflow
43,597
unknown
false
find_stack_level
def find_stack_level() -> int: """ Find the first place in the stack that is not inside pandas (tests notwithstanding). """ import pandas as pd pkg_dir = os.path.dirname(pd.__file__) test_dir = os.path.join(pkg_dir, "tests") # https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow frame: FrameType | None = inspect.currentframe() try: n = 0 while frame: filename = inspect.getfile(frame) if filename.startswith(pkg_dir) and not filename.startswith(test_dir): frame = frame.f_back n += 1 else: break finally: # See note in # https://docs.python.org/3/library/inspect.html#inspect.Traceback del frame return n
Find the first place in the stack that is not inside pandas (tests notwithstanding).
python
pandas/util/_exceptions.py
37
[]
int
true
5
7.2
pandas-dev/pandas
47,362
unknown
false
lookupStrategy
AdminApiLookupStrategy<K> lookupStrategy();
Get the lookup strategy that is responsible for finding the brokerId which will handle each respective key. @return non-null lookup strategy
java
clients/src/main/java/org/apache/kafka/clients/admin/internals/AdminApiHandler.java
97
[]
true
1
6.32
apache/kafka
31,560
javadoc
false
createInteger
public static Integer createInteger(final String str) { if (str == null) { return null; } // decode() handles 0xAABD and 0777 (hex and octal) as well. return Integer.decode(str); }
Creates an {@link Integer} from a {@link String}. Handles hexadecimal (0xhhhh) and octal (0dddd) notations. A leading zero means octal; spaces are not trimmed. <p> Returns {@code null} if the string is {@code null}. </p> @param str a {@link String} to convert, may be null. @return converted {@link Integer} (or null if the input is null). @throws NumberFormatException if the value cannot be converted.
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
261
[ "str" ]
Integer
true
2
8.24
apache/commons-lang
2,896
javadoc
false
pushAllSorted
private static void pushAllSorted(Deque<File> stack, File @Nullable [] files) { if (files == null) { return; } Arrays.sort(files, Comparator.comparing(File::getName)); for (File file : files) { stack.push(file); } }
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
159
[ "stack", "files" ]
void
true
2
7.76
spring-projects/spring-boot
79,428
javadoc
false
getAdvisors
@Override public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) { Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass(); String aspectName = aspectInstanceFactory.getAspectMetadata().getAspectName(); validate(aspectClass); // We need to wrap the MetadataAwareAspectInstanceFactory with a decorator // so that it will only instantiate once. MetadataAwareAspectInstanceFactory lazySingletonAspectInstanceFactory = new LazySingletonAspectInstanceFactoryDecorator(aspectInstanceFactory); List<Advisor> advisors = new ArrayList<>(); for (Method method : getAdvisorMethods(aspectClass)) { if (method.equals(ClassUtils.getMostSpecificMethod(method, aspectClass))) { // Prior to Spring Framework 5.2.7, advisors.size() was supplied as the declarationOrderInAspect // to getAdvisor(...) to represent the "current position" in the declared methods list. // However, since Java 7 the "current position" is not valid since the JDK no longer // returns declared methods in the order in which they are declared in the source code. // Thus, we now hard code the declarationOrderInAspect to 0 for all advice methods // discovered via reflection in order to support reliable advice ordering across JVM launches. // Specifically, a value of 0 aligns with the default value used in // AspectJPrecedenceComparator.getAspectDeclarationOrder(Advisor). Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, 0, aspectName); if (advisor != null) { advisors.add(advisor); } } } // If it's a per target aspect, emit the dummy instantiating aspect. if (!advisors.isEmpty() && lazySingletonAspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) { Advisor instantiationAdvisor = new SyntheticInstantiationAdvisor(lazySingletonAspectInstanceFactory); advisors.add(0, instantiationAdvisor); } // Find introduction fields. for (Field field : aspectClass.getDeclaredFields()) { Advisor advisor = getDeclareParentsAdvisor(field); if (advisor != null) { advisors.add(advisor); } } return advisors; }
Create a new {@code ReflectiveAspectJAdvisorFactory}, propagating the given {@link BeanFactory} to the created {@link AspectJExpressionPointcut} instances, for bean pointcut handling as well as consistent {@link ClassLoader} resolution. @param beanFactory the BeanFactory to propagate (may be {@code null}) @since 4.3.6 @see AspectJExpressionPointcut#setBeanFactory @see org.springframework.beans.factory.config.ConfigurableBeanFactory#getBeanClassLoader()
java
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java
122
[ "aspectInstanceFactory" ]
true
6
6.24
spring-projects/spring-framework
59,386
javadoc
false
optJSONArray
public JSONArray optJSONArray(int index) { Object object = opt(index); return object instanceof JSONArray ? (JSONArray) object : null; }
Returns the value at {@code index} if it exists and is a {@code JSONArray}. Returns null otherwise. @param index the index to get the value from @return the array at {@code index} or {@code null}
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java
540
[ "index" ]
JSONArray
true
2
8.16
spring-projects/spring-boot
79,428
javadoc
false
recordWaitTime
protected void recordWaitTime(long timeNs) { this.waitTime.record(timeNs, time.milliseconds()); }
Allocate a buffer of the given size. This method blocks if there is not enough memory and the buffer pool is configured with blocking mode. @param size The buffer size to allocate in bytes @param maxTimeToBlockMs The maximum time in milliseconds to block for buffer memory to be available @return The buffer @throws InterruptedException If the thread is interrupted while blocked @throws IllegalArgumentException if size is larger than the total memory controlled by the pool (and hence we would block forever)
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/BufferPool.java
210
[ "timeNs" ]
void
true
1
6.48
apache/kafka
31,560
javadoc
false
applyAsInt
int applyAsInt(T t, U u) throws E;
Applies this function to the given arguments. @param t the first function argument @param u the second function argument @return the function result @throws E Thrown when the function fails.
java
src/main/java/org/apache/commons/lang3/function/FailableToIntBiFunction.java
58
[ "t", "u" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
task
def task(self, *args, **opts): """Decorator to create a task class out of any callable. See :ref:`Task options<task-options>` for a list of the arguments that can be passed to this decorator. Examples: .. code-block:: python @app.task def refresh_feed(url): store_feed(feedparser.parse(url)) with setting extra options: .. code-block:: python @app.task(exchange='feeds') def refresh_feed(url): return store_feed(feedparser.parse(url)) Note: App Binding: For custom apps the task decorator will return a proxy object, so that the act of creating the task is not performed until the task is used or the task registry is accessed. If you're depending on binding to be deferred, then you must not access any attributes on the returned object until the application is fully set up (finalized). """ if USING_EXECV and opts.get('lazy', True): # When using execv the task in the original module will point to a # different app, so doing things like 'add.request' will point to # a different task instance. This makes sure it will always use # the task instance from the current app. # Really need a better solution for this :( from . import shared_task return shared_task(*args, lazy=False, **opts) def inner_create_task_cls(shared=True, filter=None, lazy=True, **opts): _filt = filter def _create_task_cls(fun): if shared: def cons(app): return app._task_from_fun(fun, **opts) cons.__name__ = fun.__name__ connect_on_app_finalize(cons) if not lazy or self.finalized: ret = self._task_from_fun(fun, **opts) else: # return a proxy object that evaluates on first use ret = PromiseProxy(self._task_from_fun, (fun,), opts, __doc__=fun.__doc__) self._pending.append(ret) if _filt: return _filt(ret) return ret return _create_task_cls if len(args) == 1: if callable(args[0]): return inner_create_task_cls(**opts)(*args) raise TypeError('argument 1 to @task() must be a callable') if args: raise TypeError( '@task() takes exactly 1 argument ({} given)'.format( sum([len(args), len(opts)]))) return inner_create_task_cls(**opts)
Decorator to create a task class out of any callable. See :ref:`Task options<task-options>` for a list of the arguments that can be passed to this decorator. Examples: .. code-block:: python @app.task def refresh_feed(url): store_feed(feedparser.parse(url)) with setting extra options: .. code-block:: python @app.task(exchange='feeds') def refresh_feed(url): return store_feed(feedparser.parse(url)) Note: App Binding: For custom apps the task decorator will return a proxy object, so that the act of creating the task is not performed until the task is used or the task registry is accessed. If you're depending on binding to be deferred, then you must not access any attributes on the returned object until the application is fully set up (finalized).
python
celery/app/base.py
489
[ "self" ]
false
11
7.6
celery/celery
27,741
unknown
false
toUtf16Escape
@Override protected String toUtf16Escape(final int codePoint) { final char[] surrogatePair = Character.toChars(codePoint); return "\\u" + hex(surrogatePair[0]) + "\\u" + hex(surrogatePair[1]); }
Converts the given code point to a hexadecimal string of the form {@code "\\uXXXX\\uXXXX"} @param codePoint a Unicode code point. @return the hexadecimal string for the given code point.
java
src/main/java/org/apache/commons/lang3/text/translate/JavaUnicodeEscaper.java
101
[ "codePoint" ]
String
true
1
6.72
apache/commons-lang
2,896
javadoc
false
assign
GroupAssignment assign(Cluster metadata, GroupSubscription groupSubscription);
Perform the group assignment given the member subscriptions and current cluster metadata. @param metadata Current topic/broker metadata known by consumer @param groupSubscription Subscriptions from all members including metadata provided through {@link #subscriptionUserData(Set)} @return A map from the members to their respective assignments. This should have one entry for each member in the input subscription map.
java
clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerPartitionAssignor.java
72
[ "metadata", "groupSubscription" ]
GroupAssignment
true
1
6
apache/kafka
31,560
javadoc
false
checkState
public static void checkState(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalStateException(Platform.stringValueOf(errorMessage)); } }
Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method. @param expression a boolean expression @param errorMessage the exception message to use if the check fails; will be converted to a string using {@link String#valueOf(Object)} @throws IllegalStateException if {@code expression} is false @see Verify#verify Verify.verify()
java
android/guava/src/com/google/common/base/Preconditions.java
511
[ "expression", "errorMessage" ]
void
true
2
6.08
google/guava
51,352
javadoc
false
list_command_invocations
def list_command_invocations(self, command_id: str) -> dict: """ List all command invocations for a given command ID. .. seealso:: - :external+boto3:py:meth:`SSM.Client.list_command_invocations` :param command_id: The ID of the command. :return: Response from SSM list_command_invocations API. """ return self.conn.list_command_invocations(CommandId=command_id)
List all command invocations for a given command ID. .. seealso:: - :external+boto3:py:meth:`SSM.Client.list_command_invocations` :param command_id: The ID of the command. :return: Response from SSM list_command_invocations API.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/ssm.py
91
[ "self", "command_id" ]
dict
true
1
6.24
apache/airflow
43,597
sphinx
false
get_zero_consts_asm_code
def get_zero_consts_asm_code( align_bytes: int, symbol_prefix: str, ) -> tuple[str, str]: """ This function handles zero-sized constants because the C++ standard prohibits zero-length arrays: https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c On Windows (MSVC): The compiler reports error C2466 for zero-sized arrays: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2466 Solution: Use assembly compilation to handle this case. Why not use Win32 assembly for all paths? ml64 only supports alignment up to 16 bytes, which isn't optimal for performance. Cross-platform implementation: Linux: Added '-pedantic' to disable zero-sized arrays in C++ compiler Windows: MSVC naturally rejects zero-sized arrays by default """ if _IS_WINDOWS: # Windows ml64 is max support align to 16, but it is no effect to zero size data. asm_code = """ option casemap:none .data ?_binary_constants_bin_start@@3PAEA: align 16 ?_binary_constants_bin_end@@3PAEA: align 16 public ?_binary_constants_bin_start@@3PAEA public ?_binary_constants_bin_end@@3PAEA end """ asm_ext = "asm" else: asm_code = f"\t.section\t{section_attr}\n" asm_code += f"\t.balign {align_bytes}\n" asm_code += ( f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n" ) asm_code += f"{symbol_prefix}_binary_constants_bin_start:\n" asm_code += f".globl\t{symbol_prefix}_binary_constants_bin_end\n" asm_code += f"{symbol_prefix}_binary_constants_bin_end:\n" asm_ext = "S" return asm_code, asm_ext
This function handles zero-sized constants because the C++ standard prohibits zero-length arrays: https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c On Windows (MSVC): The compiler reports error C2466 for zero-sized arrays: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2466 Solution: Use assembly compilation to handle this case. Why not use Win32 assembly for all paths? ml64 only supports alignment up to 16 bytes, which isn't optimal for performance. Cross-platform implementation: Linux: Added '-pedantic' to disable zero-sized arrays in C++ compiler Windows: MSVC naturally rejects zero-sized arrays by default
python
torch/_inductor/codecache.py
1,991
[ "align_bytes", "symbol_prefix" ]
tuple[str, str]
true
3
6.4
pytorch/pytorch
96,034
unknown
false
getRawType
private static Class<?> getRawType(final ParameterizedType parameterizedType) { final Type rawType = parameterizedType.getRawType(); // check if raw type is a Class object // not currently necessary, but since the return type is Type instead of // Class, there's enough reason to believe that future versions of Java // may return other Type implementations. And type-safety checking is // rarely a bad idea. if (!(rawType instanceof Class<?>)) { throw new IllegalStateException("Type of rawType: " + rawType); } return (Class<?>) rawType; }
Transforms the passed in type to a {@link Class} object. Type-checking method of convenience. @param parameterizedType the type to be converted. @return the corresponding {@link Class} object. @throws IllegalStateException if the conversion fails.
java
src/main/java/org/apache/commons/lang3/reflect/TypeUtils.java
689
[ "parameterizedType" ]
true
2
7.76
apache/commons-lang
2,896
javadoc
false
serializeReturnTypeOfNode
function serializeReturnTypeOfNode(node: Node): SerializedTypeNode { if (isFunctionLike(node) && node.type) { return serializeTypeNode(node.type); } else if (isAsyncFunction(node)) { return factory.createIdentifier("Promise"); } return factory.createVoidZero(); }
Serializes the return type of a node for use with decorator type metadata. @param node The node that should have its return type serialized.
typescript
src/compiler/transformers/typeSerializer.ts
242
[ "node" ]
true
5
7.04
microsoft/TypeScript
107,154
jsdoc
false
_tocomplex
def _tocomplex(arr): """Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- >>> import numpy as np First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) """ if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, nt.ushort, nt.csingle)): return arr.astype(nt.csingle) else: return arr.astype(nt.cdouble)
Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- >>> import numpy as np First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64)
python
numpy/lib/_scimath_impl.py
32
[ "arr" ]
false
3
7.52
numpy/numpy
31,054
numpy
false
handle
boolean handle(int code);
Handles the Ctrl event. @param code the code corresponding to the Ctrl sent. @return true if the handler processed the event, false otherwise. If false, the next handler will be called.
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/WindowsFunctions.java
82
[ "code" ]
true
1
6.8
elastic/elasticsearch
75,680
javadoc
false
next
@Override public String next() { if (hasNext()) { return tokens[tokenPos++]; } throw new NoSuchElementException(); }
Gets the next token. @return the next String token. @throws NoSuchElementException if there are no more elements.
java
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
630
[]
String
true
2
8.08
apache/commons-lang
2,896
javadoc
false
defaultElementEquals
private boolean defaultElementEquals(Elements e1, Elements e2, int i) { int l1 = e1.getLength(i); int l2 = e2.getLength(i); boolean indexed1 = e1.getType(i).isIndexed(); boolean indexed2 = e2.getType(i).isIndexed(); int i1 = 0; int i2 = 0; while (i1 < l1) { if (i2 >= l2) { return remainderIsNotAlphanumeric(e1, i, i1); } char ch1 = indexed1 ? e1.charAt(i, i1) : Character.toLowerCase(e1.charAt(i, i1)); char ch2 = indexed2 ? e2.charAt(i, i2) : Character.toLowerCase(e2.charAt(i, i2)); if (!indexed1 && !ElementsParser.isAlphaNumeric(ch1)) { i1++; } else if (!indexed2 && !ElementsParser.isAlphaNumeric(ch2)) { i2++; } else if (ch1 != ch2) { return false; } else { i1++; i2++; } } if (i2 < l2) { return remainderIsNotAlphanumeric(e2, i, i2); } return true; }
Returns {@code true} if this element is an ancestor (immediate or nested parent) of the specified name. @param name the name to check @return {@code true} if this name is an ancestor
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
464
[ "e1", "e2", "i" ]
true
11
8
spring-projects/spring-boot
79,428
javadoc
false
startOffset
public long startOffset() { return startOffset; }
Get the start offset for the share-partition. The start offset is the earliest offset for in-flight records being evaluated for delivery to share consumers. Some records after the start offset may already have completed delivery. @return The start offset of the partition read by the share group.
java
clients/src/main/java/org/apache/kafka/clients/admin/SharePartitionOffsetInfo.java
53
[]
true
1
6.96
apache/kafka
31,560
javadoc
false
get_temporary_credentials
def get_temporary_credentials(self, registry_ids: list[str] | str | None = None) -> list[EcrCredentials]: """ Get temporary credentials for Amazon ECR. .. seealso:: - :external+boto3:py:meth:`ECR.Client.get_authorization_token` :param registry_ids: Either AWS Account ID or list of AWS Account IDs that are associated with the registries from which credentials are obtained. If you do not specify a registry, the default registry is assumed. :return: list of :class:`airflow.providers.amazon.aws.hooks.ecr.EcrCredentials`, obtained credentials valid for 12 hours. """ registry_ids = registry_ids or None if isinstance(registry_ids, str): registry_ids = [registry_ids] if registry_ids: response = self.conn.get_authorization_token(registryIds=registry_ids) else: response = self.conn.get_authorization_token() creds = [] for auth_data in response["authorizationData"]: username, password = base64.b64decode(auth_data["authorizationToken"]).decode("utf-8").split(":") creds.append( EcrCredentials( username=username, password=password, proxy_endpoint=auth_data["proxyEndpoint"], expires_at=auth_data["expiresAt"], ) ) return creds
Get temporary credentials for Amazon ECR. .. seealso:: - :external+boto3:py:meth:`ECR.Client.get_authorization_token` :param registry_ids: Either AWS Account ID or list of AWS Account IDs that are associated with the registries from which credentials are obtained. If you do not specify a registry, the default registry is assumed. :return: list of :class:`airflow.providers.amazon.aws.hooks.ecr.EcrCredentials`, obtained credentials valid for 12 hours.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/ecr.py
81
[ "self", "registry_ids" ]
list[EcrCredentials]
true
6
7.44
apache/airflow
43,597
sphinx
false
addBeanWithType
private static <B, T> void addBeanWithType(FormatterRegistry registry, B bean, ResolvableType beanType, Class<T> type, Consumer<B> standardRegistrar, BiFunction<B, ResolvableType, BeanAdapter<?>> beanAdapterFactory) { addBean(registry, bean, beanType, type, standardRegistrar, () -> registry.addConverter(beanAdapterFactory.apply(bean, beanType))); }
Add {@link Printer}, {@link Parser}, {@link Formatter}, {@link Converter}, {@link ConverterFactory}, {@link GenericConverter}, and beans from the specified bean factory. @param registry the service to register beans with @param beanFactory the bean factory to get the beans from @param qualifier the qualifier required on the beans or {@code null} @return the beans that were added @since 3.5.0
java
core/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java
382
[ "registry", "bean", "beanType", "type", "standardRegistrar", "beanAdapterFactory" ]
void
true
1
6.56
spring-projects/spring-boot
79,428
javadoc
false
reScanHashToken
function reScanHashToken(): SyntaxKind { if (token === SyntaxKind.PrivateIdentifier) { pos = tokenStart + 1; return token = SyntaxKind.HashToken; } return token; }
Unconditionally back up and scan a template expression portion.
typescript
src/compiler/scanner.ts
3,681
[]
true
2
6.4
microsoft/TypeScript
107,154
jsdoc
false
nul
@SuppressWarnings("unchecked") static <T, E extends Exception> FailableSupplier<T, E> nul() { return NUL; }
Gets the singleton supplier that always returns null. <p> This supplier never throws an exception. </p> @param <T> Supplied type. @param <E> The kind of thrown exception or error. @return The NUL singleton. @since 3.14.0
java
src/main/java/org/apache/commons/lang3/function/FailableSupplier.java
54
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
getFallback
private @Nullable MessageInterpolator getFallback() { for (String fallback : FALLBACKS) { try { return getFallback(fallback); } catch (Exception ex) { // Swallow and continue } } return null; }
Creates a new {@link MessageInterpolatorFactory} that will produce a {@link MessageInterpolator} that uses the given {@code messageSource} to resolve any message parameters before final interpolation. @param messageSource message source to be used by the interpolator @since 2.6.0
java
core/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java
91
[]
MessageInterpolator
true
2
6.4
spring-projects/spring-boot
79,428
javadoc
false
get
def get(self, key: str) -> Hit[bytes] | None: """Retrieve a value from the on-disk cache. Args: key: The key to look up in the cache (must be str). Returns: A Hit object on cache hit where Hit.value is the cached value (bytes), or None on cache miss or version mismatch. """ fpath: Path = self._fpath_from_key(key) if not fpath.is_file(): return None pickled_value: bytes | None = None with open(fpath, "rb") as fp: if self._version_header_matches(fp): pickled_value = fp.read() if not pickled_value: # if pickled_value is still None, even though the file exists, then # we know that the version header did not match. in this case implementation # is up to preference, we choose to remove entries that do not match # the version header so that the key can be re-cached later with the correct # version header fpath.unlink() return None return Hit(value=pickled_value)
Retrieve a value from the on-disk cache. Args: key: The key to look up in the cache (must be str). Returns: A Hit object on cache hit where Hit.value is the cached value (bytes), or None on cache miss or version mismatch.
python
torch/_inductor/runtime/caching/implementations.py
272
[ "self", "key" ]
Hit[bytes] | None
true
4
7.92
pytorch/pytorch
96,034
google
false
toShort
public static short toShort(final String str) { return toShort(str, (short) 0); }
Converts a {@link String} to a {@code short}, returning {@code zero} if the conversion fails. <p> If the string is {@code null}, {@code zero} is returned. </p> <pre> NumberUtils.toShort(null) = 0 NumberUtils.toShort("") = 0 NumberUtils.toShort("1") = 1 </pre> @param str the string to convert, may be null. @return the short represented by the string, or {@code zero} if conversion fails. @since 2.5
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
1,766
[ "str" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
foundExactly
public ConditionMessage foundExactly(Object result) { return found("").items(result); }
Indicate that an exact result was found. For example {@code foundExactly("foo")} results in the message "found foo". @param result the result that was found @return a built {@link ConditionMessage}
java
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionMessage.java
216
[ "result" ]
ConditionMessage
true
1
6.48
spring-projects/spring-boot
79,428
javadoc
false
fftshift
def fftshift(x, axes=None): """ Shift the zero-frequency component to the center of the spectrum. This function swaps half-spaces for all axes listed (defaults to all). Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to shift. Default is None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- ifftshift : The inverse of `fftshift`. Examples -------- >>> import numpy as np >>> freqs = np.fft.fftfreq(10, 0.1) >>> freqs array([ 0., 1., 2., ..., -3., -2., -1.]) >>> np.fft.fftshift(freqs) array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) Shift the zero-frequency component only along the second axis: >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.fftshift(freqs, axes=(1,)) array([[ 2., 0., 1.], [-4., 3., 4.], [-1., -3., -2.]]) """ x = asarray(x) if axes is None: axes = tuple(range(x.ndim)) shift = [dim // 2 for dim in x.shape] elif isinstance(axes, integer_types): shift = x.shape[axes] // 2 else: shift = [x.shape[ax] // 2 for ax in axes] return roll(x, shift, axes)
Shift the zero-frequency component to the center of the spectrum. This function swaps half-spaces for all axes listed (defaults to all). Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to shift. Default is None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- ifftshift : The inverse of `fftshift`. Examples -------- >>> import numpy as np >>> freqs = np.fft.fftfreq(10, 0.1) >>> freqs array([ 0., 1., 2., ..., -3., -2., -1.]) >>> np.fft.fftshift(freqs) array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) Shift the zero-frequency component only along the second axis: >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.fftshift(freqs, axes=(1,)) array([[ 2., 0., 1.], [-4., 3., 4.], [-1., -3., -2.]])
python
numpy/fft/_helper.py
20
[ "x", "axes" ]
false
4
7.68
numpy/numpy
31,054
numpy
false
getJSONArray
public JSONArray getJSONArray(int index) throws JSONException { Object object = get(index); if (object instanceof JSONArray) { return (JSONArray) object; } else { throw JSON.typeMismatch(index, object, "JSONArray"); } }
Returns the value at {@code index} if it exists and is a {@code JSONArray}. @param index the index to get the value from @return the array at {@code index} @throws JSONException if the value doesn't exist or is not a {@code JSONArray}.
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java
524
[ "index" ]
JSONArray
true
2
7.92
spring-projects/spring-boot
79,428
javadoc
false
onEmitNode
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void { const savedApplicableSubstitutions = applicableSubstitutions; const savedCurrentSourceFile = currentSourceFile; if (isSourceFile(node)) { currentSourceFile = node; } if (enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= TypeScriptSubstitutionFlags.NamespaceExports; } if (enabledSubstitutions & TypeScriptSubstitutionFlags.NonQualifiedEnumMembers && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= TypeScriptSubstitutionFlags.NonQualifiedEnumMembers; } previousOnEmitNode(hint, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSourceFile = savedCurrentSourceFile; }
Hook for node emit. @param hint A hint as to the intended usage of the node. @param node The node to emit. @param emit A callback used to emit the node in the printer.
typescript
src/compiler/transformers/ts.ts
2,609
[ "hint", "node", "emitCallback" ]
true
6
6.56
microsoft/TypeScript
107,154
jsdoc
false
onSuccessResponse
private void onSuccessResponse(final StreamsGroupHeartbeatResponse response, final long currentTimeMs) { final StreamsGroupHeartbeatResponseData data = response.data(); heartbeatRequestState.updateHeartbeatIntervalMs(data.heartbeatIntervalMs()); heartbeatRequestState.onSuccessfulAttempt(currentTimeMs); heartbeatState.setEndpointInformationEpoch(data.endpointInformationEpoch()); streamsRebalanceData.setHeartbeatIntervalMs(data.heartbeatIntervalMs()); if (data.partitionsByUserEndpoint() != null) { streamsRebalanceData.setPartitionsByHost(convertHostInfoMap(data)); } List<StreamsGroupHeartbeatResponseData.Status> statuses = data.status(); if (statuses != null) { streamsRebalanceData.setStatuses(statuses); if (!statuses.isEmpty()) { String statusDetails = statuses.stream() .map(status -> "(" + status.statusCode() + ") " + status.statusDetail()) .collect(Collectors.joining(", ")); logger.warn("Membership is in the following statuses: {}", statusDetails); } } membershipManager.onHeartbeatSuccess(response); }
A heartbeat should be sent without waiting for the heartbeat interval to expire if: - the member is leaving the group or - the member is joining the group or acknowledging the assignment and for both cases there is no heartbeat request in flight. @return true if a heartbeat should be sent before the interval expires, false otherwise
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
527
[ "response", "currentTimeMs" ]
void
true
4
6.56
apache/kafka
31,560
javadoc
false
instantiateClass
public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException { Assert.notNull(clazz, "Class must not be null"); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } Constructor<T> ctor; try { ctor = clazz.getDeclaredConstructor(); } catch (NoSuchMethodException ex) { ctor = findPrimaryConstructor(clazz); if (ctor == null) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } catch (LinkageError err) { throw new BeanInstantiationException(clazz, "Unresolvable class definition", err); } return instantiateClass(ctor); }
Instantiate a class using its 'primary' constructor (for Kotlin classes, potentially having default arguments declared) or its default constructor (for regular Java classes, expecting a standard no-arg setup). <p>Note that this method tries to set the constructor accessible if given a non-accessible (that is, non-public) constructor. @param clazz the class to instantiate @return the new instance @throws BeanInstantiationException if the bean cannot be instantiated. The cause may notably indicate a {@link NoSuchMethodException} if no primary/default constructor was found, a {@link NoClassDefFoundError} or other {@link LinkageError} in case of an unresolvable class definition (for example, due to a missing dependency at runtime), or an exception thrown from the constructor invocation itself. @see Constructor#newInstance
java
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
131
[ "clazz" ]
T
true
5
7.44
spring-projects/spring-framework
59,386
javadoc
false
isMixedCase
public static boolean isMixedCase(final CharSequence cs) { if (isEmpty(cs) || cs.length() == 1) { return false; } boolean containsUppercase = false; boolean containsLowercase = false; final int sz = cs.length(); for (int i = 0; i < sz; i++) { final char nowChar = cs.charAt(i); if (Character.isUpperCase(nowChar)) { containsUppercase = true; } else if (Character.isLowerCase(nowChar)) { containsLowercase = true; } if (containsUppercase && containsLowercase) { return true; } } return false; }
Tests if the CharSequence contains mixed casing of both uppercase and lowercase characters. <p> {@code null} will return {@code false}. An empty CharSequence ({@code length()=0}) will return {@code false}. </p> <pre> StringUtils.isMixedCase(null) = false StringUtils.isMixedCase("") = false StringUtils.isMixedCase(" ") = false StringUtils.isMixedCase("ABC") = false StringUtils.isMixedCase("abc") = false StringUtils.isMixedCase("aBc") = true StringUtils.isMixedCase("A c") = true StringUtils.isMixedCase("A1c") = true StringUtils.isMixedCase("a/C") = true StringUtils.isMixedCase("aC\t") = true </pre> @param cs the CharSequence to check, may be null. @return {@code true} if the CharSequence contains both uppercase and lowercase characters. @since 3.5
java
src/main/java/org/apache/commons/lang3/StringUtils.java
3,564
[ "cs" ]
true
8
7.6
apache/commons-lang
2,896
javadoc
false
estimateRank
public static long estimateRank(ExponentialHistogram histo, double value, boolean inclusive) { if (Double.isNaN(histo.min()) || value < histo.min()) { return 0; } if (value > histo.max()) { return histo.valueCount(); } if (value >= 0) { long rank = histo.negativeBuckets().valueCount(); if (value > 0 || inclusive) { rank += histo.zeroBucket().count(); } rank += estimateRank(histo.positiveBuckets().iterator(), value, inclusive, histo.max()); return rank; } else { long numValuesGreater = estimateRank(histo.negativeBuckets().iterator(), -value, inclusive == false, -histo.min()); return histo.negativeBuckets().valueCount() - numValuesGreater; } }
Estimates the rank of a given value in the distribution represented by the histogram. In other words, returns the number of values which are less than (or less-or-equal, if {@code inclusive} is true) the provided value. @param histo the histogram to query @param value the value to estimate the rank for @param inclusive if true, counts values equal to the given value as well @return the number of elements less than (or less-or-equal, if {@code inclusive} is true) the given value
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramQuantile.java
88
[ "histo", "value", "inclusive" ]
true
7
8.08
elastic/elasticsearch
75,680
javadoc
false
period_range
def period_range( start=None, end=None, periods: int | None = None, freq=None, name: Hashable | None = None, ) -> PeriodIndex: """ Return a fixed frequency PeriodIndex. The day (calendar) is the default frequency. Parameters ---------- start : str, datetime, date, pandas.Timestamp, or period-like, default None Left bound for generating periods. end : str, datetime, date, pandas.Timestamp, or period-like, default None Right bound for generating periods. periods : int, default None Number of periods to generate. freq : str or DateOffset, optional Frequency alias. By default the freq is taken from `start` or `end` if those are Period objects. Otherwise, the default is ``"D"`` for daily frequency. name : str, default None Name of the resulting PeriodIndex. Returns ------- PeriodIndex A PeriodIndex of fixed frequency periods. See Also -------- date_range : Returns a fixed frequency DatetimeIndex. Period : Represents a period of time. PeriodIndex : Immutable ndarray holding ordinal values indicating regular periods in time. Notes ----- Of the three parameters: ``start``, ``end``, and ``periods``, exactly two must be specified. To learn more about the frequency strings, please see :ref:`this link<timeseries.offset_aliases>`. Examples -------- >>> pd.period_range(start="2017-01-01", end="2018-01-01", freq="M") PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12', '2018-01'], dtype='period[M]') If ``start`` or ``end`` are ``Period`` objects, they will be used as anchor endpoints for a ``PeriodIndex`` with frequency matching that of the ``period_range`` constructor. >>> pd.period_range( ... start=pd.Period("2017Q1", freq="Q"), ... end=pd.Period("2017Q2", freq="Q"), ... freq="M", ... ) PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'], dtype='period[M]') """ if com.count_not_none(start, end, periods) != 2: raise ValueError( "Of the three parameters: start, end, and periods, " "exactly two must be specified" ) if freq is None and (not isinstance(start, Period) and not isinstance(end, Period)): freq = "D" data, freq = PeriodArray._generate_range(start, end, periods, freq) dtype = PeriodDtype(freq) data = PeriodArray(data, dtype=dtype) return PeriodIndex(data, name=name)
Return a fixed frequency PeriodIndex. The day (calendar) is the default frequency. Parameters ---------- start : str, datetime, date, pandas.Timestamp, or period-like, default None Left bound for generating periods. end : str, datetime, date, pandas.Timestamp, or period-like, default None Right bound for generating periods. periods : int, default None Number of periods to generate. freq : str or DateOffset, optional Frequency alias. By default the freq is taken from `start` or `end` if those are Period objects. Otherwise, the default is ``"D"`` for daily frequency. name : str, default None Name of the resulting PeriodIndex. Returns ------- PeriodIndex A PeriodIndex of fixed frequency periods. See Also -------- date_range : Returns a fixed frequency DatetimeIndex. Period : Represents a period of time. PeriodIndex : Immutable ndarray holding ordinal values indicating regular periods in time. Notes ----- Of the three parameters: ``start``, ``end``, and ``periods``, exactly two must be specified. To learn more about the frequency strings, please see :ref:`this link<timeseries.offset_aliases>`. Examples -------- >>> pd.period_range(start="2017-01-01", end="2018-01-01", freq="M") PeriodIndex(['2017-01', '2017-02', '2017-03', '2017-04', '2017-05', '2017-06', '2017-07', '2017-08', '2017-09', '2017-10', '2017-11', '2017-12', '2018-01'], dtype='period[M]') If ``start`` or ``end`` are ``Period`` objects, they will be used as anchor endpoints for a ``PeriodIndex`` with frequency matching that of the ``period_range`` constructor. >>> pd.period_range( ... start=pd.Period("2017Q1", freq="Q"), ... end=pd.Period("2017Q2", freq="Q"), ... freq="M", ... ) PeriodIndex(['2017-03', '2017-04', '2017-05', '2017-06'], dtype='period[M]')
python
pandas/core/indexes/period.py
550
[ "start", "end", "periods", "freq", "name" ]
PeriodIndex
true
5
7.76
pandas-dev/pandas
47,362
numpy
false
getComment
@Override public String getComment() { synchronized (this) { ensureOpen(); return this.resources.zipContent().getComment(); } }
Return if an entry with the given name exists. @param name the name to check @return if the entry exists
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/jar/NestedJarFile.java
374
[]
String
true
1
6.88
spring-projects/spring-boot
79,428
javadoc
false
parse
@Override public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { final ListIterator<StrategyAndWidth> lt = patterns.listIterator(); while (lt.hasNext()) { final StrategyAndWidth strategyAndWidth = lt.next(); final int maxWidth = strategyAndWidth.getMaxWidth(lt); if (!strategyAndWidth.strategy.parse(this, calendar, source, pos, maxWidth)) { return false; } } return true; }
Parses a formatted date string according to the format. Updates the Calendar with parsed fields. Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed. Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to the offset of the source text which does not match the supplied format. @param source The text to parse. @param pos On input, the position in the source to start parsing, on output, updated position. @param calendar The calendar into which to set parsed fields. @return true, if source has been parsed (pos parsePosition is updated); otherwise false (and pos errorIndex is updated) @throws IllegalArgumentException when Calendar has been set to be not lenient, and a parsed field is out of range.
java
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
1,062
[ "source", "pos", "calendar" ]
true
3
8.08
apache/commons-lang
2,896
javadoc
false
run
async function run(cwd: string, cmd: string, dry = false, hidden = false): Promise<void> { const args = [underline('./' + cwd).padEnd(20), bold(cmd)] if (dry) { args.push(dim('(dry)')) } if (!hidden) { console.log(...args) } if (dry) { return } try { await execaCommand(cmd, { cwd, stdio: 'inherit', shell: true, env: { ...process.env, }, }) } catch (_e) { const e = _e as ExecaError throw new Error(red(`Error running ${bold(cmd)} in ${underline(cwd)}:`) + (e.stderr || e.stack || e.message)) } }
Runs a command and pipes the stdout & stderr to the current process. @param cwd cwd for running the command @param cmd command to run
typescript
scripts/ci/publish.ts
54
[ "cwd", "cmd", "dry", "hidden" ]
true
7
6.56
prisma/prisma
44,834
jsdoc
true
store
@Override public void store(OutputStream out, String comments) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); super.store(baos, (this.omitComments ? null : comments)); String contents = baos.toString(StandardCharsets.ISO_8859_1); for (String line : contents.split(EOL)) { if (!(this.omitComments && line.startsWith("#"))) { out.write((line + EOL).getBytes(StandardCharsets.ISO_8859_1)); } } }
Construct a new {@code SortedProperties} instance with properties populated from the supplied {@link Properties} object and honoring the supplied {@code omitComments} flag. <p>Default properties from the supplied {@code Properties} object will not be copied. @param properties the {@code Properties} object from which to copy the initial properties @param omitComments {@code true} if comments should be omitted when storing properties in a file
java
spring-context-indexer/src/main/java/org/springframework/context/index/processor/SortedProperties.java
87
[ "out", "comments" ]
void
true
4
6.08
spring-projects/spring-framework
59,386
javadoc
false
invokeExactStaticMethod
public static Object invokeExactStaticMethod(final Class<?> cls, final String methodName, final Object[] args, final Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { final Class<?>[] paramTypes = ArrayUtils.nullToEmpty(parameterTypes); final Method method = getAccessibleMethod(cls, methodName, ArrayUtils.nullToEmpty(paramTypes)); requireNonNull(method, cls, methodName, paramTypes); return method.invoke(null, ArrayUtils.nullToEmpty(args)); }
Invokes a {@code static} method whose parameter types match exactly the parameter types given. <p> This uses reflection to invoke the method obtained from a call to {@link #getAccessibleMethod(Class, String, Class[])}. </p> @param cls invoke static method on this class. @param methodName get method with this name. @param args use these arguments - treat {@code null} as empty array. @param parameterTypes match these parameters - treat {@code null} as empty array. @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 ExceptionInInitializerError Thrown if the initialization provoked by this method fails.
java
src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
693
[ "cls", "methodName", "args", "parameterTypes" ]
Object
true
1
6.24
apache/commons-lang
2,896
javadoc
false
toList
public static List<Uuid> toList(Uuid[] array) { if (array == null) return null; List<Uuid> list = new ArrayList<>(array.length); list.addAll(Arrays.asList(array)); return list; }
Convert an array of Uuids to a list of Uuid. @param array The input array @return The output list
java
clients/src/main/java/org/apache/kafka/common/Uuid.java
190
[ "array" ]
true
2
7.76
apache/kafka
31,560
javadoc
false
previous
public abstract @Nullable C previous(C value);
Returns the unique greatest value of type {@code C} that is less than {@code value}, or {@code null} if none exists. Inverse operation to {@link #next}. @param value any value of type {@code C} @return the greatest value less than {@code value}, or {@code null} if {@code value} is {@code minValue()}
java
android/guava/src/com/google/common/collect/DiscreteDomain.java
294
[ "value" ]
C
true
1
6.48
google/guava
51,352
javadoc
false
readCertificates
private static void readCertificates(String text, CertificateFactory factory, Consumer<X509Certificate> consumer) { try { Matcher matcher = PATTERN.matcher(text); while (matcher.find()) { String encodedText = matcher.group(1); byte[] decodedBytes = decodeBase64(encodedText); ByteArrayInputStream inputStream = new ByteArrayInputStream(decodedBytes); while (inputStream.available() > 0) { consumer.accept((X509Certificate) factory.generateCertificate(inputStream)); } } } catch (CertificateException ex) { throw new IllegalStateException("Error reading certificate: " + ex.getMessage(), ex); } }
Parse certificates from the specified string. @param text the text to parse @return the parsed certificates
java
core/spring-boot/src/main/java/org/springframework/boot/ssl/pem/PemCertificateParser.java
81
[ "text", "factory", "consumer" ]
void
true
4
8.24
spring-projects/spring-boot
79,428
javadoc
false
visitImportEqualsDeclaration
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement | undefined> { // Always elide type-only imports if (node.isTypeOnly) { return undefined; } if (isExternalModuleImportEqualsDeclaration(node)) { if (!shouldEmitAliasDeclaration(node)) { return undefined; } return visitEachChild(node, visitor, context); } if (!shouldEmitImportEqualsDeclaration(node)) { return undefined; } const moduleReference = createExpressionFromEntityName(factory, node.moduleReference as EntityName); setEmitFlags(moduleReference, EmitFlags.NoComments | EmitFlags.NoNestedComments); if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; return setOriginalNode( setTextRange( factory.createVariableStatement( visitNodes(node.modifiers, modifierVisitor, isModifier), factory.createVariableDeclarationList([ setOriginalNode( factory.createVariableDeclaration( node.name, /*exclamationToken*/ undefined, /*type*/ undefined, moduleReference, ), node, ), ]), ), node, ), node, ); } else { // exports.${name} = ${moduleReference}; return setOriginalNode( createNamespaceExport( node.name, moduleReference, node, ), node, ); } }
Visits an import equals declaration. @param node The import equals declaration node.
typescript
src/compiler/transformers/ts.ts
2,425
[ "node" ]
true
8
6.16
microsoft/TypeScript
107,154
jsdoc
false