language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
scrapy__scrapy
tests/test_utils_deprecate.py
{ "start": 316, "end": 357 }
class ____(SomeBaseClass): pass
NewName
python
facebook__pyre-check
client/commands/analyze.py
{ "start": 776, "end": 22348 }
class ____: """ Data structure for configuration options the backend analyze command can recognize. Need to keep in sync with `source/command/analyzeCommand.ml` """ base_arguments: backend_arguments.BaseArguments dump_call_graph: Optional[str] = None dump_model_query_results: Optional[str] = None find_missing_flows: Optional[str] = None infer_self_tito: bool = True infer_argument_tito: bool = False maximum_model_source_tree_width: Optional[int] = None maximum_model_sink_tree_width: Optional[int] = None maximum_model_tito_tree_width: Optional[int] = None maximum_tree_depth_after_widening: Optional[int] = None maximum_return_access_path_width: Optional[int] = None maximum_return_access_path_depth_after_widening: Optional[int] = None maximum_tito_collapse_depth: Optional[int] = None maximum_tito_positions: Optional[int] = None maximum_overrides_to_analyze: Optional[int] = None maximum_tito_depth: Optional[int] = None maximum_trace_length: Optional[int] = None no_verify: bool = False verify_dsl: bool = False verify_taint_config_only: bool = False repository_root: Optional[str] = None rule_filter: Optional[Sequence[int]] = None source_filter: Optional[Sequence[str]] = None sink_filter: Optional[Sequence[str]] = None transform_filter: Optional[Sequence[str]] = None save_results_to: Optional[str] = None output_format: Optional[str] = None pyrefly_results: Optional[str] = None strict: bool = False taint_model_paths: Sequence[str] = dataclasses.field(default_factory=list) use_cache: bool = False check_invariants: bool = False limit_entrypoints: bool = False compact_ocaml_heap: bool = False build_cache_only: bool = False saved_state_arguments: command_arguments.PysaSavedStateArguments = ( dataclasses.field(default_factory=command_arguments.PysaSavedStateArguments) ) compute_coverage: bool = False scheduler_policies: Optional[configuration_module.SchedulerPolicies] = None higher_order_call_graph_max_iterations: Optional[int] = None maximum_target_depth: Optional[int] = None # Used for higher order call graphs maximum_parameterized_targets_at_call_site: Optional[int] = ( None # Used for higher order call graphs ) def serialize(self) -> Dict[str, Any]: dump_call_graph = self.dump_call_graph dump_model_query_results = self.dump_model_query_results find_missing_flows = self.find_missing_flows maximum_model_source_tree_width = self.maximum_model_source_tree_width maximum_model_sink_tree_width = self.maximum_model_sink_tree_width maximum_model_tito_tree_width = self.maximum_model_tito_tree_width maximum_tree_depth_after_widening = self.maximum_tree_depth_after_widening maximum_return_access_path_width = self.maximum_return_access_path_width maximum_return_access_path_depth_after_widening = ( self.maximum_return_access_path_depth_after_widening ) maximum_tito_collapse_depth = self.maximum_tito_collapse_depth maximum_tito_positions = self.maximum_tito_positions maximum_overrides_to_analyze = self.maximum_overrides_to_analyze maximum_tito_depth = self.maximum_tito_depth maximum_trace_length = self.maximum_trace_length repository_root = self.repository_root rule_filter = self.rule_filter source_filter = self.source_filter sink_filter = self.sink_filter transform_filter = self.transform_filter save_results_to = self.save_results_to output_format = self.output_format pyrefly_results = self.pyrefly_results scheduler_policies = self.scheduler_policies higher_order_call_graph_max_iterations = ( self.higher_order_call_graph_max_iterations ) maximum_target_depth = self.maximum_target_depth maximum_parameterized_targets_at_call_site = ( self.maximum_parameterized_targets_at_call_site ) return { **self.base_arguments.serialize(), **({} if dump_call_graph is None else {"dump_call_graph": dump_call_graph}), **( {} if dump_model_query_results is None else {"dump_model_query_results": dump_model_query_results} ), **( {} if find_missing_flows is None else {"find_missing_flows": find_missing_flows} ), "infer_self_tito": self.infer_self_tito, "infer_argument_tito": self.infer_argument_tito, **( {} if maximum_model_source_tree_width is None else { "maximum_model_source_tree_width": maximum_model_source_tree_width } ), **( {} if maximum_model_sink_tree_width is None else {"maximum_model_sink_tree_width": maximum_model_sink_tree_width} ), **( {} if maximum_model_tito_tree_width is None else {"maximum_model_tito_tree_width": maximum_model_tito_tree_width} ), **( {} if maximum_tree_depth_after_widening is None else { "maximum_tree_depth_after_widening": maximum_tree_depth_after_widening } ), **( {} if maximum_return_access_path_width is None else { "maximum_return_access_path_width": maximum_return_access_path_width } ), **( {} if maximum_return_access_path_depth_after_widening is None else { "maximum_return_access_path_depth_after_widening": maximum_return_access_path_depth_after_widening } ), **( {} if maximum_tito_collapse_depth is None else {"maximum_tito_collapse_depth": maximum_tito_collapse_depth} ), **( {} if maximum_tito_positions is None else {"maximum_tito_positions": maximum_tito_positions} ), **( {} if maximum_overrides_to_analyze is None else {"maximum_overrides_to_analyze": maximum_overrides_to_analyze} ), **( {} if maximum_tito_depth is None else {"maximum_tito_depth": maximum_tito_depth} ), **( {} if maximum_trace_length is None else {"maximum_trace_length": maximum_trace_length} ), "no_verify": self.no_verify, "verify_dsl": self.verify_dsl, "verify_taint_config_only": self.verify_taint_config_only, **({} if repository_root is None else {"repository_root": repository_root}), **({} if rule_filter is None else {"rule_filter": rule_filter}), **({} if source_filter is None else {"source_filter": source_filter}), **({} if sink_filter is None else {"sink_filter": sink_filter}), **( {} if transform_filter is None else {"transform_filter": transform_filter} ), **({} if save_results_to is None else {"save_results_to": save_results_to}), **({} if output_format is None else {"output_format": output_format}), **({} if pyrefly_results is None else {"pyrefly_results": pyrefly_results}), "strict": self.strict, "taint_model_paths": self.taint_model_paths, "use_cache": self.use_cache, "build_cache_only": self.build_cache_only, "check_invariants": self.check_invariants, "limit_entrypoints": self.limit_entrypoints, "compact_ocaml_heap": self.compact_ocaml_heap, "saved_state": self.saved_state_arguments.serialize(), "compute_coverage": self.compute_coverage, **( {"scheduler_policies": scheduler_policies.to_json()} if scheduler_policies is not None else {} ), **( {} if higher_order_call_graph_max_iterations is None else { "higher_order_call_graph_max_iterations": higher_order_call_graph_max_iterations } ), **( {} if maximum_target_depth is None else {"maximum_target_depth": maximum_target_depth} ), **( {} if maximum_parameterized_targets_at_call_site is None else { "maximum_parameterized_targets_at_call_site": maximum_parameterized_targets_at_call_site } ), } def create_analyze_arguments( configuration: frontend_configuration.Base, analyze_arguments: command_arguments.AnalyzeArguments, ) -> Arguments: """ Translate client configurations to backend analyze configurations. This API is not pure since it needs to access filesystem to filter out nonexistent directories. It is idempotent though, since it does not alter any filesystem state. """ log_directory = configuration.get_log_directory() profiling_output = ( backend_arguments.get_profiling_log_path(log_directory) if analyze_arguments.enable_profiling else None ) memory_profiling_output = ( backend_arguments.get_profiling_log_path(log_directory) if analyze_arguments.enable_memory_profiling else None ) logger = configuration.get_remote_logger() remote_logging = ( backend_arguments.RemoteLogging( logger=logger, identifier=analyze_arguments.log_identifier or "" ) if logger is not None else None ) find_missing_flows = analyze_arguments.find_missing_flows rule = analyze_arguments.rule source = analyze_arguments.source sink = analyze_arguments.sink transform = analyze_arguments.transform taint_models_path = analyze_arguments.taint_models_path output_format = analyze_arguments.output_format scheduler_policies_path = analyze_arguments.scheduler_policies_path if len(taint_models_path) == 0: taint_models_path = configuration.get_taint_models_path() repository_root = analyze_arguments.repository_root if repository_root is not None: repository_root = str(Path(repository_root).resolve(strict=False)) pyrefly_results = analyze_arguments.pyrefly_results if pyrefly_results is None: source_paths = backend_arguments.get_source_path_for_check( configuration, kill_buck_after_build=analyze_arguments.kill_buck_after_build, number_of_buck_threads=analyze_arguments.number_of_buck_threads, ) base_arguments = backend_arguments.BaseArguments( log_path=str(log_directory), global_root=str(configuration.get_global_root()), checked_directory_allowlist=backend_arguments.get_checked_directory_allowlist( configuration, source_paths ), checked_directory_blocklist=configuration.get_ignore_all_errors(), debug=analyze_arguments.debug, excludes=configuration.get_excludes(), extensions=configuration.get_valid_extension_suffixes(), relative_local_root=configuration.get_relative_local_root(), memory_profiling_output=memory_profiling_output, number_of_workers=configuration.get_number_of_workers(), parallel=not analyze_arguments.sequential, profiling_output=profiling_output, python_version=configuration.get_python_version(), shared_memory=configuration.get_shared_memory(), remote_logging=remote_logging, search_paths=configuration.get_existent_search_paths(), source_paths=source_paths, ) else: # When a pyrefly result directory is provided, ignore most configuration options. base_arguments = backend_arguments.BaseArguments( log_path=str(log_directory), global_root=str(configuration.get_global_root()), checked_directory_allowlist=[], checked_directory_blocklist=[], debug=analyze_arguments.debug, excludes=[], extensions=[], relative_local_root=None, memory_profiling_output=memory_profiling_output, number_of_workers=configuration.get_number_of_workers(), parallel=not analyze_arguments.sequential, profiling_output=profiling_output, python_version=configuration.get_python_version(), shared_memory=configuration.get_shared_memory(), remote_logging=remote_logging, search_paths=[], source_paths=backend_arguments.SimpleSourcePath(elements=[]), ) return Arguments( base_arguments=base_arguments, dump_call_graph=analyze_arguments.dump_call_graph, dump_model_query_results=analyze_arguments.dump_model_query_results, find_missing_flows=( str(find_missing_flows.value) if find_missing_flows is not None else None ), infer_self_tito=analyze_arguments.infer_self_tito, infer_argument_tito=analyze_arguments.infer_argument_tito, maximum_model_source_tree_width=analyze_arguments.maximum_model_source_tree_width, maximum_model_sink_tree_width=analyze_arguments.maximum_model_sink_tree_width, maximum_model_tito_tree_width=analyze_arguments.maximum_model_tito_tree_width, maximum_tree_depth_after_widening=analyze_arguments.maximum_tree_depth_after_widening, maximum_return_access_path_width=analyze_arguments.maximum_return_access_path_width, maximum_return_access_path_depth_after_widening=analyze_arguments.maximum_return_access_path_depth_after_widening, maximum_tito_collapse_depth=analyze_arguments.maximum_tito_collapse_depth, maximum_tito_positions=analyze_arguments.maximum_tito_positions, maximum_overrides_to_analyze=analyze_arguments.maximum_overrides_to_analyze, maximum_tito_depth=analyze_arguments.maximum_tito_depth, maximum_trace_length=analyze_arguments.maximum_trace_length, no_verify=analyze_arguments.no_verify, verify_dsl=analyze_arguments.verify_dsl, verify_taint_config_only=analyze_arguments.verify_taint_config_only, repository_root=repository_root, rule_filter=None if len(rule) == 0 else rule, source_filter=None if len(source) == 0 else source, sink_filter=None if len(sink) == 0 else sink, transform_filter=None if len(transform) == 0 else transform, save_results_to=analyze_arguments.save_results_to, output_format=str(output_format.value) if output_format is not None else None, pyrefly_results=pyrefly_results, strict=configuration.is_strict(), taint_model_paths=taint_models_path, use_cache=analyze_arguments.use_cache, build_cache_only=analyze_arguments.build_cache_only, check_invariants=analyze_arguments.check_invariants, limit_entrypoints=analyze_arguments.limit_entrypoints, compact_ocaml_heap=analyze_arguments.compact_ocaml_heap, saved_state_arguments=analyze_arguments.saved_state_arguments, compute_coverage=analyze_arguments.compute_coverage, scheduler_policies=( configuration_module.SchedulerPolicies.from_path(scheduler_policies_path) if scheduler_policies_path is not None else None ), higher_order_call_graph_max_iterations=analyze_arguments.higher_order_call_graph_max_iterations, maximum_target_depth=analyze_arguments.maximum_target_depth, maximum_parameterized_targets_at_call_site=analyze_arguments.maximum_parameterized_targets_at_call_site, ) @contextlib.contextmanager def create_analyze_arguments_and_cleanup( configuration: frontend_configuration.Base, analyze_arguments: command_arguments.AnalyzeArguments, ) -> Iterator[Arguments]: arguments = create_analyze_arguments(configuration, analyze_arguments) try: yield arguments finally: # It is safe to clean up source paths after analyze command since # any created artifact directory won't be reused by other commands. arguments.base_arguments.source_paths.cleanup() def parse_taint_configuration_errors( response: str, ) -> List[error_module.TaintConfigurationError]: response_json = json.loads(response) errors = response_json.get("errors", []) return [error_module.TaintConfigurationError.from_json(error) for error in errors] def parse_model_validation_errors( response: str, ) -> List[error_module.ModelVerificationError]: response_json = json.loads(response) return validate_models.parse_validation_errors(response_json) def _run_analyze_command( command: Sequence[str], output: str, forward_stdout: bool, environment: Optional[Dict[str, str]], ) -> commands.ExitCode: with backend_arguments.backend_log_file(prefix="pyre_analyze") as log_file: with start.background_logging(Path(log_file.name)): # lint-ignore: NoUnsafeExecRule result = subprocess.run( command, stdout=subprocess.PIPE, stderr=log_file.file, universal_newlines=True, errors="replace", env=environment, ) return_code = result.returncode # Give time for the log file to be flushed. # Without this, we sometimes miss the last few lines of the log. time.sleep(0.01) # Interpretation of the return code needs to be kept in sync with # `command/analyzeCommand.ml`. if return_code == 0: if forward_stdout: log.stdout.write(result.stdout) return commands.ExitCode.SUCCESS elif return_code == 2: LOG.error("Pyre encountered a failure within buck.") return commands.ExitCode.BUCK_INTERNAL_ERROR elif return_code == 3: LOG.error("Pyre encountered an error when building the buck targets.") return commands.ExitCode.BUCK_USER_ERROR elif return_code == 10: error_module.print_errors( parse_taint_configuration_errors(result.stdout), output=output, error_kind="taint configuration", ) return commands.ExitCode.TAINT_CONFIGURATION_ERROR elif return_code == 11: error_module.print_errors( parse_model_validation_errors(result.stdout), output=output, error_kind="model verification", ) LOG.warning("Hint: use --no-verify to silence these errors") return commands.ExitCode.MODEL_VERIFICATION_ERROR elif return_code == 12: # error is printed in the binary. return commands.ExitCode.PYREFLY_FILE_FORMAT_ERROR else: LOG.error(f"Pyre exited with non-zero return code: {return_code}.") return commands.ExitCode.FAILURE def run( configuration: frontend_configuration.Base, analyze_arguments: command_arguments.AnalyzeArguments, ) -> commands.ExitCode: start_command = configuration.get_server_start_command(download_if_needed=True) if start_command is None: raise configuration_module.InvalidConfiguration( "Cannot locate a Pyre binary to run." ) LOG.info(f"Pyre binary is located at `{start_command.get_pyre_binary_location()}`") save_results_to = analyze_arguments.save_results_to if save_results_to is not None: Path(save_results_to).mkdir(parents=True, exist_ok=True) with create_analyze_arguments_and_cleanup( configuration, analyze_arguments ) as arguments: with backend_arguments.temporary_argument_file(arguments) as argument_file_path: analyze_command = [ str(start_command.get_pyre_binary_location()), "analyze", str(argument_file_path), ] environment = None if analyze_arguments.check_invariants: # We need to pass this specific argument as an environment variable, # because it is needed during the global initialization. environment = dict(os.environ) environment["PYSA_CHECK_INVARIANTS"] = "1" return _run_analyze_command( command=analyze_command, environment=environment, output=analyze_arguments.output, forward_stdout=(save_results_to is None), )
Arguments
python
dagster-io__dagster
python_modules/automation/automation/parse_dataproc_configs.py
{ "start": 4095, "end": 4681 }
class ____(namedtuple("_ParsedConfig", "name configs enums")): def __new__(cls, name, configs, enums): return super().__new__(cls, name, configs, enums) def write_configs(self, base_path): configs_filename = f"configs_{self.name}.py" print("Writing", configs_filename) # noqa: T201 with open(os.path.join(base_path, configs_filename), "wb") as f: f.write(self.configs) enums_filename = f"types_{self.name}.py" with open(os.path.join(base_path, enums_filename), "wb") as f: f.write(self.enums)
ParsedConfig
python
huggingface__transformers
src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py
{ "start": 17452, "end": 40740 }
class ____(nn.Module): """ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`. A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective) ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4, and is why Mamba is called **selective** state spaces) The are a few differences between this and Mamba2Mixer: - The variable use_precomputed_states is slightly different due to the hybrid cache structure - There's a few non-obvious bugs fixed with batching in the slow path that exist in main - Some extra variables that our layer doesn't need have been removed - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged """ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int): super().__init__() self.num_heads = config.mamba_n_heads self.hidden_size = config.hidden_size self.ssm_state_size = config.mamba_d_state self.conv_kernel_size = config.mamba_d_conv self.intermediate_size = int(config.mamba_expand * self.hidden_size) self.layer_idx = layer_idx self.use_conv_bias = config.mamba_conv_bias self.activation = config.hidden_act self.act = ACT2FN[config.hidden_act] self.use_bias = config.mamba_proj_bias self.layer_norm_epsilon = config.rms_norm_eps self.n_groups = config.mamba_n_groups self.head_dim = config.mamba_d_head self.chunk_size = config.mamba_chunk_size # FIXME: self.time_step_limit = (0.0, float("inf")) self.time_step_min = 0.001 self.time_step_max = 0.1 self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size self.conv1d = nn.Conv1d( in_channels=self.conv_dim, out_channels=self.conv_dim, bias=config.mamba_conv_bias, kernel_size=self.conv_kernel_size, groups=self.conv_dim, padding=self.conv_kernel_size - 1, ) # projection of the input hidden states projection_size = self.intermediate_size + self.conv_dim + self.num_heads self.in_proj = nn.Linear( self.hidden_size, projection_size, bias=self.use_bias, ) # selective projection used to make dt, B and C input dependent # time step projection (discretization) # instantiate once and copy inv_dt in init_weights of PretrainedModel self.dt_bias = nn.Parameter(torch.ones(self.num_heads)) # S4D real initialization. These are not discretized! # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded A = torch.arange(1, self.num_heads + 1) self.A_log = nn.Parameter(torch.log(A)) self.norm = GraniteMoeHybridRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon) self.D = nn.Parameter(torch.ones(self.num_heads)) self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias) if not is_fast_path_available: logger.warning_once( "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`" " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and" " https://github.com/Dao-AILab/causal-conv1d" ) else: logger.warning_once("The fast path for GraniteMoeHybrid will be used when running the model on a GPU") def cuda_kernels_forward( self, hidden_states: torch.Tensor, cache_params: Optional[HybridMambaAttentionDynamicCache] = None, cache_position: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, seq_idx: Optional[torch.IntTensor] = None, ): # 1. Gated MLP's linear projection hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask) projected_states = self.in_proj(hidden_states) # Set up dimensions for reshapes later batch_size, seq_len, _ = hidden_states.shape groups_time_state_size = self.n_groups * self.ssm_state_size use_precomputed_states = ( cache_params is not None and cache_params.has_previous_state and seq_len == 1 and cache_params.conv_states[self.layer_idx].shape[0] == cache_params.ssm_states[self.layer_idx].shape[0] == batch_size and cache_position is not None and cache_position[0] > 0 ) # getting projected states from cache if it exists if use_precomputed_states: gate, hidden_states_B_C, dt = projected_states.squeeze(1).split( [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 ) # 2. Convolution sequence transformation hidden_states_B_C = causal_conv1d_update( hidden_states_B_C, cache_params.conv_states[self.layer_idx], self.conv1d.weight.squeeze(1), self.conv1d.bias, self.activation, ) hidden_states, B, C = torch.split( hidden_states_B_C, [self.intermediate_size, groups_time_state_size, groups_time_state_size], dim=-1, ) # 3. SSM transformation A = -torch.exp(self.A_log.float()) # (nheads,) A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32) dt = dt[:, :, None].expand(-1, -1, self.head_dim) dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim) D = self.D[:, None, ...].expand(-1, self.head_dim) B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups) C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups) hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim) hidden_states = selective_state_update( cache_params.ssm_states[self.layer_idx], hidden_states_reshaped, dt, A, B, C, D, z=None, dt_bias=dt_bias, dt_softplus=True, ) hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim) hidden_states = self.norm(hidden_states, gate) # 4. Final linear projection out = self.out_proj(hidden_states)[:, None, ...] # Fused calculations or step by step if no initialized cache is found else: A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size) dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit} # 2-4. Fused kernel for conv1d, SSM, and the final projection if self.training and cache_params is None: out = mamba_split_conv1d_scan_combined( projected_states, self.conv1d.weight.squeeze(1), self.conv1d.bias, self.dt_bias, A, D=self.D, chunk_size=self.chunk_size, seq_idx=seq_idx, activation=self.activation, rmsnorm_weight=self.norm.weight, rmsnorm_eps=self.norm.variance_epsilon, outproj_weight=self.out_proj.weight, outproj_bias=self.out_proj.bias, headdim=self.head_dim, ngroups=self.n_groups, norm_before_gate=False, return_final_states=False, **dt_limit_kwargs, ) else: gate, hidden_states_B_C, dt = projected_states.split( [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 ) # 2. Convolution sequence transformation # Init cache if cache_params is not None: # storing the states # If we just take xBC[:, :, -self.d_conv :], it will error if seqlen < self.d_conv # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise. hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2) conv_states = nn.functional.pad( hidden_states_B_C_transposed, (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0), ) cache_params.conv_states[self.layer_idx].copy_(conv_states) if self.activation not in ["silu", "swish"]: hidden_states_B_C = self.act( self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2) ) else: hidden_states_B_C = causal_conv1d_fn( x=hidden_states_B_C.transpose(1, 2), weight=self.conv1d.weight.squeeze(1), bias=self.conv1d.bias, activation=self.activation, seq_idx=seq_idx, ).transpose(1, 2) hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask) hidden_states, B, C = torch.split( hidden_states_B_C, [self.intermediate_size, groups_time_state_size, groups_time_state_size], dim=-1, ) # 3. SSM transformation scan_output, ssm_state = mamba_chunk_scan_combined( hidden_states.view(batch_size, seq_len, -1, self.head_dim), dt, A, B.view(batch_size, seq_len, self.n_groups, -1), C.view(batch_size, seq_len, self.n_groups, -1), chunk_size=self.chunk_size, D=self.D, z=None, seq_idx=seq_idx, return_final_states=True, dt_bias=self.dt_bias, dt_softplus=True, **dt_limit_kwargs, ) # Init cache if ssm_state is not None and cache_params is not None: cache_params.ssm_states[self.layer_idx].copy_(ssm_state) scan_output = scan_output.view(batch_size, seq_len, -1) # Multiply "gate" branch and apply extra normalization layer scan_output = self.norm(scan_output, gate) # 4. Final linear projection out = self.out_proj(scan_output) return out # fmt: off def torch_forward( self, input_states, cache_params: Optional[HybridMambaAttentionDynamicCache] = None, cache_position: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, ): batch_size, seq_len, _ = input_states.shape dtype = input_states.dtype # 1. Gated MLP's linear projection input_states = apply_mask_to_padding_states(input_states, attention_mask) projected_states = self.in_proj(input_states) gate, hidden_states_B_C, dt = projected_states.split( [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 ) use_precomputed_states = ( cache_params is not None and cache_params.has_previous_state and seq_len == 1 and cache_params.conv_states[self.layer_idx].shape[0] == cache_params.ssm_states[self.layer_idx].shape[0] == batch_size and cache_position is not None and cache_position[0] > 0 ) # 2. Convolution sequence transformation if use_precomputed_states: cache_params.conv_states[self.layer_idx] = cache_params.conv_states[self.layer_idx].roll(shifts=-1, dims=-1) cache_params.conv_states[self.layer_idx][:, :, -1] = hidden_states_B_C[:, 0, :].to(cache_params.conv_states[self.layer_idx].device) # We need to guarantee that anything regarding the cache is on the same device conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device) hidden_states_B_C = torch.sum( conv_states * self.conv1d.weight.squeeze(1), dim=-1 ) if self.use_conv_bias: hidden_states_B_C = hidden_states_B_C + self.conv1d.bias hidden_states_B_C = self.act(hidden_states_B_C) else: # Init cache if cache_params is not None: hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2) conv_states = nn.functional.pad( hidden_states_B_C_transposed, (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0) ) cache_params.conv_states[self.layer_idx].copy_(conv_states) hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)) hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask) hidden_states, B, C = torch.split( hidden_states_B_C, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1 ) # 3. SSM transformation A = -torch.exp(self.A_log.float()) # [num_heads] if use_precomputed_states: # We need to guarantee that anything regarding the cache is on the same device cache_device = cache_params.ssm_states[self.layer_idx].device # Note: there is no need to pad parameter matrices here, as there is just one new token # for batched generation dt = dt[:, 0, :][:, None, ...] dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim) # [num_heads] -> [num_heads, head_dim] dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim) dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype)) dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1]) A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32) # [bsz, num_heads, head_dim, state_size] dA = (torch.exp(dt[..., None] * A)).to(device=cache_device) # Discretize B # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] -> # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size] B = B.reshape(batch_size, self.n_groups, -1)[..., None, :] B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous() B = B.reshape(batch_size, -1, B.shape[-1]) # [bsz, num_heads, head_dim, state_size] dB = dt[..., None] * B[..., None, :] # Discretize x into dB # [bsz, intermediate_size] -> [bsz, num_heads, head_dim] hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim) dBx = (dB * hidden_states[..., None]).to(device=cache_device) # State calculation cache_params.ssm_states[self.layer_idx].copy_( cache_params.ssm_states[self.layer_idx] * dA + dBx ) # Subsequent output # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size] C = C.reshape(batch_size, self.n_groups, -1)[..., None, :] C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous() C = C.reshape(batch_size, -1, C.shape[-1]) # [bsz, num_heads, head_dim] ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n] # Reshape ssm_states to merge the first two dimensions ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n] C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1] y = torch.bmm(ssm_states_reshaped, C_reshaped) y = y.view(batch_size, self.num_heads, self.head_dim) # D skip connection # [num_heads] -> [num_heads, head_dim] D = self.D[..., None].expand(self.D.shape[0], self.head_dim) y = (y + hidden_states * D).to(y.dtype) # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size] y = y.reshape(batch_size, -1)[:, None, ...] else: # begin ssd naive implementation without einsums dt = nn.functional.softplus(dt + self.dt_bias) dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1]) hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float() B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float() C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float() B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads) C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads) pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size) # Discretize x and A hidden_states = hidden_states * dt[..., None] A = A.to(hidden_states.dtype) * dt # Rearrange into blocks/chunks hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)] # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size] A = A.permute(0, 3, 1, 2) A_cumsum = torch.cumsum(A, dim=-1) # 1. Compute the output for each intra-chunk (diagonal blocks) # This is the analog of a causal mask L = torch.exp(segment_sum(A)) # Contraction of C and B to get G (attention-weights like) G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n) G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h) # Compute M, equivalent to applying attention mask to weights M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None] M = M_intermediate.sum(dim=-1) # Compute Y_diag (apply to values) Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3) # 2. Compute the state for each intra-chunk # (right term of low-rank factorization of off-diagonal blocks; B terms) decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum) B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None] states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2) # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries # (middle term of factorization of off-diag blocks; A terms) if use_precomputed_states: previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device) else: previous_states = torch.zeros_like(states[:, :1]) states = torch.cat([previous_states, states], dim=1) decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0)))) decay_chunk = decay_chunk.transpose(1, 3) new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1) states, ssm_state = new_states[:, :-1], new_states[:, -1] # 4. Compute state -> output conversion per chunk # (left term of low-rank factorization of off-diagonal blocks; C terms) state_decay_out = torch.exp(A_cumsum) C_times_states = (C[..., None, :] * states[:, :, None, ...]) state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1) Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None]) # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks) y = Y_diag + Y_off # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim] y = y.reshape(batch_size, -1, self.num_heads, self.head_dim) y = y + D_residual # Cutting off padded chunks if pad_size > 0: y = y[:, :seq_len, :, :] y = y.reshape(batch_size, seq_len, -1) # Init cache if ssm_state is not None and cache_params is not None: cache_params.ssm_states[self.layer_idx].copy_(ssm_state) scan_output = self.norm(y, gate) # end ssd naive # 4. Final linear projection contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size] return contextualized_states # fmt: on def forward( self, hidden_states, cache_params: Optional[HybridMambaAttentionDynamicCache] = None, cache_position: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, seq_idx: Optional[torch.IntTensor] = None, **kwargs, ): if is_fast_path_available and "cuda" in self.in_proj.weight.device.type: return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, seq_idx) if seq_idx is not None: raise NotImplementedError( "`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`" ) dtype = hidden_states.dtype if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1: # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66 hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype) return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
GraniteMoeHybridMambaLayer
python
getsentry__sentry
src/sentry/tagstore/snuba/backend.py
{ "start": 4104, "end": 4185 }
class ____(TypedDict, total=False): turbo: bool sample: int
_OptimizeKwargs
python
mahmoud__glom
glom/core.py
{ "start": 46498, "end": 47409 }
class ____: """Name a part of a spec and refer to it elsewhere in the same spec, useful for trees and other self-similar data structures. Args: name (str): The name of the spec to reference. subspec: Pass a spec to name it *name*, or leave unset to refer to an already-named spec. """ def __init__(self, name, subspec=_MISSING): self.name, self.subspec = name, subspec def glomit(self, target, scope): subspec = self.subspec scope_key = (Ref, self.name) if subspec is _MISSING: subspec = scope[scope_key] else: scope[scope_key] = subspec return scope[glom](target, subspec, scope) def __repr__(self): if self.subspec is _MISSING: args = bbrepr(self.name) else: args = bbrepr((self.name, self.subspec))[1:-1] return "Ref(" + args + ")"
Ref
python
django__django
tests/utils_tests/test_deconstruct.py
{ "start": 643, "end": 731 }
class ____(DeconstructibleInvalidPathClass): pass
DeconstructibleInvalidPathChildClass
python
coleifer__peewee
tests/model_sql.py
{ "start": 45746, "end": 46796 }
class ____(BaseTestCase): database = SqliteDatabase(None) def test_model_index(self): class Article(Model): name = TextField() timestamp = TimestampField() status = IntegerField() flags = IntegerField() aidx = ModelIndex(Article, (Article.name, Article.timestamp),) self.assertSQL(aidx, ( 'CREATE INDEX IF NOT EXISTS "article_name_timestamp" ON "article" ' '("name", "timestamp")'), []) aidx = aidx.where(Article.status == 1) self.assertSQL(aidx, ( 'CREATE INDEX IF NOT EXISTS "article_name_timestamp" ON "article" ' '("name", "timestamp") ' 'WHERE ("status" = ?)'), [1]) aidx = ModelIndex(Article, (Article.timestamp.desc(), Article.flags.bin_and(4)), unique=True) self.assertSQL(aidx, ( 'CREATE UNIQUE INDEX IF NOT EXISTS "article_timestamp" ' 'ON "article" ("timestamp" DESC, ("flags" & ?))'), [4])
TestModelIndex
python
google__jax
tests/lax_test.py
{ "start": 213870, "end": 215524 }
class ____(jtu.JaxTestCase): def test_int_dtype_for_dim(self): self.assertEqual(lax_utils.int_dtype_for_dim(10, signed=True), np.int32) self.assertEqual(lax_utils.int_dtype_for_dim(10, signed=False), np.uint32) self.assertEqual( lax_utils.int_dtype_for_dim(np.iinfo(np.int32).max, signed=True), np.int32, ) self.assertEqual( lax_utils.int_dtype_for_dim(np.iinfo(np.int32).max + 1, signed=True), np.int64, ) self.assertEqual( lax_utils.int_dtype_for_dim(np.iinfo(np.uint32).max, signed=False), np.uint32, ) self.assertEqual( lax_utils.int_dtype_for_dim(np.iinfo(np.uint32).max + 1, signed=False), np.uint64, ) def test_int_dtype_for_shape(self): self.assertEqual( lax_utils.int_dtype_for_shape([10, 20], signed=True), np.int32 ) self.assertEqual( lax_utils.int_dtype_for_shape([10, 20], signed=False), np.uint32 ) self.assertEqual( lax_utils.int_dtype_for_shape( [10, np.iinfo(np.int32).max], signed=True ), np.int32, ) self.assertEqual( lax_utils.int_dtype_for_shape( [np.iinfo(np.int32).max + 1, 20], signed=True ), np.int64, ) self.assertEqual( lax_utils.int_dtype_for_shape( [10, np.iinfo(np.uint32).max], signed=False ), np.uint32, ) self.assertEqual( lax_utils.int_dtype_for_shape( [np.iinfo(np.uint32).max + 1, 20], signed=False ), np.uint64, ) if __name__ == '__main__': absltest.main(testLoader=jtu.JaxTestLoader())
LaxUtilsTest
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/connectors/test_callback_connector.py
{ "start": 12489, "end": 12650 }
class ____(Callback): @property def state_key(self): return "unique_key_1" def state_dict(self): return {"state": 1}
StatefulCallback1
python
rapidsai__cudf
python/cudf/cudf/core/groupby/groupby.py
{ "start": 114906, "end": 115401 }
class ____: def __init__( self, key=None, level=None, freq=None, closed=None, label=None ): if key is not None and level is not None: raise ValueError("Grouper cannot specify both key and level") if (key, level) == (None, None) and not freq: raise ValueError("Grouper must specify either key or level") self.key = key self.level = level self.freq = freq self.closed = closed self.label = label
Grouper
python
realpython__materials
python-unittest/test_prime_v2.py
{ "start": 49, "end": 787 }
class ____(unittest.TestCase): def test_prime_number(self): self.assertTrue(is_prime(17)) def test_non_prime_number(self): self.assertFalse(is_prime(10)) def test_invalid_type_float(self): with self.assertRaises(TypeError): is_prime(4.5) def test_invalid_type_str(self): with self.assertRaises(TypeError): is_prime("5") def test_zero_and_one(self): with self.assertRaises(ValueError): is_prime(0) with self.assertRaises(ValueError): is_prime(1) def test_negative_number(self): with self.assertRaises(ValueError): is_prime(-1) if __name__ == "__main__": unittest.main(verbosity=2)
TestIsPrime
python
realpython__materials
arcade-platformer/arcade_platformer/arcade_platformer.py
{ "start": 374, "end": 1689 }
class ____(arcade.AnimatedWalkingSprite): """An enemy sprite with basic walking movement""" def __init__(self, pos_x: int, pos_y: int) -> None: super().__init__(center_x=pos_x, center_y=pos_y) # Where are the player images stored? texture_path = ASSETS_PATH / "images" / "enemies" # Setup the appropriate textures walking_texture_path = [ texture_path / "slimePurple.png", texture_path / "slimePurple_move.png", ] standing_texture_path = texture_path / "slimePurple.png" # Load them all now self.walk_left_textures = [ arcade.load_texture(texture) for texture in walking_texture_path ] self.walk_right_textures = [ arcade.load_texture(texture, mirrored=True) for texture in walking_texture_path ] self.stand_left_textures = [ arcade.load_texture(standing_texture_path, mirrored=True) ] self.stand_right_textures = [ arcade.load_texture(standing_texture_path) ] # Set the enemy defaults self.state = arcade.FACE_LEFT self.change_x = -game.PLAYER_MOVE_SPEED // 2 # Set the initial texture self.texture = self.stand_right_textures[0] # Title view
Enemy
python
pytorch__pytorch
.github/scripts/test_check_labels.py
{ "start": 1463, "end": 5241 }
class ____(TestCase): @mock.patch("trymerge.gh_graphql", side_effect=mocked_gh_graphql) @mock.patch("trymerge.GitHubPR.get_comments", return_value=[mock_get_comments()[0]]) @mock.patch("check_labels.gh_post_pr_comment") def test_correctly_add_label_err_comment( self, mock_gh_post_pr_comment: Any, mock_get_comments: Any, mock_gh_grphql: Any ) -> None: "Test add label err comment when similar comments don't exist." pr = GitHubPR("pytorch", "pytorch", 75095) add_label_err_comment(pr) mock_gh_post_pr_comment.assert_called_once() @mock.patch("trymerge.gh_graphql", side_effect=mocked_gh_graphql) @mock.patch("trymerge.GitHubPR.get_comments", return_value=[mock_get_comments()[1]]) @mock.patch("check_labels.gh_post_pr_comment") def test_not_add_label_err_comment( self, mock_gh_post_pr_comment: Any, mock_get_comments: Any, mock_gh_grphql: Any ) -> None: "Test not add label err comment when similar comments exist." pr = GitHubPR("pytorch", "pytorch", 75095) add_label_err_comment(pr) mock_gh_post_pr_comment.assert_not_called() @mock.patch("trymerge.gh_graphql", side_effect=mocked_gh_graphql) @mock.patch("trymerge.GitHubPR.get_comments", return_value=mock_get_comments()) @mock.patch("check_labels.gh_delete_comment") def test_correctly_delete_all_label_err_comments( self, mock_gh_delete_comment: Any, mock_get_comments: Any, mock_gh_grphql: Any ) -> None: "Test only delete label err comment." pr = GitHubPR("pytorch", "pytorch", 75095) delete_all_label_err_comments(pr) mock_gh_delete_comment.assert_called_once_with("pytorch", "pytorch", 2) @mock.patch("trymerge.gh_get_pr_info", return_value=mock_gh_get_info()) @mock.patch("check_labels.parse_args", return_value=mock_parse_args()) @mock.patch("check_labels.has_required_labels", return_value=False) @mock.patch( "check_labels.delete_all_label_err_comments", side_effect=mock_delete_all_label_err_comments, ) @mock.patch( "check_labels.add_label_err_comment", side_effect=mock_add_label_err_comment ) def test_ci_comments_and_exit0_without_required_labels( self, mock_add_label_err_comment: Any, mock_delete_all_label_err_comments: Any, mock_has_required_labels: Any, mock_parse_args: Any, mock_gh_get_info: Any, ) -> None: with self.assertRaises(SystemExit) as sys_exit: check_labels_main() self.assertEqual(str(sys_exit.exception), "0") mock_add_label_err_comment.assert_called_once() mock_delete_all_label_err_comments.assert_not_called() @mock.patch("trymerge.gh_get_pr_info", return_value=mock_gh_get_info()) @mock.patch("check_labels.parse_args", return_value=mock_parse_args()) @mock.patch("check_labels.has_required_labels", return_value=True) @mock.patch( "check_labels.delete_all_label_err_comments", side_effect=mock_delete_all_label_err_comments, ) @mock.patch( "check_labels.add_label_err_comment", side_effect=mock_add_label_err_comment ) def test_ci_exit0_with_required_labels( self, mock_add_label_err_comment: Any, mock_delete_all_label_err_comments: Any, mock_has_required_labels: Any, mock_parse_args: Any, mock_gh_get_info: Any, ) -> None: with self.assertRaises(SystemExit) as sys_exit: check_labels_main() self.assertEqual(str(sys_exit.exception), "0") mock_add_label_err_comment.assert_not_called() mock_delete_all_label_err_comments.assert_called_once() if __name__ == "__main__": main()
TestCheckLabels
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py
{ "start": 575, "end": 658 }
class ____: def __post_init__(self, x="hmm") -> None: ... # RUF033 @dataclass
Foo
python
pytorch__pytorch
torch/distributed/checkpoint/_experimental/barriers.py
{ "start": 4014, "end": 5214 }
class ____(Barrier): """ A barrier implementation using PyTorch's distributed barrier for synchronization. This barrier uses the built-in torch.distributed.barrier() function to coordinate synchronization across multiple processes. It's simpler than TCPStoreBarrier but requires an initialized process group. """ barrier_type = "dist_barrier" def __init__( self, ) -> None: """ Initialize a DistBarrier. This barrier requires an initialized PyTorch distributed process group. No additional arguments are needed as it uses the current process group. Raises: AssertionError: If the distributed process group is not initialized. """ if not dist.is_initialized(): raise AssertionError("DistBarrier requires an initialized process group.") def execute_barrier(self) -> None: """ Execute a synchronization barrier using the prefix provided during initialization. """ # Note: dist.barrier() doesn't support explicit timeouts # The timeout is handled by the underlying implementation dist.barrier() @register_barrier
DistBarrier
python
getsentry__sentry
src/sentry/migrations/1000_add_project_distribution_scope.py
{ "start": 170, "end": 5252 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("sentry", "0999_add_extrapolation_mode_to_snuba_query"), ] operations = [ migrations.AlterField( model_name="apiauthorization", name="scopes", field=bitfield.models.BitField( [ "project:read", "project:write", "project:admin", "project:releases", "team:read", "team:write", "team:admin", "event:read", "event:write", "event:admin", "org:read", "org:write", "org:admin", "member:read", "member:write", "member:admin", "org:integrations", "alerts:read", "alerts:write", "member:invite", "project:distribution", ], default=None, ), ), migrations.AlterField( model_name="apikey", name="scopes", field=bitfield.models.BitField( [ "project:read", "project:write", "project:admin", "project:releases", "team:read", "team:write", "team:admin", "event:read", "event:write", "event:admin", "org:read", "org:write", "org:admin", "member:read", "member:write", "member:admin", "org:integrations", "alerts:read", "alerts:write", "member:invite", "project:distribution", ], default=None, ), ), migrations.AlterField( model_name="apitoken", name="scopes", field=bitfield.models.BitField( [ "project:read", "project:write", "project:admin", "project:releases", "team:read", "team:write", "team:admin", "event:read", "event:write", "event:admin", "org:read", "org:write", "org:admin", "member:read", "member:write", "member:admin", "org:integrations", "alerts:read", "alerts:write", "member:invite", "project:distribution", ], default=None, ), ), migrations.AlterField( model_name="sentryapp", name="scopes", field=bitfield.models.BitField( [ "project:read", "project:write", "project:admin", "project:releases", "team:read", "team:write", "team:admin", "event:read", "event:write", "event:admin", "org:read", "org:write", "org:admin", "member:read", "member:write", "member:admin", "org:integrations", "alerts:read", "alerts:write", "member:invite", "project:distribution", ], default=None, ), ), ]
Migration
python
ansible__ansible
test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/grouped.py
{ "start": 265, "end": 540 }
class ____(object): """ Ansible core jinja2 filters """ def filters(self): return { 'noop': nochange, 'ultimatequestion': meaningoflife, 'b64decode': nochange, # here to colide with basename of builtin }
FilterModule
python
walkccc__LeetCode
solutions/2729. Check if The Number is Fascinating/2729.py
{ "start": 0, "end": 132 }
class ____: def isFascinating(self, n): s = str(n) + str(2 * n) + str(3 * n) return ''.join(sorted(s)) == '123456789'
Solution
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/parse_example_dataset_test.py
{ "start": 2414, "end": 43076 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def _compare_output_to_expected(self, dict_tensors, expected_tensors): self.assertEqual(set(dict_tensors.keys()), set(expected_tensors.keys())) for k, v in sorted(dict_tensors.items()): expected_v = expected_tensors[k] self.assertValuesEqual(expected_v, v) def _test(self, input_tensor, feature_val, expected_values=None, expected_err=None, create_iterator_twice=False): if expected_err: with self.assertRaisesWithPredicateMatch(expected_err[0], expected_err[1]): dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply( contrib_parsing_ops.parse_example_dataset(feature_val)) get_next = self.getNext(dataset) self.evaluate(get_next()) return else: # Returns dict w/ Tensors and SparseTensors. # Check values. dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply( contrib_parsing_ops.parse_example_dataset(feature_val)) get_next = self.getNext(dataset) result = self.evaluate(get_next()) self._compare_output_to_expected(result, expected_values) with self.assertRaises(errors_impl.OutOfRangeError): self.evaluate(get_next()) with self.assertRaises(errors_impl.OutOfRangeError): self.evaluate(get_next()) if create_iterator_twice: get_next = self.getNext(dataset) result = self.evaluate(get_next()) self._compare_output_to_expected(result, expected_values) with self.assertRaises(errors_impl.OutOfRangeError): self.evaluate(get_next()) # Check shapes; if serialized is a Tensor we need its size to # properly check. batch_size = ( self.evaluate(input_tensor).size if isinstance(input_tensor, tensor.Tensor) else np.asarray(input_tensor).size ) for k, f in feature_val.items(): if isinstance(f, parsing_ops.FixedLenFeature) and f.shape is not None: self.assertEqual( dataset_ops.get_legacy_output_shapes(dataset)[k].as_list()[0], batch_size) elif isinstance(f, parsing_ops.VarLenFeature): self.assertEqual( dataset_ops.get_legacy_output_shapes(dataset)[k].as_list()[1], None) @combinations.generate(test_base.default_test_combinations()) def testEmptySerializedWithAllDefaults(self): sparse_name = "st_a" a_name = "a" b_name = "b" c_name = "c:has_a_tricky_name" a_default = [0, 42, 0] b_default = np.random.rand(3, 3).astype(bytes) c_default = np.random.rand(2).astype(np.float32) expected_st_a = sparse_tensor.SparseTensorValue( # indices, values, shape np.empty((0, 2), dtype=np.int64), # indices np.empty((0,), dtype=np.int64), # sp_a is DT_INT64 np.array([2, 0], dtype=np.int64)) # batch == 2, max_elems = 0 expected_output = { sparse_name: expected_st_a, a_name: np.array(2 * [[a_default]]), b_name: np.array(2 * [b_default]), c_name: np.array(2 * [c_default]), } self._test( ops.convert_to_tensor(["", ""]), { sparse_name: parsing_ops.VarLenFeature(dtypes.int64), a_name: parsing_ops.FixedLenFeature( (1, 3), dtypes.int64, default_value=a_default), b_name: parsing_ops.FixedLenFeature( (3, 3), dtypes.string, default_value=b_default), c_name: parsing_ops.FixedLenFeature( (2,), dtypes.float32, default_value=c_default), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.graph_only_combinations()) def testEmptySerializedWithoutDefaultsShouldFail(self): input_features = { "st_a": parsing_ops.VarLenFeature(dtypes.int64), "a": parsing_ops.FixedLenFeature( (1, 3), dtypes.int64, default_value=[0, 42, 0]), "b": parsing_ops.FixedLenFeature( (3, 3), dtypes.string, default_value=np.random.rand(3, 3).astype(bytes)), # Feature "c" is missing a default, this gap will cause failure. "c": parsing_ops.FixedLenFeature( (2,), dtype=dtypes.float32), } # Edge case where the key is there but the feature value is empty original = example(features=features({"c": feature()})) self._test( [original.SerializeToString()], input_features, expected_err=(errors_impl.InvalidArgumentError, "Feature: c \\(data type: float\\) is required")) # Standard case of missing key and value. self._test( ["", ""], input_features, expected_err=(errors_impl.InvalidArgumentError, "Feature: c \\(data type: float\\) is required")) @combinations.generate(test_base.graph_only_combinations()) def testDenseNotMatchingShapeShouldFail(self): original = [ example(features=features({ "a": float_feature([1, 1, 3]), })), example(features=features({ "a": float_feature([-1, -1]), })) ] serialized = [m.SerializeToString() for m in original] self._test( ops.convert_to_tensor(serialized), {"a": parsing_ops.FixedLenFeature((1, 3), dtypes.float32)}, expected_err=(errors_impl.InvalidArgumentError, "Key: a, Index: 1. Number of float values")) @combinations.generate(test_base.default_test_combinations()) def testDenseDefaultNoShapeShouldFail(self): original = [example(features=features({"a": float_feature([1, 1, 3]),})),] serialized = [m.SerializeToString() for m in original] self._test( ops.convert_to_tensor(serialized), {"a": parsing_ops.FixedLenFeature(None, dtypes.float32)}, expected_err=(ValueError, "Missing shape for feature a")) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingSparse(self): original = [ example(features=features({ "st_c": float_feature([3, 4]) })), example(features=features({ "st_c": float_feature([]), # empty float list })), example(features=features({ "st_d": feature(), # feature with nothing in it })), example(features=features({ "st_c": float_feature([1, 2, -1]), "st_d": bytes_feature([b"hi"]) })) ] serialized = [m.SerializeToString() for m in original] expected_st_c = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 0], [0, 1], [3, 0], [3, 1], [3, 2]], dtype=np.int64), np.array([3.0, 4.0, 1.0, 2.0, -1.0], dtype=np.float32), np.array([4, 3], dtype=np.int64)) # batch == 2, max_elems = 3 expected_st_d = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[3, 0]], dtype=np.int64), np.array(["hi"], dtype=bytes), np.array([4, 1], dtype=np.int64)) # batch == 2, max_elems = 1 expected_output = { "st_c": expected_st_c, "st_d": expected_st_d, } self._test( ops.convert_to_tensor(serialized), { "st_c": parsing_ops.VarLenFeature(dtypes.float32), "st_d": parsing_ops.VarLenFeature(dtypes.string) }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingSparseFeature(self): original = [ example(features=features({ "val": float_feature([3, 4]), "idx": int64_feature([5, 10]) })), example(features=features({ "val": float_feature([]), # empty float list "idx": int64_feature([]) })), example(features=features({ "val": feature(), # feature with nothing in it # missing idx feature })), example(features=features({ "val": float_feature([1, 2, -1]), "idx": int64_feature([0, 9, 3]) # unsorted })) ] serialized = [m.SerializeToString() for m in original] expected_sp = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 5], [0, 10], [3, 0], [3, 3], [3, 9]], dtype=np.int64), np.array([3.0, 4.0, 1.0, -1.0, 2.0], dtype=np.float32), np.array([4, 13], dtype=np.int64)) # batch == 4, max_elems = 13 expected_output = {"sp": expected_sp,} self._test( ops.convert_to_tensor(serialized), {"sp": parsing_ops.SparseFeature(["idx"], "val", dtypes.float32, [13])}, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingSparseFeatureReuse(self): original = [ example(features=features({ "val1": float_feature([3, 4]), "val2": float_feature([5, 6]), "idx": int64_feature([5, 10]) })), example(features=features({ "val1": float_feature([]), # empty float list "idx": int64_feature([]) })), ] serialized = [m.SerializeToString() for m in original] expected_sp1 = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 5], [0, 10]], dtype=np.int64), np.array([3.0, 4.0], dtype=np.float32), np.array([2, 13], dtype=np.int64)) # batch == 2, max_elems = 13 expected_sp2 = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 5], [0, 10]], dtype=np.int64), np.array([5.0, 6.0], dtype=np.float32), np.array([2, 7], dtype=np.int64)) # batch == 2, max_elems = 13 expected_output = { "sp1": expected_sp1, "sp2": expected_sp2, } self._test( ops.convert_to_tensor(serialized), { "sp1": parsing_ops.SparseFeature("idx", "val1", dtypes.float32, 13), "sp2": parsing_ops.SparseFeature( "idx", "val2", dtypes.float32, size=7, already_sorted=True) }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContaining3DSparseFeature(self): original = [ example(features=features({ "val": float_feature([3, 4]), "idx0": int64_feature([5, 10]), "idx1": int64_feature([0, 2]), })), example(features=features({ "val": float_feature([]), # empty float list "idx0": int64_feature([]), "idx1": int64_feature([]), })), example(features=features({ "val": feature(), # feature with nothing in it # missing idx feature })), example(features=features({ "val": float_feature([1, 2, -1]), "idx0": int64_feature([0, 9, 3]), # unsorted "idx1": int64_feature([1, 0, 2]), })) ] serialized = [m.SerializeToString() for m in original] expected_sp = sparse_tensor.SparseTensorValue( # indices np.array([[0, 5, 0], [0, 10, 2], [3, 0, 1], [3, 3, 2], [3, 9, 0]], dtype=np.int64), # values np.array([3.0, 4.0, 1.0, -1.0, 2.0], dtype=np.float32), # shape batch == 4, max_elems = 13 np.array([4, 13, 3], dtype=np.int64)) expected_output = {"sp": expected_sp,} self._test( ops.convert_to_tensor(serialized), { "sp": parsing_ops.SparseFeature(["idx0", "idx1"], "val", dtypes.float32, [13, 3]) }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingDense(self): aname = "a" bname = "b*has+a:tricky_name" original = [ example(features=features({ aname: float_feature([1, 1]), bname: bytes_feature([b"b0_str"]), })), example(features=features({ aname: float_feature([-1, -1]), bname: bytes_feature([b""]), })) ] serialized = [m.SerializeToString() for m in original] expected_output = { aname: np.array( # pylint: disable=too-many-function-args [[1, 1], [-1, -1]], dtype=np.float32).reshape(2, 1, 2, 1), bname: np.array( # pylint: disable=too-many-function-args ["b0_str", ""], dtype=bytes).reshape(2, 1, 1, 1, 1), } # No defaults, values required self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenFeature((1, 2, 1), dtype=dtypes.float32), bname: parsing_ops.FixedLenFeature((1, 1, 1, 1), dtype=dtypes.string), }, expected_values=expected_output, create_iterator_twice=True) # This test is identical as the previous one except # for the creation of 'serialized'. @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingDenseWithConcat(self): aname = "a" bname = "b*has+a:tricky_name" # TODO(lew): Feature appearing twice should be an error in future. original = [ (example(features=features({ aname: float_feature([10, 10]), })), example(features=features({ aname: float_feature([1, 1]), bname: bytes_feature([b"b0_str"]), }))), ( example(features=features({ bname: bytes_feature([b"b100"]), })), example(features=features({ aname: float_feature([-1, -1]), bname: bytes_feature([b"b1"]), })),), ] serialized = [ m.SerializeToString() + n.SerializeToString() for (m, n) in original ] expected_output = { aname: np.array( # pylint: disable=too-many-function-args [[1, 1], [-1, -1]], dtype=np.float32).reshape(2, 1, 2, 1), bname: np.array( # pylint: disable=too-many-function-args ["b0_str", "b1"], dtype=bytes).reshape(2, 1, 1, 1, 1), } # No defaults, values required self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenFeature((1, 2, 1), dtype=dtypes.float32), bname: parsing_ops.FixedLenFeature((1, 1, 1, 1), dtype=dtypes.string), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingDenseScalar(self): original = [ example(features=features({ "a": float_feature([1]), })), example(features=features({})) ] serialized = [m.SerializeToString() for m in original] expected_output = { "a": np.array( [[1], [-1]], dtype=np.float32) # 2x1 (column vector) } self._test( ops.convert_to_tensor(serialized), { "a": parsing_ops.FixedLenFeature( (1,), dtype=dtypes.float32, default_value=-1), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingDenseWithDefaults(self): original = [ example(features=features({ "a": float_feature([1, 1]), })), example(features=features({ "b": bytes_feature([b"b1"]), })), example(features=features({ "b": feature() })), ] serialized = [m.SerializeToString() for m in original] expected_output = { "a": np.array( # pylint: disable=too-many-function-args [[1, 1], [3, -3], [3, -3]], dtype=np.float32).reshape(3, 1, 2, 1), "b": np.array( # pylint: disable=too-many-function-args ["tmp_str", "b1", "tmp_str"], dtype=bytes).reshape(3, 1, 1, 1, 1), } self._test( ops.convert_to_tensor(serialized), { "a": parsing_ops.FixedLenFeature( (1, 2, 1), dtype=dtypes.float32, default_value=[3.0, -3.0]), "b": parsing_ops.FixedLenFeature( (1, 1, 1, 1), dtype=dtypes.string, default_value="tmp_str"), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedSparseAndSparseFeatureAndDenseWithNoDefault(self): expected_st_a = sparse_tensor.SparseTensorValue( # indices, values, shape np.empty((0, 2), dtype=np.int64), # indices np.empty((0,), dtype=np.int64), # sp_a is DT_INT64 np.array([2, 0], dtype=np.int64)) # batch == 2, max_elems = 0 expected_sp = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 0], [0, 3], [1, 7]], dtype=np.int64), np.array(["a", "b", "c"], dtype="|S"), np.array([2, 13], dtype=np.int64)) # batch == 4, max_elems = 13 original = [ example(features=features({ "c": float_feature([3, 4]), "val": bytes_feature([b"a", b"b"]), "idx": int64_feature([0, 3]) })), example(features=features({ "c": float_feature([1, 2]), "val": bytes_feature([b"c"]), "idx": int64_feature([7]) })) ] serialized = [m.SerializeToString() for m in original] a_default = [1, 2, 3] b_default = np.random.rand(3, 3).astype(bytes) expected_output = { "st_a": expected_st_a, "sp": expected_sp, "a": np.array(2 * [[a_default]]), "b": np.array(2 * [b_default]), "c": np.array( [[3, 4], [1, 2]], dtype=np.float32), } self._test( ops.convert_to_tensor(serialized), { "st_a": parsing_ops.VarLenFeature(dtypes.int64), "sp": parsing_ops.SparseFeature("idx", "val", dtypes.string, 13), "a": parsing_ops.FixedLenFeature( (1, 3), dtypes.int64, default_value=a_default), "b": parsing_ops.FixedLenFeature( (3, 3), dtypes.string, default_value=b_default), # Feature "c" must be provided, since it has no default_value. "c": parsing_ops.FixedLenFeature((2,), dtypes.float32), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingSparseAndSparseFeatureWithReuse(self): expected_idx = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.int64), np.array([0, 3, 7, 1]), np.array([2, 2], dtype=np.int64)) # batch == 4, max_elems = 2 expected_sp = sparse_tensor.SparseTensorValue( # indices, values, shape np.array([[0, 0], [0, 3], [1, 1], [1, 7]], dtype=np.int64), np.array(["a", "b", "d", "c"], dtype="|S"), np.array([2, 13], dtype=np.int64)) # batch == 4, max_elems = 13 original = [ example(features=features({ "val": bytes_feature([b"a", b"b"]), "idx": int64_feature([0, 3]) })), example(features=features({ "val": bytes_feature([b"c", b"d"]), "idx": int64_feature([7, 1]) })) ] serialized = [m.SerializeToString() for m in original] expected_output = { "idx": expected_idx, "sp": expected_sp, } self._test( ops.convert_to_tensor(serialized), { "idx": parsing_ops.VarLenFeature(dtypes.int64), "sp": parsing_ops.SparseFeature(["idx"], "val", dtypes.string, [13]), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(batch_size=[1, 10, 20, 100, 256])) ) def testSerializedContainingVarLenDenseLargerBatch(self, batch_size): np.random.seed(3456) # During parsing, data read from the serialized proto is stored in buffers. # For small batch sizes, a buffer will contain one minibatch entry. # For larger batch sizes, a buffer may contain several minibatch # entries. This test identified a bug where the code that copied # data out of the buffers and into the output tensors assumed each # buffer only contained one minibatch entry. The bug has since been fixed. truth_int = [i for i in range(batch_size)] truth_str = [[("foo%d" % i).encode(), ("bar%d" % i).encode()] for i in range(batch_size)] expected_str = copy.deepcopy(truth_str) # Delete some intermediate entries for i in range(batch_size): col = 1 if np.random.rand() < 0.25: # w.p. 25%, drop out the second entry expected_str[i][col] = b"default" col -= 1 truth_str[i].pop() if np.random.rand() < 0.25: # w.p. 25%, drop out the second entry (possibly again) expected_str[i][col] = b"default" truth_str[i].pop() expected_output = { # Batch size batch_size, 1 time step. "a": np.array(truth_int, dtype=np.int64).reshape(batch_size, 1), # Batch size batch_size, 2 time steps. "b": np.array(expected_str, dtype="|S").reshape(batch_size, 2), } original = [ example(features=features( {"a": int64_feature([truth_int[i]]), "b": bytes_feature(truth_str[i])})) for i in range(batch_size) ] serialized = [m.SerializeToString() for m in original] self._test( ops.convert_to_tensor(serialized, dtype=dtypes.string), { "a": parsing_ops.FixedLenSequenceFeature( shape=(), dtype=dtypes.int64, allow_missing=True, default_value=-1), "b": parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.string, allow_missing=True, default_value="default"), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedShapeMismatch(self): aname = "a" bname = "b" cname = "c" original = [ example(features=features({ cname: int64_feature([2]), })), example(features=features({ aname: float_feature([1, 1]), bname: bytes_feature([b"b0_str", b"b1_str"]), })), example(features=features({ aname: float_feature([-1, -1, 2, 2]), bname: bytes_feature([b"b1"]), })), example(features=features({ aname: float_feature([]), cname: int64_feature([3]), })), ] serialized = [m.SerializeToString() for m in original] if context.executing_eagerly(): self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenSequenceFeature((2, 1), dtype=dtypes.float32, allow_missing=True, default_value=[]), bname: parsing_ops.FixedLenSequenceFeature( (2, 1, 1), dtype=dtypes.string, allow_missing=True), }, expected_err=(errors_impl.InvalidArgumentError, "Input to reshape is a tensor with 0 values")) else: self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenSequenceFeature((2, 1), dtype=dtypes.float32, allow_missing=True, default_value=[]), bname: parsing_ops.FixedLenSequenceFeature( (2, 1, 1), dtype=dtypes.string, allow_missing=True), }, expected_err=(ValueError, "Cannot reshape a tensor with 0 elements to shape")) @combinations.generate(test_base.graph_only_combinations()) def testSerializedContainingVarLenDense(self): aname = "a" bname = "b" cname = "c" dname = "d" original = [ example(features=features({ cname: int64_feature([2]), })), example( features=features({ aname: float_feature([1, 1]), bname: bytes_feature([b"b0_str", b"b1_str"]), })), example( features=features({ aname: float_feature([-1, -1, 2, 2]), bname: bytes_feature([b"b1"]), })), example( features=features({ aname: float_feature([]), cname: int64_feature([3]), })), ] serialized = [m.SerializeToString() for m in original] expected_output = { aname: np.array( # pylint: disable=too-many-function-args [ [0, 0, 0, 0], [1, 1, 0, 0], [-1, -1, 2, 2], [0, 0, 0, 0], ], dtype=np.float32).reshape(4, 2, 2, 1), bname: np.array( # pylint: disable=too-many-function-args [["", ""], ["b0_str", "b1_str"], ["b1", ""], ["", ""]], dtype=bytes).reshape(4, 2, 1, 1, 1), cname: np.array([2, 0, 0, 3], dtype=np.int64).reshape(4, 1), dname: np.empty(shape=(4, 0), dtype=bytes), } self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenSequenceFeature( (2, 1), dtype=dtypes.float32, allow_missing=True), bname: parsing_ops.FixedLenSequenceFeature( (1, 1, 1), dtype=dtypes.string, allow_missing=True), cname: parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.int64, allow_missing=True), dname: parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.string, allow_missing=True), }, expected_values=expected_output, create_iterator_twice=True) # Test with padding values. expected_output_custom_padding = dict(expected_output) expected_output_custom_padding[aname] = np.array( # pylint: disable=too-many-function-args [ [-2, -2, -2, -2], [1, 1, -2, -2], [-1, -1, 2, 2], [-2, -2, -2, -2], ], dtype=np.float32).reshape(4, 2, 2, 1) self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenSequenceFeature( (2, 1), dtype=dtypes.float32, allow_missing=True, default_value=-2.0), bname: parsing_ops.FixedLenSequenceFeature( (1, 1, 1), dtype=dtypes.string, allow_missing=True), cname: parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.int64, allow_missing=True), dname: parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.string, allow_missing=True), }, expected_output_custom_padding) # Change number of required values so the inputs are not a # multiple of this size. self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenSequenceFeature( (2, 1), dtype=dtypes.float32, allow_missing=True), bname: parsing_ops.FixedLenSequenceFeature( (2, 1, 1), dtype=dtypes.string, allow_missing=True), }, expected_err=( errors_impl.OpError, "Key: b, Index: 2. " "Number of bytes values is not a multiple of stride length.")) self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenFeature((None, 2, 1), dtype=dtypes.float32), bname: parsing_ops.FixedLenSequenceFeature( (2, 1, 1), dtype=dtypes.string, allow_missing=True), }, expected_err=(ValueError, "First dimension of shape for feature a unknown. " "Consider using FixedLenSequenceFeature.")) self._test( ops.convert_to_tensor(serialized), { cname: parsing_ops.FixedLenFeature( (1, None), dtype=dtypes.int64, default_value=[[1]]), }, expected_err=(ValueError, "All dimensions of shape for feature c need to be known " r"but received \(1, None\).")) self._test( ops.convert_to_tensor(serialized), { aname: parsing_ops.FixedLenSequenceFeature( (2, 1), dtype=dtypes.float32, allow_missing=True), bname: parsing_ops.FixedLenSequenceFeature( (1, 1, 1), dtype=dtypes.string, allow_missing=True), cname: parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.int64, allow_missing=False), dname: parsing_ops.FixedLenSequenceFeature( shape=[], dtype=dtypes.string, allow_missing=True), }, expected_err=(ValueError, "Unsupported: FixedLenSequenceFeature requires " "allow_missing to be True.")) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingRaggedFeatureWithNoPartitions(self): original = [ example( features=features({ "rt_c": float_feature([3, 4, 5, 6, 7, 8]), "rt_f_values": float_feature([0, 1, 2, 3, 4]), })), example( features=features({ "rt_c": float_feature([]), # empty float list })), example( features=features({ "rt_d": feature(), # feature with nothing in it })), example( features=features({ "rt_c": float_feature([1, 2, -1]), "rt_d": bytes_feature([b"hi"]), "rt_f_values": float_feature([0, 1, 2]), })) ] serialized = [m.SerializeToString() for m in original] expected_rt_c = ragged_factory_ops.constant_value( [[3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [], [], [1.0, 2.0, -1.0]], row_splits_dtype=dtypes.int32) expected_rt_d = ragged_factory_ops.constant_value( [[], [], [], [b"hi"]], row_splits_dtype=dtypes.int64) expected_rt_f = ragged_factory_ops.constant_value( [[0.0, 1.0, 2.0, 3.0, 4.0], [], [], [0.0, 1.0, 2.0]], row_splits_dtype=dtypes.int32) expected_output = { "rt_c": expected_rt_c, "rt_d": expected_rt_d, "rt_f": expected_rt_f, } self._test( ops.convert_to_tensor(serialized), { "rt_c": parsing_ops.RaggedFeature(dtypes.float32), "rt_d": parsing_ops.RaggedFeature( dtypes.string, row_splits_dtype=dtypes.int64), "rt_f": parsing_ops.RaggedFeature( dtypes.float32, value_key="rt_f_values"), }, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingRaggedFeatureWithOnePartition(self): original = [ example( features=features({ # rt = [[3], [4, 5, 6]] "rt_values": float_feature([3, 4, 5, 6]), "rt_splits": int64_feature([0, 1, 4]), "rt_lengths": int64_feature([1, 3]), "rt_starts": int64_feature([0, 1]), "rt_limits": int64_feature([1, 4]), "rt_rowids": int64_feature([0, 1, 1, 1]), })), example( features=features({ # rt = [] "rt_values": float_feature([]), "rt_splits": int64_feature([0]), "rt_lengths": int64_feature([]), "rt_starts": int64_feature([]), "rt_limits": int64_feature([]), "rt_rowids": int64_feature([]), })), example( features=features({ # rt = [] "rt_values": feature(), # feature with nothing in it "rt_splits": int64_feature([0]), "rt_lengths": feature(), "rt_starts": feature(), "rt_limits": feature(), "rt_rowids": feature(), })), example( features=features({ # rt = [[1.0, 2.0, -1.0], [], [8.0, 9.0], [5.0]] "rt_values": float_feature([1, 2, -1, 8, 9, 5]), "rt_splits": int64_feature([0, 3, 3, 5, 6]), "rt_lengths": int64_feature([3, 0, 2, 1]), "rt_starts": int64_feature([0, 3, 3, 5]), "rt_limits": int64_feature([3, 3, 5, 6]), "rt_rowids": int64_feature([0, 0, 0, 2, 2, 3]), })) ] serialized = [m.SerializeToString() for m in original] test_features = { "rt1": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[parsing_ops.RaggedFeature.RowSplits("rt_splits")], dtype=dtypes.float32), "rt2": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[parsing_ops.RaggedFeature.RowLengths("rt_lengths")], dtype=dtypes.float32), "rt3": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[parsing_ops.RaggedFeature.RowStarts("rt_starts")], dtype=dtypes.float32), "rt4": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[parsing_ops.RaggedFeature.RowLimits("rt_limits")], dtype=dtypes.float32), "rt5": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[parsing_ops.RaggedFeature.ValueRowIds("rt_rowids")], dtype=dtypes.float32), "uniform1": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[parsing_ops.RaggedFeature.UniformRowLength(2)], dtype=dtypes.float32), "uniform2": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[ parsing_ops.RaggedFeature.UniformRowLength(2), parsing_ops.RaggedFeature.RowSplits("rt_splits") ], dtype=dtypes.float32), } expected_rt = ragged_factory_ops.constant( [[[3], [4, 5, 6]], [], [], [[1, 2, -1], [], [8, 9], [5]]], dtype=dtypes.float32, row_splits_dtype=dtypes.int32) expected_uniform1 = ragged_factory_ops.constant( [[[3, 4], [5, 6]], [], [], [[1, 2], [-1, 8], [9, 5]]], ragged_rank=1, dtype=dtypes.float32, row_splits_dtype=dtypes.int32) expected_uniform2 = ragged_factory_ops.constant( [[[[3], [4, 5, 6]]], [], [], [[[1, 2, -1], []], [[8, 9], [5]]]], dtype=dtypes.float32, row_splits_dtype=dtypes.int32) expected_output = { "rt1": expected_rt, "rt2": expected_rt, "rt3": expected_rt, "rt4": expected_rt, "rt5": expected_rt, "uniform1": expected_uniform1, "uniform2": expected_uniform2, } self._test( ops.convert_to_tensor(serialized), test_features, expected_values=expected_output, create_iterator_twice=True) @combinations.generate(test_base.default_test_combinations()) def testSerializedContainingRaggedFeatureWithMultiplePartitions(self): original = [ # rt shape: [(batch), 2, None, None] example( features=features({ # rt = [[[[1]], [[2, 3], [4]]], [[], [[5, 6, 7]]]] "rt_values": float_feature([1, 2, 3, 4, 5, 6, 7]), "lengths_axis2": int64_feature([1, 2, 0, 1]), "lengths_axis3": int64_feature([1, 2, 1, 3]), "splits_axis3": int64_feature([0, 1, 3, 4, 7]), })), example( features=features({ # rt = [[[[1, 2, 3], [4]], [[5], [6], [7, 8]]]] "rt_values": float_feature([1, 2, 3, 4, 5, 6, 7, 8]), "lengths_axis2": int64_feature([2, 3]), "lengths_axis3": int64_feature([3, 1, 1, 1, 2]), "splits_axis3": int64_feature([0, 3, 4, 5, 6, 8]), })) ] serialized = [m.SerializeToString() for m in original] test_features = { "rt1": parsing_ops.RaggedFeature( value_key="rt_values", partitions=[ parsing_ops.RaggedFeature.UniformRowLength(2), parsing_ops.RaggedFeature.RowLengths("lengths_axis2"), parsing_ops.RaggedFeature.RowSplits("splits_axis3"), ], dtype=dtypes.float32, row_splits_dtype=dtypes.int64, ), } expected_rt = ragged_factory_ops.constant( [[[[[1]], [[2, 3], [4]]], [[], [[5, 6, 7]]]], [[[[1, 2, 3], [4]], [[5], [6], [7, 8]]]]], dtype=dtypes.float32, row_splits_dtype=dtypes.int64) expected_output = { "rt1": expected_rt, } self._test( ops.convert_to_tensor(serialized), test_features, expected_values=expected_output, create_iterator_twice=True) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( local_determinism=[None, True, False], global_determinism=[True, False]))) def testDeterminism(self, local_determinism, global_determinism): num_elements = 1000 batches = [] for i in range(num_elements): example_i = example(features=features({ "a": int64_feature([i]), })) batches.append([example_i.SerializeToString()]) test_features = {"a": parsing_ops.FixedLenFeature((), dtype=dtypes.int64)} dataset = dataset_ops.Dataset.from_tensor_slices(batches) dataset = dataset.apply( contrib_parsing_ops.parse_example_dataset( test_features, num_parallel_calls=10, deterministic=local_determinism)) opts = options_lib.Options() opts.deterministic = global_determinism dataset = dataset.with_options(opts) expected = list(range(num_elements)) actual = [elem["a"][0] for elem in self.getDatasetOutput(dataset)] require_order = local_determinism or (local_determinism is None and global_determinism) if require_order: self.assertAllEqual(expected, actual) else: self.assertCountEqual(expected, actual)
ParseExampleDatasetTest
python
lxml__lxml
src/lxml/tests/test_relaxng.py
{ "start": 6839, "end": 8399 }
class ____(HelperTestCase): pytestmark = skipif('rnc2rng is None') def test_relaxng_compact(self): tree_valid = self.parse('<a><b>B</b><c>C</c></a>') tree_invalid = self.parse('<a><b></b></a>') schema = etree.RelaxNG(file=fileInTestDir('test.rnc')) self.assertTrue(schema.validate(tree_valid)) self.assertFalse(schema.validate(tree_invalid)) def test_relaxng_compact_file_obj(self): with open(fileInTestDir('test.rnc')) as f: schema = etree.RelaxNG(file=f) tree_valid = self.parse('<a><b>B</b><c>C</c></a>') tree_invalid = self.parse('<a><b></b></a>') self.assertTrue(schema.validate(tree_valid)) self.assertFalse(schema.validate(tree_invalid)) def test_relaxng_compact_str(self): tree_valid = self.parse('<a><b>B</b></a>') tree_invalid = self.parse('<a><b>X</b></a>') rnc_str = 'element a { element b { "B" } }' schema = etree.RelaxNG.from_rnc_string(rnc_str) self.assertTrue(schema.validate(tree_valid)) self.assertFalse(schema.validate(tree_invalid)) def test_suite(): suite = unittest.TestSuite() suite.addTests([unittest.defaultTestLoader.loadTestsFromTestCase(ETreeRelaxNGTestCase)]) suite.addTests( [make_doctest('validation.txt')]) if rnc2rng is not None: suite.addTests([unittest.defaultTestLoader.loadTestsFromTestCase(RelaxNGCompactTestCase)]) return suite if __name__ == '__main__': print('to test use test.py %s' % __file__)
RelaxNGCompactTestCase
python
PyCQA__pylint
tests/functional/n/names_in__all__.py
{ "start": 846, "end": 1059 }
class ____: """A klass which contains a function""" def func(self): """A klass method""" inner = None print(inner) class InnerKlass: """An inner klass""" pass
Klass
python
ZoranPandovski__al-go-rithms
machine_learning/deep_learning/python/neuralnetwork.py
{ "start": 5383, "end": 6118 }
class ____: def __init__(self, num_nodes_in_layer, num_nodes_in_next_layer, activation_function): self.num_nodes_in_layer = num_nodes_in_layer self.activation_function = activation_function self.activations = np.zeros([num_nodes_in_layer,1]) if num_nodes_in_next_layer != 0: self.weights_for_layer = np.random.normal(0, 0.001, size=(num_nodes_in_layer, num_nodes_in_next_layer)) else: self.weights_for_layer = None self.bias_for_layer = None def add_bias(self, batch_size, num_nodes_in_next_layer): if num_nodes_in_next_layer != 0: self.bias_for_layer = np.random.normal(0, 0.01, size=(batch_size, num_nodes_in_next_layer))
layer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 208103, "end": 209030 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "author_email", "commit_body", "commit_headline", "enabled_at", "enabled_by", "merge_method", "pull_request", ) author_email = sgqlc.types.Field(String, graphql_name="authorEmail") commit_body = sgqlc.types.Field(String, graphql_name="commitBody") commit_headline = sgqlc.types.Field(String, graphql_name="commitHeadline") enabled_at = sgqlc.types.Field(DateTime, graphql_name="enabledAt") enabled_by = sgqlc.types.Field(Actor, graphql_name="enabledBy") merge_method = sgqlc.types.Field( sgqlc.types.non_null(PullRequestMergeMethod), graphql_name="mergeMethod" ) pull_request = sgqlc.types.Field( sgqlc.types.non_null("PullRequest"), graphql_name="pullRequest" )
AutoMergeRequest
python
apache__airflow
providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_asb.py
{ "start": 4134, "end": 5208 }
class ____: def test_init(self): """ Test init by creating AzureServiceBusDeleteQueueOperator with task id, queue_name and asserting with values """ asb_delete_queue_operator = AzureServiceBusDeleteQueueOperator( task_id="asb_delete_queue", queue_name=QUEUE_NAME, ) assert asb_delete_queue_operator.task_id == "asb_delete_queue" assert asb_delete_queue_operator.queue_name == QUEUE_NAME @mock.patch("airflow.providers.microsoft.azure.hooks.asb.AdminClientHook.get_conn") def test_delete_queue(self, mock_get_conn): """Test AzureServiceBusDeleteQueueOperator by mocking queue name, connection and hook delete_queue""" asb_delete_queue_operator = AzureServiceBusDeleteQueueOperator( task_id="asb_delete_queue", queue_name=QUEUE_NAME, ) asb_delete_queue_operator.execute(None) mock_get_conn.return_value.__enter__.return_value.delete_queue.assert_called_once_with(QUEUE_NAME)
TestAzureServiceBusDeleteQueueOperator
python
viewflow__viewflow
viewflow/views/base.py
{ "start": 1265, "end": 1492 }
class ____(object): def __init__(self, name, url=None, viewname=None, icon=None): assert url or viewname self.name = name self.url = url self.viewname = viewname self.icon = icon
Action
python
bokeh__bokeh
tests/support/util/examples.py
{ "start": 2141, "end": 8061 }
class ____: def __init__(self, path: str, flags: int, examples_dir: str, extensions: list[str] = []) -> None: self.path = normpath(path) self.flags = flags self.examples_dir = examples_dir self.extensions = extensions self._diff_ref = None self.pixels = 0 self._has_ref = None def __str__(self) -> str: flags = [ "file" if self.is_file else "", "server" if self.is_server else "", "notebook" if self.is_notebook else "", "slow" if self.is_slow else "", "skip" if self.is_skip else "", "xfail" if self.is_xfail else "", "no_js" if self.no_js else "", ] return f"Example({self.relpath!r}, {'|'.join(f for f in flags if f)})" __repr__ = __str__ @property def name(self) -> str: return basename(self.path_no_ext) @property def base_dir(self) -> str: return dirname(self.path) @property def relpath(self) -> str: return relpath(self.path, self.examples_dir) @property def path_no_ext(self) -> str: return splitext(self.path)[0] @property def img_path(self) -> str: return self.path_no_ext + ".png" @property def is_file(self) -> bool: return bool(self.flags & Flags.file) @property def is_server(self) -> bool: return bool(self.flags & Flags.server) @property def is_notebook(self) -> bool: return bool(self.flags & Flags.notebook) @property def is_slow(self) -> bool: return bool(self.flags & Flags.slow) @property def is_skip(self) -> bool: return bool(self.flags & Flags.skip) @property def is_xfail(self) -> bool: return bool(self.flags & Flags.xfail) @property def no_js(self) -> bool: return bool(self.flags & Flags.no_js) def store_img(self, img_data: str) -> None: _store_binary(self.img_path, b64decode(img_data)) All = Literal["all"] def add_examples(list_of_examples: list[Example], path: str, examples_dir: str, example_type: int | None = None, slow: list[str] | All | None = None, skip: list[str] | All | None = None, xfail: list[str] | All | None = None, no_js: list[str] | All | None = None) -> None: example_pattern = normpath(join(examples_dir, path)) example_path = normpath(example_pattern.strip("*")) for path in sorted(iglob(example_pattern, recursive=True)): flags = 0 extensions: list[str] = [] orig_name = name = str(Path(path).relative_to(example_path)) if name.startswith(('_', '.')): continue elif name.endswith(".py"): flags |= example_type if example_type else Flags.file elif name.endswith(".ipynb"): flags |= Flags.notebook elif isdir(join(example_path, name)): if exists(join(example_path, name, name + ".py")): name = join(name, name + ".py") flags |= example_type if example_type else Flags.file elif exists(join(example_path, name, "main.py")): # name is unchanged and passed as the example name flags |= example_type if example_type else Flags.server else: continue ext_file = "bokeh.ext.json" if exists(join(example_path, orig_name, ext_file)): extensions.append(join(example_path, orig_name)) else: for dir_name in os.listdir(join(example_path, orig_name)): dir_path = join(example_path, orig_name, dir_name) if exists(join(dir_path, ext_file)): extensions.append(dir_path) else: continue if slow is not None and orig_name in slow: flags |= Flags.slow if skip is not None and (skip == 'all' or basename(orig_name) in skip): flags |= Flags.skip if xfail is not None and (xfail == 'all' or basename(orig_name) in xfail): flags |= Flags.xfail if no_js is not None and (no_js == 'all' or basename(orig_name) in no_js): flags |= Flags.no_js list_of_examples.append(Example(join(example_path, name), flags, examples_dir, extensions)) def collect_examples(config_path: str) -> list[Example]: examples_dir = join(dirname(config_path), pardir) list_of_examples: list[Example] = [] with open(config_path) as f: examples = yaml.safe_load(f.read()) for example in examples: path = example["path"] if example.get("type") is not None: example_type = getattr(Flags, example["type"]) else: example_type = None slow_status = example.get("slow") skip_status = example.get("skip") xfail_status = example.get("xfail") no_js_status = example.get("no_js") add_examples(list_of_examples, path, examples_dir, example_type=example_type, slow=slow_status, skip=skip_status, xfail=xfail_status, no_js=no_js_status) return list_of_examples #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- def _store_binary(path: PathLike, data: bytes) -> None: directory = dirname(path) if not exists(directory): os.makedirs(directory) with open(path, "wb") as f: f.write(data) #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Example
python
huggingface__transformers
src/transformers/models/pix2struct/image_processing_pix2struct_fast.py
{ "start": 2248, "end": 13280 }
class ____(BaseImageProcessorFast): rescale_factor = None do_normalize = True do_convert_rgb = True patch_size = {"height": 16, "width": 16} max_patches = 2048 is_vqa = False valid_kwargs = Pix2StructImageProcessorKwargs model_input_names = ["flattened_patches", "attention_mask"] def _further_process_kwargs( self, patch_size: Optional[dict[str, int]] = None, **kwargs, ) -> dict: """ Process custom Pix2Struct kwargs, specifically converting patch_size to SizeDict. """ # Call super to handle standard kwargs processing (like converting patch_size to SizeDict) kwargs = super()._further_process_kwargs(**kwargs) kwargs["patch_size"] = SizeDict(**get_size_dict(size=patch_size, param_name="patch_size")) return kwargs def _validate_preprocess_kwargs(self, **kwargs): """ Skip standard validation as Pix2Struct uses custom preprocessing. """ # Pix2Struct doesn't use standard resize/rescale/normalize parameters # so we skip the default validation pass def render_header( self, image: torch.Tensor, header: str, font_bytes: Optional[bytes] = None, font_path: Optional[str] = None, ) -> torch.Tensor: """ Render header text on image using torch tensors. Args: image (`torch.Tensor`): Image tensor in channel-first format (C, H, W). header (`str`): Header text to render. font_bytes (`bytes`, *optional*): Font bytes to use for rendering. font_path (`str`, *optional*): Path to font file to use for rendering. Returns: `torch.Tensor`: Image with header in channel-first format (C, H, W). """ device = image.device dtype = image.dtype # Convert tensor to PIL (channel-first to channel-last for PIL) if image.dtype == torch.uint8: image_pil = F.to_pil_image(image) else: # If float, convert to uint8 first image_uint8 = (image * 255).clamp(0, 255).to(torch.uint8) image_pil = F.to_pil_image(image_uint8) # Render header text as PIL image header_image = render_text(header, font_bytes=font_bytes, font_path=font_path) # Calculate new dimensions new_width = max(header_image.width, image_pil.width) new_height = int(image_pil.height * (new_width / image_pil.width)) new_header_height = int(header_image.height * (new_width / header_image.width)) # Create new image and paste header and original image new_image = Image.new("RGB", (new_width, new_height + new_header_height), "white") new_image.paste(header_image.resize((new_width, new_header_height)), (0, 0)) new_image.paste(image_pil.resize((new_width, new_height)), (0, new_header_height)) # Convert back to tensor (channel-first) result = F.pil_to_tensor(new_image).to(device) # Convert back to original dtype if needed if dtype != torch.uint8: result = result.float() / 255.0 return result def normalize(self, images: torch.Tensor) -> torch.Tensor: """ Normalize batched images using per-image mean and standard deviation. Args: images (`torch.Tensor`): Batched float image tensor of shape (B, C, H, W). Returns: `torch.Tensor`: Normalized images of shape (B, C, H, W). """ # Compute mean and std per image along spatial and channel dimensions mean = images.mean(dim=(1, 2, 3), keepdim=True) # Shape: (B, 1, 1, 1) std = images.std(dim=(1, 2, 3), keepdim=True) # Shape: (B, 1, 1, 1) num_elements_per_image = images.shape[1] * images.shape[2] * images.shape[3] min_std = 1.0 / num_elements_per_image**0.5 adjusted_stddev = torch.maximum(std, torch.tensor(min_std, device=std.device)) return (images - mean) / adjusted_stddev def extract_flattened_patches( self, images: torch.Tensor, max_patches: int, patch_size: SizeDict, ) -> torch.Tensor: """ Extract flattened patches from a batch of images. Args: images (`torch.Tensor`): Batched images tensor of shape (batch, channels, height, width). max_patches (`int`): Maximum number of patches to extract. patch_size (`dict[str, int]`): Dictionary containing patch height and width. Returns: `torch.Tensor`: Batched flattened patches with row/column IDs of shape (batch, max_patches, patch_dim). """ patch_height, patch_width = patch_size.height, patch_size.width batch_size, channels, image_height, image_width = images.shape # Calculate scale to maximize patches while respecting max_patches scale = (max_patches * (patch_height / image_height) * (patch_width / image_width)) ** 0.5 num_feasible_rows = max(min(int(scale * image_height / patch_height), max_patches), 1) num_feasible_cols = max(min(int(scale * image_width / patch_width), max_patches), 1) resized_height = max(num_feasible_rows * patch_height, 1) resized_width = max(num_feasible_cols * patch_width, 1) # Resize images (batched) using parent class method resize_size = SizeDict(height=resized_height, width=resized_width) images = self.resize( image=images, size=resize_size, interpolation=F.InterpolationMode.BILINEAR, antialias=True ) # Extract patches: [batch, rows, columns, patch_height * patch_width * channels] patches = torch_extract_patches(images, patch_height, patch_width) batch_size, rows, columns, depth = patches.shape # Reshape to [batch, rows * columns, depth] patches = patches.reshape(batch_size, rows * columns, depth) # Create row and column IDs row_ids = ( torch.arange(rows, device=images.device).reshape(rows, 1).repeat(1, columns).reshape(1, rows * columns, 1) ) col_ids = ( torch.arange(columns, device=images.device) .reshape(1, columns) .repeat(rows, 1) .reshape(1, rows * columns, 1) ) # Expand to batch size row_ids = row_ids.expand(batch_size, -1, -1) col_ids = col_ids.expand(batch_size, -1, -1) # Offset by 1 so IDs don't contain zeros (which represent padding) row_ids = (row_ids + 1).float() col_ids = (col_ids + 1).float() # Concatenate row_ids, col_ids, and patches: [batch, rows * columns, 2 + depth] result = torch.cat([row_ids, col_ids, patches], dim=-1) # Pad to max_patches: [batch, max_patches, 2 + depth] result = torch.nn.functional.pad(result, [0, 0, 0, max_patches - (rows * columns)]).float() return result @auto_docstring def preprocess( self, images: ImageInput, header_text: Optional[Union[str, list[str]]] = None, **kwargs: Unpack[Pix2StructImageProcessorKwargs], ) -> BatchFeature: r""" header_text (`Union[str, list[str]]`, *optional*): Text to render as a header. Only has an effect if `image_processor.is_vqa` is `True`. """ return super().preprocess(images, header_text=header_text, **kwargs) def _preprocess_image_like_inputs( self, images: ImageInput, header_text: Optional[Union[str, list[str]]] = None, do_convert_rgb: bool = True, input_data_format: ChannelDimension = ChannelDimension.FIRST, device: Optional[Union[str, torch.device]] = None, **kwargs: Unpack[Pix2StructImageProcessorKwargs], ) -> BatchFeature: """ Preprocess images for Pix2Struct. """ # Prepare images (converts to torch tensors) images = self._prepare_image_like_inputs( images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device, ) # Handle VQA mode with header rendering is_vqa = kwargs.get("is_vqa", self.is_vqa) if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models.") font_bytes = kwargs.pop("font_bytes", None) font_path = kwargs.pop("font_path", None) if isinstance(header_text, str): header_text = [header_text] * len(images) # Render headers using torch-native method images = [ self.render_header(image, header_text[i], font_bytes=font_bytes, font_path=font_path) for i, image in enumerate(images) ] return self._preprocess(images, **kwargs) def _preprocess( self, images: list[torch.Tensor], do_normalize: bool, max_patches: int, patch_size: SizeDict, return_tensors: Optional[Union[str, TensorType]], disable_grouping: bool, **kwargs, ) -> BatchFeature: """ Preprocess images to extract flattened patches. """ # Group images by shape first for efficient batch processing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) flattened_patches_grouped = {} attention_masks_grouped = {} for shape, stacked_images in grouped_images.items(): # Convert to float if needed (for resize and other operations) if stacked_images.dtype == torch.uint8: stacked_images = stacked_images.float() # Normalize batched images with per-image mean and std if do_normalize: stacked_images = self.normalize(stacked_images) patches = self.extract_flattened_patches( images=stacked_images, max_patches=max_patches, patch_size=patch_size ) masks = (patches.sum(dim=-1) != 0).float() flattened_patches_grouped[shape] = patches attention_masks_grouped[shape] = masks flattened_patches = reorder_images(flattened_patches_grouped, grouped_images_index) attention_masks = reorder_images(attention_masks_grouped, grouped_images_index) # Stack if return_tensors is set if return_tensors: flattened_patches = torch.stack(flattened_patches, dim=0) attention_masks = torch.stack(attention_masks, dim=0) return BatchFeature( data={"flattened_patches": flattened_patches, "attention_mask": attention_masks}, tensor_type=return_tensors, ) __all__ = ["Pix2StructImageProcessorFast"]
Pix2StructImageProcessorFast
python
jazzband__django-simple-history
simple_history/exceptions.py
{ "start": 65, "end": 202 }
class ____(Exception): """The model has been registered to have history tracking more than once""" pass
MultipleRegistrationsError
python
spack__spack
lib/spack/spack/database.py
{ "start": 72929, "end": 73037 }
class ____(SpackError): """Raised when DB cannot find records for dependencies"""
MissingDependenciesError
python
getsentry__sentry
src/sentry/pipeline/views/base.py
{ "start": 283, "end": 719 }
class ____[P](Protocol): def dispatch(self, request: HttpRequest, pipeline: P) -> HttpResponseBase: ... def render_react_view( request: HttpRequest, pipeline_name: str, props: Mapping[str, Any], ) -> HttpResponseBase: return render_to_response( template="sentry/bases/react_pipeline.html", request=request, context={"pipelineName": pipeline_name, "props": json.dumps(props)}, )
PipelineView
python
doocs__leetcode
solution/2800-2899/2813.Maximum Elegance of a K-Length Subsequence/Solution.py
{ "start": 0, "end": 588 }
class ____: def findMaximumElegance(self, items: List[List[int]], k: int) -> int: items.sort(key=lambda x: -x[0]) tot = 0 vis = set() dup = [] for p, c in items[:k]: tot += p if c not in vis: vis.add(c) else: dup.append(p) ans = tot + len(vis) ** 2 for p, c in items[k:]: if c in vis or not dup: continue vis.add(c) tot += p - dup.pop() ans = max(ans, tot + len(vis) ** 2) return ans
Solution
python
ray-project__ray
python/ray/data/_internal/logical/operators/map_operator.py
{ "start": 8747, "end": 9789 }
class ____(AbstractUDFMap): """Logical operator for map.""" def __init__( self, input_op: LogicalOperator, fn: UserDefinedFunction, fn_args: Optional[Iterable[Any]] = None, fn_kwargs: Optional[Dict[str, Any]] = None, fn_constructor_args: Optional[Iterable[Any]] = None, fn_constructor_kwargs: Optional[Dict[str, Any]] = None, compute: Optional[ComputeStrategy] = None, ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, ray_remote_args: Optional[Dict[str, Any]] = None, ): super().__init__( "Map", input_op, fn, fn_args=fn_args, fn_kwargs=fn_kwargs, fn_constructor_args=fn_constructor_args, fn_constructor_kwargs=fn_constructor_kwargs, compute=compute, ray_remote_args_fn=ray_remote_args_fn, ray_remote_args=ray_remote_args, ) def can_modify_num_rows(self) -> bool: return False
MapRows
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 36523, "end": 38305 }
class ____(unittest.TestCase): """Tests SSN in the pl_PL locale""" def setUp(self): self.fake = Faker("pl_PL") Faker.seed(0) def test_ssn_checksum(self): assert pl_checksum([0, 5, 2, 6, 2, 8, 1, 2, 3, 6]) == 5 assert pl_checksum([8, 5, 0, 5, 0, 8, 1, 5, 5, 8]) == 7 assert pl_checksum([4, 5, 1, 1, 1, 0, 0, 2, 4, 3]) == 3 assert pl_checksum([9, 1, 0, 7, 2, 6, 1, 4, 8, 7]) == 3 assert pl_checksum([8, 1, 1, 2, 1, 4, 1, 1, 8, 7]) == 6 def test_calculate_month(self): assert pl_calculate_mouth(datetime.strptime("1 1 1900", "%m %d %Y")) == 1 assert pl_calculate_mouth(datetime.strptime("12 1 1900", "%m %d %Y")) == 12 assert pl_calculate_mouth(datetime.strptime("1 1 1999", "%m %d %Y")) == 1 assert pl_calculate_mouth(datetime.strptime("1 1 2000", "%m %d %Y")) == 21 assert pl_calculate_mouth(datetime.strptime("12 1 2000", "%m %d %Y")) == 32 assert pl_calculate_mouth(datetime.strptime("1 1 2099", "%m %d %Y")) == 21 assert pl_calculate_mouth(datetime.strptime("1 1 2100", "%m %d %Y")) == 41 assert pl_calculate_mouth(datetime.strptime("12 1 2100", "%m %d %Y")) == 52 assert pl_calculate_mouth(datetime.strptime("1 1 2199", "%m %d %Y")) == 41 assert pl_calculate_mouth(datetime.strptime("1 1 2200", "%m %d %Y")) == 61 assert pl_calculate_mouth(datetime.strptime("12 1 2200", "%m %d %Y")) == 72 assert pl_calculate_mouth(datetime.strptime("1 1 2299", "%m %d %Y")) == 61 def test_ssn(self): for _ in range(100): assert re.search(r"^\d{11}$", self.fake.ssn()) def test_vat_id(self): for _ in range(100): assert re.search(r"^PL\d{10}$", self.fake.vat_id())
TestPlPL
python
encode__django-rest-framework
tests/test_response.py
{ "start": 1469, "end": 1582 }
class ____(RendererB): media_type = 'mock/rendererc' format = 'formatc' charset = "rendererc"
RendererC
python
cython__cython
Cython/Compiler/Tests/TestUtilityLoad.py
{ "start": 2436, "end": 3121 }
class ____(TestTempitaUtilityLoader): """ Test loading CythonUtilityCodes """ # Just change the attributes and run the same tests expected = None, "test {{cy_loader}} impl" expected_tempita = None, "test CyLoader impl" required = None, "req {{cy_loader}} impl" required_tempita = None, "req CyLoader impl" context = dict(cy_loader='CyLoader') name = "TestCyUtilityLoader" filename = "TestCyUtilityLoader.pyx" cls = UtilityCode.CythonUtilityCode # Small hack to pass our tests above cls.proto = None test_load = TestUtilityLoader.test_load test_load_tempita = TestTempitaUtilityLoader.test_load
TestCythonUtilityLoader
python
openai__openai-python
src/openai/resources/vector_stores/file_batches.py
{ "start": 15921, "end": 31902 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFileBatchesWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return AsyncFileBatchesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncFileBatchesWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return AsyncFileBatchesWithStreamingResponse(self) async def create( self, vector_store_id: str, *, attributes: Optional[Dict[str, Union[str, float, bool]]] | Omit = omit, chunking_strategy: FileChunkingStrategyParam | Omit = omit, file_ids: SequenceNotStr[str] | Omit = omit, files: Iterable[file_batch_create_params.File] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFileBatch: """ Create a vector store file batch. Args: attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters, booleans, or numbers. chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. If `attributes` or `chunking_strategy` are provided, they will be applied to all files in the batch. Mutually exclusive with `files`. files: A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. Use this when you need to override metadata for specific files. The global `attributes` or `chunking_strategy` will be ignored and must be specified for each file. Mutually exclusive with `file_ids`. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/vector_stores/{vector_store_id}/file_batches", body=await async_maybe_transform( { "attributes": attributes, "chunking_strategy": chunking_strategy, "file_ids": file_ids, "files": files, }, file_batch_create_params.FileBatchCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFileBatch, ) async def retrieve( self, batch_id: str, *, vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFileBatch: """ Retrieves a vector store file batch. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not batch_id: raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/vector_stores/{vector_store_id}/file_batches/{batch_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFileBatch, ) async def cancel( self, batch_id: str, *, vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> VectorStoreFileBatch: """Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not batch_id: raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=VectorStoreFileBatch, ) async def create_and_poll( self, vector_store_id: str, *, file_ids: SequenceNotStr[str], poll_interval_ms: int | Omit = omit, chunking_strategy: FileChunkingStrategyParam | Omit = omit, ) -> VectorStoreFileBatch: """Create a vector store batch and poll until all files have been processed.""" batch = await self.create( vector_store_id=vector_store_id, file_ids=file_ids, chunking_strategy=chunking_strategy, ) # TODO: don't poll unless necessary?? return await self.poll( batch.id, vector_store_id=vector_store_id, poll_interval_ms=poll_interval_ms, ) def list_files( self, batch_id: str, *, vector_store_id: str, after: str | Omit = omit, before: str | Omit = omit, filter: Literal["in_progress", "completed", "failed", "cancelled"] | Omit = omit, limit: int | Omit = omit, order: Literal["asc", "desc"] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AsyncPaginator[VectorStoreFile, AsyncCursorPage[VectorStoreFile]]: """ Returns a list of vector store files in a batch. Args: after: A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not vector_store_id: raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not batch_id: raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/vector_stores/{vector_store_id}/file_batches/{batch_id}/files", page=AsyncCursorPage[VectorStoreFile], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform( { "after": after, "before": before, "filter": filter, "limit": limit, "order": order, }, file_batch_list_files_params.FileBatchListFilesParams, ), ), model=VectorStoreFile, ) async def poll( self, batch_id: str, *, vector_store_id: str, poll_interval_ms: int | Omit = omit, ) -> VectorStoreFileBatch: """Wait for the given file batch to be processed. Note: this will return even if one of the files failed to process, you need to check batch.file_counts.failed_count to handle this case. """ headers: dict[str, str] = {"X-Stainless-Poll-Helper": "true"} if is_given(poll_interval_ms): headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) while True: response = await self.with_raw_response.retrieve( batch_id, vector_store_id=vector_store_id, extra_headers=headers, ) batch = response.parse() if batch.file_counts.in_progress > 0: if not is_given(poll_interval_ms): from_header = response.headers.get("openai-poll-after-ms") if from_header is not None: poll_interval_ms = int(from_header) else: poll_interval_ms = 1000 await self._sleep(poll_interval_ms / 1000) continue return batch async def upload_and_poll( self, vector_store_id: str, *, files: Iterable[FileTypes], max_concurrency: int = 5, file_ids: SequenceNotStr[str] = [], poll_interval_ms: int | Omit = omit, chunking_strategy: FileChunkingStrategyParam | Omit = omit, ) -> VectorStoreFileBatch: """Uploads the given files concurrently and then creates a vector store file batch. If you've already uploaded certain files that you want to include in this batch then you can pass their IDs through the `file_ids` argument. By default, if any file upload fails then an exception will be eagerly raised. The number of concurrency uploads is configurable using the `max_concurrency` parameter. Note: this method only supports `asyncio` or `trio` as the backing async runtime. """ uploaded_files: list[FileObject] = [] async_library = sniffio.current_async_library() if async_library == "asyncio": async def asyncio_upload_file(semaphore: asyncio.Semaphore, file: FileTypes) -> None: async with semaphore: file_obj = await self._client.files.create( file=file, purpose="assistants", ) uploaded_files.append(file_obj) semaphore = asyncio.Semaphore(max_concurrency) tasks = [asyncio_upload_file(semaphore, file) for file in files] await asyncio.gather(*tasks) elif async_library == "trio": # We only import if the library is being used. # We support Python 3.7 so are using an older version of trio that does not have type information import trio # type: ignore # pyright: ignore[reportMissingTypeStubs] async def trio_upload_file(limiter: trio.CapacityLimiter, file: FileTypes) -> None: async with limiter: file_obj = await self._client.files.create( file=file, purpose="assistants", ) uploaded_files.append(file_obj) limiter = trio.CapacityLimiter(max_concurrency) async with trio.open_nursery() as nursery: for file in files: nursery.start_soon(trio_upload_file, limiter, file) # pyright: ignore [reportUnknownMemberType] else: raise RuntimeError( f"Async runtime {async_library} is not supported yet. Only asyncio or trio is supported", ) batch = await self.create_and_poll( vector_store_id=vector_store_id, file_ids=[*file_ids, *(f.id for f in uploaded_files)], poll_interval_ms=poll_interval_ms, chunking_strategy=chunking_strategy, ) return batch
AsyncFileBatches
python
PyCQA__pylint
tests/functional/n/non/non_iterator_returned.py
{ "start": 1786, "end": 1919 }
class ____: """ __iter__ without next """ def __iter__(self): # [non-iterator-returned] return self
SecondBadIterator
python
django__django
tests/managers_regress/tests.py
{ "start": 391, "end": 6906 }
class ____(TestCase): def test_managers(self): a1 = Child1.objects.create(name="fred", data="a1") a2 = Child1.objects.create(name="barney", data="a2") b1 = Child2.objects.create(name="fred", data="b1", value=1) b2 = Child2.objects.create(name="barney", data="b2", value=42) c1 = Child3.objects.create(name="fred", data="c1", comment="yes") c2 = Child3.objects.create(name="barney", data="c2", comment="no") d1 = Child4.objects.create(name="fred", data="d1") d2 = Child4.objects.create(name="barney", data="d2") fred1 = Child5.objects.create(name="fred", comment="yes") Child5.objects.create(name="barney", comment="no") f1 = Child6.objects.create(name="fred", data="f1", value=42) f2 = Child6.objects.create(name="barney", data="f2", value=42) fred2 = Child7.objects.create(name="fred") barney = Child7.objects.create(name="barney") self.assertSequenceEqual(Child1.manager1.all(), [a1]) self.assertSequenceEqual(Child1.manager2.all(), [a2]) self.assertSequenceEqual(Child1._default_manager.all(), [a1]) self.assertSequenceEqual(Child2._default_manager.all(), [b1]) self.assertSequenceEqual(Child2.restricted.all(), [b2]) self.assertSequenceEqual(Child3._default_manager.all(), [c1]) self.assertSequenceEqual(Child3.manager1.all(), [c1]) self.assertSequenceEqual(Child3.manager2.all(), [c2]) # Since Child6 inherits from Child4, the corresponding rows from f1 and # f2 also appear here. This is the expected result. self.assertSequenceEqual( Child4._default_manager.order_by("data"), [d1, d2, f1.child4_ptr, f2.child4_ptr], ) self.assertCountEqual(Child4.manager1.all(), [d1, f1.child4_ptr]) self.assertCountEqual(Child5._default_manager.all(), [fred1]) self.assertCountEqual(Child6._default_manager.all(), [f1, f2]) self.assertSequenceEqual( Child7._default_manager.order_by("name"), [barney, fred2], ) def test_abstract_manager(self): # Accessing the manager on an abstract model should # raise an attribute error with an appropriate message. # This error message isn't ideal, but if the model is abstract and # a lot of the class instantiation logic isn't invoked; if the # manager is implied, then we don't get a hook to install the # error-raising manager. msg = "type object 'AbstractBase3' has no attribute 'objects'" with self.assertRaisesMessage(AttributeError, msg): AbstractBase3.objects.all() def test_custom_abstract_manager(self): # Accessing the manager on an abstract model with a custom # manager should raise an attribute error with an appropriate # message. msg = "Manager isn't available; AbstractBase2 is abstract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase2.restricted.all() def test_explicit_abstract_manager(self): # Accessing the manager on an abstract model with an explicit # manager should raise an attribute error with an appropriate # message. msg = "Manager isn't available; AbstractBase1 is abstract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase1.objects.all() @override_settings(TEST_SWAPPABLE_MODEL="managers_regress.Parent") @isolate_apps("managers_regress") def test_swappable_manager(self): class SwappableModel(models.Model): class Meta: swappable = "TEST_SWAPPABLE_MODEL" # Accessing the manager on a swappable model should # raise an attribute error with a helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.objects.all() @override_settings(TEST_SWAPPABLE_MODEL="managers_regress.Parent") @isolate_apps("managers_regress") def test_custom_swappable_manager(self): class SwappableModel(models.Model): stuff = models.Manager() class Meta: swappable = "TEST_SWAPPABLE_MODEL" # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.stuff.all() @override_settings(TEST_SWAPPABLE_MODEL="managers_regress.Parent") @isolate_apps("managers_regress") def test_explicit_swappable_manager(self): class SwappableModel(models.Model): objects = models.Manager() class Meta: swappable = "TEST_SWAPPABLE_MODEL" # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.objects.all() def test_regress_3871(self): related = RelatedModel.objects.create() relation = RelationModel() relation.fk = related relation.gfk = related relation.save() relation.m2m.add(related) t = Template( "{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}" "{{ related.test_m2m.all.0 }}" ) self.assertEqual( t.render(Context({"related": related})), "".join([str(relation.pk)] * 3), ) def test_field_can_be_called_exact(self): # Make sure related managers core filters don't include an # explicit `__exact` lookup that could be interpreted as a # reference to a foreign `exact` field. refs #23940. related = RelatedModel.objects.create(exact=False) relation = related.test_fk.create() self.assertEqual(related.test_fk.get(), relation) @isolate_apps("managers_regress")
ManagersRegressionTests
python
automl__auto-sklearn
test/test_pipeline/components/regression/test_ard_regression.py
{ "start": 167, "end": 714 }
class ____(BaseRegressionComponentTest): __test__ = True res = dict() res["default_boston"] = 0.7033160711079323 res["default_boston_iterative"] = None res["default_boston_sparse"] = None res["default_boston_iterative_sparse"] = None res["default_diabetes"] = 0.4172008418124077 res["default_diabetes_iterative"] = None res["default_diabetes_sparse"] = None res["default_diabetes_iterative_sparse"] = None sk_mod = sklearn.linear_model.ARDRegression module = ARDRegression
ARDRegressionComponentTest
python
pikepdf__pikepdf
src/pikepdf/objects.py
{ "start": 1545, "end": 1883 }
class ____(type(Object)): # type: ignore """Support instance checking.""" def __instancecheck__(self, instance: Any) -> bool: # Note: since this class is a metaclass, self is a class object if type(instance) is not Object: return False return self.object_type == instance._type_code
_ObjectMeta
python
google__jax
jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py
{ "start": 7685, "end": 9707 }
class ____(nn.Module): """Transformer encoder-decoder layer. Attributes: config: TransformerConfig dataclass containing hyperparameters. """ config: TransformerConfig @nn.compact def __call__(self, targets, encoded, decoder_mask=None, encoder_decoder_mask=None): """Applies EncoderDecoder1DBlock module. Args: targets: input data for decoder encoded: input data from encoder decoder_mask: decoder self-attention mask. encoder_decoder_mask: encoder-decoder attention mask. Returns: output after transformer encoder-decoder block. """ config = self.config # Decoder block. assert targets.ndim == 3 x = nn.LayerNorm(dtype=config.dtype)(targets) x = nn.SelfAttention( num_heads=config.num_heads, dtype=config.dtype, qkv_features=config.qkv_dim, kernel_init=config.kernel_init, bias_init=config.bias_init, use_bias=False, broadcast_dropout=False, dropout_rate=config.attention_dropout_rate, deterministic=config.deterministic, decode=config.decode)(x, decoder_mask) x = nn.Dropout(rate=config.dropout_rate)( x, deterministic=config.deterministic) x = x + targets # Encoder-Decoder block. y = nn.LayerNorm(dtype=config.dtype)(x) y = nn.MultiHeadDotProductAttention( num_heads=config.num_heads, dtype=config.dtype, qkv_features=config.qkv_dim, kernel_init=config.kernel_init, bias_init=config.bias_init, use_bias=False, broadcast_dropout=False, dropout_rate=config.attention_dropout_rate, deterministic=config.deterministic)(y, encoded, encoder_decoder_mask) y = nn.Dropout(rate=config.dropout_rate)( y, deterministic=config.deterministic) y = y + x # MLP block. z = nn.LayerNorm(dtype=config.dtype)(y) z = MlpBlock(config=config)(z) return y + z
EncoderDecoder1DBlock
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 2055, "end": 2801 }
class ____(Operation): def call(self, x): return backend.nn.sigmoid(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["keras.ops.sigmoid", "keras.ops.nn.sigmoid"]) def sigmoid(x): """Sigmoid activation function. It is defined as `f(x) = 1 / (1 + exp(-x))`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor([-6.0, 1.0, 0.0, 1.0, 6.0]) >>> keras.ops.sigmoid(x) array([0.00247262, 0.7310586, 0.5, 0.7310586, 0.9975274], dtype=float32) """ if any_symbolic_tensors((x,)): return Sigmoid().symbolic_call(x) return backend.nn.sigmoid(x)
Sigmoid
python
PyCQA__pylint
tests/functional/i/invalid/invalid_bytes_returned.py
{ "start": 447, "end": 565 }
class ____(type): def __bytes__(cls): return b"some bytes" @six.add_metaclass(BytesMetaclass)
BytesMetaclass
python
ansible__ansible
lib/ansible/module_utils/_internal/_json/_profiles/__init__.py
{ "start": 12724, "end": 16975 }
class ____(json.JSONDecoder): """Profile based JSON decoder capable of handling Ansible internal types.""" _profile: type[_JSONSerializationProfile] profile_name: str def __init__(self, **kwargs): kwargs.update(object_hook=self.object_hook) super().__init__(**kwargs) def __init_subclass__(cls, **kwargs) -> None: cls.profile_name = cls._profile.profile_name def raw_decode(self, s: str, idx: int = 0) -> tuple[t.Any, int]: obj, end = super().raw_decode(s, idx) if _string_encoding_check_enabled(): try: _recursively_check_string_encoding(obj) except UnicodeEncodeError as ex: raise _create_encoding_check_error() from ex obj = self._profile.post_deserialize(self, obj) return obj, end def object_hook(self, pairs: dict[str, object]) -> object: if _string_encoding_check_enabled(): try: for key, value in pairs.items(): key.encode() _recursively_check_string_encoding(value) except UnicodeEncodeError as ex: raise _create_encoding_check_error() from ex for mapped_key, mapped_callable in self._profile.deserialize_map.items(): if mapped_key in pairs: return mapped_callable(pairs) return pairs _check_encoding_setting = 'MODULE_STRICT_UTF8_RESPONSE' r""" The setting to control whether strings are checked to verify they can be encoded as valid UTF8. This is currently only used during deserialization, to prevent string values from entering the controller which will later fail to be encoded as bytes. The encoding failure can occur when the string represents one of two kinds of values: 1) It was created through decoding bytes with the `surrogateescape` error handler, and that handler is not being used when encoding. 2) It represents an invalid UTF8 value, such as `"\ud8f3"` in a JSON payload. This cannot be encoded, even using the `surrogateescape` error handler. Although this becomes an error during deserialization, there are other opportunities for these values to become strings within Ansible. Future code changes should further restrict bytes to string conversions to eliminate use of `surrogateescape` where appropriate. Additional warnings at other boundaries may be needed to give users an opportunity to resolve the issues before they become errors. """ # DTFIX-FUTURE: add strict UTF8 string encoding checking to serialization profiles (to match the checks performed during deserialization) # DTFIX3: the surrogateescape note above isn't quite right, for encoding use surrogatepass, which does work # DTFIX-FUTURE: this config setting should probably be deprecated def _create_encoding_check_error() -> Exception: """ Return an AnsibleError for use when a UTF8 string encoding check has failed. These checks are only performed in the controller context, but since this is module_utils code, dynamic loading of the `errors` module is required. """ errors = _internal.import_controller_module('ansible.errors') # bypass AnsiballZ import scanning return errors.AnsibleRuntimeError( message='Refusing to deserialize an invalid UTF8 string value.', help_text=f'This check can be disabled with the `{_check_encoding_setting}` setting.', ) @functools.lru_cache def _string_encoding_check_enabled() -> bool: """Return True if JSON deserialization should verify strings can be encoded as valid UTF8.""" if constants := _internal.import_controller_module('ansible.constants'): # bypass AnsiballZ import scanning return constants.config.get_config_value(_check_encoding_setting) # covers all profile-based deserializers, not just modules return False def _recursively_check_string_encoding(value: t.Any) -> None: """Recursively check the given object to ensure all strings can be encoded as valid UTF8.""" value_type = type(value) if value_type is str: value.encode() elif value_type is list: # dict is handled by the JSON deserializer for item in value: _recursively_check_string_encoding(item)
AnsibleProfileJSONDecoder
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 41934, "end": 43080 }
class ____(PipesBlobStoreMessageWriterChannel): """Message writer channel for writing messages by periodically writing message chunks to an S3 bucket. Args: client (Any): A boto3.client("s3") object. bucket (str): The name of the S3 bucket to write to. key_prefix (Optional[str]): An optional prefix to use for the keys of written blobs. interval (float): interval in seconds between upload chunk uploads """ # client is a boto3.client("s3") object def __init__( self, client: Any, bucket: str, key_prefix: Optional[str], *, interval: float = 10 ): super().__init__(interval=interval) self._client = client self._bucket = bucket self._key_prefix = key_prefix def upload_messages_chunk(self, payload: IO, index: int) -> None: key = f"{self._key_prefix}/{index}.json" if self._key_prefix else f"{index}.json" self._client.put_object( Body=payload.read(), Bucket=self._bucket, Key=key, ) # ######################## # ##### IO - GCS # ########################
PipesS3MessageWriterChannel
python
pytorch__pytorch
test/dynamo/test_unspec.py
{ "start": 980, "end": 32050 }
class ____(torch._dynamo.test_case.TestCase): def test_numpy_correctness(self): def fn(x, y, z): xy = [x + y, y, False] np_x = x.numpy() np_y = y.numpy() return { "x": x, "z": z, "a": np_y.sum(), "b": xy, "c": np_y[0][0] / 68, "d": np_x.sum(), "e": np_x + np_y, }, x + np_y.sum() + z x = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float64) y = torch.ones([2, 2], dtype=torch.int64) z = np.int64(12) res1 = fn(x, y, z) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) res2 = opt_fn(x, y, z) self.assertEqual(res1, res2) def test_no_recompilations(self): # no recompilations if passing on different numpy int values def fn(x, y): return {"a": x + 1, "b": y / 2} x = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float64) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) for i in range(10): opt_fn(x, np.int64(i)) self.assertEqual(cnts.frame_count, 1) self.assertEqual(cnts.op_count, 2) @requires_cuda def test_no_recompilations_with_efficient_attention(self): def fn(q, k, v, attn_mask): from torch.nn.attention import sdpa_kernel, SDPBackend from torch.nn.functional import scaled_dot_product_attention with sdpa_kernel(backends=[SDPBackend.EFFICIENT_ATTENTION]): return scaled_dot_product_attention( q, k, v, attn_mask=attn_mask, scale=1.0 ) def make_q_k_v_mask(batch, num_heads, head_dim, seq_len_kv): from collections import namedtuple from functools import partial dtype = torch.float16 device = "cuda" make_tensor = partial( torch.rand, device=device, dtype=dtype, requires_grad=True ) seq_len_q = 64 SdpaShape = namedtuple( "Sdpa_Shape", ["batch", "num_heads", "seq_len", "head_dim"] ) query = make_tensor(SdpaShape(batch, num_heads, seq_len_q, head_dim)) kv_shape = SdpaShape(batch, num_heads, seq_len_kv, head_dim) key, value = make_tensor(kv_shape), make_tensor(kv_shape) mask = torch.randn( (batch, num_heads, seq_len_q, seq_len_kv), device=device, dtype=dtype ) return query, key, value, mask cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) q, k, v, mask = make_q_k_v_mask(16, 16, 64, 15) opt_fn(q, k, v, mask) q, k, v, mask = make_q_k_v_mask(16, 16, 64, 16) opt_fn(q, k, v, mask) self.assertEqual(cnts.frame_count, 1) @unittest.expectedFailure # array scalars decay to 0D arrays def test_builtin_max_min(self): # test unspecialized primitive max/min def fn(x, y, z): return z + 1, max(x, y), min(x - 4, y) x = np.int64(12) y = 10 z = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float64) res1 = fn(x, y, z) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) res2 = opt_fn(x, y, z) self.assertTrue(same(res1, res2, relax_numpy_equality=True)) def test_feed_random_values_into_graph_only(self): def fn(shape): torch.manual_seed(123) x = torch.randn(shape, device="cpu") * random.randint(30, 100) return x shape = [2, 3] random.seed(1) res1 = fn(shape) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) # Especially for internal: before resetting the seed, first shake out any rng # calls that occur on compile, e.g., as a result of some module initializations. opt_fn(shape) random.seed(1) res2 = opt_fn(shape) self.assertTrue(same(res1, res2)) def test_random_values_with_graph_break(self): def fn(x): r1 = random.random() y = x + random.uniform(10, 20) y.sum().item() r2 = random.randint(2, 18) # no graph output in this frame y.sum().item() return y + r1, r2 x = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) random.seed(1) res1 = fn(x) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) # Especially for internal: before resetting the seed, first shake out any rng # calls that occur on compile, e.g., as a result of some module initializations. opt_fn(x) random.seed(1) res2 = opt_fn(x) self.assertTrue(same(res1, res2)) # Really annoying intersection of specialization and RandomValueSource # If we get a RandomValueSource with a single element tensor, we should return a ConstantVariable like other # unspects... but if we do, we break the bytecode assumptions and guards will not work as we will be referring # to a name from a source that is not there. If we call .item() and take the wrapped_value out, where we do # wrapped_value = wrapped_value.item() where we send unspec down to wrap_fx_proxy, this test passes and then # some models fail on missing codegen.tx.output.random_values_var. If we let the tensor value go into wrap as # it is, this test fails. # The real solution here is to rewrite RandomValueSource and all the codegen it does from the ground up. def test_multiple_consecutive_random_calls_before_graph(self): def fn(x): dim1 = random.randrange(start=0, stop=5) dim2 = random.randrange(start=0, stop=5) dim3 = random.randrange(start=0, stop=5) y = torch.rand(dim1, dim2, dim3) return x + 2, y x = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) random.seed(1) res1 = fn(x) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) # Especially for internal: before resetting the seed, first shake out any rng # calls that occur on compile, e.g., as a result of some module initializations. opt_fn(x) random.seed(1) res2 = opt_fn(x) self.assertTrue(same(res1, res2)) def test_compiled_random_calls_are_random(self): # For compiled functions with random calls, # it should return different values for every iteration. # https://github.com/pytorch/pytorch/issues/95425 @torch.compile(backend="eager", fullgraph=True) def fn(x): return (x + 1) * random.uniform(0, 1) res = [] for _ in range(5): res.append(fn(torch.ones(2))) for i in range(1, 5): self.assertFalse(same(res[i - 1], res[i])) def test_random_call_with_while_loop(self): def fn(x): dim1 = random.randrange(start=0, stop=3) dim2 = dim1 while dim1 == dim2: dim2 = random.randrange(start=0, stop=3) return x * 2 x = torch.randn(4) random.seed(1) res1 = fn(x) opt_fn = torch.compile(fn, backend="eager") # Especially for internal: before resetting the seed, first shake out any rng # calls that occur on compile, e.g., as a result of some module initializations. opt_fn(x) random.seed(1) res2 = opt_fn(x) self.assertTrue(same(res1, res2)) random.seed(10) res1 = fn(x) random.seed(10) res2 = opt_fn(x) self.assertTrue(same(res1, res2)) def test_random_object(self): # test argument passing, mutation, reconstruction, state correctness def fn(x, rand2): r1 = random.randint(1, 9) r2 = rand2.randint(1, 9) rand3 = random.Random(42) r3 = rand3.randint(1, 9) y = x + r1 + r2 + r3 return y, rand2, rand3 inp = torch.randn(3, 3) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) random.seed(0) y_1, rand2_1, rand3_1 = fn(inp, random.Random(12)) state_1 = random.getstate() # Especially for internal: before resetting the seed, first shake out any rng # calls that occur on compile, e.g., as a result of some module initializations. opt_fn(inp, random.Random(12)) random.seed(0) y_2, rand2_2, rand3_2 = opt_fn(inp, random.Random(12)) state_2 = random.getstate() self.assertEqual(y_1, y_2) self.assertEqual(state_1, state_2) self.assertEqual(rand2_1.getstate(), rand2_2.getstate()) self.assertEqual(rand3_1.getstate(), rand3_2.getstate()) def test_random_object_methods(self): def fn(x, rand1, rand2, rand3): rand1.seed(42) rand4 = random.Random(9002) rand2.setstate(rand4.getstate()) r1 = rand1.random() r2 = rand2.randint(1, 10) r3 = rand3.randrange(10) r4 = rand4.uniform(0, 1) return x + r1 + r2 + r3 + r4 inp = torch.randn(3, 3) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) rand1_1 = random.Random(1) rand2_1 = random.Random(2) rand3_1 = random.Random(3) rand1_2 = random.Random(1) rand2_2 = random.Random(2) rand3_2 = random.Random(3) y1 = fn(inp, rand1_1, rand2_1, rand3_1) y2 = opt_fn(inp, rand1_2, rand2_2, rand3_2) self.assertEqual(y1, y2) self.assertEqual(rand1_1.getstate(), rand1_2.getstate()) self.assertEqual(rand2_1.getstate(), rand2_2.getstate()) self.assertEqual(rand3_1.getstate(), rand3_2.getstate()) def test_random_object_overridden_methods(self): # these will result in graph breaks, but we shouldn't crash def get_rng(): rand1 = random.Random(1) rand2 = random.Random(2) orig_random = rand1.random def custom_random(): return orig_random() orig_getstate = rand2.getstate def custom_getstate(): return orig_getstate() rand1.random = custom_random rand2.getstate = custom_getstate return rand1, rand2 def fn(x, rand1, rand2): r1 = rand1.random() rand3 = random.Random() rand3.setstate(rand2.getstate()) r2 = rand3.random() return x + r1 + r2 inp = torch.randn(3, 3) opt_fn = torch.compile(fn, backend="eager") y1 = fn(inp, *get_rng()) y2 = opt_fn(inp, *get_rng()) self.assertEqual(y1, y2) def test_builtin_getitem(self): # builtin getitem args[0] is python list and args[1] is unspec def fn(x, idx): return (torch.zeros(idx), x[idx], x[idx:]) x = list(range(50)) ref = fn(x, 48) # 48 is unspecialized cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) res = opt_fn(x, 48) self.assertTrue(same(ref, res)) def test_use_and_specialize(self): cnt = CompileCounter() @torch.compile(backend=cnt, fullgraph=True, dynamic=True) def fn(x, y): x = x + y if y == 2: return x - 1 else: return x + 1 self.assertTrue(same(fn(torch.tensor([5]), 2), 6)) self.assertTrue(same(fn(torch.tensor([6]), 2), 7)) self.assertTrue(same(fn(torch.tensor([5]), 3), 9)) self.assertTrue(same(fn(torch.tensor([4]), 3), 8)) self.assertEqual(cnt.frame_count, 2) def test_no_recompiles(self): cnt = CompileCounter() @torch.compile(backend=cnt, fullgraph=True, dynamic=True) def fn(x, y): return x + y self.assertTrue(same(fn(torch.tensor([5]), 100), 105)) self.assertTrue(same(fn(torch.tensor([4]), 200), 204)) self.assertTrue(same(fn(torch.tensor([3]), 300), 303)) self.assertTrue(same(fn(torch.tensor([2]), 400), 402)) self.assertEqual(cnt.frame_count, 1) self.assertEqual(cnt.op_count, 1) def test_no_recompiles_prod_backward(self): # https://github.com/pytorch/pytorch/issues/120608 cnt = CompileCounter() @torch.compile(backend=cnt, fullgraph=True, dynamic=True) def fn(t): return torch.prod(t, 3, keepdim=True) input_shapes = [(8, 10, 3, 2), (8, 3, 5, 2), (8, 4, 8, 2)] for s in input_shapes: t1 = torch.randn(s, requires_grad=True) h_result = fn(t1) grad = torch.ones_like(h_result) h_result.backward(grad) self.assertEqual(cnt.frame_count, 1) self.assertEqual(cnt.op_count, 1) def test_unspec_float_precision(self): def fn(image, scale_factor): image = torch.nn.functional.interpolate( image[None], size=None, scale_factor=scale_factor, mode="bilinear", recompute_scale_factor=True, align_corners=False, )[0] return image.shape x = torch.rand([3, 427, 640]) scale_factor = 1.873536229133606 ref = fn(x, scale_factor) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.compile(fn, backend=cnts) res = opt_fn(x, scale_factor) self.assertTrue(same(ref, res)) @unittest.expectedFailure # fails as long as numpy scalars are 0D arrays def test_specializing_numpy_float_in_control_flow(self): # np.float64 is unspecialized by default, # but it should be specialized when used in control flow. def fn(x, y): if y > 1.0: return x + 1 else: return x - 1 x = torch.rand(4) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) for t in [np.float16, np.float32, np.float64]: y = t(1.23) ref = fn(x, y) res = opt_fn(x, y) self.assertTrue(same(ref, res)) def test_mark_static_inside(self): def fn(x): torch._dynamo.mark_static(x, 0) comptime.assert_static(x.size(0)) return x + 1 opt_fn = torch.compile(fn, dynamic=True, fullgraph=True) opt_fn(torch.randn(12, 23)) def test_shape_graph_break(self): from torch._dynamo.comptime import comptime def fn(x): x_shape = x.size() comptime.graph_break() return x + torch.randn(x_shape) x = torch.randn(20) opt_fn = torch.compile(fn, backend="eager") opt_fn(x) def test_isinstance_symint(self): def fn(x): assert isinstance(x.size(0), int) return x * 2 x = torch.randn(20) opt_fn = torch.compile(fn, backend="eager") opt_fn(x) y = torch.randn(30) torch._dynamo.mark_dynamic(y, 0) opt_fn(y) def test_mark_01_dynamic(self): def fn(x): return x * 2 x = torch.randn(1) torch._dynamo.mark_dynamic(x, 0) opt_fn = torch.compile(fn, backend="eager") # This will fail to compile a generic kernel, but we should not # complain about it (mark dynamic will try its best but 0/1 # specialization is allowed) opt_fn(x) def test_conv1d_symint_padding(self): kernel = torch.randn(1, 1, 4) def func(x): padding = math.ceil((kernel.shape[-1] + x.shape[-1] % 2) / 2) - 1 out = F.conv1d(x, kernel, padding=padding, stride=2) return out opt_func = torch.compile(func) x = torch.randn(1, 1, 175) opt_func(x) # passes x = torch.randn(1, 1, 249) opt_func(x) # crashes @torch._dynamo.config.patch("assume_static_by_default", True) def test_propagate_dynamic_dim(self): x = torch.randn(20) torch._dynamo.mark_dynamic(x, 0) @torch.compile() def fn(x): y = x * 2 comptime.graph_break() z = y * 2 return z z = fn(x) self.assertEqual(z._dynamo_weak_dynamic_indices, {0}) def test_rshift_dynamic(self): def shift_right(tensor: torch.Tensor) -> torch.Tensor: return (tensor >> 2).to(torch.long) opt_fn = torch.compile(shift_right, fullgraph=True, dynamic=True) sample_input = torch.tensor([4, 4, 16, 32], dtype=torch.uint8) opt_fn(sample_input) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_symfloat_to_tensor(self): def f1(v): return torch.tensor([v.item()]) def f2(v): return torch.tensor([[v.item()], [2.0]]) def f3(v): return torch.tensor(v.item()) def f4(v): return torch.tensor((v.item(),)) optimize = torch.compile(backend="aot_eager", fullgraph=True) r = torch.randn(1) self.assertEqual(f1(r), optimize(f1)(r)) self.assertEqual(f2(r), optimize(f2)(r)) self.assertEqual(f3(r), optimize(f3)(r)) self.assertEqual(f4(r), optimize(f4)(r)) @skipIfWindows( msg="AssertionError: The values for attribute 'dtype' do not match: torch.int32 != torch.int64." ) def test_to_tensor(self): def f1(): a = np.random.uniform(low=-1, high=1, size=(20, 1)) return torch.tensor([a, a, a, a], dtype=torch.float64, device="cpu") def f2(): a = torch.tensor([[[123]]]) return torch.tensor([a, a]) def f3(): a = torch.tensor(123) return torch.tensor([a, a]) def f4(): a = torch.tensor(123) b = torch.tensor([[[456]]]) return torch.tensor([a, b]) def f5(): a = np.array([1, 2]) return torch.tensor([a, a]) optimize = torch.compile(backend="aot_eager", fullgraph=True) self.assertEqual(f1().shape, optimize(f1)().shape) self.assertEqual(f2(), optimize(f2)()) self.assertEqual(f3(), optimize(f3)()) self.assertEqual(f4(), optimize(f4)()) self.assertEqual(f5(), optimize(f5)()) def test_sym_int_conversion(self): def f(x): y = x.size(0) return x * int(y == 0) opt_fn = torch.compile(f, backend="eager", fullgraph=True) x = torch.randn(2, 3) opt_fn(x) def test_sum_dimlist_spec(self): def fn(inputs, dim): return torch.sum(inputs, dim) inputs = torch.randn(128, 5, 24, 24) dim = (-1, 1, 0, 2) compl_fn = torch.compile(fn, dynamic=True, backend="eager", fullgraph=True) self.assertEqual(compl_fn(inputs, dim), fn(inputs, dim)) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_item_max(self): def fn(x): return torch.ones(max(x.item(), 1024)) x = torch.tensor([1000]) y = torch.tensor([2000]) compl_fn = torch.compile(fn, backend="eager", fullgraph=True) self.assertEqual(fn(x), compl_fn(x)) self.assertEqual(fn(y), compl_fn(y)) # https://github.com/pytorch/pytorch/issues/104812 def test_argmin_coerces_symint_to_intlist_spec(self): def fn(x, dim): # the python arg parser coerces dim into a vector<int> return torch.amin(x, dim=dim, keepdim=True) x = torch.randn(4, 4, 4) dim = 2 compl_fn = torch.compile(fn, dynamic=True, backend="eager", fullgraph=True) self.assertEqual(compl_fn(x, dim), fn(x, dim)) def test_exponential(self): def fn(inputs, op_inputs_dict): res = inputs.exponential_(**op_inputs_dict) return res inputs = torch.randn(2, 3, 4) op_inputs_dict = {"lambd": 10, "generator": None} compl_fn = torch.compile(fn, dynamic=True, backend="eager", fullgraph=True) self.assertEqual(compl_fn(inputs, op_inputs_dict), fn(inputs, op_inputs_dict)) def test_symbol_guard_limit_before_specialize(self): cnts = torch._dynamo.testing.CompileCounter() @torch.compile(backend=cnts, dynamic=True) def fn(x): torch._check(x.size(0) != 3) torch._check(x.size(0) != 4) torch._check(x.size(0) != 5) torch._check(x.size(0) != 6) return x + 2 # Control test fn(torch.randn(12)) fn(torch.randn(13)) fn(torch.randn(14)) self.assertExpectedInline(cnts.frame_count, """1""") cnts.frame_count = 0 torch._dynamo.reset() with torch.fx.experimental._config.patch( symbol_guard_limit_before_specialize=3 ): fn(torch.randn(12)) fn(torch.randn(13)) fn(torch.randn(14)) self.assertExpectedInline(cnts.frame_count, """3""") def test_defaults(self): def g(x, i=8): comptime.assert_static(i) return x * i def fn(x): return g(x) inputs = torch.randn(2, 3, 4) compl_fn = torch.compile(fn, dynamic=True, backend="eager") self.assertEqual(compl_fn(inputs), fn(inputs)) @torch._dynamo.config.patch(specialize_float=False) def test_symfloat_no_replacement(self): # See https://github.com/pytorch/pytorch/pull/139250 for more context # The high level idea is if we don't want to set a replacement where a # symbol is on both the right and left side, otherwise we'll end up # in an infinite self._find recursion. def fn(t, m): return 2 * t if m.is_integer() else t t = torch.tensor([1]) compl_fn = torch.compile(fn, dynamic=True, backend="eager") self.assertEqual(fn(t, 1.0), compl_fn(t, 1.0)) @torch._dynamo.config.patch(specialize_float=False) def test_unspec_roundtrip_float_input(self): def f(x, y): if y == 5.0: return x + 2 else: return x + y return (x, y) cf = torch.compile(backend="eager", fullgraph=True)(f) x = 1.1234567891234568 y = 1.1234567891234569 self.assertAlmostEqual(f(x, y), cf(x, y)) @torch._dynamo.config.patch(specialize_float=False, assume_static_by_default=True) def test_unspec_float_input(self): cnts = torch._dynamo.testing.CompileCounter() def f(x, y): if y == 5.0: return x + 2 else: return x + y cf = torch.compile(backend=cnts, fullgraph=True)(f) x = torch.randn(3) self.assertEqual(f(x, 2.0), cf(x, 2.0)) self.assertEqual(f(x, 3.0), cf(x, 3.0)) # automatic dynamic kicks in here self.assertEqual(f(x, 4.0), cf(x, 4.0)) self.assertExpectedInline(cnts.frame_count, """2""") # no recompile self.assertEqual(f(x, 5.0), cf(x, 5.0)) self.assertExpectedInline(cnts.frame_count, """3""") # guard worked self.assertEqual(f(x, math.nan), cf(x, math.nan)) self.assertExpectedInline(cnts.frame_count, """4""") # nan always recompiles @torch._dynamo.config.patch(specialize_float=False, capture_scalar_outputs=True) def test_unspecialized_float_multiply_precision(self): dtypes = [torch.bfloat16, torch.float16, torch.float32, torch.float64] for dtype in dtypes: def fn(x, y): return x * y cnt = CompileCounterWithBackend("aot_eager") fn_opt = torch.compile(fn, backend=cnt) x = torch.randn(5, dtype=dtype, requires_grad=True) y1 = 1.00048828125 y2 = 1.00048828126 y3 = 1.00048828127 self.assertEqual(fn_opt(x, y1), fn(x, y1)) self.assertEqual(fn_opt(x, y2), fn(x, y2)) self.assertEqual(fn_opt(x, y3), fn(x, y3)) self.assertEqual(cnt.frame_count, 1) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_tensorfiy_python_scalars_1(self): @torch.compile(backend="aot_eager") def f(x): y = x.sum() return x + y.item() dtypes = [torch.bfloat16, torch.float16, torch.float32, torch.float64] for dtype in dtypes: x = torch.ones(3, 3, dtype=dtype) self.assertEqual(f(x), x + x.sum().item()) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_tensorfiy_python_scalars_2(self): @torch.compile(backend="aot_eager") def f(x): return x.item() * x.item() * torch.ones((), dtype=torch.float64) x = torch.tensor(1e20, dtype=torch.float32) self.assertEqual( f(x), x.item() * x.item() * torch.ones((), dtype=torch.float64) ) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_tensorfiy_python_scalars_3(self): @torch.compile(backend="aot_eager") def f(x): y = x.item() * 101 return y * torch.tensor([1], dtype=torch.float32) finfo_float16 = torch.finfo(torch.float16) x = torch.tensor([finfo_float16.max], dtype=torch.float16) self.assertEqual(f(x), x.item() * 101 * torch.tensor([1], dtype=torch.float32)) @torch._dynamo.config.patch(specialize_float=False, assume_static_by_default=False) def test_unspec_float_input_f64(self): cnts = torch._dynamo.testing.CompileCounter() def f(x, y): return x + y cf = torch.compile(backend=cnts, fullgraph=True)(f) x = torch.zeros(3, dtype=torch.float64) # 17 digits of precision so unrepresentable in float32 flt = 1.2345678901234567 self.assertEqual(f(x, flt), cf(x, flt)) @torch._dynamo.config.patch(specialize_float=False, assume_static_by_default=True) def test_unspec_float_output(self): cnts = torch._dynamo.testing.CompileCounter() def f(x, y): return x + 1, y * 2 cf = torch.compile(backend=cnts, fullgraph=True)(f) x = torch.randn(3) self.assertEqual(f(x, 3.0), cf(x, 3.0)) self.assertEqual(f(x, 4.0), cf(x, 4.0)) self.assertEqual(f(x, 5.0), cf(x, 5.0)) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_data_dependent_evaluate_expr_graph_break(self): cnts = torch._dynamo.testing.CompileCounter() # To ensure that the continuation frame is compiled, # have to write the test function in this funny way. # See https://github.com/pytorch/pytorch/issues/111918 def test(y): if y > 2: return True else: return False @torch.compile(backend=cnts) def fn(x): x = x + 1 y = x.item() if test(y): return x * 2 else: return x * 3 x = torch.tensor([3.0]) fn(x) self.assertExpectedInline(cnts.frame_count, """2""") self.assertExpectedInline(cnts.op_count, """4""") def test_prune_torch_check(self): log_stream, ctx = logs_to_string("torch._dynamo.output_graph", "graph_code") @torch.compile(fullgraph=True, dynamic=True, backend="eager") def f(x, y): torch._check(y + 5 == 85) torch._check(x.size(0) == 80) with ctx(): f(torch.randn(80, 100), 80) out = "\n".join(log_stream.getvalue().strip().split("\n")[3:]).strip() self.assertExpectedInline( out, """\ def forward(self): return ()""", ) @torch._dynamo.config.patch(capture_scalar_outputs=True) def test_split_aot_autograd(self): @torch.compile(backend="aot_eager", fullgraph=True) def f(x, i): y, z = i.tolist() return torch.split(x, [y, z]) print(f(torch.randn(10, requires_grad=True), torch.tensor([7, 3]))) def test_bool_tensor_ctor(self): cnts = torch._dynamo.testing.CompileCounter() @torch.compile(backend=cnts, dynamic=True, fullgraph=True) def f(x): y = torch.empty((x.size(0) // 13) * 13) return torch.tensor(y.numel() == 0) self.assertTrue(f(torch.empty(8)).item()) self.assertFalse(f(torch.empty(13)).item()) @torch._dynamo.config.patch(error_on_recompile=True) def test_mark_unbacked(self): class TestModel(torch.nn.Module): def __init__( self, ): super().__init__() def forward(self, x: torch.Tensor, val: int) -> torch.Tensor: return x * 2 main_model = TestModel() opt_model = torch.compile(main_model, mode="max-autotune", dynamic=True) x1 = torch.rand(3, 5, 4, 8) x2 = torch.rand(1, 5, 4, 8) torch._dynamo.decorators.mark_unbacked(x1, 0) o1_ref = main_model(x1, 2) o1 = opt_model(x1, 2) self.assertEqual(o1_ref, o1) o1_2_ref = main_model(x2, 2) o1_2 = opt_model(x2, 2) self.assertEqual(o1_2_ref, o1_2) @torch._dynamo.config.patch(error_on_recompile=True) def test_mark_unbacked_hint_consistency(self): from torch.fx.experimental.symbolic_shapes import guard_size_oblivious x = torch.randn(1) torch._dynamo.decorators.mark_unbacked(x, 0) @torch.compile() def f(x): if guard_size_oblivious(x.size(0) != 1): return x + 3 else: return x + 4 self.assertEqual(f(x), x + 3) @torch._dynamo.config.patch(error_on_recompile=True) def test_mark_unbacked_channels_last(self): class TestModel(torch.nn.Module): def __init__( self, ): super().__init__() def forward(self, x: torch.Tensor, val: int) -> torch.Tensor: return x * 2 main_model = TestModel() opt_model = torch.compile(main_model, mode="max-autotune", dynamic=True) x1 = torch.rand(3, 5, 4, 8).to(memory_format=torch.channels_last) x2 = torch.rand(1, 5, 4, 8).to(memory_format=torch.channels_last) torch._dynamo.decorators.mark_unbacked(x1, 0) o1_ref = main_model(x1, 2) o1 = opt_model(x1, 2) self.assertEqual(o1_ref, o1) o1_2_ref = main_model(x2, 2) o1_2 = opt_model(x2, 2) self.assertEqual(o1_2_ref, o1_2)
UnspecTests
python
walkccc__LeetCode
solutions/142. Linked List Cycle II/142.py
{ "start": 0, "end": 345 }
class ____: def detectCycle(self, head: ListNode) -> ListNode: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: slow = head while slow != fast: slow = slow.next fast = fast.next return slow return None
Solution
python
apache__avro
lang/py/avro/schema.py
{ "start": 21049, "end": 23888 }
class ____(EqualByPropsMixin, NamedSchema): def __init__( self, name: str, namespace: str, symbols: Sequence[str], names: Optional[avro.name.Names] = None, doc: Optional[str] = None, other_props: Optional[Mapping[str, object]] = None, validate_enum_symbols: bool = True, validate_names: bool = True, ) -> None: """ @arg validate_enum_symbols: If False, will allow enum symbols that are not valid Avro names and default, which is not an enumerated symbol. """ if validate_enum_symbols: for symbol in symbols: try: validate_basename(symbol) except avro.errors.InvalidName: raise avro.errors.InvalidName("An enum symbol must be a valid schema name.") if len(set(symbols)) < len(symbols): raise avro.errors.AvroException(f"Duplicate symbol: {symbols}") # Call parent ctor NamedSchema.__init__(self, "enum", name, namespace, names, other_props, validate_names) # Add class members self.set_prop("symbols", symbols) if doc is not None: self.set_prop("doc", doc) if validate_enum_symbols and other_props and "default" in other_props: default = other_props["default"] if default not in symbols: raise avro.errors.InvalidDefault(f"Enum default '{default}' is not a valid member of symbols '{symbols}'") @property def symbols(self) -> Sequence[str]: symbols = self.get_prop("symbols") if isinstance(symbols, Sequence): return symbols raise Exception @property def doc(self): return self.get_prop("doc") def match(self, writer): """Return True if the current schema (as reader) matches the writer schema. @arg writer: the schema to match against @return bool """ return self.type == writer.type and self.check_props(writer, ["fullname"]) def to_json(self, names=None): names = names or Names(validate_names=self.validate_names) if self.fullname in names.names: return self.name_ref(names) names.names[self.fullname] = self return names.prune_namespace(self.props) def to_canonical_json(self, names=None): names_as_json = self.to_json(names) if isinstance(names_as_json, str): to_dump = self.fullname else: to_dump = self.canonical_properties to_dump["name"] = self.fullname return to_dump def validate(self, datum): """Return self if datum is a valid member of this Enum, else None.""" return self if datum in self.symbols else None # # Complex Types (recursive) #
EnumSchema
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/pymssql.py
{ "start": 822, "end": 1075 }
class ____(sqltypes.Numeric): def result_processor(self, dialect, type_): if not self.asdecimal: return processors.to_float else: return sqltypes.Numeric.result_processor(self, dialect, type_)
_MSNumeric_pymssql
python
gevent__gevent
src/gevent/tests/test__threading_2.py
{ "start": 23628, "end": 23796 }
class ____(lock_tests.BoundedSemaphoreTests): semtype = staticmethod(threading.BoundedSemaphore) if __name__ == "__main__": greentest.main()
BoundedSemaphoreTests
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 13645, "end": 14082 }
class ____(_TestDSTBase): def test_definition_ortho(self): # Test orthornomal mode. dt = np.result_type(np.float32, self.rdt) for xr in X: x = np.array(xr, dtype=self.rdt) y = dst(x, norm='ortho', type=1) y2 = naive_dst1(x, norm='ortho') assert_equal(y.dtype, dt) assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
_TestDSTIBase
python
getsentry__sentry
src/sentry/seer/breakpoints.py
{ "start": 810, "end": 1185 }
class ____(TypedDict): data: list[BreakpointData] seer_breakpoint_connection_pool = connection_from_url( settings.SEER_BREAKPOINT_DETECTION_URL, retries=Retry( total=5, status_forcelist=[408, 429, 502, 503, 504], ), timeout=settings.SEER_BREAKPOINT_DETECTION_TIMEOUT, ) # TODO: Source these from shared schema repository
BreakpointResponse
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 85139, "end": 85502 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING AutoModelForDocumentQuestionAnswering = auto_class_update( AutoModelForDocumentQuestionAnswering, head_doc="document question answering", checkpoint_for_example='impira/layoutlm-document-qa", revision="52e01b3', )
AutoModelForDocumentQuestionAnswering
python
mlflow__mlflow
mlflow/types/chat.py
{ "start": 3424, "end": 3998 }
class ____(ParamType): """ OpenAI uses JSON Schema (https://json-schema.org/) for function parameters. See OpenAI function calling reference: https://platform.openai.com/docs/guides/function-calling?&api-mode=responses#defining-functions JSON Schema enum supports any JSON type (str, int, float, bool, null, arrays, objects), but we restrict to basic scalar types for practical use cases and API safety. """ description: str | None = None enum: list[str | int | float | bool] | None = None items: ParamType | None = None
ParamProperty
python
ansible__ansible
test/lib/ansible_test/_internal/host_configs.py
{ "start": 12945, "end": 13079 }
class ____(HostConfig, metaclass=abc.ABCMeta): """Base class for Windows host configuration.""" @dataclasses.dataclass
WindowsConfig
python
miyuchina__mistletoe
mistletoe/block_token.py
{ "start": 37070, "end": 40065 }
class ____(BlockToken): """ Block-level HTML token. This is a leaf block token with a single child of type span_token.RawText, which holds the raw HTML content. """ _end_cond = None multiblock = re.compile(r'<(pre|script|style|textarea)[ >\n]') predefined = re.compile(r'<\/?(.+?)(?:\/?>|[ \n])') custom_tag = re.compile(r'(?:' + '|'.join((span_token._open_tag, span_token._closing_tag)) + r')\s*$') def __init__(self, lines): self.children = (span_token.RawText(''.join(lines).rstrip('\n')),) @property def content(self): """Returns the raw HTML content.""" return self.children[0].content @classmethod def start(cls, line): stripped = line.lstrip() if len(line) - len(stripped) >= 4: return False # rule 1: HTML tags designed to contain literal content, allow newlines in block match_obj = cls.multiblock.match(stripped) if match_obj is not None: cls._end_cond = '</{}>'.format(match_obj.group(1).casefold()) return 1 # rule 2: html comment tags, allow newlines in block if stripped.startswith('<!--'): cls._end_cond = '-->' return 2 # rule 3: tags that starts with <?, allow newlines in block if stripped.startswith('<?'): cls._end_cond = '?>' return 3 # rule 4: tags that starts with <!, allow newlines in block if stripped.startswith('<!') and stripped[2].isupper(): cls._end_cond = '>' return 4 # rule 5: CDATA declaration, allow newlines in block if stripped.startswith('<![CDATA['): cls._end_cond = ']]>' return 5 # rule 6: predefined tags (see html_token._tags), read until newline match_obj = cls.predefined.match(stripped) if match_obj is not None and match_obj.group(1).casefold() in span_token._tags: cls._end_cond = None return 6 # rule 7: custom tags, read until newline match_obj = cls.custom_tag.match(stripped) if match_obj is not None: cls._end_cond = None return 7 return False @classmethod def check_interrupts_paragraph(cls, lines): html_block = cls.start(lines.peek()) return html_block and html_block != 7 @classmethod def read(cls, lines): # note: stop condition can trigger on the starting line line_buffer = [] for line in lines: line_buffer.append(line) if cls._end_cond is not None: if cls._end_cond in line.casefold(): break elif line.strip() == '': line_buffer.pop() lines.backstep() break return line_buffer HTMLBlock = HtmlBlock """ Deprecated name of the `HtmlBlock` class. """ _token_types = [] reset_tokens()
HtmlBlock
python
tensorflow__tensorflow
tensorflow/python/framework/c_api_util.py
{ "start": 1013, "end": 1442 }
class ____(Exception): def __init__(self, name, obj_type): super(AlreadyGarbageCollectedError, self).__init__(f"{name} of type {obj_type} has already been garbage " f"collected and cannot be called.") # FIXME(b/235488206): Convert all Scoped objects to the context manager # to protect against deletion during use when the object is attached to # an attribute.
AlreadyGarbageCollectedError
python
kubernetes-client__python
kubernetes/client/models/v1beta1_match_resources.py
{ "start": 383, "end": 10138 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'exclude_resource_rules': 'list[V1beta1NamedRuleWithOperations]', 'match_policy': 'str', 'namespace_selector': 'V1LabelSelector', 'object_selector': 'V1LabelSelector', 'resource_rules': 'list[V1beta1NamedRuleWithOperations]' } attribute_map = { 'exclude_resource_rules': 'excludeResourceRules', 'match_policy': 'matchPolicy', 'namespace_selector': 'namespaceSelector', 'object_selector': 'objectSelector', 'resource_rules': 'resourceRules' } def __init__(self, exclude_resource_rules=None, match_policy=None, namespace_selector=None, object_selector=None, resource_rules=None, local_vars_configuration=None): # noqa: E501 """V1beta1MatchResources - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._exclude_resource_rules = None self._match_policy = None self._namespace_selector = None self._object_selector = None self._resource_rules = None self.discriminator = None if exclude_resource_rules is not None: self.exclude_resource_rules = exclude_resource_rules if match_policy is not None: self.match_policy = match_policy if namespace_selector is not None: self.namespace_selector = namespace_selector if object_selector is not None: self.object_selector = object_selector if resource_rules is not None: self.resource_rules = resource_rules @property def exclude_resource_rules(self): """Gets the exclude_resource_rules of this V1beta1MatchResources. # noqa: E501 ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about. The exclude rules take precedence over include rules (if a resource matches both, it is excluded) # noqa: E501 :return: The exclude_resource_rules of this V1beta1MatchResources. # noqa: E501 :rtype: list[V1beta1NamedRuleWithOperations] """ return self._exclude_resource_rules @exclude_resource_rules.setter def exclude_resource_rules(self, exclude_resource_rules): """Sets the exclude_resource_rules of this V1beta1MatchResources. ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about. The exclude rules take precedence over include rules (if a resource matches both, it is excluded) # noqa: E501 :param exclude_resource_rules: The exclude_resource_rules of this V1beta1MatchResources. # noqa: E501 :type: list[V1beta1NamedRuleWithOperations] """ self._exclude_resource_rules = exclude_resource_rules @property def match_policy(self): """Gets the match_policy of this V1beta1MatchResources. # noqa: E501 matchPolicy defines how the \"MatchResources\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\". - Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy. - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy. Defaults to \"Equivalent\" # noqa: E501 :return: The match_policy of this V1beta1MatchResources. # noqa: E501 :rtype: str """ return self._match_policy @match_policy.setter def match_policy(self, match_policy): """Sets the match_policy of this V1beta1MatchResources. matchPolicy defines how the \"MatchResources\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\". - Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy. - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy. Defaults to \"Equivalent\" # noqa: E501 :param match_policy: The match_policy of this V1beta1MatchResources. # noqa: E501 :type: str """ self._match_policy = match_policy @property def namespace_selector(self): """Gets the namespace_selector of this V1beta1MatchResources. # noqa: E501 :return: The namespace_selector of this V1beta1MatchResources. # noqa: E501 :rtype: V1LabelSelector """ return self._namespace_selector @namespace_selector.setter def namespace_selector(self, namespace_selector): """Sets the namespace_selector of this V1beta1MatchResources. :param namespace_selector: The namespace_selector of this V1beta1MatchResources. # noqa: E501 :type: V1LabelSelector """ self._namespace_selector = namespace_selector @property def object_selector(self): """Gets the object_selector of this V1beta1MatchResources. # noqa: E501 :return: The object_selector of this V1beta1MatchResources. # noqa: E501 :rtype: V1LabelSelector """ return self._object_selector @object_selector.setter def object_selector(self, object_selector): """Sets the object_selector of this V1beta1MatchResources. :param object_selector: The object_selector of this V1beta1MatchResources. # noqa: E501 :type: V1LabelSelector """ self._object_selector = object_selector @property def resource_rules(self): """Gets the resource_rules of this V1beta1MatchResources. # noqa: E501 ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches. The policy cares about an operation if it matches _any_ Rule. # noqa: E501 :return: The resource_rules of this V1beta1MatchResources. # noqa: E501 :rtype: list[V1beta1NamedRuleWithOperations] """ return self._resource_rules @resource_rules.setter def resource_rules(self, resource_rules): """Sets the resource_rules of this V1beta1MatchResources. ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches. The policy cares about an operation if it matches _any_ Rule. # noqa: E501 :param resource_rules: The resource_rules of this V1beta1MatchResources. # noqa: E501 :type: list[V1beta1NamedRuleWithOperations] """ self._resource_rules = resource_rules def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta1MatchResources): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta1MatchResources): return True return self.to_dict() != other.to_dict()
V1beta1MatchResources
python
kamyu104__LeetCode-Solutions
Python/find-xor-beauty-of-array.py
{ "start": 72, "end": 243 }
class ____(object): def xorBeauty(self, nums): """ :type nums: List[int] :rtype: int """ return reduce(operator.xor, nums)
Solution
python
django-import-export__django-import-export
tests/core/models.py
{ "start": 3775, "end": 3885 }
class ____(models.Model): user = models.OneToOneField("auth.User", on_delete=models.CASCADE, null=True)
Role
python
getsentry__sentry
src/sentry/preprod/api/endpoints/project_installable_preprod_artifact_download.py
{ "start": 701, "end": 4866 }
class ____(ProjectEndpoint): owner = ApiOwner.EMERGE_TOOLS publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } authentication_classes = () # No authentication required permission_classes = () def get(self, request: Request, project: Project, url_path: str) -> HttpResponseBase: """ Download an installable preprod artifact or its plist, if not expired. """ format_type = request.GET.get("response_format") try: installable = InstallablePreprodArtifact.objects.select_related( "preprod_artifact", "preprod_artifact__project", ).get( url_path=url_path, ) except InstallablePreprodArtifact.DoesNotExist: return Response({"error": "Installable preprod artifact not found"}, status=404) # Validate that the URL parameters match the actual organization and project preprod_artifact: PreprodArtifact = installable.preprod_artifact if preprod_artifact.project.id != project.id: return Response({"error": "Project not found"}, status=404) if installable.expiration_date and timezone.now() > installable.expiration_date: return Response({"error": "Install link expired"}, status=410) preprod_artifact = installable.preprod_artifact if preprod_artifact.installable_app_file_id is None: return Response({"error": "No installable file available"}, status=404) try: file_obj = File.objects.get(id=preprod_artifact.installable_app_file_id) except File.DoesNotExist: return Response({"error": "Installable file not found"}, status=404) if format_type == "plist": app_id = preprod_artifact.app_id build_version = preprod_artifact.build_version app_name = preprod_artifact.app_name if not app_id or not build_version or not app_name: return Response({"error": "App details not found"}, status=404) ipa_url = absolute_uri( f"/api/0/projects/{project.organization.slug}/{project.slug}/files/installablepreprodartifact/{installable.url_path}/?response_format=ipa" ) plist = f"""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>items</key> <array> <dict> <key>assets</key> <array> <dict> <key>kind</key> <string>software-package</string> <key>url</key> <string>{ipa_url}</string> </dict> </array> <key>metadata</key> <dict> <key>bundle-identifier</key> <string>{app_id}</string> <key>bundle-version</key> <string>{build_version}</string> <key>kind</key> <string>software</string> <key>platform-identifier</key> <string>com.apple.platform.iphoneos</string> <key>title</key> <string>{app_name}</string> </dict> </dict> </array> </dict> </plist>""" return HttpResponse(plist, content_type="text/plain; charset=utf-8") else: InstallablePreprodArtifact.objects.filter(pk=installable.pk).update( download_count=F("download_count") + 1 ) fp = file_obj.getfile() filename = preprod_artifact.app_id or "app" if preprod_artifact.build_version: filename += f"@{preprod_artifact.build_version}" if preprod_artifact.build_number: filename += f"+{preprod_artifact.build_number}" ext = format_type if format_type else "bin" filename += f".{ext}" response = FileResponse( fp, content_type="application/octet-stream", ) response["Content-Length"] = file_obj.size response["Content-Disposition"] = f'attachment; filename="{filename}"' return response
ProjectInstallablePreprodArtifactDownloadEndpoint
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 117308, "end": 117847 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("card_id", "column_id", "after_card_id", "client_mutation_id") card_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="cardId") column_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="columnId") after_card_id = sgqlc.types.Field(ID, graphql_name="afterCardId") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
MoveProjectCardInput
python
doocs__leetcode
solution/2400-2499/2452.Words Within Two Edits of Dictionary/Solution.py
{ "start": 0, "end": 313 }
class ____: def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]: ans = [] for s in queries: for t in dictionary: if sum(a != b for a, b in zip(s, t)) < 3: ans.append(s) break return ans
Solution
python
explosion__spaCy
spacy/lang/it/__init__.py
{ "start": 580, "end": 1230 }
class ____(Language): lang = "it" Defaults = ItalianDefaults @Italian.factory( "lemmatizer", assigns=["token.lemma"], default_config={ "model": None, "mode": "pos_lookup", "overwrite": False, "scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"}, }, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, overwrite: bool, scorer: Optional[Callable], ): return ItalianLemmatizer( nlp.vocab, model, name, mode=mode, overwrite=overwrite, scorer=scorer ) __all__ = ["Italian"]
Italian
python
google__pytype
pytype/overlays/typing_overlay.py
{ "start": 9307, "end": 12804 }
class ____(abstract.PyTDFunction, abc.ABC): """Base class for type variables (TypeVar and ParamSpec).""" _ABSTRACT_CLASS: _Type[abstract.BaseValue] = None @abc.abstractmethod def _get_namedarg(self, node, args, name, default_value): return NotImplemented def _get_constant(self, var, name, arg_type, arg_type_desc=None): try: ret = abstract_utils.get_atomic_python_constant(var, arg_type) except abstract_utils.ConversionError as e: desc = arg_type_desc or f"a constant {arg_type.__name__}" raise TypeVarError(f"{name} must be {desc}") from e return ret def _get_annotation(self, node, var, name): with self.ctx.errorlog.checkpoint() as record: annot = self.ctx.annotation_utils.extract_annotation( node, var, name, self.ctx.vm.simple_stack() ) if record.errors: raise TypeVarError("\n".join(error.message for error in record.errors)) if annot.formal: raise TypeVarError(f"{name} cannot contain TypeVars") return annot def _get_typeparam_name(self, node, args): try: self.match_args(node, args) except error_types.InvalidParameters as e: raise TypeVarError("wrong arguments", e.bad_call) from e except error_types.FailedFunctionCall as e: # It is currently impossible to get here, since the only # FailedFunctionCall that is not an InvalidParameters is NotCallable. raise TypeVarError("initialization failed") from e return self._get_constant( args.posargs[0], "name", str, arg_type_desc="a constant str" ) def _get_typeparam_args(self, node, args): constraints = tuple( self._get_annotation(node, c, "constraint") for c in args.posargs[1:] ) if len(constraints) == 1: raise TypeVarError("the number of constraints must be 0 or more than 1") bound = self._get_namedarg(node, args, "bound", None) covariant = self._get_namedarg(node, args, "covariant", False) contravariant = self._get_namedarg(node, args, "contravariant", False) if constraints and bound: raise TypeVarError("constraints and a bound are mutually exclusive") # `default` is unsupported for now - access it just to generate a warning. # TODO: b/382028836 - actually support the `default` arg to `TypeVar` self._get_namedarg(node, args, "default", None) extra_kwargs = set(args.namedargs) - { "bound", "covariant", "contravariant", "default", } if extra_kwargs: raise TypeVarError("extra keyword arguments: " + ", ".join(extra_kwargs)) if args.starargs: raise TypeVarError("*args must be a constant tuple") if args.starstarargs: raise TypeVarError("ambiguous **kwargs not allowed") return constraints, bound, covariant, contravariant def call(self, node, func, args, alias_map=None): """Call typing.TypeVar().""" args = args.simplify(node, self.ctx) try: name = self._get_typeparam_name(node, args) except TypeVarError as e: self.ctx.errorlog.invalid_typevar(self.ctx.vm.frames, str(e), e.bad_call) return node, self.ctx.new_unsolvable(node) try: typeparam_args = self._get_typeparam_args(node, args) except TypeVarError as e: self.ctx.errorlog.invalid_typevar(self.ctx.vm.frames, str(e), e.bad_call) typeparam_args = () param = self._ABSTRACT_CLASS(name, self.ctx, *typeparam_args) # pylint: disable=not-callable return node, param.to_variable(node)
_TypeVariable
python
catalyst-team__catalyst
tests/catalyst/callbacks/test_control_flow.py
{ "start": 7104, "end": 16091 }
class ____(unittest.TestCase): def test_with_missing_args(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) for order in orders: callback = RaiserCallback(order, "on_epoch_start") with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback) def test_epochs_with_wrong_args(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) order = random.choice(orders) callback = RaiserCallback(order, "on_epoch_start") with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, epochs=None) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, epochs="123456") def test_ignore_epochs_with_wrong_args(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) order = random.choice(orders) callback = RaiserCallback(order, "on_epoch_start") with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, ignore_epochs=None) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, ignore_epochs="123456") def test_loaders_with_wrong_args(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) order = random.choice(orders) callback = RaiserCallback(order, "on_epoch_start") with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, loaders=1234.56) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, loaders=1234.56) with self.assertRaises(ValueError): ControlFlowCallbackWrapper( callback, loaders={"train": ["", "fjdskjfdk", "1234"]} ) def test_ignore_loaders_with_wrong_args(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) order = random.choice(orders) callback = RaiserCallback(order, "on_epoch_start") with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, ignore_loaders=1234.56) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, ignore_loaders=1234.56) with self.assertRaises(ValueError): ControlFlowCallbackWrapper( callback, ignore_loaders={"train": ["", "fjdskjfdk", "1234"]} ) def test_ignore_foo_with_wrong_args(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) order = random.choice(orders) callback = RaiserCallback(order, "on_epoch_start") with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, filter_fn=12345) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, filter_fn=lambda arg: True) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, filter_fn=lambda *args: True) with self.assertRaises(ValueError): ControlFlowCallbackWrapper( callback, filter_fn=lambda one, two, three, four: True ) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, filter_fn=lambda *args, **kwargs: True) def test_filter_fn_with_wrong_args(self): runner = Mock(loader_key="train", epoch=1) orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) def _ignore_foo(epoch: int, loader: str) -> bool: return False def _raise_foo(epoch: int, loader: str) -> bool: return True for order in orders: callback = RaiserCallback(order, "on_loader_start") wrapper = ControlFlowCallbackWrapper(callback, filter_fn=_ignore_foo) wrapper.on_loader_start(runner) callback = RaiserCallback(order, "on_loader_start") wrapper = ControlFlowCallbackWrapper(callback, filter_fn=_raise_foo) with self.assertRaises(Dummy): wrapper.on_loader_start(runner) events = ( "on_loader_end", "on_experiment_start", "on_experiment_end", "on_epoch_start", "on_epoch_end", "on_batch_start", "on_batch_end", "on_exception", ) for event in events: for order in orders: callback = RaiserCallback(order, event) wrapper = ControlFlowCallbackWrapper(callback, filter_fn=_ignore_foo) wrapper.on_loader_start(runner) wrapper.__getattribute__(event)(runner) callback = RaiserCallback(order, event) wrapper = ControlFlowCallbackWrapper(callback, filter_fn=_raise_foo) wrapper.on_loader_start(runner) with self.assertRaises(Dummy): wrapper.__getattribute__(event)(runner) def test_filter_fn_with_eval(self): runner = Mock(loader_key="train", epoch=1) orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) for order in orders: callback = RaiserCallback(order, "on_loader_start") wrapper = ControlFlowCallbackWrapper( callback, filter_fn="lambda e, l: False" ) wrapper.on_loader_start(runner) callback = RaiserCallback(order, "on_loader_start") wrapper = ControlFlowCallbackWrapper(callback, filter_fn="lambda e, l: True") with self.assertRaises(Dummy): wrapper.on_loader_start(runner) events = ( "on_loader_end", "on_experiment_start", "on_experiment_end", "on_epoch_start", "on_epoch_end", "on_batch_start", "on_batch_end", "on_exception", ) for event in events: for order in orders: callback = RaiserCallback(order, event) wrapper = ControlFlowCallbackWrapper( callback, filter_fn="lambda e, l: False" ) wrapper.on_loader_start(runner) wrapper.__getattribute__(event)(runner) callback = RaiserCallback(order, event) wrapper = ControlFlowCallbackWrapper( callback, filter_fn="lambda e, l: True" ) wrapper.on_loader_start(runner) with self.assertRaises(Dummy): wrapper.__getattribute__(event)(runner) def test_filter_fn_with_err_in_eval(self): orders = ( CallbackOrder.Internal, CallbackOrder.Metric, CallbackOrder.MetricAggregation, CallbackOrder.Optimizer, CallbackOrder.Scheduler, CallbackOrder.External, ) events = ( "on_loader_start", "on_loader_end", "on_experiment_start", "on_experiment_end", "on_epoch_start", "on_epoch_end", "on_batch_start", "on_batch_end", "on_exception", ) for event in events: for order in orders: callback = RaiserCallback(order, event) with self.assertRaises(ValueError): ControlFlowCallbackWrapper(callback, filter_fn="lambda e, l")
TestControlFlowCallback
python
facelessuser__soupsieve
soupsieve/util.py
{ "start": 499, "end": 3352 }
class ____(Exception): """Syntax error in a CSS selector.""" def __init__(self, msg: str, pattern: str | None = None, index: int | None = None) -> None: """Initialize.""" self.line = None self.col = None self.context = None if pattern is not None and index is not None: # Format pattern to show line and column position self.context, self.line, self.col = get_pattern_context(pattern, index) msg = f'{msg}\n line {self.line}:\n{self.context}' super().__init__(msg) def deprecated(message: str, stacklevel: int = 2) -> Callable[..., Any]: # pragma: no cover """ Raise a `DeprecationWarning` when wrapped function/method is called. Usage: @deprecated("This method will be removed in version X; use Y instead.") def some_method()" pass """ def _wrapper(func: Callable[..., Any]) -> Callable[..., Any]: @wraps(func) def _deprecated_func(*args: Any, **kwargs: Any) -> Any: warnings.warn( f"'{func.__name__}' is deprecated. {message}", category=DeprecationWarning, stacklevel=stacklevel ) return func(*args, **kwargs) return _deprecated_func return _wrapper def warn_deprecated(message: str, stacklevel: int = 2) -> None: # pragma: no cover """Warn deprecated.""" warnings.warn( message, category=DeprecationWarning, stacklevel=stacklevel ) def get_pattern_context(pattern: str, index: int) -> tuple[str, int, int]: """Get the pattern context.""" last = 0 current_line = 1 col = 1 text = [] # type: list[str] line = 1 offset = None # type: int | None # Split pattern by newline and handle the text before the newline for m in RE_PATTERN_LINE_SPLIT.finditer(pattern): linetext = pattern[last:m.start(0)] if not len(m.group(0)) and not len(text): indent = '' offset = -1 col = index - last + 1 elif last <= index < m.end(0): indent = '--> ' offset = (-1 if index > m.start(0) else 0) + 3 col = index - last + 1 else: indent = ' ' offset = None if len(text): # Regardless of whether we are presented with `\r\n`, `\r`, or `\n`, # we will render the output with just `\n`. We will still log the column # correctly though. text.append('\n') text.append(f'{indent}{linetext}') if offset is not None: text.append('\n') text.append(' ' * (col + offset) + '^') line = current_line current_line += 1 last = m.end(0) return ''.join(text), line, col
SelectorSyntaxError
python
ray-project__ray
python/ray/tests/test_runtime_env_plugin.py
{ "start": 18323, "end": 22699 }
class ____: @pytest.mark.parametrize( "set_runtime_env_plugins", [ json.dumps([{"class": URI_CACHING_TEST_PLUGIN_CLASS_PATH}]), ], indirect=True, ) def test_uri_caching( self, set_runtime_env_plugins, start_cluster, uri_cache_size_100_gb ): cluster, address = start_cluster ray.init(address=address) def reinit(): ray.shutdown() # TODO(architkulkarni): Currently, reinit the driver will generate the same # job id. And if we reinit immediately after shutdown, raylet may # process new job started before old job finished in some cases. This # inconsistency could disorder the URI reference and delete a valid # runtime env. We sleep here to walk around this issue. time.sleep(5) ray.init(address=address) @ray.remote def f(): return True # Run a task to trigger runtime_env creation. ref1 = f.options( runtime_env={ URI_CACHING_TEST_PLUGIN_NAME: { "uri": "file:///tmp/test_uri_1", "size_bytes": gb_to_bytes(50), } } ).remote() ray.get(ref1) # Check that the URI was "created on disk". print(get_plugin_usage_data()) wait_for_condition( lambda: get_plugin_usage_data() == { "uris_to_sizes": {"file:///tmp/test_uri_1": gb_to_bytes(50)}, "modify_context_call_count": 1, "create_call_count": 1, } ) # Shutdown ray to stop the worker and remove the runtime_env reference. reinit() # Run a task with a different runtime env. ref2 = f.options( runtime_env={ URI_CACHING_TEST_PLUGIN_NAME: { "uri": "file:///tmp/test_uri_2", "size_bytes": gb_to_bytes(51), } } ).remote() ray.get(ref2) # This should delete the old URI and create a new one, because 50 + 51 > 100 # and the cache size limit is 100. wait_for_condition( lambda: get_plugin_usage_data() == { "uris_to_sizes": {"file:///tmp/test_uri_2": gb_to_bytes(51)}, "modify_context_call_count": 2, "create_call_count": 2, } ) reinit() # Run a task with the cached runtime env, to check that the runtime env is not # created anew. ref3 = f.options( runtime_env={ URI_CACHING_TEST_PLUGIN_NAME: { "uri": "file:///tmp/test_uri_2", "size_bytes": gb_to_bytes(51), } } ).remote() ray.get(ref3) # modify_context should still be called even if create() is not called. # Example: for a "conda" plugin, even if the conda env is already created # and cached, we still need to call modify_context to add "conda activate" to # the RuntimeEnvContext.command_prefix for the worker. wait_for_condition( lambda: get_plugin_usage_data() == { "uris_to_sizes": {"file:///tmp/test_uri_2": gb_to_bytes(51)}, "modify_context_call_count": 3, "create_call_count": 2, } ) reinit() # Run a task with a new runtime env ref4 = f.options( runtime_env={ URI_CACHING_TEST_PLUGIN_NAME: { "uri": "file:///tmp/test_uri_3", "size_bytes": gb_to_bytes(10), } } ).remote() ray.get(ref4) # The last two URIs should still be present in the cache, because 51 + 10 < 100. wait_for_condition( lambda: get_plugin_usage_data() == { "uris_to_sizes": { "file:///tmp/test_uri_2": gb_to_bytes(51), "file:///tmp/test_uri_3": gb_to_bytes(10), }, "modify_context_call_count": 4, "create_call_count": 3, } ) if __name__ == "__main__": sys.exit(pytest.main(["-sv", __file__]))
TestGC
python
falconry__falcon
falcon/asgi/ws.py
{ "start": 25381, "end": 31035 }
class ____: """Buffer incoming WebSocket messages. This class is used internally to monitor the WebSocket status (so that we can detect when it is disconnected). """ __slots__ = [ '_asgi_receive', '_loop', '_max_queue', '_messages', '_pop_message_waiter', '_pump_task', '_put_message_waiter', 'client_disconnected', 'client_disconnected_code', ] _pop_message_waiter: asyncio.Future[None] | None _put_message_waiter: asyncio.Future[None] | None _pump_task: asyncio.Task[None] | None _messages: collections.deque[AsgiEvent] client_disconnected: bool client_disconnected_code: int | None def __init__(self, asgi_receive: AsgiReceive, max_queue: int) -> None: self._asgi_receive = asgi_receive self._max_queue = max_queue self._loop = asyncio.get_running_loop() self._messages = collections.deque() self._pop_message_waiter = None self._put_message_waiter = None self._pump_task = None self.client_disconnected = False self.client_disconnected_code = None def start(self) -> None: # NOTE(vytas): Do not start anything if buffering is disabled. if self._pump_task is None and self._max_queue > 0: self._pump_task = asyncio.create_task(self._pump()) async def stop(self) -> None: if self._pump_task is None: return self._pump_task.cancel() try: await self._pump_task except asyncio.CancelledError: pass self._pump_task = None async def receive(self) -> AsgiEvent: # NOTE(kgriffs): Since this class is only used internally, we # use an assertion to mitigate against framework bugs. # # receive() may not be called again while another coroutine # is already waiting for the next message. assert self._pop_message_waiter is None assert self._pump_task is not None # NOTE(kgriffs): Wait for a message if none are available. This pattern # was borrowed from the websockets.protocol module. while not self._messages: # -------------------------------------------------------------------------- # NOTE(kgriffs): The pattern below was borrowed from the websockets.protocol # module under the BSD 3-Clause "New" or "Revised" License. # # Ref: https://github.com/aaugustin/websockets/blob/master/src/websockets/protocol.py # noqa E501 # # -------------------------------------------------------------------------- # PERF(kgriffs): Using a bare future like this seems to be # slightly more efficient vs. something like asyncio.Event pop_message_waiter = self._loop.create_future() self._pop_message_waiter = pop_message_waiter try: await asyncio.wait( [pop_message_waiter, self._pump_task], return_when=asyncio.FIRST_COMPLETED, ) finally: self._pop_message_waiter = None if not pop_message_waiter.done(): # NOTE(kgriffs): asyncio.wait(...) exited because # self._pump_task completed before receiving a # new message. pop_message_waiter.cancel() return { 'type': EventType.WS_DISCONNECT, } message = self._messages.popleft() # Notify _pump() if self._put_message_waiter is not None: self._put_message_waiter.set_result(None) self._put_message_waiter = None return message async def _pump(self) -> None: while not self.client_disconnected: received_event = await self._asgi_receive() if received_event['type'] == EventType.WS_DISCONNECT: self.client_disconnected = True self.client_disconnected_code = received_event.get( 'code', WSCloseCode.NORMAL ) # -------------------------------------------------------------------------- # NOTE(kgriffs): The pattern below was borrowed from the websockets.protocol # module under the BSD 3-Clause "New" or "Revised" License. # # Ref: https://github.com/aaugustin/websockets/blob/master/src/websockets/protocol.py # noqa E501 # # -------------------------------------------------------------------------- while len(self._messages) >= self._max_queue: self._put_message_waiter = self._loop.create_future() try: await self._put_message_waiter finally: self._put_message_waiter = None self._messages.append(received_event) # Notify receive() if self._pop_message_waiter is not None: self._pop_message_waiter.set_result(None) self._pop_message_waiter = None @misc._lru_cache_for_simple_logic(maxsize=16) def _supports_reason(asgi_ver: str) -> bool: """Check if the websocket version support a close reason.""" target_ver = (2, 3) current_ver = tuple(map(int, asgi_ver.split('.'))) return current_ver >= target_ver def http_status_to_ws_code(http_status: int) -> int: """Convert the provided http status to a websocket close code by adding 3000.""" return http_status + 3000
_BufferedReceiver
python
tensorflow__tensorflow
tensorflow/python/keras/engine/base_layer_utils.py
{ "start": 31329, "end": 33130 }
class ____(TrackableWeightHandler): """Wrapper for handling weight collection for static hash tables.""" def __init__(self, getter_lambda): # pylint: disable=super-init-not-called self._num_tensors = 2 self._getter = getter_lambda self._distribute_strategy = distribute_lib.get_strategy() def raise_error(_): raise RuntimeError('This layer contains a static lookup table, which ' 'cannot be changed via set_weights().') self._setter = raise_error def no_ragged_support(inputs, layer_name): input_list = nest.flatten(inputs) if any(isinstance(x, ragged_tensor.RaggedTensor) for x in input_list): raise ValueError('Layer %s does not support RaggedTensors as input. ' 'Inputs received: %s. You can try converting your ' 'input to an uniform tensor.' % (layer_name, inputs)) def is_split_variable(v): """Returns True if `v` is either a PartitionedVariable or a ShardedVariable.""" return hasattr(v, '_variable_list') or hasattr(v, '_variables') def has_weights(obj): obj_type = type(obj) return (hasattr(obj_type, 'trainable_weights') and hasattr(obj_type, 'non_trainable_weights') and not isinstance(obj, type)) # TODO(kathywu): This is a temporary hack. When a network of layers is revived # from SavedModel, only the top-level layer will have losses. This causes issues # in eager mode because the child layers may have graph losses # (thus model.losses returns a mix of Eager and graph tensors). To fix this, # whenever eager losses are added to one layer, add eager losses to all # child layers. This causes `.losses` to only return eager losses. REVIVED_LOSS_PLACEHOLDER = ( 'This layer\'s losses have been added to the parent layer.')
StaticTableHandler
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/utils/mrjob/log4j.py
{ "start": 1289, "end": 4392 }
class ____( namedtuple( "_Log4jRecord", "caller_location level logger message num_lines start_line thread timestamp" ) ): r"""Represents a Log4J log record. caller_location -- e.g. 'YarnClientImpl.java:submitApplication(251)' level -- e.g. 'INFO' logger -- e.g. 'amazon.emr.metrics.MetricsSaver' message -- the actual message. If this is a multi-line message (e.g. for counters), the lines will be joined by '\n' num_lines -- how many lines made up the message start_line -- which line the message started on (0-indexed) thread -- e.g. 'main'. Defaults to '' timestamp -- unparsed timestamp, e.g. '15/12/07 20:49:28' """ def __new__( cls, caller_location, level, logger, message, num_lines, start_line, thread, timestamp ): return super().__new__( cls, caller_location, level, logger, message, num_lines, start_line, thread, timestamp ) @staticmethod def fake_record(line, line_num): """Used to represent a leading Log4J line that doesn't conform to the regular expressions we expect. """ return Log4jRecord( caller_location="", level="", logger="", message=line, num_lines=1, start_line=line_num, thread="", timestamp="", ) def parse_hadoop_log4j_records(lines): r"""Parse lines from a hadoop log into log4j records. Yield Log4jRecords. Lines will be converted to unicode, and trailing \r and \n will be stripped from lines. Also yields fake records for leading non-log4j lines (trailing non-log4j lines are assumed to be part of a multiline message if not pre-filtered). """ last_record = None line_num = 0 for line_num, raw_line in enumerate(lines.split("\n")): # convert from bytes to unicode, if needed, and strip trailing newlines line = raw_line.rstrip("\r\n") m = _HADOOP_LOG4J_LINE_RE.match(line) or _HADOOP_LOG4J_LINE_ALTERNATE_RE.match(line) if m: if last_record: last_record = last_record._replace(num_lines=line_num - last_record.start_line) yield last_record matches = m.groupdict() last_record = Log4jRecord( caller_location=matches.get("caller_location", ""), level=matches["level"], logger=matches["logger"], message=matches["message"], num_lines=1, start_line=line_num, thread=matches.get("thread", ""), timestamp=matches["timestamp"], ) else: # add on to previous record if last_record: last_record = last_record._replace(message=last_record.message + "\n" + line) else: yield Log4jRecord.fake_record(line, line_num) if last_record: last_record = last_record._replace(num_lines=line_num + 1 - last_record.start_line) yield last_record
Log4jRecord
python
Pylons__pyramid
tests/pkgs/staticpermapp/__init__.py
{ "start": 110, "end": 897 }
class ____: __acl__ = [('Allow', 'bob', 'view')] def __init__(self, request): pass def includeme(config): from pyramid.authentication import RemoteUserAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy authn_policy = RemoteUserAuthenticationPolicy() authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_static_view('allowed', 'tests:fixtures/static/') config.add_static_view( 'protected', 'tests:fixtures/static/', permission='view' ) config.add_static_view( 'factory_protected', 'tests:fixtures/static/', permission='view', factory=LocalRootFactory, )
LocalRootFactory
python
falconry__falcon
falcon/routing/compiled.py
{ "start": 29915, "end": 30031 }
class ____(ValueError): """Error raised by ``add_error`` when a route is not acceptable."""
UnacceptableRouteError
python
fluentpython__example-code-2e
05-data-classes/dataclass/resource_repr.py
{ "start": 1432, "end": 2294 }
class ____: """Media resource description.""" identifier: str title: str = '<untitled>' creators: list[str] = field(default_factory=list) date: Optional[date] = None type: ResourceType = ResourceType.BOOK description: str = '' language: str = '' subjects: list[str] = field(default_factory=list) # tag::REPR[] def __repr__(self): cls = self.__class__ cls_name = cls.__name__ indent = ' ' * 4 res = [f'{cls_name}('] # <1> for f in fields(cls): # <2> value = getattr(self, f.name) # <3> res.append(f'{indent}{f.name} = {value!r},') # <4> res.append(')') # <5> return '\n'.join(res) # <6> # end::REPR[]
Resource
python
kamyu104__LeetCode-Solutions
Python/meeting-rooms-ii.py
{ "start": 1210, "end": 1758 }
class ____(object): def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ if not intervals: return 0 intervals.sort(key=lambda x: x[0]) free_rooms = [] heappush(free_rooms, intervals[0][1]) for interval in intervals[1:]: if free_rooms[0] <= interval[0]: heappop(free_rooms) heappush(free_rooms, interval[1]) return len(free_rooms)
Solution3
python
kamyu104__LeetCode-Solutions
Python/alt-and-tab-simulation.py
{ "start": 42, "end": 522 }
class ____(object): def simulationResult(self, windows, queries): """ :type windows: List[int] :type queries: List[int] :rtype: List[int] """ lookup = [False]*len(windows) result = [] for x in reversed(queries): if lookup[x-1]: continue lookup[x-1] = True result.append(x) result.extend(x for x in windows if not lookup[x-1]) return result
Solution
python
django__django
tests/admin_views/admin.py
{ "start": 20608, "end": 20674 }
class ____(admin.ModelAdmin): list_filter = ["title"]
AlbumAdmin
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 22979, "end": 23102 }
class ____(Hostname): platform = 'Linux' distribution = 'Anolis' strategy_class = RedHatStrategy
AnolisOSHostname
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_heapq.py
{ "start": 11245, "end": 11516 }
class ____: "Dummy element that always raises an error during comparison" def __eq__(self, other): raise ZeroDivisionError __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__ def R(seqn): 'Regular generator' for i in seqn: yield i
CmpErr
python
mahmoud__glom
glom/core.py
{ "start": 10648, "end": 12494 }
class ____(GlomError, AttributeError, KeyError, IndexError): """This :exc:`GlomError` subtype represents a failure to access an attribute as dictated by the spec. The most commonly-seen error when using glom, it maintains a copy of the original exception and produces a readable error message for easy debugging. If you see this error, you may want to: * Check the target data is accurate using :class:`~glom.Inspect` * Catch the exception and return a semantically meaningful error message * Use :class:`glom.Coalesce` to specify a default * Use the top-level ``default`` kwarg on :func:`~glom.glom()` In any case, be glad you got this error and not the one it was wrapping! Args: exc (Exception): The error that arose when we tried to access *path*. Typically an instance of KeyError, AttributeError, IndexError, or TypeError, and sometimes others. path (Path): The full Path glom was in the middle of accessing when the error occurred. part_idx (int): The index of the part of the *path* that caused the error. >>> target = {'a': {'b': None}} >>> glom(target, 'a.b.c') Traceback (most recent call last): ... PathAccessError: could not access 'c', part 2 of Path('a', 'b', 'c'), got error: ... """ def __init__(self, exc, path, part_idx): self.exc = exc self.path = path self.part_idx = part_idx def get_message(self): path_part = Path(self.path).values()[self.part_idx] return ('could not access %r, part %r of %r, got error: %r' % (path_part, self.part_idx, self.path, self.exc)) def __repr__(self): cn = self.__class__.__name__ return f'{cn}({self.exc!r}, {self.path!r}, {self.part_idx!r})'
PathAccessError
python
google__python-fire
examples/widget/collector_test.py
{ "start": 718, "end": 1190 }
class ____(testutils.BaseTestCase): def testCollectorHasWidget(self): col = collector.Collector() self.assertIsInstance(col.widget, widget.Widget) def testCollectorWantsMoreWidgets(self): col = collector.Collector() self.assertEqual(col.desired_widget_count, 10) def testCollectorGetsWantedWidgets(self): col = collector.Collector() self.assertEqual(len(col.collect_widgets()), 10) if __name__ == '__main__': testutils.main()
CollectorTest
python
getsentry__sentry
src/sentry/integrations/source_code_management/metrics.py
{ "start": 3105, "end": 3374 }
class ____(StrEnum): """Common reasons why a commit context integration may halt without success/failure.""" COMMIT_NOT_IN_DEFAULT_BRANCH = "commit_not_in_default_branch" MISSING_PR = "missing_pr" ALREADY_QUEUED = "already_queued"
CommitContextHaltReason
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 396618, "end": 397912 }
class ____(VegaLiteSchema): """ FeatureCollection schema wrapper. A collection of feature objects. https://tools.ietf.org/html/rfc7946#section-3.3 Parameters ---------- features : Sequence[dict, :class:`FeatureGeometryGeoJsonProperties`] type : Literal['FeatureCollection'] Specifies the type of GeoJSON object. bbox : :class:`BBox`, Sequence[float] Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. The value of the bbox member is an array of length 2*n where n is the number of dimensions represented in the contained geometries, with all axes of the most southwesterly point followed by all axes of the more northeasterly point. The axes order of a bbox follows the axes order of geometries. https://tools.ietf.org/html/rfc7946#section-5 """ _schema = {"$ref": "#/definitions/FeatureCollection"} def __init__( self, features: Optional[Sequence[SchemaBase | Map]] = Undefined, type: Optional[Literal["FeatureCollection"]] = Undefined, bbox: Optional[SchemaBase | Sequence[float]] = Undefined, **kwds, ): super().__init__(features=features, type=type, bbox=bbox, **kwds)
FeatureCollection
python
readthedocs__readthedocs.org
readthedocs/gold/migrations/0005_last_4_digits_null.py
{ "start": 149, "end": 498 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("gold", "0004_add_vat_id"), ] operations = [ migrations.AlterField( model_name="golduser", name="last_4_card_digits", field=models.CharField(blank=True, max_length=4, null=True), ), ]
Migration
python
huggingface__transformers
src/transformers/models/sam3/modeling_sam3.py
{ "start": 12159, "end": 13825 }
class ____(nn.Module): def __init__(self, config: Union[Sam3ViTConfig]): super().__init__() self.config = config self.activation_fn = ACT2FN[config.hidden_act] self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.fc1(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) return hidden_states def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: Optional[float] = None, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): if scaling is None: scaling = query.size(-1) ** -0.5 # Take the dot product between "query" and "key" to get the raw attention scores. attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: attention_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights
Sam3MLP
python
getsentry__sentry
src/sentry/spans/consumers/process/flusher.py
{ "start": 4432, "end": 18962 }
class ____(ProcessingStrategy[FilteredPayload | int]): """ A background multiprocessing manager that polls Redis for new segments to flush and to produce to Kafka. Creates one process per shard for parallel processing. This is a processing step to be embedded into the consumer that writes to Redis. It takes and fowards integer messages that represent recently processed timestamps (from the producer timestamp of the incoming span message), which are then used as a clock to determine whether segments have expired. :param topic: The topic to send segments to. :param produce_to_pipe: For unit-testing, produce to this multiprocessing Pipe instead of creating a kafka consumer. """ def __init__( self, buffer: SpansBuffer, next_step: ProcessingStrategy[FilteredPayload | int], max_processes: int | None = None, produce_to_pipe: Callable[[KafkaPayload], None] | None = None, ): self.next_step = next_step self.max_processes = max_processes or len(buffer.assigned_shards) self.slice_id = buffer.slice_id self.mp_context = mp_context = multiprocessing.get_context("spawn") self.stopped = mp_context.Value("i", 0) self.redis_was_full = False self.current_drift = mp_context.Value("i", 0) self.produce_to_pipe = produce_to_pipe # Determine which shards get their own processes vs shared processes self.num_processes = min(self.max_processes, len(buffer.assigned_shards)) self.process_to_shards_map: dict[int, list[int]] = { i: [] for i in range(self.num_processes) } for i, shard in enumerate(buffer.assigned_shards): process_index = i % self.num_processes self.process_to_shards_map[process_index].append(shard) self.processes: dict[int, multiprocessing.context.SpawnProcess | threading.Thread] = {} self.process_healthy_since = { process_index: mp_context.Value("i", 0) for process_index in range(self.num_processes) } self.process_backpressure_since = { process_index: mp_context.Value("i", 0) for process_index in range(self.num_processes) } self.process_restarts = {process_index: 0 for process_index in range(self.num_processes)} self.buffers: dict[int, SpansBuffer] = {} self._create_processes() # When starting the consumer, block the consumer's main thread until # all processes are healthy. This ensures we do not write into Redis if # the flusher deterministically crashes on start, because in # combination with the consumer crashlooping this will cause Redis to # be filled up. for process_index in self.process_to_shards_map.keys(): self._wait_for_process_to_become_healthy(process_index) def _wait_for_process_to_become_healthy(self, process_index: int): start_time = time.time() max_unhealthy_seconds = options.get("spans.buffer.flusher.max-unhealthy-seconds") * 2 while True: if self.process_healthy_since[process_index].value != 0: break if time.time() - start_time > max_unhealthy_seconds: shards = self.process_to_shards_map[process_index] raise RuntimeError( f"process {process_index} (shards {shards}) didn't start up in {max_unhealthy_seconds} seconds" ) time.sleep(0.1) def _create_processes(self): # Create processes based on shard mapping for process_index, shards in self.process_to_shards_map.items(): self._create_process_for_shards(process_index, shards) def _create_process_for_shards(self, process_index: int, shards: list[int]): self.process_healthy_since[process_index].value = 0 # Create a buffer for these specific shards shard_buffer = SpansBuffer(shards, slice_id=self.slice_id) make_process: Callable[..., multiprocessing.context.SpawnProcess | threading.Thread] if self.produce_to_pipe is None: target = run_with_initialized_sentry( SpanFlusher.main, # unpickling buffer will import sentry, so it needs to be # pickled separately. at the same time, pickling # synchronization primitives like multiprocessing.Value can # only be done by the Process shard_buffer, ) make_process = self.mp_context.Process else: target = partial(SpanFlusher.main, shard_buffer) make_process = threading.Thread process = make_process( target=target, args=( shards, self.stopped, self.current_drift, self.process_backpressure_since[process_index], self.process_healthy_since[process_index], self.produce_to_pipe, ), daemon=True, ) process.start() self.processes[process_index] = process self.buffers[process_index] = shard_buffer def _create_process_for_shard(self, shard: int): # Find which process this shard belongs to and restart that process for process_index, shards in self.process_to_shards_map.items(): if shard in shards: self._create_process_for_shards(process_index, shards) break @staticmethod def main( buffer: SpansBuffer, shards: list[int], stopped, current_drift, backpressure_since, healthy_since, produce_to_pipe: Callable[[KafkaPayload], None] | None, ) -> None: # TODO: remove once span buffer is live in all regions scope = sentry_sdk.get_isolation_scope() scope.level = "warning" shard_tag = ",".join(map(str, shards)) sentry_sdk.set_tag("sentry_spans_buffer_component", "flusher") sentry_sdk.set_tag("sentry_spans_buffer_shards", shard_tag) try: producer_futures = [] if produce_to_pipe is not None: produce = produce_to_pipe producer_manager = None else: producer_manager = MultiProducer(Topic.BUFFERED_SEGMENTS) def produce(payload: KafkaPayload) -> None: producer_futures.append(producer_manager.produce(payload)) while not stopped.value: system_now = int(time.time()) now = system_now + current_drift.value flushed_segments = buffer.flush_segments(now=now) # Check backpressure flag set by buffer if buffer.any_shard_at_limit: if backpressure_since.value == 0: backpressure_since.value = system_now else: backpressure_since.value = 0 # Update healthy_since for all shards handled by this process healthy_since.value = system_now if not flushed_segments: time.sleep(1) continue with metrics.timer("spans.buffer.flusher.produce", tags={"shard": shard_tag}): for flushed_segment in flushed_segments.values(): if not flushed_segment.spans: continue spans = [span.payload for span in flushed_segment.spans] kafka_payload = KafkaPayload(None, orjson.dumps({"spans": spans}), []) metrics.timing( "spans.buffer.segment_size_bytes", len(kafka_payload.value), tags={"shard": shard_tag}, ) produce(kafka_payload) with metrics.timer("spans.buffer.flusher.wait_produce", tags={"shards": shard_tag}): for future in producer_futures: future.result() producer_futures.clear() buffer.done_flush_segments(flushed_segments) if producer_manager is not None: producer_manager.close() except KeyboardInterrupt: pass except Exception: sentry_sdk.capture_exception() raise def poll(self) -> None: self.next_step.poll() def _ensure_processes_alive(self) -> None: max_unhealthy_seconds = options.get("spans.buffer.flusher.max-unhealthy-seconds") for process_index, process in self.processes.items(): if not process: continue shards = self.process_to_shards_map[process_index] cause = None if not process.is_alive(): exitcode = getattr(process, "exitcode", "unknown") cause = f"no_process_{exitcode}" elif ( int(time.time()) - self.process_healthy_since[process_index].value > max_unhealthy_seconds ): # Check if any shard handled by this process is unhealthy cause = "hang" if cause is None: continue # healthy # Report unhealthy for all shards handled by this process for shard in shards: metrics.incr( "spans.buffer.flusher_unhealthy", tags={"cause": cause, "shard": shard} ) if self.process_restarts[process_index] > MAX_PROCESS_RESTARTS: raise RuntimeError( f"flusher process for shards {shards} crashed repeatedly ({cause}), restarting consumer" ) self.process_restarts[process_index] += 1 try: if isinstance(process, multiprocessing.Process): process.kill() except (ValueError, AttributeError): pass # Process already closed, ignore self._create_process_for_shards(process_index, shards) self._wait_for_process_to_become_healthy(process_index) def submit(self, message: Message[FilteredPayload | int]) -> None: # Note that submit is not actually a hot path. Their message payloads # are mapped from *batches* of spans, and there are a handful of spans # per second at most. If anything, self.poll() might even be called # more often than submit() self._ensure_processes_alive() for buffer in self.buffers.values(): buffer.record_stored_segments() # We pause insertion into Redis if the flusher is not making progress # fast enough. We could backlog into Redis, but we assume, despite best # efforts, it is still always going to be less durable than Kafka. # Minimizing our Redis memory usage also makes COGS easier to reason # about. backpressure_secs = options.get("spans.buffer.flusher.backpressure-seconds") for backpressure_since in self.process_backpressure_since.values(): if ( backpressure_since.value > 0 and int(time.time()) - backpressure_since.value > backpressure_secs ): metrics.incr("spans.buffer.flusher.backpressure") raise MessageRejected() # We set the drift. The backpressure based on redis memory comes after. # If Redis is full for a long time, the drift will grow into a large # negative value, effectively pausing flushing as well. if isinstance(message.payload, int): self.current_drift.value = drift = message.payload - int(time.time()) metrics.timing("spans.buffer.flusher.drift", drift) # We also pause insertion into Redis if Redis is too full. In this case # we cannot allow the flusher to progress either, as it would write # partial/fragmented segments to buffered-segments topic. We have to # wait until the situation is improved manually. max_memory_percentage = options.get("spans.buffer.max-memory-percentage") if max_memory_percentage < 1.0: memory_infos: list[ServiceMemory] = [] for buffer in self.buffers.values(): memory_infos.extend(buffer.get_memory_info()) used = sum(x.used for x in memory_infos) available = sum(x.available for x in memory_infos) if available > 0 and used / available > max_memory_percentage: if not self.redis_was_full: logger.fatal("Pausing consumer due to Redis being full") metrics.incr("spans.buffer.flusher.hard_backpressure") self.redis_was_full = True # Pause consumer if Redis memory is full. Because the drift is # set before we emit backpressure, the flusher effectively # stops as well. Alternatively we may simply crash the consumer # but this would also trigger a lot of rebalancing. raise MessageRejected() self.redis_was_full = False self.next_step.submit(message) def terminate(self) -> None: self.stopped.value = True self.next_step.terminate() def close(self) -> None: # Do not shut down the flusher here -- this is running at the beginning # of rebalancing, so everytime we are rebalancing we will cause a huge # memory spike in redis self.next_step.close() def join(self, timeout: float | None = None): # set stopped flag first so we can "flush" the background threads while # next_step is also shutting down. we can do two things at once! self.stopped.value = True deadline = time.time() + timeout if timeout else None self.next_step.join(timeout) # Wait for all processes to finish for process_index, process in self.processes.items(): if deadline is not None: remaining_time = deadline - time.time() if remaining_time <= 0: break while process.is_alive() and (deadline is None or deadline > time.time()): time.sleep(0.1) if isinstance(process, multiprocessing.Process): process.terminate()
SpanFlusher
python
PrefectHQ__prefect
tests/client/test_prefect_client.py
{ "start": 84791, "end": 88053 }
class ____: @pytest.fixture async def variable( self, client, ): res = await client.post( "/variables/", json=VariableCreate( name="my_variable", value="my-value", tags=["123", "456"] ).model_dump(mode="json"), ) assert res.status_code == 201 return parse_obj_as(Variable, res.json()) @pytest.fixture async def variables( self, client, ): variables = [ VariableCreate(name="my_variable1", value="my-value1", tags=["1"]), VariableCreate(name="my_variable2", value="my-value2", tags=["2"]), VariableCreate(name="my_variable3", value="my-value3", tags=["3"]), ] results = [] for variable in variables: res = await client.post( "/variables/", json=variable.model_dump(mode="json") ) assert res.status_code == 201 results.append(res.json()) return parse_obj_as(List[Variable], results) @pytest.mark.parametrize( "value", [ "string-value", '"string-value"', 123, 12.3, True, False, None, {"key": "value"}, ["value1", "value2"], {"key": ["value1", "value2"]}, ], ) async def test_create_variable(self, prefect_client, value): created_variable = await prefect_client.create_variable( variable=VariableCreate(name="my_variable", value=value) ) assert created_variable assert created_variable.name == "my_variable" assert created_variable.value == value res = await prefect_client.read_variable_by_name(created_variable.name) assert res.name == created_variable.name assert res.value == value async def test_read_variable_by_name(self, prefect_client, variable): res = await prefect_client.read_variable_by_name(variable.name) assert res.name == variable.name assert res.value == variable.value assert res.tags == variable.tags async def test_read_variable_by_name_doesnt_exist(self, prefect_client): res = await prefect_client.read_variable_by_name("doesnt_exist") assert res is None async def test_delete_variable_by_name(self, prefect_client, variable): await prefect_client.delete_variable_by_name(variable.name) res = await prefect_client.read_variable_by_name(variable.name) assert not res async def test_delete_variable_by_name_doesnt_exist(self, prefect_client): with pytest.raises(prefect.exceptions.ObjectNotFound): await prefect_client.delete_variable_by_name("doesnt_exist") async def test_read_variables(self, prefect_client, variables): res = await prefect_client.read_variables() assert len(res) == len(variables) assert {r.name for r in res} == {v.name for v in variables} async def test_read_variables_with_limit(self, prefect_client, variables): res = await prefect_client.read_variables(limit=1) assert len(res) == 1 assert res[0].name == variables[0].name
TestVariables
python
astropy__astropy
astropy/units/tests/test_quantity_non_ufuncs.py
{ "start": 32390, "end": 34410 }
class ____: def setup_method(self): self.q = np.array([-np.inf, +np.inf, np.nan, 3.0, 4.0]) * u.m def check(self, func): out = func(self.q) expected = func(self.q.value) assert type(out) is np.ndarray assert out.dtype.kind == "b" assert np.all(out == expected) def test_isposinf(self): self.check(np.isposinf) def test_isneginf(self): self.check(np.isneginf) def test_isreal(self): self.check(np.isreal) assert not np.isreal([1.0 + 1j] * u.m) def test_iscomplex(self): self.check(np.iscomplex) assert np.iscomplex([1.0 + 1j] * u.m) def test_isclose(self): q1 = np.arange(3.0) * u.m q2 = np.array([0.0, 102.0, 199.0]) * u.cm atol = 1.5 * u.cm rtol = 1.0 * u.percent out = np.isclose(q1, q2, atol=atol) expected = np.isclose( q1.value, q2.to_value(q1.unit), atol=atol.to_value(q1.unit) ) assert type(out) is np.ndarray assert out.dtype.kind == "b" assert np.all(out == expected) out = np.isclose(q1, q2, atol=0, rtol=rtol) expected = np.isclose(q1.value, q2.to_value(q1.unit), atol=0, rtol=0.01) assert type(out) is np.ndarray assert out.dtype.kind == "b" assert np.all(out == expected) def test_allclose_atol_default_unit(self): q_cm = self.q.to(u.cm) out = np.isclose(self.q, q_cm) expected = np.isclose(self.q.value, q_cm.to_value(u.m)) assert np.all(out == expected) q1 = np.arange(3.0) * u.m q2 = np.array([0.0, 101.0, 198.0]) * u.cm out = np.isclose(q1, q2, atol=0.011, rtol=0) expected = np.isclose(q1.value, q2.to_value(q1.unit), atol=0.011, rtol=0) assert np.all(out == expected) out2 = np.isclose(q2, q1, atol=0.011, rtol=0) expected2 = np.isclose(q2.value, q1.to_value(q2.unit), atol=0.011, rtol=0) assert np.all(out2 == expected2)
TestUfuncLikeTests
python
lepture__authlib
authlib/oauth2/rfc6749/grants/base.py
{ "start": 185, "end": 2715 }
class ____(Hookable): #: Allowed client auth methods for token endpoint TOKEN_ENDPOINT_AUTH_METHODS = ["client_secret_basic"] #: Designed for which "grant_type" GRANT_TYPE = None # NOTE: there is no charset for application/json, since # application/json should always in UTF-8. # The example on RFC is incorrect. # https://tools.ietf.org/html/rfc4627 TOKEN_RESPONSE_HEADER = default_json_headers def __init__(self, request: OAuth2Request, server): super().__init__() self.prompt = None self.redirect_uri = None self.request = request self.server = server @property def client(self): return self.request.client def generate_token( self, user=None, scope=None, grant_type=None, expires_in=None, include_refresh_token=True, ): if grant_type is None: grant_type = self.GRANT_TYPE return self.server.generate_token( client=self.request.client, grant_type=grant_type, user=user, scope=scope, expires_in=expires_in, include_refresh_token=include_refresh_token, ) def authenticate_token_endpoint_client(self): """Authenticate client with the given methods for token endpoint. For example, the client makes the following HTTP request using TLS: .. code-block:: http POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb Default available methods are: "none", "client_secret_basic" and "client_secret_post". :return: client """ client = self.server.authenticate_client( self.request, self.TOKEN_ENDPOINT_AUTH_METHODS ) self.server.send_signal("after_authenticate_client", client=client, grant=self) return client def save_token(self, token): """A method to save token into database.""" return self.server.save_token(token, self.request) def validate_requested_scope(self): """Validate if requested scope is supported by Authorization Server.""" scope = self.request.payload.scope return self.server.validate_requested_scope(scope)
BaseGrant
python
streamlit__streamlit
lib/tests/streamlit/elements/element_policies_test.py
{ "start": 4875, "end": 6485 }
class ____(ElementPoliciesTest): SECTION_DESCRIPTIONS = copy.deepcopy(config._section_descriptions) CONFIG_OPTIONS = copy.deepcopy(config._config_options) def setUp(self): self.patches = [ patch.object( config, "_section_descriptions", new=copy.deepcopy(SpecialSessionStatesTest.SECTION_DESCRIPTIONS), ), patch.object( config, "_config_options", new=copy.deepcopy(SpecialSessionStatesTest.CONFIG_OPTIONS), ), patch.dict(os.environ), ] for p in self.patches: p.start() def tearDown(self): for p in self.patches: p.stop() config._delete_option("_test.tomlTest") @patch("streamlit.runtime.Runtime.exists", MagicMock(return_value=True)) @patch("streamlit.elements.lib.policies.get_session_state") @patch("streamlit.warning") def test_check_session_state_rules_prints_warning( self, patched_st_warning, patched_get_session_state ): mock_session_state = MagicMock() mock_session_state.is_new_state_value.return_value = True patched_get_session_state.return_value = mock_session_state # Reset globale flag: utils._shown_default_value_warning = False check_session_state_rules(5, key=_KEY) patched_st_warning.assert_called_once() args, _ = patched_st_warning.call_args warning_msg = args[0] assert 'The widget with key "the key"' in warning_msg
SpecialSessionStatesTest
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 16422, "end": 16905 }
class ____(LocalizableStreamlitException): """Exception raised when a callback with an invalid name is provided.""" def __init__(self, callback_name: str) -> None: super().__init__( "The callback name `'{callback_name}'` is not allowed. " "Callback names must follow the pattern `on_{{event_name}}_change` " "where `event_name` is not empty.", callback_name=callback_name, )
BidiComponentInvalidCallbackNameError
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 95207, "end": 96795 }
class ____(nn.Module): def __init__( self, d_model=512, nhead=8, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec=False, layer_norm_eps=1e-05, ): super().__init__() decoder_layer = OneFormerTransformerDecoderQueryTransformerDecoderLayer( d_model, nhead, dim_feedforward, dropout, activation, normalize_before, layer_norm_eps ) decoder_norm = nn.LayerNorm(d_model, eps=layer_norm_eps) self.decoder = OneFormerTransformerDecoderQueryTransformerDecoder( decoder_layer, num_decoder_layers, decoder_norm, return_intermediate=return_intermediate_dec, ) self.d_model = d_model self.nhead = nhead def forward(self, src, mask, query_embed, pos_embed, task_token=None): batch_size = src.shape[0] src = src.flatten(2).permute(2, 0, 1) pos_embed = pos_embed.flatten(2).permute(2, 0, 1) query_embed = query_embed.unsqueeze(1).repeat(1, batch_size, 1) if mask is not None: mask = mask.flatten(1) if task_token is None: queries = torch.zeros_like(query_embed) else: queries = task_token.repeat(query_embed.shape[0], 1, 1) queries = self.decoder(queries, src, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed) return queries.transpose(1, 2)
OneFormerTransformerDecoderQueryTransformer
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_alloy_db.py
{ "start": 5218, "end": 7287 }
class ____: def setup_method(self): self.operator = AlloyDBWriteBaseOperator( task_id=TEST_TASK_ID, project_id=TEST_GCP_PROJECT, location=TEST_GCP_REGION, gcp_conn_id=TEST_GCP_CONN_ID, request_id=TEST_REQUEST_ID, validate_request=TEST_VALIDATE_ONLY, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) def test_init(self): assert self.operator.request_id == TEST_REQUEST_ID assert self.operator.validate_request == TEST_VALIDATE_ONLY def test_template_fields(self): expected_template_fields = {"request_id", "validate_request"} | set( AlloyDBBaseOperator.template_fields ) assert set(AlloyDBWriteBaseOperator.template_fields) == expected_template_fields @mock.patch(BASE_WRITE_CLUSTER_OPERATOR_PATH.format("log")) @mock.patch(ALLOY_DB_HOOK_PATH) def test_get_operation_result(self, mock_hook, mock_log): mock_operation = mock.MagicMock() mock_wait_for_operation = mock_hook.return_value.wait_for_operation expected_result = mock_wait_for_operation.return_value result = self.operator.get_operation_result(mock_operation) assert result == expected_result assert not mock_log.called mock_wait_for_operation.assert_called_once_with(timeout=TEST_TIMEOUT, operation=mock_operation) @mock.patch(BASE_WRITE_CLUSTER_OPERATOR_PATH.format("log")) @mock.patch(ALLOY_DB_HOOK_PATH) def test_get_operation_result_validate_result(self, mock_hook, mock_log): mock_operation = mock.MagicMock() mock_wait_for_operation = mock_hook.return_value.wait_for_operation self.operator.validate_request = True result = self.operator.get_operation_result(mock_operation) assert result is None assert not mock_log.info.called assert not mock_wait_for_operation.called
TestAlloyDBWriteBaseOperator
python
google__flatbuffers
tests/service_test_grpc.fb.py
{ "start": 376, "end": 1364 }
class ____(object): """Interface exported by the server.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Hello = channel.unary_unary( method='/example.HelloService/Hello', request_serializer=_serialize_to_bytes, response_deserializer=HelloResponse.GetRootAs, ) self.StreamClient = channel.stream_unary( method='/example.HelloService/StreamClient', request_serializer=_serialize_to_bytes, response_deserializer=HelloResponse.GetRootAs, ) self.StreamServer = channel.unary_stream( method='/example.HelloService/StreamServer', request_serializer=_serialize_to_bytes, response_deserializer=HelloResponse.GetRootAs, ) self.Stream = channel.stream_stream( method='/example.HelloService/Stream', request_serializer=_serialize_to_bytes, response_deserializer=HelloResponse.GetRootAs, )
HelloServiceStub
python
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 5635, "end": 7007 }
class ____(LinksTestCase): link_method = 'link' p = None def cleanup(self): self.p.unlink_all() self.p = None def test_return(self): self.p = gevent.spawn(return25) for _ in range(3): self._test_return(self.p, 25) self.p.kill() def _test_return(self, p, result): event, queue, callback_flag = self.set_links(p) # stuff that will time out because there's no unhandled exception: xxxxx = self.set_links_timeout(p.link_exception) sleep(DELAY * 2) self.assertFalse(p) self.assertEqual(event.get(), result) self.assertEqual(queue.get().get(), result) sleep(DELAY) self.assertFalse(callback_flag) self.check_timed_out(*xxxxx) def _test_kill(self, p): event, queue, callback_flag = self.set_links(p) xxxxx = self.set_links_timeout(p.link_exception) p.kill() sleep(DELAY) self.assertFalse(p) self.assertIsInstance(event.get(), gevent.GreenletExit) self.assertIsInstance(queue.get().get(), gevent.GreenletExit) sleep(DELAY) self.assertFalse(callback_flag) self.check_timed_out(*xxxxx) def test_kill(self): p = self.p = gevent.spawn(sleep, DELAY) for _ in range(3): self._test_kill(p)
TestReturn_link
python
huggingface__transformers
src/transformers/models/nllb_moe/modeling_nllb_moe.py
{ "start": 17631, "end": 19478 }
class ____(nn.Module): r""" Implementation of the NLLB-MoE sparse MLP module. """ def __init__(self, config: NllbMoeConfig, ffn_dim: int): super().__init__() self.router = NllbMoeTop2Router(config) self.num_experts = config.num_experts self.experts = NllbMoeExperts(config, ffn_dim) def forward(self, hidden_states: torch.Tensor, padding_mask: Optional[torch.Tensor] = None): batch_size, sequence_length, hidden_dim = hidden_states.shape hidden_states = hidden_states.view(-1, hidden_dim) top_1_mask, router_probs, _ = self.router(hidden_states, padding_mask) hidden_states = self.experts(hidden_states, top_1_mask, router_probs) return hidden_states.reshape(batch_size, sequence_length, hidden_dim) # Copied from transformers.models.bert.modeling_bert.eager_attention_forward def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: Optional[float] = None, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): if scaling is None: scaling = query.size(-1) ** -0.5 # Take the dot product between "query" and "key" to get the raw attention scores. attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: attention_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights
NllbMoeSparseMLP
python
chroma-core__chroma
chromadb/utils/embedding_functions/jina_embedding_function.py
{ "start": 361, "end": 411 }
class ____(TypedDict): task: str
JinaQueryConfig
python
kamyu104__LeetCode-Solutions
Python/prime-in-diagonal.py
{ "start": 651, "end": 1049 }
class ____(object): def diagonalPrime(self, nums): """ :type nums: List[List[int]] :rtype: int """ result = 0 for i in xrange(len(nums)): if nums[i][i] in PRIMES_SET: result = max(result, nums[i][i]) if nums[i][~i] in PRIMES_SET: result = max(result, nums[i][~i]) return result
Solution
python
aio-libs__aiohttp
aiohttp/helpers.py
{ "start": 30021, "end": 33257 }
class ____: """Mixin for handling cookies.""" _cookies: SimpleCookie | None = None @property def cookies(self) -> SimpleCookie: if self._cookies is None: self._cookies = SimpleCookie() return self._cookies def set_cookie( self, name: str, value: str, *, expires: str | None = None, domain: str | None = None, max_age: int | str | None = None, path: str = "/", secure: bool | None = None, httponly: bool | None = None, samesite: str | None = None, partitioned: bool | None = None, ) -> None: """Set or update response cookie. Sets new cookie or updates existent with new value. Also updates only those params which are not None. """ if self._cookies is None: self._cookies = SimpleCookie() self._cookies[name] = value c = self._cookies[name] if expires is not None: c["expires"] = expires elif c.get("expires") == "Thu, 01 Jan 1970 00:00:00 GMT": del c["expires"] if domain is not None: c["domain"] = domain if max_age is not None: c["max-age"] = str(max_age) elif "max-age" in c: del c["max-age"] c["path"] = path if secure is not None: c["secure"] = secure if httponly is not None: c["httponly"] = httponly if samesite is not None: c["samesite"] = samesite if partitioned is not None: c["partitioned"] = partitioned if DEBUG: cookie_length = len(c.output(header="")[1:]) if cookie_length > COOKIE_MAX_LENGTH: warnings.warn( "The size of is too large, it might get ignored by the client.", UserWarning, stacklevel=2, ) def del_cookie( self, name: str, *, domain: str | None = None, path: str = "/", secure: bool | None = None, httponly: bool | None = None, samesite: str | None = None, ) -> None: """Delete cookie. Creates new empty expired cookie. """ # TODO: do we need domain/path here? if self._cookies is not None: self._cookies.pop(name, None) self.set_cookie( name, "", max_age=0, expires="Thu, 01 Jan 1970 00:00:00 GMT", domain=domain, path=path, secure=secure, httponly=httponly, samesite=samesite, ) def populate_with_cookies(headers: "CIMultiDict[str]", cookies: SimpleCookie) -> None: for cookie in cookies.values(): value = cookie.output(header="")[1:] headers.add(hdrs.SET_COOKIE, value) # https://tools.ietf.org/html/rfc7232#section-2.3 _ETAGC = r"[!\x23-\x7E\x80-\xff]+" _ETAGC_RE = re.compile(_ETAGC) _QUOTED_ETAG = rf'(W/)?"({_ETAGC})"' QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG) LIST_QUOTED_ETAG_RE = re.compile(rf"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)") ETAG_ANY = "*" @frozen_dataclass_decorator
CookieMixin