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
matches
boolean matches(T item);
Return if the filter matches the specified item. @param item the item to test @return if the filter matches
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/layer/ContentFilter.java
35
[ "item" ]
true
1
6.8
spring-projects/spring-boot
79,428
javadoc
false
can_produce
def can_produce(self, output_spec: Spec) -> bool: """Stack can produce any tensor output with at least one dimension.""" if not isinstance(output_spec, TensorSpec): return False # Stack creates a new dimension, so output must have at least one dimension # Also, no dimension can be 0 since that would require stacking 0 tensors # Limit to outputs where all dimensions are <= 4 to avoid creating too large graphs return ( len(output_spec.size) > 0 and 0 not in output_spec.size and all(dim <= 4 for dim in output_spec.size) )
Stack can produce any tensor output with at least one dimension.
python
tools/experimental/torchfuzz/operators/layout.py
670
[ "self", "output_spec" ]
bool
true
4
6
pytorch/pytorch
96,034
unknown
false
stripAll
public static String[] stripAll(final String... strs) { return stripAll(strs, null); }
Strips whitespace from the start and end of every String in an array. Whitespace is defined by {@link Character#isWhitespace(char)}. <p> A new array is returned each time, except for length zero. A {@code null} array will return {@code null}. An empty array will return itself. A {@code null} array entry will be ignored. </p> <pre> StringUtils.stripAll(null) = null StringUtils.stripAll([]) = [] StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"] StringUtils.stripAll(["abc ", null]) = ["abc", null] </pre> @param strs the array to remove whitespace from, may be null. @return the stripped Strings, {@code null} if null array input.
java
src/main/java/org/apache/commons/lang3/StringUtils.java
7,890
[]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
to_orc
def to_orc( df: DataFrame, path: FilePath | WriteBuffer[bytes] | None = None, *, engine: Literal["pyarrow"] = "pyarrow", index: bool | None = None, engine_kwargs: dict[str, Any] | None = None, ) -> bytes | None: """ Write a DataFrame to the ORC format. Parameters ---------- df : DataFrame The dataframe to be written to ORC. Raises NotImplementedError if dtype of one or more columns is category, unsigned integers, intervals, periods or sparse. path : str, file-like object or None, default None If a string, it will be used as Root Directory path when writing a partitioned dataset. By file-like object, we refer to objects with a write() method, such as a file handle (e.g. via builtin open function). If path is None, a bytes object is returned. engine : str, default 'pyarrow' ORC library to use. index : bool, optional If ``True``, include the dataframe's index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, similar to ``infer`` the dataframe's index(es) will be saved. However, instead of being saved as values, the RangeIndex will be stored as a range in the metadata so it doesn't require much space and is faster. Other indexes will be included as columns in the file output. engine_kwargs : dict[str, Any] or None, default None Additional keyword arguments passed to :func:`pyarrow.orc.write_table`. Returns ------- bytes if no path argument is provided else None Raises ------ NotImplementedError Dtype of one or more columns is category, unsigned integers, interval, period or sparse. ValueError engine is not pyarrow. Notes ----- * Before using this function you should read the :ref:`user guide about ORC <io.orc>` and :ref:`install optional dependencies <install.warn_orc>`. * This function requires `pyarrow <https://arrow.apache.org/docs/python/>`_ library. * For supported dtypes please refer to `supported ORC features in Arrow <https://arrow.apache.org/docs/cpp/orc.html#data-types>`__. * Currently timezones in datetime columns are not preserved when a dataframe is converted into ORC files. """ if index is None: index = df.index.names[0] is not None if engine_kwargs is None: engine_kwargs = {} # validate index # -------------- # validate that we have only a default index # raise on anything else as we don't serialize the index if not df.index.equals(default_index(len(df))): raise ValueError( "orc does not support serializing a non-default index for the index; " "you can .reset_index() to make the index into column(s)" ) if df.index.name is not None: raise ValueError("orc does not serialize index meta-data on a default index") if engine != "pyarrow": raise ValueError("engine must be 'pyarrow'") pa = import_optional_dependency("pyarrow") orc = import_optional_dependency("pyarrow.orc") was_none = path is None if was_none: path = io.BytesIO() assert path is not None # For mypy with get_handle(path, "wb", is_text=False) as handles: try: orc.write_table( pa.Table.from_pandas(df, preserve_index=index), handles.handle, **engine_kwargs, ) except (TypeError, pa.ArrowNotImplementedError) as e: raise NotImplementedError( "The dtype of one or more columns is not supported yet." ) from e if was_none: assert isinstance(path, io.BytesIO) # For mypy return path.getvalue() return None
Write a DataFrame to the ORC format. Parameters ---------- df : DataFrame The dataframe to be written to ORC. Raises NotImplementedError if dtype of one or more columns is category, unsigned integers, intervals, periods or sparse. path : str, file-like object or None, default None If a string, it will be used as Root Directory path when writing a partitioned dataset. By file-like object, we refer to objects with a write() method, such as a file handle (e.g. via builtin open function). If path is None, a bytes object is returned. engine : str, default 'pyarrow' ORC library to use. index : bool, optional If ``True``, include the dataframe's index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, similar to ``infer`` the dataframe's index(es) will be saved. However, instead of being saved as values, the RangeIndex will be stored as a range in the metadata so it doesn't require much space and is faster. Other indexes will be included as columns in the file output. engine_kwargs : dict[str, Any] or None, default None Additional keyword arguments passed to :func:`pyarrow.orc.write_table`. Returns ------- bytes if no path argument is provided else None Raises ------ NotImplementedError Dtype of one or more columns is category, unsigned integers, interval, period or sparse. ValueError engine is not pyarrow. Notes ----- * Before using this function you should read the :ref:`user guide about ORC <io.orc>` and :ref:`install optional dependencies <install.warn_orc>`. * This function requires `pyarrow <https://arrow.apache.org/docs/python/>`_ library. * For supported dtypes please refer to `supported ORC features in Arrow <https://arrow.apache.org/docs/cpp/orc.html#data-types>`__. * Currently timezones in datetime columns are not preserved when a dataframe is converted into ORC files.
python
pandas/io/orc.py
139
[ "df", "path", "engine", "index", "engine_kwargs" ]
bytes | None
true
8
6.8
pandas-dev/pandas
47,362
numpy
false
visitNested
function visitNested({ includeOrSelect, result, parentModelName, runtimeDataModel, visitor }: VisitNestedParams) { for (const [fieldName, subConfig] of Object.entries(includeOrSelect)) { if (!subConfig || result[fieldName] == null || isSkip(subConfig)) { continue } const parentModel = runtimeDataModel.models[parentModelName] const field = parentModel.fields.find((field) => field.name === fieldName) if (!field || field.kind !== 'object' || !field.relationName) { continue } const args = typeof subConfig === 'object' ? subConfig : {} result[fieldName] = visitQueryResult({ visitor, result: result[fieldName], args, modelName: field.type, runtimeDataModel, }) } }
Function recursively walks through provided query response using `include` and `select` query parameters and calls `visitor` callback for each model it encounters. `visitor` receives the value of a particular response section, model it corresponds to and the arguments used to query it. If visitor returns any non-undefined value that value will replace corresponding part of the final result. @param params @returns
typescript
packages/client/src/runtime/core/extensions/visitQueryResult.ts
69
[ "{ includeOrSelect, result, parentModelName, runtimeDataModel, visitor }" ]
false
8
7.28
prisma/prisma
44,834
jsdoc
false
setContextValue
@Override public ContextedRuntimeException setContextValue(final String label, final Object value) { exceptionContext.setContextValue(label, value); return this; }
Sets information helpful to a developer in diagnosing and correcting the problem. For the information to be meaningful, the value passed should have a reasonable toString() implementation. Any existing values with the same labels are removed before the new one is added. <p> Note: This exception is only serializable if the object added as value is serializable. </p> @param label a textual label associated with information, {@code null} not recommended @param value information needed to understand exception, may be {@code null} @return {@code this}, for method chaining, not {@code null}
java
src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java
248
[ "label", "value" ]
ContextedRuntimeException
true
1
6.56
apache/commons-lang
2,896
javadoc
false
getGitCommit
function getGitCommit() { try { return execSync('git show -s --no-show-signature --format=%h') .toString() .trim(); } catch (error) { // Mozilla runs this command from a git archive. // In that context, there is no Git context. // Using the commit hash specified to download-experimental-build.js script as a fallback. // Try to read from build/COMMIT_SHA file const commitShaPath = resolve(__dirname, '..', '..', 'build', 'COMMIT_SHA'); if (!existsSync(commitShaPath)) { throw new Error( 'Could not find build/COMMIT_SHA file. Did you run scripts/release/download-experimental-build.js script?', ); } try { const commitHash = readFileSync(commitShaPath, 'utf8').trim(); // Return short hash (first 7 characters) to match abbreviated commit hash format return commitHash.slice(0, 7); } catch (readError) { throw new Error( `Failed to read build/COMMIT_SHA file: ${readError.message}`, ); } } }
Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
javascript
packages/react-devtools-extensions/utils.js
14
[]
false
4
6.4
facebook/react
241,750
jsdoc
false
readToDirectBuffer
private static int readToDirectBuffer(InputStream input, ByteBuffer b, int count) throws IOException { int totalRead = 0; final byte[] buffer = LOCAL_BUFFER.get(); while (totalRead < count) { final int len = Math.min(count - totalRead, buffer.length); final int read = input.read(buffer, 0, len); if (read == -1) { break; } b.put(buffer, 0, read); totalRead += read; } return totalRead; }
Read up to {code count} bytes from {@code input} and store them into {@code buffer}. The buffers position will be incremented by the number of bytes read from the stream. @param input stream to read from @param buffer buffer to read into @param count maximum number of bytes to read @return number of bytes read from the stream @throws IOException in case of I/O errors
java
libs/core/src/main/java/org/elasticsearch/core/Streams.java
108
[ "input", "b", "count" ]
true
3
7.92
elastic/elasticsearch
75,680
javadoc
false
predictBeanType
protected @Nullable Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { Class<?> targetType = mbd.getTargetType(); if (targetType != null) { return targetType; } if (mbd.getFactoryMethodName() != null) { return null; } return resolveBeanClass(mbd, beanName, typesToMatch); }
Predict the eventual bean type (of the processed bean instance) for the specified bean. Called by {@link #getType} and {@link #isTypeMatch}. Does not need to handle FactoryBeans specifically, since it is only supposed to operate on the raw bean type. <p>This implementation is simplistic in that it is not able to handle factory methods and InstantiationAwareBeanPostProcessors. It only predicts the bean type correctly for a standard bean. To be overridden in subclasses, applying more sophisticated type detection. @param beanName the name of the bean @param mbd the merged bean definition to determine the type for @param typesToMatch the types to match in case of internal type matching purposes (also signals that the returned {@code Class} will never be exposed to application code) @return the type of the bean, or {@code null} if not predictable
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
1,680
[ "beanName", "mbd" ]
true
3
7.92
spring-projects/spring-framework
59,386
javadoc
false
alterConsumerGroupOffsets
default AlterConsumerGroupOffsetsResult alterConsumerGroupOffsets(String groupId, Map<TopicPartition, OffsetAndMetadata> offsets) { return alterConsumerGroupOffsets(groupId, offsets, new AlterConsumerGroupOffsetsOptions()); }
<p>Alters offsets for the specified group. In order to succeed, the group must be empty. <p>This is a convenience method for {@link #alterConsumerGroupOffsets(String, Map, AlterConsumerGroupOffsetsOptions)} with default options. See the overload for more details. @param groupId The group for which to alter offsets. @param offsets A map of offsets by partition with associated metadata. @return The AlterOffsetsResult.
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
1,279
[ "groupId", "offsets" ]
AlterConsumerGroupOffsetsResult
true
1
6.32
apache/kafka
31,560
javadoc
false
subscribeInternal
private void subscribeInternal(Pattern pattern, Optional<ConsumerRebalanceListener> listener) { throwIfGroupIdNotDefined(); if (pattern == null || pattern.toString().isEmpty()) throw new IllegalArgumentException("Topic pattern to subscribe to cannot be " + (pattern == null ? "null" : "empty")); acquireAndEnsureOpen(); try { throwIfNoAssignorsConfigured(); log.info("Subscribed to pattern: '{}'", pattern); this.subscriptions.subscribe(pattern, listener); this.coordinator.updatePatternSubscription(metadata.fetch()); this.metadata.requestUpdateForNewTopics(); } finally { release(); } }
Internal helper method for {@link #subscribe(Pattern)} and {@link #subscribe(Pattern, ConsumerRebalanceListener)} <p> Subscribe to all topics matching specified pattern to get dynamically assigned partitions. The pattern matching will be done periodically against all topics existing at the time of check. This can be controlled through the {@code metadata.max.age.ms} configuration: by lowering the max metadata age, the consumer will refresh metadata more often and check for matching topics. <p> See {@link #subscribe(Collection, ConsumerRebalanceListener)} for details on the use of the {@link ConsumerRebalanceListener}. Generally rebalances are triggered when there is a change to the topics matching the provided pattern and when consumer group membership changes. Group rebalances only take place during an active call to {@link #poll(Duration)}. @param pattern Pattern to subscribe to @param listener {@link Optional} listener instance to get notifications on partition assignment/revocation for the subscribed topics @throws IllegalArgumentException If pattern or listener is null @throws IllegalStateException If {@code subscribe()} is called previously with topics, or assign is called previously (without a subsequent call to {@link #unsubscribe()}), or if not configured at-least one partition assignment strategy
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ClassicKafkaConsumer.java
559
[ "pattern", "listener" ]
void
true
4
6.24
apache/kafka
31,560
javadoc
false
_get_param_names
def _get_param_names(self, return_alias): """Get names of all metadata that can be consumed or routed by this method. This method returns the names of all metadata, even the ``False`` ones. Parameters ---------- return_alias : bool Controls whether original or aliased names should be returned. If ``False``, aliases are ignored and original names are returned. Returns ------- names : set of str A set of strings with the names of all metadata. """ return set( alias if return_alias and not request_is_valid(alias) else prop for prop, alias in self._requests.items() if not request_is_valid(alias) or alias is not False )
Get names of all metadata that can be consumed or routed by this method. This method returns the names of all metadata, even the ``False`` ones. Parameters ---------- return_alias : bool Controls whether original or aliased names should be returned. If ``False``, aliases are ignored and original names are returned. Returns ------- names : set of str A set of strings with the names of all metadata.
python
sklearn/utils/_metadata_requests.py
407
[ "self", "return_alias" ]
false
4
6.08
scikit-learn/scikit-learn
64,340
numpy
false
copyOf
@IgnoreJRERequirement // Users will use this only if they're already using streams. public static ImmutableDoubleArray copyOf(DoubleStream stream) { // Note this uses very different growth behavior from copyOf(Iterable) and the builder. double[] array = stream.toArray(); return (array.length == 0) ? EMPTY : new ImmutableDoubleArray(array); }
Returns an immutable array containing all the values from {@code stream}, in order. @since 33.4.0 (but since 22.0 in the JRE flavor)
java
android/guava/src/com/google/common/primitives/ImmutableDoubleArray.java
176
[ "stream" ]
ImmutableDoubleArray
true
2
6
google/guava
51,352
javadoc
false
replicaId
public int replicaId() { return replicaId; }
Return the ID for this replica. @return The ID for this replica
java
clients/src/main/java/org/apache/kafka/clients/admin/QuorumInfo.java
139
[]
true
1
6.96
apache/kafka
31,560
javadoc
false
findAdvisorsThatCanApply
protected List<Advisor> findAdvisorsThatCanApply( List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) { ProxyCreationContext.setCurrentProxiedBeanName(beanName); try { return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); } finally { ProxyCreationContext.setCurrentProxiedBeanName(null); } }
Search the given candidate Advisors to find all Advisors that can apply to the specified bean. @param candidateAdvisors the candidate Advisors @param beanClass the target's bean class @param beanName the target's bean name @return the List of applicable Advisors @see ProxyCreationContext#getCurrentProxiedBeanName()
java
spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAdvisorAutoProxyCreator.java
130
[ "candidateAdvisors", "beanClass", "beanName" ]
true
1
6.08
spring-projects/spring-framework
59,386
javadoc
false
shouldInitialize
private boolean shouldInitialize() { return fetchState.equals(FetchStates.INITIALIZING) && !pendingRevocation; }
Check if we need to retrieve a fetch position for the given partition. True if the partition state is {@link FetchStates#INITIALIZING}, and the partition is not being revoked. <p/> While in this state, a position for the partition will be retrieved (based on committed offsets or partitions offsets). Note that retrieving a position does not mean that we can start fetching from the partition (see {@link #isFetchable()})
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
1,231
[]
true
2
6.64
apache/kafka
31,560
javadoc
false
primitiveValues
public static boolean[] primitiveValues() { return new boolean[] {false, true}; }
Returns a new array of possible values (like an enum would). @return a new array of possible values (like an enum would). @since 3.12.0
java
src/main/java/org/apache/commons/lang3/BooleanUtils.java
378
[]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
withSuffix
default JsonWriter<T> withSuffix(@Nullable String suffix) { if (!StringUtils.hasLength(suffix)) { return this; } return (instance, out) -> { write(instance, out); out.append(suffix); }; }
Return a new {@link JsonWriter} instance that appends the given suffix after the JSON has been written. @param suffix the suffix to write, if any @return a new {@link JsonWriter} instance that appends a suffix after the JSON
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
124
[ "suffix" ]
true
2
7.92
spring-projects/spring-boot
79,428
javadoc
false
_configure_secrets_masker
def _configure_secrets_masker(): """Configure the secrets masker with values from config.""" from airflow._shared.secrets_masker import ( DEFAULT_SENSITIVE_FIELDS, _secrets_masker as secrets_masker_core, ) from airflow.configuration import conf min_length_to_mask = conf.getint("logging", "min_length_masked_secret", fallback=5) secret_mask_adapter = conf.getimport("logging", "secret_mask_adapter", fallback=None) sensitive_fields = DEFAULT_SENSITIVE_FIELDS.copy() sensitive_variable_fields = conf.get("core", "sensitive_var_conn_names") if sensitive_variable_fields: sensitive_fields |= frozenset({field.strip() for field in sensitive_variable_fields.split(",")}) core_masker = secrets_masker_core() core_masker.min_length_to_mask = min_length_to_mask core_masker.sensitive_variables_fields = list(sensitive_fields) core_masker.secret_mask_adapter = secret_mask_adapter from airflow.sdk._shared.secrets_masker import _secrets_masker as sdk_secrets_masker sdk_masker = sdk_secrets_masker() sdk_masker.min_length_to_mask = min_length_to_mask sdk_masker.sensitive_variables_fields = list(sensitive_fields) sdk_masker.secret_mask_adapter = secret_mask_adapter
Configure the secrets masker with values from config.
python
airflow-core/src/airflow/settings.py
627
[]
false
2
6.08
apache/airflow
43,597
unknown
false
parseDate
public static Date parseDate(final String str, final Locale locale, final String... parsePatterns) throws ParseException { return parseDateWithLeniency(str, locale, parsePatterns, true); }
Parses a string representing a date by trying a variety of different parsers, using the default date format symbols for the given locale. <p>The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.</p> The parser will be lenient toward the parsed date. @param str the date to parse, not null. @param locale the locale whose date format symbols should be used. If {@code null}, the system locale is used (as per {@link #parseDate(String, String...)}). @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null. @return the parsed date. @throws NullPointerException if the date string or pattern array is null. @throws ParseException if none of the date patterns were suitable (or there were none). @since 3.2
java
src/main/java/org/apache/commons/lang3/time/DateUtils.java
1,264
[ "str", "locale" ]
Date
true
1
6.8
apache/commons-lang
2,896
javadoc
false
I
def I(self): # noqa: E743 """ Returns the (multiplicative) inverse of invertible `self`. Parameters ---------- None Returns ------- ret : matrix object If `self` is non-singular, `ret` is such that ``ret * self`` == ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return ``True``. Raises ------ numpy.linalg.LinAlgError: Singular matrix If `self` is singular. See Also -------- linalg.inv Examples -------- >>> m = np.matrix('[1, 2; 3, 4]'); m matrix([[1, 2], [3, 4]]) >>> m.getI() matrix([[-2. , 1. ], [ 1.5, -0.5]]) >>> m.getI() * m matrix([[ 1., 0.], # may vary [ 0., 1.]]) """ M, N = self.shape if M == N: from numpy.linalg import inv as func else: from numpy.linalg import pinv as func return asmatrix(func(self))
Returns the (multiplicative) inverse of invertible `self`. Parameters ---------- None Returns ------- ret : matrix object If `self` is non-singular, `ret` is such that ``ret * self`` == ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return ``True``. Raises ------ numpy.linalg.LinAlgError: Singular matrix If `self` is singular. See Also -------- linalg.inv Examples -------- >>> m = np.matrix('[1, 2; 3, 4]'); m matrix([[1, 2], [3, 4]]) >>> m.getI() matrix([[-2. , 1. ], [ 1.5, -0.5]]) >>> m.getI() * m matrix([[ 1., 0.], # may vary [ 0., 1.]])
python
numpy/matrixlib/defmatrix.py
801
[ "self" ]
false
3
7.68
numpy/numpy
31,054
numpy
false
compare
public static int compare(final char x, final char y) { return x - y; }
Compares two {@code char} values numerically. This is the same functionality as provided in Java 7. @param x the first {@code char} to compare @param y the second {@code char} to compare @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if {@code x < y}; and a value greater than {@code 0} if {@code x > y} @since 3.4
java
src/main/java/org/apache/commons/lang3/CharUtils.java
72
[ "x", "y" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
join
@SafeVarargs public static <T> String join(final T... elements) { return join(elements, null); }
Joins the elements of the provided array into a single String containing the provided list of elements. <p> No separator is added to the joined String. Null objects or empty strings within the array are represented by empty strings. </p> <pre> StringUtils.join(null) = null StringUtils.join([]) = "" StringUtils.join([null]) = "" StringUtils.join(["a", "b", "c"]) = "abc" StringUtils.join([null, "", "a"]) = "a" </pre> @param <T> the specific type of values to join together. @param elements the values to join together, may be null. @return the joined String, {@code null} if null array input. @since 2.0 @since 3.0 Changed signature to use varargs
java
src/main/java/org/apache/commons/lang3/StringUtils.java
4,700
[]
String
true
1
6.8
apache/commons-lang
2,896
javadoc
false
toString
@Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(type.getLabel()).append(' ').append(arch.getLabel()); return builder.toString(); }
Tests if {@link Processor} is type of x86. @return {@code true}, if {@link Processor} is {@link Type#X86}, else {@code false}.
java
src/main/java/org/apache/commons/lang3/arch/Processor.java
245
[]
String
true
1
6.88
apache/commons-lang
2,896
javadoc
false
ensureActiveGroup
boolean ensureActiveGroup(final Timer timer) { // always ensure that the coordinator is ready because we may have been disconnected // when sending heartbeats and does not necessarily require us to rejoin the group. if (!ensureCoordinatorReady(timer)) { return false; } startHeartbeatThreadIfNeeded(); return joinGroupIfNeeded(timer); }
Ensure the group is active (i.e., joined and synced) @param timer Timer bounding how long this method can block @throws KafkaException if the callback throws exception @return true iff the group is active
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractCoordinator.java
413
[ "timer" ]
true
2
7.76
apache/kafka
31,560
javadoc
false
concatenate
def concatenate(arrays, axis=0): """ Concatenate a sequence of arrays along the given axis. Parameters ---------- arrays : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- result : MaskedArray The concatenated array with any masked entries preserved. See Also -------- numpy.concatenate : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy as np >>> import numpy.ma as ma >>> a = ma.arange(3) >>> a[1] = ma.masked >>> b = ma.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b masked_array(data=[2, 3, 4], mask=False, fill_value=999999) >>> ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999) """ d = np.concatenate([getdata(a) for a in arrays], axis) rcls = get_masked_subclass(*arrays) data = d.view(rcls) # Check whether one of the arrays has a non-empty mask. for x in arrays: if getmask(x) is not nomask: break else: return data # OK, so we have to concatenate the masks dm = np.concatenate([getmaskarray(a) for a in arrays], axis) dm = dm.reshape(d.shape) # If we decide to keep a '_shrinkmask' option, we want to check that # all of them are True, and then check for dm.any() data._mask = _shrink_mask(dm) return data
Concatenate a sequence of arrays along the given axis. Parameters ---------- arrays : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- result : MaskedArray The concatenated array with any masked entries preserved. See Also -------- numpy.concatenate : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy as np >>> import numpy.ma as ma >>> a = ma.arange(3) >>> a[1] = ma.masked >>> b = ma.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b masked_array(data=[2, 3, 4], mask=False, fill_value=999999) >>> ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999)
python
numpy/ma/core.py
7,297
[ "arrays", "axis" ]
false
4
7.6
numpy/numpy
31,054
numpy
false
compare
@InlineMe(replacement = "Boolean.compare(a, b)") public static int compare(boolean a, boolean b) { return Boolean.compare(a, b); }
Compares the two specified {@code boolean} values in the standard way ({@code false} is considered less than {@code true}). The sign of the value returned is the same as that of {@code ((Boolean) a).compareTo(b)}. <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the equivalent {@link Boolean#compare} method instead. @param a the first {@code boolean} to compare @param b the second {@code boolean} to compare @return a positive number if only {@code a} is {@code true}, a negative number if only {@code b} is true, or zero if {@code a == b}
java
android/guava/src/com/google/common/primitives/Booleans.java
125
[ "a", "b" ]
true
1
6.64
google/guava
51,352
javadoc
false
unwrapReturnValue
private @Nullable Object unwrapReturnValue(@Nullable Object returnValue) { return ObjectUtils.unwrapOptional(returnValue); }
Find a cached value only for {@link CacheableOperation} that passes the condition. @param contexts the cacheable operations @return a {@link Cache.ValueWrapper} holding the cached value, or {@code null} if none is found
java
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
635
[ "returnValue" ]
Object
true
1
6.64
spring-projects/spring-framework
59,386
javadoc
false
numpy_random
def numpy_random(dtype, *shapes): """Return a random numpy tensor of the provided dtype. Args: shapes: int or a sequence of ints to defining the shapes of the tensor dtype: use the dtypes from numpy (https://numpy.org/doc/stable/user/basics.types.html) Return: numpy tensor of dtype """ # TODO: consider more complex/custom dynamic ranges for # comprehensive test coverage. return np.random.rand(*shapes).astype(dtype)
Return a random numpy tensor of the provided dtype. Args: shapes: int or a sequence of ints to defining the shapes of the tensor dtype: use the dtypes from numpy (https://numpy.org/doc/stable/user/basics.types.html) Return: numpy tensor of dtype
python
benchmarks/operator_benchmark/benchmark_utils.py
35
[ "dtype" ]
false
1
6.24
pytorch/pytorch
96,034
google
false
afterPropertiesSet
@Override public void afterPropertiesSet() throws ClassNotFoundException, NoSuchMethodException { prepare(); // Use specific name if given, else fall back to bean name. String name = (this.name != null ? this.name : this.beanName); // Consider the concurrent flag to choose between stateful and stateless job. Class<? extends Job> jobClass = (this.concurrent ? MethodInvokingJob.class : StatefulMethodInvokingJob.class); // Build JobDetail instance. JobDetailImpl jdi = new JobDetailImpl(); jdi.setName(name != null ? name : toString()); jdi.setGroup(this.group); jdi.setJobClass(jobClass); jdi.setDurability(true); jdi.getJobDataMap().put("methodInvoker", this); this.jobDetail = jdi; postProcessJobDetail(this.jobDetail); }
Set the name of the target bean in the Spring BeanFactory. <p>This is an alternative to specifying {@link #setTargetObject "targetObject"}, allowing for non-singleton beans to be invoked. Note that specified "targetObject" and {@link #setTargetClass "targetClass"} values will override the corresponding effect of this "targetBeanName" setting (i.e. statically pre-define the bean type or even the bean object).
java
spring-context-support/src/main/java/org/springframework/scheduling/quartz/MethodInvokingJobDetailFactoryBean.java
161
[]
void
true
4
6.4
spring-projects/spring-framework
59,386
javadoc
false
_wrap
def _wrap( orig: Callable, dim_offset: Optional[int] = None, keepdim_offset: Optional[int] = None, dim_name: Optional[str] = None, single_dim: Optional[bool] = None, reduce: Optional[bool] = None, ) -> Callable: """ Wrap a PyTorch function to support first-class dimensions. Args: orig: Original function to wrap dim_offset: Offset for dimension argument (default: 0) keepdim_offset: Offset for keepdim argument (default: 1) dim_name: Name of dimension parameter (default: "dim") single_dim: Whether function takes single dimension (default: False) reduce: Whether function reduces dimensions (default: True) """ dim_name = dim_name or "dim" wrapper = WrappedOperator(orig, patched_dim_method, dim_name) if dim_offset is not None: wrapper.dim_offset = dim_offset if keepdim_offset is not None: wrapper.keepdim_offset = keepdim_offset if single_dim is not None: wrapper.single_dim = single_dim if reduce is not None: wrapper.reduce = reduce return wrapper.function()
Wrap a PyTorch function to support first-class dimensions. Args: orig: Original function to wrap dim_offset: Offset for dimension argument (default: 0) keepdim_offset: Offset for keepdim argument (default: 1) dim_name: Name of dimension parameter (default: "dim") single_dim: Whether function takes single dimension (default: False) reduce: Whether function reduces dimensions (default: True)
python
functorch/dim/_wrap.py
215
[ "orig", "dim_offset", "keepdim_offset", "dim_name", "single_dim", "reduce" ]
Callable
true
6
6.08
pytorch/pytorch
96,034
google
false
unmodifiableMultiset
public static <E extends @Nullable Object> Multiset<E> unmodifiableMultiset( Multiset<? extends E> multiset) { if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) { @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe Multiset<E> result = (Multiset<E>) multiset; return result; } return new UnmodifiableMultiset<>(checkNotNull(multiset)); }
Returns an unmodifiable view of the specified multiset. Query operations on the returned multiset "read through" to the specified multiset, and attempts to modify the returned multiset result in an {@link UnsupportedOperationException}. <p>The returned multiset will be serializable if the specified multiset is serializable. @param multiset the multiset for which an unmodifiable view is to be generated @return an unmodifiable view of the multiset
java
android/guava/src/com/google/common/collect/Multisets.java
106
[ "multiset" ]
true
3
7.44
google/guava
51,352
javadoc
false
getExitingExecutorService
@J2ktIncompatible @GwtIncompatible // concurrency public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) { return new Application().getExitingExecutorService(executor); }
Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete. It does so by using daemon threads and adding a shutdown hook to wait for their completion. <p>This method waits 120 seconds before continuing with JVM termination, even if the executor has not finished its work. <p>This is mainly for fixed thread pools. See {@link Executors#newFixedThreadPool(int)}. @param executor the executor to modify to make sure it exits when the application is finished @return an unmodifiable version of the input which will not hang the JVM
java
android/guava/src/com/google/common/util/concurrent/MoreExecutors.java
129
[ "executor" ]
ExecutorService
true
1
6.72
google/guava
51,352
javadoc
false
tryParse
@GwtIncompatible // regular expressions public static @Nullable Float tryParse(String string) { if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(lowasser): could be potentially optimized, but only with // extensive testing try { return Float.parseFloat(string); } catch (NumberFormatException e) { // Float.parseFloat has changed specs several times, so fall through // gracefully } } return null; }
Parses the specified string as a single-precision floating point value. The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. <p>Unlike {@link Float#parseFloat(String)}, this method returns {@code null} instead of throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link Float#valueOf(String)}, except that leading and trailing whitespace is not permitted. <p>This implementation is likely to be faster than {@code Float.parseFloat} if many failures are expected. @param string the string representation of a {@code float} value @return the floating point value represented by {@code string}, or {@code null} if {@code string} has a length of zero or cannot be parsed as a {@code float} value @throws NullPointerException if {@code string} is {@code null} @since 14.0
java
android/guava/src/com/google/common/primitives/Floats.java
721
[ "string" ]
Float
true
3
7.76
google/guava
51,352
javadoc
false
validateSyntax
private static boolean validateSyntax(List<String> parts) { int lastIndex = parts.size() - 1; // Validate the last part specially, as it has different syntax rules. if (!validatePart(parts.get(lastIndex), true)) { return false; } for (int i = 0; i < lastIndex; i++) { String part = parts.get(i); if (!validatePart(part, false)) { return false; } } return true; }
Validation method used by {@code from} to ensure that the domain name is syntactically valid according to RFC 1035. @return Is the domain name syntactically valid?
java
android/guava/src/com/google/common/net/InternetDomainName.java
270
[ "parts" ]
true
4
7.04
google/guava
51,352
javadoc
false
rename_categories
def rename_categories(self, new_categories) -> Self: """ Rename categories. This method is commonly used to re-label or adjust the category names in categorical data without changing the underlying data. It is useful in situations where you want to modify the labels used for clarity, consistency, or readability. Parameters ---------- new_categories : list-like, dict-like or callable New categories which will replace old categories. * list-like: all items must be unique and the number of items in the new categories must match the existing number of categories. * dict-like: specifies a mapping from old categories to new. Categories not contained in the mapping are passed through and extra categories in the mapping are ignored. * callable : a callable that is called on all items in the old categories and whose return values comprise the new categories. Returns ------- Categorical Categorical with renamed categories. Raises ------ ValueError If new categories are list-like and do not have the same number of items than the current categories or do not validate as categories See Also -------- reorder_categories : Reorder categories. add_categories : Add new categories. remove_categories : Remove the specified categories. remove_unused_categories : Remove categories which are not used. set_categories : Set the categories to the specified ones. Examples -------- >>> c = pd.Categorical(["a", "a", "b"]) >>> c.rename_categories([0, 1]) [0, 0, 1] Categories (2, int64): [0, 1] For dict-like ``new_categories``, extra keys are ignored and categories not in the dictionary are passed through >>> c.rename_categories({"a": "A", "c": "C"}) ['A', 'A', 'b'] Categories (2, str): ['A', 'b'] You may also provide a callable to create the new categories >>> c.rename_categories(lambda x: x.upper()) ['A', 'A', 'B'] Categories (2, str): ['A', 'B'] """ if is_dict_like(new_categories): new_categories = [ new_categories.get(item, item) for item in self.categories ] elif callable(new_categories): new_categories = [new_categories(item) for item in self.categories] cat = self.copy() cat._set_categories(new_categories) return cat
Rename categories. This method is commonly used to re-label or adjust the category names in categorical data without changing the underlying data. It is useful in situations where you want to modify the labels used for clarity, consistency, or readability. Parameters ---------- new_categories : list-like, dict-like or callable New categories which will replace old categories. * list-like: all items must be unique and the number of items in the new categories must match the existing number of categories. * dict-like: specifies a mapping from old categories to new. Categories not contained in the mapping are passed through and extra categories in the mapping are ignored. * callable : a callable that is called on all items in the old categories and whose return values comprise the new categories. Returns ------- Categorical Categorical with renamed categories. Raises ------ ValueError If new categories are list-like and do not have the same number of items than the current categories or do not validate as categories See Also -------- reorder_categories : Reorder categories. add_categories : Add new categories. remove_categories : Remove the specified categories. remove_unused_categories : Remove categories which are not used. set_categories : Set the categories to the specified ones. Examples -------- >>> c = pd.Categorical(["a", "a", "b"]) >>> c.rename_categories([0, 1]) [0, 0, 1] Categories (2, int64): [0, 1] For dict-like ``new_categories``, extra keys are ignored and categories not in the dictionary are passed through >>> c.rename_categories({"a": "A", "c": "C"}) ['A', 'A', 'b'] Categories (2, str): ['A', 'b'] You may also provide a callable to create the new categories >>> c.rename_categories(lambda x: x.upper()) ['A', 'A', 'B'] Categories (2, str): ['A', 'B']
python
pandas/core/arrays/categorical.py
1,190
[ "self", "new_categories" ]
Self
true
3
8.08
pandas-dev/pandas
47,362
numpy
false
visitVariableStatement
function visitVariableStatement(node: VariableStatement): Statement | undefined { if (isExportOfNamespace(node)) { const variables = getInitializedVariables(node.declarationList); if (variables.length === 0) { // elide statement if there are no initialized variables. return undefined; } return setTextRange( factory.createExpressionStatement( factory.inlineExpressions( map(variables, transformInitializedVariable), ), ), node, ); } else { return visitEachChild(node, visitor, context); } }
Determines whether to emit an accessor declaration. We should not emit the declaration if it does not have a body and is abstract. @param node The declaration node.
typescript
src/compiler/transformers/ts.ts
1,628
[ "node" ]
true
4
6.88
microsoft/TypeScript
107,154
jsdoc
false
remove
@CanIgnoreReturnValue @Override boolean remove(@Nullable Object element);
Removes a <i>single</i> occurrence of the specified element from this multiset, if present. <p>This method refines {@link Collection#remove} to further specify that it <b>may not</b> throw an exception in response to {@code element} being null or of the wrong type. <p>To both remove the element and obtain the previous count of that element, use {@link #remove(Object, int) remove}{@code (element, 1)} instead. @param element the element to remove one occurrence of @return {@code true} if an occurrence was found and removed
java
android/guava/src/com/google/common/collect/Multiset.java
190
[ "element" ]
true
1
6.96
google/guava
51,352
javadoc
false
escape
@Override protected final char @Nullable [] escape(int cp) { if (cp < replacementsLength) { char[] chars = replacements[cp]; if (chars != null) { return chars; } } if (cp >= safeMin && cp <= safeMax) { return null; } return escapeUnsafe(cp); }
Escapes a single Unicode code point using the replacement array and safe range values. If the given character does not have an explicit replacement and lies outside the safe range then {@link #escapeUnsafe} is called. @return the replacement characters, or {@code null} if no escaping was required
java
android/guava/src/com/google/common/escape/ArrayBasedUnicodeEscaper.java
163
[ "cp" ]
true
5
6.32
google/guava
51,352
javadoc
false
clean_column_name
def clean_column_name(name: Hashable) -> Hashable: """ Function to emulate the cleaning of a backtick quoted name. The purpose for this function is to see what happens to the name of identifier if it goes to the process of being parsed a Python code inside a backtick quoted string and than being cleaned (removed of any special characters). Parameters ---------- name : hashable Name to be cleaned. Returns ------- name : hashable Returns the name after tokenizing and cleaning. """ try: # Escape backticks name = name.replace("`", "``") if isinstance(name, str) else name tokenized = tokenize_string(f"`{name}`") tokval = next(tokenized)[1] return create_valid_python_identifier(tokval) except SyntaxError: return name
Function to emulate the cleaning of a backtick quoted name. The purpose for this function is to see what happens to the name of identifier if it goes to the process of being parsed a Python code inside a backtick quoted string and than being cleaned (removed of any special characters). Parameters ---------- name : hashable Name to be cleaned. Returns ------- name : hashable Returns the name after tokenizing and cleaning.
python
pandas/core/computation/parsing.py
108
[ "name" ]
Hashable
true
2
6.88
pandas-dev/pandas
47,362
numpy
false
get_performance_dag_environment_variable
def get_performance_dag_environment_variable(performance_dag_conf: dict[str, str], env_name: str) -> str: """ Get env variable value. Returns value of environment variable with given env_name based on provided `performance_dag_conf`. :param performance_dag_conf: dict with environment variables as keys and their values as values :param env_name: name of the environment variable value of which should be returned. :return: value of environment variable taken from performance_dag_conf or its default value, if it was not present in the dictionary (if applicable) :rtype: str :raises: ValueError: if env_name is a mandatory environment variable but it is missing from performance_dag_conf if env_name is not a valid name of an performance dag environment variable """ if env_name in MANDATORY_performance_DAG_VARIABLES: if env_name not in performance_dag_conf: raise ValueError( f"Mandatory environment variable '{env_name}' is missing from performance dag configuration." ) return performance_dag_conf[env_name] if env_name not in performance_DAG_VARIABLES_DEFAULT_VALUES: raise ValueError( f"Provided environment variable '{env_name}' is not a valid performance dag" f"configuration variable." ) return performance_dag_conf.get(env_name, performance_DAG_VARIABLES_DEFAULT_VALUES[env_name])
Get env variable value. Returns value of environment variable with given env_name based on provided `performance_dag_conf`. :param performance_dag_conf: dict with environment variables as keys and their values as values :param env_name: name of the environment variable value of which should be returned. :return: value of environment variable taken from performance_dag_conf or its default value, if it was not present in the dictionary (if applicable) :rtype: str :raises: ValueError: if env_name is a mandatory environment variable but it is missing from performance_dag_conf if env_name is not a valid name of an performance dag environment variable
python
performance/src/performance_dags/performance_dag/performance_dag_utils.py
581
[ "performance_dag_conf", "env_name" ]
str
true
4
7.76
apache/airflow
43,597
sphinx
false
field
public XContentBuilder field(String name, Boolean value) throws IOException { return (value == null) ? nullField(name) : field(name, value.booleanValue()); }
@return the value of the "human readable" flag. When the value is equal to true, some types of values are written in a format easier to read for a human.
java
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContentBuilder.java
392
[ "name", "value" ]
XContentBuilder
true
2
6.96
elastic/elasticsearch
75,680
javadoc
false
get_dag
def get_dag(self, dag_id, session: Session = NEW_SESSION): """ Get the DAG out of the dictionary, and refreshes it if expired. :param dag_id: DAG ID """ # Avoid circular import from airflow.models.dag import DagModel dag = self.dags.get(dag_id) # If DAG Model is absent, we can't check last_expired property. Is the DAG not yet synchronized? if (orm_dag := DagModel.get_current(dag_id, session=session)) is None: return dag is_expired = ( orm_dag.last_expired and dag and dag.last_loaded and dag.last_loaded < orm_dag.last_expired ) if is_expired: # Remove associated dags so we can re-add them. self.dags.pop(dag_id, None) if dag is None or is_expired: # Reprocess source file. found_dags = self.process_file( filepath=correct_maybe_zipped(orm_dag.fileloc), only_if_updated=False ) # If the source file no longer exports `dag_id`, delete it from self.dags if found_dags and dag_id in [found_dag.dag_id for found_dag in found_dags]: return self.dags[dag_id] self.dags.pop(dag_id, None) return self.dags.get(dag_id)
Get the DAG out of the dictionary, and refreshes it if expired. :param dag_id: DAG ID
python
airflow-core/src/airflow/dag_processing/dagbag.py
280
[ "self", "dag_id", "session" ]
true
10
7.04
apache/airflow
43,597
sphinx
false
convertToNodeArray
private static Node[] convertToNodeArray(List<Integer> replicaIds, Map<Integer, Node> nodesById) { // Since this is on hot path for partition info, use indexed iteration to avoid allocation overhead of Streams. int size = replicaIds.size(); Node[] nodes = new Node[size]; for (int i = 0; i < size; i++) { Integer replicaId = replicaIds.get(i); Node node = nodesById.get(replicaId); if (node == null) node = new Node(replicaId, "", -1); nodes[i] = node; } return nodes; }
Get a snapshot of the cluster metadata from this response @return the cluster snapshot
java
clients/src/main/java/org/apache/kafka/common/requests/MetadataResponse.java
183
[ "replicaIds", "nodesById" ]
true
3
6.56
apache/kafka
31,560
javadoc
false
hashBlockLoose
std::string hashBlockLoose(BinaryContext &BC, const BinaryBasicBlock &BB) { // The hash is computed by creating a string of all lexicographically ordered // instruction opcodes, which is then hashed with std::hash. std::set<std::string> Opcodes; for (const MCInst &Inst : BB) { // Skip pseudo instructions and nops. if (BC.MIB->isPseudo(Inst) || BC.MIB->isNoop(Inst)) continue; // Ignore unconditional jumps, as they can be added / removed as a result // of basic block reordering. if (BC.MIB->isUnconditionalBranch(Inst)) continue; // Do not distinguish different types of conditional jumps. if (BC.MIB->isConditionalBranch(Inst)) { Opcodes.insert("JMP"); continue; } std::string Mnemonic = BC.InstPrinter->getMnemonic(Inst).first; llvm::erase_if(Mnemonic, [](unsigned char ch) { return std::isspace(ch); }); Opcodes.insert(Mnemonic); } std::string HashString; for (const std::string &Opcode : Opcodes) HashString.append(Opcode); return HashString; }
collisions that need to be resolved by a stronger hashing.
cpp
bolt/lib/Core/HashUtilities.cpp
133
[]
true
5
7.2
llvm/llvm-project
36,021
doxygen
false
postProcessBeforeInstantiation
default @Nullable Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { return null; }
Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>. The returned bean object may be a proxy to use instead of the target bean, effectively suppressing default instantiation of the target bean. <p>If a non-null object is returned by this method, the bean creation process will be short-circuited. The only further processing applied is the {@link #postProcessAfterInitialization} callback from the configured {@link BeanPostProcessor BeanPostProcessors}. <p>This callback will be applied to bean definitions with their bean class, as well as to factory-method definitions in which case the returned bean type will be passed in here. <p>Post-processors may implement the extended {@link SmartInstantiationAwareBeanPostProcessor} interface in order to predict the type of the bean object that they are going to return here. <p>The default implementation returns {@code null}. @param beanClass the class of the bean to be instantiated @param beanName the name of the bean @return the bean object to expose instead of a default instance of the target bean, or {@code null} to proceed with default instantiation @throws org.springframework.beans.BeansException in case of errors @see #postProcessAfterInstantiation @see org.springframework.beans.factory.support.AbstractBeanDefinition#getBeanClass() @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName()
java
spring-beans/src/main/java/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.java
70
[ "beanClass", "beanName" ]
Object
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
toArray
public static byte[] toArray(Collection<? extends Number> collection) { if (collection instanceof ByteArrayAsList) { return ((ByteArrayAsList) collection).toByteArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; byte[] array = new byte[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue(); } return array; }
Returns an array containing each value of {@code collection}, converted to a {@code byte} value in the manner of {@link Number#byteValue}. <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. Calling this method is as thread-safe as calling that method. @param collection a collection of {@code Number} instances @return an array containing the same values as {@code collection}, in the same order, converted to primitives @throws NullPointerException if {@code collection} or any of its elements is null @since 1.0 (parameter was {@code Collection<Byte>} before 12.0)
java
android/guava/src/com/google/common/primitives/Bytes.java
220
[ "collection" ]
true
3
8.08
google/guava
51,352
javadoc
false
_is_strictly_monotonic_increasing
def _is_strictly_monotonic_increasing(self) -> bool: """ Return if the index is strictly monotonic increasing (only increasing) values. Examples -------- >>> Index([1, 2, 3])._is_strictly_monotonic_increasing True >>> Index([1, 2, 2])._is_strictly_monotonic_increasing False >>> Index([1, 3, 2])._is_strictly_monotonic_increasing False """ return self.is_unique and self.is_monotonic_increasing
Return if the index is strictly monotonic increasing (only increasing) values. Examples -------- >>> Index([1, 2, 3])._is_strictly_monotonic_increasing True >>> Index([1, 2, 2])._is_strictly_monotonic_increasing False >>> Index([1, 3, 2])._is_strictly_monotonic_increasing False
python
pandas/core/indexes/base.py
2,424
[ "self" ]
bool
true
2
6.8
pandas-dev/pandas
47,362
unknown
false
isAssignable
private static boolean isAssignable(Method writeMethod, Method readMethod, PropertyDescriptor sourcePd, PropertyDescriptor targetPd) { Type paramType = writeMethod.getGenericParameterTypes()[0]; if (paramType instanceof Class<?> clazz) { return ClassUtils.isAssignable(clazz, readMethod.getReturnType()); } else if (paramType.equals(readMethod.getGenericReturnType())) { return true; } else { ResolvableType sourceType = ((GenericTypeAwarePropertyDescriptor) sourcePd).getReadMethodType(); ResolvableType targetType = ((GenericTypeAwarePropertyDescriptor) targetPd).getWriteMethodType(); // Ignore generic types in assignable check if either ResolvableType has unresolvable generics. return (sourceType.hasUnresolvableGenerics() || targetType.hasUnresolvableGenerics() ? ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType()) : targetType.isAssignableFrom(sourceType)); } }
Copy the property values of the given source bean into the given target bean. <p>Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored. <p>As of Spring Framework 5.3, this method honors generic type information when matching properties in the source and target objects. See the documentation for {@link #copyProperties(Object, Object)} for details. @param source the source bean @param target the target bean @param editable the class (or interface) to restrict property setting to @param ignoreProperties array of property names to ignore @throws BeansException if the copying failed @see BeanWrapper
java
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
841
[ "writeMethod", "readMethod", "sourcePd", "targetPd" ]
true
5
6.88
spring-projects/spring-framework
59,386
javadoc
false
detect_console_encoding
def detect_console_encoding() -> str: """ Try to find the most capable encoding supported by the console. slightly modified from the way IPython handles the same issue. """ global _initial_defencoding encoding = None try: encoding = sys.stdout.encoding or sys.stdin.encoding except (AttributeError, OSError): pass # try again for something better if not encoding or "ascii" in encoding.lower(): try: encoding = locale.getpreferredencoding() except locale.Error: # can be raised by locale.setlocale(), which is # called by getpreferredencoding # (on some systems, see stdlib locale docs) pass # when all else fails. this will usually be "ascii" if not encoding or "ascii" in encoding.lower(): encoding = sys.getdefaultencoding() # GH#3360, save the reported defencoding at import time # MPL backends may change it. Make available for debugging. if not _initial_defencoding: _initial_defencoding = sys.getdefaultencoding() return encoding
Try to find the most capable encoding supported by the console. slightly modified from the way IPython handles the same issue.
python
pandas/_config/display.py
17
[]
str
true
7
7.2
pandas-dev/pandas
47,362
unknown
false
fromString
@CanIgnoreReturnValue // TODO(b/219820829): consider removing public static HostAndPort fromString(String hostPortString) { checkNotNull(hostPortString); String host; String portString = null; boolean hasBracketlessColons = false; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } else { int colonPos = hostPortString.indexOf(':'); if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { // Exactly 1 colon. Split into host:port. host = hostPortString.substring(0, colonPos); portString = hostPortString.substring(colonPos + 1); } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString; hasBracketlessColons = colonPos >= 0; } } Integer port; if (isNullOrEmpty(portString)) { port = NO_PORT; } else { port = Ints.tryParse(portString); checkArgument(port != null, "Unparseable port number: %s", hostPortString); checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); } return new HostAndPort(host, port, hasBracketlessColons); }
Split a freeform string into a host and port, without strict validation. <p>Note that the host-only formats will leave the port field undefined. You can use {@link #withDefaultPort(int)} to patch in a default value. @param hostPortString the input string to parse. @return if parsing was successful, a populated HostAndPort object. @throws IllegalArgumentException if nothing meaningful could be parsed.
java
android/guava/src/com/google/common/net/HostAndPort.java
167
[ "hostPortString" ]
HostAndPort
true
5
8.08
google/guava
51,352
javadoc
false
buildAutowiringMetadata
private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) { if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) { return InjectionMetadata.EMPTY; } final List<InjectionMetadata.InjectedElement> elements = new ArrayList<>(); Class<?> targetClass = ClassUtils.getUserClass(clazz); do { final List<InjectionMetadata.InjectedElement> fieldElements = new ArrayList<>(); ReflectionUtils.doWithLocalFields(targetClass, field -> { MergedAnnotation<?> ann = findAutowiredAnnotation(field); if (ann != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isInfoEnabled()) { logger.info("Autowired annotation is not supported on static fields: " + field); } return; } boolean required = determineRequiredStatus(ann); fieldElements.add(new AutowiredFieldElement(field, required)); } }); final List<InjectionMetadata.InjectedElement> methodElements = new ArrayList<>(); ReflectionUtils.doWithLocalMethods(targetClass, method -> { if (method.isBridge()) { return; } MergedAnnotation<?> ann = findAutowiredAnnotation(method); if (ann != null && method.equals(BridgeMethodResolver.getMostSpecificMethod(method, clazz))) { if (Modifier.isStatic(method.getModifiers())) { if (logger.isInfoEnabled()) { logger.info("Autowired annotation is not supported on static methods: " + method); } return; } if (method.getParameterCount() == 0) { if (method.getDeclaringClass().isRecord()) { // Annotations on the compact constructor arguments made available on accessors, ignoring. return; } if (logger.isInfoEnabled()) { logger.info("Autowired annotation should only be used on methods with parameters: " + method); } } boolean required = determineRequiredStatus(ann); PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method, clazz); methodElements.add(new AutowiredMethodElement(method, required, pd)); } }); elements.addAll(0, sortMethodElements(methodElements, targetClass)); elements.addAll(0, fieldElements); targetClass = targetClass.getSuperclass(); } while (targetClass != null && targetClass != Object.class); return InjectionMetadata.forElements(elements, clazz); }
<em>Native</em> processing method for direct calls with an arbitrary target instance, resolving all of its fields and methods which are annotated with one of the configured 'autowired' annotation types. @param bean the target instance to process @throws BeanCreationException if autowiring failed @see #setAutowiredAnnotationTypes(Set)
java
spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
546
[ "clazz" ]
InjectionMetadata
true
14
6.16
spring-projects/spring-framework
59,386
javadoc
false
ipinfoTypeCleanup
static String ipinfoTypeCleanup(String type) { List<String> parts = Arrays.asList(type.split("[ _.]")); return parts.stream().filter((s) -> IPINFO_TYPE_STOP_WORDS.contains(s) == false).collect(Collectors.joining("_")); }
Cleans up the database_type String from an ipinfo database by splitting on punctuation, removing stop words, and then joining with an underscore. <p> e.g. "ipinfo free_foo_sample.mmdb" -> "foo" @param type the database_type from an ipinfo database @return a cleaned up database_type string
java
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/IpinfoIpDataLookups.java
72
[ "type" ]
String
true
1
6.96
elastic/elasticsearch
75,680
javadoc
false
generateBeanName
public static String generateBeanName( BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean) throws BeanDefinitionStoreException { String generatedBeanName = definition.getBeanClassName(); if (generatedBeanName == null) { if (definition.getParentName() != null) { generatedBeanName = definition.getParentName() + "$child"; } else if (definition.getFactoryBeanName() != null) { generatedBeanName = definition.getFactoryBeanName() + "$created"; } } if (!StringUtils.hasText(generatedBeanName)) { throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " + "'class' nor 'parent' nor 'factory-bean' - can't generate bean name"); } if (isInnerBean) { // Inner bean: generate identity hashcode suffix. return generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition); } // Top-level bean: use plain class name with unique suffix if necessary. return uniqueBeanName(generatedBeanName, registry); }
Generate a bean name for the given bean definition, unique within the given bean factory. @param definition the bean definition to generate a bean name for @param registry the bean factory that the definition is going to be registered with (to check for existing bean names) @param isInnerBean whether the given bean definition will be registered as inner bean or as top-level bean (allowing for special name generation for inner beans versus top-level beans) @return the generated bean name @throws BeanDefinitionStoreException if no unique name can be generated for the given bean definition
java
spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionReaderUtils.java
103
[ "definition", "registry", "isInnerBean" ]
String
true
6
7.76
spring-projects/spring-framework
59,386
javadoc
false
append
private void append(StringBuilder report, Map<String, List<PropertyMigration>> content) { content.forEach((name, properties) -> { report.append(String.format("Property source '%s':%n", name)); properties.sort(PropertyMigration.COMPARATOR); properties.forEach((property) -> { report.append(String.format("\tKey: %s%n", property.getProperty().getName())); if (property.getLineNumber() != null) { report.append(String.format("\t\tLine: %d%n", property.getLineNumber())); } report.append(String.format("\t\t%s%n", property.determineReason())); }); report.append(String.format("%n")); }); }
Return a report for all the properties that are no longer supported. If no such properties were found, return {@code null}. @return a report with the configurations keys that are no longer supported
java
core/spring-boot-properties-migrator/src/main/java/org/springframework/boot/context/properties/migrator/PropertiesMigrationReport.java
89
[ "report", "content" ]
void
true
2
7.04
spring-projects/spring-boot
79,428
javadoc
false
binaryBeMsb0ToHexDigit
public static char binaryBeMsb0ToHexDigit(final boolean[] src) { return binaryBeMsb0ToHexDigit(src, 0); }
Converts the first 4 bits of a binary (represented as boolean array) in big-endian MSB0 bit ordering to a hexadecimal digit. <p> (1, 0, 0, 0) is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0) is converted to '4'. </p> @param src the binary to convert. @return a hexadecimal digit representing the selected bits. @throws IllegalArgumentException if {@code src} is empty. @throws NullPointerException if {@code src} is {@code null}.
java
src/main/java/org/apache/commons/lang3/Conversion.java
89
[ "src" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
getMatchingMethod
public static Method getMatchingMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) { Objects.requireNonNull(cls, "cls"); Validate.notEmpty(methodName, "methodName"); final List<Method> methods = Stream.of(cls.getDeclaredMethods()) .filter(method -> method.getName().equals(methodName)) .collect(Collectors.toList()); final List<Class<?>> allSuperclassesAndInterfaces = getAllSuperclassesAndInterfaces(cls); Collections.reverse(allSuperclassesAndInterfaces); allSuperclassesAndInterfaces.stream() .map(Class::getDeclaredMethods) .flatMap(Stream::of) .filter(method -> method.getName().equals(methodName)) .forEach(methods::add); for (final Method method : methods) { if (Arrays.deepEquals(method.getParameterTypes(), parameterTypes)) { return method; } } final TreeMap<Integer, List<Method>> candidates = new TreeMap<>(); methods.stream() .filter(method -> ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) .forEach(method -> { final int distance = distance(parameterTypes, method.getParameterTypes()); final List<Method> candidatesAtDistance = candidates.computeIfAbsent(distance, k -> new ArrayList<>()); candidatesAtDistance.add(method); }); if (candidates.isEmpty()) { return null; } final List<Method> bestCandidates = candidates.values().iterator().next(); if (bestCandidates.size() == 1 || !Objects.equals(bestCandidates.get(0).getDeclaringClass(), bestCandidates.get(1).getDeclaringClass())) { return bestCandidates.get(0); } throw new IllegalStateException(String.format("Found multiple candidates for method %s on class %s : %s", methodName + Stream.of(parameterTypes).map(String::valueOf).collect(Collectors.joining(",", "(", ")")), cls.getName(), bestCandidates.stream().map(Method::toString).collect(Collectors.joining(",", "[", "]")))); }
Gets a method whether or not it's accessible. If no such method can be found, return {@code null}. @param cls The class that will be subjected to the method search. @param methodName The method that we wish to call. @param parameterTypes Argument class types. @throws IllegalStateException if there is no unique result. @throws NullPointerException if the class is {@code null}. @return The method. @since 3.5
java
src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
365
[ "cls", "methodName" ]
Method
true
5
8.08
apache/commons-lang
2,896
javadoc
false
value_counts_arraylike
def value_counts_arraylike( values: np.ndarray, dropna: bool, mask: npt.NDArray[np.bool_] | None = None ) -> tuple[ArrayLike, npt.NDArray[np.int64], int]: """ Parameters ---------- values : np.ndarray dropna : bool mask : np.ndarray[bool] or None, default None Returns ------- uniques : np.ndarray counts : np.ndarray[np.int64] """ original = values values = _ensure_data(values) keys, counts, na_counter = htable.value_count(values, dropna, mask=mask) if needs_i8_conversion(original.dtype): # datetime, timedelta, or period if dropna: mask = keys != iNaT keys, counts = keys[mask], counts[mask] res_keys = _reconstruct_data(keys, original.dtype, original) return res_keys, counts, na_counter
Parameters ---------- values : np.ndarray dropna : bool mask : np.ndarray[bool] or None, default None Returns ------- uniques : np.ndarray counts : np.ndarray[np.int64]
python
pandas/core/algorithms.py
955
[ "values", "dropna", "mask" ]
tuple[ArrayLike, npt.NDArray[np.int64], int]
true
3
6.4
pandas-dev/pandas
47,362
numpy
false
writeTo
int writeTo(TransferableChannel channel, int position, int length) throws IOException;
Attempts to write the contents of this buffer to a channel. @param channel The channel to write to @param position The position in the buffer to write from @param length The number of bytes to write @return The number of bytes actually written @throws IOException For any IO errors
java
clients/src/main/java/org/apache/kafka/common/record/TransferableRecords.java
38
[ "channel", "position", "length" ]
true
1
6.48
apache/kafka
31,560
javadoc
false
apply
R apply(T input) throws E;
Applies this function. @param input the input for the function @return the result of the function @throws E Thrown when the function fails.
java
src/main/java/org/apache/commons/lang3/function/FailableFunction.java
96
[ "input" ]
R
true
1
6.8
apache/commons-lang
2,896
javadoc
false
axis0_safe_slice
def axis0_safe_slice(X, mask, len_mask): """Return a mask which is safer to use on X than safe_mask. This mask is safer than safe_mask since it returns an empty array, when a sparse matrix is sliced with a boolean mask with all False, instead of raising an unhelpful error in older versions of SciPy. See: https://github.com/scipy/scipy/issues/5361 Also note that we can avoid doing the dot product by checking if the len_mask is not zero in _huber_loss_and_gradient but this is not going to be the bottleneck, since the number of outliers and non_outliers are typically non-zero and it makes the code tougher to follow. Parameters ---------- X : {array-like, sparse matrix} Data on which to apply mask. mask : ndarray Mask to be used on X. len_mask : int The length of the mask. Returns ------- mask : ndarray Array that is safe to use on X. """ if len_mask != 0: return X[safe_mask(X, mask), :] return np.zeros(shape=(0, X.shape[1]))
Return a mask which is safer to use on X than safe_mask. This mask is safer than safe_mask since it returns an empty array, when a sparse matrix is sliced with a boolean mask with all False, instead of raising an unhelpful error in older versions of SciPy. See: https://github.com/scipy/scipy/issues/5361 Also note that we can avoid doing the dot product by checking if the len_mask is not zero in _huber_loss_and_gradient but this is not going to be the bottleneck, since the number of outliers and non_outliers are typically non-zero and it makes the code tougher to follow. Parameters ---------- X : {array-like, sparse matrix} Data on which to apply mask. mask : ndarray Mask to be used on X. len_mask : int The length of the mask. Returns ------- mask : ndarray Array that is safe to use on X.
python
sklearn/utils/_mask.py
115
[ "X", "mask", "len_mask" ]
false
2
6.08
scikit-learn/scikit-learn
64,340
numpy
false
isWhitespace
function isWhitespace(code: number): boolean { return ( code === CharCode.Space || code === CharCode.Tab || code === CharCode.LineFeed || code === CharCode.CarriageReturn ); }
@returns A filter which combines the provided set of filters with an or. The *first* filters that matches defined the return value of the returned filter.
typescript
src/vs/base/common/filters.ts
138
[ "code" ]
true
4
7.04
microsoft/vscode
179,840
jsdoc
false
astype_array
def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> ArrayLike: """ Cast array (ndarray or ExtensionArray) to the new dtype. Parameters ---------- values : ndarray or ExtensionArray dtype : dtype object copy : bool, default False copy if indicated Returns ------- ndarray or ExtensionArray """ if values.dtype == dtype: if copy: return values.copy() return values if not isinstance(values, np.ndarray): # i.e. ExtensionArray values = values.astype(dtype, copy=copy) else: values = _astype_nansafe(values, dtype, copy=copy) # in pandas we don't store numpy str dtypes, so convert to object if isinstance(dtype, np.dtype) and issubclass(values.dtype.type, str): values = np.array(values, dtype=object) return values
Cast array (ndarray or ExtensionArray) to the new dtype. Parameters ---------- values : ndarray or ExtensionArray dtype : dtype object copy : bool, default False copy if indicated Returns ------- ndarray or ExtensionArray
python
pandas/core/dtypes/astype.py
160
[ "values", "dtype", "copy" ]
ArrayLike
true
7
6.56
pandas-dev/pandas
47,362
numpy
false
toTimeZone
public static TimeZone toTimeZone(final TimeZone timeZone) { return ObjectUtils.getIfNull(timeZone, TimeZone::getDefault); }
Returns the given TimeZone if non-{@code null}, otherwise {@link TimeZone#getDefault()}. @param timeZone a locale or {@code null}. @return the given locale if non-{@code null}, otherwise {@link TimeZone#getDefault()}. @since 3.13.0
java
src/main/java/org/apache/commons/lang3/time/TimeZones.java
81
[ "timeZone" ]
TimeZone
true
1
6.32
apache/commons-lang
2,896
javadoc
false
visitImportSpecifier
function visitImportSpecifier(node: ImportSpecifier): VisitResult<ImportSpecifier> | undefined { return !node.isTypeOnly && shouldEmitAliasDeclaration(node) ? node : undefined; }
Visits an import specifier, eliding it if its target, its references, and the compilation settings allow. @param node The import specifier node.
typescript
src/compiler/transformers/ts.ts
2,315
[ "node" ]
true
3
6.32
microsoft/TypeScript
107,154
jsdoc
false
parseExpectedToken
function parseExpectedToken(t: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: string): Node { return parseOptionalToken(t) || createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || Diagnostics._0_expected, arg0 || tokenToString(t)!); }
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
2,540
[ "t", "diagnosticMessage?", "arg0?" ]
true
4
6.64
microsoft/TypeScript
107,154
jsdoc
false
printStackTrace
@Override public void printStackTrace(PrintStream ps) { if (ObjectUtils.isEmpty(this.messageExceptions)) { super.printStackTrace(ps); } else { ps.println(super.toString() + "; message exception details (" + this.messageExceptions.length + ") are:"); for (int i = 0; i < this.messageExceptions.length; i++) { Exception subEx = this.messageExceptions[i]; ps.println("Failed message " + (i + 1) + ":"); subEx.printStackTrace(ps); } } }
Return an array with thrown message exceptions. <p>Note that a general mail server connection failure will not result in failed messages being returned here: A message will only be contained here if actually sending it was attempted but failed. @return the array of thrown message exceptions, or an empty array if no failed messages
java
spring-context-support/src/main/java/org/springframework/mail/MailSendException.java
166
[ "ps" ]
void
true
3
6.88
spring-projects/spring-framework
59,386
javadoc
false
_translate_body
def _translate_body(self, idx_lengths: dict, max_rows: int, max_cols: int): """ Build each <tr> within table <body> as a list Use the following structure: +--------------------------------------------+---------------------------+ | index_header_0 ... index_header_n | data_by_column ... | +--------------------------------------------+---------------------------+ Also add elements to the cellstyle_map for more efficient grouped elements in <style></style> block Parameters ---------- sparsify_index : bool Whether index_headers section will add rowspan attributes (>1) to elements. Returns ------- body : list The associated HTML elements needed for template rendering. """ rlabels = self.data.index.tolist() if not isinstance(self.data.index, MultiIndex): rlabels = [[x] for x in rlabels] body: list = [] visible_row_count: int = 0 for r, row_tup in [ z for z in enumerate(self.data.itertuples()) if z[0] not in self.hidden_rows ]: visible_row_count += 1 if self._check_trim( visible_row_count, max_rows, body, "row", ): break body_row = self._generate_body_row( (r, row_tup, rlabels), max_cols, idx_lengths ) body.append(body_row) return body
Build each <tr> within table <body> as a list Use the following structure: +--------------------------------------------+---------------------------+ | index_header_0 ... index_header_n | data_by_column ... | +--------------------------------------------+---------------------------+ Also add elements to the cellstyle_map for more efficient grouped elements in <style></style> block Parameters ---------- sparsify_index : bool Whether index_headers section will add rowspan attributes (>1) to elements. Returns ------- body : list The associated HTML elements needed for template rendering.
python
pandas/io/formats/style_render.py
625
[ "self", "idx_lengths", "max_rows", "max_cols" ]
true
4
6.24
pandas-dev/pandas
47,362
numpy
false
Singleton
explicit Singleton( typename Singleton::CreateFunc c, typename Singleton::TeardownFunc t = nullptr) { if (c == nullptr) { detail::singletonThrowNullCreator(typeid(T)); } auto vault = SingletonVault::singleton<VaultTag>(); getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t))); vault->registerSingleton(&getEntry()); }
@param c The create function to use (in lieu of new). @param t The teardown function to use (in lieu of delete).
cpp
folly/Singleton.h
728
[ "c" ]
true
2
6.72
facebook/folly
30,157
doxygen
false
peek
@Override public @Nullable E peek() { return isEmpty() ? null : elementData(0); }
Adds the given element to this queue. If this queue has a maximum size, after adding {@code element} the queue will automatically evict its greatest element (according to its comparator), which may be {@code element} itself.
java
android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
317
[]
E
true
2
6.8
google/guava
51,352
javadoc
false
processReturnType
private static @Nullable Object processReturnType( Object proxy, @Nullable Object target, Method method, Object[] arguments, @Nullable Object returnValue) { // Massage return value if necessary if (returnValue != null && returnValue == target && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) { // Special case: it returned "this". Note that we can't help // if the target sets a reference to itself in another returned object. returnValue = proxy; } Class<?> returnType = method.getReturnType(); if (returnValue == null && returnType != void.class && returnType.isPrimitive()) { throw new AopInvocationException( "Null return value from advice does not match primitive return type for: " + method); } if (COROUTINES_REACTOR_PRESENT && KotlinDetector.isSuspendingFunction(method)) { return COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName()) ? CoroutinesUtils.asFlow(returnValue) : CoroutinesUtils.awaitSingleOrNull(returnValue, arguments[arguments.length - 1]); } return returnValue; }
Process a return value. Wraps a return of {@code this} if necessary to be the {@code proxy} and also verifies that {@code null} is not returned as a primitive. Also takes care of the conversion from {@code Mono} to Kotlin Coroutines if needed.
java
spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java
423
[ "proxy", "target", "method", "arguments", "returnValue" ]
Object
true
10
6
spring-projects/spring-framework
59,386
javadoc
false
intersectionWith
public Range<T> intersectionWith(final Range<T> other) { if (!this.isOverlappedBy(other)) { throw new IllegalArgumentException(String.format( "Cannot calculate intersection with non-overlapping range %s", other)); } if (this.equals(other)) { return this; } final T min = getComparator().compare(minimum, other.minimum) < 0 ? other.minimum : minimum; final T max = getComparator().compare(maximum, other.maximum) < 0 ? maximum : other.maximum; return of(min, max, getComparator()); }
Calculate the intersection of {@code this} and an overlapping Range. @param other overlapping Range. @return range representing the intersection of {@code this} and {@code other} ({@code this} if equal). @throws IllegalArgumentException if {@code other} does not overlap {@code this}. @since 3.0.1
java
src/main/java/org/apache/commons/lang3/Range.java
400
[ "other" ]
true
5
7.6
apache/commons-lang
2,896
javadoc
false
autowireByType
protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); Set<String> autowiredBeanNames = new LinkedHashSet<>(propertyNames.length * 2); for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // Don't try autowiring by type for type Object: never makes sense, // even if it technically is an unsatisfied, non-simple property. if (Object.class != pd.getPropertyType()) { MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered); DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { registerDependentBean(autowiredBeanName, beanName); if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }
Abstract method defining "autowire by type" (bean properties by type) behavior. <p>This is like PicoContainer default, in which there must be exactly one bean of the property type in the bean factory. This makes bean factories simple to configure for small namespaces, but doesn't work as well as standard Spring behavior for bigger applications. @param beanName the name of the bean to autowire by type @param mbd the merged bean definition to update through autowiring @param bw the BeanWrapper from which we can obtain information about the bean @param pvs the PropertyValues to register wired objects with
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
1,508
[ "beanName", "mbd", "bw", "pvs" ]
void
true
6
6.88
spring-projects/spring-framework
59,386
javadoc
false
encode
def encode(self, encoding, errors: str = "strict"): """ Encode character string in the Series/Index using indicated encoding. Equivalent to :meth:`str.encode`. Parameters ---------- encoding : str Specifies the encoding to be used. errors : str, optional Specifies the error handling scheme. Possible values are those supported by :meth:`str.encode`. Returns ------- Series/Index of objects A Series or Index with strings encoded into bytes. See Also -------- Series.str.decode : Decodes bytes into strings in a Series/Index. Examples -------- >>> ser = pd.Series(["cow", "123", "()"]) >>> ser.str.encode(encoding="ascii") 0 b'cow' 1 b'123' 2 b'()' dtype: object """ result = self._data.array._str_encode(encoding, errors) return self._wrap_result(result, returns_string=False)
Encode character string in the Series/Index using indicated encoding. Equivalent to :meth:`str.encode`. Parameters ---------- encoding : str Specifies the encoding to be used. errors : str, optional Specifies the error handling scheme. Possible values are those supported by :meth:`str.encode`. Returns ------- Series/Index of objects A Series or Index with strings encoded into bytes. See Also -------- Series.str.decode : Decodes bytes into strings in a Series/Index. Examples -------- >>> ser = pd.Series(["cow", "123", "()"]) >>> ser.str.encode(encoding="ascii") 0 b'cow' 1 b'123' 2 b'()' dtype: object
python
pandas/core/strings/accessor.py
2,179
[ "self", "encoding", "errors" ]
true
1
6.8
pandas-dev/pandas
47,362
numpy
false
get_link
def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey) -> str: """ Retrieve the link from the XComs. :param operator: The Airflow operator object this link is associated to. :param ti_key: TaskInstance ID to return link for. :return: link to external system, but by pulling it from XComs """ self.log.info( "Attempting to retrieve link from XComs with key: %s for task id: %s", self.xcom_key, ti_key ) with create_session() as session: value = session.execute( XComModel.get_many( key=self.xcom_key, run_id=ti_key.run_id, dag_ids=ti_key.dag_id, task_ids=ti_key.task_id, map_indexes=ti_key.map_index, ).with_only_columns(XComModel.value) ).first() if not value: self.log.debug( "No link with name: %s present in XCom as key: %s, returning empty link", self.name, self.xcom_key, ) return "" return XComModel.deserialize_value(value)
Retrieve the link from the XComs. :param operator: The Airflow operator object this link is associated to. :param ti_key: TaskInstance ID to return link for. :return: link to external system, but by pulling it from XComs
python
airflow-core/src/airflow/serialization/serialized_objects.py
3,883
[ "self", "operator", "ti_key" ]
str
true
2
8.08
apache/airflow
43,597
sphinx
false
resolveDefaultValue
protected abstract Object resolveDefaultValue(MetadataGenerationEnvironment environment);
Resolve the default value for this property. @param environment the metadata generation environment @return the default value or {@code null}
java
configuration-metadata/spring-boot-configuration-processor/src/main/java/org/springframework/boot/configurationprocessor/PropertyDescriptor.java
221
[ "environment" ]
Object
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
build
public RestClient build() { if (failureListener == null) { failureListener = new RestClient.FailureListener(); } CloseableHttpAsyncClient httpClient = AccessController.doPrivileged( (PrivilegedAction<CloseableHttpAsyncClient>) this::createHttpClient ); RestClient restClient = new RestClient( httpClient, defaultHeaders, nodes, pathPrefix, failureListener, nodeSelector, strictDeprecationMode, compressionEnabled, metaHeaderEnabled ); httpClient.start(); return restClient; }
Creates a new {@link RestClient} based on the provided configuration.
java
client/rest/src/main/java/org/elasticsearch/client/RestClientBuilder.java
284
[]
RestClient
true
2
6.24
elastic/elasticsearch
75,680
javadoc
false
applyAsLong
long applyAsLong(long left, long right) throws E;
Applies this operator to the given operands. @param left the first operand @param right the second operand @return the operator result @throws E if the operation fails
java
src/main/java/org/apache/commons/lang3/function/FailableLongBinaryOperator.java
39
[ "left", "right" ]
true
1
6.64
apache/commons-lang
2,896
javadoc
false
toBoolean
public static boolean toBoolean(final String str) { return toBooleanObject(str) == Boolean.TRUE; }
Converts a String to a boolean (optimized for performance). <p>{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'} (case insensitive) will return {@code true}. Otherwise, {@code false} is returned.</p> <p>This method performs 4 times faster (JDK1.4) than {@code Boolean.valueOf(String)}. However, this method accepts 'on' and 'yes', 't', 'y' as true values. <pre> BooleanUtils.toBoolean(null) = false BooleanUtils.toBoolean("true") = true BooleanUtils.toBoolean("TRUE") = true BooleanUtils.toBoolean("tRUe") = true BooleanUtils.toBoolean("on") = true BooleanUtils.toBoolean("yes") = true BooleanUtils.toBoolean("false") = false BooleanUtils.toBoolean("x gti") = false BooleanUtils.toBoolean("y") = true BooleanUtils.toBoolean("n") = false BooleanUtils.toBoolean("t") = true BooleanUtils.toBoolean("f") = false </pre> @param str the String to check @return the boolean value of the string, {@code false} if no match or the String is null
java
src/main/java/org/apache/commons/lang3/BooleanUtils.java
510
[ "str" ]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
afterPropertiesSet
@Override public void afterPropertiesSet() throws Exception { if (this.applicationEventClassConstructor == null) { throw new IllegalArgumentException("Property 'applicationEventClass' is required"); } }
Set the application event class to publish. <p>The event class <b>must</b> have a constructor with a single {@code Object} argument for the event source. The interceptor will pass in the invoked object. @throws IllegalArgumentException if the supplied {@code Class} is {@code null} or if it is not an {@code ApplicationEvent} subclass or if it does not expose a constructor that takes a single {@code Object} argument
java
spring-context/src/main/java/org/springframework/context/event/EventPublicationInterceptor.java
86
[]
void
true
2
6.72
spring-projects/spring-framework
59,386
javadoc
false
_check_generated_dataframe
def _check_generated_dataframe( name, case, index, outputs_default, outputs_dataframe_lib, is_supported_dataframe, create_dataframe, assert_frame_equal, ): """Check if the generated DataFrame by the transformer is valid. The DataFrame implementation is specified through the parameters of this function. Parameters ---------- name : str The name of the transformer. case : str A single case from the cases generated by `_output_from_fit_transform`. index : index or None The index of the DataFrame. `None` if the library does not implement a DataFrame with an index. outputs_default : tuple A tuple containing the output data and feature names for the default output. outputs_dataframe_lib : tuple A tuple containing the output data and feature names for the pandas case. is_supported_dataframe : callable A callable that takes a DataFrame instance as input and return whether or E.g. `lambda X: isintance(X, pd.DataFrame)`. create_dataframe : callable A callable taking as parameters `data`, `columns`, and `index` and returns a callable. Be aware that `index` can be ignored. For example, polars dataframes would ignore the idnex. assert_frame_equal : callable A callable taking 2 dataframes to compare if they are equal. """ X_trans, feature_names_default = outputs_default df_trans, feature_names_dataframe_lib = outputs_dataframe_lib assert is_supported_dataframe(df_trans) # We always rely on the output of `get_feature_names_out` of the # transformer used to generate the dataframe as a ground-truth of the # columns. # If a dataframe is passed into transform, then the output should have the same # index expected_index = index if case.endswith("df") else None expected_dataframe = create_dataframe( X_trans, columns=feature_names_dataframe_lib, index=expected_index ) try: assert_frame_equal(df_trans, expected_dataframe) except AssertionError as e: raise AssertionError( f"{name} does not generate a valid dataframe in the {case} " "case. The generated dataframe is not equal to the expected " f"dataframe. The error message is: {e}" ) from e
Check if the generated DataFrame by the transformer is valid. The DataFrame implementation is specified through the parameters of this function. Parameters ---------- name : str The name of the transformer. case : str A single case from the cases generated by `_output_from_fit_transform`. index : index or None The index of the DataFrame. `None` if the library does not implement a DataFrame with an index. outputs_default : tuple A tuple containing the output data and feature names for the default output. outputs_dataframe_lib : tuple A tuple containing the output data and feature names for the pandas case. is_supported_dataframe : callable A callable that takes a DataFrame instance as input and return whether or E.g. `lambda X: isintance(X, pd.DataFrame)`. create_dataframe : callable A callable taking as parameters `data`, `columns`, and `index` and returns a callable. Be aware that `index` can be ignored. For example, polars dataframes would ignore the idnex. assert_frame_equal : callable A callable taking 2 dataframes to compare if they are equal.
python
sklearn/utils/estimator_checks.py
5,072
[ "name", "case", "index", "outputs_default", "outputs_dataframe_lib", "is_supported_dataframe", "create_dataframe", "assert_frame_equal" ]
false
2
6
scikit-learn/scikit-learn
64,340
numpy
false
withClientSaslSupport
public ConfigDef withClientSaslSupport() { SaslConfigs.addClientSaslSupport(this); return this; }
Add standard SASL client configuration options. @return this
java
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
502
[]
ConfigDef
true
1
6.32
apache/kafka
31,560
javadoc
false
ready
@Override public boolean ready(Node node, long now) { if (node.isEmpty()) throw new IllegalArgumentException("Cannot connect to empty node " + node); if (isReady(node, now)) return true; if (connectionStates.canConnect(node.idString(), now)) // if we are interested in sending to a node and we don't have a connection to it, initiate one initiateConnect(node, now); return false; }
Begin connecting to the given node, return true if we are already connected and ready to send to that node. @param node The node to check @param now The current timestamp @return True if we are ready to send to the given node
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
358
[ "node", "now" ]
true
4
8.4
apache/kafka
31,560
javadoc
false
matches
MatchStatus matches(Properties properties);
Test if the given properties match. @param properties the properties to test @return the status of the match
java
spring-beans/src/main/java/org/springframework/beans/factory/config/YamlProcessor.java
378
[ "properties" ]
MatchStatus
true
1
6.8
spring-projects/spring-framework
59,386
javadoc
false
findAnnotationOnBean
<A extends Annotation> @Nullable A findAnnotationOnBean( String beanName, Class<A> annotationType, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
Find an {@link Annotation} of {@code annotationType} on the specified bean, traversing its interfaces and superclasses if no annotation can be found on the given class itself, as well as checking the bean's factory method (if any). @param beanName the name of the bean to look for annotations on @param annotationType the type of annotation to look for (at class, interface or factory method level of the specified bean) @param allowFactoryBeanInit whether a {@code FactoryBean} may get initialized just for the purpose of determining its object type @return the annotation of the given type if found, or {@code null} otherwise @throws NoSuchBeanDefinitionException if there is no bean with the given name @since 5.3.14 @see #findAnnotationOnBean(String, Class) @see #findAllAnnotationsOnBean(String, Class, boolean) @see #getBeanNamesForAnnotation(Class) @see #getBeansWithAnnotation(Class) @see #getType(String, boolean)
java
spring-beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java
398
[ "beanName", "annotationType", "allowFactoryBeanInit" ]
A
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
createClassDescriptor
private static @Nullable ClassDescriptor createClassDescriptor(InputStream inputStream) { try { ClassReader classReader = new ClassReader(inputStream); ClassDescriptor classDescriptor = new ClassDescriptor(); classReader.accept(classDescriptor, ClassReader.SKIP_CODE); return classDescriptor; } catch (IOException ex) { return null; } }
Perform the given callback operation on all main classes from the given jar. @param <T> the result type @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @param callback the callback @return the first callback result or {@code null} @throws IOException in case of I/O errors
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java
261
[ "inputStream" ]
ClassDescriptor
true
2
7.76
spring-projects/spring-boot
79,428
javadoc
false
_ensure_leading_slash
def _ensure_leading_slash(self, ssm_path: str): """ AWS Systems Manager mandate to have a leading "/". Adding it dynamically if not there to the SSM path. :param ssm_path: SSM parameter path """ if not ssm_path.startswith("/"): ssm_path = f"/{ssm_path}" return ssm_path
AWS Systems Manager mandate to have a leading "/". Adding it dynamically if not there to the SSM path. :param ssm_path: SSM parameter path
python
providers/amazon/src/airflow/providers/amazon/aws/secrets/systems_manager.py
193
[ "self", "ssm_path" ]
true
2
6.88
apache/airflow
43,597
sphinx
false
usingExtractedPairs
public <E> Member<T> usingExtractedPairs(BiConsumer<T, Consumer<E>> elements, PairExtractor<E> extractor) { Assert.notNull(elements, "'elements' must not be null"); Assert.notNull(extractor, "'extractor' must not be null"); return usingExtractedPairs(elements, extractor::getName, extractor::getValue); }
Add JSON name/value pairs by extracting values from a series of elements. Typically used with a {@link Iterable#forEach(Consumer)} call, for example: <pre class="code"> members.add(Event::getTags).usingExtractedPairs(Iterable::forEach, pairExtractor); </pre> <p> When used with a named member, the pairs will be added as a new JSON value object: <pre> { "name": { "p1": 1, "p2": 2 } } </pre> When used with an unnamed member the pairs will be added to the existing JSON object: <pre> { "p1": 1, "p2": 2 } </pre> @param <E> the element type @param elements callback used to provide the elements @param extractor a {@link PairExtractor} used to extract the name/value pair @return a {@link Member} which may be configured further @see #usingExtractedPairs(BiConsumer, Function, Function) @see #usingPairs(BiConsumer)
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
496
[ "elements", "extractor" ]
true
1
6.56
spring-projects/spring-boot
79,428
javadoc
false
sort_values
def sort_values( self, *, return_indexer: bool = False, ascending: bool = True, na_position: NaPosition = "last", key: Callable | None = None, ) -> Self | tuple[Self, np.ndarray]: """ Return a sorted copy of the index. Return a sorted copy of the index, and optionally return the indices that sorted the index itself. Parameters ---------- return_indexer : bool, default False Should the indices that would sort the index be returned. ascending : bool, default True Should the index values be sorted in an ascending order. na_position : {'first' or 'last'}, default 'last' Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at the end. key : callable, optional If not None, apply the key function to the index values before sorting. This is similar to the `key` argument in the builtin :meth:`sorted` function, with the notable difference that this `key` function should be *vectorized*. It should expect an ``Index`` and return an ``Index`` of the same shape. Returns ------- sorted_index : pandas.Index Sorted copy of the index. indexer : numpy.ndarray, optional The indices that the index itself was sorted by. See Also -------- Series.sort_values : Sort values of a Series. DataFrame.sort_values : Sort values in a DataFrame. Examples -------- >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices `idx` was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2])) """ if key is None and ( (ascending and self.is_monotonic_increasing) or (not ascending and self.is_monotonic_decreasing) ): if return_indexer: indexer = np.arange(len(self), dtype=np.intp) return self.copy(), indexer else: return self.copy() # GH 35584. Sort missing values according to na_position kwarg # ignore na_position for MultiIndex if not isinstance(self, ABCMultiIndex): _as = nargsort( items=self, ascending=ascending, na_position=na_position, key=key ) else: idx = cast(Index, ensure_key_mapped(self, key)) _as = idx.argsort(na_position=na_position) if not ascending: _as = _as[::-1] sorted_index = self.take(_as) if return_indexer: return sorted_index, _as else: return sorted_index
Return a sorted copy of the index. Return a sorted copy of the index, and optionally return the indices that sorted the index itself. Parameters ---------- return_indexer : bool, default False Should the indices that would sort the index be returned. ascending : bool, default True Should the index values be sorted in an ascending order. na_position : {'first' or 'last'}, default 'last' Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at the end. key : callable, optional If not None, apply the key function to the index values before sorting. This is similar to the `key` argument in the builtin :meth:`sorted` function, with the notable difference that this `key` function should be *vectorized*. It should expect an ``Index`` and return an ``Index`` of the same shape. Returns ------- sorted_index : pandas.Index Sorted copy of the index. indexer : numpy.ndarray, optional The indices that the index itself was sorted by. See Also -------- Series.sort_values : Sort values of a Series. DataFrame.sort_values : Sort values in a DataFrame. Examples -------- >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices `idx` was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))
python
pandas/core/indexes/base.py
5,811
[ "self", "return_indexer", "ascending", "na_position", "key" ]
Self | tuple[Self, np.ndarray]
true
13
8.4
pandas-dev/pandas
47,362
numpy
false
readBoolean
@CanIgnoreReturnValue // to skip a byte @Override public boolean readBoolean() throws IOException { return readUnsignedByte() != 0; }
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
216
[]
true
1
6.56
google/guava
51,352
javadoc
false
get_fwd_bwd_interactions
def get_fwd_bwd_interactions( fwd_graph: fx.Graph, bwd_graph: fx.Graph, size_of: Callable[[int | torch.SymInt], int] | None = None, ) -> tuple[int, OrderedSet[str]]: """ Analyze the interactions between the forward (fwd) and backward (bwd) graphs to determine memory usage characteristics. Args: - fwd_graph (fx.Graph): The forward graph representing the forward pass. - bwd_graph (fx.Graph): The backward graph representing the backward pass. - size_of (Callable[[int | torch.SymInt], int]): A function that converts byte counts (possibly symbolic) to concrete integers. Returns: - tuple[int, OrderedSet[str]]: A tuple containing: 1. The baseline memory usage during the backward pass, accounting for storages that persist from the forward pass (i.e., in fwd output but not in bwd input). 2. A set of node names whose storage cannot be released during the bwd pass. These include nodes that use storage from primals or are in bwd input but not in fwd output. """ size_of = size_of or _size_of_default # Build alias info for forward graph fwd_nodes = list(fwd_graph.nodes) fwd_alias_info = GraphAliasTracker(fwd_nodes) # Identify storages allocated by primal placeholder nodes primal_storages: OrderedSet[StorageKey] = OrderedSet() for node in fwd_graph.find_nodes(op="placeholder"): if node.name.startswith("primals"): primal_storages.update(fwd_alias_info.get_fresh_allocations(node)) # Get storages in forward output fwd_output_node = next(iter(reversed(fwd_graph.nodes)))[-1] assert fwd_output_node.op == "output" fwd_output_storages = fwd_alias_info.get_storage_uses(fwd_output_node) # Node names that should not be deleted during memory profile estimation of bwd_graph do_not_delete: OrderedSet[str] = OrderedSet() # Collect all storages in backward inputs and identify nodes to not delete bwd_input_storages: OrderedSet[StorageKey] = OrderedSet() for node in bwd_graph.find_nodes(op="placeholder"): node_storages = GraphAliasTracker._get_output_storages(node) bwd_input_storages.update(node_storages) # Check if this node uses primal storage if node_storages & primal_storages: do_not_delete.add(node.name) # Check if this node's storages are not in forward outputs # (meaning it's an external input to backward pass) if not (node_storages & fwd_output_storages): do_not_delete.add(node.name) # Calculate baseline memory: storages in fwd output but not in bwd input # These storages persist throughout the backward pass baseline_storages = fwd_output_storages - bwd_input_storages bwd_baseline_memory = 0 for storage_key in baseline_storages: if storage_key.device.type != "cpu": bwd_baseline_memory += size_of(storage_key.storage.nbytes()) return bwd_baseline_memory, do_not_delete
Analyze the interactions between the forward (fwd) and backward (bwd) graphs to determine memory usage characteristics. Args: - fwd_graph (fx.Graph): The forward graph representing the forward pass. - bwd_graph (fx.Graph): The backward graph representing the backward pass. - size_of (Callable[[int | torch.SymInt], int]): A function that converts byte counts (possibly symbolic) to concrete integers. Returns: - tuple[int, OrderedSet[str]]: A tuple containing: 1. The baseline memory usage during the backward pass, accounting for storages that persist from the forward pass (i.e., in fwd output but not in bwd input). 2. A set of node names whose storage cannot be released during the bwd pass. These include nodes that use storage from primals or are in bwd input but not in fwd output.
python
torch/_inductor/fx_passes/memory_estimator.py
217
[ "fwd_graph", "bwd_graph", "size_of" ]
tuple[int, OrderedSet[str]]
true
9
8
pytorch/pytorch
96,034
google
false
size
def size(self): """ Compute group sizes. Returns ------- Series Number of rows in each group. See Also -------- Series.groupby : Apply a function groupby to a Series. DataFrame.groupby : Apply a function groupby to each row or column of a DataFrame. Examples -------- >>> ser = pd.Series( ... [1, 2, 3], ... index=pd.DatetimeIndex(["2023-01-01", "2023-01-15", "2023-02-01"]), ... ) >>> ser 2023-01-01 1 2023-01-15 2 2023-02-01 3 dtype: int64 >>> ser.resample("MS").size() 2023-01-01 2 2023-02-01 1 Freq: MS, dtype: int64 """ result = self._downsample("size") # If the result is a non-empty DataFrame we stack to get a Series # GH 46826 if isinstance(result, ABCDataFrame) and not result.empty: result = result.stack() if not len(self.ax): from pandas import Series if self._selected_obj.ndim == 1: name = self._selected_obj.name else: name = None result = Series([], index=result.index, dtype="int64", name=name) return result
Compute group sizes. Returns ------- Series Number of rows in each group. See Also -------- Series.groupby : Apply a function groupby to a Series. DataFrame.groupby : Apply a function groupby to each row or column of a DataFrame. Examples -------- >>> ser = pd.Series( ... [1, 2, 3], ... index=pd.DatetimeIndex(["2023-01-01", "2023-01-15", "2023-02-01"]), ... ) >>> ser 2023-01-01 1 2023-01-15 2 2023-02-01 3 dtype: int64 >>> ser.resample("MS").size() 2023-01-01 2 2023-02-01 1 Freq: MS, dtype: int64
python
pandas/core/resample.py
1,796
[ "self" ]
false
6
7.84
pandas-dev/pandas
47,362
unknown
false
checkTokenized
private void checkTokenized() { if (tokens == null) { if (chars == null) { // still call tokenize as subclass may do some work final List<String> split = tokenize(null, 0, 0); tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY); } else { final List<String> split = tokenize(chars, 0, chars.length); tokens = split.toArray(ArrayUtils.EMPTY_STRING_ARRAY); } } }
Checks if tokenization has been done, and if not then do it.
java
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
430
[]
void
true
3
7.04
apache/commons-lang
2,896
javadoc
false
getArg
@SuppressWarnings("unchecked") public <A> @Nullable A getArg(Class<A> type) { Assert.notNull(type, "'type' must not be null"); Function<Class<?>, Object> parameter = getAvailableParameter(type); Assert.state(parameter != null, "Unknown argument type " + type.getName()); return (A) parameter.apply(this.type); }
Get an injectable argument instance for the given type. This method can be used when manually instantiating an object without reflection. @param <A> the argument type @param type the argument type @return the argument to inject or {@code null} @since 3.4.0
java
core/spring-boot/src/main/java/org/springframework/boot/util/Instantiator.java
183
[ "type" ]
A
true
1
7.04
spring-projects/spring-boot
79,428
javadoc
false
randomPrint
@Deprecated public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) { return secure().nextPrint(minLengthInclusive, maxLengthExclusive); }
Creates a random string whose length is between the inclusive minimum and the exclusive maximum. <p> Characters will be chosen from the set of \p{Print} characters. </p> @param minLengthInclusive the inclusive minimum length of the string to generate. @param maxLengthExclusive the exclusive maximum length of the string to generate. @return the random string. @since 3.5 @deprecated Use {@link #nextPrint(int, int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
java
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
623
[ "minLengthInclusive", "maxLengthExclusive" ]
String
true
1
6.32
apache/commons-lang
2,896
javadoc
false
convertToTypedCollection
@SuppressWarnings("unchecked") private Collection<?> convertToTypedCollection(Collection<?> original, @Nullable String propertyName, Class<?> requiredType, @Nullable TypeDescriptor typeDescriptor) { if (!Collection.class.isAssignableFrom(requiredType)) { return original; } boolean approximable = CollectionFactory.isApproximableCollectionType(requiredType); if (!approximable && !canCreateCopy(requiredType)) { if (logger.isDebugEnabled()) { logger.debug("Custom Collection type [" + original.getClass().getName() + "] does not allow for creating a copy - injecting original Collection as-is"); } return original; } boolean originalAllowed = requiredType.isInstance(original); TypeDescriptor elementType = (typeDescriptor != null ? typeDescriptor.getElementTypeDescriptor() : null); if (elementType == null && originalAllowed && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) { return original; } Iterator<?> it; try { it = original.iterator(); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Cannot access Collection of type [" + original.getClass().getName() + "] - injecting original Collection as-is: " + ex); } return original; } Collection<Object> convertedCopy; try { if (approximable && requiredType.isInstance(original)) { convertedCopy = CollectionFactory.createApproximateCollection(original, original.size()); } else { convertedCopy = CollectionFactory.createCollection(requiredType, original.size()); } } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Cannot create copy of Collection type [" + original.getClass().getName() + "] - injecting original Collection as-is: " + ex); } return original; } for (int i = 0; it.hasNext(); i++) { Object element = it.next(); String indexedPropertyName = buildIndexedPropertyName(propertyName, i); Object convertedElement = convertIfNecessary(indexedPropertyName, null, element, (elementType != null ? elementType.getType() : null) , elementType); try { convertedCopy.add(convertedElement); } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Collection type [" + original.getClass().getName() + "] seems to be read-only - injecting original Collection as-is: " + ex); } return original; } originalAllowed = originalAllowed && (element == convertedElement); } return (originalAllowed ? original : convertedCopy); }
Convert the given text value using the given property editor. @param oldValue the previous value, if available (may be {@code null}) @param newTextValue the proposed text value @param editor the PropertyEditor to use @return the converted value
java
spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
475
[ "original", "propertyName", "requiredType", "typeDescriptor" ]
true
21
6.32
spring-projects/spring-framework
59,386
javadoc
false
canApply
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { Assert.notNull(pc, "Pointcut must not be null"); if (!pc.getClassFilter().matches(targetClass)) { return false; } MethodMatcher methodMatcher = pc.getMethodMatcher(); if (methodMatcher == MethodMatcher.TRUE) { // No need to iterate the methods if we're matching any method anyway... return true; } IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null; if (methodMatcher instanceof IntroductionAwareMethodMatcher iamm) { introductionAwareMethodMatcher = iamm; } Set<Class<?>> classes = new LinkedHashSet<>(); if (!Proxy.isProxyClass(targetClass)) { classes.add(ClassUtils.getUserClass(targetClass)); } classes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); for (Class<?> clazz : classes) { Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); for (Method method : methods) { if (introductionAwareMethodMatcher != null ? introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) : methodMatcher.matches(method, targetClass)) { return true; } } } return false; }
Can the given pointcut apply at all on the given class? <p>This is an important test as it can be used to optimize out a pointcut for a class. @param pc the static or dynamic pointcut to check @param targetClass the class to test @param hasIntroductions whether the advisor chain for this bean includes any introductions @return whether the pointcut can apply on any method
java
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
239
[ "pc", "targetClass", "hasIntroductions" ]
true
7
7.92
spring-projects/spring-framework
59,386
javadoc
false
collectFetch
private Fetch<K, V> collectFetch() { // With the non-blocking async poll, it's critical that the application thread wait until the background // thread has completed the stage of validating positions. This prevents a race condition where both // threads may attempt to update the SubscriptionState.position() for a given partition. So if the background // thread has not completed that stage for the inflight event, don't attempt to collect data from the fetch // buffer. If the inflight event was nulled out by checkInflightPoll(), that implies that it is safe to // attempt to collect data from the fetch buffer. if (positionsValidator.canSkipUpdateFetchPositions()) { return fetchCollector.collectFetch(fetchBuffer); } if (inflightPoll != null && !inflightPoll.isValidatePositionsComplete()) { return Fetch.empty(); } return fetchCollector.collectFetch(fetchBuffer); }
Perform the "{@link FetchCollector#collectFetch(FetchBuffer) fetch collection}" step by reading raw data out of the {@link #fetchBuffer}, converting it to a well-formed {@link CompletedFetch}, validating that it and the internal {@link SubscriptionState state} are correct, and then converting it all into a {@link Fetch} for returning.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
1,933
[]
true
4
6.24
apache/kafka
31,560
javadoc
false
getUmdSymbol
function getUmdSymbol(token: Node, checker: TypeChecker): Symbol | undefined { // try the identifier to see if it is the umd symbol const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; if (isUMDExportSymbol(umdSymbol)) return umdSymbol; // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. const { parent } = token; if ((isJsxOpeningLikeElement(parent) && parent.tagName === token) || isJsxOpeningFragment(parent)) { const parentSymbol = checker.resolveName(checker.getJsxNamespace(parent), isJsxOpeningLikeElement(parent) ? token : parent, SymbolFlags.Value, /*excludeGlobals*/ false); if (isUMDExportSymbol(parentSymbol)) { return parentSymbol; } } return undefined; }
@returns `Comparison.LessThan` if `a` is better than `b`.
typescript
src/services/codefixes/importFixes.ts
1,492
[ "token", "checker" ]
true
8
6.56
microsoft/TypeScript
107,154
jsdoc
false
putBuckets
private static int putBuckets( FixedCapacityExponentialHistogram output, BucketIterator buckets, boolean isPositive, DownscaleStats downscaleStats ) { boolean collectDownScaleStatsOnNext = false; long prevIndex = 0; int overflowCount = 0; while (buckets.hasNext()) { long idx = buckets.peekIndex(); if (collectDownScaleStatsOnNext) { downscaleStats.add(prevIndex, idx); } else { collectDownScaleStatsOnNext = downscaleStats != null; } if (output.tryAddBucket(idx, buckets.peekCount(), isPositive) == false) { overflowCount++; } prevIndex = idx; buckets.advance(); } return overflowCount; }
Merges the given histogram into the current result. The histogram might be upscaled if needed. @param toAdd the histogram to merge
java
libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramMerger.java
271
[ "output", "buckets", "isPositive", "downscaleStats" ]
true
4
6.72
elastic/elasticsearch
75,680
javadoc
false