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
withMaximumThrowableDepth
public StandardStackTracePrinter withMaximumThrowableDepth(int maximumThrowableDepth) { Assert.isTrue(maximumThrowableDepth > 0, "'maximumThrowableDepth' must be positive"); return withFrameFilter((index, element) -> index < maximumThrowableDepth); }
Return a new {@link StandardStackTracePrinter} from this one that filter frames (including caused and suppressed) deeper then the specified maximum. @param maximumThrowableDepth the maximum throwable depth @return a new {@link StandardStackTracePrinter} instance
java
core/spring-boot/src/main/java/org/springframework/boot/logging/StandardStackTracePrinter.java
190
[ "maximumThrowableDepth" ]
StandardStackTracePrinter
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
bind
function bind(node: Node | undefined): void { if (!node) { return; } setParent(node, parent); if (tracing) (node as TracingNode).tracingPath = file.path; const saveInStrictMode = inStrictMode; // Even though in the AST the jsdoc @typedef node belongs to the current node, // its symbol might be in the same scope with the current node's symbol. Consider: // // /** @typedef {string | number} MyType */ // function foo(); // // Here the current node is "foo", which is a container, but the scope of "MyType" should // not be inside "foo". Therefore we always bind @typedef before bind the parent node, // and skip binding this tag later when binding all the other jsdoc tags. // First we bind declaration nodes to a symbol if possible. We'll both create a symbol // and then potentially add the symbol to an appropriate symbol table. Possible // destination symbol tables are: // // 1) The 'exports' table of the current container's symbol. // 2) The 'members' table of the current container's symbol. // 3) The 'locals' table of the current container. // // However, not all symbols will end up in any of these tables. 'Anonymous' symbols // (like TypeLiterals for example) will not be put in any table. bindWorker(node); // Then we recurse into the children of the node to bind them as well. For certain // symbols we do specialized work when we recurse. For example, we'll keep track of // the current 'container' node when it changes. This helps us know which symbol table // a local should go into for example. Since terminal nodes are known not to have // children, as an optimization we don't process those. if (node.kind > SyntaxKind.LastToken) { const saveParent = parent; parent = node; const containerFlags = getContainerFlags(node); if (containerFlags === ContainerFlags.None) { bindChildren(node); } else { bindContainer(node as HasContainerFlags, containerFlags); } parent = saveParent; } else { const saveParent = parent; if (node.kind === SyntaxKind.EndOfFileToken) parent = node; bindJSDoc(node); parent = saveParent; } inStrictMode = saveInStrictMode; }
Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. @param symbolTable - The symbol table which node will be added to. @param parent - node's parent declaration. @param node - The declaration to be added to the symbol table @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
typescript
src/compiler/binder.ts
2,750
[ "node" ]
true
8
6.8
microsoft/TypeScript
107,154
jsdoc
false
_update_mean_variance
def _update_mean_variance(n_past, mu, var, X, sample_weight=None): """Compute online update of Gaussian mean and variance. Given starting sample count, mean, and variance, a new set of points X, and optionally sample weights, return the updated mean and variance. (NB - each dimension (column) in X is treated as independent -- you get variance, not covariance). Can take scalar mean and variance, or vector mean and variance to simultaneously update a number of independent Gaussians. See Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque: http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf Parameters ---------- n_past : int Number of samples represented in old mean and variance. If sample weights were given, this should contain the sum of sample weights represented in old mean and variance. mu : array-like of shape (number of Gaussians,) Means for Gaussians in original set. var : array-like of shape (number of Gaussians,) Variances for Gaussians in original set. sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- total_mu : array-like of shape (number of Gaussians,) Updated mean for each Gaussian over the combined set. total_var : array-like of shape (number of Gaussians,) Updated variance for each Gaussian over the combined set. """ xp, _ = get_namespace(X) if X.shape[0] == 0: return mu, var # Compute (potentially weighted) mean and variance of new datapoints if sample_weight is not None: n_new = float(xp.sum(sample_weight)) if np.isclose(n_new, 0.0): return mu, var new_mu = _average(X, axis=0, weights=sample_weight, xp=xp) new_var = _average((X - new_mu) ** 2, axis=0, weights=sample_weight, xp=xp) else: n_new = X.shape[0] new_var = xp.var(X, axis=0) new_mu = xp.mean(X, axis=0) if n_past == 0: return new_mu, new_var n_total = float(n_past + n_new) # Combine mean of old and new data, taking into consideration # (weighted) number of observations total_mu = (n_new * new_mu + n_past * mu) / n_total # Combine variance of old and new data, taking into consideration # (weighted) number of observations. This is achieved by combining # the sum-of-squared-differences (ssd) old_ssd = n_past * var new_ssd = n_new * new_var total_ssd = old_ssd + new_ssd + (n_new * n_past / n_total) * (mu - new_mu) ** 2 total_var = total_ssd / n_total return total_mu, total_var
Compute online update of Gaussian mean and variance. Given starting sample count, mean, and variance, a new set of points X, and optionally sample weights, return the updated mean and variance. (NB - each dimension (column) in X is treated as independent -- you get variance, not covariance). Can take scalar mean and variance, or vector mean and variance to simultaneously update a number of independent Gaussians. See Stanford CS tech report STAN-CS-79-773 by Chan, Golub, and LeVeque: http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf Parameters ---------- n_past : int Number of samples represented in old mean and variance. If sample weights were given, this should contain the sum of sample weights represented in old mean and variance. mu : array-like of shape (number of Gaussians,) Means for Gaussians in original set. var : array-like of shape (number of Gaussians,) Variances for Gaussians in original set. sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- total_mu : array-like of shape (number of Gaussians,) Updated mean for each Gaussian over the combined set. total_var : array-like of shape (number of Gaussians,) Updated variance for each Gaussian over the combined set.
python
sklearn/naive_bayes.py
288
[ "n_past", "mu", "var", "X", "sample_weight" ]
false
6
6
scikit-learn/scikit-learn
64,340
numpy
false
handleUnsupportedVersionException
boolean handleUnsupportedVersionException(UnsupportedVersionException exception) { return false; }
Handle an UnsupportedVersionException. @param exception The exception. @return True if the exception can be handled; false otherwise.
java
clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
995
[ "exception" ]
true
1
6.16
apache/kafka
31,560
javadoc
false
of
static ApplicationContextFactory of(Supplier<ConfigurableApplicationContext> supplier) { return (webApplicationType) -> supplier.get(); }
Creates an {@code ApplicationContextFactory} that will create contexts by calling the given {@link Supplier}. @param supplier the context supplier, for example {@code AnnotationConfigApplicationContext::new} @return the factory that will instantiate the context class
java
core/spring-boot/src/main/java/org/springframework/boot/ApplicationContextFactory.java
99
[ "supplier" ]
ApplicationContextFactory
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
toIntStream
public IntStream toIntStream() { return IntStream.rangeClosed(getMinimum(), getMaximum()); }
Returns a sequential ordered {@code IntStream} from {@link #getMinimum()} (inclusive) to {@link #getMaximum()} (inclusive) by an incremental step of {@code 1}. @return a sequential {@code IntStream} for the range of {@code int} elements @since 3.18.0
java
src/main/java/org/apache/commons/lang3/IntegerRange.java
118
[]
IntStream
true
1
6.32
apache/commons-lang
2,896
javadoc
false
containsTokenWithValue
static boolean containsTokenWithValue(final Token[] tokens, final Object value) { return Stream.of(tokens).anyMatch(token -> token.getValue() == value); }
Helper method to determine if a set of tokens contain a value @param tokens set to look in @param value to look for @return boolean {@code true} if contained
java
src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java
98
[ "tokens", "value" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
outsideOf
public static NumericEntityEscaper outsideOf(final int codePointLow, final int codePointHigh) { return new NumericEntityEscaper(codePointLow, codePointHigh, false); }
Constructs a {@link NumericEntityEscaper} outside of the specified values (exclusive). @param codePointLow below which to escape. @param codePointHigh above which to escape. @return the newly created {@link NumericEntityEscaper} instance.
java
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityEscaper.java
69
[ "codePointLow", "codePointHigh" ]
NumericEntityEscaper
true
1
6.16
apache/commons-lang
2,896
javadoc
false
compareCaseLowerFirst
function compareCaseLowerFirst(one: string, other: string): number { if (startsWithLower(one) && startsWithUpper(other)) { return -1; } return (startsWithUpper(one) && startsWithLower(other)) ? 1 : 0; }
Compares the case of the provided strings - lowercase before uppercase @returns ```text -1 if one is lowercase and other is uppercase 1 if one is uppercase and other is lowercase 0 otherwise ```
typescript
src/vs/base/common/comparers.ts
241
[ "one", "other" ]
true
5
7.52
microsoft/vscode
179,840
jsdoc
false
get_workflow_run_info
def get_workflow_run_info(run_id: str, repo: str, fields: str) -> dict: """ Get the workflow information for a specific run ID and return the specified fields. :param run_id: The ID of the workflow run to check. :param repo: Workflow repository example: 'apache/airflow' :param fields: Comma-separated fields to retrieve from the workflow run to fetch. eg: "status,conclusion,name,jobs" """ make_sure_gh_is_installed() command = ["gh", "run", "view", run_id, "--json", fields, "--repo", repo] result = run_command(command, capture_output=True, check=False) if result.returncode != 0: get_console().print(f"[red]Error fetching workflow run status: {result.stderr}[/red]") sys.exit(1) return json.loads(result.stdout.strip())
Get the workflow information for a specific run ID and return the specified fields. :param run_id: The ID of the workflow run to check. :param repo: Workflow repository example: 'apache/airflow' :param fields: Comma-separated fields to retrieve from the workflow run to fetch. eg: "status,conclusion,name,jobs"
python
dev/breeze/src/airflow_breeze/utils/gh_workflow_utils.py
131
[ "run_id", "repo", "fields" ]
dict
true
2
6.72
apache/airflow
43,597
sphinx
false
_check_indexing_method
def _check_indexing_method( self, method: str_t | None, limit: int | None = None, tolerance=None, ) -> None: """ Raise if we have a get_indexer `method` that is not supported or valid. """ if method not in [None, "bfill", "backfill", "pad", "ffill", "nearest"]: # in practice the clean_reindex_fill_method call would raise # before we get here raise ValueError("Invalid fill method") # pragma: no cover if self._is_multi: if method == "nearest": raise NotImplementedError( "method='nearest' not implemented yet " "for MultiIndex; see GitHub issue 9365" ) if method in ("pad", "backfill"): if tolerance is not None: raise NotImplementedError( "tolerance not implemented yet for MultiIndex" ) if isinstance(self.dtype, (IntervalDtype, CategoricalDtype)): # GH#37871 for now this is only for IntervalIndex and CategoricalIndex if method is not None: raise NotImplementedError( f"method {method} not yet implemented for {type(self).__name__}" ) if method is None: if tolerance is not None: raise ValueError( "tolerance argument only valid if doing pad, " "backfill or nearest reindexing" ) if limit is not None: raise ValueError( "limit argument only valid if doing pad, " "backfill or nearest reindexing" )
Raise if we have a get_indexer `method` that is not supported or valid.
python
pandas/core/indexes/base.py
3,842
[ "self", "method", "limit", "tolerance" ]
None
true
11
6
pandas-dev/pandas
47,362
unknown
false
hashCode
@Override public int hashCode() { // diverge from the original, which doesn't implement hashCode return this.values.hashCode(); }
Encodes this array as a human-readable JSON string for debugging, such as: <pre> [ 94043, 90210 ]</pre> @param indentSpaces the number of spaces to indent for each level of nesting. @return a human-readable JSON string of this array @throws JSONException if processing of json failed
java
cli/spring-boot-cli/src/json-shade/java/org/springframework/boot/cli/json/JSONArray.java
663
[]
true
1
6.72
spring-projects/spring-boot
79,428
javadoc
false
registerBean
<T> String registerBean(Class<T> beanClass, Consumer<Spec<T>> customizer);
Register a bean from the given class, customizing it with the customizer callback. The bean will be instantiated using the supplier that can be configured in the customizer callback, or will be tentatively instantiated with its {@link BeanUtils#getResolvableConstructor resolvable constructor} otherwise. <p>For registering a bean with a generic type, consider {@link #registerBean(ParameterizedTypeReference, Consumer)}. @param beanClass the class of the bean @param customizer the callback to customize other bean properties than the name @return the generated bean name
java
spring-beans/src/main/java/org/springframework/beans/factory/BeanRegistry.java
87
[ "beanClass", "customizer" ]
String
true
1
6
spring-projects/spring-framework
59,386
javadoc
false
getAllDecoratorsOfProperty
function getAllDecoratorsOfProperty(property: PropertyDeclaration): AllDecorators | undefined { const decorators = getDecorators(property); if (!some(decorators)) { return undefined; } return { decorators }; }
Gets an AllDecorators object containing the decorators for the property. @param property The class property member.
typescript
src/compiler/transformers/utilities.ts
781
[ "property" ]
true
2
6.08
microsoft/TypeScript
107,154
jsdoc
false
read_table
def read_table( self, table_name: str, index_col: str | list[str] | None = None, coerce_float: bool = True, parse_dates=None, columns=None, schema: str | None = None, chunksize: int | None = None, dtype_backend: DtypeBackend | Literal["numpy"] = "numpy", ) -> DataFrame | Iterator[DataFrame]: """ Read SQL database table into a DataFrame. Parameters ---------- table_name : str Name of SQL table in database. coerce_float : bool, default True Raises NotImplementedError parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg}``, where the arg corresponds to the keyword arguments of :func:`pandas.to_datetime`. Especially useful with databases without native Datetime support, such as SQLite. columns : list, default: None List of column names to select from SQL table. schema : string, default None Name of SQL schema in database to query (if database flavor supports this). If specified, this overwrites the default schema of the SQL database object. chunksize : int, default None Raises NotImplementedError dtype_backend : {'numpy_nullable', 'pyarrow'} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame` .. versionadded:: 2.0 Returns ------- DataFrame See Also -------- pandas.read_sql_table SQLDatabase.read_query """ if coerce_float is not True: raise NotImplementedError( "'coerce_float' is not implemented for ADBC drivers" ) if chunksize: raise NotImplementedError("'chunksize' is not implemented for ADBC drivers") if columns: if index_col: index_select = maybe_make_list(index_col) else: index_select = [] to_select = index_select + columns select_list = ", ".join(f'"{x}"' for x in to_select) else: select_list = "*" if schema: stmt = f"SELECT {select_list} FROM {schema}.{table_name}" else: stmt = f"SELECT {select_list} FROM {table_name}" with self.execute(stmt) as cur: pa_table = cur.fetch_arrow_table() df = arrow_table_to_pandas(pa_table, dtype_backend=dtype_backend) return _wrap_result_adbc( df, index_col=index_col, parse_dates=parse_dates, )
Read SQL database table into a DataFrame. Parameters ---------- table_name : str Name of SQL table in database. coerce_float : bool, default True Raises NotImplementedError parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg}``, where the arg corresponds to the keyword arguments of :func:`pandas.to_datetime`. Especially useful with databases without native Datetime support, such as SQLite. columns : list, default: None List of column names to select from SQL table. schema : string, default None Name of SQL schema in database to query (if database flavor supports this). If specified, this overwrites the default schema of the SQL database object. chunksize : int, default None Raises NotImplementedError dtype_backend : {'numpy_nullable', 'pyarrow'} Back-end data type applied to the resultant :class:`DataFrame` (still experimental). If not specified, the default behavior is to not use nullable data types. If specified, the behavior is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` :class:`DataFrame` .. versionadded:: 2.0 Returns ------- DataFrame See Also -------- pandas.read_sql_table SQLDatabase.read_query
python
pandas/io/sql.py
2,163
[ "self", "table_name", "index_col", "coerce_float", "parse_dates", "columns", "schema", "chunksize", "dtype_backend" ]
DataFrame | Iterator[DataFrame]
true
9
6.32
pandas-dev/pandas
47,362
numpy
false
mightBeAndroid
private static boolean mightBeAndroid() { String runtime = System.getProperty("java.runtime.name", ""); // I have no reason to believe that `null` is possible here, but let's make sure we don't crash: return runtime == null || runtime.contains("Android"); }
{@link AtomicHelper} based on {@code synchronized} and volatile writes. <p>This is an implementation of last resort for when certain basic VM features are broken (like AtomicReferenceFieldUpdater).
java
android/guava/src/com/google/common/util/concurrent/AbstractFutureState.java
826
[]
true
2
6.4
google/guava
51,352
javadoc
false
currentBlock
function currentBlock(deferBlock: DeferBlockData): CurrentDeferBlock | null { if (['placeholder', 'loading', 'error'].includes(deferBlock.state)) { return deferBlock.state as 'placeholder' | 'loading' | 'error'; } return null; }
Group Nodes under a defer block if they are part of it. @param node @param deferredNodesToSkip Will mutate the set with the nodes that are grouped into the created deferblock. @param deferBlocks @param appendTo @param getComponent @param getDirectives @param getDirectiveMetadata
typescript
devtools/projects/ng-devtools-backend/src/lib/directive-forest/render-tree.ts
216
[ "deferBlock" ]
true
2
6.4
angular/angular
99,544
jsdoc
false
isEmpty
@Override public boolean isEmpty() { /* * Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and * removed in one segment while checking another, in which case the table was never actually * empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment * modifications before recheck.) Method containsValue() uses similar constructions for * stability checks. */ long sum = 0L; Segment<K, V>[] segments = this.segments; for (Segment<K, V> segment : segments) { if (segment.count != 0) { return false; } sum += segment.modCount; } if (sum != 0L) { // recheck unless no modifications for (Segment<K, V> segment : segments) { if (segment.count != 0) { return false; } sum -= segment.modCount; } return sum == 0L; } return true; }
A custom queue for managing access order. Note that this is tightly integrated with {@code ReferenceEntry}, upon which it relies to perform its linking. <p>Note that this entire implementation makes the assumption that all elements which are in the map are also in this queue, and that all elements not in the queue are not in the map. <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the current model.
java
android/guava/src/com/google/common/cache/LocalCache.java
3,818
[]
true
4
6.88
google/guava
51,352
javadoc
false
remove
@CanIgnoreReturnValue @Override public int remove(@Nullable Object element, int occurrences) { if (occurrences == 0) { return count(element); } CollectPreconditions.checkPositive(occurrences, "occurrences"); AtomicInteger existingCounter = safeGet(countMap, element); if (existingCounter == null) { return 0; } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { int newValue = max(0, oldValue - occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { if (newValue == 0) { // Just CASed to 0; remove the entry to clean up the map. If the removal fails, // another thread has already replaced it with a new counter, which is fine. countMap.remove(element, existingCounter); } return oldValue; } } else { return 0; } } }
Removes a number of occurrences of the specified element from this multiset. If the multiset contains fewer than this number of occurrences to begin with, all occurrences will be removed. @param element the element whose occurrences should be removed @param occurrences the number of occurrences of the element to remove @return the count of the element before the operation; possibly zero @throws IllegalArgumentException if {@code occurrences} is negative
java
android/guava/src/com/google/common/collect/ConcurrentHashMultiset.java
292
[ "element", "occurrences" ]
true
7
7.76
google/guava
51,352
javadoc
false
resize
def resize(a, new_shape): """ Return a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of `a`. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of `a`. Parameters ---------- a : array_like Array to be resized. new_shape : int or tuple of int Shape of resized array. Returns ------- reshaped_array : ndarray The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order. See Also -------- numpy.reshape : Reshape an array without changing the total size. numpy.pad : Enlarge and pad an array. numpy.repeat : Repeat elements of an array. ndarray.resize : resize an array in-place. Notes ----- When the total size of the array does not change `~numpy.reshape` should be used. In most other cases either indexing (to reduce the size) or padding (to increase the size) may be a more appropriate solution. Warning: This functionality does **not** consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, iterating over `a` in C-order, disregarding axes (and cycling back from the start if the new shape is larger). This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity. Examples -------- >>> import numpy as np >>> a = np.array([[0,1],[2,3]]) >>> np.resize(a,(2,3)) array([[0, 1, 2], [3, 0, 1]]) >>> np.resize(a,(1,4)) array([[0, 1, 2, 3]]) >>> np.resize(a,(2,4)) array([[0, 1, 2, 3], [0, 1, 2, 3]]) """ if isinstance(new_shape, (int, nt.integer)): new_shape = (new_shape,) a = ravel(a) new_size = 1 for dim_length in new_shape: new_size *= dim_length if dim_length < 0: raise ValueError( 'all elements of `new_shape` must be non-negative' ) if a.size == 0 or new_size == 0: # First case must zero fill. The second would have repeats == 0. return np.zeros_like(a, shape=new_shape) # ceiling division without negating new_size repeats = (new_size + a.size - 1) // a.size a = concatenate((a,) * repeats)[:new_size] return reshape(a, new_shape)
Return a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of `a`. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of `a`. Parameters ---------- a : array_like Array to be resized. new_shape : int or tuple of int Shape of resized array. Returns ------- reshaped_array : ndarray The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order. See Also -------- numpy.reshape : Reshape an array without changing the total size. numpy.pad : Enlarge and pad an array. numpy.repeat : Repeat elements of an array. ndarray.resize : resize an array in-place. Notes ----- When the total size of the array does not change `~numpy.reshape` should be used. In most other cases either indexing (to reduce the size) or padding (to increase the size) may be a more appropriate solution. Warning: This functionality does **not** consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, iterating over `a` in C-order, disregarding axes (and cycling back from the start if the new shape is larger). This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity. Examples -------- >>> import numpy as np >>> a = np.array([[0,1],[2,3]]) >>> np.resize(a,(2,3)) array([[0, 1, 2], [3, 0, 1]]) >>> np.resize(a,(1,4)) array([[0, 1, 2, 3]]) >>> np.resize(a,(2,4)) array([[0, 1, 2, 3], [0, 1, 2, 3]])
python
numpy/_core/fromnumeric.py
1,509
[ "a", "new_shape" ]
false
6
7.6
numpy/numpy
31,054
numpy
false
stripAccents
public static String stripAccents(final String input) { if (isEmpty(input)) { return input; } final StringBuilder decomposed = new StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFKD)); convertRemainingAccentCharacters(decomposed); return STRIP_ACCENTS_PATTERN.matcher(decomposed).replaceAll(EMPTY); }
Removes diacritics (~= accents) from a string. The case will not be altered. <p> For instance, '&agrave;' will be replaced by 'a'. </p> <p> Decomposes ligatures and digraphs per the KD column in the <a href = "https://www.unicode.org/charts/normalization/">Unicode Normalization Chart.</a> </p> <pre> StringUtils.stripAccents(null) = null StringUtils.stripAccents("") = "" StringUtils.stripAccents("control") = "control" StringUtils.stripAccents("&eacute;clair") = "eclair" StringUtils.stripAccents("\u1d43\u1d47\u1d9c\u00b9\u00b2\u00b3") = "abc123" StringUtils.stripAccents("\u00BC \u00BD \u00BE") = "1⁄4 1⁄2 3⁄4" </pre> <p> See also <a href="https://www.unicode.org/unicode/reports/tr15/tr15-23.html">Unicode Standard Annex #15 Unicode Normalization Forms</a>. </p> @param input String to be stripped. @return input text with diacritics removed. @since 3.0
java
src/main/java/org/apache/commons/lang3/StringUtils.java
7,863
[ "input" ]
String
true
2
7.6
apache/commons-lang
2,896
javadoc
false
requiresDestruction
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) { return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors( bean, getBeanPostProcessorCache().destructionAware)))); }
Determine whether the given bean requires destruction on shutdown. <p>The default implementation checks the DisposableBean interface as well as a specified destroy method and registered DestructionAwareBeanPostProcessors. @param bean the bean instance to check @param mbd the corresponding bean definition @see org.springframework.beans.factory.DisposableBean @see AbstractBeanDefinition#getDestroyMethodName() @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
1,904
[ "bean", "mbd" ]
true
4
6.08
spring-projects/spring-framework
59,386
javadoc
false
requestDescription
abstract String requestDescription();
@return String containing the request name and arguments, to be used for logging purposes.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
903
[]
String
true
1
6.64
apache/kafka
31,560
javadoc
false
forEachPair
@Beta public static <A extends @Nullable Object, B extends @Nullable Object> void forEachPair( Stream<A> streamA, Stream<B> streamB, BiConsumer<? super A, ? super B> consumer) { checkNotNull(consumer); if (streamA.isParallel() || streamB.isParallel()) { zip(streamA, streamB, TemporaryPair::new).forEach(pair -> consumer.accept(pair.a, pair.b)); } else { Iterator<A> iterA = streamA.iterator(); Iterator<B> iterB = streamB.iterator(); while (iterA.hasNext() && iterB.hasNext()) { consumer.accept(iterA.next(), iterB.next()); } } }
Invokes {@code consumer} once for each pair of <i>corresponding</i> elements in {@code streamA} and {@code streamB}. If one stream is longer than the other, the extra elements are silently ignored. Elements passed to the consumer are guaranteed to come from the same position in their respective source streams. For example: {@snippet : Streams.forEachPair( Stream.of("foo1", "foo2", "foo3"), Stream.of("bar1", "bar2"), (arg1, arg2) -> System.out.println(arg1 + ":" + arg2) } <p>will print: {@snippet : foo1:bar1 foo2:bar2 } <p><b>Warning:</b> If either supplied stream is a parallel stream, the same correspondence between elements will be made, but the order in which those pairs of elements are passed to the consumer is <i>not</i> defined. <p>Note that many usages of this method can be replaced with simpler calls to {@link #zip}. This method behaves equivalently to {@linkplain #zip zipping} the stream elements into temporary pair objects and then using {@link Stream#forEach} on that stream. @since 33.4.0 (but since 22.0 in the JRE flavor)
java
android/guava/src/com/google/common/collect/Streams.java
401
[ "streamA", "streamB", "consumer" ]
void
true
5
6.88
google/guava
51,352
javadoc
false
expand
def expand(self, *args: Dim) -> _Tensor: """ Expand tensor by adding new dimensions or expanding existing dimensions. If all arguments are Dim objects, adds new named dimensions. Otherwise, falls back to regular tensor expansion behavior. Args: args: Either Dim objects for new dimensions or sizes for regular expansion Returns: New tensor with expanded dimensions Example: >>> i, j = dims() >>> t = torch.randn(3, 4) >>> expanded = t[i].expand(j, k) # Add j, k dimensions >>> expanded2 = t[i].expand(2, 4) # Regular expand with sizes """ info = TensorInfo.create(self, ensure_batched=False, ensure_present=False) for arg in args: if not isinstance(arg, Dim): # Not all args are Dims, fallback to regular expand if isinstance(self, torch.Tensor) and not isinstance(self, _Tensor): return torch.Tensor.expand(self, *args) else: return self.__torch_function__( torch.Tensor.expand, (type(self),), (self,) + args ) # All args are Dim objects - proceed with first-class dimension expansion if not info: # No tensor info available, fallback return self.__torch_function__( torch.Tensor.expand, (type(self),), (self,) + args ) # First-class dimension expansion - all args are Dim objects data = info.tensor if data is None: # No tensor data available, fallback return self.__torch_function__( torch.Tensor.expand, (type(self),), (self,) + args ) levels = info.levels new_levels: list[DimEntry] = [] new_sizes = [] new_strides = [] for d in args: # Check if dimension already exists in current levels or new_levels for level in levels: if not level.is_positional() and level.dim() is d: raise DimensionBindError( f"expanding dimension {d} already exists in tensor with dims" ) for new_level in new_levels: if not new_level.is_positional() and new_level.dim() is d: raise DimensionBindError( f"expanding dimension {d} already exists in tensor with dims" ) new_levels.append(DimEntry(d)) new_sizes.append(d.size) new_strides.append(0) # Add existing levels new_levels.extend(levels) # Add existing sizes and strides orig_sizes = list(data.size()) orig_strides = list(data.stride()) new_sizes.extend(orig_sizes) new_strides.extend(orig_strides) # Create expanded tensor using as_strided expanded_data = data.as_strided(new_sizes, new_strides, data.storage_offset()) # Return new tensor with expanded dimensions result = Tensor.from_positional(expanded_data, new_levels, info.has_device) return result # type: ignore[return-value] # Tensor and torch.Tensor are interchangeable
Expand tensor by adding new dimensions or expanding existing dimensions. If all arguments are Dim objects, adds new named dimensions. Otherwise, falls back to regular tensor expansion behavior. Args: args: Either Dim objects for new dimensions or sizes for regular expansion Returns: New tensor with expanded dimensions Example: >>> i, j = dims() >>> t = torch.randn(3, 4) >>> expanded = t[i].expand(j, k) # Add j, k dimensions >>> expanded2 = t[i].expand(2, 4) # Regular expand with sizes
python
functorch/dim/__init__.py
626
[ "self" ]
_Tensor
true
15
9.6
pytorch/pytorch
96,034
google
false
resolveSetting
private <V> V resolveSetting(String key, Function<String, V> parser, V defaultValue) { try { String setting = getSettingAsString(expandSettingKey(key)); if (setting == null || setting.isEmpty()) { return defaultValue; } return parser.apply(setting); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new SslConfigException("cannot retrieve setting [" + settingPrefix + key + "]", e); } }
Resolve all necessary configuration settings, and load a {@link SslConfiguration}. @param basePath The base path to use for any settings that represent file paths. Typically points to the Elasticsearch configuration directory. @throws SslConfigException For any problems with the configuration, or with loading the required SSL classes.
java
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java
448
[ "key", "parser", "defaultValue" ]
V
true
5
6.24
elastic/elasticsearch
75,680
javadoc
false
class_distribution
def class_distribution(y, sample_weight=None): """Compute class priors from multioutput-multiclass target data. Parameters ---------- y : {array-like, sparse matrix} of size (n_samples, n_outputs) The labels for each example. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- classes : list of size n_outputs of ndarray of size (n_classes,) List of classes for each column. n_classes : list of int of size n_outputs Number of classes in each column. class_prior : list of size n_outputs of ndarray of size (n_classes,) Class distribution of each column. """ classes = [] n_classes = [] class_prior = [] n_samples, n_outputs = y.shape if sample_weight is not None: sample_weight = np.asarray(sample_weight) if issparse(y): y = y.tocsc() y_nnz = np.diff(y.indptr) for k in range(n_outputs): col_nonzero = y.indices[y.indptr[k] : y.indptr[k + 1]] # separate sample weights for zero and non-zero elements if sample_weight is not None: nz_samp_weight = sample_weight[col_nonzero] zeros_samp_weight_sum = np.sum(sample_weight) - np.sum(nz_samp_weight) else: nz_samp_weight = None zeros_samp_weight_sum = y.shape[0] - y_nnz[k] classes_k, y_k = np.unique( y.data[y.indptr[k] : y.indptr[k + 1]], return_inverse=True ) class_prior_k = np.bincount(y_k, weights=nz_samp_weight) # An explicit zero was found, combine its weight with the weight # of the implicit zeros if 0 in classes_k: class_prior_k[classes_k == 0] += zeros_samp_weight_sum # If there is an implicit zero and it is not in classes and # class_prior, make an entry for it if 0 not in classes_k and y_nnz[k] < y.shape[0]: classes_k = np.insert(classes_k, 0, 0) class_prior_k = np.insert(class_prior_k, 0, zeros_samp_weight_sum) classes.append(classes_k) n_classes.append(classes_k.shape[0]) class_prior.append(class_prior_k / class_prior_k.sum()) else: for k in range(n_outputs): classes_k, y_k = np.unique(y[:, k], return_inverse=True) classes.append(classes_k) n_classes.append(classes_k.shape[0]) class_prior_k = np.bincount(y_k, weights=sample_weight) class_prior.append(class_prior_k / class_prior_k.sum()) return (classes, n_classes, class_prior)
Compute class priors from multioutput-multiclass target data. Parameters ---------- y : {array-like, sparse matrix} of size (n_samples, n_outputs) The labels for each example. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- classes : list of size n_outputs of ndarray of size (n_classes,) List of classes for each column. n_classes : list of int of size n_outputs Number of classes in each column. class_prior : list of size n_outputs of ndarray of size (n_classes,) Class distribution of each column.
python
sklearn/utils/multiclass.py
474
[ "y", "sample_weight" ]
false
11
6
scikit-learn/scikit-learn
64,340
numpy
false
reverseDelimited
public static String reverseDelimited(final String str, final char separatorChar) { final String[] strs = split(str, separatorChar); ArrayUtils.reverse(strs); return join(strs, separatorChar); }
Reverses a String that is delimited by a specific character. <p> The Strings between the delimiters are not reversed. Thus java.lang.String becomes String.lang.java (if the delimiter is {@code '.'}). </p> <pre> StringUtils.reverseDelimited(null, *) = null StringUtils.reverseDelimited("", *) = "" StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c" StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a" </pre> @param str the String to reverse, may be null. @param separatorChar the separator character to use. @return the reversed String, {@code null} if null String input. @since 2.0
java
src/main/java/org/apache/commons/lang3/StringUtils.java
6,818
[ "str", "separatorChar" ]
String
true
1
6.4
apache/commons-lang
2,896
javadoc
false
drain
public Map<Integer, List<ProducerBatch>> drain(MetadataSnapshot metadataSnapshot, Set<Node> nodes, int maxSize, long now) { if (nodes.isEmpty()) return Collections.emptyMap(); Map<Integer, List<ProducerBatch>> batches = new HashMap<>(); for (Node node : nodes) { List<ProducerBatch> ready = drainBatchesForOneNode(metadataSnapshot, node, maxSize, now); batches.put(node.id(), ready); } return batches; }
Drain all the data for the given nodes and collate them into a list of batches that will fit within the specified size on a per-node basis. This method attempts to avoid choosing the same topic-node over and over. @param metadataSnapshot The current cluster metadata @param nodes The list of node to drain @param maxSize The maximum number of bytes to drain @param now The current unix time in milliseconds @return A list of {@link ProducerBatch} for each node specified with total size less than the requested maxSize.
java
clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
959
[ "metadataSnapshot", "nodes", "maxSize", "now" ]
true
2
7.92
apache/kafka
31,560
javadoc
false
init_Aarch_64Bit
private static void init_Aarch_64Bit() { addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.AARCH_64), "aarch64"); }
Gets a {@link Processor} object the given value {@link String}. The {@link String} must be like a value returned by the {@code "os.arch"} system property. @param value A {@link String} like a value returned by the {@code os.arch} System Property. @return A {@link Processor} when it exists, else {@code null}.
java
src/main/java/org/apache/commons/lang3/ArchUtils.java
103
[]
void
true
1
6.96
apache/commons-lang
2,896
javadoc
false
toFloat
public static float toFloat(final String str) { return toFloat(str, 0.0f); }
Converts a {@link String} to a {@code float}, returning {@code 0.0f} if the conversion fails. <p> If the string {@code str} is {@code null}, {@code 0.0f} is returned. </p> <pre> NumberUtils.toFloat(null) = 0.0f NumberUtils.toFloat("") = 0.0f NumberUtils.toFloat("1.5") = 1.5f </pre> @param str the string to convert, may be {@code null}. @return the float represented by the string, or {@code 0.0f} if conversion fails. @since 2.1
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
1,493
[ "str" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
loadMetadata
InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException { ClassicHttpResponse httpResponse = executeInitializrMetadataRetrieval(serviceUrl); validateResponse(httpResponse, serviceUrl); return parseJsonMetadata(httpResponse.getEntity()); }
Load the {@link InitializrServiceMetadata} at the specified url. @param serviceUrl to url of the initializer service @return the metadata describing the service @throws IOException if the service's metadata cannot be loaded
java
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java
106
[ "serviceUrl" ]
InitializrServiceMetadata
true
1
6.08
spring-projects/spring-boot
79,428
javadoc
false
get_task_description
def get_task_description(self, task_arn: str) -> dict: """ Get description for the specified ``task_arn``. .. seealso:: - :external+boto3:py:meth:`DataSync.Client.describe_task` :param task_arn: TaskArn :return: AWS metadata about a task. :raises AirflowBadRequest: If ``task_arn`` is empty. """ if not task_arn: raise AirflowBadRequest("task_arn not specified") return self.get_conn().describe_task(TaskArn=task_arn)
Get description for the specified ``task_arn``. .. seealso:: - :external+boto3:py:meth:`DataSync.Client.describe_task` :param task_arn: TaskArn :return: AWS metadata about a task. :raises AirflowBadRequest: If ``task_arn`` is empty.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/datasync.py
252
[ "self", "task_arn" ]
dict
true
2
7.44
apache/airflow
43,597
sphinx
false
visitParameter
function visitParameter(node: ParameterDeclaration): ParameterDeclaration { if (parametersWithPrecedingObjectRestOrSpread?.has(node)) { return factory.updateParameterDeclaration( node, /*modifiers*/ undefined, node.dotDotDotToken, isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined, ); } if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return factory.updateParameterDeclaration( node, /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), /*questionToken*/ undefined, /*type*/ undefined, visitNode(node.initializer, visitor, isExpression), ); } return visitEachChild(node, visitor, context); }
Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement. @param node A ForOfStatement.
typescript
src/compiler/transformers/es2018.ts
946
[ "node" ]
true
4
6.08
microsoft/TypeScript
107,154
jsdoc
false
load_config_file
def load_config_file(config_path: str) -> dict: """Load configuration from JSON or YAML file. Automatically converts 'nh' field from strings to tuples. Args: config_path: Path to the configuration file Returns: Dictionary containing the configuration Raises: FileNotFoundError: If config file doesn't exist ValueError: If config file format is invalid """ with open(config_path) as f: config_str = f.read() # Try to load as JSON first try: config = json.loads(config_str) except json.JSONDecodeError: # Fall back to YAML parsing config = _parse_simple_yaml(config_str) # Apply automatic conversions for 'nh' field if "nh" in config and isinstance(config["nh"], list): config["nh"] = [ heads_input_type(h) if isinstance(h, str) else h for h in config["nh"] ] return config
Load configuration from JSON or YAML file. Automatically converts 'nh' field from strings to tuples. Args: config_path: Path to the configuration file Returns: Dictionary containing the configuration Raises: FileNotFoundError: If config file doesn't exist ValueError: If config file format is invalid
python
benchmarks/transformer/config_utils.py
36
[ "config_path" ]
dict
true
4
7.44
pytorch/pytorch
96,034
google
false
hasSimilarGroup
boolean hasSimilarGroup(ItemMetadata metadata) { if (!metadata.isOfItemType(ItemMetadata.ItemType.GROUP)) { throw new IllegalStateException("item " + metadata + " must be a group"); } for (ItemMetadata existing : this.metadataItems) { if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName()) && existing.getType().equals(metadata.getType())) { return true; } } return false; }
Creates a new {@code MetadataProcessor} instance. @param mergeRequired specify whether an item can be merged @param previousMetadata any previous metadata or {@code null}
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/MetadataCollector.java
84
[ "metadata" ]
true
5
6.08
spring-projects/spring-boot
79,428
javadoc
false
parseJSDocType
function parseJSDocType(): TypeNode { scanner.setSkipJsDocLeadingAsterisks(true); const pos = getNodePos(); if (parseOptional(SyntaxKind.ModuleKeyword)) { // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here? const moduleTag = factory.createJSDocNamepathType(/*type*/ undefined!); terminate: while (true) { switch (token()) { case SyntaxKind.CloseBraceToken: case SyntaxKind.EndOfFileToken: case SyntaxKind.CommaToken: case SyntaxKind.WhitespaceTrivia: break terminate; default: nextTokenJSDoc(); } } scanner.setSkipJsDocLeadingAsterisks(false); return finishNode(moduleTag, pos); } const hasDotDotDot = parseOptional(SyntaxKind.DotDotDotToken); let type = parseTypeOrTypePredicate(); scanner.setSkipJsDocLeadingAsterisks(false); if (hasDotDotDot) { type = finishNode(factory.createJSDocVariadicType(type), pos); } if (token() === SyntaxKind.EqualsToken) { nextToken(); return finishNode(factory.createJSDocOptionalType(type), pos); } return type; }
Reports a diagnostic error for the current token being an invalid name. @param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName). @param nameDiagnostic Diagnostic to report for all other cases. @param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
typescript
src/compiler/parser.ts
3,910
[]
true
5
6.88
microsoft/TypeScript
107,154
jsdoc
false
addInterface
public void addInterface(Class<?> ifc) { Assert.notNull(ifc, "Interface must not be null"); if (!ifc.isInterface()) { throw new IllegalArgumentException("[" + ifc.getName() + "] is not an interface"); } if (!this.interfaces.contains(ifc)) { this.interfaces.add(ifc); adviceChanged(); } }
Add a new proxied interface. @param ifc the additional interface to proxy
java
spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java
231
[ "ifc" ]
void
true
3
6.88
spring-projects/spring-framework
59,386
javadoc
false
findThreadGroupsByName
public static Collection<ThreadGroup> findThreadGroupsByName(final String threadGroupName) { return findThreadGroups(predicateThreadGroup(threadGroupName)); }
Finds active thread groups with the specified group name. @param threadGroupName The thread group name. @return the thread groups with the specified group name or an empty collection if no such thread group exists. The collection returned is always unmodifiable. @throws NullPointerException if group name is null. @throws SecurityException if the current thread cannot access the system thread group. @throws SecurityException if the current thread cannot modify thread groups from this thread's thread group up to the system thread group.
java
src/main/java/org/apache/commons/lang3/ThreadUtils.java
312
[ "threadGroupName" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
get_instance_state
def get_instance_state(self, instance_id: str) -> str: """ Get EC2 instance state by id and return it. :param instance_id: id of the AWS EC2 instance :return: current state of the instance """ if self._api_type == "client_type": return self.get_instances(instance_ids=[instance_id])[0]["State"]["Name"] return self.get_instance(instance_id=instance_id).state["Name"]
Get EC2 instance state by id and return it. :param instance_id: id of the AWS EC2 instance :return: current state of the instance
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/ec2.py
180
[ "self", "instance_id" ]
str
true
2
8.08
apache/airflow
43,597
sphinx
false
unmodifiableBiMap
public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) { return new UnmodifiableBiMap<>(bimap, null); }
Returns an unmodifiable view of the specified bimap. This method allows modules to provide users with "read-only" access to internal bimaps. Query operations on the returned bimap "read through" to the specified bimap, and attempts to modify the returned map, whether direct or via its collection views, result in an {@code UnsupportedOperationException}. <p>The returned bimap will be serializable if the specified bimap is serializable. @param bimap the bimap for which an unmodifiable view is to be returned @return an unmodifiable view of the specified bimap
java
android/guava/src/com/google/common/collect/Maps.java
1,640
[ "bimap" ]
true
1
6.48
google/guava
51,352
javadoc
false
substring
public String substring(final int start) { return substring(start, size); }
Extracts a portion of this string builder as a string. @param start the start index, inclusive, must be valid @return the new string @throws IndexOutOfBoundsException if the index is invalid
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
2,908
[ "start" ]
String
true
1
6.48
apache/commons-lang
2,896
javadoc
false
commitSync
public CompletableFuture<Map<TopicIdPartition, Acknowledgements>> commitSync( final Map<TopicIdPartition, NodeAcknowledgements> acknowledgementsMap, final long deadlineMs) { final AtomicInteger resultCount = new AtomicInteger(); final CompletableFuture<Map<TopicIdPartition, Acknowledgements>> future = new CompletableFuture<>(); final ResultHandler resultHandler = new ResultHandler(resultCount, Optional.of(future)); final Cluster cluster = metadata.fetch(); sessionHandlers.forEach((nodeId, sessionHandler) -> { Node node = cluster.nodeById(nodeId); if (node != null) { acknowledgeRequestStates.putIfAbsent(nodeId, new Tuple<>(null, null, null)); // Add the incoming commitSync() request to the queue. Map<TopicIdPartition, Acknowledgements> acknowledgementsMapForNode = new HashMap<>(); for (TopicIdPartition tip : sessionHandler.sessionPartitions()) { NodeAcknowledgements nodeAcknowledgements = acknowledgementsMap.get(tip); if ((nodeAcknowledgements != null) && (nodeAcknowledgements.nodeId() == node.id())) { if (!isLeaderKnownToHaveChanged(node.id(), tip)) { acknowledgementsMapForNode.put(tip, nodeAcknowledgements.acknowledgements()); metricsManager.recordAcknowledgementSent(nodeAcknowledgements.acknowledgements().size()); log.debug("Added sync acknowledge request for partition {} to node {}", tip.topicPartition(), node.id()); resultCount.incrementAndGet(); } else { nodeAcknowledgements.acknowledgements().complete(Errors.NOT_LEADER_OR_FOLLOWER.exception()); maybeSendShareAcknowledgementEvent(Map.of(tip, nodeAcknowledgements.acknowledgements()), true, Optional.empty()); } } } if (!acknowledgementsMapForNode.isEmpty()) { acknowledgeRequestStates.get(nodeId).addSyncRequest(new AcknowledgeRequestState(logContext, ShareConsumeRequestManager.class.getSimpleName() + ":1", deadlineMs, retryBackoffMs, retryBackoffMaxMs, sessionHandler, nodeId, acknowledgementsMapForNode, resultHandler, AcknowledgeRequestType.COMMIT_SYNC )); } } }); resultHandler.completeIfEmpty(); return future; }
Enqueue an AcknowledgeRequestState to be picked up on the next poll @param acknowledgementsMap The acknowledgements to commit @param deadlineMs Time until which the request will be retried if it fails with an expected retriable error. @return The future which completes when the acknowledgements finished
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ShareConsumeRequestManager.java
540
[ "acknowledgementsMap", "deadlineMs" ]
true
6
7.92
apache/kafka
31,560
javadoc
false
default_config
def default_config(self) -> dict: """ An immutable default waiter configuration. :return: a waiter configuration for AWS Batch services """ if self._default_config is None: config_path = Path(__file__).with_name("batch_waiters.json").resolve() with open(config_path) as config_file: self._default_config = json.load(config_file) return deepcopy(self._default_config) # avoid accidental mutation
An immutable default waiter configuration. :return: a waiter configuration for AWS Batch services
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/batch_waiters.py
112
[ "self" ]
dict
true
2
6.4
apache/airflow
43,597
unknown
false
random
@Deprecated public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) { return secure().next(count, start, end, letters, numbers, chars); }
Creates a random string based on a variety of options, using default source of randomness. <p> This method has exactly the same semantics as {@link #random(int,int,int,boolean,boolean,char[],Random)}, but instead of using an externally supplied source of randomness, it uses the internal static {@link Random} instance. </p> @param count the length of random string to create. @param start the position in set of chars to start at. @param end the position in set of chars to end before. @param letters if {@code true}, generated string may include alphabetic characters. @param numbers if {@code true}, generated string may include numeric characters. @param chars the set of chars to choose randoms from. If {@code null}, then it will use the set of all chars. @return the random string. @throws ArrayIndexOutOfBoundsException if there are not {@code (end - start) + 1} characters in the set array. @throws IllegalArgumentException if {@code count} &lt; 0. @deprecated Use {@link #next(int, int, int, boolean, boolean, char...)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
java
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
218
[ "count", "start", "end", "letters", "numbers" ]
String
true
1
6.88
apache/commons-lang
2,896
javadoc
false
lastSeenLeaderEpoch
public Optional<Integer> lastSeenLeaderEpoch(TopicPartition topicPartition) { return Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition)); }
Request an update for the partition metadata iff we have seen a newer leader epoch. This is called by the client any time it handles a response from the broker that includes leader epoch, except for update via Metadata RPC which follows a different code path ({@link #update}). @param topicPartition @param leaderEpoch @return true if we updated the last seen epoch, false otherwise
java
clients/src/main/java/org/apache/kafka/clients/Metadata.java
256
[ "topicPartition" ]
true
1
6.48
apache/kafka
31,560
javadoc
false
inverse
@Override public ImmutableListMultimap<V, K> inverse() { ImmutableListMultimap<V, K> result = inverse; return (result == null) ? (inverse = invert()) : result; }
{@inheritDoc} <p>Because an inverse of a list multimap can contain multiple pairs with the same key and value, this method returns an {@code ImmutableListMultimap} rather than the {@code ImmutableMultimap} specified in the {@code ImmutableMultimap} class. @since 11.0
java
android/guava/src/com/google/common/collect/ImmutableListMultimap.java
474
[]
true
2
6.08
google/guava
51,352
javadoc
false
allSupportedApiVersions
public Map<ApiKeys, ApiVersion> allSupportedApiVersions() { return supportedVersions; }
Get the version information for a given API. @param apiKey The api key to lookup @return The api version information from the broker or null if it is unsupported
java
clients/src/main/java/org/apache/kafka/clients/NodeApiVersions.java
253
[]
true
1
6.64
apache/kafka
31,560
javadoc
false
readChar
@CanIgnoreReturnValue // to skip some bytes @Override public char readChar() throws IOException { return (char) readUnsignedShort(); }
Reads a char as specified by {@link DataInputStream#readChar()}, except using little-endian byte order. @return the next two bytes of the input stream, interpreted as a {@code char} in little-endian byte order @throws IOException if an I/O error occurs
java
android/guava/src/com/google/common/io/LittleEndianDataInputStream.java
204
[]
true
1
6.56
google/guava
51,352
javadoc
false
get_cluster_status
def get_cluster_status(self, cluster_id: str) -> str: """ Get the status of a Neptune cluster. :param cluster_id: The ID of the cluster to get the status of. :return: The status of the cluster. """ return self.conn.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]["Status"]
Get the status of a Neptune cluster. :param cluster_id: The ID of the cluster to get the status of. :return: The status of the cluster.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/neptune.py
84
[ "self", "cluster_id" ]
str
true
1
7.04
apache/airflow
43,597
sphinx
false
addBean
static void addBean(FormatterRegistry registry, Object bean, @Nullable ResolvableType beanType) { if (bean instanceof GenericConverter converterBean) { addBean(registry, converterBean, beanType, GenericConverter.class, registry::addConverter, (Runnable) null); } else if (bean instanceof Converter<?, ?> converterBean) { Assert.state(beanType != null, "beanType is missing"); addBeanWithType(registry, converterBean, beanType, Converter.class, registry::addConverter, ConverterBeanAdapter::new); } else if (bean instanceof ConverterFactory<?, ?> converterBean) { Assert.state(beanType != null, "beanType is missing"); addBeanWithType(registry, converterBean, beanType, ConverterFactory.class, registry::addConverterFactory, ConverterFactoryBeanAdapter::new); } else if (bean instanceof Formatter<?> formatterBean) { addBean(registry, formatterBean, beanType, Formatter.class, registry::addFormatter, () -> { Assert.state(beanType != null, "beanType is missing"); registry.addConverter(new PrinterBeanAdapter(formatterBean, beanType)); registry.addConverter(new ParserBeanAdapter(formatterBean, beanType)); }); } else if (bean instanceof Printer<?> printerBean) { Assert.state(beanType != null, "beanType is missing"); addBeanWithType(registry, printerBean, beanType, Printer.class, registry::addPrinter, PrinterBeanAdapter::new); } else if (bean instanceof Parser<?> parserBean) { Assert.state(beanType != null, "beanType is missing"); addBeanWithType(registry, parserBean, beanType, Parser.class, registry::addParser, ParserBeanAdapter::new); } }
Add {@link Printer}, {@link Parser}, {@link Formatter}, {@link Converter}, {@link ConverterFactory}, {@link GenericConverter}, and beans from the specified bean factory. @param registry the service to register beans with @param beanFactory the bean factory to get the beans from @param qualifier the qualifier required on the beans or {@code null} @return the beans that were added @since 3.5.0
java
core/spring-boot/src/main/java/org/springframework/boot/convert/ApplicationConversionService.java
350
[ "registry", "bean", "beanType" ]
void
true
7
7.76
spring-projects/spring-boot
79,428
javadoc
false
render_template
def render_template( template_name: str, context: dict[str, Any], autoescape: bool = False, keep_trailing_newline: bool = False, ) -> str: """ Renders template based on its name. Reads the template from <name>.jinja2 in current dir. :param template_name: name of the template to use :param context: Jinja2 context :param autoescape: Whether to autoescape HTML :param keep_trailing_newline: Whether to keep the newline in rendered output :return: rendered template """ import jinja2 template_loader = jinja2.FileSystemLoader(searchpath=MY_DIR_PATH) template_env = jinja2.Environment( loader=template_loader, undefined=jinja2.StrictUndefined, autoescape=autoescape, keep_trailing_newline=keep_trailing_newline, ) template = template_env.get_template(f"{template_name}.jinja2") content: str = template.render(context) return content
Renders template based on its name. Reads the template from <name>.jinja2 in current dir. :param template_name: name of the template to use :param context: Jinja2 context :param autoescape: Whether to autoescape HTML :param keep_trailing_newline: Whether to keep the newline in rendered output :return: rendered template
python
dev/assign_cherry_picked_prs_with_milestone.py
142
[ "template_name", "context", "autoescape", "keep_trailing_newline" ]
str
true
1
6.88
apache/airflow
43,597
sphinx
false
partition
private static int partition(double[] array, int from, int to) { // Select a pivot, and move it to the start of the slice i.e. to index from. movePivotToStartOfSlice(array, from, to); double pivot = array[from]; // Move all elements with indexes in (from, to] which are greater than the pivot to the end of // the array. Keep track of where those elements begin. int partitionPoint = to; for (int i = to; i > from; i--) { if (array[i] > pivot) { swap(array, partitionPoint, i); partitionPoint--; } } // We now know that all elements with indexes in (from, partitionPoint] are less than or equal // to the pivot at from, and all elements with indexes in (partitionPoint, to] are greater than // it. We swap the pivot into partitionPoint and we know the array is partitioned around that. swap(array, from, partitionPoint); return partitionPoint; }
Performs a partition operation on the slice of {@code array} with elements in the range [{@code from}, {@code to}]. Uses the median of {@code from}, {@code to}, and the midpoint between them as a pivot. Returns the index which the slice is partitioned around, i.e. if it returns {@code ret} then we know that the values with indexes in [{@code from}, {@code ret}) are less than or equal to the value at {@code ret} and the values with indexes in ({@code ret}, {@code to}] are greater than or equal to that.
java
android/guava/src/com/google/common/math/Quantiles.java
575
[ "array", "from", "to" ]
true
3
6
google/guava
51,352
javadoc
false
process
public final T process() { try { System.setProperty(AOT_PROCESSING, "true"); return doProcess(); } finally { System.clearProperty(AOT_PROCESSING); } }
Run AOT processing. @return the result of the processing.
java
spring-context/src/main/java/org/springframework/context/aot/AbstractAotProcessor.java
81
[]
T
true
1
7.04
spring-projects/spring-framework
59,386
javadoc
false
toString
@Override public String toString() { return toString(ToStringFormat.DEFAULT, false); }
Returns {@code true} if this element is an ancestor (immediate or nested parent) of the specified name. @param name the name to check @return {@code true} if this name is an ancestor
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java
550
[]
String
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
alterStreamsGroupOffsets
AlterStreamsGroupOffsetsResult alterStreamsGroupOffsets(String groupId, Map<TopicPartition, OffsetAndMetadata> offsets, AlterStreamsGroupOffsetsOptions options);
<p>Alters offsets for the specified group. In order to succeed, the group must be empty. <p>This operation is not transactional so it may succeed for some partitions while fail for others. <em>Note</em>: this method effectively does the same as the corresponding consumer group method {@link Admin#alterConsumerGroupOffsets} does. @param groupId The group for which to alter offsets. @param offsets A map of offsets by partition with associated metadata. Partitions not specified in the map are ignored. @param options The options to use when altering the offsets. @return The AlterOffsetsResult.
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
1,321
[ "groupId", "offsets", "options" ]
AlterStreamsGroupOffsetsResult
true
1
6.32
apache/kafka
31,560
javadoc
false
getAreaAbsorptionCapacity
function getAreaAbsorptionCapacity( unit: 'percent' | 'pixel', areaSnapshot: IAreaSnapshot, pixels: number, allAreasSizePixel: number, ): IAreaAbsorptionCapacity | undefined | void { // No pain no gain if (pixels === 0) { return { areaSnapshot, pixelAbsorb: 0, percentAfterAbsorption: areaSnapshot.sizePercentAtStart, pixelRemain: 0, }; } // Area start at zero and need to be reduced, not possible if (areaSnapshot.sizePixelAtStart === 0 && pixels < 0) { return { areaSnapshot, pixelAbsorb: 0, percentAfterAbsorption: 0, pixelRemain: pixels, }; } if (unit === 'percent') { return getAreaAbsorptionCapacityPercent(areaSnapshot, pixels, allAreasSizePixel); } if (unit === 'pixel') { return getAreaAbsorptionCapacityPixel(areaSnapshot, pixels, allAreasSizePixel); } }
@license Copyright Google LLC All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at https://angular.dev/license
typescript
devtools/projects/ng-devtools/src/lib/shared/split/utils.ts
133
[ "unit", "areaSnapshot", "pixels", "allAreasSizePixel" ]
true
6
6
angular/angular
99,544
jsdoc
false
columnMap
@Override public Map<C, Map<R, @Nullable V>> columnMap() { ColumnMap map = columnMap; return (map == null) ? columnMap = new ColumnMap() : map; }
Returns an immutable set of the valid column keys, including those that are associated with null values only. @return immutable set of column keys
java
android/guava/src/com/google/common/collect/ArrayTable.java
642
[]
true
2
8.08
google/guava
51,352
javadoc
false
builder
public static SnifferBuilder builder(RestClient restClient) { return new SnifferBuilder(restClient); }
Returns a new {@link SnifferBuilder} to help with {@link Sniffer} creation. @param restClient the client that gets its hosts set (via {@link RestClient#setNodes(Collection)}) once they are fetched @return a new instance of {@link SnifferBuilder}
java
client/sniffer/src/main/java/org/elasticsearch/client/sniff/Sniffer.java
235
[ "restClient" ]
SnifferBuilder
true
1
6.32
elastic/elasticsearch
75,680
javadoc
false
maybe_convert_indices
def maybe_convert_indices(indices, n: int, verify: bool = True) -> np.ndarray: """ Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If we have indices that are out-of-bounds, raise an IndexError. Parameters ---------- indices : array-like Array of indices that we are to convert. n : int Number of elements in the array that we are indexing. verify : bool, default True Check that all entries are between 0 and n - 1, inclusive. Returns ------- array-like An array-like of positive indices that correspond to the ones that were passed in initially to this function. Raises ------ IndexError One of the converted indices either exceeded the number of, elements (specified by `n`), or was still negative. """ if isinstance(indices, list): indices = np.array(indices) if len(indices) == 0: # If `indices` is empty, np.array will return a float, # and will cause indexing errors. return np.empty(0, dtype=np.intp) mask = indices < 0 if mask.any(): indices = indices.copy() indices[mask] += n if verify: mask = (indices >= n) | (indices < 0) if mask.any(): raise IndexError("indices are out-of-bounds") return indices
Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If we have indices that are out-of-bounds, raise an IndexError. Parameters ---------- indices : array-like Array of indices that we are to convert. n : int Number of elements in the array that we are indexing. verify : bool, default True Check that all entries are between 0 and n - 1, inclusive. Returns ------- array-like An array-like of positive indices that correspond to the ones that were passed in initially to this function. Raises ------ IndexError One of the converted indices either exceeded the number of, elements (specified by `n`), or was still negative.
python
pandas/core/indexers/utils.py
241
[ "indices", "n", "verify" ]
np.ndarray
true
6
6.88
pandas-dev/pandas
47,362
numpy
false
writeStartArray
@Override public void writeStartArray() throws IOException { try { generator.writeStartArray(); } catch (JsonGenerationException e) { throw new XContentGenerationException(e); } }
Reference to filtering generator because writing an empty object '{}' when everything is filtered out needs a specific treatment
java
libs/x-content/impl/src/main/java/org/elasticsearch/xcontent/provider/json/JsonXContentGenerator.java
167
[]
void
true
2
6.24
elastic/elasticsearch
75,680
javadoc
false
row
Map<C, V> row(@ParametricNullness R rowKey);
Returns a view of all mappings that have the given row key. For each row key / column key / value mapping in the table with that row key, the returned map associates the column key with the value. If no mappings in the table have the provided row key, an empty map is returned. <p>Changes to the returned map will update the underlying table, and vice versa. @param rowKey key of row to search for in the table @return the corresponding map from column keys to values
java
android/guava/src/com/google/common/collect/Table.java
187
[ "rowKey" ]
true
1
6.64
google/guava
51,352
javadoc
false
resolve
private List<ConfigDataResolutionResult> resolve(ConfigDataLocationResolverContext locationResolverContext, @Nullable Profiles profiles, ConfigDataLocation location) { try { return this.resolvers.resolve(locationResolverContext, location, profiles); } catch (ConfigDataNotFoundException ex) { handle(ex, location, null); return Collections.emptyList(); } }
Resolve and load the given list of locations, filtering any that have been previously loaded. @param activationContext the activation context @param locationResolverContext the location resolver context @param loaderContext the loader context @param locations the locations to resolve @return a map of the loaded locations and data
java
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataImporter.java
104
[ "locationResolverContext", "profiles", "location" ]
true
2
7.28
spring-projects/spring-boot
79,428
javadoc
false
deactivate
def deactivate(): """ Unset the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value
Unset the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE.
python
django/utils/timezone.py
103
[]
false
2
6.24
django/django
86,204
unknown
false
append
@Override public StrBuilder append(final char ch) { final int len = length(); ensureCapacity(len + 1); buffer[size++] = ch; return this; }
Appends a char value to the string builder. @param ch the value to append @return {@code this} instance. @since 3.0
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
352
[ "ch" ]
StrBuilder
true
1
7.04
apache/commons-lang
2,896
javadoc
false
failure
public static <T> RequestFuture<T> failure(RuntimeException e) { RequestFuture<T> future = new RequestFuture<>(); future.raise(e); return future; }
Convert from a request future of one type to another type @param adapter The adapter which does the conversion @param <S> The type of the future adapted to @return The new future
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestFuture.java
231
[ "e" ]
true
1
6.4
apache/kafka
31,560
javadoc
false
time_bounded
def time_bounded(self, bitgen, args): """ Timer for 8-bit bounded values. Parameters (packed as args) ---------- dt : {uint8, uint16, uint32, unit64} output dtype max : int Upper bound for range. Lower is always 0. Must be <= 2**bits. """ dt, max = args if bitgen == 'numpy': self.rg.randint(0, max + 1, nom_size, dtype=dt) else: self.rg.integers(0, max + 1, nom_size, dtype=dt)
Timer for 8-bit bounded values. Parameters (packed as args) ---------- dt : {uint8, uint16, uint32, unit64} output dtype max : int Upper bound for range. Lower is always 0. Must be <= 2**bits.
python
benchmarks/benchmarks/bench_random.py
158
[ "self", "bitgen", "args" ]
false
3
6.08
numpy/numpy
31,054
unknown
false
getReport
PropertiesMigrationReport getReport() { PropertiesMigrationReport report = new PropertiesMigrationReport(); Map<String, List<PropertyMigration>> properties = getPropertySourceMigrations( ConfigurationMetadataProperty::isDeprecated); if (properties.isEmpty()) { return report; } properties.forEach((name, candidates) -> { PropertySource<?> propertySource = mapPropertiesWithReplacement(report, name, candidates); if (propertySource != null) { this.environment.getPropertySources().addBefore(name, propertySource); } }); return report; }
Analyse the {@link ConfigurableEnvironment environment} and attempt to rename legacy properties if a replacement exists. @return a report of the migration
java
core/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReporter.java
71
[]
PropertiesMigrationReport
true
3
7.28
spring-projects/spring-boot
79,428
javadoc
false
getTSVInstance
public static StrTokenizer getTSVInstance(final String input) { final StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; }
Gets a new tokenizer instance which parses Tab Separated Value strings. The default for CSV processing will be trim whitespace from both ends (which can be overridden with the setTrimmer method). @param input the string to parse. @return a new tokenizer instance which parses Tab Separated Value strings.
java
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
213
[ "input" ]
StrTokenizer
true
1
6.72
apache/commons-lang
2,896
javadoc
false
repeat
def repeat(self, repeats: int, axis=None) -> MultiIndex: """ Repeat elements of a MultiIndex. Returns a new MultiIndex where each element of the current MultiIndex is repeated consecutively a given number of times. Parameters ---------- repeats : int or array of ints The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty MultiIndex. axis : None Must be ``None``. Has no effect but is accepted for compatibility with numpy. Returns ------- MultiIndex Newly created MultiIndex with repeated elements. See Also -------- Series.repeat : Equivalent function for Series. numpy.repeat : Similar method for :class:`numpy.ndarray`. Examples -------- >>> idx = pd.MultiIndex.from_arrays([["a", "b", "c"], [1, 2, 3]]) >>> idx MultiIndex([('a', 1), ('b', 2), ('c', 3)], ) >>> idx.repeat(2) MultiIndex([('a', 1), ('a', 1), ('b', 2), ('b', 2), ('c', 3), ('c', 3)], ) >>> idx.repeat([1, 2, 3]) MultiIndex([('a', 1), ('b', 2), ('b', 2), ('c', 3), ('c', 3), ('c', 3)], ) """ nv.validate_repeat((), {"axis": axis}) # error: Incompatible types in assignment (expression has type "ndarray", # variable has type "int") repeats = ensure_platform_int(repeats) # type: ignore[assignment] return MultiIndex( levels=self.levels, codes=[ level_codes.view(np.ndarray).astype(np.intp, copy=False).repeat(repeats) for level_codes in self.codes ], names=self.names, sortorder=self.sortorder, verify_integrity=False, )
Repeat elements of a MultiIndex. Returns a new MultiIndex where each element of the current MultiIndex is repeated consecutively a given number of times. Parameters ---------- repeats : int or array of ints The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty MultiIndex. axis : None Must be ``None``. Has no effect but is accepted for compatibility with numpy. Returns ------- MultiIndex Newly created MultiIndex with repeated elements. See Also -------- Series.repeat : Equivalent function for Series. numpy.repeat : Similar method for :class:`numpy.ndarray`. Examples -------- >>> idx = pd.MultiIndex.from_arrays([["a", "b", "c"], [1, 2, 3]]) >>> idx MultiIndex([('a', 1), ('b', 2), ('c', 3)], ) >>> idx.repeat(2) MultiIndex([('a', 1), ('a', 1), ('b', 2), ('b', 2), ('c', 3), ('c', 3)], ) >>> idx.repeat([1, 2, 3]) MultiIndex([('a', 1), ('b', 2), ('b', 2), ('c', 3), ('c', 3), ('c', 3)], )
python
pandas/core/indexes/multi.py
2,506
[ "self", "repeats", "axis" ]
MultiIndex
true
1
7.2
pandas-dev/pandas
47,362
numpy
false
createBeanDefinitionLoader
protected BeanDefinitionLoader createBeanDefinitionLoader(BeanDefinitionRegistry registry, Object[] sources) { return new BeanDefinitionLoader(registry, sources); }
Factory method used to create the {@link BeanDefinitionLoader}. @param registry the bean definition registry @param sources the sources to load @return the {@link BeanDefinitionLoader} that will be used to load beans
java
core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java
747
[ "registry", "sources" ]
BeanDefinitionLoader
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
get
@ParametricNullness public static <T extends @Nullable Object> T get(Iterator<T> iterator, int position) { checkNonnegative(position); int skipped = advance(iterator, position); if (!iterator.hasNext()) { throw new IndexOutOfBoundsException( "position (" + position + ") must be less than the number of elements that remained (" + skipped + ")"); } return iterator.next(); }
Advances {@code iterator} {@code position + 1} times, returning the element at the {@code position}th position. @param position position of the element to return @return the element at the specified position in {@code iterator} @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to the number of elements remaining in {@code iterator}
java
android/guava/src/com/google/common/collect/Iterators.java
842
[ "iterator", "position" ]
T
true
2
7.6
google/guava
51,352
javadoc
false
buildMessage
private static String buildMessage(Set<String> mutuallyExclusiveNames, Set<String> configuredNames) { Assert.isTrue(configuredNames != null && configuredNames.size() > 1, "'configuredNames' must contain 2 or more names"); Assert.isTrue(mutuallyExclusiveNames != null && mutuallyExclusiveNames.size() > 1, "'mutuallyExclusiveNames' must contain 2 or more names"); return "The configuration properties '" + String.join(", ", mutuallyExclusiveNames) + "' are mutually exclusive and '" + String.join(", ", configuredNames) + "' have been configured together"; }
Return the names of the properties that are mutually exclusive. @return the names of the mutually exclusive properties
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/MutuallyExclusiveConfigurationPropertiesException.java
89
[ "mutuallyExclusiveNames", "configuredNames" ]
String
true
3
6.72
spring-projects/spring-boot
79,428
javadoc
false
getAndAdd
public short getAndAdd(final short operand) { final short last = value; this.value += operand; return last; }
Increments this instance's value by {@code operand}; this method returns the value associated with the instance immediately prior to the addition operation. This method is not thread safe. @param operand the quantity to add, not null. @return the value associated with this instance immediately before the operand was added. @since 3.5
java
src/main/java/org/apache/commons/lang3/mutable/MutableShort.java
221
[ "operand" ]
true
1
6.88
apache/commons-lang
2,896
javadoc
false
get
@Nullable StructuredLogFormatter<E> get(Instantiator<?> instantiator, String format) { CommonStructuredLogFormat commonFormat = CommonStructuredLogFormat.forId(format); CommonFormatterFactory<E> factory = (commonFormat != null) ? this.factories.get(commonFormat) : null; return (factory != null) ? factory.createFormatter(instantiator) : null; }
Add the factory that should be used for the given {@link CommonStructuredLogFormat}. @param format the common structured log format @param factory the factory to use
java
core/spring-boot/src/main/java/org/springframework/boot/logging/structured/StructuredLogFormatterFactory.java
178
[ "instantiator", "format" ]
true
3
6.56
spring-projects/spring-boot
79,428
javadoc
false
replace
public static String replace(final Object source, final Properties valueProperties) { if (valueProperties == null) { return source.toString(); } final Map<String, String> valueMap = new HashMap<>(); final Enumeration<?> propNames = valueProperties.propertyNames(); while (propNames.hasMoreElements()) { final String propName = String.valueOf(propNames.nextElement()); final String propValue = valueProperties.getProperty(propName); valueMap.put(propName, propValue); } return replace(source, valueMap); }
Replaces all the occurrences of variables in the given source object with their matching values from the properties. @param source the source text containing the variables to substitute, null returns null. @param valueProperties the properties with values, may be null. @return the result of the replace operation.
java
src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java
205
[ "source", "valueProperties" ]
String
true
3
7.92
apache/commons-lang
2,896
javadoc
false
launch
protected void launch(String[] args) throws Exception { if (!isExploded()) { Handlers.register(); } try { ClassLoader classLoader = createClassLoader(getClassPathUrls()); String jarMode = System.getProperty("jarmode"); String mainClassName = hasLength(jarMode) ? JAR_MODE_RUNNER_CLASS_NAME : getMainClass(); launch(classLoader, mainClassName, args); } catch (UncheckedIOException ex) { throw ex.getCause(); } }
Launch the application. This method is the initial entry point that should be called by a subclass {@code public static void main(String[] args)} method. @param args the incoming arguments @throws Exception if the application fails to launch
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/launch/Launcher.java
56
[ "args" ]
void
true
4
7.04
spring-projects/spring-boot
79,428
javadoc
false
enterWhenUninterruptibly
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) { long timeoutNanos = toSafeNanos(time, unit); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } ReentrantLock lock = this.lock; long startTime = 0L; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); boolean interrupted = Thread.interrupted(); try { if (fair || !lock.tryLock()) { startTime = initNanoTime(timeoutNanos); for (long remainingNanos = timeoutNanos; ; ) { try { if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) { break; } else { return false; } } catch (InterruptedException interrupt) { interrupted = true; remainingNanos = remainingNanos(startTime, timeoutNanos); } } } boolean satisfied = false; try { while (true) { try { if (guard.isSatisfied()) { satisfied = true; } else { long remainingNanos; if (startTime == 0L) { startTime = initNanoTime(timeoutNanos); remainingNanos = timeoutNanos; } else { remainingNanos = remainingNanos(startTime, timeoutNanos); } satisfied = awaitNanos(guard, remainingNanos, signalBeforeWaiting); } return satisfied; } catch (InterruptedException interrupt) { interrupted = true; signalBeforeWaiting = false; } } } finally { if (!satisfied) { lock.unlock(); // No need to signal if timed out } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
Enters this monitor when the guard is satisfied. Blocks at most the given time, including both the time to acquire the lock and the time to wait for the guard to be satisfied. @return whether the monitor was entered, which guarantees that the guard is now satisfied
java
android/guava/src/com/google/common/util/concurrent/Monitor.java
614
[ "guard", "time", "unit" ]
true
13
6.96
google/guava
51,352
javadoc
false
containsValue
@Override public boolean containsValue(@Nullable Object value) { if (value == null) { return false; } // This implementation is patterned after ConcurrentHashMap, but without the locking. The only // way for it to return a false negative would be for the target value to jump around in the map // such that none of the subsequent iterations observed it, despite the fact that at every point // in time it was present somewhere int the map. This becomes increasingly unlikely as // CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible. Segment<K, V, E, S>[] segments = this.segments; long last = -1L; for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) { long sum = 0L; for (Segment<K, V, E, S> segment : segments) { // ensure visibility of most recent completed write int unused = segment.count; // read-volatile AtomicReferenceArray<E> table = segment.table; for (int j = 0; j < table.length(); j++) { for (E e = table.get(j); e != null; e = e.getNext()) { V v = segment.getLiveValue(e); if (v != null && valueEquivalence().equivalent(value, v)) { return true; } } } sum += segment.modCount; } if (sum == last) { break; } last = sum; } return false; }
Returns the internal entry for the specified key. The entry may be computing or partially collected. Does not impact recency ordering.
java
android/guava/src/com/google/common/collect/MapMakerInternalMap.java
2,385
[ "value" ]
true
8
6
google/guava
51,352
javadoc
false
binaryToShort
public static short binaryToShort(final boolean[] src, final int srcPos, final short dstInit, final int dstPos, final int nBools) { if (src.length == 0 && srcPos == 0 || 0 == nBools) { return dstInit; } if (nBools - 1 + dstPos >= Short.SIZE) { throw new IllegalArgumentException("nBools - 1 + dstPos >= 16"); } short out = dstInit; for (int i = 0; i < nBools; i++) { final int shift = i + dstPos; final int bits = (src[i + srcPos] ? 1 : 0) << shift; final int mask = 0x1 << shift; out = (short) (out & ~mask | bits); } return out; }
Converts binary (represented as boolean array) into a short using the default (little endian, LSB0) byte and bit ordering. @param src the binary to convert. @param srcPos the position in {@code src}, in boolean unit, from where to start the conversion. @param dstInit initial value of the destination short. @param dstPos the position of the LSB, in bits, in the result short. @param nBools the number of booleans to convert. @return a short containing the selected bits. @throws NullPointerException if {@code src} is {@code null}. @throws IllegalArgumentException if {@code nBools - 1 + dstPos >= 16}. @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}.
java
src/main/java/org/apache/commons/lang3/Conversion.java
362
[ "src", "srcPos", "dstInit", "dstPos", "nBools" ]
true
7
7.92
apache/commons-lang
2,896
javadoc
false
compare
@SuppressWarnings("InlineMeInliner") // Integer.compare unavailable under GWT+J2CL public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); }
Compares the two specified {@code long} values, treating them as unsigned values between {@code 0} and {@code 2^64 - 1} inclusive. <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the equivalent {@link Long#compareUnsigned(long, long)} method instead. @param a the first unsigned {@code long} to compare @param b the second unsigned {@code long} to compare @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is greater than {@code b}; or zero if they are equal
java
android/guava/src/com/google/common/primitives/UnsignedLongs.java
77
[ "a", "b" ]
true
1
6.48
google/guava
51,352
javadoc
false
power
def power(a, b, third=None): """ Returns element-wise base array raised to power from second array. This is the masked array version of `numpy.power`. For details see `numpy.power`. See Also -------- numpy.power Notes ----- The *out* argument to `numpy.power` is not supported, `third` has to be None. Examples -------- >>> import numpy as np >>> import numpy.ma as ma >>> x = [11.2, -3.973, 0.801, -1.41] >>> mask = [0, 0, 0, 1] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array(data=[11.2, -3.973, 0.801, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, 2) masked_array(data=[125.43999999999998, 15.784728999999999, 0.6416010000000001, --], mask=[False, False, False, True], fill_value=1e+20) >>> y = [-0.5, 2, 0, 17] >>> masked_y = ma.masked_array(y, mask) >>> masked_y masked_array(data=[-0.5, 2.0, 0.0, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, masked_y) masked_array(data=[0.2988071523335984, 15.784728999999999, 1.0, --], mask=[False, False, False, True], fill_value=1e+20) """ if third is not None: raise MaskError("3-argument power not supported.") # Get the masks ma = getmask(a) mb = getmask(b) m = mask_or(ma, mb) # Get the rawdata fa = getdata(a) fb = getdata(b) # Get the type of the result (so that we preserve subclasses) if isinstance(a, MaskedArray): basetype = type(a) else: basetype = MaskedArray # Get the result and view it as a (subclass of) MaskedArray with np.errstate(divide='ignore', invalid='ignore'): result = np.where(m, fa, umath.power(fa, fb)).view(basetype) result._update_from(a) # Find where we're in trouble w/ NaNs and Infs invalid = np.logical_not(np.isfinite(result.view(ndarray))) # Add the initial mask if m is not nomask: if not result.ndim: return masked result._mask = np.logical_or(m, invalid) # Fix the invalid parts if invalid.any(): if not result.ndim: return masked elif result._mask is nomask: result._mask = invalid result._data[invalid] = result.fill_value return result
Returns element-wise base array raised to power from second array. This is the masked array version of `numpy.power`. For details see `numpy.power`. See Also -------- numpy.power Notes ----- The *out* argument to `numpy.power` is not supported, `third` has to be None. Examples -------- >>> import numpy as np >>> import numpy.ma as ma >>> x = [11.2, -3.973, 0.801, -1.41] >>> mask = [0, 0, 0, 1] >>> masked_x = ma.masked_array(x, mask) >>> masked_x masked_array(data=[11.2, -3.973, 0.801, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, 2) masked_array(data=[125.43999999999998, 15.784728999999999, 0.6416010000000001, --], mask=[False, False, False, True], fill_value=1e+20) >>> y = [-0.5, 2, 0, 17] >>> masked_y = ma.masked_array(y, mask) >>> masked_y masked_array(data=[-0.5, 2.0, 0.0, --], mask=[False, False, False, True], fill_value=1e+20) >>> ma.power(masked_x, masked_y) masked_array(data=[0.2988071523335984, 15.784728999999999, 1.0, --], mask=[False, False, False, True], fill_value=1e+20)
python
numpy/ma/core.py
7,118
[ "a", "b", "third" ]
false
9
6.24
numpy/numpy
31,054
unknown
false
resolveNamedBean
<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;
Resolve the bean instance that uniquely matches the given object type, if any, including its bean name. <p>This is effectively a variant of {@link #getBean(Class)} which preserves the bean name of the matching instance. @param requiredType type the bean must match; can be an interface or superclass @return the bean name plus bean instance @throws NoSuchBeanDefinitionException if no matching bean was found @throws NoUniqueBeanDefinitionException if more than one matching bean was found @throws BeansException if the bean could not be created @since 4.3.3 @see #getBean(Class)
java
spring-beans/src/main/java/org/springframework/beans/factory/config/AutowireCapableBeanFactory.java
356
[ "requiredType" ]
true
1
6.32
spring-projects/spring-framework
59,386
javadoc
false
load_string
def load_string( self, string_data: str, key: str, bucket_name: str | None = None, replace: bool = False, encrypt: bool = False, encoding: str | None = None, acl_policy: str | None = None, compression: str | None = None, ) -> None: """ Load a string to S3. This is provided as a convenience to drop a string in S3. It uses the boto infrastructure to ship a file to s3. .. seealso:: - :external+boto3:py:meth:`S3.Client.upload_fileobj` :param string_data: str to set as content for the key. :param key: S3 key that will point to the file :param bucket_name: Name of the bucket in which to store the file :param replace: A flag to decide whether or not to overwrite the key if it already exists :param encrypt: If True, the file will be encrypted on the server-side by S3 and will be stored in an encrypted form while at rest in S3. :param encoding: The string to byte encoding :param acl_policy: The string to specify the canned ACL policy for the object to be uploaded :param compression: Type of compression to use, currently only gzip is supported. """ encoding = encoding or "utf-8" bytes_data = string_data.encode(encoding) # Compress string available_compressions = ["gzip"] if compression is not None and compression not in available_compressions: raise NotImplementedError( f"Received {compression} compression type. " f"String can currently be compressed in {available_compressions} only." ) if compression == "gzip": bytes_data = gz.compress(bytes_data) with BytesIO(bytes_data) as f: self._upload_file_obj(f, key, bucket_name, replace, encrypt, acl_policy)
Load a string to S3. This is provided as a convenience to drop a string in S3. It uses the boto infrastructure to ship a file to s3. .. seealso:: - :external+boto3:py:meth:`S3.Client.upload_fileobj` :param string_data: str to set as content for the key. :param key: S3 key that will point to the file :param bucket_name: Name of the bucket in which to store the file :param replace: A flag to decide whether or not to overwrite the key if it already exists :param encrypt: If True, the file will be encrypted on the server-side by S3 and will be stored in an encrypted form while at rest in S3. :param encoding: The string to byte encoding :param acl_policy: The string to specify the canned ACL policy for the object to be uploaded :param compression: Type of compression to use, currently only gzip is supported.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/s3.py
1,235
[ "self", "string_data", "key", "bucket_name", "replace", "encrypt", "encoding", "acl_policy", "compression" ]
None
true
5
7.04
apache/airflow
43,597
sphinx
false
_math_mode_with_dollar
def _math_mode_with_dollar(s: str) -> str: r""" All characters in LaTeX math mode are preserved. The substrings in LaTeX math mode, which start with the character ``$`` and end with ``$``, are preserved without escaping. Otherwise regular LaTeX escaping applies. Parameters ---------- s : str Input to be escaped Return ------ str : Escaped string """ s = s.replace(r"\$", r"rt8§=§7wz") pattern = re.compile(r"\$.*?\$") pos = 0 ps = pattern.search(s, pos) res = [] while ps: res.append(_escape_latex(s[pos : ps.span()[0]])) res.append(ps.group()) pos = ps.span()[1] ps = pattern.search(s, pos) res.append(_escape_latex(s[pos : len(s)])) return "".join(res).replace(r"rt8§=§7wz", r"\$")
r""" All characters in LaTeX math mode are preserved. The substrings in LaTeX math mode, which start with the character ``$`` and end with ``$``, are preserved without escaping. Otherwise regular LaTeX escaping applies. Parameters ---------- s : str Input to be escaped Return ------ str : Escaped string
python
pandas/io/formats/style_render.py
2,579
[ "s" ]
str
true
2
6.72
pandas-dev/pandas
47,362
numpy
false
add
@Deprecated public static int[] add(final int[] array, final int index, final int element) { return (int[]) add(array, index, Integer.valueOf(element), Integer.TYPE); }
Inserts the specified element at the specified position in the array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). <p> This method returns a new array with the same elements of the input array plus the given element on the specified position. The component type of the returned array is always the same as that of the input array. </p> <p> If the input array is {@code null}, a new one element array is returned whose component type is the same as the element. </p> <pre> ArrayUtils.add([1], 0, 2) = [2, 1] ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10] ArrayUtils.add([2, 6], 0, -4) = [-4, 2, 6] ArrayUtils.add([2, 6, 3], 2, 1) = [2, 6, 1, 3] </pre> @param array the array to add the element to, may be {@code null}. @param index the position of the new object. @param element the object to add. @return A new array containing the existing elements and the new element. @throws IndexOutOfBoundsException if the index is out of range (index &lt; 0 || index &gt; array.length). @deprecated this method has been superseded by {@link #insert(int, int[], int...)} and may be removed in a future release. Please note the handling of {@code null} input arrays differs in the new method: inserting {@code X} into a {@code null} array results in {@code null} not {@code X}.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
579
[ "array", "index", "element" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
diff
def diff(self, periods: int = 1) -> Series: """ First discrete difference of element. Calculates the difference of a {klass} element compared with another element in the {klass} (default is element in previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. {extra_params} Returns ------- {klass} First differences of the Series. See Also -------- {klass}.pct_change: Percent change over given number of periods. {klass}.shift: Shift index by desired number of periods with an optional time freq. {other_klass}.diff: First discrete difference of object. Notes ----- For boolean dtypes, this uses :meth:`operator.xor` rather than :meth:`operator.sub`. The result is calculated according to current dtype in {klass}, however dtype of the result is always float64. Examples -------- {examples} """ if not lib.is_integer(periods): if not (is_float(periods) and periods.is_integer()): raise ValueError("periods must be an integer") result = algorithms.diff(self._values, periods) return self._constructor(result, index=self.index, copy=False).__finalize__( self, method="diff" )
First discrete difference of element. Calculates the difference of a {klass} element compared with another element in the {klass} (default is element in previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. {extra_params} Returns ------- {klass} First differences of the Series. See Also -------- {klass}.pct_change: Percent change over given number of periods. {klass}.shift: Shift index by desired number of periods with an optional time freq. {other_klass}.diff: First discrete difference of object. Notes ----- For boolean dtypes, this uses :meth:`operator.xor` rather than :meth:`operator.sub`. The result is calculated according to current dtype in {klass}, however dtype of the result is always float64. Examples -------- {examples}
python
pandas/core/series.py
2,864
[ "self", "periods" ]
Series
true
4
6.24
pandas-dev/pandas
47,362
numpy
false
stubFalse
function stubFalse() { return false; }
This method returns `false`. @static @memberOf _ @since 4.13.0 @category Util @returns {boolean} Returns `false`. @example _.times(2, _.stubFalse); // => [false, false]
javascript
lodash.js
16,168
[]
false
1
7.12
lodash/lodash
61,490
jsdoc
false
newArrayListWithCapacity
@SuppressWarnings("NonApiType") // acts as a direct substitute for a constructor call public static <E extends @Nullable Object> ArrayList<E> newArrayListWithCapacity( int initialArraySize) { checkNonnegative(initialArraySize, "initialArraySize"); // for GWT. return new ArrayList<>(initialArraySize); }
Creates an {@code ArrayList} instance backed by an array with the specified initial size; simply delegates to {@link ArrayList#ArrayList(int)}. <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly, taking advantage of <a href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#type-inference-instantiation">"diamond" syntax</a>. (Unlike here, there is no risk of overload ambiguity, since the {@code ArrayList} constructors very wisely did not accept varargs.) @param initialArraySize the exact size of the initial backing array for the returned array list ({@code ArrayList} documentation calls this value the "capacity") @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size reaches {@code initialArraySize + 1} @throws IllegalArgumentException if {@code initialArraySize} is negative
java
android/guava/src/com/google/common/collect/Lists.java
179
[ "initialArraySize" ]
true
1
6.24
google/guava
51,352
javadoc
false
get
@Override public ConfigData get(String path, Set<String> keys) { return get(path, pathname -> Files.isRegularFile(pathname) && keys.contains(pathname.getFileName().toString())); }
Retrieves the data contained in the regular files named by {@code keys} in the directory given by {@code path}. Non-regular files (such as directories) in the given directory are silently ignored. @param path the directory where data files reside. @param keys the keys whose values will be retrieved. @return the configuration data.
java
clients/src/main/java/org/apache/kafka/common/config/provider/DirectoryConfigProvider.java
78
[ "path", "keys" ]
ConfigData
true
2
8.24
apache/kafka
31,560
javadoc
false
get_rocm_compiler
def get_rocm_compiler() -> str: """ Get path to ROCm's clang compiler. Uses PyTorch's ROCM_HOME detection. Returns: Path to clang compiler Raises: RuntimeError: If ROCm is not found """ if ROCM_HOME is None: raise RuntimeError( "ROCm installation not found. " "PyTorch was not built with ROCm support or ROCM_HOME is not set." ) # ROCm's clang is at <ROCM_HOME>/llvm/bin/clang clang_path = _join_rocm_home("llvm", "bin", "clang") if not os.path.exists(clang_path): raise RuntimeError( f"ROCm clang not found at {clang_path}. ROCM_HOME is set to {ROCM_HOME}" ) return clang_path
Get path to ROCm's clang compiler. Uses PyTorch's ROCM_HOME detection. Returns: Path to clang compiler Raises: RuntimeError: If ROCm is not found
python
torch/_inductor/rocm_multiarch_utils.py
14
[]
str
true
3
8.08
pytorch/pytorch
96,034
unknown
false
append
public StrBuilder append(final StrBuilder str) { if (str == null) { return appendNull(); } final int strLen = str.length(); if (strLen > 0) { final int len = length(); ensureCapacity(len + strLen); System.arraycopy(str.buffer, 0, buffer, len, strLen); size += strLen; } return this; }
Appends another string builder to this string builder. Appending null will call {@link #appendNull()}. @param str the string builder to append @return {@code this} instance.
java
src/main/java/org/apache/commons/lang3/text/StrBuilder.java
575
[ "str" ]
StrBuilder
true
3
8.08
apache/commons-lang
2,896
javadoc
false
communityId
public static String communityId( String sourceIpAddrString, String destIpAddrString, Object ianaNumber, Object transport, Object sourcePort, Object destinationPort, Object icmpType, Object icmpCode ) { return CommunityIdProcessor.apply( sourceIpAddrString, destIpAddrString, ianaNumber, transport, sourcePort, destinationPort, icmpType, icmpCode ); }
Uses {@link CommunityIdProcessor} to compute community ID for network flow data. @param sourceIpAddrString source IP address @param destIpAddrString destination IP address @param ianaNumber IANA number @param transport transport protocol @param sourcePort source port @param destinationPort destination port @param icmpType ICMP type @param icmpCode ICMP code @return Community ID
java
modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/Processors.java
167
[ "sourceIpAddrString", "destIpAddrString", "ianaNumber", "transport", "sourcePort", "destinationPort", "icmpType", "icmpCode" ]
String
true
1
6.08
elastic/elasticsearch
75,680
javadoc
false
topicNames
public Map<Uuid, String> topicNames() { return metadataSnapshot.topicNames(); }
@return Mapping from topic IDs to topic names for all topics in the cache.
java
clients/src/main/java/org/apache/kafka/clients/Metadata.java
757
[]
true
1
6.96
apache/kafka
31,560
javadoc
false
stream
public static <E> FailableStream<E> stream(final Collection<E> collection) { return new FailableStream<>(collection.stream()); }
Converts the given collection into a {@link FailableStream}. The {@link FailableStream} consists of the collections elements. Shortcut for <pre> Functions.stream(collection.stream()); </pre> @param collection The collection, which is being converted into a {@link FailableStream}. @param <E> The collections element type. (In turn, the result streams element type.) @return The created {@link FailableStream}.
java
src/main/java/org/apache/commons/lang3/function/Failable.java
562
[ "collection" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
getOrder
@Override public int getOrder() { if (this.beanFactory != null && this.aspectBeanName != null && this.beanFactory.isSingleton(this.aspectBeanName) && this.beanFactory.isTypeMatch(this.aspectBeanName, Ordered.class)) { return ((Ordered) this.beanFactory.getBean(this.aspectBeanName)).getOrder(); } return Ordered.LOWEST_PRECEDENCE; }
Look up the aspect bean from the {@link BeanFactory} and return it. @see #setAspectBeanName
java
spring-aop/src/main/java/org/springframework/aop/config/SimpleBeanFactoryAwareAspectInstanceFactory.java
80
[]
true
5
6.56
spring-projects/spring-framework
59,386
javadoc
false
get_edge_info
def get_edge_info(self, upstream_task_id: str, downstream_task_id: str) -> EdgeInfoType: """Return edge information for the given pair of tasks or an empty edge if there is no information.""" # Note - older serialized dags may not have edge_info being a dict at all empty = cast("EdgeInfoType", {}) if self.edge_info: return self.edge_info.get(upstream_task_id, {}).get(downstream_task_id, empty) return empty
Return edge information for the given pair of tasks or an empty edge if there is no information.
python
airflow-core/src/airflow/serialization/serialized_objects.py
3,650
[ "self", "upstream_task_id", "downstream_task_id" ]
EdgeInfoType
true
2
6
apache/airflow
43,597
unknown
false
_encode_attribute
def _encode_attribute(self, name, type_): '''(INTERNAL) Encodes an attribute line. The attribute follow the template:: @attribute <attribute-name> <datatype> where ``attribute-name`` is a string, and ``datatype`` can be: - Numerical attributes as ``NUMERIC``, ``INTEGER`` or ``REAL``. - Strings as ``STRING``. - Dates (NOT IMPLEMENTED). - Nominal attributes with format: {<nominal-name1>, <nominal-name2>, <nominal-name3>, ...} This method must receive a the name of the attribute and its type, if the attribute type is nominal, ``type`` must be a list of values. :param name: a string. :param type_: a string or a list of string. :return: a string with the encoded attribute declaration. ''' for char in ' %{},': if char in name: name = '"%s"'%name break if isinstance(type_, (tuple, list)): type_tmp = ['%s' % encode_string(type_k) for type_k in type_] type_ = '{%s}'%(', '.join(type_tmp)) return '%s %s %s'%(_TK_ATTRIBUTE, name, type_)
(INTERNAL) Encodes an attribute line. The attribute follow the template:: @attribute <attribute-name> <datatype> where ``attribute-name`` is a string, and ``datatype`` can be: - Numerical attributes as ``NUMERIC``, ``INTEGER`` or ``REAL``. - Strings as ``STRING``. - Dates (NOT IMPLEMENTED). - Nominal attributes with format: {<nominal-name1>, <nominal-name2>, <nominal-name3>, ...} This method must receive a the name of the attribute and its type, if the attribute type is nominal, ``type`` must be a list of values. :param name: a string. :param type_: a string or a list of string. :return: a string with the encoded attribute declaration.
python
sklearn/externals/_arff.py
937
[ "self", "name", "type_" ]
false
4
7.12
scikit-learn/scikit-learn
64,340
sphinx
false
divideBy
public Fraction divideBy(final Fraction fraction) { Objects.requireNonNull(fraction, "fraction"); if (fraction.numerator == 0) { throw new ArithmeticException("The fraction to divide by must not be zero"); } return multiplyBy(fraction.invert()); }
Divide the value of this fraction by another. @param fraction the fraction to divide by, must not be {@code null} @return a {@link Fraction} instance with the resulting values @throws NullPointerException if the fraction is {@code null} @throws ArithmeticException if the fraction to divide by is zero @throws ArithmeticException if the resulting numerator or denominator exceeds {@code Integer.MAX_VALUE}
java
src/main/java/org/apache/commons/lang3/math/Fraction.java
613
[ "fraction" ]
Fraction
true
2
7.28
apache/commons-lang
2,896
javadoc
false
create_endpoint_config
def create_endpoint_config(self, config: dict): """ Create an endpoint configuration to deploy models. In the configuration, you identify one or more models, created using the CreateModel API, to deploy and the resources that you want Amazon SageMaker to provision. .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.create_endpoint_config` - :class:`airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.create_model` - :class:`airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.create_endpoint` :param config: the config for endpoint-config :return: A response to endpoint config creation """ return self.get_conn().create_endpoint_config(**config)
Create an endpoint configuration to deploy models. In the configuration, you identify one or more models, created using the CreateModel API, to deploy and the resources that you want Amazon SageMaker to provision. .. seealso:: - :external+boto3:py:meth:`SageMaker.Client.create_endpoint_config` - :class:`airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.create_model` - :class:`airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.create_endpoint` :param config: the config for endpoint-config :return: A response to endpoint config creation
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker.py
475
[ "self", "config" ]
true
1
6.08
apache/airflow
43,597
sphinx
false