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
isFallthroughSwitchBranch
static bool isFallthroughSwitchBranch(const SwitchBranch &Branch) { struct SwitchCaseVisitor : RecursiveASTVisitor<SwitchCaseVisitor> { using RecursiveASTVisitor<SwitchCaseVisitor>::DataRecursionQueue; bool TraverseLambdaExpr(LambdaExpr *, DataRecursionQueue * = nullptr) { return true; // Ignore lambdas } bool TraverseDecl(Decl *) { return true; // No need to check declarations } bool TraverseSwitchStmt(SwitchStmt *, DataRecursionQueue * = nullptr) { return true; // Ignore sub-switches } // NOLINTNEXTLINE(readability-identifier-naming) - FIXME bool TraverseSwitchCase(SwitchCase *, DataRecursionQueue * = nullptr) { return true; // Ignore cases } bool TraverseDefaultStmt(DefaultStmt *, DataRecursionQueue * = nullptr) { return true; // Ignore defaults } bool TraverseAttributedStmt(AttributedStmt *S) { if (!S) return true; return llvm::all_of(S->getAttrs(), [](const Attr *A) { return !isa<FallThroughAttr>(A); }); } } Visitor; for (const Stmt *Elem : Branch) if (!Visitor.TraverseStmt(const_cast<Stmt *>(Elem))) return true; return false; }
and ignores the `case X:` or `default:` at the start of the branch.
cpp
clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
42
[]
true
3
6.88
llvm/llvm-project
36,021
doxygen
false
run_program
def run_program(self, program_path): """ Run a generated Python program and handle output/errors. Args: program_path: Path to the Python program to run Returns: bool: True if program ran successfully, False otherwise """ abs_path = os.path.abspath(program_path) print(f"Running: {abs_path}") # Select a random CUDA device if available cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") if cuda_visible_devices: devices = [d.strip() for d in cuda_visible_devices.split(",") if d.strip()] else: # Default to all GPUs if not set try: import torch num_gpus = torch.cuda.device_count() devices = [str(i) for i in range(num_gpus)] except ImportError: devices = [] if devices: selected_device = random.choice(devices) env = os.environ.copy() env["CUDA_VISIBLE_DEVICES"] = selected_device print(f"Selected CUDA_VISIBLE_DEVICES={selected_device}") else: env = None # No GPU available or torch not installed try: result = subprocess.run( [sys.executable, abs_path], capture_output=True, text=True, check=True, env=env, ) print("=== Program Output ===") print(result.stdout) print(result.stderr) return True except subprocess.CalledProcessError as e: print("=== Program Output (Failure) ===") print(e.stdout) print(e.stderr) print("===============================") print("=== Program Source ===") with open(abs_path) as f: print(f.read()) print("======================") print(f"Program exited with code: {e.returncode}") sys.exit(1)
Run a generated Python program and handle output/errors. Args: program_path: Path to the Python program to run Returns: bool: True if program ran successfully, False otherwise
python
tools/experimental/torchfuzz/runner.py
18
[ "self", "program_path" ]
false
5
7.04
pytorch/pytorch
96,034
google
false
map
R map(R instance, @Nullable T value);
Map a existing instance for the given nullable value. @param instance the existing instance @param value the value to map (may be {@code null}) @return the resulting mapped instance
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java
552
[ "instance", "value" ]
R
true
1
6.8
spring-projects/spring-boot
79,428
javadoc
false
validate_udf
def validate_udf(func: Callable) -> None: """ Validate user defined function for ops when using Numba with groupby ops. The first signature arguments should include: def f(values, index, ...): ... Parameters ---------- func : function, default False user defined function Returns ------- None Raises ------ NumbaUtilError """ if not callable(func): raise NotImplementedError( "Numba engine can only be used with a single function." ) udf_signature = list(inspect.signature(func).parameters.keys()) expected_args = ["values", "index"] min_number_args = len(expected_args) if ( len(udf_signature) < min_number_args or udf_signature[:min_number_args] != expected_args ): raise NumbaUtilError( f"The first {min_number_args} arguments to {func.__name__} must be " f"{expected_args}" )
Validate user defined function for ops when using Numba with groupby ops. The first signature arguments should include: def f(values, index, ...): ... Parameters ---------- func : function, default False user defined function Returns ------- None Raises ------ NumbaUtilError
python
pandas/core/groupby/numba_.py
27
[ "func" ]
None
true
4
6.24
pandas-dev/pandas
47,362
numpy
false
get_param_nodes
def get_param_nodes(graph: fx.Graph) -> list[fx.Node]: """Get all parameter nodes from a graph as a list. You can rely on this providing the correct order of parameters you need to feed into the joint graph (at the very beginning of the argument list, before buffers). Args: graph: The FX joint graph with descriptors Returns: A list of FX nodes representing all parameters in the graph. Raises: RuntimeError: If subclass tensors are encountered (not yet supported), as it is not clear if you wanted each individual constituent piece of the subclasses, or have them grouped up in some way. """ return list(get_named_param_nodes(graph).values())
Get all parameter nodes from a graph as a list. You can rely on this providing the correct order of parameters you need to feed into the joint graph (at the very beginning of the argument list, before buffers). Args: graph: The FX joint graph with descriptors Returns: A list of FX nodes representing all parameters in the graph. Raises: RuntimeError: If subclass tensors are encountered (not yet supported), as it is not clear if you wanted each individual constituent piece of the subclasses, or have them grouped up in some way.
python
torch/_functorch/_aot_autograd/fx_utils.py
279
[ "graph" ]
list[fx.Node]
true
1
6.72
pytorch/pytorch
96,034
google
false
nextDouble
@Deprecated public static double nextDouble(final double startInclusive, final double endExclusive) { return secure().randomDouble(startInclusive, endExclusive); }
Generates a random double within the specified range. @param startInclusive the smallest value that can be returned, must be non-negative. @param endExclusive the upper bound (not included). @throws IllegalArgumentException if {@code startInclusive > endExclusive} or if {@code startInclusive} is negative. @return the random double. @deprecated Use {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
java
src/main/java/org/apache/commons/lang3/RandomUtils.java
153
[ "startInclusive", "endExclusive" ]
true
1
6.16
apache/commons-lang
2,896
javadoc
false
maybeBindThisJoinPoint
private boolean maybeBindThisJoinPoint() { if ((this.argumentTypes[0] == JoinPoint.class) || (this.argumentTypes[0] == ProceedingJoinPoint.class)) { bindParameterName(0, THIS_JOIN_POINT); return true; } else { return false; } }
If the first parameter is of type JoinPoint or ProceedingJoinPoint, bind "thisJoinPoint" as parameter name and return true, else return false.
java
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java
309
[]
true
3
6.56
spring-projects/spring-framework
59,386
javadoc
false
emptyResults
public <T> Map<TopicPartition, T> emptyResults() { Map<TopicPartition, T> result = new HashMap<>(); timestampsToSearch.keySet().forEach(tp -> result.put(tp, null)); return result; }
Build result representing that no offsets were found as part of the current event. @return Map containing all the partitions the event was trying to get offsets for, and null {@link OffsetAndTimestamp} as value
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ListOffsetsEvent.java
53
[]
true
1
6.56
apache/kafka
31,560
javadoc
false
getBeanInfo
private static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException { for (BeanInfoFactory beanInfoFactory : beanInfoFactories) { BeanInfo beanInfo = beanInfoFactory.getBeanInfo(beanClass); if (beanInfo != null) { return beanInfo; } } return simpleBeanInfoFactory.getBeanInfo(beanClass); }
Retrieve a {@link BeanInfo} descriptor for the given target class. @param beanClass the target class to introspect @return the resulting {@code BeanInfo} descriptor (never {@code null}) @throws IntrospectionException from introspecting the given bean class
java
spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
218
[ "beanClass" ]
BeanInfo
true
2
7.28
spring-projects/spring-framework
59,386
javadoc
false
write
<V> void write(@Nullable V value) { value = processValue(value); if (value == null) { append("null"); } else if (value instanceof WritableJson writableJson) { try { writableJson.to(this.out); } catch (IOException ex) { throw new UncheckedIOException(ex); } } else if (value instanceof Iterable<?> iterable && canWriteAsArray(iterable)) { writeArray(iterable::forEach); } else if (ObjectUtils.isArray(value)) { writeArray(Arrays.asList(ObjectUtils.toObjectArray(value))::forEach); } else if (value instanceof Map<?, ?> map) { writeObject(map::forEach); } else if (value instanceof Number || value instanceof Boolean) { append(value.toString()); } else { writeString(value); } }
Write a value to the JSON output. The following value types are supported: <ul> <li>Any {@code null} value</li> <li>A {@link WritableJson} instance</li> <li>Any {@link Iterable} or Array (written as a JSON array)</li> <li>A {@link Map} (written as a JSON object)</li> <li>Any {@link Number}</li> <li>A {@link Boolean}</li> </ul> All other values are written as JSON strings. @param <V> the value type @param value the value to write
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonValueWriter.java
122
[ "value" ]
void
true
10
6.72
spring-projects/spring-boot
79,428
javadoc
false
apply
protected void apply(@Nullable LogFile logFile, PropertyResolver resolver) { setSystemProperty(LoggingSystemProperty.APPLICATION_NAME, resolver); setSystemProperty(LoggingSystemProperty.APPLICATION_GROUP, resolver); setSystemProperty(LoggingSystemProperty.PID, new ApplicationPid().toString()); setSystemProperty(LoggingSystemProperty.CONSOLE_CHARSET, resolver, getDefaultConsoleCharset().name()); setSystemProperty(LoggingSystemProperty.FILE_CHARSET, resolver, getDefaultFileCharset().name()); setSystemProperty(LoggingSystemProperty.CONSOLE_THRESHOLD, resolver, this::thresholdMapper); setSystemProperty(LoggingSystemProperty.FILE_THRESHOLD, resolver, this::thresholdMapper); setSystemProperty(LoggingSystemProperty.EXCEPTION_CONVERSION_WORD, resolver); setSystemProperty(LoggingSystemProperty.CONSOLE_PATTERN, resolver); setSystemProperty(LoggingSystemProperty.FILE_PATTERN, resolver); setSystemProperty(LoggingSystemProperty.CONSOLE_STRUCTURED_FORMAT, resolver); setSystemProperty(LoggingSystemProperty.FILE_STRUCTURED_FORMAT, resolver); setSystemProperty(LoggingSystemProperty.LEVEL_PATTERN, resolver); setSystemProperty(LoggingSystemProperty.DATEFORMAT_PATTERN, resolver); setSystemProperty(LoggingSystemProperty.CORRELATION_PATTERN, resolver); if (logFile != null) { logFile.applyToSystemProperties(); } if (!this.environment.getProperty("logging.console.enabled", Boolean.class, true)) { setSystemProperty(LoggingSystemProperty.CONSOLE_THRESHOLD.getEnvironmentVariableName(), "OFF"); } }
Returns the {@link Console} to use. @return the {@link Console} to use @since 3.5.0
java
core/spring-boot/src/main/java/org/springframework/boot/logging/LoggingSystemProperties.java
127
[ "logFile", "resolver" ]
void
true
3
6.88
spring-projects/spring-boot
79,428
javadoc
false
lastIndexOf
public static int lastIndexOf(final long[] array, final long valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); }
Finds the last index of the given value within the array. <p> This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array. </p> @param array the array to traverse backwards looking for the object, may be {@code null}. @param valueToFind the object to find. @return the last index of the value within the array, {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
4,081
[ "array", "valueToFind" ]
true
1
6.8
apache/commons-lang
2,896
javadoc
false
assign_fields_by_name
def assign_fields_by_name(dst, src, zero_unassigned=True): """ Assigns values from one structured array to another by field name. Normally in numpy >= 1.14, assignment of one structured array to another copies fields "by position", meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name. This function instead copies "by field name", such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13. Parameters ---------- dst : ndarray src : ndarray The source and destination arrays during assignment. zero_unassigned : bool, optional If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified. """ if dst.dtype.names is None: dst[...] = src return for name in dst.dtype.names: if name not in src.dtype.names: if zero_unassigned: dst[name] = 0 else: assign_fields_by_name(dst[name], src[name], zero_unassigned)
Assigns values from one structured array to another by field name. Normally in numpy >= 1.14, assignment of one structured array to another copies fields "by position", meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name. This function instead copies "by field name", such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13. Parameters ---------- dst : ndarray src : ndarray The source and destination arrays during assignment. zero_unassigned : bool, optional If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified.
python
numpy/lib/recfunctions.py
1,233
[ "dst", "src", "zero_unassigned" ]
false
6
6.08
numpy/numpy
31,054
numpy
false
run
@Override public void run() { try { log.debug("Consumer network thread started"); // Wait until we're securely in the background network thread to initialize these objects... try { initializeResources(); } catch (Throwable t) { KafkaException e = ConsumerUtils.maybeWrapAsKafkaException(t); maybeSetInitializationError(e); // This will still call cleanup() via the `finally` section below. return; } finally { initializationLatch.countDown(); } while (running) { try { runOnce(); } catch (final Throwable e) { // Swallow the exception and continue log.error("Unexpected error caught in consumer network thread", e); } } } catch (Throwable t) { log.error("Unexpected failure in consumer network thread", t); } finally { cleanup(); } }
Start the network thread and let it complete its initialization before proceeding. The {@link ClassicKafkaConsumer} constructor blocks during creation of its {@link NetworkClient}, providing precedent for waiting here. In certain cases (e.g. an invalid {@link LoginModule} in {@link SaslConfigs#SASL_JAAS_CONFIG}), an error could be thrown during {@link #initializeResources()}. This would result in the {@link #run()} method exiting, no longer able to process events, which means that the consumer effectively hangs. @param timeoutMs Length of time, in milliseconds, to wait for the thread to start and complete initialization
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java
142
[]
void
true
5
6.56
apache/kafka
31,560
javadoc
false
_define_gemm_instance
def _define_gemm_instance( self, op: GemmOperation, evt_name: Optional[str] = None, ) -> tuple[str, str]: """Defines and renders the Cutlass / CUDA C++ code for a given GEMM operation instance. This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply forms a core part of a number of scientific applications, so this efficient and adaptable implementation is crucial. Args: op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering. Returns: tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++ code (render) and the second part is the string that specifies the operation type. """ assert cutlass_utils.try_import_cutlass() import cutlass_library.library as cutlass_lib from .cutlass_lib_extensions import gemm_operation_extensions as gemm_extensions emitter = gemm_extensions.EmitGemmUniversal3xInstanceWithEVT(evt_name=evt_name) # type: ignore[call-arg] if not hasattr(op, "epilogue_functor") or not isinstance( op.epilogue_functor, enum.Enum ): op = copy.deepcopy(op) op.epilogue_functor = cutlass_lib.EpilogueFunctor.LinearCombination op_def = emitter.emit(op) pattern = re.compile(r"\s*struct\s(.*?)\s:") decl = [line for line in op_def.split("\n") if "struct " in line][-1] match = pattern.match(decl) if match is None: raise RuntimeError("Invalid Gemm config: \n" + op_def) op_type = match.groups()[0] if op.gemm_kind == cutlass_lib.GemmKind.Universal3x: op_def += f"\n using {op_type}_device_type = cutlass::gemm::device::GemmUniversalAdapter<{op_type}>;\n" op_type = f"{op_type}_device_type" return op_def, op_type
Defines and renders the Cutlass / CUDA C++ code for a given GEMM operation instance. This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply forms a core part of a number of scientific applications, so this efficient and adaptable implementation is crucial. Args: op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering. Returns: tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++ code (render) and the second part is the string that specifies the operation type.
python
torch/_inductor/codegen/cuda/gemm_template.py
1,539
[ "self", "op", "evt_name" ]
tuple[str, str]
true
5
7.92
pytorch/pytorch
96,034
google
false
toString
@Override public String toString() { StringBuilder sb = new StringBuilder("class=").append(getBeanClassName()); sb.append("; scope=").append(this.scope); sb.append("; abstract=").append(this.abstractFlag); sb.append("; lazyInit=").append(this.lazyInit); sb.append("; autowireMode=").append(this.autowireMode); sb.append("; dependencyCheck=").append(this.dependencyCheck); sb.append("; autowireCandidate=").append(this.autowireCandidate); sb.append("; primary=").append(this.primary); sb.append("; fallback=").append(this.fallback); sb.append("; factoryBeanName=").append(this.factoryBeanName); sb.append("; factoryMethodName=").append(this.factoryMethodName); sb.append("; initMethodNames=").append(Arrays.toString(this.initMethodNames)); sb.append("; destroyMethodNames=").append(Arrays.toString(this.destroyMethodNames)); if (this.resource != null) { sb.append("; defined in ").append(this.resource.getDescription()); } return sb.toString(); }
Clone this bean definition. To be implemented by concrete subclasses. @return the cloned bean definition object
java
spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanDefinition.java
1,355
[]
String
true
2
7.76
spring-projects/spring-framework
59,386
javadoc
false
apply
R apply(int 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/FailableIntFunction.java
55
[ "input" ]
R
true
1
6.8
apache/commons-lang
2,896
javadoc
false
connect
def connect(self, *args, **kwargs): """Connect receiver to sender for signal. Arguments: receiver (Callable): A function or an instance method which is to receive signals. Receivers must be hashable objects. if weak is :const:`True`, then receiver must be weak-referenceable. Receivers must be able to accept keyword arguments. If receivers have a `dispatch_uid` attribute, the receiver will not be added if another receiver already exists with that `dispatch_uid`. sender (Any): The sender to which the receiver should respond. Must either be a Python object, or :const:`None` to receive events from any sender. weak (bool): Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid (Hashable): An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. retry (bool): If the signal receiver raises an exception (e.g. ConnectionError), the receiver will be retried until it runs successfully. A strong ref to the receiver will be stored and the `weak` option will be ignored. """ def _handle_options(sender=None, weak=True, dispatch_uid=None, retry=False): def _connect_signal(fun): options = {'dispatch_uid': dispatch_uid, 'weak': weak} def _retry_receiver(retry_fun): def _try_receiver_over_time(*args, **kwargs): def on_error(exc, intervals, retries): interval = next(intervals) err_msg = RECEIVER_RETRY_ERROR % \ {'receiver': retry_fun, 'when': humanize_seconds(interval, 'in', ' ')} logger.error(err_msg) return interval return retry_over_time(retry_fun, Exception, args, kwargs, on_error) return _try_receiver_over_time if retry: options['weak'] = False if not dispatch_uid: # if there's no dispatch_uid then we need to set the # dispatch uid to the original func id so we can look # it up later with the original func id options['dispatch_uid'] = _make_id(fun) fun = _retry_receiver(fun) fun._dispatch_uid = options['dispatch_uid'] self._connect_signal(fun, sender, options['weak'], options['dispatch_uid']) return fun return _connect_signal if args and callable(args[0]): return _handle_options(*args[1:], **kwargs)(args[0]) return _handle_options(*args, **kwargs)
Connect receiver to sender for signal. Arguments: receiver (Callable): A function or an instance method which is to receive signals. Receivers must be hashable objects. if weak is :const:`True`, then receiver must be weak-referenceable. Receivers must be able to accept keyword arguments. If receivers have a `dispatch_uid` attribute, the receiver will not be added if another receiver already exists with that `dispatch_uid`. sender (Any): The sender to which the receiver should respond. Must either be a Python object, or :const:`None` to receive events from any sender. weak (bool): Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid (Hashable): An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. retry (bool): If the signal receiver raises an exception (e.g. ConnectionError), the receiver will be retried until it runs successfully. A strong ref to the receiver will be stored and the `weak` option will be ignored.
python
celery/utils/dispatch/signal.py
110
[ "self" ]
false
5
6
celery/celery
27,741
google
false
start_instances
def start_instances(self, instance_ids: list) -> dict: """ Start instances with given ids. :param instance_ids: List of instance ids to start :return: Dict with key `StartingInstances` and value as list of instances being started """ self.log.info("Starting instances: %s", instance_ids) return self.conn.start_instances(InstanceIds=instance_ids)
Start instances with given ids. :param instance_ids: List of instance ids to start :return: Dict with key `StartingInstances` and value as list of instances being started
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/ec2.py
110
[ "self", "instance_ids" ]
dict
true
1
6.72
apache/airflow
43,597
sphinx
false
getCompatIPv4Address
public static Inet4Address getCompatIPv4Address(Inet6Address ip) { checkArgument( isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); }
Returns the IPv4 address embedded in an IPv4 compatible address. @param ip {@link Inet6Address} to be examined for an embedded IPv4 address @return {@link Inet4Address} of the embedded IPv4 address @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
java
android/guava/src/com/google/common/net/InetAddresses.java
702
[ "ip" ]
Inet4Address
true
1
6.4
google/guava
51,352
javadoc
false
forBeanTypes
static LazyInitializationExcludeFilter forBeanTypes(Class<?>... types) { return (beanName, beanDefinition, beanType) -> { for (Class<?> type : types) { if (type.isAssignableFrom(beanType)) { return true; } } return false; }; }
Factory method that creates a filter for the given bean types. @param types the filtered types @return a new filter instance
java
core/spring-boot/src/main/java/org/springframework/boot/LazyInitializationExcludeFilter.java
64
[]
LazyInitializationExcludeFilter
true
2
8.24
spring-projects/spring-boot
79,428
javadoc
false
_tile_description_to_json
def _tile_description_to_json(cls, tile_desc: "TileDescription") -> str: # type: ignore[name-defined] # noqa: F821 """ Convert TileDescription to JSON string. Args: tile_desc: TileDescription object Returns: str: JSON string representation """ # Create the main dictionary with field names matching TileDescription constructor parameters result = { "threadblock_shape": tile_desc.threadblock_shape, "stages": tile_desc.stages, "warp_count": tile_desc.warp_count, "math_instruction": cls._math_instruction_to_json( tile_desc.math_instruction ), "min_compute": tile_desc.minimum_compute_capability, # Store as min_compute for constructor "max_compute": tile_desc.maximum_compute_capability, # Store as max_compute for constructor "cluster_shape": tile_desc.cluster_shape, "explicit_vector_sizes": tile_desc.explicit_vector_sizes, } # Add tile_shape if it exists and differs from threadblock_shape if ( hasattr(tile_desc, "tile_shape") and tile_desc.tile_shape != tile_desc.threadblock_shape ): result["tile_shape"] = tile_desc.tile_shape return json.dumps(result)
Convert TileDescription to JSON string. Args: tile_desc: TileDescription object Returns: str: JSON string representation
python
torch/_inductor/codegen/cuda/serialization.py
222
[ "cls", "tile_desc" ]
str
true
3
7.6
pytorch/pytorch
96,034
google
false
appendExportsOfDeclaration
function appendExportsOfDeclaration(statements: Statement[] | undefined, seen: IdentifierNameMap<boolean>, decl: Declaration, liveBinding?: boolean): Statement[] | undefined { const name = factory.getDeclarationName(decl); const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name); if (exportSpecifiers) { for (const exportSpecifier of exportSpecifiers) { statements = appendExportStatement(statements, seen, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /*allowComments*/ undefined, liveBinding); } } return statements; }
Appends the exports of a declaration to a statement list, returning the statement list. @param statements A statement list to which the down-level export statements are to be appended. If `statements` is `undefined`, a new array is allocated if statements are appended. @param decl The declaration to export.
typescript
src/compiler/transformers/module/module.ts
2,108
[ "statements", "seen", "decl", "liveBinding?" ]
true
2
6.72
microsoft/TypeScript
107,154
jsdoc
false
_fit_transform
def _fit_transform(self, X, y=None, W=None, H=None, update_H=True): """Learn a NMF model for the data X and returns the transformed data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Data matrix to be decomposed y : Ignored W : array-like of shape (n_samples, n_components), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is initialised as an array of zeros, unless `solver='mu'`, then it is filled with values calculated by `np.sqrt(X.mean() / self._n_components)`. If `None`, uses the initialisation method specified in `init`. H : array-like of shape (n_components, n_features), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is used as a constant, to solve for W only. If `None`, uses the initialisation method specified in `init`. update_H : bool, default=True If True, both W and H will be estimated from initial guesses, this corresponds to a call to the 'fit_transform' method. If False, only W will be estimated, this corresponds to a call to the 'transform' method. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. H : ndarray of shape (n_components, n_features) Factorization matrix, sometimes called 'dictionary'. n_iter_ : int Actual number of iterations. """ # check parameters self._check_params(X) if X.min() == 0 and self._beta_loss <= 0: raise ValueError( "When beta_loss <= 0 and X contains zeros, " "the solver may diverge. Please add small values " "to X, or use a positive beta_loss." ) # initialize or check W and H W, H = self._check_w_h(X, W, H, update_H) # scale the regularization terms l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H = self._compute_regularization(X) if self.solver == "cd": W, H, n_iter = _fit_coordinate_descent( X, W, H, self.tol, self.max_iter, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H=update_H, verbose=self.verbose, shuffle=self.shuffle, random_state=self.random_state, ) elif self.solver == "mu": W, H, n_iter, *_ = _fit_multiplicative_update( X, W, H, self._beta_loss, self.max_iter, self.tol, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H, self.verbose, ) else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn( "Maximum number of iterations %d reached. Increase " "it to improve convergence." % self.max_iter, ConvergenceWarning, ) return W, H, n_iter
Learn a NMF model for the data X and returns the transformed data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Data matrix to be decomposed y : Ignored W : array-like of shape (n_samples, n_components), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is initialised as an array of zeros, unless `solver='mu'`, then it is filled with values calculated by `np.sqrt(X.mean() / self._n_components)`. If `None`, uses the initialisation method specified in `init`. H : array-like of shape (n_components, n_features), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is used as a constant, to solve for W only. If `None`, uses the initialisation method specified in `init`. update_H : bool, default=True If True, both W and H will be estimated from initial guesses, this corresponds to a call to the 'fit_transform' method. If False, only W will be estimated, this corresponds to a call to the 'transform' method. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. H : ndarray of shape (n_components, n_features) Factorization matrix, sometimes called 'dictionary'. n_iter_ : int Actual number of iterations.
python
sklearn/decomposition/_nmf.py
1,630
[ "self", "X", "y", "W", "H", "update_H" ]
false
8
6
scikit-learn/scikit-learn
64,340
numpy
false
nextLong
@Deprecated public static long nextLong() { return secure().randomLong(); }
Generates a random long between 0 (inclusive) and Long.MAX_VALUE (exclusive). @return the random long. @see #nextLong(long, long) @since 3.5 @deprecated Use {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}.
java
src/main/java/org/apache/commons/lang3/RandomUtils.java
220
[]
true
1
6.32
apache/commons-lang
2,896
javadoc
false
_concat_same_type
def _concat_same_type(cls, to_concat: Sequence[Self]) -> Self: """ Concatenate multiple array of this dtype. Parameters ---------- to_concat : sequence of this type An array of the same dtype to concatenate. Returns ------- ExtensionArray See Also -------- api.extensions.ExtensionArray._explode : Transform each element of list-like to a row. api.extensions.ExtensionArray._formatter : Formatting function for scalar values. api.extensions.ExtensionArray._from_factorized : Reconstruct an ExtensionArray after factorization. Examples -------- >>> arr1 = pd.array([1, 2, 3]) >>> arr2 = pd.array([4, 5, 6]) >>> pd.arrays.IntegerArray._concat_same_type([arr1, arr2]) <IntegerArray> [1, 2, 3, 4, 5, 6] Length: 6, dtype: Int64 """ # Implementer note: this method will only be called with a sequence of # ExtensionArrays of this class and with the same dtype as self. This # should allow "easy" concatenation (no upcasting needed), and result # in a new ExtensionArray of the same dtype. # Note: this strict behaviour is only guaranteed starting with pandas 1.1 raise AbstractMethodError(cls)
Concatenate multiple array of this dtype. Parameters ---------- to_concat : sequence of this type An array of the same dtype to concatenate. Returns ------- ExtensionArray See Also -------- api.extensions.ExtensionArray._explode : Transform each element of list-like to a row. api.extensions.ExtensionArray._formatter : Formatting function for scalar values. api.extensions.ExtensionArray._from_factorized : Reconstruct an ExtensionArray after factorization. Examples -------- >>> arr1 = pd.array([1, 2, 3]) >>> arr2 = pd.array([4, 5, 6]) >>> pd.arrays.IntegerArray._concat_same_type([arr1, arr2]) <IntegerArray> [1, 2, 3, 4, 5, 6] Length: 6, dtype: Int64
python
pandas/core/arrays/base.py
2,141
[ "cls", "to_concat" ]
Self
true
1
6.8
pandas-dev/pandas
47,362
numpy
false
findThreadGroups
public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup threadGroup, final boolean recurse, final Predicate<ThreadGroup> predicate) { Objects.requireNonNull(threadGroup, "threadGroup"); Objects.requireNonNull(predicate, "predicate"); int count = threadGroup.activeGroupCount(); ThreadGroup[] threadGroups; do { threadGroups = new ThreadGroup[count + count / 2 + 1]; //slightly grow the array size count = threadGroup.enumerate(threadGroups, recurse); //return value of enumerate() must be strictly less than the array size according to Javadoc } while (count >= threadGroups.length); return Collections.unmodifiableCollection(Stream.of(threadGroups).limit(count).filter(predicate).collect(Collectors.toList())); }
Finds all active thread groups which match the given predicate and which is a subgroup of the given thread group (or one of its subgroups). @param threadGroup the thread group. @param recurse if {@code true} then evaluate the predicate recursively on all thread groups in all subgroups of the given group. @param predicate the predicate. @return An unmodifiable {@link Collection} of active thread groups which match the given predicate and which is a subgroup of the given thread group. @throws NullPointerException if the given group or predicate is null. @throws SecurityException if the current thread cannot modify thread groups from this thread's thread group up to the system thread group. @since 3.13.0
java
src/main/java/org/apache/commons/lang3/ThreadUtils.java
258
[ "threadGroup", "recurse", "predicate" ]
true
1
7.04
apache/commons-lang
2,896
javadoc
false
getAllowedPaths
private List<Path> getAllowedPaths(String configValue) { if (configValue != null && !configValue.isEmpty()) { List<Path> allowedPaths = new ArrayList<>(); Arrays.stream(configValue.split(",")).forEach(b -> { Path normalisedPath = Paths.get(b).normalize(); if (!normalisedPath.isAbsolute()) { throw new ConfigException("Path " + normalisedPath + " is not absolute"); } else if (!Files.exists(normalisedPath)) { throw new ConfigException("Path " + normalisedPath + " does not exist"); } else { allowedPaths.add(normalisedPath); } }); return allowedPaths; } return null; }
Constructs AllowedPaths with a list of Paths retrieved from {@code configValue}. @param configValue {@code allowed.paths} config value which is a string containing comma separated list of paths @throws ConfigException if any of the given paths is not absolute or does not exist.
java
clients/src/main/java/org/apache/kafka/common/config/internals/AllowedPaths.java
40
[ "configValue" ]
true
5
6.72
apache/kafka
31,560
javadoc
false
readNextToken
private int readNextToken(final char[] srcChars, int start, final int len, final StrBuilder workArea, final List<String> tokenList) { // skip all leading whitespace, unless it is the // field delimiter or the quote character while (start < len) { final int removeLen = Math.max( getIgnoredMatcher().isMatch(srcChars, start, start, len), getTrimmerMatcher().isMatch(srcChars, start, start, len)); if (removeLen == 0 || getDelimiterMatcher().isMatch(srcChars, start, start, len) > 0 || getQuoteMatcher().isMatch(srcChars, start, start, len) > 0) { break; } start += removeLen; } // handle reaching end if (start >= len) { addToken(tokenList, StringUtils.EMPTY); return -1; } // handle empty token final int delimLen = getDelimiterMatcher().isMatch(srcChars, start, start, len); if (delimLen > 0) { addToken(tokenList, StringUtils.EMPTY); return start + delimLen; } // handle found token final int quoteLen = getQuoteMatcher().isMatch(srcChars, start, start, len); if (quoteLen > 0) { return readWithQuotes(srcChars, start + quoteLen, len, workArea, tokenList, start, quoteLen); } return readWithQuotes(srcChars, start, len, workArea, tokenList, 0, 0); }
Reads character by character through the String to get the next token. @param srcChars the character array being tokenized. @param start the first character of field. @param len the length of the character array being tokenized. @param workArea a temporary work area. @param tokenList the list of parsed tokens. @return the starting position of the next field (the character immediately after the delimiter), or -1 if end of string found.
java
src/main/java/org/apache/commons/lang3/text/StrTokenizer.java
708
[ "srcChars", "start", "len", "workArea", "tokenList" ]
true
8
8.24
apache/commons-lang
2,896
javadoc
false
calculateFirstNotNull
function calculateFirstNotNull(field: Field, ignoreNulls: boolean, nullAsZero: boolean): FieldCalcs { const data = field.values; for (let idx = 0; idx < data.length; idx++) { const v = data[idx]; if (v != null && !Number.isNaN(v)) { return { firstNotNull: v }; } } return { firstNotNull: null }; }
@returns an object with a key for each selected stat NOTE: This will also modify the 'field.state' object, leaving values in a cache until cleared.
typescript
packages/grafana-data/src/transformations/fieldReducer.ts
611
[ "field", "ignoreNulls", "nullAsZero" ]
true
4
8.24
grafana/grafana
71,362
jsdoc
false
whenNotNull
public Member<T> whenNotNull(Function<@Nullable T, ?> extractor) { Assert.notNull(extractor, "'extractor' must not be null"); return when((instance) -> Objects.nonNull(extractor.apply(instance))); }
Only include this member when an extracted value is not {@code null}. @param extractor an function used to extract the value to test @return a {@link Member} which may be configured further
java
core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java
400
[ "extractor" ]
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
isReady
@Override public boolean isReady(Node node, long now) { // if we need to update our metadata now declare all requests unready to make metadata requests first // priority return !metadataUpdater.isUpdateDue(now) && canSendRequest(node.idString(), now); }
Check if the node with the given id is ready to send more requests. @param node The node @param now The current time in ms @return true if the node is ready
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
517
[ "node", "now" ]
true
2
8.08
apache/kafka
31,560
javadoc
false
sliceUnaligned
public UnalignedFileRecords sliceUnaligned(int position, int size) { int availableBytes = availableBytes(position, size); return new UnalignedFileRecords(channel, this.start + position, availableBytes); }
Return a slice of records from this instance, the difference with {@link FileRecords#slice(int, int)} is that the position is not necessarily on an offset boundary. This method is reserved for cases where offset alignment is not necessary, such as in the replication of raft snapshots. @param position The start position to begin the read from @param size The number of bytes after the start position to include @return A unaligned slice of records on this message set limited based on the given position and size
java
clients/src/main/java/org/apache/kafka/common/record/FileRecords.java
161
[ "position", "size" ]
UnalignedFileRecords
true
1
6.48
apache/kafka
31,560
javadoc
false
streamingIterator
@Override public CloseableIterator<Record> streamingIterator(BufferSupplier bufferSupplier) { if (isCompressed()) return compressedIterator(bufferSupplier, false); else return uncompressedIterator(); }
Gets the base timestamp of the batch which is used to calculate the record timestamps from the deltas. @return The base timestamp
java
clients/src/main/java/org/apache/kafka/common/record/DefaultRecordBatch.java
357
[ "bufferSupplier" ]
true
2
6.88
apache/kafka
31,560
javadoc
false
wrapAndThrowExecutionExceptionOrError
private static void wrapAndThrowExecutionExceptionOrError(Throwable cause) throws ExecutionException { if (cause instanceof Error) { throw new ExecutionError((Error) cause); } else if (cause instanceof RuntimeException) { throw new UncheckedExecutionException(cause); } else { throw new ExecutionException(cause); } }
Creates a TimeLimiter instance using the given executor service to execute method calls. <p><b>Warning:</b> using a bounded executor may be counterproductive! If the thread pool fills up, any time callers spend waiting for a thread may count toward their time limit, and in this case the call may even time out before the target method is ever invoked. @param executor the ExecutorService that will execute the method calls on the target objects; for example, a {@link Executors#newCachedThreadPool()}. @since 22.0
java
android/guava/src/com/google/common/util/concurrent/SimpleTimeLimiter.java
261
[ "cause" ]
void
true
3
6.72
google/guava
51,352
javadoc
false
loss_gradient
def loss_gradient( self, coef, X, y, sample_weight=None, l2_reg_strength=0.0, n_threads=1, raw_prediction=None, ): """Computes the sum of loss and gradient w.r.t. coef. Parameters ---------- coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) Coefficients of a linear model. If shape (n_classes * n_dof,), the classes of one feature are contiguous, i.e. one reconstructs the 2d-array via coef.reshape((n_classes, -1), order="F"). X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : contiguous array of shape (n_samples,) Observed, true target values. sample_weight : None or contiguous array of shape (n_samples,), default=None Sample weights. l2_reg_strength : float, default=0.0 L2 regularization strength n_threads : int, default=1 Number of OpenMP threads to use. raw_prediction : C-contiguous array of shape (n_samples,) or array of \ shape (n_samples, n_classes) Raw prediction values (in link space). If provided, these are used. If None, then raw_prediction = X @ coef + intercept is calculated. Returns ------- loss : float Weighted average of losses per sample, plus penalty. gradient : ndarray of shape coef.shape The gradient of the loss. """ (n_samples, n_features), n_classes = X.shape, self.base_loss.n_classes n_dof = n_features + int(self.fit_intercept) if raw_prediction is None: weights, intercept, raw_prediction = self.weight_intercept_raw(coef, X) else: weights, intercept = self.weight_intercept(coef) loss, grad_pointwise = self.base_loss.loss_gradient( y_true=y, raw_prediction=raw_prediction, sample_weight=sample_weight, n_threads=n_threads, ) sw_sum = n_samples if sample_weight is None else np.sum(sample_weight) loss = loss.sum() / sw_sum loss += self.l2_penalty(weights, l2_reg_strength) grad_pointwise /= sw_sum if not self.base_loss.is_multiclass: grad = np.empty_like(coef, dtype=weights.dtype) grad[:n_features] = X.T @ grad_pointwise + l2_reg_strength * weights if self.fit_intercept: grad[-1] = grad_pointwise.sum() else: grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") # grad_pointwise.shape = (n_samples, n_classes) grad[:, :n_features] = grad_pointwise.T @ X + l2_reg_strength * weights if self.fit_intercept: grad[:, -1] = grad_pointwise.sum(axis=0) if coef.ndim == 1: grad = grad.ravel(order="F") return loss, grad
Computes the sum of loss and gradient w.r.t. coef. Parameters ---------- coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) Coefficients of a linear model. If shape (n_classes * n_dof,), the classes of one feature are contiguous, i.e. one reconstructs the 2d-array via coef.reshape((n_classes, -1), order="F"). X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : contiguous array of shape (n_samples,) Observed, true target values. sample_weight : None or contiguous array of shape (n_samples,), default=None Sample weights. l2_reg_strength : float, default=0.0 L2 regularization strength n_threads : int, default=1 Number of OpenMP threads to use. raw_prediction : C-contiguous array of shape (n_samples,) or array of \ shape (n_samples, n_classes) Raw prediction values (in link space). If provided, these are used. If None, then raw_prediction = X @ coef + intercept is calculated. Returns ------- loss : float Weighted average of losses per sample, plus penalty. gradient : ndarray of shape coef.shape The gradient of the loss.
python
sklearn/linear_model/_linear_loss.py
269
[ "self", "coef", "X", "y", "sample_weight", "l2_reg_strength", "n_threads", "raw_prediction" ]
false
9
6
scikit-learn/scikit-learn
64,340
numpy
false
forFile
public static Layout forFile(File file) { Assert.notNull(file, "'file' must not be null"); String lowerCaseFileName = file.getName().toLowerCase(Locale.ENGLISH); if (lowerCaseFileName.endsWith(".jar")) { return new Jar(); } if (lowerCaseFileName.endsWith(".war")) { return new War(); } if (file.isDirectory() || lowerCaseFileName.endsWith(".zip")) { return new Expanded(); } throw new IllegalStateException("Unable to deduce layout for '" + file + "'"); }
Return a layout for the given source file. @param file the source file @return a {@link Layout}
java
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Layouts.java
49
[ "file" ]
Layout
true
5
8.08
spring-projects/spring-boot
79,428
javadoc
false
_safe_print
def _safe_print(*args: Any, **kwargs: Any) -> None: """Safe print that avoids recursive torch function dispatches.""" import sys # Convert any torch objects to basic representations safe_args = [] for arg in args: if hasattr(arg, "__class__") and "torch" in str(type(arg)): safe_args.append(f"<{type(arg).__name__}>") else: safe_args.append(str(arg)) print(*safe_args, **kwargs, file=sys.stderr)
Safe print that avoids recursive torch function dispatches.
python
functorch/dim/__init__.py
413
[]
None
true
5
6.72
pytorch/pytorch
96,034
unknown
false
toObject
public static Character[] toObject(final char[] array) { if (array == null) { return null; } if (array.length == 0) { return EMPTY_CHARACTER_OBJECT_ARRAY; } return setAll(new Character[array.length], i -> Character.valueOf(array[i])); }
Converts an array of primitive chars to objects. <p>This method returns {@code null} for a {@code null} input array.</p> @param array a {@code char} array. @return a {@link Character} array, {@code null} if null array input.
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
8,708
[ "array" ]
true
3
8.24
apache/commons-lang
2,896
javadoc
false
find
static Zip64EndOfCentralDirectoryLocator find(DataBlock dataBlock, long endOfCentralDirectoryPos) throws IOException { debug.log("Finding Zip64EndOfCentralDirectoryLocator from EOCD at %s", endOfCentralDirectoryPos); long pos = endOfCentralDirectoryPos - SIZE; if (pos < 0) { debug.log("No Zip64EndOfCentralDirectoryLocator due to negative position %s", pos); return null; } ByteBuffer buffer = ByteBuffer.allocate(SIZE); buffer.order(ByteOrder.LITTLE_ENDIAN); dataBlock.read(buffer, pos); buffer.rewind(); int signature = buffer.getInt(); if (signature != SIGNATURE) { debug.log("Found incorrect Zip64EndOfCentralDirectoryLocator signature %s at position %s", signature, pos); return null; } debug.log("Found Zip64EndOfCentralDirectoryLocator at position %s", pos); return new Zip64EndOfCentralDirectoryLocator(pos, buffer.getInt(), buffer.getLong(), buffer.getInt()); }
Return the {@link Zip64EndOfCentralDirectoryLocator} or {@code null} if this is not a Zip64 file. @param dataBlock the source data block @param endOfCentralDirectoryPos the {@link ZipEndOfCentralDirectoryRecord} position @return a {@link Zip64EndOfCentralDirectoryLocator} instance or null @throws IOException on I/O error
java
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/zip/Zip64EndOfCentralDirectoryLocator.java
59
[ "dataBlock", "endOfCentralDirectoryPos" ]
Zip64EndOfCentralDirectoryLocator
true
3
7.28
spring-projects/spring-boot
79,428
javadoc
false
is_interval_dtype
def is_interval_dtype(arr_or_dtype) -> bool: """ Check whether an array-like or dtype is of the Interval dtype. .. deprecated:: 2.2.0 Use isinstance(dtype, pd.IntervalDtype) instead. Parameters ---------- arr_or_dtype : array-like or dtype The array-like or dtype to check. Returns ------- boolean Whether or not the array-like or dtype is of the Interval dtype. See Also -------- api.types.is_object_dtype : Check whether an array-like or dtype is of the object dtype. api.types.is_numeric_dtype : Check whether the provided array or dtype is of a numeric dtype. api.types.is_categorical_dtype : Check whether an array-like or dtype is of the Categorical dtype. Examples -------- >>> from pandas.api.types import is_interval_dtype >>> is_interval_dtype(object) False >>> is_interval_dtype(pd.IntervalDtype()) True >>> is_interval_dtype([1, 2, 3]) False >>> >>> interval = pd.Interval(1, 2, closed="right") >>> is_interval_dtype(interval) False >>> is_interval_dtype(pd.IntervalIndex([interval])) True """ # GH#52607 warnings.warn( "is_interval_dtype is deprecated and will be removed in a future version. " "Use `isinstance(dtype, pd.IntervalDtype)` instead", Pandas4Warning, stacklevel=2, ) if isinstance(arr_or_dtype, ExtensionDtype): # GH#33400 fastpath for dtype object return arr_or_dtype.type is Interval if arr_or_dtype is None: return False return IntervalDtype.is_dtype(arr_or_dtype)
Check whether an array-like or dtype is of the Interval dtype. .. deprecated:: 2.2.0 Use isinstance(dtype, pd.IntervalDtype) instead. Parameters ---------- arr_or_dtype : array-like or dtype The array-like or dtype to check. Returns ------- boolean Whether or not the array-like or dtype is of the Interval dtype. See Also -------- api.types.is_object_dtype : Check whether an array-like or dtype is of the object dtype. api.types.is_numeric_dtype : Check whether the provided array or dtype is of a numeric dtype. api.types.is_categorical_dtype : Check whether an array-like or dtype is of the Categorical dtype. Examples -------- >>> from pandas.api.types import is_interval_dtype >>> is_interval_dtype(object) False >>> is_interval_dtype(pd.IntervalDtype()) True >>> is_interval_dtype([1, 2, 3]) False >>> >>> interval = pd.Interval(1, 2, closed="right") >>> is_interval_dtype(interval) False >>> is_interval_dtype(pd.IntervalIndex([interval])) True
python
pandas/core/dtypes/common.py
490
[ "arr_or_dtype" ]
bool
true
3
8
pandas-dev/pandas
47,362
numpy
false
removeAllOccurrences
public static long[] removeAllOccurrences(final long[] array, final long element) { return (long[]) removeAt(array, indexesOf(array, element)); }
Removes the occurrences of the specified element from the specified long array. <p> All subsequent elements are shifted to the left (subtracts one from their indices). If the array doesn't contain such an element, no elements are removed from the array. {@code null} will be returned if the input array is {@code null}. </p> @param array the input array, will not be modified, and may be {@code null}. @param element the element to remove. @return A new array containing the existing elements except the occurrences of the specified element. @since 3.10
java
src/main/java/org/apache/commons/lang3/ArrayUtils.java
5,538
[ "array", "element" ]
true
1
6.96
apache/commons-lang
2,896
javadoc
false
haversinMeters
public static double haversinMeters(double lat1, double lon1, double lat2, double lon2) { return haversinMeters(haversinSortKey(lat1, lon1, lat2, lon2)); }
Returns the Haversine distance in meters between two points specified in decimal degrees (latitude/longitude). This works correctly even if the dateline is between the two points. <p>Error is at most 4E-1 (40cm) from the actual haversine distance, but is typically much smaller for reasonable distances: around 1E-5 (0.01mm) for distances less than 1000km. @param lat1 Latitude of the first point. @param lon1 Longitude of the first point. @param lat2 Latitude of the second point. @param lon2 Longitude of the second point. @return distance in meters.
java
libs/geo/src/main/java/org/elasticsearch/geometry/simplify/SloppyMath.java
32
[ "lat1", "lon1", "lat2", "lon2" ]
true
1
6.96
elastic/elasticsearch
75,680
javadoc
false
missRate
public double missRate() { long requestCount = requestCount(); return (requestCount == 0) ? 0.0 : (double) missCount / requestCount; }
Returns the ratio of cache requests which were misses. This is defined as {@code missCount / requestCount}, or {@code 0.0} when {@code requestCount == 0}. Note that {@code hitRate + missRate =~ 1.0}. Cache misses include all requests which weren't cache hits, including requests which resulted in either successful or failed loading attempts, and requests which waited for other threads to finish loading. It is thus the case that {@code missCount >= loadSuccessCount + loadExceptionCount}. Multiple concurrent misses for the same key will result in a single load operation.
java
android/guava/src/com/google/common/cache/CacheStats.java
147
[]
true
2
6.64
google/guava
51,352
javadoc
false
withoutImports
ConfigDataProperties withoutImports() { return new ConfigDataProperties(null, this.activate); }
Return a new variant of these properties without any imports. @return a new {@link ConfigDataProperties} instance
java
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java
83
[]
ConfigDataProperties
true
1
6
spring-projects/spring-boot
79,428
javadoc
false
staged_predict
def staged_predict(self, X): """Predict classes at each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. .. versionadded:: 0.24 Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Yields ------ y : generator of ndarray of shape (n_samples,) The predicted classes of the input samples, for each iteration. """ for raw_predictions in self._staged_raw_predict(X): if raw_predictions.shape[1] == 1: # np.argmax([0, 0]) is 0, not 1, therefore "> 0" not ">= 0" encoded_classes = (raw_predictions.ravel() > 0).astype(int) else: encoded_classes = np.argmax(raw_predictions, axis=1) yield self.classes_.take(encoded_classes, axis=0)
Predict classes at each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. .. versionadded:: 0.24 Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Yields ------ y : generator of ndarray of shape (n_samples,) The predicted classes of the input samples, for each iteration.
python
sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
2,237
[ "self", "X" ]
false
4
6.08
scikit-learn/scikit-learn
64,340
numpy
false
from
public <T> Source<T> from(@Nullable T value) { return from(() -> value); }
Return a new {@link Source} from the specified value that can be used to perform the mapping. @param <T> the source type @param value the value @return a {@link Source} that can be used to complete the mapping
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java
96
[ "value" ]
true
1
6.96
spring-projects/spring-boot
79,428
javadoc
false
__contains__
def __contains__(self, key: Any) -> bool: """ return a boolean if this key is IN the index We *only* accept an Interval Parameters ---------- key : Interval Returns ------- bool """ hash(key) if not isinstance(key, Interval): if is_valid_na_for_dtype(key, self.dtype): return self.hasnans return False try: self.get_loc(key) return True except KeyError: return False
return a boolean if this key is IN the index We *only* accept an Interval Parameters ---------- key : Interval Returns ------- bool
python
pandas/core/indexes/interval.py
456
[ "self", "key" ]
bool
true
3
6.4
pandas-dev/pandas
47,362
numpy
false
whenHasText
public Source<T> whenHasText() { return when((value) -> StringUtils.hasText(value.toString())); }
Return a filtered version of the source that will only map values that have a {@code toString()} containing actual text. @return a new filtered source instance
java
core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java
234
[]
true
1
6.64
spring-projects/spring-boot
79,428
javadoc
false
to_string
def to_string( self, buf: FilePath | WriteBuffer[str] | None = None, *, encoding: str | None = None, sparse_index: bool | None = None, sparse_columns: bool | None = None, max_rows: int | None = None, max_columns: int | None = None, delimiter: str = " ", ) -> str | None: """ Write Styler to a file, buffer or string in text format. Parameters ---------- %(buf)s %(encoding)s sparse_index : bool, optional Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. Defaults to ``pandas.options.styler.sparse.index`` value. sparse_columns : bool, optional Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each column. Defaults to ``pandas.options.styler.sparse.columns`` value. max_rows : int, optional The maximum number of rows that will be rendered. Defaults to ``pandas.options.styler.render.max_rows``, which is None. max_columns : int, optional The maximum number of columns that will be rendered. Defaults to ``pandas.options.styler.render.max_columns``, which is None. Rows and columns may be reduced if the number of total elements is large. This value is set to ``pandas.options.styler.render.max_elements``, which is 262144 (18 bit browser rendering). delimiter : str, default single space The separator between data elements. Returns ------- str or None If `buf` is None, returns the result as a string. Otherwise returns `None`. See Also -------- DataFrame.to_string : Render a DataFrame to a console-friendly tabular output. Examples -------- >>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}) >>> df.style.to_string() ' A B\\n0 1 3\\n1 2 4\\n' """ obj = self._copy(deepcopy=True) if sparse_index is None: sparse_index = get_option("styler.sparse.index") if sparse_columns is None: sparse_columns = get_option("styler.sparse.columns") text = obj._render_string( sparse_columns=sparse_columns, sparse_index=sparse_index, max_rows=max_rows, max_cols=max_columns, delimiter=delimiter, ) return save_to_buffer( text, buf=buf, encoding=(encoding if buf is not None else None) )
Write Styler to a file, buffer or string in text format. Parameters ---------- %(buf)s %(encoding)s sparse_index : bool, optional Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row. Defaults to ``pandas.options.styler.sparse.index`` value. sparse_columns : bool, optional Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each column. Defaults to ``pandas.options.styler.sparse.columns`` value. max_rows : int, optional The maximum number of rows that will be rendered. Defaults to ``pandas.options.styler.render.max_rows``, which is None. max_columns : int, optional The maximum number of columns that will be rendered. Defaults to ``pandas.options.styler.render.max_columns``, which is None. Rows and columns may be reduced if the number of total elements is large. This value is set to ``pandas.options.styler.render.max_elements``, which is 262144 (18 bit browser rendering). delimiter : str, default single space The separator between data elements. Returns ------- str or None If `buf` is None, returns the result as a string. Otherwise returns `None`. See Also -------- DataFrame.to_string : Render a DataFrame to a console-friendly tabular output. Examples -------- >>> df = pd.DataFrame({"A": [1, 2], "B": [3, 4]}) >>> df.style.to_string() ' A B\\n0 1 3\\n1 2 4\\n'
python
pandas/io/formats/style.py
1,517
[ "self", "buf", "encoding", "sparse_index", "sparse_columns", "max_rows", "max_columns", "delimiter" ]
str | None
true
4
7.92
pandas-dev/pandas
47,362
numpy
false
calcTimeoutMsRemainingAsInt
static int calcTimeoutMsRemainingAsInt(long now, long deadlineMs) { long deltaMs = deadlineMs - now; if (deltaMs > Integer.MAX_VALUE) deltaMs = Integer.MAX_VALUE; else if (deltaMs < Integer.MIN_VALUE) deltaMs = Integer.MIN_VALUE; return (int) deltaMs; }
Get the current time remaining before a deadline as an integer. @param now The current time in milliseconds. @param deadlineMs The deadline time in milliseconds. @return The time delta in milliseconds.
java
clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java
461
[ "now", "deadlineMs" ]
true
3
7.92
apache/kafka
31,560
javadoc
false
isReusableParameter
function isReusableParameter(node: Node) { if (node.kind !== SyntaxKind.Parameter) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. const parameter = node as ParameterDeclaration; return parameter.initializer === undefined; }
Reports a diagnostic error for the current token being an invalid name. @param blankDiagnostic Diagnostic to report for the case of the name being blank (matched tokenIfBlankName). @param nameDiagnostic Diagnostic to report for all other cases. @param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped).
typescript
src/compiler/parser.ts
3,399
[ "node" ]
false
2
6.08
microsoft/TypeScript
107,154
jsdoc
false
positionOrNull
public synchronized FetchPosition positionOrNull(TopicPartition tp) { final TopicPartitionState state = assignedStateOrNull(tp); if (state == null) { return null; } return assignedState(tp).position; }
Attempt to complete validation with the end offset returned from the OffsetForLeaderEpoch request. @return Log truncation details if detected and no reset policy is defined.
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/SubscriptionState.java
632
[ "tp" ]
FetchPosition
true
2
6.4
apache/kafka
31,560
javadoc
false
doConvertValue
private @Nullable Object doConvertValue(@Nullable Object oldValue, @Nullable Object newValue, @Nullable Class<?> requiredType, @Nullable PropertyEditor editor) { Object convertedValue = newValue; if (editor != null && !(convertedValue instanceof String)) { // Not a String -> use PropertyEditor's setValue. // With standard PropertyEditors, this will return the very same object; // we just want to allow special PropertyEditors to override setValue // for type conversion from non-String values to the required type. try { editor.setValue(convertedValue); Object newConvertedValue = editor.getValue(); if (newConvertedValue != convertedValue) { convertedValue = newConvertedValue; // Reset PropertyEditor: It already did a proper conversion. // Don't use it again for a setAsText call. editor = null; } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex); } // Swallow and proceed. } } Object returnValue = convertedValue; if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[] array) { // Convert String array to a comma-separated String. // Only applies if no PropertyEditor converted the String array before. // The CSV String will be passed into a PropertyEditor's setAsText method, if any. if (logger.isTraceEnabled()) { logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]"); } convertedValue = StringUtils.arrayToCommaDelimitedString(array); } if (convertedValue instanceof String newTextValue) { if (editor != null) { // Use PropertyEditor's setAsText in case of a String value. if (logger.isTraceEnabled()) { logger.trace("Converting String to [" + requiredType + "] using property editor [" + editor + "]"); } return doConvertTextValue(oldValue, newTextValue, editor); } else if (String.class == requiredType) { returnValue = convertedValue; } } return returnValue; }
Convert the value to the required type (if necessary from a String), using the given property editor. @param oldValue the previous value, if available (may be {@code null}) @param newValue the proposed new value @param requiredType the type we must convert to (or {@code null} if not known, for example in case of a collection element) @param editor the PropertyEditor to use @return the new value, possibly the result of type conversion @throws IllegalArgumentException if type conversion failed
java
spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
361
[ "oldValue", "newValue", "requiredType", "editor" ]
Object
true
14
7.76
spring-projects/spring-framework
59,386
javadoc
false
toFinite
function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; }
Converts `value` to a finite number. @static @memberOf _ @since 4.12.0 @category Lang @param {*} value The value to convert. @returns {number} Returns the converted number. @example _.toFinite(3.2); // => 3.2 _.toFinite(Number.MIN_VALUE); // => 5e-324 _.toFinite(Infinity); // => 1.7976931348623157e+308 _.toFinite('3.2'); // => 3.2
javascript
lodash.js
12,465
[ "value" ]
false
7
7.2
lodash/lodash
61,490
jsdoc
false
addTo
public void addTo(String to, String personal) throws MessagingException, UnsupportedEncodingException { Assert.notNull(to, "To address must not be null"); addTo(getEncoding() != null ? new InternetAddress(to, personal, getEncoding()) : new InternetAddress(to, personal)); }
Validate all given mail addresses. <p>The default implementation simply delegates to {@link #validateAddress} for each address. @param addresses the addresses to validate @throws AddressException if validation failed @see #validateAddress(InternetAddress)
java
spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java
633
[ "to", "personal" ]
void
true
2
6.08
spring-projects/spring-framework
59,386
javadoc
false
lag2poly
def lag2poly(c): """ Convert a Laguerre series to a polynomial. Convert an array representing the coefficients of a Laguerre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Laguerre series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2lag Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import lag2poly >>> lag2poly([ 23., -63., 58., -18.]) array([0., 1., 2., 3.]) """ from .polynomial import polyadd, polymulx, polysub [c] = pu.as_series([c]) n = len(c) if n == 1: return c else: c0 = c[-2] c1 = c[-1] # i is the current degree of c1 for i in range(n - 1, 1, -1): tmp = c0 c0 = polysub(c[i - 2], (c1 * (i - 1)) / i) c1 = polyadd(tmp, polysub((2 * i - 1) * c1, polymulx(c1)) / i) return polyadd(c0, polysub(c1, polymulx(c1)))
Convert a Laguerre series to a polynomial. Convert an array representing the coefficients of a Laguerre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameters ---------- c : array_like 1-D array containing the Laguerre series coefficients, ordered from lowest order term to highest. Returns ------- pol : ndarray 1-D array containing the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest order term to highest. See Also -------- poly2lag Notes ----- The easy way to do conversions between polynomial basis sets is to use the convert method of a class instance. Examples -------- >>> from numpy.polynomial.laguerre import lag2poly >>> lag2poly([ 23., -63., 58., -18.]) array([0., 1., 2., 3.])
python
numpy/polynomial/laguerre.py
140
[ "c" ]
false
4
7.52
numpy/numpy
31,054
numpy
false
setExpression
public void setExpression(@Nullable String expression) { this.expression = expression; try { onSetExpression(expression); } catch (IllegalArgumentException ex) { // Fill in location information if possible. if (this.location != null) { throw new IllegalArgumentException("Invalid expression at location [" + this.location + "]: " + ex); } else { throw ex; } } }
Return location information about the pointcut expression if available. This is useful in debugging. @return location information as a human-readable String, or {@code null} if none is available
java
spring-aop/src/main/java/org/springframework/aop/support/AbstractExpressionPointcut.java
58
[ "expression" ]
void
true
3
6.88
spring-projects/spring-framework
59,386
javadoc
false
equals
@Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof Fraction)) { return false; } final Fraction other = (Fraction) obj; return getNumerator() == other.getNumerator() && getDenominator() == other.getDenominator(); }
Compares this fraction to another object to test if they are equal. <p> To be equal, both values must be equal. Thus 2/4 is not equal to 1/2. </p> @param obj the reference object with which to compare @return {@code true} if this object is equal
java
src/main/java/org/apache/commons/lang3/math/Fraction.java
641
[ "obj" ]
true
4
8.24
apache/commons-lang
2,896
javadoc
false
isLenient
function isLenient() { if (insecureHTTPParser && !warnedLenient) { warnedLenient = true; process.emitWarning('Using insecure HTTP parsing'); } return insecureHTTPParser; }
True if val contains an invalid field-vchar field-value = *( field-content / obs-fold ) field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] field-vchar = VCHAR / obs-text @param {string} val @returns {boolean}
javascript
lib/_http_common.js
293
[]
false
3
6.32
nodejs/node
114,839
jsdoc
false
parseJavaClassPath
@VisibleForTesting // TODO(b/65488446): Make this a public API. static ImmutableList<URL> parseJavaClassPath() { ImmutableList.Builder<URL> urls = ImmutableList.builder(); for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) { try { try { urls.add(new File(entry).toURI().toURL()); } catch (SecurityException e) { // File.toURI checks to see if the file is a directory urls.add(new URL("file", null, new File(entry).getAbsolutePath())); } } catch (MalformedURLException e) { logger.log(WARNING, "malformed classpath entry: " + entry, e); } } return urls.build(); }
Returns the URLs in the class path specified by the {@code java.class.path} {@linkplain System#getProperty system property}.
java
android/guava/src/com/google/common/reflect/ClassPath.java
636
[]
true
3
6.4
google/guava
51,352
javadoc
false
match
public final boolean match(EndpointId endpointId) { return isIncluded(endpointId) && !isExcluded(endpointId); }
Return {@code true} if the filter matches. @param endpointId the endpoint ID to check @return {@code true} if the filter matches @since 2.6.0
java
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilter.java
125
[ "endpointId" ]
true
2
7.84
spring-projects/spring-boot
79,428
javadoc
false
resolve
private List<StandardConfigDataResource> resolve(StandardConfigDataReference reference) { if (!this.resourceLoader.isPattern(reference.getResourceLocation())) { return resolveNonPattern(reference); } return resolvePattern(reference); }
Create a new {@link StandardConfigDataLocationResolver} instance. @param logFactory the factory for loggers to use @param binder a binder backed by the initial {@link Environment} @param resourceLoader a {@link ResourceLoader} used to load resources
java
core/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java
311
[ "reference" ]
true
2
6.08
spring-projects/spring-boot
79,428
javadoc
false
describeTopics
DescribeTopicsResult describeTopics(TopicCollection topics, DescribeTopicsOptions options);
Describe some topics in the cluster. When using topic IDs, this operation is supported by brokers with version 3.1.0 or higher. @param topics The topics to describe. @param options The options to use when describing the topics. @return The DescribeTopicsResult.
java
clients/src/main/java/org/apache/kafka/clients/admin/Admin.java
332
[ "topics", "options" ]
DescribeTopicsResult
true
1
6.48
apache/kafka
31,560
javadoc
false
_default_custom_combo_kernel_horizontal_partition
def _default_custom_combo_kernel_horizontal_partition( nodes: list[BaseSchedulerNode], triton_scheduling: SIMDScheduling, kernel_map: dict[BaseSchedulerNode, TritonKernel], node_info_map: dict[BaseSchedulerNode, tuple[Any, Any, Any, Any]], ) -> list[list[BaseSchedulerNode]]: """Horizontally partition the given list of nodes into a list of list of nodes where each sublist represents a partition. Nodes in different partitions are implemented in different combo kernels. Nodes in the same partition are likely to be implemented in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args. Input arguments: nodes: a list of fused scheduler nodes to partition. triton_scheduling: TritonScheduling instance. kernel_map: a map from node to its kernel. node_info_map: a map from node to (node_schedule, tiled_groups, numel, rnumel). Output: a list of list of nodes with each sublist representing a partition. The default algorithm is to partition nodes based on the following rules: 1) nodes with the same number of block dimensions are grouped together. 2) large pointwise nodes (numels greater than LARGE_NUMELS) are separated from other nodes. 3) large reduce nodes are separated from other nodes. """ assert len(nodes) >= 1 # first partition nodes based on number of block dimensions tilings = [node_info_map[n][1] for n in nodes] max_dims = max(len(t) for t in tilings) nodes_per_ndim: list[list[BaseSchedulerNode]] = [] for i in range(2, max_dims + 1): group_per_dim = [n for n, t in zip(nodes, tilings) if len(t) == i] reduction = [ n for n in group_per_dim if kernel_map[n].inside_reduction and not (kernel_map[n].persistent_reduction and kernel_map[n].no_x_dim) ] not_reduction = [n for n in group_per_dim if n not in reduction] # rnumel > 2048 usually has long execution time # BaseSchedulerNode.group[-1][-1] is rnumel for reduction nodes long_reduction = [ n for n in reduction if ( V.graph.sizevars.shape_env.has_hint(n.group[-1][-1]) and V.graph.sizevars.size_hint(n.group[-1][-1]) > 2048 # type: ignore[arg-type] ) ] short_reduction = [n for n in reduction if n not in long_reduction] if long_reduction: log.debug( "ComboKernels: %d long reduction nodes are separated", len(long_reduction), ) large_pointwise = [ n for n in not_reduction if not kernel_map[n].inside_reduction and len(kernel_map[n].numels) == 2 and V.graph.sizevars.shape_env.has_hint(kernel_map[n].numels["x"]) and V.graph.sizevars.size_hint(kernel_map[n].numels["x"]) > LARGE_NUMELS ] if large_pointwise: # TODO benchmark the performance when large pointwise nodes combining with others log.debug( "ComboKernels: %d large pointwise nodes are separated", len(large_pointwise), ) not_reduction = [n for n in not_reduction if n not in large_pointwise] nodes_per_ndim.extend([node] for node in large_pointwise) nodes_per_ndim.extend( g for g in (not_reduction, short_reduction, long_reduction) if g ) assert sum(len(p) for p in nodes_per_ndim) == len(nodes) return nodes_per_ndim
Horizontally partition the given list of nodes into a list of list of nodes where each sublist represents a partition. Nodes in different partitions are implemented in different combo kernels. Nodes in the same partition are likely to be implemented in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args. Input arguments: nodes: a list of fused scheduler nodes to partition. triton_scheduling: TritonScheduling instance. kernel_map: a map from node to its kernel. node_info_map: a map from node to (node_schedule, tiled_groups, numel, rnumel). Output: a list of list of nodes with each sublist representing a partition. The default algorithm is to partition nodes based on the following rules: 1) nodes with the same number of block dimensions are grouped together. 2) large pointwise nodes (numels greater than LARGE_NUMELS) are separated from other nodes. 3) large reduce nodes are separated from other nodes.
python
torch/_inductor/codegen/triton_combo_kernel.py
48
[ "nodes", "triton_scheduling", "kernel_map", "node_info_map" ]
list[list[BaseSchedulerNode]]
true
10
6.8
pytorch/pytorch
96,034
unknown
false
min
public static byte min(byte a, final byte b, final byte c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; }
Gets the minimum of three {@code byte} values. @param a value 1. @param b value 2. @param c value 3. @return the smallest of the values.
java
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
1,124
[ "a", "b", "c" ]
true
3
8.24
apache/commons-lang
2,896
javadoc
false
documentation
@Override public String documentation() { return "Represents a series of tagged fields."; }
Create a new TaggedFields object with the given tags and fields. @param fields This is an array containing Integer tags followed by associated Field objects. @return The new {@link TaggedFields}
java
clients/src/main/java/org/apache/kafka/common/protocol/types/TaggedFields.java
175
[]
String
true
1
6.64
apache/kafka
31,560
javadoc
false
generateCodeForFactoryMethod
private CodeBlock generateCodeForFactoryMethod( RegisteredBean registeredBean, Method factoryMethod, Class<?> targetClass) { if (!isVisible(factoryMethod, targetClass)) { return generateCodeForInaccessibleFactoryMethod(registeredBean.getBeanName(), factoryMethod, targetClass); } return generateCodeForAccessibleFactoryMethod(registeredBean.getBeanName(), factoryMethod, targetClass, registeredBean.getMergedBeanDefinition().getFactoryBeanName()); }
Generate the instance supplier code. @param registeredBean the bean to handle @param instantiationDescriptor the executable to use to create the bean @return the generated code @since 6.1.7
java
spring-beans/src/main/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGenerator.java
262
[ "registeredBean", "factoryMethod", "targetClass" ]
CodeBlock
true
2
7.44
spring-projects/spring-framework
59,386
javadoc
false
build
@Override Map<String, List<TopicPartition>> build() { if (log.isDebugEnabled()) { log.debug("performing general assign. partitionsPerTopic: {}, subscriptions: {}, currentAssignment: {}, rackInfo: {}", partitionsPerTopic, subscriptions, currentAssignment, rackInfo); } Map<TopicPartition, ConsumerGenerationPair> prevAssignment = new HashMap<>(); partitionMovements = new PartitionMovements(); prepopulateCurrentAssignments(prevAssignment); // the partitions already assigned in current assignment List<TopicPartition> assignedPartitions = assignOwnedPartitions(); // all partitions that still need to be assigned List<TopicPartition> unassignedPartitions = getUnassignedPartitions(assignedPartitions); if (log.isDebugEnabled()) { log.debug("unassigned Partitions: {}", unassignedPartitions); } // at this point we have preserved all valid topic partition to consumer assignments and removed // all invalid topic partitions and invalid consumers. Now we need to assign unassignedPartitions // to consumers so that the topic partition assignments are as balanced as possible. sortedCurrentSubscriptions.addAll(currentAssignment.keySet()); balance(prevAssignment, unassignedPartitions); log.info("Final assignment of partitions to consumers: \n{}", currentAssignment); return currentAssignment; }
Constructs a general assignment builder. @param partitionsPerTopic The partitions for each subscribed topic. @param subscriptions Map from the member id to their respective topic subscription @param currentAssignment Each consumer's previously owned and still-subscribed partitions @param rackInfo Rack information for consumers and partitions
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractStickyAssignor.java
1,000
[]
true
3
6.24
apache/kafka
31,560
javadoc
false
parseForValidate
Map<String, Object> parseForValidate(Map<String, String> props, Map<String, ConfigValue> configValues) { Map<String, Object> parsed = new HashMap<>(); Set<String> configsWithNoParent = getConfigsWithNoParent(); for (String name: configsWithNoParent) { parseForValidate(name, props, parsed, configValues); } return parsed; }
Validate the current configuration values with the configuration definition. @param props the current configuration values @return List of Config, each Config contains the updated configuration information given the current configuration values.
java
clients/src/main/java/org/apache/kafka/common/config/ConfigDef.java
585
[ "props", "configValues" ]
true
1
6.24
apache/kafka
31,560
javadoc
false
toLabelFilter
function toLabelFilter(key: string, value: string | number, operator: string): QueryBuilderLabelFilter { // We need to make sure that we convert the value back to string because it may be a number const transformedValue = value === Infinity ? '+Inf' : value.toString(); return { label: key, op: operator, value: transformedValue }; }
Parse the string and get all VectorSelector positions in the query together with parsed representation of the vector selector. @param query
typescript
packages/grafana-prometheus/src/add_label_to_query.ts
59
[ "key", "value", "operator" ]
true
2
6.56
grafana/grafana
71,362
jsdoc
false
resolveEmptyDirectories
private Collection<StandardConfigDataResource> resolveEmptyDirectories( Set<StandardConfigDataReference> references) { Set<StandardConfigDataResource> empty = new LinkedHashSet<>(); for (StandardConfigDataReference reference : references) { if (reference.getDirectory() != null) { empty.addAll(resolveEmptyDirectories(reference)); } } return empty; }
Create a new {@link StandardConfigDataLocationResolver} instance. @param logFactory the factory for loggers to use @param binder a binder backed by the initial {@link Environment} @param resourceLoader a {@link ResourceLoader} used to load resources
java
core/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java
270
[ "references" ]
true
2
6.08
spring-projects/spring-boot
79,428
javadoc
false
assignOwnedPartitions
private List<TopicPartition> assignOwnedPartitions() { List<TopicPartition> assignedPartitions = new ArrayList<>(); for (Iterator<Entry<String, List<TopicPartition>>> it = currentAssignment.entrySet().iterator(); it.hasNext();) { Map.Entry<String, List<TopicPartition>> entry = it.next(); String consumer = entry.getKey(); Subscription consumerSubscription = subscriptions.get(consumer); if (consumerSubscription == null) { // if a consumer that existed before (and had some partition assignments) is now removed, remove it from currentAssignment for (TopicPartition topicPartition: entry.getValue()) currentPartitionConsumer.remove(topicPartition); it.remove(); } else { // otherwise (the consumer still exists) for (Iterator<TopicPartition> partitionIter = entry.getValue().iterator(); partitionIter.hasNext();) { TopicPartition partition = partitionIter.next(); if (!topic2AllPotentialConsumers.containsKey(partition.topic())) { // if this topic partition of this consumer no longer exists, remove it from currentAssignment of the consumer partitionIter.remove(); currentPartitionConsumer.remove(partition); } else if (!consumerSubscription.topics().contains(partition.topic()) || rackInfo.racksMismatch(consumer, partition)) { // if the consumer is no longer subscribed to its topic or if racks don't match for rack-aware assignment, // remove it from currentAssignment of the consumer partitionIter.remove(); revocationRequired = true; } else { // otherwise, remove the topic partition from those that need to be assigned only if // its current consumer is still subscribed to its topic (because it is already assigned // and we would want to preserve that assignment as much as possible) assignedPartitions.add(partition); } } } } return assignedPartitions; }
Constructs a general assignment builder. @param partitionsPerTopic The partitions for each subscribed topic. @param subscriptions Map from the member id to their respective topic subscription @param currentAssignment Each consumer's previously owned and still-subscribed partitions @param rackInfo Rack information for consumers and partitions
java
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractStickyAssignor.java
1,033
[]
true
7
6.24
apache/kafka
31,560
javadoc
false
getT
public <T, E extends Throwable> T getT(final FailableSupplier<T, E> supplier) throws Throwable { startResume(); try { return supplier.get(); } finally { suspend(); } }
Delegates to {@link FailableSupplier#get()} while recording the duration of the call. @param <T> the type of results supplied by this supplier. @param <E> The kind of thrown exception or error. @param supplier The supplier to {@link Supplier#get()}. @return a result from the given Supplier. @throws Throwable if the supplier fails. @since 3.18.0
java
src/main/java/org/apache/commons/lang3/time/StopWatch.java
535
[ "supplier" ]
T
true
1
6.72
apache/commons-lang
2,896
javadoc
false
insert
def insert(self, loc: int, item: Hashable, value: ArrayLike, refs=None) -> None: """ Insert item at selected position. Parameters ---------- loc : int item : hashable value : np.ndarray or ExtensionArray refs : The reference tracking object of the value to set. """ new_axis = self.items.insert(loc, item) if value.ndim == 2: value = value.T if len(value) > 1: raise ValueError( f"Expected a 1D array, got an array with shape {value.T.shape}" ) else: value = ensure_block_shape(value, ndim=self.ndim) bp = BlockPlacement(slice(loc, loc + 1)) block = new_block_2d(values=value, placement=bp, refs=refs) if not len(self.blocks): # Fastpath self._blklocs = np.array([0], dtype=np.intp) self._blknos = np.array([0], dtype=np.intp) else: self._insert_update_mgr_locs(loc) self._insert_update_blklocs_and_blknos(loc) self.axes[0] = new_axis self.blocks += (block,) self._known_consolidated = False if ( get_option("performance_warnings") and sum(not block.is_extension for block in self.blocks) > 100 ): warnings.warn( "DataFrame is highly fragmented. This is usually the result " "of calling `frame.insert` many times, which has poor performance. " "Consider joining all columns at once using pd.concat(axis=1) " "instead. To get a de-fragmented frame, use `newframe = frame.copy()`", PerformanceWarning, stacklevel=find_stack_level(), )
Insert item at selected position. Parameters ---------- loc : int item : hashable value : np.ndarray or ExtensionArray refs : The reference tracking object of the value to set.
python
pandas/core/internals/managers.py
1,496
[ "self", "loc", "item", "value", "refs" ]
None
true
8
6.72
pandas-dev/pandas
47,362
numpy
false
getObject
@Override public Object getObject() { if (this.proxy == null) { throw new FactoryBeanNotInitializedException(); } return this.proxy; }
A hook for subclasses to post-process the {@link ProxyFactory} before creating the proxy instance with it. @param proxyFactory the AOP ProxyFactory about to be used @since 4.2
java
spring-aop/src/main/java/org/springframework/aop/framework/AbstractSingletonProxyFactoryBean.java
210
[]
Object
true
2
6.4
spring-projects/spring-framework
59,386
javadoc
false
import_executor_cls
def import_executor_cls(cls, executor_name: ExecutorName) -> tuple[type[BaseExecutor], ConnectorSource]: """ Import the executor class. Supports the same formats as ExecutorLoader.load_executor. :param executor_name: Name of core executor or module path to executor. :return: executor class via executor_name and executor import source """ return import_string(executor_name.module_path), executor_name.connector_source
Import the executor class. Supports the same formats as ExecutorLoader.load_executor. :param executor_name: Name of core executor or module path to executor. :return: executor class via executor_name and executor import source
python
airflow-core/src/airflow/executors/executor_loader.py
368
[ "cls", "executor_name" ]
tuple[type[BaseExecutor], ConnectorSource]
true
1
6.24
apache/airflow
43,597
sphinx
false
lexsort_indexer
def lexsort_indexer( keys: Sequence[ArrayLike | Index | Series], orders=None, na_position: str = "last", key: Callable | None = None, codes_given: bool = False, ) -> npt.NDArray[np.intp]: """ Performs lexical sorting on a set of keys Parameters ---------- keys : Sequence[ArrayLike | Index | Series] Sequence of arrays to be sorted by the indexer Sequence[Series] is only if key is not None. orders : bool or list of booleans, optional Determines the sorting order for each element in keys. If a list, it must be the same length as keys. This determines whether the corresponding element in keys should be sorted in ascending (True) or descending (False) order. if bool, applied to all elements as above. if None, defaults to True. na_position : {'first', 'last'}, default 'last' Determines placement of NA elements in the sorted list ("last" or "first") key : Callable, optional Callable key function applied to every element in keys before sorting codes_given: bool, False Avoid categorical materialization if codes are already provided. Returns ------- np.ndarray[np.intp] """ from pandas.core.arrays import Categorical if na_position not in ["last", "first"]: raise ValueError(f"invalid na_position: {na_position}") if isinstance(orders, bool): orders = itertools.repeat(orders, len(keys)) elif orders is None: orders = itertools.repeat(True, len(keys)) else: orders = reversed(orders) labels = [] for k, order in zip(reversed(keys), orders, strict=True): k = ensure_key_mapped(k, key) if codes_given: codes = cast(np.ndarray, k) n = codes.max() + 1 if len(codes) else 0 else: cat = Categorical(k, ordered=True) codes = cat.codes n = len(cat.categories) mask = codes == -1 if na_position == "last" and mask.any(): codes = np.where(mask, n, codes) # not order means descending if not order: codes = np.where(mask, codes, n - codes - 1) labels.append(codes) return np.lexsort(labels)
Performs lexical sorting on a set of keys Parameters ---------- keys : Sequence[ArrayLike | Index | Series] Sequence of arrays to be sorted by the indexer Sequence[Series] is only if key is not None. orders : bool or list of booleans, optional Determines the sorting order for each element in keys. If a list, it must be the same length as keys. This determines whether the corresponding element in keys should be sorted in ascending (True) or descending (False) order. if bool, applied to all elements as above. if None, defaults to True. na_position : {'first', 'last'}, default 'last' Determines placement of NA elements in the sorted list ("last" or "first") key : Callable, optional Callable key function applied to every element in keys before sorting codes_given: bool, False Avoid categorical materialization if codes are already provided. Returns ------- np.ndarray[np.intp]
python
pandas/core/sorting.py
302
[ "keys", "orders", "na_position", "key", "codes_given" ]
npt.NDArray[np.intp]
true
12
6.8
pandas-dev/pandas
47,362
numpy
false
of
@SafeVarargs // Creating a stream from an array is safe public static IntStream of(final int... values) { return values == null ? IntStream.empty() : IntStream.of(values); }
Null-safe version of {@link IntStream#of(int[])}. @param values the elements of the new stream, may be {@code null}. @return the new stream on {@code values} or {@link IntStream#empty()}. @since 3.18.0
java
src/main/java/org/apache/commons/lang3/stream/IntStreams.java
38
[]
IntStream
true
2
7.84
apache/commons-lang
2,896
javadoc
false
omitBy
function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); }
The opposite of `_.pickBy`; this method creates an object composed of the own and inherited enumerable string keyed properties of `object` that `predicate` doesn't return truthy for. The predicate is invoked with two arguments: (value, key). @static @memberOf _ @since 4.0.0 @category Object @param {Object} object The source object. @param {Function} [predicate=_.identity] The function invoked per property. @returns {Object} Returns the new object. @example var object = { 'a': 1, 'b': '2', 'c': 3 }; _.omitBy(object, _.isNumber); // => { 'b': '2' }
javascript
lodash.js
13,645
[ "object", "predicate" ]
false
1
6.24
lodash/lodash
61,490
jsdoc
false
reverse
@CheckReturnValue public Converter<B, A> reverse() { Converter<B, A> result = reverse; return (result == null) ? reverse = new ReverseConverter<>(this) : result; }
Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a value roughly equivalent to {@code a}. <p>The returned converter is serializable if {@code this} converter is. <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons.
java
android/guava/src/com/google/common/base/Converter.java
301
[]
true
2
7.04
google/guava
51,352
javadoc
false
scopeWithDelimiter
private static String scopeWithDelimiter(Inet6Address ip) { // getHostAddress on android sometimes maps the scope ID to an invalid interface name; if the // mapped interface isn't present, fallback to use the scope ID (which has no validation against // present interfaces) NetworkInterface scopedInterface = ip.getScopedInterface(); if (scopedInterface != null) { return "%" + scopedInterface.getName(); } int scope = ip.getScopeId(); if (scope != 0) { return "%" + scope; } return ""; }
Returns the string representation of an {@link InetAddress}. <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6 addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section 4. The main difference is that this method uses "::" for zero compression, while Java's version uses the uncompressed form (except on Android, where the zero compression is also done). The other difference is that this method outputs any scope ID in the format that it was provided at creation time, while Android may always output it as an interface name, even if it was supplied as a numeric ID. <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses such as "::c000:201". @param ip {@link InetAddress} to be converted to an address string @return {@code String} containing the text-formatted IP address @since 10.0
java
android/guava/src/com/google/common/net/InetAddresses.java
483
[ "ip" ]
String
true
3
8.08
google/guava
51,352
javadoc
false
readResolve
private Object readResolve() { return NULL; }
Ensures singleton after serialization. @return the singleton value.
java
src/main/java/org/apache/commons/lang3/ObjectUtils.java
96
[]
Object
true
1
6.16
apache/commons-lang
2,896
javadoc
false
incidentEdges
@Override public Set<E> incidentEdges() { return new AbstractSet<E>() { @Override public UnmodifiableIterator<E> iterator() { Iterable<E> incidentEdges = (selfLoopCount == 0) ? Iterables.concat(inEdgeMap.keySet(), outEdgeMap.keySet()) : Sets.union(inEdgeMap.keySet(), outEdgeMap.keySet()); return Iterators.unmodifiableIterator(incidentEdges.iterator()); } @Override public int size() { return IntMath.saturatedAdd(inEdgeMap.size(), outEdgeMap.size() - selfLoopCount); } @Override public boolean contains(@Nullable Object obj) { return inEdgeMap.containsKey(obj) || outEdgeMap.containsKey(obj); } }; }
Keys are edges outgoing from the origin node, values are the target node.
java
android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java
64
[]
true
3
7.04
google/guava
51,352
javadoc
false
records
public List<ConsumerRecord<K, V>> records(TopicPartition partition) { List<ConsumerRecord<K, V>> recs = this.records.get(partition); if (recs == null) return Collections.emptyList(); else return Collections.unmodifiableList(recs); }
Get just the records for the given partition @param partition The partition to get records for
java
clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerRecords.java
58
[ "partition" ]
true
2
6.4
apache/kafka
31,560
javadoc
false
get_workflow_run_id
def get_workflow_run_id(workflow_name: str, repo: str) -> int: """ Get the latest workflow run ID for a given workflow name and repository. :param workflow_name: The name of the workflow to check. :param repo: The repository in the format 'owner/repo'. """ make_sure_gh_is_installed() command = [ "gh", "run", "list", "--workflow", workflow_name, "--repo", repo, "--limit", "1", "--json", "databaseId", ] result = run_command(command, capture_output=True, check=False) if result.returncode != 0: get_console().print(f"[red]Error fetching workflow run ID: {result.stderr}[/red]") sys.exit(1) runs_data = result.stdout.strip() if not runs_data: get_console().print("[red]No workflow runs found.[/red]") sys.exit(1) run_id = json.loads(runs_data)[0].get("databaseId") get_console().print( f"[blue]Running workflow {workflow_name} at https://github.com/{repo}/actions/runs/{run_id}[/blue]", ) return run_id
Get the latest workflow run ID for a given workflow name and repository. :param workflow_name: The name of the workflow to check. :param repo: The repository in the format 'owner/repo'.
python
dev/breeze/src/airflow_breeze/utils/gh_workflow_utils.py
90
[ "workflow_name", "repo" ]
int
true
3
7.04
apache/airflow
43,597
sphinx
false
writeHeader
public static void writeHeader(ByteBuffer buffer, long baseOffset, int lastOffsetDelta, int sizeInBytes, byte magic, CompressionType compressionType, TimestampType timestampType, long baseTimestamp, long maxTimestamp, long producerId, short epoch, int sequence, boolean isTransactional, boolean isControlBatch, boolean isDeleteHorizonSet, int partitionLeaderEpoch, int numRecords) { if (magic < RecordBatch.CURRENT_MAGIC_VALUE) throw new IllegalArgumentException("Invalid magic value " + magic); if (baseTimestamp < 0 && baseTimestamp != NO_TIMESTAMP) throw new IllegalArgumentException("Invalid message timestamp " + baseTimestamp); short attributes = computeAttributes(compressionType, timestampType, isTransactional, isControlBatch, isDeleteHorizonSet); int position = buffer.position(); buffer.putLong(position + BASE_OFFSET_OFFSET, baseOffset); buffer.putInt(position + LENGTH_OFFSET, sizeInBytes - LOG_OVERHEAD); buffer.putInt(position + PARTITION_LEADER_EPOCH_OFFSET, partitionLeaderEpoch); buffer.put(position + MAGIC_OFFSET, magic); buffer.putShort(position + ATTRIBUTES_OFFSET, attributes); buffer.putLong(position + BASE_TIMESTAMP_OFFSET, baseTimestamp); buffer.putLong(position + MAX_TIMESTAMP_OFFSET, maxTimestamp); buffer.putInt(position + LAST_OFFSET_DELTA_OFFSET, lastOffsetDelta); buffer.putLong(position + PRODUCER_ID_OFFSET, producerId); buffer.putShort(position + PRODUCER_EPOCH_OFFSET, epoch); buffer.putInt(position + BASE_SEQUENCE_OFFSET, sequence); buffer.putInt(position + RECORDS_COUNT_OFFSET, numRecords); long crc = Crc32C.compute(buffer, ATTRIBUTES_OFFSET, sizeInBytes - ATTRIBUTES_OFFSET); buffer.putInt(position + CRC_OFFSET, (int) crc); buffer.position(position + RECORD_BATCH_OVERHEAD); }
Gets the base timestamp of the batch which is used to calculate the record timestamps from the deltas. @return The base timestamp
java
clients/src/main/java/org/apache/kafka/common/record/DefaultRecordBatch.java
459
[ "buffer", "baseOffset", "lastOffsetDelta", "sizeInBytes", "magic", "compressionType", "timestampType", "baseTimestamp", "maxTimestamp", "producerId", "epoch", "sequence", "isTransactional", "isControlBatch", "isDeleteHorizonSet", "partitionLeaderEpoch", "numRecords" ]
void
true
4
6.88
apache/kafka
31,560
javadoc
false
lowestPriorityChannel
public KafkaChannel lowestPriorityChannel() { KafkaChannel channel = null; if (!closingChannels.isEmpty()) { channel = closingChannels.values().iterator().next(); } else if (idleExpiryManager != null && !idleExpiryManager.lruConnections.isEmpty()) { String channelId = idleExpiryManager.lruConnections.keySet().iterator().next(); channel = channel(channelId); } else if (!channels.isEmpty()) { channel = channels.values().iterator().next(); } return channel; }
Returns the lowest priority channel chosen using the following sequence: 1) If one or more channels are in closing state, return any one of them 2) If idle expiry manager is enabled, return the least recently updated channel 3) Otherwise return any of the channels This method is used to close a channel to accommodate a new channel on the inter-broker listener when broker-wide `max.connections` limit is enabled.
java
clients/src/main/java/org/apache/kafka/common/network/Selector.java
1,026
[]
KafkaChannel
true
5
6.4
apache/kafka
31,560
javadoc
false
get_db_snapshot_state
def get_db_snapshot_state(self, snapshot_id: str) -> str: """ Get the current state of a DB instance snapshot. .. seealso:: - :external+boto3:py:meth:`RDS.Client.describe_db_snapshots` :param snapshot_id: The ID of the target DB instance snapshot :return: Returns the status of the DB snapshot as a string (eg. "available") :raises AirflowNotFoundException: If the DB instance snapshot does not exist. """ try: response = self.conn.describe_db_snapshots(DBSnapshotIdentifier=snapshot_id) except self.conn.exceptions.DBSnapshotNotFoundFault as e: raise AirflowNotFoundException(e) return response["DBSnapshots"][0]["Status"].lower()
Get the current state of a DB instance snapshot. .. seealso:: - :external+boto3:py:meth:`RDS.Client.describe_db_snapshots` :param snapshot_id: The ID of the target DB instance snapshot :return: Returns the status of the DB snapshot as a string (eg. "available") :raises AirflowNotFoundException: If the DB instance snapshot does not exist.
python
providers/amazon/src/airflow/providers/amazon/aws/hooks/rds.py
53
[ "self", "snapshot_id" ]
str
true
1
6.4
apache/airflow
43,597
sphinx
false
getApplicationListeners
protected Collection<ApplicationListener<?>> getApplicationListeners() { synchronized (this.defaultRetriever) { return this.defaultRetriever.getApplicationListeners(); } }
Return a Collection containing all ApplicationListeners. @return a Collection of ApplicationListeners @see org.springframework.context.ApplicationListener
java
spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java
173
[]
true
1
6.08
spring-projects/spring-framework
59,386
javadoc
false
fit_transform
def fit_transform(self, X, y=None, **params): """Fit the model from data in X and transform X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. **params : kwargs Parameters (keyword arguments) and values passed to the fit_transform instance. Returns ------- X_new : ndarray of shape (n_samples, n_components) Transformed values. """ self.fit(X, **params) # no need to use the kernel to transform X, use shortcut expression X_transformed = self.eigenvectors_ * np.sqrt(self.eigenvalues_) if self.fit_inverse_transform: self._fit_inverse_transform(X_transformed, X) return X_transformed
Fit the model from data in X and transform X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. **params : kwargs Parameters (keyword arguments) and values passed to the fit_transform instance. Returns ------- X_new : ndarray of shape (n_samples, n_components) Transformed values.
python
sklearn/decomposition/_kernel_pca.py
455
[ "self", "X", "y" ]
false
2
6.08
scikit-learn/scikit-learn
64,340
numpy
false
doSend
private void doSend(ClientRequest clientRequest, boolean isInternalRequest, long now, AbstractRequest request) { String destination = clientRequest.destination(); RequestHeader header = clientRequest.makeHeader(request.version()); if (log.isDebugEnabled()) { log.debug("Sending {} request with header {} and timeout {} to node {}: {}", clientRequest.apiKey(), header, clientRequest.requestTimeoutMs(), destination, request); } Send send = request.toSend(header); InFlightRequest inFlightRequest = new InFlightRequest( clientRequest, header, isInternalRequest, request, send, now); this.inFlightRequests.add(inFlightRequest); selector.send(new NetworkSend(clientRequest.destination(), send)); }
Queue up the given request for sending. Requests can only be sent out to ready nodes. @param request The request @param now The current timestamp
java
clients/src/main/java/org/apache/kafka/clients/NetworkClient.java
601
[ "clientRequest", "isInternalRequest", "now", "request" ]
void
true
2
7.04
apache/kafka
31,560
javadoc
false
unwrap
public static String unwrap(final String str, final char wrapChar) { if (isEmpty(str) || wrapChar == CharUtils.NUL || str.length() == 1) { return str; } if (str.charAt(0) == wrapChar && str.charAt(str.length() - 1) == wrapChar) { final int startIndex = 0; final int endIndex = str.length() - 1; return str.substring(startIndex + 1, endIndex); } return str; }
Unwraps a given string from a character. <pre> StringUtils.unwrap(null, null) = null StringUtils.unwrap(null, '\0') = null StringUtils.unwrap(null, '1') = null StringUtils.unwrap("a", 'a') = "a" StringUtils.unwrap("aa", 'a') = "" StringUtils.unwrap("\'abc\'", '\'') = "abc" StringUtils.unwrap("AABabcBAA", 'A') = "ABabcBA" StringUtils.unwrap("A", '#') = "A" StringUtils.unwrap("#A", '#') = "#A" StringUtils.unwrap("A#", '#') = "A#" </pre> @param str the String to be unwrapped, can be null. @param wrapChar the character used to unwrap. @return unwrapped String or the original string if it is not quoted properly with the wrapChar. @since 3.6
java
src/main/java/org/apache/commons/lang3/StringUtils.java
8,943
[ "str", "wrapChar" ]
String
true
6
7.76
apache/commons-lang
2,896
javadoc
false
isParenthesizedArrowFunctionExpression
function isParenthesizedArrowFunctionExpression(): Tristate { if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken || token() === SyntaxKind.AsyncKeyword) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } if (token() === SyntaxKind.EqualsGreaterThanToken) { // ERROR RECOVERY TWEAK: // If we see a standalone => try to parse it as an arrow function expression as that's // likely what the user intended to write. return Tristate.True; } // Definitely not a parenthesized arrow function. return Tristate.False; }
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
5,236
[]
true
5
6.88
microsoft/TypeScript
107,154
jsdoc
false
isStereotypeWithNameValue
protected boolean isStereotypeWithNameValue(String annotationType, Set<String> metaAnnotationTypes, Map<String, @Nullable Object> attributes) { boolean isStereotype = metaAnnotationTypes.contains(COMPONENT_ANNOTATION_CLASSNAME) || annotationType.equals("jakarta.inject.Named"); return (isStereotype && attributes.containsKey(MergedAnnotation.VALUE)); }
Check whether the given annotation is a stereotype that is allowed to suggest a component name through its {@code value()} attribute. @param annotationType the name of the annotation class to check @param metaAnnotationTypes the names of meta-annotations on the given annotation @param attributes the map of attributes for the given annotation @return whether the annotation qualifies as a stereotype with component name
java
spring-context/src/main/java/org/springframework/context/annotation/AnnotationBeanNameGenerator.java
217
[ "annotationType", "metaAnnotationTypes", "attributes" ]
true
3
7.6
spring-projects/spring-framework
59,386
javadoc
false
tryAllocate
ByteBuffer tryAllocate(int sizeBytes);
Tries to acquire a ByteBuffer of the specified size @param sizeBytes size required @return a ByteBuffer (which later needs to be release()ed), or null if no memory available. the buffer will be of the exact size requested, even if backed by a larger chunk of memory
java
clients/src/main/java/org/apache/kafka/common/memory/MemoryPool.java
65
[ "sizeBytes" ]
ByteBuffer
true
1
6.32
apache/kafka
31,560
javadoc
false
trimToSize
public void trimToSize() { if (needsAllocArrays()) { return; } Set<E> delegate = delegateOrNull(); if (delegate != null) { Set<E> newDelegate = createHashFloodingResistantDelegate(size()); newDelegate.addAll(delegate); this.table = newDelegate; return; } int size = this.size; if (size < requireEntries().length) { resizeEntries(size); } int minimumTableSize = CompactHashing.tableSize(size); int mask = hashTableMask(); if (minimumTableSize < mask) { // smaller table size will always be less than current mask resizeTable(mask, minimumTableSize, UNSET, UNSET); } }
Ensures that this {@code CompactHashSet} has the smallest representation in memory, given its current size.
java
android/guava/src/com/google/common/collect/CompactHashSet.java
626
[]
void
true
5
6.08
google/guava
51,352
javadoc
false
attributesFor
static @Nullable AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationType) { return attributesFor(metadata, annotationType.getName()); }
Register all relevant annotation post processors in the given registry. @param registry the registry to operate on @param source the configuration source element (already extracted) that this registration was triggered from. May be {@code null}. @return a Set of BeanDefinitionHolders, containing all bean definitions that have actually been registered by this call
java
spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java
289
[ "metadata", "annotationType" ]
AnnotationAttributes
true
1
6.16
spring-projects/spring-framework
59,386
javadoc
false
render_template
def render_template(template: Any, context: MutableMapping[str, Any], *, native: bool) -> Any: """ Render a Jinja2 template with given Airflow context. The default implementation of ``jinja2.Template.render()`` converts the input context into dict eagerly many times, which triggers deprecation messages in our custom context class. This takes the implementation apart and retain the context mapping without resolving instead. :param template: A Jinja2 template to render. :param context: The Airflow task context to render the template with. :param native: If set to *True*, render the template into a native type. A DAG can enable this with ``render_template_as_native_obj=True``. :returns: The render result. """ context = copy.copy(context) env = template.environment if template.globals: context.update((k, v) for k, v in template.globals.items() if k not in context) try: nodes = template.root_render_func(env.context_class(env, context, template.name, template.blocks)) except Exception: env.handle_exception() # Rewrite traceback to point to the template. if native: import jinja2.nativetypes return jinja2.nativetypes.native_concat(nodes) return "".join(nodes)
Render a Jinja2 template with given Airflow context. The default implementation of ``jinja2.Template.render()`` converts the input context into dict eagerly many times, which triggers deprecation messages in our custom context class. This takes the implementation apart and retain the context mapping without resolving instead. :param template: A Jinja2 template to render. :param context: The Airflow task context to render the template with. :param native: If set to *True*, render the template into a native type. A DAG can enable this with ``render_template_as_native_obj=True``. :returns: The render result.
python
airflow-core/src/airflow/utils/helpers.py
235
[ "template", "context", "native" ]
Any
true
3
7.6
apache/airflow
43,597
sphinx
false
setAsText
@Override public void setAsText(@Nullable String text) { if (text == null) { setValue(null); } else { String value = text.trim(); if (this.charsToDelete != null) { value = StringUtils.deleteAny(value, this.charsToDelete); } if (this.emptyAsNull && value.isEmpty()) { setValue(null); } else { setValue(value); } } }
Create a new StringTrimmerEditor. @param charsToDelete a set of characters to delete, in addition to trimming an input String. Useful for deleting unwanted line breaks: for example, "\r\n\f" will delete all new lines and line feeds in a String. @param emptyAsNull {@code true} if an empty String is to be transformed into {@code null}
java
spring-beans/src/main/java/org/springframework/beans/propertyeditors/StringTrimmerEditor.java
65
[ "text" ]
void
true
5
6.88
spring-projects/spring-framework
59,386
javadoc
false