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
getStackFrames
public static String[] getStackFrames(final Throwable throwable) { if (throwable == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } return getStackFrames(getStackTrace(throwable)); }
Gets the stack trace associated with the specified {@link Throwable} object, decomposing it into a list of stack frames. <p> The result of this method vary by JDK version as this method uses {@link Throwable#printStackTrace(java.io.PrintWriter)}. </p> @param throwable the {@link Throwable} to examine, may be null. @return an array of strings describing each stack frame, never null.
java
src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
446
[ "throwable" ]
true
2
7.92
apache/commons-lang
2,896
javadoc
false
get_table_primary_key
def get_table_primary_key(self, table: str, schema: str | None = "public") -> list[str] | None: """ Get the table's primary key. :param table: Name of the target table :param schema: Name of the target schema, public by default :return: Primary key columns list """ sql = """ select kcu.column_name from information_schema.table_constraints tco join information_schema.key_column_usage kcu on kcu.constraint_name = tco.constraint_name and kcu.constraint_schema = tco.constraint_schema and kcu.constraint_name = tco.constraint_name where tco.constraint_type = 'PRIMARY KEY' and kcu.table_schema = %s and kcu.table_name = %s """ pk_columns = [row[0] for row in self.get_records(sql, (schema, table))] return pk_columns or None
Get the table's primary key. :param table: Name of the target table :param schema: Name of the target schema, public by default :return: Primary key columns list
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/redshift_sql.py
188
[ "self", "table", "schema" ]
list[str] | None
true
2
8.24
apache/airflow
43,597
sphinx
false
asCallable
public static <V> Callable<V> asCallable(final FailableCallable<V, ?> callable) { return () -> call(callable); }
Converts the given {@link FailableCallable} into a standard {@link Callable}. @param <V> the type used by the callables @param callable a {@link FailableCallable} @return a standard {@link Callable}
java
src/main/java/org/apache/commons/lang3/function/Failable.java
328
[ "callable" ]
true
1
6.16
apache/commons-lang
2,896
javadoc
false
toString
@Override public String toString() { if (isEmpty()) { return "[]"; } StringBuilder builder = new StringBuilder(length() * 5); // rough estimate is fine builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } builder.append(']'); return builder.toString(); }
Returns a string representation of this array in the same form as {@link Arrays#toString(double[])}, for example {@code "[1, 2, 3]"}.
java
android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
621
[]
String
true
3
6.56
google/guava
51,352
javadoc
false
hasGetterOrIsProxy
function hasGetterOrIsProxy(obj, astProp, cb) { if (!obj || !astProp) { return cb(false); } if (astProp.type === 'Literal') { // We have something like `obj['foo'].x` where `x` is the literal return propHasGetterOrIsProxy(obj, astProp.value, cb); } if ( astProp.type === 'Identifier' && exprStr.at(astProp.start - 1) === '.' ) { // We have something like `obj.foo.x` where `foo` is the identifier return propHasGetterOrIsProxy(obj, astProp.name, cb); } return evalFn( // Note: this eval runs the property expression, which might be side-effectful, for example // the user could be running `obj[getKey()].` where `getKey()` has some side effects. // Arguably this behavior should not be too surprising, but if it turns out that it is, // then we can revisit this behavior and add logic to analyze the property expression // and eval it only if we can confidently say that it can't have any side effects `try { ${exprStr.slice(astProp.start, astProp.end)} } catch {} `, ctx, getREPLResourceName(), (err, evaledProp) => { if (err) { return cb(false); } if (typeof evaledProp === 'string') { return propHasGetterOrIsProxy(obj, evaledProp, cb); } return cb(false); }, ); }
Utility to see if a property has a getter associated to it or if the property itself is a proxy object. @returns {void}
javascript
lib/internal/repl/completion.js
727
[ "obj", "astProp", "cb" ]
false
8
6.24
nodejs/node
114,839
jsdoc
false
min
public static <A extends Comparable<A>> A min(final A comparable1, final A comparable2) { return ObjectUtils.compare(comparable1, comparable2, true) < 0 ? comparable1 : comparable2; }
Returns the lesser of two {@link Comparable} values, ignoring null. <p> For three or more values, use {@link ObjectUtils#min(Comparable...)}. </p> @param <A> Type of what we are comparing. @param comparable1 the first comparable, may be null. @param comparable2 the second comparable, may be null. @return the smallest of {@code comparable1} and {@code comparable2}. @see ObjectUtils#min(Comparable...) @since 3.13.0
java
src/main/java/org/apache/commons/lang3/compare/ComparableUtils.java
239
[ "comparable1", "comparable2" ]
A
true
2
7.52
apache/commons-lang
2,896
javadoc
false
_memory_usage
def _memory_usage(self, deep: bool = False) -> int: """ Memory usage of the values. Parameters ---------- deep : bool, default False Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption. Returns ------- bytes used Returns memory usage of the values in the Index in bytes. See Also -------- numpy.ndarray.nbytes : Total bytes consumed by the elements of the array. Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False or if used on PyPy Examples -------- >>> idx = pd.Index([1, 2, 3]) >>> idx.memory_usage() 24 """ if hasattr(self.array, "memory_usage"): return self.array.memory_usage( # pyright: ignore[reportAttributeAccessIssue] deep=deep, ) v = self.array.nbytes if deep and is_object_dtype(self.dtype) and not PYPY: values = cast(np.ndarray, self._values) v += lib.memory_usage_of_objects(values) return v
Memory usage of the values. Parameters ---------- deep : bool, default False Introspect the data deeply, interrogate `object` dtypes for system-level memory consumption. Returns ------- bytes used Returns memory usage of the values in the Index in bytes. See Also -------- numpy.ndarray.nbytes : Total bytes consumed by the elements of the array. Notes ----- Memory usage does not include memory consumed by elements that are not components of the array if deep=False or if used on PyPy Examples -------- >>> idx = pd.Index([1, 2, 3]) >>> idx.memory_usage() 24
python
pandas/core/base.py
1,238
[ "self", "deep" ]
int
true
5
8.32
pandas-dev/pandas
47,362
numpy
false
findEligibleAdvisors
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) { List<Advisor> candidateAdvisors = findCandidateAdvisors(); List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); extendAdvisors(eligibleAdvisors); if (!eligibleAdvisors.isEmpty()) { try { eligibleAdvisors = sortAdvisors(eligibleAdvisors); } catch (BeanCreationException ex) { throw new AopConfigException("Advisor sorting failed with unexpected bean creation, probably due " + "to custom use of the Ordered interface. Consider using the @Order annotation instead.", ex); } } return eligibleAdvisors; }
Find all eligible Advisors for auto-proxying this class. @param beanClass the clazz to find advisors for @param beanName the name of the currently proxied bean @return the empty List, not {@code null}, if there are no pointcuts or interceptors @see #findCandidateAdvisors @see #sortAdvisors @see #extendAdvisors
java
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java
96
[ "beanClass", "beanName" ]
true
3
7.6
spring-projects/spring-framework
59,386
javadoc
false
_construct_result
def _construct_result( self, result: ArrayLike | tuple[ArrayLike, ArrayLike], name: Hashable, other: AnyArrayLike | DataFrame, ) -> Series | tuple[Series, Series]: """ Construct an appropriately-labelled Series from the result of an op. Parameters ---------- result : ndarray or ExtensionArray name : Label other : Series, DataFrame or array-like Returns ------- Series In the case of __divmod__ or __rdivmod__, a 2-tuple of Series. """ if isinstance(result, tuple): # produced by divmod or rdivmod res1 = self._construct_result(result[0], name=name, other=other) res2 = self._construct_result(result[1], name=name, other=other) # GH#33427 assertions to keep mypy happy assert isinstance(res1, Series) assert isinstance(res2, Series) return (res1, res2) # TODO: result should always be ArrayLike, but this fails for some # JSONArray tests dtype = getattr(result, "dtype", None) out = self._constructor(result, index=self.index, dtype=dtype, copy=False) out = out.__finalize__(self) out = out.__finalize__(other) # Set the result's name after __finalize__ is called because __finalize__ # would set it back to self.name out.name = name return out
Construct an appropriately-labelled Series from the result of an op. Parameters ---------- result : ndarray or ExtensionArray name : Label other : Series, DataFrame or array-like Returns ------- Series In the case of __divmod__ or __rdivmod__, a 2-tuple of Series.
python
pandas/core/series.py
6,739
[ "self", "result", "name", "other" ]
Series | tuple[Series, Series]
true
2
6.56
pandas-dev/pandas
47,362
numpy
false
equalsAny
@Deprecated public static boolean equalsAny(final CharSequence string, final CharSequence... searchStrings) { return Strings.CS.equalsAny(string, searchStrings); }
Compares given {@code string} to a CharSequences vararg of {@code searchStrings}, returning {@code true} if the {@code string} is equal to any of the {@code searchStrings}. <pre> StringUtils.equalsAny(null, (CharSequence[]) null) = false StringUtils.equalsAny(null, null, null) = true StringUtils.equalsAny(null, "abc", "def") = false StringUtils.equalsAny("abc", null, "def") = false StringUtils.equalsAny("abc", "abc", "def") = true StringUtils.equalsAny("abc", "ABC", "DEF") = false </pre> @param string to compare, may be {@code null}. @param searchStrings a vararg of strings, may be {@code null}. @return {@code true} if the string is equal (case-sensitive) to any other element of {@code searchStrings}; {@code false} if {@code searchStrings} is null or contains no matches. @since 3.5 @deprecated Use {@link Strings#equalsAny(CharSequence, CharSequence...) Strings.CS.equalsAny(CharSequence, CharSequence...)}.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
1,812
[ "string" ]
true
1
6.48
apache/commons-lang
2,896
javadoc
false
connectionFailed
@Override public boolean connectionFailed(Node node) { return connectionStates.isDisconnected(node.idString()); }
Check if the connection of the node has failed, based on the connection state. Such connection failure are usually transient and can be resumed in the next {@link #ready(org.apache.kafka.common.Node, long)} } call, but there are cases where transient failures needs to be caught and re-acted upon. @param node the node to check @return true iff the connection has failed and the node is disconnected
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
493
[ "node" ]
true
1
6.96
apache/kafka
31,560
javadoc
false
toStream
public Stream<String> toStream() { return StreamSupport.stream(spliterator(), false); }
Returns a sequential stream on this Iterable instance. @return a sequential stream on this Iterable instance.
java
src/main/java/org/apache/commons/lang3/util/IterableStringTokenizer.java
111
[]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
of
public static LevelConfiguration of(LogLevel logLevel) { Assert.notNull(logLevel, "'logLevel' must not be null"); return new LevelConfiguration(logLevel.name(), logLevel); }
Create a new {@link LevelConfiguration} instance of the given {@link LogLevel}. @param logLevel the log level @return a new {@link LevelConfiguration} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/LoggerConfiguration.java
236
[ "logLevel" ]
LevelConfiguration
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
getProperty
private @Nullable String getProperty(SpringApplicationEvent event, List<Property> candidates) { for (Property candidate : candidates) { String value = candidate.getValue(event); if (value != null) { return value; } } return null; }
Sets the type of application event that will trigger writing of the PID file. Defaults to {@link ApplicationPreparedEvent}. NOTE: If you use the {@link org.springframework.boot.context.event.ApplicationStartingEvent} to trigger the write, you will not be able to specify the PID filename in the Spring {@link Environment}. @param triggerEventType the trigger event type
java
core/spring-boot/src/main/java/org/springframework/boot/context/ApplicationPidFileWriter.java
167
[ "event", "candidates" ]
String
true
2
6.4
spring-projects/spring-boot
79,428
javadoc
false
setSafeRange
@CanIgnoreReturnValue public Builder setSafeRange(char safeMin, char safeMax) { this.safeMin = safeMin; this.safeMax = safeMax; return this; }
Sets the safe range of characters for the escaper. Characters in this range that have no explicit replacement are considered 'safe' and remain unescaped in the output. If {@code safeMax < safeMin} then the safe range is empty. @param safeMin the lowest 'safe' character @param safeMax the highest 'safe' character @return the builder instance
java
android/guava/src/com/google/common/escape/Escapers.java
109
[ "safeMin", "safeMax" ]
Builder
true
1
6.88
google/guava
51,352
javadoc
false
clone
public static double[] clone(final double[] array) { return array != null ? array.clone() : null; }
Clones an array or returns {@code null}. <p> This method returns {@code null} for a {@code null} input array. </p> @param array the array to clone, may be {@code null}. @return the cloned array, {@code null} if {@code null} input.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
1,492
[ "array" ]
true
2
8.16
apache/commons-lang
2,896
javadoc
false
get
@ParametricNullness public static <T extends @Nullable Object> T get( Iterator<? extends T> iterator, int position, @ParametricNullness T defaultValue) { checkNonnegative(position); advance(iterator, position); return getNext(iterator, defaultValue); }
Advances {@code iterator} {@code position + 1} times, returning the element at the {@code position}th position or {@code defaultValue} otherwise. @param position position of the element to return @param defaultValue the default value to return if the iterator is empty or if {@code position} is greater than the number of elements remaining in {@code iterator} @return the element at the specified position in {@code iterator} or {@code defaultValue} if {@code iterator} produces fewer than {@code position + 1} elements. @throws IndexOutOfBoundsException if {@code position} is negative @since 4.0
java
android/guava/src/com/google/common/collect/Iterators.java
869
[ "iterator", "position", "defaultValue" ]
T
true
1
6.56
google/guava
51,352
javadoc
false
keySet
@Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; }
Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most once on a given map, at the time when {@code entrySet} is first called.
java
android/guava/src/com/google/common/collect/Maps.java
3,531
[]
true
2
6.72
google/guava
51,352
javadoc
false
initializeThread
private void initializeThread(final Thread thread) { if (getNamingPattern() != null) { final Long count = Long.valueOf(threadCounter.incrementAndGet()); thread.setName(String.format(getNamingPattern(), count)); } if (getUncaughtExceptionHandler() != null) { thread.setUncaughtExceptionHandler(getUncaughtExceptionHandler()); } if (getPriority() != null) { thread.setPriority(getPriority().intValue()); } if (getDaemonFlag() != null) { thread.setDaemon(getDaemonFlag().booleanValue()); } }
Initializes the specified thread. This method is called by {@link #newThread(Runnable)} after a new thread has been obtained from the wrapped thread factory. It initializes the thread according to the options set for this factory. @param thread the thread to be initialized
java
src/main/java/org/apache/commons/lang3/concurrent/BasicThreadFactory.java
353
[ "thread" ]
void
true
5
6.88
apache/commons-lang
2,896
javadoc
false
entrySet
@Override public ImmutableSet<Entry<E>> entrySet() { ImmutableSet<Entry<E>> es = entrySet; return (es == null) ? (entrySet = createEntrySet()) : es; }
@since 21.0 (present with return type {@code Set} since 2.0)
java
android/guava/src/com/google/common/collect/ImmutableMultiset.java
352
[]
true
2
6.4
google/guava
51,352
javadoc
false
toObject
public static Byte[] toObject(final byte[] array) { if (array == null) { return null; } if (array.length == 0) { return EMPTY_BYTE_OBJECT_ARRAY; } return setAll(new Byte[array.length], i -> Byte.valueOf(array[i])); }
Converts an array of primitive bytes to objects. <p>This method returns {@code null} for a {@code null} input array.</p> @param array a {@code byte} array. @return a {@link Byte} array, {@code null} if null array input.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
8,690
[ "array" ]
true
3
8.24
apache/commons-lang
2,896
javadoc
false
asFunction
@SuppressWarnings("unchecked") public static <T, R> Function<T, R> asFunction(final Method method) { return asInterfaceInstance(Function.class, method); }
Produces a {@link Function} for a given a <em>supplier</em> Method. You call the Function with one argument: the object receiving the method call. The Function return type must match the method's return type. <p> For example to invoke {@link String#length()}: </p> <pre>{@code final Method method = String.class.getMethod("length"); final Function<String, Integer> function = MethodInvokers.asFunction(method); assertEquals(3, function.apply("ABC")); }</pre> @param <T> the type of the first argument to the function: The type containing the method. @param <R> the type of the result of the function: The method return type. @param method the method to invoke. @return a correctly-typed wrapper for the given target.
java
src/main/java/org/apache/commons/lang3/function/MethodInvokers.java
192
[ "method" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
addAll
void addAll(Collection<CompletedFetch> completedFetches) { if (completedFetches == null || completedFetches.isEmpty()) return; try { lock.lock(); this.completedFetches.addAll(completedFetches); wokenup.set(true); blockingCondition.signalAll(); } finally { lock.unlock(); } }
Return whether we have any completed fetches pending return to the user. This method is thread-safe. Has visibility for testing. @return {@code true} if there are completed fetches that match the {@link Predicate}, {@code false} otherwise
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchBuffer.java
102
[ "completedFetches" ]
void
true
3
7.04
apache/kafka
31,560
javadoc
false
shapes_hinted
def shapes_hinted(self) -> tuple[tuple[int, ...], ...]: """ Get the size hints for shapes of all input nodes. Returns: A tuple of shape tuples with integer hints for each input node """ return tuple( V.graph.sizevars.size_hints( node.get_size(), fallback=torch._inductor.config.unbacked_symint_fallback, ) for node in self._input_nodes )
Get the size hints for shapes of all input nodes. Returns: A tuple of shape tuples with integer hints for each input node
python
torch/_inductor/kernel_inputs.py
117
[ "self" ]
tuple[tuple[int, ...], ...]
true
1
6.56
pytorch/pytorch
96,034
unknown
false
getCauseUsingMethodName
private static Throwable getCauseUsingMethodName(final Throwable throwable, final String methodName) { if (methodName != null) { final Method method = MethodUtils.getMethodObject(throwable.getClass(), methodName); if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { try { return (Throwable) method.invoke(throwable); } catch (final ReflectiveOperationException ignored) { // exception ignored } } } return null; }
Gets a {@link Throwable} by method name. @param throwable the exception to examine. @param methodName the name of the method to find and invoke. @return the wrapped exception, or {@code null} if not found.
java
src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java
253
[ "throwable", "methodName" ]
Throwable
true
5
8.08
apache/commons-lang
2,896
javadoc
false
getMaxDevVersionIncrement
function getMaxDevVersionIncrement(versions: string[]): number { const regex = /\d+\.\d+\.\d+-dev\.(\d+)/ const increments = versions .filter((v) => v.trim().length > 0) .map((v) => { const match = regex.exec(v) if (match) { return Number(match[1]) } return 0 }) .filter((v) => v) return Math.max(...increments, 0) }
Takes the max dev version + 1 For now supporting X.Y.Z-dev.# @param packages Local package definitions
typescript
scripts/ci/publish.ts
321
[ "versions" ]
true
2
6.72
prisma/prisma
44,834
jsdoc
false
close
@Override public void close() throws IOException { try { if (!finished) { // basically flush the buffer writing the last block writeBlock(); // write the end block writeEndMark(); } } finally { try { if (out != null) { try (OutputStream outStream = out) { outStream.flush(); } } } finally { out = null; buffer = null; compressedBuffer = null; finished = true; } } }
A simple state check to ensure the stream is still open.
java
clients/src/main/java/org/apache/kafka/common/compress/Lz4BlockOutputStream.java
237
[]
void
true
3
7.04
apache/kafka
31,560
javadoc
false
skipUpTo
static long skipUpTo(InputStream in, long n) throws IOException { long totalSkipped = 0; // A buffer is allocated if skipSafely does not skip any bytes. byte[] buf = null; while (totalSkipped < n) { long remaining = n - totalSkipped; long skipped = skipSafely(in, remaining); if (skipped == 0) { // Do a buffered read since skipSafely could return 0 repeatedly, for example if // in.available() always returns 0 (the default). int skip = (int) min(remaining, BUFFER_SIZE); if (buf == null) { // Allocate a buffer bounded by the maximum size that can be requested, for // example an array of BUFFER_SIZE is unnecessary when the value of remaining // is smaller. buf = new byte[skip]; } if ((skipped = in.read(buf, 0, skip)) == -1) { // Reached EOF break; } } totalSkipped += skipped; } return totalSkipped; }
Discards up to {@code n} bytes of data from the input stream. This method will block until either the full amount has been skipped or until the end of the stream is reached, whichever happens first. Returns the total number of bytes skipped.
java
android/guava/src/com/google/common/io/ByteStreams.java
843
[ "in", "n" ]
true
5
6
google/guava
51,352
javadoc
false
responseContentTypeHeader
public String responseContentTypeHeader() { return mediaTypeWithoutParameters() + formatParameters(parameters); }
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
157
[]
String
true
1
6.32
elastic/elasticsearch
75,680
javadoc
false
get
def get(self, key, default=None): """ Get item from object for given key (ex: DataFrame column). Returns ``default`` value if not found. Parameters ---------- key : object Key for which item should be returned. default : object, default None Default value to return if key is not found. Returns ------- same type as items contained in object Item for given key or ``default`` value, if key is not found. See Also -------- DataFrame.get : Get item from object for given key (ex: DataFrame column). Series.get : Get item from object for given key (ex: DataFrame column). Examples -------- >>> df = pd.DataFrame( ... [ ... [24.3, 75.7, "high"], ... [31, 87.8, "high"], ... [22, 71.6, "medium"], ... [35, 95, "medium"], ... ], ... columns=["temp_celsius", "temp_fahrenheit", "windspeed"], ... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"), ... ) >>> df temp_celsius temp_fahrenheit windspeed 2014-02-12 24.3 75.7 high 2014-02-13 31.0 87.8 high 2014-02-14 22.0 71.6 medium 2014-02-15 35.0 95.0 medium >>> df.get(["temp_celsius", "windspeed"]) temp_celsius windspeed 2014-02-12 24.3 high 2014-02-13 31.0 high 2014-02-14 22.0 medium 2014-02-15 35.0 medium >>> ser = df["windspeed"] >>> ser.get("2014-02-13") 'high' If the key isn't found, the default value will be used. >>> df.get(["temp_celsius", "temp_kelvin"], default="default_value") 'default_value' >>> ser.get("2014-02-10", "[unknown]") '[unknown]' """ try: return self[key] except (KeyError, ValueError, IndexError): return default
Get item from object for given key (ex: DataFrame column). Returns ``default`` value if not found. Parameters ---------- key : object Key for which item should be returned. default : object, default None Default value to return if key is not found. Returns ------- same type as items contained in object Item for given key or ``default`` value, if key is not found. See Also -------- DataFrame.get : Get item from object for given key (ex: DataFrame column). Series.get : Get item from object for given key (ex: DataFrame column). Examples -------- >>> df = pd.DataFrame( ... [ ... [24.3, 75.7, "high"], ... [31, 87.8, "high"], ... [22, 71.6, "medium"], ... [35, 95, "medium"], ... ], ... columns=["temp_celsius", "temp_fahrenheit", "windspeed"], ... index=pd.date_range(start="2014-02-12", end="2014-02-15", freq="D"), ... ) >>> df temp_celsius temp_fahrenheit windspeed 2014-02-12 24.3 75.7 high 2014-02-13 31.0 87.8 high 2014-02-14 22.0 71.6 medium 2014-02-15 35.0 95.0 medium >>> df.get(["temp_celsius", "windspeed"]) temp_celsius windspeed 2014-02-12 24.3 high 2014-02-13 31.0 high 2014-02-14 22.0 medium 2014-02-15 35.0 medium >>> ser = df["windspeed"] >>> ser.get("2014-02-13") 'high' If the key isn't found, the default value will be used. >>> df.get(["temp_celsius", "temp_kelvin"], default="default_value") 'default_value' >>> ser.get("2014-02-10", "[unknown]") '[unknown]'
python
pandas/core/generic.py
4,315
[ "self", "key", "default" ]
false
1
6.08
pandas-dev/pandas
47,362
numpy
false
getIfUnique
default @Nullable T getIfUnique() throws BeansException { try { return getObject(); } catch (NoSuchBeanDefinitionException ex) { return null; } }
Return an instance (possibly shared or independent) of the object managed by this factory. @return an instance of the bean, or {@code null} if not available or not unique (i.e. multiple candidates found with none marked as primary) @throws BeansException in case of creation errors @see #getObject()
java
spring-beans/src/main/java/org/springframework/beans/factory/ObjectProvider.java
172
[]
T
true
2
7.92
spring-projects/spring-framework
59,386
javadoc
false
get_connection_from_secrets
def get_connection_from_secrets(cls, conn_id: str) -> Connection: """ Get connection by conn_id. If `MetastoreBackend` is getting used in the execution context, use Task SDK API. :param conn_id: connection id :return: connection """ # TODO: This is not the best way of having compat, but it's "better than erroring" for now. This still # means SQLA etc is loaded, but we can't avoid that unless/until we add import shims as a big # back-compat layer # If this is set it means are in some kind of execution context (Task, Dag Parse or Triggerer perhaps) # and should use the Task SDK API server path if hasattr(sys.modules.get("airflow.sdk.execution_time.task_runner"), "SUPERVISOR_COMMS"): from airflow.sdk import Connection as TaskSDKConnection from airflow.sdk.exceptions import AirflowRuntimeError, ErrorType warnings.warn( "Using Connection.get_connection_from_secrets from `airflow.models` is deprecated." "Please use `get` on Connection from sdk(`airflow.sdk.Connection`) instead", DeprecationWarning, stacklevel=1, ) try: conn = TaskSDKConnection.get(conn_id=conn_id) if isinstance(conn, TaskSDKConnection): if conn.password: mask_secret(conn.password) if conn.extra: mask_secret(conn.extra) return conn except AirflowRuntimeError as e: if e.error.error == ErrorType.CONNECTION_NOT_FOUND: raise AirflowNotFoundException(f"The conn_id `{conn_id}` isn't defined") from None raise # check cache first # enabled only if SecretCache.init() has been called first try: uri = SecretCache.get_connection_uri(conn_id) return Connection(conn_id=conn_id, uri=uri) except SecretCache.NotPresentException: pass # continue business # iterate over backends if not in cache (or expired) for secrets_backend in ensure_secrets_loaded(): try: conn = secrets_backend.get_connection(conn_id=conn_id) if conn: SecretCache.save_connection_uri(conn_id, conn.get_uri()) return conn except Exception: log.debug( "Unable to retrieve connection from secrets backend (%s). " "Checking subsequent secrets backend.", type(secrets_backend).__name__, ) raise AirflowNotFoundException(f"The conn_id `{conn_id}` isn't defined")
Get connection by conn_id. If `MetastoreBackend` is getting used in the execution context, use Task SDK API. :param conn_id: connection id :return: connection
python
airflow-core/src/airflow/models/connection.py
482
[ "cls", "conn_id" ]
Connection
true
8
7.84
apache/airflow
43,597
sphinx
false
get_bucket_tagging
def get_bucket_tagging(self, bucket_name: str | None = None) -> list[dict[str, str]] | None: """ Get a List of tags from a bucket. .. seealso:: - :external+boto3:py:meth:`S3.Client.get_bucket_tagging` :param bucket_name: The name of the bucket. :return: A List containing the key/value pairs for the tags """ try: s3_client = self.get_conn() result = s3_client.get_bucket_tagging(Bucket=bucket_name)["TagSet"] self.log.info("S3 Bucket Tag Info: %s", result) return result except ClientError as e: self.log.error(e) raise e
Get a List of tags from a bucket. .. seealso:: - :external+boto3:py:meth:`S3.Client.get_bucket_tagging` :param bucket_name: The name of the bucket. :return: A List containing the key/value pairs for the tags
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py
1,645
[ "self", "bucket_name" ]
list[dict[str, str]] | None
true
1
6.4
apache/airflow
43,597
sphinx
false
load
public <T> AotServices<T> load(Class<T> type) { return new AotServices<>(this.springFactoriesLoader.load(type), loadBeans(type)); }
Load all AOT services of the given type. @param <T> the service type @param type the service type @return a new {@link AotServices} instance
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/AotServices.java
209
[ "type" ]
true
1
6.64
spring-projects/spring-framework
59,386
javadoc
false
_json_to_tile_description
def _json_to_tile_description( cls, json_dict: Optional[str] ) -> Optional["TileDescription"]: # type: ignore[name-defined] # noqa: F821 """ Convert JSON dict to TileDescription object. Args: json_dict: Dictionary representation Returns: TileDescription: Reconstructed object """ if json_dict is None: return None tile_dict = json.loads(json_dict) from cutlass_library.library import TileDescription math_instruction = cls._json_to_math_instruction(tile_dict["math_instruction"]) # Get compute capability values, checking both naming conventions min_compute = tile_dict.get( "min_compute", tile_dict.get("minimum_compute_capability") ) max_compute = tile_dict.get( "max_compute", tile_dict.get("maximum_compute_capability") ) # Get cluster shape with default value cluster_shape = tile_dict.get("cluster_shape", [1, 1, 1]) # Create the TileDescription object tile_desc = TileDescription( threadblock_shape=tile_dict["threadblock_shape"], stages=tile_dict["stages"], warp_count=tile_dict["warp_count"], math_instruction=math_instruction, min_compute=min_compute, max_compute=max_compute, cluster_shape=cluster_shape, explicit_vector_sizes=tile_dict.get("explicit_vector_sizes"), ) # Set tile_shape if it exists and differs from threadblock_shape if ( "tile_shape" in tile_dict and tile_dict["tile_shape"] != tile_dict["threadblock_shape"] ): tile_desc.tile_shape = tile_dict["tile_shape"] return tile_desc
Convert JSON dict to TileDescription object. Args: json_dict: Dictionary representation Returns: TileDescription: Reconstructed object
python
torch/_inductor/codegen/cuda/serialization.py
258
[ "cls", "json_dict" ]
Optional["TileDescription"]
true
4
7.44
pytorch/pytorch
96,034
google
false
build
@SuppressWarnings("unchecked") @Override public ImmutableSet<E> build() { switch (size) { case 0: return of(); case 1: /* * requireNonNull is safe because we ensure that the first `size` elements have been * populated. */ return (ImmutableSet<E>) of(requireNonNull(contents[0])); default: ImmutableSet<E> result; if (hashTable != null && chooseTableSize(size) == hashTable.length) { @Nullable Object[] uniqueElements = shouldTrim(size, contents.length) ? Arrays.copyOf(contents, size) : contents; result = new RegularImmutableSet<E>( uniqueElements, hashCode, hashTable, hashTable.length - 1, size); } else { result = construct(size, contents); // construct has the side effect of deduping contents, so we update size // accordingly. size = result.size(); } forceCopy = true; hashTable = null; return result; } }
Returns a newly-created {@code ImmutableSet} based on the contents of the {@code Builder}.
java
android/guava/src/com/google/common/collect/ImmutableSet.java
594
[]
true
4
6.4
google/guava
51,352
javadoc
false
noNullElements
public static <T> T[] noNullElements(final T[] array) { return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE); }
Validate that the specified argument array is neither {@code null} nor contains any elements that are {@code null}; otherwise throwing an exception. <pre>Validate.noNullElements(myArray);</pre> <p>If the array is {@code null}, then the message in the exception is &quot;The validated object is null&quot;.</p> <p>If the array has a {@code null} element, then the message in the exception is &quot;The validated array contains null element at index: &quot; followed by the index.</p> @param <T> the array type. @param array the array to check, validated not null by this method. @return the validated array (never {@code null} method for chaining). @throws NullPointerException if the array is {@code null}. @throws IllegalArgumentException if an element is {@code null}. @see #noNullElements(Object[], String, Object...)
java
src/main/java/org/apache/commons/lang3/Validate.java
724
[ "array" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
withMaximumLength
public StandardStackTracePrinter withMaximumLength(int maximumLength) { Assert.isTrue(maximumLength > 0, "'maximumLength' must be positive"); return new StandardStackTracePrinter(this.options, maximumLength, this.lineSeparator, this.filter, this.frameFilter, this.formatter, this.frameFormatter, this.frameHasher); }
Return a new {@link StandardStackTracePrinter} from this one that will use ellipses to truncate output longer that the specified length. @param maximumLength the maximum length that can be printed @return a new {@link StandardStackTracePrinter} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/StandardStackTracePrinter.java
178
[ "maximumLength" ]
StandardStackTracePrinter
true
1
6.24
spring-projects/spring-boot
79,428
javadoc
false
resolveTypeDescriptor
private TypeDescriptor resolveTypeDescriptor(TypeElement element) { if (this.typeDescriptors.containsKey(element)) { return this.typeDescriptors.get(element); } return createTypeDescriptor(element); }
Return the {@link PrimitiveType} of the specified type or {@code null} if the type does not represent a valid wrapper type. @param typeMirror a type @return the primitive type or {@code null} if the type is not a wrapper type
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/TypeUtils.java
221
[ "element" ]
TypeDescriptor
true
2
7.92
spring-projects/spring-boot
79,428
javadoc
false
load32
static int load32(byte[] source, int offset) { // TODO(user): Measure the benefit of delegating this to LittleEndianBytes also. return (source[offset] & 0xFF) | ((source[offset + 1] & 0xFF) << 8) | ((source[offset + 2] & 0xFF) << 16) | ((source[offset + 3] & 0xFF) << 24); }
Load 4 bytes from the provided array at the indicated offset. @param source the input bytes @param offset the offset into the array at which to start @return the value found in the array in the form of a long
java
android/guava/src/com/google/common/hash/LittleEndianByteArray.java
103
[ "source", "offset" ]
true
1
7.2
google/guava
51,352
javadoc
false
replaceParameter
private @Nullable String replaceParameter(String parameter, Locale locale, Set<String> visitedParameters) { parameter = replaceParameters(parameter, locale, visitedParameters); String value = this.messageSource.getMessage(parameter, null, DEFAULT_MESSAGE, locale); if (value == null || value.equals(DEFAULT_MESSAGE)) { return null; } return replaceParameters(value, locale, visitedParameters); }
Recursively replaces all message parameters. <p> The message parameter prefix <code>&#123;</code> and suffix <code>&#125;</code> can be escaped using {@code \}, e.g. <code>\&#123;escaped\&#125;</code>. @param message the message containing the parameters to be replaced @param locale the locale to use when resolving replacements @return the message with parameters replaced
java
core/spring-boot/src/main/java/org/springframework/boot/validation/MessageSourceMessageInterpolator.java
119
[ "parameter", "locale", "visitedParameters" ]
String
true
3
7.76
spring-projects/spring-boot
79,428
javadoc
false
entryToAccessExpression
function entryToAccessExpression(entry: FindAllReferences.NodeEntry): ElementAccessExpression | PropertyAccessExpression | undefined { if (entry.node.parent) { const reference = entry.node; const parent = reference.parent; switch (parent.kind) { // `C.foo` case SyntaxKind.PropertyAccessExpression: const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; // `C["foo"]` case SyntaxKind.ElementAccessExpression: const elementAccessExpression = tryCast(parent, isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { return elementAccessExpression; } break; } } return undefined; }
Gets the symbol for the contextual type of the node if it is not a union or intersection.
typescript
src/services/refactors/convertParamsToDestructuredObject.ts
403
[ "entry" ]
true
6
6
microsoft/TypeScript
107,154
jsdoc
false
newArrayListWithExpectedSize
@SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call public static <E extends @Nullable Object> ArrayList<E> newArrayListWithExpectedSize( int estimatedSize) { return new ArrayList<>(computeArrayListCapacity(estimatedSize)); }
Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an unspecified amount of padding; **don't do this**. Instead, use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly and choose an explicit padding amount. @param estimatedSize an estimate of the eventual {@link List#size()} of the new list @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of elements @throws IllegalArgumentException if {@code estimatedSize} is negative
java
android/guava/src/com/google/common/collect/Lists.java
197
[ "estimatedSize" ]
true
1
6.08
google/guava
51,352
javadoc
false
addErrorPages
@Override public void addErrorPages(ErrorPage... errorPages) { for (ErrorPage errorPage : errorPages) { if (errorPage.isGlobal()) { this.global = errorPage.getPath(); } else if (errorPage.getStatus() != null) { this.statuses.put(errorPage.getStatus().value(), errorPage.getPath()); } else { this.exceptions.put(errorPage.getException(), errorPage.getPath()); } } }
Return the description for the given request. By default this method will return a description based on the request {@code servletPath} and {@code pathInfo}. @param request the source request @return the description
java
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/support/ErrorPageFilter.java
278
[]
void
true
3
7.92
spring-projects/spring-boot
79,428
javadoc
false
humanize_seconds
def humanize_seconds( secs: int, prefix: str = '', sep: str = '', now: str = 'now', microseconds: bool = False) -> str: """Show seconds in human form. For example, 60 becomes "1 minute", and 7200 becomes "2 hours". Arguments: prefix (str): can be used to add a preposition to the output (e.g., 'in' will give 'in 1 second', but add nothing to 'now'). now (str): Literal 'now'. microseconds (bool): Include microseconds. """ secs = float(format(float(secs), '.2f')) for unit, divider, formatter in TIME_UNITS: if secs >= divider: w = secs / float(divider) return '{}{}{} {}'.format(prefix, sep, formatter(w), pluralize(w, unit)) if microseconds and secs > 0.0: return '{prefix}{sep}{0:.2f} seconds'.format( secs, sep=sep, prefix=prefix) return now
Show seconds in human form. For example, 60 becomes "1 minute", and 7200 becomes "2 hours". Arguments: prefix (str): can be used to add a preposition to the output (e.g., 'in' will give 'in 1 second', but add nothing to 'now'). now (str): Literal 'now'. microseconds (bool): Include microseconds.
python
celery/utils/time.py
293
[ "secs", "prefix", "sep", "now", "microseconds" ]
str
true
5
6.88
celery/celery
27,741
google
false
getScramCredentialInfosFor
private static List<ScramCredentialInfo> getScramCredentialInfosFor( DescribeUserScramCredentialsResponseData.DescribeUserScramCredentialsResult userResult) { return userResult.credentialInfos().stream().map(c -> new ScramCredentialInfo(ScramMechanism.fromType(c.mechanism()), c.iterations())) .collect(Collectors.toList()); }
@param userName the name of the user description being requested @return a future indicating the description results for the given user. The future will complete exceptionally if the future returned by {@link #users()} completes exceptionally. Note that if the given user does not exist in the list of described users then the returned future will complete exceptionally with {@link org.apache.kafka.common.errors.ResourceNotFoundException}.
java
clients/src/main/java/org/apache/kafka/clients/admin/DescribeUserScramCredentialsResult.java
140
[ "userResult" ]
true
1
6.24
apache/kafka
31,560
javadoc
false
values
@Override public Collection<V> values() { // does not impact recency ordering Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); }
Returns the internal entry for the specified key. The entry may be loading, expired, or partially collected.
java
android/guava/src/com/google/common/cache/LocalCache.java
4,187
[]
true
2
7.04
google/guava
51,352
javadoc
false
loadBeanDefinitions
int loadBeanDefinitions(String location) throws BeanDefinitionStoreException;
Load bean definitions from the specified resource location. <p>The location can also be a location pattern, provided that the {@link ResourceLoader} of this bean definition reader is a {@code ResourcePatternResolver}. @param location the resource location, to be loaded with the {@code ResourceLoader} (or {@code ResourcePatternResolver}) of this bean definition reader @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/BeanDefinitionReader.java
109
[ "location" ]
true
1
6
spring-projects/spring-framework
59,386
javadoc
false
start_pipeline
def start_pipeline( self, pipeline_name: str, display_name: str = "airflow-triggered-execution", pipeline_params: dict | None = None, ) -> str: """ Start a new execution for a SageMaker pipeline. .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.start_pipeline_execution` :param pipeline_name: Name of the pipeline to start (this is _not_ the ARN). :param display_name: The name this pipeline execution will have in the UI. Doesn't need to be unique. :param pipeline_params: Optional parameters for the pipeline. All parameters supplied need to already be present in the pipeline definition. :return: the ARN of the pipeline execution launched. """ formatted_params = format_tags(pipeline_params, key_label="Name") try: res = self.conn.start_pipeline_execution( PipelineName=pipeline_name, PipelineExecutionDisplayName=display_name, PipelineParameters=formatted_params, ) except ClientError as ce: self.log.error("Failed to start pipeline execution, error: %s", ce) raise return res["PipelineExecutionArn"]
Start a new execution for a SageMaker pipeline. .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.start_pipeline_execution` :param pipeline_name: Name of the pipeline to start (this is _not_ the ARN). :param display_name: The name this pipeline execution will have in the UI. Doesn't need to be unique. :param pipeline_params: Optional parameters for the pipeline. All parameters supplied need to already be present in the pipeline definition. :return: the ARN of the pipeline execution launched.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
1,101
[ "self", "pipeline_name", "display_name", "pipeline_params" ]
str
true
1
6.4
apache/airflow
43,597
sphinx
false
wrapWithHoc
function wrapWithHoc( Component: (props: any, ref: React$RefSetter<any>) => any, ) { function Hoc() { return <Component />; } // $FlowFixMe[prop-missing] const displayName = Component.displayName || Component.name; // $FlowFixMe[incompatible-type] found when upgrading Flow Hoc.displayName = `withHoc(${displayName})`; return Hoc; } const HocWithHooks = wrapWithHoc(FunctionWithHooks); const Suspendender = React.lazy(() => { return new Promise<any>(resolve => { setTimeout(() => { resolve({ default: () => 'Finished!', }); }, 3000); }); }); function Transition() { const [show, setShow] = React.useState(false); const [isPending, startTransition] = React.useTransition(); return ( <div> <React.Suspense fallback="Loading"> {isPending ? 'Pending' : null} {show ? <Suspendender /> : null} </React.Suspense> {!show && ( <button onClick={() => startTransition(() => setShow(true))}> Transition </button> )} </div> ); } function incrementWithDelay(previousState: number, formData: FormData) { const incrementDelay = +formData.get('incrementDelay'); const shouldReject = formData.get('shouldReject'); const reason = formData.get('reason'); return new Promise((resolve, reject) => { setTimeout(() => { if (shouldReject) { reject(reason); } else { resolve(previousState + 1); } }, incrementDelay); }); } function FormStatus() { const status = useFormStatus(); return <pre>{JSON.stringify(status)}</pre>; } function Forms() { const [state, formAction] = useFormState<any, any>(incrementWithDelay, 0); return ( <form> State: {state}&nbsp; <label> delay: <input name="incrementDelay" defaultValue={5000} type="text" inputMode="numeric" /> </label> <label> Reject: <input name="reason" type="text" /> <input name="shouldReject" type="checkbox" /> </label> <button formAction={formAction}>Increment</button> <FormStatus /> </form> ); } class ErrorBoundary extends React.Component<{children?: React$Node}> { state: {error: any} = {error: null}; static getDerivedStateFromError(error: mixed): {error: any} { return {error}; } componentDidCatch(error: any, info: any) { console.error(error, info); } render(): any { if (this.state.error) { return <div>Error: {String(this.state.error)}</div>; } return this.props.children; } } export default function CustomHooks(): React.Node { return ( <Fragment> <FunctionWithHooks /> <MemoWithHooks /> <ForwardRefWithHooks /> <HocWithHooks /> <Transition /> <ErrorBoundary> <Forms /> </ErrorBoundary> </Fragment> ); }
Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. @flow
javascript
packages/react-devtools-shell/src/app/InspectableElements/CustomHooks.js
111
[]
false
7
6.16
facebook/react
241,750
jsdoc
false
get_python_version_list
def get_python_version_list(python_versions: str) -> list[str]: """ Retrieve and validate space-separated list of Python versions and return them in the form of list. :param python_versions: space separated list of Python versions :return: List of python versions """ python_version_list = python_versions.split(" ") errors = False for python in python_version_list: if python not in ALLOWED_PYTHON_MAJOR_MINOR_VERSIONS: get_console().print( f"[error]The Python version {python} passed in {python_versions} is wrong.[/]" ) errors = True if errors: get_console().print( f"\nSome of the Python versions passed are not in the " f"list: {ALLOWED_PYTHON_MAJOR_MINOR_VERSIONS}. Quitting.\n" ) sys.exit(1) return python_version_list
Retrieve and validate space-separated list of Python versions and return them in the form of list. :param python_versions: space separated list of Python versions :return: List of python versions
python
dev/breeze/src/airflow_breeze/utils/python_versions.py
25
[ "python_versions" ]
list[str]
true
4
8.08
apache/airflow
43,597
sphinx
false
min
public static byte min(final byte... array) { // Validates input validateArray(array); // Finds and returns min byte min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; }
Returns the minimum value in an array. @param array an array, must not be null or empty. @return the minimum value in the array. @throws NullPointerException if {@code array} is {@code null}. @throws IllegalArgumentException if {@code array} is empty. @since 3.4 Changed signature from min(byte[]) to min(byte...).
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
1,103
[]
true
3
8.24
apache/commons-lang
2,896
javadoc
false
spread
function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); }
Creates a function that invokes `func` with the `this` binding of the create function and an array of arguments much like [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). **Note:** This method is based on the [spread operator](https://mdn.io/spread_operator). @static @memberOf _ @since 3.2.0 @category Function @param {Function} func The function to spread arguments over. @param {number} [start=0] The start position of the spread. @returns {Function} Returns the new function. @example var say = _.spread(function(who, what) { return who + ' says ' + what; }); say(['fred', 'hello']); // => 'fred says hello' var numbers = Promise.all([ Promise.resolve(40), Promise.resolve(36) ]); numbers.then(_.spread(function(x, y) { return x + y; })); // => a Promise of 76
javascript
lodash.js
10,944
[ "func", "start" ]
false
4
7.2
lodash/lodash
61,490
jsdoc
false
SetProcessWorkingSetSize
boolean SetProcessWorkingSetSize(Handle handle, long minSize, long maxSize);
Sets the minimum and maximum working set sizes for the specified process. @param handle A handle to the process whose working set sizes is to be set. @param minSize The minimum working set size for the process, in bytes. @param maxSize The maximum working set size for the process, in bytes. @return true if the function succeeds. @see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms686234%28v=vs.85%29.aspx">SetProcessWorkingSetSize docs</a>
java
libs/native/src/main/java/org/elasticsearch/nativeaccess/lib/Kernel32Library.java
85
[ "handle", "minSize", "maxSize" ]
true
1
6.16
elastic/elasticsearch
75,680
javadoc
false
readValueUnsafe
private static Object readValueUnsafe(Token currentToken, XContentParser parser, Supplier<Map<String, Object>> mapFactory) throws IOException { assert currentToken == parser.currentToken() : "Supplied current token [" + currentToken + "] is different from actual parser current token [" + parser.currentToken() + "]"; switch (currentToken) { case VALUE_STRING: return parser.text(); case VALUE_NUMBER: return parser.numberValue(); case VALUE_BOOLEAN: return parser.booleanValue(); case START_OBJECT: { final Map<String, Object> map = mapFactory.get(); final String nextFieldName = parser.nextFieldName(); return nextFieldName == null ? map : readMapEntries(parser, mapFactory, map, nextFieldName); } case START_ARRAY: return readListUnsafe(parser, mapFactory); case VALUE_EMBEDDED_OBJECT: return parser.binaryValue(); case VALUE_NULL: default: return null; } }
Reads next value from the parser that is assumed to be at the given current token without any additional checks. @param currentToken current token that the parser is at @param parser parser to read from @param mapFactory map factory to use for reading objects
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/support/AbstractXContentParser.java
419
[ "currentToken", "parser", "mapFactory" ]
Object
true
2
6.56
elastic/elasticsearch
75,680
javadoc
false
executeSynchronized
@SuppressWarnings({ "unchecked", "rawtypes" }) private @Nullable Object executeSynchronized(CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) { CacheOperationContext context = contexts.get(CacheableOperation.class).iterator().next(); if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) { Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT); Cache cache = context.getCaches().iterator().next(); if (CompletableFuture.class.isAssignableFrom(method.getReturnType())) { AtomicBoolean invokeFailure = new AtomicBoolean(false); CompletableFuture<?> result = doRetrieve(cache, key, () -> { CompletableFuture<?> invokeResult = ((CompletableFuture<?>) invokeOperation(invoker)); if (invokeResult == null) { throw new IllegalStateException("Returned CompletableFuture must not be null: " + method); } return invokeResult.exceptionallyCompose(ex -> { invokeFailure.set(true); return CompletableFuture.failedFuture(ex); }); }); return result.exceptionallyCompose(ex -> { if (!(ex instanceof RuntimeException rex)) { return CompletableFuture.failedFuture(ex); } try { getErrorHandler().handleCacheGetError(rex, cache, key); if (invokeFailure.get()) { return CompletableFuture.failedFuture(ex); } return (CompletableFuture) invokeOperation(invoker); } catch (Throwable ex2) { return CompletableFuture.failedFuture(ex2); } }); } if (this.reactiveCachingHandler != null) { Object returnValue = this.reactiveCachingHandler.executeSynchronized(invoker, method, cache, key); if (returnValue != ReactiveCachingHandler.NOT_HANDLED) { return returnValue; } } try { return wrapCacheValue(method, doGet(cache, key, () -> unwrapReturnValue(invokeOperation(invoker)))); } catch (Cache.ValueRetrievalException ex) { // Directly propagate ThrowableWrapper from the invoker, // or potentially also an IllegalArgumentException etc. ReflectionUtils.rethrowRuntimeException(ex.getCause()); // Never reached return null; } } else { // No caching required, just call the underlying method return invokeOperation(invoker); } }
Execute the underlying operation (typically in case of cache miss) and return the result of the invocation. If an exception occurs it will be wrapped in a {@link CacheOperationInvoker.ThrowableWrapper}: the exception can be handled or modified but it <em>must</em> be wrapped in a {@link CacheOperationInvoker.ThrowableWrapper} as well. @param invoker the invoker handling the operation being cached @return the result of the invocation @see CacheOperationInvoker#invoke()
java
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
445
[ "invoker", "method", "contexts" ]
Object
true
10
7.52
spring-projects/spring-framework
59,386
javadoc
false
obtrudeValue
@Override public void obtrudeValue(T value) { throw erroneousCompletionException(); }
Completes this future exceptionally. For internal use by the Kafka clients, not by user code. @param throwable the exception. @return {@code true} if this invocation caused this CompletableFuture to transition to a completed state, else {@code false}
java
clients/src/main/java/org/apache/kafka/common/internals/KafkaCompletableFuture.java
62
[ "value" ]
void
true
1
6.64
apache/kafka
31,560
javadoc
false
hasBeanMethods
static boolean hasBeanMethods(AnnotationMetadata metadata) { try { return metadata.hasAnnotatedMethods(Bean.class.getName()); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex); } return false; } }
Check the given metadata for a configuration class candidate (or nested component class declared within a configuration/component class). @param metadata the metadata of the annotated class @return {@code true} if the given class is to be registered for configuration class processing; {@code false} otherwise
java
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java
191
[ "metadata" ]
true
3
7.6
spring-projects/spring-framework
59,386
javadoc
false
equals
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MemberAssignment that = (MemberAssignment) o; return Objects.equals(topicPartitions, that.topicPartitions); }
Creates an instance with the specified parameters. @param topicPartitions List of topic partitions
java
clients/src/main/java/org/apache/kafka/clients/admin/MemberAssignment.java
41
[ "o" ]
true
4
6.08
apache/kafka
31,560
javadoc
false
inspectorOpen
function inspectorOpen(port, host, wait) { if (isEnabled()) { throw new ERR_INSPECTOR_ALREADY_ACTIVATED(); } // inspectorOpen() currently does not typecheck its arguments and adding // such checks would be a potentially breaking change. However, the native // open() function requires the port to fit into a 16-bit unsigned integer, // causing an integer overflow otherwise, so we at least need to prevent that. if (isUint32(port)) { validateInt32(port, 'port', 0, 65535); } if (host && !isLoopback(host)) { process.emitWarning( 'Binding the inspector to a public IP with an open port is insecure, ' + 'as it allows external hosts to connect to the inspector ' + 'and perform a remote code execution attack. ' + 'Documentation can be found at ' + 'https://nodejs.org/api/cli.html#--inspecthostport', 'SecurityWarning', ); } open(port, host); if (wait) waitForDebugger(); return { __proto__: null, [SymbolDispose]() { _debugEnd(); } }; }
Activates inspector on host and port. @param {number} [port] @param {string} [host] @param {boolean} [wait] @returns {void}
javascript
lib/inspector.js
169
[ "port", "host", "wait" ]
false
6
6.08
nodejs/node
114,839
jsdoc
false
writeReplace
protected Object writeReplace() { List<DestructionAwareBeanPostProcessor> serializablePostProcessors = null; if (this.beanPostProcessors != null) { serializablePostProcessors = new ArrayList<>(); for (DestructionAwareBeanPostProcessor postProcessor : this.beanPostProcessors) { if (postProcessor instanceof Serializable) { serializablePostProcessors.add(postProcessor); } } } return new DisposableBeanAdapter( this.bean, this.beanName, this.nonPublicAccessAllowed, this.invokeDisposableBean, this.invokeAutoCloseable, this.destroyMethodNames, serializablePostProcessors); }
Serializes a copy of the state of this class, filtering out non-serializable BeanPostProcessors.
java
spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java
367
[]
Object
true
3
6.08
spring-projects/spring-framework
59,386
javadoc
false
take
def take( arr, indices: TakeIndexer, axis: AxisInt = 0, allow_fill: bool = False, fill_value=None, ): """ Take elements from an array. Parameters ---------- arr : numpy.ndarray, ExtensionArray, Index, or Series Input array. indices : sequence of int or one-dimensional np.ndarray of int Indices to be taken. axis : int, default 0 The axis over which to select values. allow_fill : bool, default False How to handle negative values in `indices`. * False: negative values in `indices` indicate positional indices from the right (the default). This is similar to :func:`numpy.take`. * True: negative values in `indices` indicate missing values. These values are set to `fill_value`. Any other negative values raise a ``ValueError``. fill_value : any, optional Fill value to use for NA-indices when `allow_fill` is True. This may be ``None``, in which case the default NA value for the type (``self.dtype.na_value``) is used. For multi-dimensional `arr`, each *element* is filled with `fill_value`. Returns ------- ndarray or ExtensionArray Same type as the input. Raises ------ IndexError When `indices` is out of bounds for the array. ValueError When the indexer contains negative values other than ``-1`` and `allow_fill` is True. Notes ----- When `allow_fill` is False, `indices` may be whatever dimensionality is accepted by NumPy for `arr`. When `allow_fill` is True, `indices` should be 1-D. See Also -------- numpy.take : Take elements from an array along an axis. Examples -------- >>> import pandas as pd With the default ``allow_fill=False``, negative numbers indicate positional indices from the right. >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1]) array([10, 10, 30]) Setting ``allow_fill=True`` will place `fill_value` in those positions. >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1], allow_fill=True) array([10., 10., nan]) >>> pd.api.extensions.take( ... np.array([10, 20, 30]), [0, 0, -1], allow_fill=True, fill_value=-10 ... ) array([ 10, 10, -10]) """ if not isinstance( arr, (np.ndarray, ABCExtensionArray, ABCIndex, ABCSeries, ABCNumpyExtensionArray), ): # GH#52981 raise TypeError( "pd.api.extensions.take requires a numpy.ndarray, ExtensionArray, " f"Index, Series, or NumpyExtensionArray got {type(arr).__name__}." ) indices = ensure_platform_int(indices) if allow_fill: # Pandas style, -1 means NA validate_indices(indices, arr.shape[axis]) # error: Argument 1 to "take_nd" has incompatible type # "ndarray[Any, Any] | ExtensionArray | Index | Series"; expected # "ndarray[Any, Any]" result = take_nd( arr, # type: ignore[arg-type] indices, axis=axis, allow_fill=True, fill_value=fill_value, ) else: # NumPy style # error: Unexpected keyword argument "axis" for "take" of "ExtensionArray" result = arr.take(indices, axis=axis) # type: ignore[call-arg,assignment] return result
Take elements from an array. Parameters ---------- arr : numpy.ndarray, ExtensionArray, Index, or Series Input array. indices : sequence of int or one-dimensional np.ndarray of int Indices to be taken. axis : int, default 0 The axis over which to select values. allow_fill : bool, default False How to handle negative values in `indices`. * False: negative values in `indices` indicate positional indices from the right (the default). This is similar to :func:`numpy.take`. * True: negative values in `indices` indicate missing values. These values are set to `fill_value`. Any other negative values raise a ``ValueError``. fill_value : any, optional Fill value to use for NA-indices when `allow_fill` is True. This may be ``None``, in which case the default NA value for the type (``self.dtype.na_value``) is used. For multi-dimensional `arr`, each *element* is filled with `fill_value`. Returns ------- ndarray or ExtensionArray Same type as the input. Raises ------ IndexError When `indices` is out of bounds for the array. ValueError When the indexer contains negative values other than ``-1`` and `allow_fill` is True. Notes ----- When `allow_fill` is False, `indices` may be whatever dimensionality is accepted by NumPy for `arr`. When `allow_fill` is True, `indices` should be 1-D. See Also -------- numpy.take : Take elements from an array along an axis. Examples -------- >>> import pandas as pd With the default ``allow_fill=False``, negative numbers indicate positional indices from the right. >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1]) array([10, 10, 30]) Setting ``allow_fill=True`` will place `fill_value` in those positions. >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1], allow_fill=True) array([10., 10., nan]) >>> pd.api.extensions.take( ... np.array([10, 20, 30]), [0, 0, -1], allow_fill=True, fill_value=-10 ... ) array([ 10, 10, -10])
python
pandas/core/algorithms.py
1,126
[ "arr", "indices", "axis", "allow_fill", "fill_value" ]
true
4
8.4
pandas-dev/pandas
47,362
numpy
false
isEmptyBindingName
function isEmptyBindingName(bindingName: SynthBindingName | undefined): boolean { if (!bindingName) { return true; } if (isSynthIdentifier(bindingName)) { return !bindingName.identifier.text; } return every(bindingName.elements, isEmptyBindingName); }
@param hasContinuation Whether another `then`, `catch`, or `finally` continuation follows the continuation to which this statement belongs. @param continuationArgName The argument name for the continuation that follows this call.
typescript
src/services/codefixes/convertToAsyncFunction.ts
889
[ "bindingName" ]
true
3
6.08
microsoft/TypeScript
107,154
jsdoc
false
add
void add(long previousBucketIndex, long currentBucketIndex) { assert currentBucketIndex > previousBucketIndex; assert previousBucketIndex >= MIN_INDEX && previousBucketIndex <= MAX_INDEX; assert currentBucketIndex <= MAX_INDEX; /* * Below is an efficient variant of the following algorithm: * for (int i=0; i<63; i++) { * if (prevIndex>>(i+1) == currIndex>>(i+1)) { * collapsedBucketCount[i]++; * break; * } * } * So we find the smallest scale reduction required to make the two buckets collapse into one. */ long bitXor = previousBucketIndex ^ currentBucketIndex; int numEqualLeadingBits = Long.numberOfLeadingZeros(bitXor); // if there are zero equal leading bits, the indices have a different sign. // Therefore right-shifting will never make the buckets combine if (numEqualLeadingBits > 0) { int requiredScaleChange = 64 - numEqualLeadingBits; collapsedBucketCount[requiredScaleChange - 1]++; } }
Adds a pair of neighboring bucket indices to track for potential merging. @param previousBucketIndex the index of the previous bucket @param currentBucketIndex the index of the current bucket
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/DownscaleStats.java
57
[ "previousBucketIndex", "currentBucketIndex" ]
void
true
3
6.72
elastic/elasticsearch
75,680
javadoc
false
forProperty
public static ItemIgnore forProperty(String name) { return new ItemIgnore(ItemType.PROPERTY, name); }
Create an ignore for a property with the given name. @param name the name @return the item ignore
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/metadata/ItemIgnore.java
64
[ "name" ]
ItemIgnore
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
_serialize_operator_extra_links
def _serialize_operator_extra_links( cls, operator_extra_links: Iterable[BaseOperatorLink] ) -> dict[str, str]: """ Serialize Operator Links. Store the "name" of the link mapped with the xcom_key which can be later used to retrieve this operator extra link from XComs. For example: ``{'link-name-1': 'xcom-key-1'}`` :param operator_extra_links: Operator Link :return: Serialized Operator Link """ return {link.name: link.xcom_key for link in operator_extra_links}
Serialize Operator Links. Store the "name" of the link mapped with the xcom_key which can be later used to retrieve this operator extra link from XComs. For example: ``{'link-name-1': 'xcom-key-1'}`` :param operator_extra_links: Operator Link :return: Serialized Operator Link
python
airflow-core/src/airflow/serialization/serialized_objects.py
1,820
[ "cls", "operator_extra_links" ]
dict[str, str]
true
1
6.56
apache/airflow
43,597
sphinx
false
equals
@Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof BloomFilter) { BloomFilter<?> that = (BloomFilter<?>) object; return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); } return false; }
Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom filters are appropriately sized to avoid saturating them. @param that The Bloom filter to combine this Bloom filter with. It is not mutated. @throws IllegalArgumentException if {@code isCompatible(that) == false} @since 15.0
java
android/guava/src/com/google/common/hash/BloomFilter.java
288
[ "object" ]
true
6
6.72
google/guava
51,352
javadoc
false
real_if_close
def real_if_close(a, tol=100): """ If input is complex with all imaginary parts close to zero, return real parts. "Close to zero" is defined as `tol` * (machine epsilon of the type for `a`). Parameters ---------- a : array_like Input array. tol : float Tolerance in machine epsilons for the complex part of the elements in the array. If the tolerance is <=1, then the absolute tolerance is used. Returns ------- out : ndarray If `a` is real, the type of `a` is used for the output. If `a` has complex elements, the returned type is float. See Also -------- real, imag, angle Notes ----- Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use 'np.finfo(float).eps' to print out the machine epsilon for floats. Examples -------- >>> import numpy as np >>> np.finfo(float).eps 2.2204460492503131e-16 # may vary >>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000) array([2.1, 5.2]) >>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000) array([2.1+4.e-13j, 5.2 + 3e-15j]) """ a = asanyarray(a) type_ = a.dtype.type if not issubclass(type_, _nx.complexfloating): return a if tol > 1: f = getlimits.finfo(type_) tol = f.eps * tol if _nx.all(_nx.absolute(a.imag) < tol): a = a.real return a
If input is complex with all imaginary parts close to zero, return real parts. "Close to zero" is defined as `tol` * (machine epsilon of the type for `a`). Parameters ---------- a : array_like Input array. tol : float Tolerance in machine epsilons for the complex part of the elements in the array. If the tolerance is <=1, then the absolute tolerance is used. Returns ------- out : ndarray If `a` is real, the type of `a` is used for the output. If `a` has complex elements, the returned type is float. See Also -------- real, imag, angle Notes ----- Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use 'np.finfo(float).eps' to print out the machine epsilon for floats. Examples -------- >>> import numpy as np >>> np.finfo(float).eps 2.2204460492503131e-16 # may vary >>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000) array([2.1, 5.2]) >>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000) array([2.1+4.e-13j, 5.2 + 3e-15j])
python
numpy/lib/_type_check_impl.py
501
[ "a", "tol" ]
false
4
7.68
numpy/numpy
31,054
numpy
false
visitArrowFunction
function visitArrowFunction(node: ArrowFunction) { let parameters: NodeArray<ParameterDeclaration>; const functionFlags = getFunctionFlags(node); return factory.updateArrowFunction( node, visitNodes(node.modifiers, visitor, isModifier), /*typeParameters*/ undefined, parameters = functionFlags & FunctionFlags.Async ? transformAsyncFunctionParameterList(node) : visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, functionFlags & FunctionFlags.Async ? transformAsyncFunctionBody(node, parameters) : visitFunctionBody(node.body, visitor, context), ); }
Visits an ArrowFunction. This function will be called when one of the following conditions are met: - The node is marked async @param node The node to visit.
typescript
src/compiler/transformers/es2017.ts
555
[ "node" ]
false
3
6.08
microsoft/TypeScript
107,154
jsdoc
false
_intersection_non_unique
def _intersection_non_unique(self, other: IntervalIndex) -> IntervalIndex: """ Used when the IntervalIndex does have some common endpoints, on either sides. Return the intersection with another IntervalIndex. Parameters ---------- other : IntervalIndex Returns ------- IntervalIndex """ # Note: this is about 3.25x faster than super()._intersection(other) # in IntervalIndexMethod.time_intersection_both_duplicate(1000) mask = np.zeros(len(self), dtype=bool) if self.hasnans and other.hasnans: first_nan_loc = np.arange(len(self))[self.isna()][0] mask[first_nan_loc] = True other_tups = set(zip(other.left, other.right, strict=True)) for i, tup in enumerate(zip(self.left, self.right, strict=True)): if tup in other_tups: mask[i] = True return self[mask]
Used when the IntervalIndex does have some common endpoints, on either sides. Return the intersection with another IntervalIndex. Parameters ---------- other : IntervalIndex Returns ------- IntervalIndex
python
pandas/core/indexes/interval.py
1,211
[ "self", "other" ]
IntervalIndex
true
5
6.24
pandas-dev/pandas
47,362
numpy
false
lastEntry
@Override public @Nullable Entry<K, V> lastEntry() { return isEmpty() ? null : entrySet().asList().get(size() - 1); }
This method returns a {@code ImmutableSortedMap}, consisting of the entries whose keys are greater than (or equal to, if {@code inclusive}) {@code fromKey}. <p>The {@link SortedMap#tailMap} documentation states that a submap of a submap throws an {@link IllegalArgumentException} if passed a {@code fromKey} less than an earlier {@code fromKey}. However, this method doesn't throw an exception in that situation, but instead keeps the original {@code fromKey}. @since 12.0
java
android/guava/src/com/google/common/collect/ImmutableSortedMap.java
1,107
[]
true
2
6.64
google/guava
51,352
javadoc
false
equals
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AutoOffsetResetStrategy that = (AutoOffsetResetStrategy) o; return type == that.type && Objects.equals(duration, that.duration); }
Return the timestamp to be used for the ListOffsetsRequest. @return the timestamp for the OffsetResetStrategy, if the strategy is EARLIEST or LATEST or duration is provided else return Optional.empty()
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AutoOffsetResetStrategy.java
137
[ "o" ]
true
5
6.4
apache/kafka
31,560
javadoc
false
getDescription
@Override protected String getDescription() { Assert.state(this.servlet != null, "Unable to return description for null servlet"); return "servlet " + getServletName(); }
Returns the {@link MultipartConfigElement multi-part configuration} to be applied or {@code null}. @return the multipart config
java
core/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletRegistrationBean.java
171
[]
String
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
vander
def vander(x, N=None, increasing=False): """ Generate a Vandermonde matrix. The columns of the output matrix are powers of the input vector. The order of the powers is determined by the `increasing` boolean argument. Specifically, when `increasing` is False, the `i`-th output column is the input vector raised element-wise to the power of ``N - i - 1``. Such a matrix with a geometric progression in each row is named for Alexandre- Theophile Vandermonde. Parameters ---------- x : array_like 1-D input array. N : int, optional Number of columns in the output. If `N` is not specified, a square array is returned (``N = len(x)``). increasing : bool, optional Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed. Returns ------- out : ndarray Vandermonde matrix. If `increasing` is False, the first column is ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is True, the columns are ``x^0, x^1, ..., x^(N-1)``. See Also -------- polynomial.polynomial.polyvander Examples -------- >>> import numpy as np >>> x = np.array([1, 2, 3, 5]) >>> N = 3 >>> np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> np.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> x = np.array([1, 2, 3, 5]) >>> np.vander(x) array([[ 1, 1, 1, 1], [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) >>> np.vander(x, increasing=True) array([[ 1, 1, 1, 1], [ 1, 2, 4, 8], [ 1, 3, 9, 27], [ 1, 5, 25, 125]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np.linalg.det(np.vander(x)) 48.000000000000043 # may vary >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48 """ x = asarray(x) if x.ndim != 1: raise ValueError("x must be a one-dimensional array or sequence.") if N is None: N = len(x) v = empty((len(x), N), dtype=promote_types(x.dtype, int)) tmp = v[:, ::-1] if not increasing else v if N > 0: tmp[:, 0] = 1 if N > 1: tmp[:, 1:] = x[:, None] multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1) return v
Generate a Vandermonde matrix. The columns of the output matrix are powers of the input vector. The order of the powers is determined by the `increasing` boolean argument. Specifically, when `increasing` is False, the `i`-th output column is the input vector raised element-wise to the power of ``N - i - 1``. Such a matrix with a geometric progression in each row is named for Alexandre- Theophile Vandermonde. Parameters ---------- x : array_like 1-D input array. N : int, optional Number of columns in the output. If `N` is not specified, a square array is returned (``N = len(x)``). increasing : bool, optional Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed. Returns ------- out : ndarray Vandermonde matrix. If `increasing` is False, the first column is ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is True, the columns are ``x^0, x^1, ..., x^(N-1)``. See Also -------- polynomial.polynomial.polyvander Examples -------- >>> import numpy as np >>> x = np.array([1, 2, 3, 5]) >>> N = 3 >>> np.vander(x, N) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> np.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1, 1, 1], [ 4, 2, 1], [ 9, 3, 1], [25, 5, 1]]) >>> x = np.array([1, 2, 3, 5]) >>> np.vander(x) array([[ 1, 1, 1, 1], [ 8, 4, 2, 1], [ 27, 9, 3, 1], [125, 25, 5, 1]]) >>> np.vander(x, increasing=True) array([[ 1, 1, 1, 1], [ 1, 2, 4, 8], [ 1, 3, 9, 27], [ 1, 5, 25, 125]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np.linalg.det(np.vander(x)) 48.000000000000043 # may vary >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48
python
numpy/lib/_twodim_base_impl.py
561
[ "x", "N", "increasing" ]
false
6
7.6
numpy/numpy
31,054
numpy
false
get_lb_policy
def get_lb_policy(policy_name: str, policy_args: dict[str, Any]) -> Policy: """ Create load balancing policy. :param policy_name: Name of the policy to use. :param policy_args: Parameters for the policy. """ if policy_name == "DCAwareRoundRobinPolicy": local_dc = policy_args.get("local_dc", "") used_hosts_per_remote_dc = int(policy_args.get("used_hosts_per_remote_dc", 0)) return DCAwareRoundRobinPolicy(local_dc, used_hosts_per_remote_dc) if policy_name == "WhiteListRoundRobinPolicy": hosts = policy_args.get("hosts") if not hosts: raise ValueError("Hosts must be specified for WhiteListRoundRobinPolicy") return WhiteListRoundRobinPolicy(hosts) if policy_name == "TokenAwarePolicy": allowed_child_policies = ( "RoundRobinPolicy", "DCAwareRoundRobinPolicy", "WhiteListRoundRobinPolicy", ) child_policy_name = policy_args.get("child_load_balancing_policy", "RoundRobinPolicy") child_policy_args = policy_args.get("child_load_balancing_policy_args", {}) if child_policy_name not in allowed_child_policies: return TokenAwarePolicy(RoundRobinPolicy()) child_policy = CassandraHook.get_lb_policy(child_policy_name, child_policy_args) return TokenAwarePolicy(child_policy) # Fallback to default RoundRobinPolicy return RoundRobinPolicy()
Create load balancing policy. :param policy_name: Name of the policy to use. :param policy_args: Parameters for the policy.
python
providers/apache/cassandra/src/airflow/providers/apache/cassandra/hooks/cassandra.py
142
[ "policy_name", "policy_args" ]
Policy
true
6
7.04
apache/airflow
43,597
sphinx
false
shell_command
def shell_command() -> None: """Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application. """ import code banner = ( f"Python {sys.version} on {sys.platform}\n" f"App: {current_app.import_name}\n" f"Instance: {current_app.instance_path}" ) ctx: dict[str, t.Any] = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get("PYTHONSTARTUP") if startup and os.path.isfile(startup): with open(startup) as f: eval(compile(f.read(), startup, "exec"), ctx) ctx.update(current_app.make_shell_context()) # Site, customize, or startup script can set a hook to call when # entering interactive mode. The default one sets up readline with # tab and history completion. interactive_hook = getattr(sys, "__interactivehook__", None) if interactive_hook is not None: try: import readline from rlcompleter import Completer except ImportError: pass else: # rlcompleter uses __main__.__dict__ by default, which is # flask.__main__. Use the shell context instead. readline.set_completer(Completer(ctx).complete) interactive_hook() code.interact(banner=banner, local=ctx)
Run an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to its configuration. This is useful for executing small snippets of management code without having to manually configure the application.
python
src/flask/cli.py
1,001
[]
None
true
5
7.04
pallets/flask
70,946
unknown
false
readUnsignedShort
@CanIgnoreReturnValue // to skip some bytes @Override public int readUnsignedShort() throws IOException { byte b1 = readAndCheckByte(); byte b2 = readAndCheckByte(); return Ints.fromBytes((byte) 0, (byte) 0, b2, b1); }
Reads an unsigned {@code short} as specified by {@link DataInputStream#readUnsignedShort()}, except using little-endian byte order. @return the next two bytes of the input stream, interpreted as an unsigned 16-bit integer in little-endian byte order @throws IOException if an I/O error occurs
java
android/guava/src/com/google/common/io/LittleEndianDataInputStream.java
97
[]
true
1
6.08
google/guava
51,352
javadoc
false
_alert_malformed
def _alert_malformed(self, msg: str, row_num: int) -> None: """ Alert a user about a malformed row, depending on value of `self.on_bad_lines` enum. If `self.on_bad_lines` is ERROR, the alert will be `ParserError`. If `self.on_bad_lines` is WARN, the alert will be printed out. Parameters ---------- msg: str The error message to display. row_num: int The row number where the parsing error occurred. Because this row number is displayed, we 1-index, even though we 0-index internally. """ if self.on_bad_lines == self.BadLineHandleMethod.ERROR: raise ParserError(msg) if self.on_bad_lines == self.BadLineHandleMethod.WARN or callable( self.on_bad_lines ): warnings.warn( f"Skipping line {row_num}: {msg}\n", ParserWarning, stacklevel=find_stack_level(), )
Alert a user about a malformed row, depending on value of `self.on_bad_lines` enum. If `self.on_bad_lines` is ERROR, the alert will be `ParserError`. If `self.on_bad_lines` is WARN, the alert will be printed out. Parameters ---------- msg: str The error message to display. row_num: int The row number where the parsing error occurred. Because this row number is displayed, we 1-index, even though we 0-index internally.
python
pandas/io/parsers/python_parser.py
946
[ "self", "msg", "row_num" ]
None
true
4
6.72
pandas-dev/pandas
47,362
numpy
false
numberToString
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Number must be non-null"); } double doubleValue = number.doubleValue(); JSON.checkDouble(doubleValue); // the original returns "-0" instead of "-0.0" for negative zero if (number.equals(NEGATIVE_ZERO)) { return "-0"; } long longValue = number.longValue(); if (doubleValue == longValue) { return Long.toString(longValue); } return number.toString(); }
Encodes the number as a JSON string. @param number a finite value. May not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}. @return the encoded value @throws JSONException if an error occurs
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONObject.java
743
[ "number" ]
String
true
4
8.08
spring-projects/spring-boot
79,428
javadoc
false
documentationOf
public String documentationOf(String key) { ConfigDef.ConfigKey configKey = definition.configKeys().get(key); if (configKey == null) return null; return configKey.documentation; }
Called directly after user configs got parsed (and thus default values got set). This allows to change default values for "secondary defaults" if required. @param parsedValues unmodifiable map of current configuration @return a map of updates that should be applied to the configuration (will be validated to prevent bad updates)
java
clients/src/main/java/org/apache/kafka/common/config/AbstractConfig.java
222
[ "key" ]
String
true
2
7.6
apache/kafka
31,560
javadoc
false
_formatter
def _formatter(self, boxed: bool = False) -> Callable[[Any], str | None]: """ Formatting function for scalar values. This is used in the default '__repr__'. The returned formatting function receives instances of your scalar type. Parameters ---------- boxed : bool, default False An indicated for whether or not your array is being printed within a Series, DataFrame, or Index (True), or just by itself (False). This may be useful if you want scalar values to appear differently within a Series versus on its own (e.g. quoted or not). Returns ------- Callable[[Any], str] A callable that gets instances of the scalar type and returns a string. By default, :func:`repr` is used when ``boxed=False`` and :func:`str` is used when ``boxed=True``. See Also -------- api.extensions.ExtensionArray._concat_same_type : Concatenate multiple array of this dtype. api.extensions.ExtensionArray._explode : Transform each element of list-like to a row. api.extensions.ExtensionArray._from_factorized : Reconstruct an ExtensionArray after factorization. api.extensions.ExtensionArray._from_sequence : Construct a new ExtensionArray from a sequence of scalars. Examples -------- >>> class MyExtensionArray(pd.arrays.NumpyExtensionArray): ... def _formatter(self, boxed=False): ... return lambda x: "*" + str(x) + "*" >>> MyExtensionArray(np.array([1, 2, 3, 4])) <MyExtensionArray> [*1*, *2*, *3*, *4*] Length: 4, dtype: int64 """ if boxed: return str return repr
Formatting function for scalar values. This is used in the default '__repr__'. The returned formatting function receives instances of your scalar type. Parameters ---------- boxed : bool, default False An indicated for whether or not your array is being printed within a Series, DataFrame, or Index (True), or just by itself (False). This may be useful if you want scalar values to appear differently within a Series versus on its own (e.g. quoted or not). Returns ------- Callable[[Any], str] A callable that gets instances of the scalar type and returns a string. By default, :func:`repr` is used when ``boxed=False`` and :func:`str` is used when ``boxed=True``. See Also -------- api.extensions.ExtensionArray._concat_same_type : Concatenate multiple array of this dtype. api.extensions.ExtensionArray._explode : Transform each element of list-like to a row. api.extensions.ExtensionArray._from_factorized : Reconstruct an ExtensionArray after factorization. api.extensions.ExtensionArray._from_sequence : Construct a new ExtensionArray from a sequence of scalars. Examples -------- >>> class MyExtensionArray(pd.arrays.NumpyExtensionArray): ... def _formatter(self, boxed=False): ... return lambda x: "*" + str(x) + "*" >>> MyExtensionArray(np.array([1, 2, 3, 4])) <MyExtensionArray> [*1*, *2*, *3*, *4*] Length: 4, dtype: int64
python
pandas/core/arrays/base.py
2,032
[ "self", "boxed" ]
Callable[[Any], str | None]
true
2
7.84
pandas-dev/pandas
47,362
numpy
false
_apply_rule
def _apply_rule(self, dates: DatetimeIndex) -> DatetimeIndex: """ Apply the given offset/observance to a DatetimeIndex of dates. Parameters ---------- dates : DatetimeIndex Dates to apply the given offset/observance rule Returns ------- Dates with rules applied """ if dates.empty: return dates.copy() if self.observance is not None: return dates.map(lambda d: self.observance(d)) if self.offset is not None: if not isinstance(self.offset, list): offsets = [self.offset] else: offsets = self.offset for offset in offsets: # if we are adding a non-vectorized value # ignore the PerformanceWarnings: with warnings.catch_warnings(): warnings.simplefilter("ignore", PerformanceWarning) dates += offset return dates
Apply the given offset/observance to a DatetimeIndex of dates. Parameters ---------- dates : DatetimeIndex Dates to apply the given offset/observance rule Returns ------- Dates with rules applied
python
pandas/tseries/holiday.py
396
[ "self", "dates" ]
DatetimeIndex
true
7
6.24
pandas-dev/pandas
47,362
numpy
false
resolveItemDeprecation
ItemDeprecation resolveItemDeprecation(Element element) { AnnotationMirror annotation = getAnnotation(element, this.deprecatedConfigurationPropertyAnnotation); String reason = null; String replacement = null; String since = null; if (annotation != null) { reason = getAnnotationElementStringValue(annotation, "reason"); replacement = getAnnotationElementStringValue(annotation, "replacement"); since = getAnnotationElementStringValue(annotation, "since"); } return new ItemDeprecation(reason, replacement, since); }
Resolve the {@link SourceMetadata} for the specified property. @param field the field of the property (can be {@code null}) @param getter the getter of the property (can be {@code null}) @return the {@link SourceMetadata} for the specified property
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataGenerationEnvironment.java
200
[ "element" ]
ItemDeprecation
true
2
7.76
spring-projects/spring-boot
79,428
javadoc
false
readRecords
default MemoryRecords readRecords(int length) { if (length < 0) { // no records return null; } else { ByteBuffer recordsBuffer = readByteBuffer(length); return MemoryRecords.readableRecords(recordsBuffer); } }
Returns a new Readable object whose content will be shared with this object. <br> The content of the new Readable object will start at this Readable's current position. The two Readable position will be independent, so read from one will not impact the other.
java
clients/src/main/java/org/apache/kafka/common/protocol/Readable.java
65
[ "length" ]
MemoryRecords
true
2
6
apache/kafka
31,560
javadoc
false
reScanLessThanToken
function reScanLessThanToken(): SyntaxKind { if (token === SyntaxKind.LessThanLessThanToken) { pos = tokenStart + 1; return token = SyntaxKind.LessThanToken; } return token; }
Unconditionally back up and scan a template expression portion.
typescript
src/compiler/scanner.ts
3,673
[]
true
2
6.4
microsoft/TypeScript
107,154
jsdoc
false
getTeredoInfo
public static TeredoInfo getTeredoInfo(Inet6Address ip) { checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip)); byte[] bytes = ip.getAddress(); Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8)); int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff; // Teredo obfuscates the mapped client port, per section 4 of the RFC. int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff; byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16); for (int i = 0; i < clientBytes.length; i++) { // Teredo obfuscates the mapped client IP, per section 4 of the RFC. clientBytes[i] = (byte) ~clientBytes[i]; } Inet4Address client = getInet4Address(clientBytes); return new TeredoInfo(server, client, port, flags); }
Returns the Teredo information embedded in a Teredo address. @param ip {@link Inet6Address} to be examined for embedded Teredo information @return extracted {@code TeredoInfo} @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
java
android/guava/src/com/google/common/net/InetAddresses.java
823
[ "ip" ]
TeredoInfo
true
2
7.44
google/guava
51,352
javadoc
false
authenticationException
@Override public AuthenticationException authenticationException(Node node) { return connectionStates.authenticationException(node.idString()); }
Check if authentication to this node has failed, based on the connection state. Authentication failures are propagated without any retries. @param node the node to check @return an AuthenticationException iff authentication has failed, null otherwise
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
505
[ "node" ]
AuthenticationException
true
1
6
apache/kafka
31,560
javadoc
false
newConcurrentHashSet
public static <E> Set<E> newConcurrentHashSet() { return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>()); }
Creates a thread-safe set backed by a hash map. The set is backed by a {@link ConcurrentHashMap} instance, and thus carries the same concurrency guarantees. <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The set is serializable. @return a new, empty thread-safe {@code Set} @since 15.0
java
android/guava/src/com/google/common/collect/Sets.java
279
[]
true
1
6.8
google/guava
51,352
javadoc
false
validate
@Override public void validate() throws BeanDefinitionValidationException { super.validate(); if (this.parentName == null) { throw new BeanDefinitionValidationException("'parentName' must be set in ChildBeanDefinition"); } }
Create a new ChildBeanDefinition as deep copy of the given bean definition. @param original the original bean definition to copy from
java
spring-beans/src/main/java/org/springframework/beans/factory/support/ChildBeanDefinition.java
143
[]
void
true
2
6.4
spring-projects/spring-framework
59,386
javadoc
false
create_replication_group
def create_replication_group(self, config: dict) -> dict: """ Create a Redis (cluster mode disabled) or a Redis (cluster mode enabled) replication group. .. seealso:: - :external+boto3:py:meth:`ElastiCache.Client.create_replication_group` :param config: Configuration for creating the replication group :return: Response from ElastiCache create replication group API """ return self.conn.create_replication_group(**config)
Create a Redis (cluster mode disabled) or a Redis (cluster mode enabled) replication group. .. seealso:: - :external+boto3:py:meth:`ElastiCache.Client.create_replication_group` :param config: Configuration for creating the replication group :return: Response from ElastiCache create replication group API
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/elasticache_replication_group.py
63
[ "self", "config" ]
dict
true
1
6.08
apache/airflow
43,597
sphinx
false
atleast_3d
def atleast_3d(*arys): """ View inputs as arrays with at least three dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape ``(N,)`` becomes a view of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> import numpy as np >>> np.atleast_3d(3.0) array([[[3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape (1, 3, 1) >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape (4, 3, 1) >>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print(arr, arr.shape) # doctest: +SKIP ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2) """ res = [] for ary in arys: ary = asanyarray(ary) if ary.ndim == 0: result = ary.reshape(1, 1, 1) elif ary.ndim == 1: result = ary[_nx.newaxis, :, _nx.newaxis] elif ary.ndim == 2: result = ary[:, :, _nx.newaxis] else: result = ary res.append(result) if len(res) == 1: return res[0] else: return tuple(res)
View inputs as arrays with at least three dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape ``(N,)`` becomes a view of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> import numpy as np >>> np.atleast_3d(3.0) array([[[3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape (1, 3, 1) >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape (4, 3, 1) >>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print(arr, arr.shape) # doctest: +SKIP ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2)
python
numpy/_core/shape_base.py
138
[]
false
8
7.44
numpy/numpy
31,054
numpy
false
getMethodObject
public static Method getMethodObject(final Class<?> cls, final String name, final Class<?>... parameterTypes) { try { return name != null && cls != null ? cls.getMethod(name, parameterTypes) : null; } catch (final NoSuchMethodException | SecurityException e) { return null; } }
Gets a Method, or {@code null} if a checked {@link Class#getMethod(String, Class...) } exception is thrown. @param cls Receiver for {@link Class#getMethod(String, Class...)}. @param name the name of the method. @param parameterTypes the list of parameters. @return a Method or {@code null}. @see SecurityManager#checkPermission @see Class#getMethod(String, Class...) @since 3.15.0
java
src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
415
[ "cls", "name" ]
Method
true
4
7.6
apache/commons-lang
2,896
javadoc
false
baseDelay
function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); }
The base implementation of `_.delay` and `_.defer` which accepts `args` to provide to `func`. @private @param {Function} func The function to delay. @param {number} wait The number of milliseconds to delay invocation. @param {Array} args The arguments to provide to `func`. @returns {number|Object} Returns the timer id or timeout object.
javascript
lodash.js
2,788
[ "func", "wait", "args" ]
false
2
6.24
lodash/lodash
61,490
jsdoc
false
awaitTermination
public ThreadPoolTaskSchedulerBuilder awaitTermination(boolean awaitTermination) { return new ThreadPoolTaskSchedulerBuilder(this.poolSize, awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix, this.taskDecorator, this.customizers); }
Set whether the executor should wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue. @param awaitTermination whether the executor needs to wait for the tasks to complete on shutdown @return a new builder instance @see #awaitTerminationPeriod(Duration)
java
core/spring-boot/src/main/java/org/springframework/boot/task/ThreadPoolTaskSchedulerBuilder.java
92
[ "awaitTermination" ]
ThreadPoolTaskSchedulerBuilder
true
1
6.32
spring-projects/spring-boot
79,428
javadoc
false
unregisterMetricFromSubscription
@Override public void unregisterMetricFromSubscription(KafkaMetric metric) { if (!metrics().containsKey(metric.metricName())) { clientTelemetryReporter.ifPresent(reporter -> reporter.metricRemoval(metric)); } else { log.debug("Skipping unregistration for metric {}. Existing producer metrics cannot be removed.", metric.metricName()); } }
Remove the provided application metric for subscription. This metric is removed from this client's metrics and will not be available for subscription any longer. Executing this method with a metric that has not been registered is a benign operation and does not result in any action taken (no-op). @param metric The application metric to remove
java
clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java
1,424
[ "metric" ]
void
true
2
7.04
apache/kafka
31,560
javadoc
false
waitForUninterruptibly
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) { long timeoutNanos = toSafeNanos(time, unit); if (!((guard.monitor == this) && lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (guard.isSatisfied()) { return true; } boolean signalBeforeWaiting = true; long startTime = initNanoTime(timeoutNanos); boolean interrupted = Thread.interrupted(); try { for (long remainingNanos = timeoutNanos; ; ) { try { return awaitNanos(guard, remainingNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; if (guard.isSatisfied()) { return true; } signalBeforeWaiting = false; remainingNanos = remainingNanos(startTime, timeoutNanos); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
Waits for the guard to be satisfied. Waits at most the given time. May be called only by a thread currently occupying this monitor. @return whether the guard is now satisfied
java
android/guava/src/com/google/common/util/concurrent/Monitor.java
906
[ "guard", "time", "unit" ]
true
8
7.04
google/guava
51,352
javadoc
false
unwrapDefaultListableBeanFactory
private static @Nullable DefaultListableBeanFactory unwrapDefaultListableBeanFactory(BeanDefinitionRegistry registry) { if (registry instanceof DefaultListableBeanFactory dlbf) { return dlbf; } else if (registry instanceof GenericApplicationContext gac) { return gac.getDefaultListableBeanFactory(); } else { return null; } }
Register all relevant annotation post processors in the given registry. @param registry the registry to operate on @param source the configuration source element (already extracted) that this registration was triggered from. May be {@code null}. @return a Set of BeanDefinitionHolders, containing all bean definitions that have actually been registered by this call
java
spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java
215
[ "registry" ]
DefaultListableBeanFactory
true
3
7.44
spring-projects/spring-framework
59,386
javadoc
false
close
public void close(final Duration timeout) { closer.close( () -> Utils.closeQuietly(() -> networkThread.close(timeout), "consumer network thread"), () -> log.warn("The application event handler was already closed") ); }
Add a {@link CompletableApplicationEvent} to the handler. The method blocks waiting for the result, and will return the result value upon successful completion; otherwise throws an error. <p/> See {@link ConsumerUtils#getResult(Future)} for more details. @param event A {@link CompletableApplicationEvent} created by the polling thread @return Value that is the result of the event @param <T> Type of return value of the event
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventHandler.java
152
[ "timeout" ]
void
true
1
6.72
apache/kafka
31,560
javadoc
false
lastIndexOfIgnoreCase
@Deprecated public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { return Strings.CI.lastIndexOf(str, searchStr); }
Case in-sensitive find of the last index within a CharSequence. <p> A {@code null} CharSequence will return {@code -1}. A negative start position returns {@code -1}. An empty ("") search CharSequence always matches unless the start position is negative. A start position greater than the string length searches the whole string. </p> <pre> StringUtils.lastIndexOfIgnoreCase(null, *) = -1 StringUtils.lastIndexOfIgnoreCase(*, null) = -1 StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7 StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5 StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4 </pre> @param str the CharSequence to check, may be null. @param searchStr the CharSequence to find, may be null. @return the first index of the search CharSequence, -1 if no match or {@code null} string input. @since 2.5 @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence) @deprecated Use {@link Strings#lastIndexOf(CharSequence, CharSequence) Strings.CI.lastIndexOf(CharSequence, CharSequence)}.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
4,958
[ "str", "searchStr" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
lock
def lock(self) -> locks._LockProtocol: """Get a context manager for acquiring the file lock. Uses file locking to ensure thread safety across processes. Args: timeout: Optional timeout in seconds (float) for acquiring the file lock. Returns: A callable that returns a context manager for the file lock. """ def _lock_with_timeout( timeout: float | None = None, ) -> locks._LockContextManager: return locks._acquire_flock_with_timeout(self._flock, timeout) return _lock_with_timeout
Get a context manager for acquiring the file lock. Uses file locking to ensure thread safety across processes. Args: timeout: Optional timeout in seconds (float) for acquiring the file lock. Returns: A callable that returns a context manager for the file lock.
python
torch/_inductor/runtime/caching/implementations.py
252
[ "self" ]
locks._LockProtocol
true
1
6.72
pytorch/pytorch
96,034
google
false