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
catalyst-team__catalyst
catalyst/contrib/losses/circle.py
{ "start": 706, "end": 2600 }
class ____(nn.Module): """ CircleLoss from `Circle Loss: A Unified Perspective of Pair Similarity Optimization`_ paper. Adapter from: https://github.com/TinyZeaMays/CircleLoss Example: >>> import torch >>> from torch.nn import functional as F >>> from catalyst.contrib.losses import CircleLoss >>> >>> features = F.normalize(torch.rand(256, 64, requires_grad=True)) >>> labels = torch.randint(high=10, size=(256)) >>> criterion = CircleLoss(margin=0.25, gamma=256) >>> criterion(features, labels) .. _`Circle Loss: A Unified Perspective of Pair Similarity Optimization`: https://arxiv.org/abs/2002.10857 """ def __init__(self, margin: float, gamma: float) -> None: """ Args: margin: margin to use gamma: gamma to use """ super().__init__() self.margin = margin self.gamma = gamma self.soft_plus = nn.Softplus() def forward(self, normed_features: Tensor, labels: Tensor) -> Tensor: """ Args: normed_features: batch with samples features of shape [bs; feature_len] labels: batch with samples correct labels of shape [bs; ] Returns: torch.Tensor: circle loss """ sp, sn = _convert_label_to_similarity(normed_features, labels) ap = torch.clamp_min(-sp.detach() + 1 + self.margin, min=0.0) an = torch.clamp_min(sn.detach() + self.margin, min=0.0) delta_p = 1 - self.margin delta_n = self.margin logit_p = -ap * (sp - delta_p) * self.gamma logit_n = an * (sn - delta_n) * self.gamma loss = self.soft_plus( torch.logsumexp(logit_n, dim=0) + torch.logsumexp(logit_p, dim=0) ) return loss __all__ = ["CircleLoss"]
CircleLoss
python
huggingface__transformers
src/transformers/models/smolvlm/configuration_smolvlm.py
{ "start": 5401, "end": 9071 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`SmolVLMModel`]. It is used to instantiate a SmolVLM model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the model of the SmolVLM [HuggingFaceTB/SmolVLM2-2.2B-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM2-2.2B-Instruct) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should cache the key/value pairs of the attention mechanism. Only relevant if `config.is_decoder=True`. image_token_id (`int`, *optional*, defaults to 128257): The id of the "image" token. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether or not to tie the word embeddings with the token embeddings. vision_config (`IdeficsVisionConfig` or `dict`, *optional*, defaults to `IdeficsVisionConfig`): Custom vision config or dict for the vision tower text_config (`PreTrainedConfig` or `dict`, *optional*, defaults to `LlamaConfig`): Custom text config or dict for the text model scale_factor (`int`, *optional*, defaults to 2): The scale factor for the image encoder. pad_token_id (`int`, *optional*, defaults to 128002): The id of the padding token. Example: ```python >>> from transformers import SmolVLMModel, SmolVLMConfig >>> # Initializing configuration >>> configuration = SmolVLMConfig() >>> # Initializing a model from the configuration >>> model = SmolVLMModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "smolvlm" sub_configs = {"text_config": AutoConfig, "vision_config": SmolVLMVisionConfig} def __init__( self, use_cache=True, image_token_id=128257, tie_word_embeddings=False, vision_config=None, text_config=None, scale_factor=2, pad_token_id=128_002, **kwargs, ): self.image_token_id = image_token_id self.use_cache = use_cache self.tie_word_embeddings = tie_word_embeddings if vision_config is None: self.vision_config = SmolVLMVisionConfig() logger.info("vision_config is None, using default vision config") elif isinstance(vision_config, dict): self.vision_config = SmolVLMVisionConfig(**vision_config) elif isinstance(vision_config, SmolVLMVisionConfig): self.vision_config = vision_config if isinstance(text_config, dict): text_config["model_type"] = text_config.get("model_type", "llama") text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) elif text_config is None: logger.info("text_config is None, using default text config") text_config = CONFIG_MAPPING["llama"]( rms_norm_eps=1e-5, pad_token_id=pad_token_id, tie_word_embeddings=False, ) self.text_config = text_config self.scale_factor = scale_factor super().__init__(**kwargs, pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings) __all__ = ["SmolVLMVisionConfig", "SmolVLMConfig"]
SmolVLMConfig
python
google__pytype
pytype/tests/test_errors_format.py
{ "start": 236, "end": 3722 }
class ____(test_base.BaseTest): """Tests for errors.""" def test_error_format(self): errors = self.CheckWithErrors(""" def f(x): y = 42 y.foobar # attribute-error[e] """) message = textwrap.dedent("""\ dummy_input_file:3:3: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: in f: No attribute 'foobar' on int [attribute-error] y.foobar # attribute-error[e] \x1b[1m\x1b[31m~~~~~~~~\x1b[39m\x1b[0m """) self.assertDiagnosticMessages(errors, {"e": message}) def test_error_format_with_no_end_line_late_directive_error(self): errors = self.CheckWithErrors(""" def f() -> bool: # pytype: disable=bad-return-type # late-directive[e] return 42 """) message = textwrap.dedent("""\ dummy_input_file:2:1: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: : bad-return-type disabled from here to the end of the file [late-directive] Consider limiting this directive's scope or moving it to the top of the file. # pytype: disable=bad-return-type # late-directive[e] \x1b[1m\x1b[31m~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1b[39m\x1b[0m """) self.assertDiagnosticMessages(errors, {"e": message}) def test_error_format_with_no_end_line_redundant_function_type_comment_error( self, ): errors = self.CheckWithErrors(""" def f() -> None: # type: () -> None # redundant-function-type-comment[e] pass """) message = textwrap.dedent("""\ dummy_input_file:2:1: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: : Function type comments cannot be used with annotations [redundant-function-type-comment] # type: () -> None # redundant-function-type-comment[e] \x1b[1m\x1b[31m~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1b[39m\x1b[0m """) self.assertDiagnosticMessages(errors, {"e": message}) def test_error_format_with_source(self): errors = self.CheckWithErrors(""" from typing import List def foo(args: List[str]) -> None: for arg in args: print(arg + 3) # unsupported-operands[e] """) message = textwrap.dedent("""\ dummy_input_file:4:11: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: in foo: unsupported operand type(s) for +: str and int [unsupported-operands] Function __add__ on str expects str print(arg + 3) # unsupported-operands[e] \x1b[1m\x1b[31m~~~~~~~\x1b[39m\x1b[0m """) self.assertDiagnosticMessages(errors, {"e": message}) def test_error_format_with_source_multiple_lines(self): errors = self.CheckWithErrors(""" from typing import List def foo(args: List[str]) -> None: for arg in args: print(arg # unsupported-operands[e] + 3) """) message = textwrap.dedent("""\ dummy_input_file:4:11: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: in foo: unsupported operand type(s) for +: str and int [unsupported-operands] Function __add__ on str expects str print(arg # unsupported-operands[e] \x1b[1m\x1b[31m~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\x1b[39m\x1b[0m + \x1b[1m\x1b[31m~~~~~~~\x1b[39m\x1b[0m 3) \x1b[1m\x1b[31m~~~~~\x1b[39m\x1b[0m """) self.assertDiagnosticMessages(errors, {"e": message}) # TODO: b/338455486 - Add a test case for diagnostic missing a filepath # information if __name__ == "__main__": test_base.main()
ErrorTest
python
facebook__pyre-check
tools/typeshed_patcher/patch_specs.py
{ "start": 490, "end": 1187 }
class ____(Exception): pass def _read_string(input_object: object, field_name: Optional[str] = None) -> str: if not isinstance(input_object, str): field_message = f" for field `{field_name}`" if field_name is not None else "" raise ReadPatchException( f"Expect a string{field_message} but got {input_object}" ) return input_object def _ensure_string_value(input_object: Mapping[str, object], field_name: str) -> str: if field_name not in input_object: raise ReadPatchException(f"Missing required field `{field_name}`") return _read_string(input_object[field_name], field_name) @dataclasses.dataclass(frozen=True)
ReadPatchException
python
django__django
tests/proxy_models/models.py
{ "start": 4011, "end": 4120 }
class ____(Bug): """ Proxy of an inherited class """ class Meta: proxy = True
ProxyBug
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 50462, "end": 51418 }
class ____(ModelOutput): r""" loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`): Total loss prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, patch_length)`): Prediction output from the pretrain head. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, d_model)`): Backbone embeddings before passing through the head. hidden_states (`tuple(torch.FloatTensor)`, *optional*): Hidden-states of the model at the output of each layer. """ loss: Optional[torch.FloatTensor] = None prediction_outputs: Optional[torch.FloatTensor] = None last_hidden_state: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor]] = None @auto_docstring( custom_intro=""" `PatchTSMixer` for mask pretraining. """ )
PatchTSMixerForPreTrainingOutput
python
doocs__leetcode
solution/2600-2699/2642.Design Graph With Shortest Path Calculator/Solution.py
{ "start": 0, "end": 946 }
class ____: def __init__(self, n: int, edges: List[List[int]]): self.n = n self.g = [[inf] * n for _ in range(n)] for f, t, c in edges: self.g[f][t] = c def addEdge(self, edge: List[int]) -> None: f, t, c = edge self.g[f][t] = c def shortestPath(self, node1: int, node2: int) -> int: dist = [inf] * self.n dist[node1] = 0 vis = [False] * self.n for _ in range(self.n): t = -1 for j in range(self.n): if not vis[j] and (t == -1 or dist[t] > dist[j]): t = j vis[t] = True for j in range(self.n): dist[j] = min(dist[j], dist[t] + self.g[t][j]) return -1 if dist[node2] == inf else dist[node2] # Your Graph object will be instantiated and called as such: # obj = Graph(n, edges) # obj.addEdge(edge) # param_2 = obj.shortestPath(node1,node2)
Graph
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 49812, "end": 54379 }
class ____(Request): """ Return the debug image per metric and variant for the provided iteration :param task: Task ID :type task: str :param metric: Metric name :type metric: str :param variant: Metric variant :type variant: str :param iteration: The iteration to bring debug image from. If not specified then the latest reported image is retrieved :type iteration: int :param refresh: If set then scroll state will be refreshed to reflect the latest changes in the debug images :type refresh: bool :param scroll_id: Scroll ID from the previous call to get_debug_image_sample or empty :type scroll_id: str """ _service = "events" _action = "get_debug_image_sample" _version = "2.13" _schema = { "definitions": {}, "properties": { "iteration": { "description": "The iteration to bring debugimage from. If not specifiedthen the latest reported imageis retrieved", "type": "integer", }, "metric": {"description": "Metric name", "type": "string"}, "refresh": { "description": "If set then scroll state will berefreshed to reflect the latestchanges in the debug images", "type": "boolean", }, "scroll_id": { "description": "Scroll ID from the previous callto get_debug_image_sample orempty", "type": "string", }, "task": {"description": "Task ID", "type": "string"}, "variant": {"description": "Metric variant", "type": "string"}, }, "required": ["task", "metric", "variant"], "type": "object", } def __init__( self, task: str, metric: str, variant: str, iteration: Optional[int] = None, refresh: Optional[bool] = None, scroll_id: Optional[str] = None, **kwargs: Any ) -> None: super(GetDebugImageSampleRequest, self).__init__(**kwargs) self.task = task self.metric = metric self.variant = variant self.iteration = iteration self.refresh = refresh self.scroll_id = scroll_id @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("metric") def metric(self) -> str: return self._property_metric @metric.setter def metric(self, value: str) -> None: if value is None: self._property_metric = None return self.assert_isinstance(value, "metric", six.string_types) self._property_metric = value @schema_property("variant") def variant(self) -> str: return self._property_variant @variant.setter def variant(self, value: str) -> None: if value is None: self._property_variant = None return self.assert_isinstance(value, "variant", six.string_types) self._property_variant = value @schema_property("iteration") def iteration(self) -> Optional[int]: return self._property_iteration @iteration.setter def iteration(self, value: Optional[int]) -> None: if value is None: self._property_iteration = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "iteration", six.integer_types) self._property_iteration = value @schema_property("refresh") def refresh(self) -> Optional[bool]: return self._property_refresh @refresh.setter def refresh(self, value: Optional[bool]) -> None: if value is None: self._property_refresh = None return self.assert_isinstance(value, "refresh", (bool,)) self._property_refresh = value @schema_property("scroll_id") def scroll_id(self) -> Optional[str]: return self._property_scroll_id @scroll_id.setter def scroll_id(self, value: Optional[str]) -> None: if value is None: self._property_scroll_id = None return self.assert_isinstance(value, "scroll_id", six.string_types) self._property_scroll_id = value
GetDebugImageSampleRequest
python
django__django
django/db/migrations/exceptions.py
{ "start": 502, "end": 603 }
class ____(ValueError): """A model's base classes can't be resolved.""" pass
InvalidBasesError
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 60419, "end": 67634 }
class ____: @mock.patch("google.cloud.aiplatform.datasets.TimeSeriesDataset") @mock.patch(VERTEX_AI_PATH.format("auto_ml.AutoMLHook")) def test_execute(self, mock_hook, mock_dataset): mock_hook.return_value.create_auto_ml_forecasting_training_job.return_value = (None, "training_id") op = CreateAutoMLForecastingTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, display_name=DISPLAY_NAME, dataset_id=TEST_DATASET_ID, target_column=TEST_TRAINING_TARGET_COLUMN, time_column=TEST_TRAINING_TIME_COLUMN, time_series_identifier_column=TEST_TRAINING_TIME_SERIES_IDENTIFIER_COLUMN, unavailable_at_forecast_columns=TEST_TRAINING_UNAVAILABLE_AT_FORECAST_COLUMNS, available_at_forecast_columns=TEST_TRAINING_AVAILABLE_AT_FORECAST_COLUMNS, forecast_horizon=TEST_TRAINING_FORECAST_HORIZON, data_granularity_unit=TEST_TRAINING_DATA_GRANULARITY_UNIT, data_granularity_count=TEST_TRAINING_DATA_GRANULARITY_COUNT, sync=True, region=GCP_LOCATION, project_id=GCP_PROJECT, parent_model=TEST_PARENT_MODEL, holiday_regions=TEST_TRAINING_DATA_HOLIDAY_REGIONS, ) op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()}) mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN) mock_dataset.assert_called_once_with(dataset_name=TEST_DATASET_ID) mock_hook.return_value.create_auto_ml_forecasting_training_job.assert_called_once_with( project_id=GCP_PROJECT, region=GCP_LOCATION, display_name=DISPLAY_NAME, dataset=mock_dataset.return_value, target_column=TEST_TRAINING_TARGET_COLUMN, time_column=TEST_TRAINING_TIME_COLUMN, time_series_identifier_column=TEST_TRAINING_TIME_SERIES_IDENTIFIER_COLUMN, unavailable_at_forecast_columns=TEST_TRAINING_UNAVAILABLE_AT_FORECAST_COLUMNS, available_at_forecast_columns=TEST_TRAINING_AVAILABLE_AT_FORECAST_COLUMNS, forecast_horizon=TEST_TRAINING_FORECAST_HORIZON, data_granularity_unit=TEST_TRAINING_DATA_GRANULARITY_UNIT, data_granularity_count=TEST_TRAINING_DATA_GRANULARITY_COUNT, parent_model=TEST_PARENT_MODEL, optimization_objective=None, column_specs=None, column_transformations=None, labels=None, training_encryption_spec_key_name=None, model_encryption_spec_key_name=None, training_fraction_split=None, validation_fraction_split=None, test_fraction_split=None, predefined_split_column_name=None, weight_column=None, time_series_attribute_columns=None, context_window=None, export_evaluated_data_items=False, export_evaluated_data_items_bigquery_destination_uri=None, export_evaluated_data_items_override_destination=False, quantiles=None, validation_options=None, budget_milli_node_hours=1000, model_display_name=None, model_labels=None, sync=True, is_default_version=None, model_version_aliases=None, model_version_description=None, window_stride_length=None, window_max_count=None, holiday_regions=TEST_TRAINING_DATA_HOLIDAY_REGIONS, ) @mock.patch("google.cloud.aiplatform.datasets.TimeSeriesDataset") @mock.patch(VERTEX_AI_PATH.format("auto_ml.AutoMLHook")) def test_execute__parent_model_version_index_is_removed(self, mock_hook, mock_dataset): mock_hook.return_value.create_auto_ml_forecasting_training_job.return_value = (None, "training_id") op = CreateAutoMLForecastingTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, display_name=DISPLAY_NAME, dataset_id=TEST_DATASET_ID, target_column=TEST_TRAINING_TARGET_COLUMN, time_column=TEST_TRAINING_TIME_COLUMN, time_series_identifier_column=TEST_TRAINING_TIME_SERIES_IDENTIFIER_COLUMN, unavailable_at_forecast_columns=TEST_TRAINING_UNAVAILABLE_AT_FORECAST_COLUMNS, available_at_forecast_columns=TEST_TRAINING_AVAILABLE_AT_FORECAST_COLUMNS, forecast_horizon=TEST_TRAINING_FORECAST_HORIZON, data_granularity_unit=TEST_TRAINING_DATA_GRANULARITY_UNIT, data_granularity_count=TEST_TRAINING_DATA_GRANULARITY_COUNT, sync=True, region=GCP_LOCATION, project_id=GCP_PROJECT, parent_model=VERSIONED_TEST_PARENT_MODEL, holiday_regions=TEST_TRAINING_DATA_HOLIDAY_REGIONS, ) op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()}) mock_hook.return_value.create_auto_ml_forecasting_training_job.assert_called_once_with( project_id=GCP_PROJECT, region=GCP_LOCATION, display_name=DISPLAY_NAME, dataset=mock_dataset.return_value, target_column=TEST_TRAINING_TARGET_COLUMN, time_column=TEST_TRAINING_TIME_COLUMN, time_series_identifier_column=TEST_TRAINING_TIME_SERIES_IDENTIFIER_COLUMN, unavailable_at_forecast_columns=TEST_TRAINING_UNAVAILABLE_AT_FORECAST_COLUMNS, available_at_forecast_columns=TEST_TRAINING_AVAILABLE_AT_FORECAST_COLUMNS, forecast_horizon=TEST_TRAINING_FORECAST_HORIZON, data_granularity_unit=TEST_TRAINING_DATA_GRANULARITY_UNIT, data_granularity_count=TEST_TRAINING_DATA_GRANULARITY_COUNT, parent_model=TEST_PARENT_MODEL, optimization_objective=None, column_specs=None, column_transformations=None, labels=None, training_encryption_spec_key_name=None, model_encryption_spec_key_name=None, training_fraction_split=None, validation_fraction_split=None, test_fraction_split=None, predefined_split_column_name=None, weight_column=None, time_series_attribute_columns=None, context_window=None, export_evaluated_data_items=False, export_evaluated_data_items_bigquery_destination_uri=None, export_evaluated_data_items_override_destination=False, quantiles=None, validation_options=None, budget_milli_node_hours=1000, model_display_name=None, model_labels=None, sync=True, is_default_version=None, model_version_aliases=None, model_version_description=None, window_stride_length=None, window_max_count=None, holiday_regions=TEST_TRAINING_DATA_HOLIDAY_REGIONS, )
TestVertexAICreateAutoMLForecastingTrainingJobOperator
python
huggingface__transformers
src/transformers/models/idefics3/modeling_idefics3.py
{ "start": 18370, "end": 21139 }
class ____(Idefics3PreTrainedModel): config: Idefics3VisionConfig input_modalities = ("image",) _supports_sdpa = True _supports_flash_attn = True _supports_flex_attn = True _can_record_outputs = { "hidden_states": Idefics3EncoderLayer, "attentions": Idefics3VisionAttention, } def __init__(self, config: Idefics3VisionConfig): super().__init__(config) embed_dim = config.hidden_size self.embeddings = Idefics3VisionEmbeddings(config) self.encoder = Idefics3Encoder(config) self.patch_size = config.patch_size self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2VisionTransformer.get_input_embeddings def get_input_embeddings(self): return self.embeddings # Copied from transformers.models.idefics2.modeling_idefics2.Idefics2VisionTransformer.set_input_embeddings def set_input_embeddings(self, value): self.embeddings = value @check_model_inputs(tie_last_hidden_states=False) def forward( self, pixel_values, patch_attention_mask: Optional[torch.BoolTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutput]: batch_size = pixel_values.size(0) if patch_attention_mask is None: patch_size = self.patch_size patch_attention_mask = torch.ones( ( batch_size, pixel_values.size(2) // patch_size, pixel_values.size(3) // patch_size, ) ) patch_attention_mask = patch_attention_mask.to(dtype=torch.bool, device=pixel_values.device) hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask) patch_attention_mask = patch_attention_mask.view(batch_size, -1) # Create the correct attention mask based on the attention implementation patch_attention_mask = create_bidirectional_mask( config=self.config, input_embeds=hidden_states, attention_mask=patch_attention_mask, ) encoder_outputs: BaseModelOutput = self.encoder( inputs_embeds=hidden_states, attention_mask=patch_attention_mask, ) last_hidden_state = encoder_outputs.last_hidden_state last_hidden_state = self.post_layernorm(last_hidden_state) return BaseModelOutput( last_hidden_state=last_hidden_state, ) @auto_docstring( custom_intro=""" Idefics3 model consisting of a SIGLIP vision encoder and Llama3 language decoder """ )
Idefics3VisionTransformer
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/attach_features.py
{ "start": 997, "end": 1483 }
class ____: def method_with_optionals(self, a: int = 0, b: int = 1) -> None: _test_sink(b) def attach_to_returned_sink(): x = _test_source() return x def attach_to_returned_source(): return 0 def attach_to_returned_source_2(): return 0 def attach_to_returned_with_captures(): x = 0 def nested(): nonlocal x x = _test_source() return 0 return nested() def attach_to_parameter_source(x): _test_sink(x)
HasMethods
python
kamyu104__LeetCode-Solutions
Python/number-of-subarrays-that-match-a-pattern-i.py
{ "start": 35, "end": 1119 }
class ____(object): def countMatchingSubarrays(self, nums, pattern): """ :type nums: List[int] :type pattern: List[int] :rtype: int """ def getPrefix(pattern): prefix = [-1]*len(pattern) j = -1 for i in xrange(1, len(pattern)): while j+1 > 0 and pattern[j+1] != pattern[i]: j = prefix[j] if pattern[j+1] == pattern[i]: j += 1 prefix[i] = j return prefix def KMP(text, pattern): prefix = getPrefix(pattern) j = -1 for i, x in enumerate(text): while j+1 > 0 and pattern[j+1] != x: j = prefix[j] if pattern[j+1] == x: j += 1 if j+1 == len(pattern): yield i-j j = prefix[j] return sum(1 for _ in KMP((cmp(nums[i+1], nums[i]) for i in xrange(len(nums)-1)), pattern)) # Time: O(n * m) # Space: O(1) # brute force
Solution
python
getsentry__sentry
tests/sentry/integrations/github/tasks/test_link_all_repos.py
{ "start": 919, "end": 9703 }
class ____(IntegrationTestCase): provider = GitHubIntegrationProvider base_url = "https://api.github.com" key = "github" def _add_responses(self): responses.add( responses.GET, self.base_url + "/installation/repositories?per_page=100", status=200, json={ "total_count": 2, "repositories": [ { "id": 1, "full_name": "getsentry/sentry", }, { "id": 2, "full_name": "getsentry/snuba", }, ], }, ) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_all_repos_inactive_integration( self, mock_record: MagicMock, _: MagicMock ) -> None: self.integration.update(status=ObjectStatus.DISABLED) link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) assert_slo_metric(mock_record, EventLifecycleOutcome.FAILURE) assert_failure_metric(mock_record, LinkAllReposHaltReason.MISSING_INTEGRATION.value) @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_all_repos(self, mock_record: MagicMock, _: MagicMock) -> None: self._add_responses() link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) with assume_test_silo_mode(SiloMode.REGION): repos = Repository.objects.all() assert len(repos) == 2 for repo in repos: assert repo.organization_id == self.organization.id assert repo.provider == "integrations:github" assert repos[0].name == "getsentry/sentry" assert repos[1].name == "getsentry/snuba" assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS) @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_all_repos_api_response_keyerror( self, mock_record: MagicMock, _: MagicMock ) -> None: responses.add( responses.GET, self.base_url + "/installation/repositories?per_page=100", status=200, json={ "total_count": 2, "repositories": [ { "full_name": "getsentry/sentry", }, { "id": 2, "full_name": "getsentry/snuba", }, ], }, ) link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) with assume_test_silo_mode(SiloMode.REGION): repos = Repository.objects.all() assert len(repos) == 1 assert repos[0].organization_id == self.organization.id assert repos[0].provider == "integrations:github" assert repos[0].name == "getsentry/snuba" assert_slo_metric(mock_record, EventLifecycleOutcome.HALTED) assert_halt_metric( mock_record, LinkAllReposHaltReason.REPOSITORY_NOT_CREATED.value ) # should be halt because it didn't complete successfully @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_all_repos_api_response_keyerror_single_repo( self, mock_record: MagicMock, _: MagicMock ) -> None: responses.add( responses.GET, self.base_url + "/installation/repositories?per_page=100", status=200, json={ "total_count": 2, "repositories": [ { "full_name": "getsentry/sentry", }, ], }, ) link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) with assume_test_silo_mode(SiloMode.REGION): repos = Repository.objects.all() assert len(repos) == 0 assert_slo_metric(mock_record, EventLifecycleOutcome.HALTED) assert_halt_metric(mock_record, LinkAllReposHaltReason.REPOSITORY_NOT_CREATED.value) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_all_repos_missing_integration(self, mock_record: MagicMock, _: MagicMock) -> None: link_all_repos( integration_key=self.key, integration_id=0, organization_id=self.organization.id, ) assert_slo_metric(mock_record, EventLifecycleOutcome.FAILURE) assert_failure_metric(mock_record, LinkAllReposHaltReason.MISSING_INTEGRATION.value) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_link_all_repos_missing_organization( self, mock_record: MagicMock, _: MagicMock ) -> None: link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=0, ) assert_slo_metric(mock_record, EventLifecycleOutcome.FAILURE) assert_failure_metric(mock_record, LinkAllReposHaltReason.MISSING_ORGANIZATION.value) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") @responses.activate def test_link_all_repos_api_error(self, mock_record: MagicMock, _: MagicMock) -> None: responses.add( responses.GET, self.base_url + "/installation/repositories?per_page=100", status=400, ) with pytest.raises(RetryTaskError): link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) assert_slo_metric(mock_record, EventLifecycleOutcome.FAILURE) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") @responses.activate def test_link_all_repos_api_error_rate_limited( self, mock_record: MagicMock, _: MagicMock ) -> None: responses.add( responses.GET, self.base_url + "/installation/repositories?per_page=100", status=400, json={ "message": "API rate limit exceeded", "documentation_url": "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting", }, ) link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) assert_slo_metric(mock_record, EventLifecycleOutcome.HALTED) assert_halt_metric(mock_record, LinkAllReposHaltReason.RATE_LIMITED.value) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") @patch("sentry.models.Repository.objects.create") @responses.activate def test_link_all_repos_repo_creation_error( self, mock_repo: MagicMock, mock_record: MagicMock, _: MagicMock ) -> None: mock_repo.side_effect = IntegrityError self._add_responses() link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) assert_slo_metric(mock_record, EventLifecycleOutcome.HALTED) assert_halt_metric(mock_record, LinkAllReposHaltReason.REPOSITORY_NOT_CREATED.value) @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") @patch("sentry.integrations.services.repository.repository_service.create_repository") @patch("sentry.plugins.providers.IntegrationRepositoryProvider.on_delete_repository") @responses.activate def test_link_all_repos_repo_creation_exception( self, mock_delete_repo, mock_create_repository, mock_record, _ ): mock_create_repository.return_value = None mock_delete_repo.side_effect = Exception self._add_responses() with pytest.raises(Exception): link_all_repos( integration_key=self.key, integration_id=self.integration.id, organization_id=self.organization.id, ) assert_slo_metric(mock_record, EventLifecycleOutcome.FAILURE)
LinkAllReposTestCase
python
PrefectHQ__prefect
tests/docker/test_public_api.py
{ "start": 188, "end": 415 }
class ____(TestCase): """this is a regression test for https://github.com/PrefectHQ/prefect/issues/16171""" def test_warning(self): with self.assertWarns(UserWarning): function_that_warns()
TestWarnings
python
numba__llvmlite
llvmlite/ir/values.py
{ "start": 18150, "end": 20458 }
class ____(NamedValue): """ A debug information descriptor, containing key-value pairs. Do not instantiate directly, use Module.add_debug_info() instead. """ name_prefix = '!' def __init__(self, parent, is_distinct, kind, operands, name): super(DIValue, self).__init__(parent, types.MetaDataType(), name=name) self.is_distinct = is_distinct self.kind = kind self.operands = tuple(operands) parent.metadata.append(self) def descr(self, buf): if self.is_distinct: buf += ("distinct ",) operands = [] for key, value in self.operands: if value is None: strvalue = "null" elif value is True: strvalue = "true" elif value is False: strvalue = "false" elif isinstance(value, DIToken): strvalue = value.value elif isinstance(value, str): strvalue = '"{}"'.format(_escape_string(value)) elif isinstance(value, int): strvalue = str(value) elif isinstance(value, Constant): # Support for typed constants (e.g., i32 1, i8 2) # This calls Constant._to_string() which formats as "type value" strvalue = str(value) elif isinstance(value, NamedValue): strvalue = value.get_reference() else: raise TypeError("invalid operand type for debug info: %r" % (value,)) operands.append("{0}: {1}".format(key, strvalue)) operands = ', '.join(operands) buf += ("!", self.kind, "(", operands, ")\n") def _get_reference(self): return self.name_prefix + str(self.name) def __eq__(self, other): if isinstance(other, DIValue): return self.is_distinct == other.is_distinct and \ self.kind == other.kind and \ self.operands == other.operands else: return False def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash((self.is_distinct, self.kind, self.operands))
DIValue
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/cloud_run.py
{ "start": 10415, "end": 12751 }
class ____(GoogleBaseAsyncHook): """ Async hook for the Google Cloud Run services. :param gcp_conn_id: The connection ID to use when fetching connection info. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account. """ sync_hook_class = CloudRunServiceHook def __init__( self, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ): self._client: ServicesClient | None = None super().__init__(gcp_conn_id=gcp_conn_id, impersonation_chain=impersonation_chain, **kwargs) def get_conn(self): if self._client is None: self._client = ServicesAsyncClient(credentials=self.get_credentials(), client_info=CLIENT_INFO) return self._client @GoogleBaseHook.fallback_to_default_project_id async def create_service( self, service_name: str, service: Service | dict, region: str, project_id: str = PROVIDE_PROJECT_ID ) -> AsyncOperation: if isinstance(service, dict): service = Service(service) create_request = CreateServiceRequest( parent=f"projects/{project_id}/locations/{region}", service=service, service_id=service_name, ) return await self.get_conn().create_service(create_request) @GoogleBaseHook.fallback_to_default_project_id async def delete_service( self, service_name: str, region: str, project_id: str = PROVIDE_PROJECT_ID ) -> AsyncOperation: delete_request = DeleteServiceRequest( name=f"projects/{project_id}/locations/{region}/services/{service_name}" ) return await self.get_conn().delete_service(delete_request)
CloudRunServiceAsyncHook
python
matplotlib__matplotlib
lib/matplotlib/patches.py
{ "start": 32379, "end": 33728 }
class ____(Patch): """A regular polygon patch.""" def __str__(self): s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)" return s % (self.xy[0], self.xy[1], self.numvertices, self.radius, self.orientation) @_docstring.interpd def __init__(self, xy, numVertices, *, radius=5, orientation=0, **kwargs): """ Parameters ---------- xy : (float, float) The center position. numVertices : int The number of vertices. radius : float The distance from the center to each of the vertices. orientation : float The polygon rotation angle (in radians). **kwargs `Patch` properties: %(Patch:kwdoc)s """ self.xy = xy self.numvertices = numVertices self.orientation = orientation self.radius = radius self._path = Path.unit_regular_polygon(numVertices) self._patch_transform = transforms.Affine2D() super().__init__(**kwargs) def get_path(self): return self._path def get_patch_transform(self): return self._patch_transform.clear() \ .scale(self.radius) \ .rotate(self.orientation) \ .translate(*self.xy)
RegularPolygon
python
sympy__sympy
sympy/functions/elementary/trigonometric.py
{ "start": 115946, "end": 122110 }
class ____(InverseTrigonometricFunction): r""" The function ``atan2(y, x)`` computes `\operatorname{atan}(y/x)` taking two arguments `y` and `x`. Signs of both `y` and `x` are considered to determine the appropriate quadrant of `\operatorname{atan}(y/x)`. The range is `(-\pi, \pi]`. The complete definition reads as follows: .. math:: \operatorname{atan2}(y, x) = \begin{cases} \arctan\left(\frac y x\right) & \qquad x > 0 \\ \arctan\left(\frac y x\right) + \pi& \qquad y \ge 0, x < 0 \\ \arctan\left(\frac y x\right) - \pi& \qquad y < 0, x < 0 \\ +\frac{\pi}{2} & \qquad y > 0, x = 0 \\ -\frac{\pi}{2} & \qquad y < 0, x = 0 \\ \text{undefined} & \qquad y = 0, x = 0 \end{cases} Attention: Note the role reversal of both arguments. The `y`-coordinate is the first argument and the `x`-coordinate the second. If either `x` or `y` is complex: .. math:: \operatorname{atan2}(y, x) = -i\log\left(\frac{x + iy}{\sqrt{x^2 + y^2}}\right) Examples ======== Going counter-clock wise around the origin we find the following angles: >>> from sympy import atan2 >>> atan2(0, 1) 0 >>> atan2(1, 1) pi/4 >>> atan2(1, 0) pi/2 >>> atan2(1, -1) 3*pi/4 >>> atan2(0, -1) pi >>> atan2(-1, -1) -3*pi/4 >>> atan2(-1, 0) -pi/2 >>> atan2(-1, 1) -pi/4 which are all correct. Compare this to the results of the ordinary `\operatorname{atan}` function for the point `(x, y) = (-1, 1)` >>> from sympy import atan, S >>> atan(S(1)/-1) -pi/4 >>> atan2(1, -1) 3*pi/4 where only the `\operatorname{atan2}` function returns what we expect. We can differentiate the function with respect to both arguments: >>> from sympy import diff >>> from sympy.abc import x, y >>> diff(atan2(y, x), x) -y/(x**2 + y**2) >>> diff(atan2(y, x), y) x/(x**2 + y**2) We can express the `\operatorname{atan2}` function in terms of complex logarithms: >>> from sympy import log >>> atan2(y, x).rewrite(log) -I*log((x + I*y)/sqrt(x**2 + y**2)) and in terms of `\operatorname(atan)`: >>> from sympy import atan >>> atan2(y, x).rewrite(atan) Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) but note that this form is undefined on the negative real axis. See Also ======== sympy.functions.elementary.trigonometric.sin sympy.functions.elementary.trigonometric.csc sympy.functions.elementary.trigonometric.cos sympy.functions.elementary.trigonometric.sec sympy.functions.elementary.trigonometric.tan sympy.functions.elementary.trigonometric.cot sympy.functions.elementary.trigonometric.asin sympy.functions.elementary.trigonometric.acsc sympy.functions.elementary.trigonometric.acos sympy.functions.elementary.trigonometric.asec sympy.functions.elementary.trigonometric.atan sympy.functions.elementary.trigonometric.acot References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] https://en.wikipedia.org/wiki/Atan2 .. [3] https://functions.wolfram.com/ElementaryFunctions/ArcTan2 """ @classmethod def eval(cls, y, x): from sympy.functions.special.delta_functions import Heaviside if x is S.NegativeInfinity: if y.is_zero: # Special case y = 0 because we define Heaviside(0) = 1/2 return pi return 2*pi*(Heaviside(re(y))) - pi elif x is S.Infinity: return S.Zero elif x.is_imaginary and y.is_imaginary and x.is_number and y.is_number: x = im(x) y = im(y) if x.is_extended_real and y.is_extended_real: if x.is_positive: return atan(y/x) elif x.is_negative: if y.is_negative: return atan(y/x) - pi elif y.is_nonnegative: return atan(y/x) + pi elif x.is_zero: if y.is_positive: return pi/2 elif y.is_negative: return -pi/2 elif y.is_zero: return S.NaN if y.is_zero: if x.is_extended_nonzero: return pi*(S.One - Heaviside(x)) if x.is_number: return Piecewise((pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) if x.is_number and y.is_number: return -S.ImaginaryUnit*log( (x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_log(self, y, x, **kwargs): return -S.ImaginaryUnit*log((x + S.ImaginaryUnit*y)/sqrt(x**2 + y**2)) def _eval_rewrite_as_atan(self, y, x, **kwargs): return Piecewise((2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, Ne(x, 0)), (S.NaN, True)) def _eval_rewrite_as_arg(self, y, x, **kwargs): if x.is_extended_real and y.is_extended_real: return arg_f(x + y*S.ImaginaryUnit) n = x + S.ImaginaryUnit*y d = x**2 + y**2 return arg_f(n/sqrt(d)) - S.ImaginaryUnit*log(abs(n)/sqrt(abs(d))) def _eval_is_extended_real(self): return self.args[0].is_extended_real and self.args[1].is_extended_real def _eval_conjugate(self): return self.func(self.args[0].conjugate(), self.args[1].conjugate()) def fdiff(self, argindex): y, x = self.args if argindex == 1: # Diff wrt y return x/(x**2 + y**2) elif argindex == 2: # Diff wrt x return -y/(x**2 + y**2) else: raise ArgumentIndexError(self, argindex) def _eval_evalf(self, prec): y, x = self.args if x.is_extended_real and y.is_extended_real: return super()._eval_evalf(prec)
atan2
python
bokeh__bokeh
src/bokeh/models/filters.py
{ "start": 3618, "end": 3890 }
class ____(CompositeFilter): """ Computes intersection of indices resulting from other filters. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
IntersectionFilter
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/layer_order_independence.py
{ "start": 873, "end": 1559 }
class ____(App[None]): CSS = """ Screen { layers: base higher; } Overlay { layer: higher; dock: top; width: auto; height: auto; padding: 2; border: solid yellow; background: red; color: yellow; } Body2 { background: green; } """ SCREENS = {"good": Good, "bad": Bad} BINDINGS = [("t", "toggle", "Toggle Screen")] def on_mount(self): self.push_screen("good") def action_toggle(self): self.switch_screen( "bad" if self.screen.__class__.__name__ == "Good" else "good" ) if __name__ == "__main__": Layers().run()
Layers
python
google__pytype
pytype/overlays/special_builtins.py
{ "start": 12009, "end": 12737 }
class ____(abstract.PyTDClass): """Implementation of classes in builtins.pytd. The module name is passed in to allow classes in other modules to subclass a module in builtins and inherit the custom behaviour. """ _NAME: str = None @classmethod def make(cls, ctx): assert cls._NAME return cls(cls._NAME, ctx, "builtins") @classmethod def make_alias(cls, name, ctx, module): # Although this method has the same signature as __init__, it makes alias # creation more readable and consistent with BuiltinFunction. return cls(name, ctx, module) def __init__(self, name, ctx, module): super().__init__(name, ctx.loader.lookup_pytd(module, name), ctx) self.module = module
BuiltinClass
python
dagster-io__dagster
scripts/run-pyright.py
{ "start": 3538, "end": 3602 }
class ____(TypedDict): start: Position end: Position
Range
python
django__django
tests/check_framework/tests.py
{ "start": 612, "end": 675 }
class ____: def __repr__(self): return "obj"
DummyObj
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 61918, "end": 62616 }
class ____(BiffRecord): """ Offset Size Contents 0 2 Index to row 2 2 Index to column 4 2 Index to XF record 6 8 Result of the formula 14 2 Option flags: Bit Mask Contents 0 0001H 1 = Recalculate always 1 0002H 1 = Calculate on open 3 0008H 1 = Part of a shared formula 16 4 Not used 20 var. Formula data (RPN token array) """ _REC_ID = 0x0006 def __init__(self, row, col, xf_index, rpn, calc_flags=0): self._rec_data = pack('<3HQHL', row, col, xf_index, 0xFFFF000000000003, calc_flags & 3, 0) + rpn
FormulaRecord
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/unit_tests/test_test_full_refresh.py
{ "start": 612, "end": 7996 }
class ____(ConnectionTestConfig): ignored_fields: Dict[str, List[IgnoredFieldsConfiguration]] = { "test_stream": [ IgnoredFieldsConfiguration(name="ignore_me", bypass_reason="test"), IgnoredFieldsConfiguration(name="ignore_me_too", bypass_reason="test"), ] } def record_message_from_record(records: List[Dict], emitted_at: int) -> List[AirbyteMessage]: return [ AirbyteMessage( type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data=record, emitted_at=emitted_at), ) for record in records ] def get_default_catalog(schema, **kwargs): configured_catalog_kwargs = {"sync_mode": "full_refresh", "destination_sync_mode": "overwrite"} primary_key = kwargs.get("primary_key") if primary_key: configured_catalog_kwargs["primary_key"] = primary_key return ConfiguredAirbyteCatalog( streams=[ ConfiguredAirbyteStream( stream=AirbyteStream( name="test_stream", json_schema=schema, supported_sync_modes=[SyncMode.full_refresh], ), **configured_catalog_kwargs, ) ] ) fail_context = pytest.raises( Failed, match="the two sequential reads should produce either equal set of records or one of them is a strict subset of the other", ) no_fail_context = does_not_raise() recordset_comparison_test_cases = [ pytest.param( [["id"]], [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], [{"id": 1, "first_name": "Albert", "last_name": "Einstein"}, {"id": 2, "first_name": "Joseph", "last_name": "Lagrange"}], no_fail_context, id="pk_sets_equal_success", ), pytest.param( [["id"]], [ {"id": 1, "first_name": "Thomas", "last_name": "Edison"}, ], [{"id": 1, "first_name": "Albert", "last_name": "Einstein"}, {"id": 2, "first_name": "Joseph", "last_name": "Lagrange"}], no_fail_context, id="pk_first_is_subset_success", ), pytest.param( [["id"]], [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], [{"id": 1, "first_name": "Albert", "last_name": "Einstein"}], fail_context, id="pk_second_is_subset_fail", ), pytest.param( [["id"]], [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], [{"id": 2, "first_name": "Thomas", "last_name": "Edison"}, {"id": 3, "first_name": "Nicola", "last_name": "Tesla"}], fail_context, id="pk_no_subsets_fail", ), pytest.param( None, [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], no_fail_context, id="no_pk_sets_equal_success", ), pytest.param( None, [ {"id": 1, "first_name": "Thomas", "last_name": "Edison"}, ], [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], no_fail_context, id="no_pk_first_is_subset_success", ), pytest.param( None, [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], [ {"id": 1, "first_name": "Thomas", "last_name": "Edison"}, ], fail_context, id="no_pk_second_is_subset_fail", ), pytest.param( None, [{"id": 1, "first_name": "Thomas", "last_name": "Edison"}, {"id": 2, "first_name": "Nicola", "last_name": "Tesla"}], [{"id": 2, "first_name": "Nicola", "last_name": "Tesla"}, {"id": 3, "first_name": "Albert", "last_name": "Einstein"}], fail_context, id="no_pk_no_subsets_fail", ), ] @pytest.mark.parametrize( "schema, records_1, records_2, expectation", [ ( {"type": "object"}, [ AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 23}, emitted_at=111)), AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 24}, emitted_at=111)), ], [ AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 23}, emitted_at=112)), AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 24}, emitted_at=112)), ], does_not_raise(), ), ( {"type": "object"}, [ AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 23}, emitted_at=111)), AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 24}, emitted_at=111)), ], [ AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 24}, emitted_at=112)), AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 23}, emitted_at=112)), ], does_not_raise(), ), ( {"type": "object"}, [ AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 23}, emitted_at=111)), AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 24}, emitted_at=111)), ], [ AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 23}, emitted_at=111)), AirbyteMessage(type=Type.RECORD, record=AirbyteRecordMessage(stream="test_stream", data={"aa": 24}, emitted_at=112)), ], pytest.raises(AssertionError, match="emitted_at should increase on subsequent runs"), ), ], ) async def test_emitted_at_increase_on_subsequent_runs(mocker, schema, records_1, records_2, expectation): configured_catalog = ConfiguredAirbyteCatalog( streams=[ ConfiguredAirbyteStream( stream=AirbyteStream.parse_obj({"name": "test_stream", "json_schema": schema, "supported_sync_modes": ["full_refresh"]}), sync_mode="full_refresh", destination_sync_mode="overwrite", ) ] ) docker_runner_mock = mocker.MagicMock(call_read=mocker.AsyncMock(side_effect=[records_1, records_2])) input_config = ReadTestConfigWithIgnoreFields() t = _TestFullRefresh() with expectation: await t.test_sequential_reads( ignored_fields=input_config.ignored_fields, connector_config=mocker.MagicMock(), configured_catalog=configured_catalog, docker_runner=docker_runner_mock, detailed_logger=docker_runner_mock, )
ReadTestConfigWithIgnoreFields
python
huggingface__transformers
src/transformers/models/jamba/modular_jamba.py
{ "start": 7633, "end": 9833 }
class ____(LlamaAttention): def __init__(self, config: JambaConfig, layer_idx: int): super().__init__(config, layer_idx) self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False) self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False) self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False) self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[HybridMambaAttentionDynamicCache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) if past_key_values is not None: key_states, value_states = past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, ) attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
JambaAttention
python
mkdocstrings__mkdocstrings
src/mkdocstrings/_internal/handlers/rendering.py
{ "start": 10416, "end": 12016 }
class ____(Extension): """Extension that should always be added to Markdown sub-documents that handlers request (and *only* them).""" def __init__(self, headings: list[Element]): """Initialize the object. Arguments: headings: A list that will be populated with all HTML heading elements encountered in the document. """ super().__init__() self.headings = headings """The list that will be populated with all HTML heading elements encountered in the document.""" def extendMarkdown(self, md: Markdown) -> None: # noqa: N802 (casing: parent method's name) """Register the extension. Arguments: md: A `markdown.Markdown` instance. """ md.registerExtension(self) md.treeprocessors.register( HeadingShiftingTreeprocessor(md, 0), HeadingShiftingTreeprocessor.name, priority=12, ) md.treeprocessors.register( IdPrependingTreeprocessor(md, ""), IdPrependingTreeprocessor.name, priority=4, # Right after 'toc' (needed because that extension adds ids to headers). ) md.treeprocessors.register( _HeadingReportingTreeprocessor(md, self.headings), _HeadingReportingTreeprocessor.name, priority=1, # Close to the end. ) md.treeprocessors.register( ParagraphStrippingTreeprocessor(md), ParagraphStrippingTreeprocessor.name, priority=0.99, # Close to the end. )
MkdocstringsInnerExtension
python
ray-project__ray
python/ray/util/dask/callbacks.py
{ "start": 1107, "end": 6056 }
class ____(Callback): """ Extends Dask's `Callback` class with Ray-specific hooks. When instantiating or subclassing this class, both the normal Dask hooks (e.g. pretask, posttask, etc.) and the Ray-specific hooks can be provided. See `dask.callbacks.Callback` for usage. Caveats: Any Dask-Ray scheduler must bring the Ray-specific callbacks into context using the `local_ray_callbacks` context manager, since the built-in `local_callbacks` context manager provided by Dask isn't aware of this class. """ # Set of active Ray-specific callbacks. ray_active = set() def __init__(self, **kwargs): for cb in CBS: cb_func = kwargs.pop(cb, None) if cb_func is not None: setattr(self, "_" + cb, cb_func) super().__init__(**kwargs) @property def _ray_callback(self): return RayCallback(*[getattr(self, field, None) for field in CB_FIELDS]) def __enter__(self): self._ray_cm = add_ray_callbacks(self) self._ray_cm.__enter__() super().__enter__() return self def __exit__(self, *args): super().__exit__(*args) self._ray_cm.__exit__(*args) def register(self): type(self).ray_active.add(self._ray_callback) super().register() def unregister(self): type(self).ray_active.remove(self._ray_callback) super().unregister() def _ray_presubmit(self, task, key, deps) -> Optional[Any]: """Run before submitting a Ray task. If this callback returns a non-`None` value, Ray does _not_ create a task and uses this value as the would-be task's result value. Args: task: A Dask task, where the first tuple item is the task function, and the remaining tuple items are the task arguments, which are either the actual argument values, or Dask keys into the deps dictionary whose corresponding values are the argument values. key: The Dask graph key for the given task. deps: The dependencies of this task. Returns: Either None, in which case Ray submits a task, or a non-None value, in which case Ray task doesn't submit a task and uses this return value as the would-be task result value. """ pass def _ray_postsubmit(self, task, key, deps, object_ref: ray.ObjectRef): """Run after submitting a Ray task. Args: task: A Dask task, where the first tuple item is the task function, and the remaining tuple items are the task arguments, which are either the actual argument values, or Dask keys into the deps dictionary whose corresponding values are the argument values. key: The Dask graph key for the given task. deps: The dependencies of this task. object_ref: The object reference for the return value of the Ray task. """ pass def _ray_pretask(self, key, object_refs: List[ray.ObjectRef]): """Run before executing a Dask task within a Ray task. This method executes after Ray submits the task within a Ray worker. Ray passes the return value of this task to the _ray_posttask callback, if provided. Args: key: The Dask graph key for the Dask task. object_refs: The object references for the arguments of the Ray task. Returns: A value that Ray passes to the corresponding _ray_posttask callback, if the callback is defined. """ pass def _ray_posttask(self, key, result, pre_state): """Run after executing a Dask task within a Ray task. This method executes within a Ray worker. This callback receives the return value of the _ray_pretask callback, if provided. Args: key: The Dask graph key for the Dask task. result: The task result value. pre_state: The return value of the corresponding _ray_pretask callback, if said callback is defined. """ pass def _ray_postsubmit_all(self, object_refs: List[ray.ObjectRef], dsk): """Run after Ray submits all tasks. Args: object_refs: The object references for the output (leaf) Ray tasks of the task graph. dsk: The Dask graph. """ pass def _ray_finish(self, result): """Run after Ray finishes executing all Ray tasks and returns the final result. Args: result: The final result (output) of the Dask computation, before any repackaging is done by Dask collection-specific post-compute callbacks. """ pass
RayDaskCallback
python
kamyu104__LeetCode-Solutions
Python/shuffle-string.py
{ "start": 49, "end": 600 }
class ____(object): def restoreString(self, s, indices): """ :type s: str :type indices: List[int] :rtype: str """ result = list(s) for i, c in enumerate(result): if indices[i] == i: continue move, j = c, indices[i] while j != i: result[j], move = move, result[j] indices[j], j = j, indices[j] result[i] = move return "".join(result) # Time: O(n) # Space: O(1) import itertools
Solution
python
spack__spack
lib/spack/spack/vendor/jinja2/runtime.py
{ "start": 12787, "end": 14124 }
class ____: """One block on a template reference.""" def __init__( self, name: str, context: "Context", stack: t.List[t.Callable[["Context"], t.Iterator[str]]], depth: int, ) -> None: self.name = name self._context = context self._stack = stack self._depth = depth @property def super(self) -> t.Union["BlockReference", "Undefined"]: """Super the block.""" if self._depth + 1 >= len(self._stack): return self._context.environment.undefined( f"there is no parent block called {self.name!r}.", name="super" ) return BlockReference(self.name, self._context, self._stack, self._depth + 1) @internalcode async def _async_call(self) -> str: rv = concat( [x async for x in self._stack[self._depth](self._context)] # type: ignore ) if self._context.eval_ctx.autoescape: return Markup(rv) return rv @internalcode def __call__(self) -> str: if self._context.environment.is_async: return self._async_call() # type: ignore rv = concat(self._stack[self._depth](self._context)) if self._context.eval_ctx.autoescape: return Markup(rv) return rv
BlockReference
python
numba__numba
numba/core/typing/builtins.py
{ "start": 18372, "end": 18763 }
class ____(AbstractTemplate): key = "static_getitem" def generic(self, args, kws): tup, idx = args ret = None if not isinstance(tup, types.LiteralList): return if isinstance(idx, int): ret = tup.types[idx] if ret is not None: sig = signature(ret, *args) return sig @infer
StaticGetItemLiteralList
python
getsentry__sentry
src/sentry/uptime/grouptype.py
{ "start": 1442, "end": 3379 }
class ____: """ Represents the value passed into the uptime detector """ check_result: CheckResult subscription: UptimeSubscription metric_tags: dict[str, str] def build_evidence_display(result: CheckResult) -> list[IssueEvidence]: evidence_display: list[IssueEvidence] = [] status_reason = result["status_reason"] if status_reason: reason_evidence = IssueEvidence( name="Failure reason", value=f'{status_reason["type"]} - {status_reason["description"]}', important=True, ) evidence_display.extend([reason_evidence]) duration_evidence = IssueEvidence( name="Duration", value=f"{result["duration_ms"]}ms", important=False, ) evidence_display.append(duration_evidence) request_info = result["request_info"] if request_info: method_evidence = IssueEvidence( name="Method", value=request_info["request_type"], important=False, ) status_code_evidence = IssueEvidence( name="Status Code", value=str(request_info["http_status_code"]), important=False, ) evidence_display.extend([method_evidence, status_code_evidence]) return evidence_display def build_event_data(result: CheckResult, detector: Detector) -> EventData: # Default environment when it hasn't been configured env = detector.config.get("environment", "prod") # Received time is the actual time the check was performed. received = datetime.fromtimestamp(result["actual_check_time_ms"] / 1000) return { "project_id": detector.project_id, "environment": env, "received": received, "platform": "other", "sdk": None, "contexts": { "trace": {"trace_id": result["trace_id"], "span_id": result.get("span_id")}, }, }
UptimePacketValue
python
langchain-ai__langchain
libs/standard-tests/langchain_tests/integration_tests/cache.py
{ "start": 337, "end": 3821 }
class ____(BaseStandardTests): """Test suite for checking the `BaseCache` API of a caching layer for LLMs. This test suite verifies the basic caching API of a caching layer for LLMs. The test suite is designed for synchronous caching layers. Implementers should subclass this test suite and provide a fixture that returns an empty cache for each test. """ @abstractmethod @pytest.fixture def cache(self) -> BaseCache: """Get the cache class to test. The returned cache should be EMPTY. """ def get_sample_prompt(self) -> str: """Return a sample prompt for testing.""" return "Sample prompt for testing." def get_sample_llm_string(self) -> str: """Return a sample LLM string for testing.""" return "Sample LLM string configuration." def get_sample_generation(self) -> Generation: """Return a sample `Generation` object for testing.""" return Generation( text="Sample generated text.", generation_info={"reason": "test"}, ) def test_cache_is_empty(self, cache: BaseCache) -> None: """Test that the cache is empty.""" assert ( cache.lookup(self.get_sample_prompt(), self.get_sample_llm_string()) is None ) def test_update_cache(self, cache: BaseCache) -> None: """Test updating the cache.""" prompt = self.get_sample_prompt() llm_string = self.get_sample_llm_string() generation = self.get_sample_generation() cache.update(prompt, llm_string, [generation]) assert cache.lookup(prompt, llm_string) == [generation] def test_cache_still_empty(self, cache: BaseCache) -> None: """Test that the cache is still empty. This test should follow a test that updates the cache. This just verifies that the fixture is set up properly to be empty after each test. """ assert ( cache.lookup(self.get_sample_prompt(), self.get_sample_llm_string()) is None ) def test_clear_cache(self, cache: BaseCache) -> None: """Test clearing the cache.""" prompt = self.get_sample_prompt() llm_string = self.get_sample_llm_string() generation = self.get_sample_generation() cache.update(prompt, llm_string, [generation]) cache.clear() assert cache.lookup(prompt, llm_string) is None def test_cache_miss(self, cache: BaseCache) -> None: """Test cache miss.""" assert cache.lookup("Nonexistent prompt", self.get_sample_llm_string()) is None def test_cache_hit(self, cache: BaseCache) -> None: """Test cache hit.""" prompt = self.get_sample_prompt() llm_string = self.get_sample_llm_string() generation = self.get_sample_generation() cache.update(prompt, llm_string, [generation]) assert cache.lookup(prompt, llm_string) == [generation] def test_update_cache_with_multiple_generations(self, cache: BaseCache) -> None: """Test updating the cache with multiple `Generation` objects.""" prompt = self.get_sample_prompt() llm_string = self.get_sample_llm_string() generations = [ self.get_sample_generation(), Generation(text="Another generated text."), ] cache.update(prompt, llm_string, generations) assert cache.lookup(prompt, llm_string) == generations
SyncCacheTestSuite
python
pytorch__pytorch
torch/_inductor/subgraph_lowering.py
{ "start": 745, "end": 4729 }
class ____(torch.fx.Interpreter): """ Lowers a pointwise subgraph to a single set of buffers with a separate lowering object. Errors if buffers are created unexpectedly """ graph_outputs: Optional[list[ir.IRNode]] root_graph: GraphLowering _current_op: Optional[TargetType] # For backwards of buffer_grads with scatters we allow mutations allowed_mutations: Optional[OrderedSet[OpOverload]] additional_lowerings: Optional[LoweringDict] buffers: list[ir.Buffer] mutated_buffers: OrderedSet[str] def __init__( self, gm: torch.fx.GraphModule, root_graph_lowering: GraphLowering, allowed_mutations: Optional[OrderedSet[OpOverload]] = None, additional_lowerings: Optional[LoweringDict] = None, ) -> None: super().__init__(gm) self.graph_outputs = None self.root_graph = root_graph_lowering self.allowed_mutations = allowed_mutations self.additional_lowerings = additional_lowerings self._current_op = None # Used to track buffers created during lowering self.mutated_buffers = OrderedSet() self.buffers = [] @contextmanager def _op_context(self, op: TargetType) -> Generator[None, None, None]: """Set which op is being processed in call function to know if we can mutate buffers""" previous = self._current_op self._current_op = op try: yield finally: self._current_op = previous def _approved_mutator(self) -> bool: return ( self.allowed_mutations is not None and self._current_op in self.allowed_mutations ) def mark_buffer_mutated(self, name: str) -> None: if self._approved_mutator(): self.mutated_buffers.add(name) else: raise SubgraphLoweringException( f"Buffer mutation detected during lowering of {self._current_op}. " "Buffer mutations are only allowed in approved mutation ops. " "This is an error in the lowering of the subgraph, please file a bug report." ) def register_buffer(self, buffer: ir.Buffer, *, set_name: bool = False) -> str: if self._approved_mutator(): name = self.root_graph.register_buffer(buffer, set_name=set_name) return name else: raise SubgraphLoweringException( "Buffers cannot be created while lowering a pointwise subgraph. " "This could be for a good reason (e.g. you're calling an op we can't codegen as a pointwise op), " "but it could also be a bug. Please file a bug report if you think this should be supportable." ) def __getattr__(self, name: str) -> Any: return getattr(self.root_graph, name) def call_function( self, target: TargetType, args: Any, kwargs: dict[str, Any], ) -> Any: from .lowering import lowerings with self._op_context(target): if target is operator.getitem and isinstance(args[0], (list, tuple, dict)): return super().call_function(target, args, kwargs) # These takes precedence over the main lowerings if self.additional_lowerings is not None: if target in self.additional_lowerings: assert isinstance(target, OpOverload) return self.additional_lowerings[target](*args, **kwargs) if target not in lowerings: raise SubgraphLoweringException( f"{target} not supported in subgraph, (missing lowering)" ) return lowerings[target](*args, **kwargs) def output(self, target: str, args: tuple[Any], kwargs: dict[str, Any]) -> None: # type: ignore[override] assert len(args) == 1 self.graph_outputs = args[0] @dataclass
PointwiseSubgraphLowering
python
huggingface__transformers
tests/quantization/compressed_tensors_integration/test_compressed_models.py
{ "start": 434, "end": 6759 }
class ____(unittest.TestCase): # Define stubs as class attributes compressed_uncompressed_model_stubs = [ ( "nm-testing/llama2.c-stories42M-gsm8k-quantized-only-compressed", "nm-testing/llama2.c-stories42M-gsm8k-quantized-only-uncompressed", ), ( "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed", "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed", ), ( "nm-testing/llama2.c-stories42M-gsm8k-stacked-compressed", "nm-testing/llama2.c-stories42M-gsm8k-stacked-uncompressed", ), ] # Flatten the list for tests that require a single list of stubs. model_stubs = [stub for pair in compressed_uncompressed_model_stubs for stub in pair] # For the outputs matching test, use the sparse-only pair. sparse_compressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed" sparse_uncompressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed" prompt = "Paris is the capital of which country?" def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_compressed_uncompressed_model_shapes(self): """ Verify that the weights of an uncompressed model and its decompressed compressed counterpart match. Note: Weights for sparsely compressed models may differ due to packing. """ def _has_nested_attr(obj, attr_path): attrs = attr_path.split(".") for attr in attrs: if not hasattr(obj, attr): return None obj = getattr(obj, attr) return obj from compressed_tensors.quantization.utils import iter_named_leaf_modules for compressed_model, uncompressed_model in self.compressed_uncompressed_model_stubs: with self.subTest(compressed_model=compressed_model, uncompressed_model=uncompressed_model): uncompressed = AutoModelForCausalLM.from_pretrained( uncompressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) compressed_decompressed = AutoModelForCausalLM.from_pretrained( compressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) for name, submodule in iter_named_leaf_modules(uncompressed): comp_decomp_obj = _has_nested_attr(compressed_decompressed, name) if comp_decomp_obj is not None and hasattr(submodule, "weight"): if "sparse-only" in uncompressed_model: self.assertTrue( torch.equal(submodule.weight, comp_decomp_obj.weight), f"Weight mismatch for module '{name}' in sparse-only model.", ) else: self.assertTrue( torch.allclose( submodule.weight.to(torch_device), comp_decomp_obj.weight.to(torch_device), atol=0.2, ), f"Weight mismatch for module '{name}' in quantized-only or stacked model.", ) def test_outputs_match(self): """ Ensure that the generated outputs match between the uncompressed model and its decompressed compressed counterpart. """ tokenizer = AutoTokenizer.from_pretrained(self.sparse_uncompressed_model) input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids uncompressed = AutoModelForCausalLM.from_pretrained( self.sparse_uncompressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) output_uncompressed = uncompressed.generate(input_ids.to(uncompressed.device), max_new_tokens=100) decompressed = AutoModelForCausalLM.from_pretrained( self.sparse_compressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) output_decompressed = decompressed.generate(input_ids.to(decompressed.device), max_new_tokens=100) self.assertEqual( tokenizer.decode(output_uncompressed[0]), tokenizer.decode(output_decompressed[0]), "Generated outputs do not match between compressed and uncompressed models.", ) def test_no_warnings_for_all_models(self): """ Confirm that loading any model using compressed tensors does not trigger warnings about missing or unexpected keys. """ for model_stub in self.model_stubs: with self.subTest(model_stub=model_stub): with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") AutoModelForCausalLM.from_pretrained( model_stub, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) for warning in caught_warnings: self.assertNotIn( "missing keys", str(warning.message).lower(), f"'missing keys' found in warnings for model {model_stub}", ) self.assertNotIn( "unexpected keys", str(warning.message).lower(), f"'unexpected keys' found in warnings for model {model_stub}", ) @require_compressed_tensors @require_torch
StackCompressedModelTest
python
matplotlib__matplotlib
lib/matplotlib/cbook.py
{ "start": 3464, "end": 4091 }
class ____: """ Wrapper similar to a weakref, but keeping a strong reference to the object. """ def __init__(self, obj): self._obj = obj def __call__(self): return self._obj def __eq__(self, other): return isinstance(other, _StrongRef) and self._obj == other._obj def __hash__(self): return hash(self._obj) def _weak_or_strong_ref(func, callback): """ Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`. """ try: return weakref.WeakMethod(func, callback) except TypeError: return _StrongRef(func)
_StrongRef
python
wandb__wandb
wandb/vendor/pygments/lexers/varnish.py
{ "start": 490, "end": 6488 }
class ____(RegexLexer): """ For Varnish Configuration Language (VCL). .. versionadded:: 2.2 """ name = 'VCL' aliases = ['vcl'] filenames = ['*.vcl'] mimetypes = ['text/x-vclsrc'] def analyse_text(text): # If the very first line is 'vcl 4.0;' it's pretty much guaranteed # that this is VCL if text.startswith('vcl 4.0;'): return 1.0 # Skip over comments and blank lines # This is accurate enough that returning 0.9 is reasonable. # Almost no VCL files start without some comments. elif '\nvcl 4\.0;' in text[:1000]: return 0.9 tokens = { 'probe': [ include('whitespace'), include('comments'), (r'(\.\w+)(\s*=\s*)([^;]*)(;)', bygroups(Name.Attribute, Operator, using(this), Punctuation)), (r'\}', Punctuation, '#pop'), ], 'acl': [ include('whitespace'), include('comments'), (r'[!/]+', Operator), (r';', Punctuation), (r'\d+', Number), (r'\}', Punctuation, '#pop'), ], 'backend': [ include('whitespace'), (r'(\.probe)(\s*=\s*)(\w+)(;)', bygroups(Name.Attribute, Operator, Name.Variable.Global, Punctuation)), (r'(\.probe)(\s*=\s*)(\{)', bygroups(Name.Attribute, Operator, Punctuation), 'probe'), (r'(\.\w+\b)(\s*=\s*)([^;]*)(\s*;)', bygroups(Name.Attribute, Operator, using(this), Punctuation)), (r'\{', Punctuation, '#push'), (r'\}', Punctuation, '#pop'), ], 'statements': [ (r'(\d\.)?\d+[sdwhmy]', Literal.Date), (r'(\d\.)?\d+ms', Literal.Date), (r'(vcl_pass|vcl_hash|vcl_hit|vcl_init|vcl_backend_fetch|vcl_pipe|' r'vcl_backend_response|vcl_synth|vcl_deliver|vcl_backend_error|' r'vcl_fini|vcl_recv|vcl_purge|vcl_miss)\b', Name.Function), (r'(pipe|retry|hash|synth|deliver|purge|abandon|lookup|pass|fail|ok|' r'miss|fetch|restart)\b', Name.Constant), (r'(beresp|obj|resp|req|req_top|bereq)\.http\.[a-zA-Z_-]+\b', Name.Variable), (words(( 'obj.status', 'req.hash_always_miss', 'beresp.backend', 'req.esi_level', 'req.can_gzip', 'beresp.ttl', 'obj.uncacheable', 'req.ttl', 'obj.hits', 'client.identity', 'req.hash_ignore_busy', 'obj.reason', 'req.xid', 'req_top.proto', 'beresp.age', 'obj.proto', 'obj.age', 'local.ip', 'beresp.uncacheable', 'req.method', 'beresp.backend.ip', 'now', 'obj.grace', 'req.restarts', 'beresp.keep', 'req.proto', 'resp.proto', 'bereq.xid', 'bereq.between_bytes_timeout', 'req.esi', 'bereq.first_byte_timeout', 'bereq.method', 'bereq.connect_timeout', 'beresp.do_gzip', 'resp.status', 'beresp.do_gunzip', 'beresp.storage_hint', 'resp.is_streaming', 'beresp.do_stream', 'req_top.method', 'bereq.backend', 'beresp.backend.name', 'beresp.status', 'req.url', 'obj.keep', 'obj.ttl', 'beresp.reason', 'bereq.retries', 'resp.reason', 'bereq.url', 'beresp.do_esi', 'beresp.proto', 'client.ip', 'bereq.proto', 'server.hostname', 'remote.ip', 'req.backend_hint', 'server.identity', 'req_top.url', 'beresp.grace', 'beresp.was_304', 'server.ip', 'bereq.uncacheable'), suffix=r'\b'), Name.Variable), (r'[!%&+*\-,/<.}{>=|~]+', Operator), (r'[();]', Punctuation), (r'[,]+', Punctuation), (words(('hash_data', 'regsub', 'regsuball', 'if', 'else', 'elsif', 'elif', 'synth', 'synthetic', 'ban', 'return', 'set', 'unset', 'import', 'include', 'new', 'rollback', 'call'), suffix=r'\b'), Keyword), (r'storage\.\w+\.\w+\b', Name.Variable), (words(('true', 'false')), Name.Builtin), (r'\d+\b', Number), (r'(backend)(\s+\w+)(\s*\{)', bygroups(Keyword, Name.Variable.Global, Punctuation), 'backend'), (r'(probe\s)(\s*\w+\s)(\{)', bygroups(Keyword, Name.Variable.Global, Punctuation), 'probe'), (r'(acl\s)(\s*\w+\s)(\{)', bygroups(Keyword, Name.Variable.Global, Punctuation), 'acl'), (r'(vcl )(4.0)(;)$', bygroups(Keyword.Reserved, Name.Constant, Punctuation)), (r'(sub\s+)([a-zA-Z]\w*)(\s*\{)', bygroups(Keyword, Name.Function, Punctuation)), (r'([a-zA-Z_]\w*)' r'(\.)' r'([a-zA-Z_]\w*)' r'(\s*\(.*\))', bygroups(Name.Function, Punctuation, Name.Function, using(this))), ('[a-zA-Z_]\w*', Name), ], 'comment': [ (r'[^*/]+', Comment.Multiline), (r'/\*', Comment.Multiline, '#push'), (r'\*/', Comment.Multiline, '#pop'), (r'[*/]', Comment.Multiline), ], 'comments': [ (r'#.*$', Comment), (r'/\*', Comment.Multiline, 'comment'), (r'//.*$', Comment), ], 'string': [ (r'"', String, '#pop'), (r'[^"\n]+', String), # all other characters ], 'multistring': [ (r'[^"}]', String), (r'"\}', String, '#pop'), (r'["}]', String), ], 'whitespace': [ (r'L?"', String, 'string'), (r'\{"', String, 'multistring'), (r'\n', Text), (r'\s+', Text), (r'\\\n', Text), # line continuation ], 'root': [ include('whitespace'), include('comments'), include('statements'), (r'\s+', Text), ], }
VCLLexer
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 669965, "end": 670362 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "client_mutation_id", "issue") actor = sgqlc.types.Field(Actor, graphql_name="actor") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") issue = sgqlc.types.Field("Issue", graphql_name="issue")
UpdateIssuePayload
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 2530, "end": 2745 }
class ____(BaseLinksSerializer): _self = serializers.SerializerMethodField() def get__self(self, obj): path = obj.get_absolute_url() return self._absolute_url(path)
NotificationLinksSerializer
python
django__django
tests/constraints/models.py
{ "start": 5041, "end": 5257 }
class ____(models.Model): field = models.CharField(max_length=255) field_with_db_default = models.CharField( max_length=255, db_default=models.Value("field_with_db_default") )
ModelWithDatabaseDefault
python
joke2k__faker
tests/providers/test_lorem.py
{ "start": 14809, "end": 17630 }
class ____: """Test fa_IR lorem provider""" word_list = [word.lower() for word in FaIrLoremProvider.word_list] def test_paragraph(self, faker, num_samples): num_sentences = 10 for _ in range(num_samples): paragraph = faker.paragraph(nb_sentences=num_sentences) assert isinstance(paragraph, str) words = paragraph.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_paragraphs(self, faker, num_samples): num_paragraphs = 5 for _ in range(num_samples): paragraphs = faker.paragraphs(nb=num_paragraphs) for paragraph in paragraphs: assert isinstance(paragraph, str) words = paragraph.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_sentence(self, faker, num_samples): num_words = 10 for _ in range(num_samples): sentence = faker.sentence(nb_words=num_words) assert isinstance(sentence, str) words = sentence.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_sentences(self, faker, num_samples): num_sentences = 5 for _ in range(num_samples): sentences = faker.sentences(nb=num_sentences) for sentence in sentences: assert isinstance(sentence, str) words = sentence.replace(".", "").split() assert all(word.lower() in self.word_list for word in words) def test_text(self, faker, num_samples): num_chars = 25 for _ in range(num_samples): text = faker.text(max_nb_chars=num_chars) assert isinstance(text, str) words = re.sub(r"[.\n]+", " ", text).split() assert all(word.lower() in self.word_list for word in words) def test_texts(self, faker, num_samples): num_texts = 5 num_chars = 25 for _ in range(num_samples): texts = faker.texts(max_nb_chars=num_chars, nb_texts=num_texts) for text in texts: assert isinstance(text, str) words = re.sub(r"[.\n]+", " ", text).split() assert all(word.lower() in self.word_list for word in words) def test_word(self, faker, num_samples): for _ in range(num_samples): word = faker.word() assert isinstance(word, str) and word in FaIrLoremProvider.word_list def test_words(self, faker, num_samples): num_words = 5 for _ in range(num_samples): words = faker.words(num_words) assert all(isinstance(word, str) and word in FaIrLoremProvider.word_list for word in words)
TestFaIr
python
explosion__spaCy
spacy/lang/nn/__init__.py
{ "start": 221, "end": 457 }
class ____(BaseDefaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS prefixes = TOKENIZER_PREFIXES infixes = TOKENIZER_INFIXES suffixes = TOKENIZER_SUFFIXES syntax_iterators = SYNTAX_ITERATORS
NorwegianNynorskDefaults
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/quux/package.py
{ "start": 1298, "end": 5922 }
class ____ { private: static const int version_major; static const int version_minor; public: Quux(); int get_version() const; int quuxify() const; }; #endif // QUUX_H_ """ quuxifier_cc = """ #include "quux.h" #include <iostream> int main() { Quux quux; quux.quuxify(); return 0; } """ quux_version_h = """const int quux_version_major = %s; const int quux_version_minor = %s; """ mkdirp("%s/quux" % prefix.include) mkdirp("%s/quux" % self.stage.source_path) with open("%s/quux_version.h" % self.stage.source_path, "w", encoding="utf-8") as f: f.write(quux_version_h % (self.version[0], self.version[1:])) with open("%s/quux/quux.cc" % self.stage.source_path, "w", encoding="utf-8") as f: f.write(quux_cc % (prefix.config)) with open("%s/quux/quux.h" % self.stage.source_path, "w", encoding="utf-8") as f: f.write(quux_h) with open("%s/quux/quuxifier.cc" % self.stage.source_path, "w", encoding="utf-8") as f: f.write(quuxifier_cc) gpp = which( "g++", path=":".join( [s for s in os.environ["PATH"].split(os.pathsep) if "lib/spack/env" not in s] ), ) if sys.platform == "darwin": gpp = which("/usr/bin/clang++") gpp( "-Dquux_EXPORTS", "-I%s" % self.stage.source_path, "-I%s" % spec["garply"].prefix.include, "-O2", "-g", "-DNDEBUG", "-fPIC", "-o", "quux.cc.o", "-c", "quux/quux.cc", ) gpp( "-Dquux_EXPORTS", "-I%s" % self.stage.source_path, "-I%s" % spec["garply"].prefix.include, "-O2", "-g", "-DNDEBUG", "-fPIC", "-o", "quuxifier.cc.o", "-c", "quux/quuxifier.cc", ) if sys.platform == "darwin": gpp( "-fPIC", "-O2", "-g", "-DNDEBUG", "-dynamiclib", "-Wl,-headerpad_max_install_names", "-o", "libquux.dylib", "-install_name", "@rpath/libquux.dylib", "quux.cc.o", "-Wl,-rpath,%s" % prefix.lib64, "-Wl,-rpath,%s" % spec["garply"].prefix.lib64, "%s/libgarply.dylib" % spec["garply"].prefix.lib64, ) gpp( "-O2", "-g", "-DNDEBUG", "quuxifier.cc.o", "-o", "quuxifier", "-Wl,-rpath,%s" % prefix.lib64, "-Wl,-rpath,%s" % spec["garply"].prefix.lib64, "libquux.dylib", "%s/libgarply.dylib" % spec["garply"].prefix.lib64, ) mkdirp(prefix.lib64) copy("libquux.dylib", "%s/libquux.dylib" % prefix.lib64) os.link("%s/libquux.dylib" % prefix.lib64, "%s/libquux.dylib.3.0" % prefix.lib64) else: gpp( "-fPIC", "-O2", "-g", "-DNDEBUG", "-shared", "-Wl,-soname,libquux.so", "-o", "libquux.so", "quux.cc.o", "-Wl,-rpath,%s:%s::::" % (prefix.lib64, spec["garply"].prefix.lib64), "%s/libgarply.so" % spec["garply"].prefix.lib64, ) gpp( "-O2", "-g", "-DNDEBUG", "-rdynamic", "quuxifier.cc.o", "-o", "quuxifier", "-Wl,-rpath,%s:%s::::" % (prefix.lib64, spec["garply"].prefix.lib64), "libquux.so", "%s/libgarply.so" % spec["garply"].prefix.lib64, ) mkdirp(prefix.lib64) copy("libquux.so", "%s/libquux.so" % prefix.lib64) os.link("%s/libquux.so" % prefix.lib64, "%s/libquux.so.3.0" % prefix.lib64) copy("quuxifier", "%s/quuxifier" % prefix.lib64) copy("%s/quux/quux.h" % self.stage.source_path, "%s/quux/quux.h" % prefix.include) mkdirp(prefix.bin) copy("quux_version.h", "%s/quux_version.h" % prefix.bin) os.symlink("%s/quuxifier" % prefix.lib64, "%s/quuxifier" % prefix.bin) os.symlink("%s/garplinator" % spec["garply"].prefix.lib64, "%s/garplinator" % prefix.bin)
Quux
python
apache__thrift
lib/py/src/server/TNonblockingServer.py
{ "start": 2926, "end": 7469 }
class ____(object): """Basic class is represented connection. It can be in state: WAIT_LEN --- connection is reading request len. WAIT_MESSAGE --- connection is reading request. WAIT_PROCESS --- connection has just read whole request and waits for call ready routine. SEND_ANSWER --- connection is sending answer string (including length of answer). CLOSED --- socket was closed and connection should be deleted. """ def __init__(self, new_socket, wake_up): self.socket = new_socket self.socket.setblocking(False) self.status = WAIT_LEN self.len = 0 self.received = deque() self._reading = Message(0, 4, True) self._rbuf = b'' self._wbuf = b'' self.lock = threading.Lock() self.wake_up = wake_up self.remaining = False @socket_exception def read(self): """Reads data from stream and switch state.""" assert self.status in (WAIT_LEN, WAIT_MESSAGE) assert not self.received buf_size = 8192 first = True done = False while not done: read = self.socket.recv(buf_size) rlen = len(read) done = rlen < buf_size self._rbuf += read if first and rlen == 0: if self.status != WAIT_LEN or self._rbuf: logger.error('could not read frame from socket') else: logger.debug('read zero length. client might have disconnected') self.close() while len(self._rbuf) >= self._reading.end: if self._reading.is_header: mlen, = struct.unpack('!i', self._rbuf[:4]) if mlen < 0: logger.error('could not read the head from frame') self.close() break self._reading = Message(self._reading.end, mlen, False) self.status = WAIT_MESSAGE else: self._reading.buffer = self._rbuf self.received.append(self._reading) self._rbuf = self._rbuf[self._reading.end:] self._reading = Message(0, 4, True) first = False if self.received: self.status = WAIT_PROCESS break self.remaining = not done @socket_exception def write(self): """Writes data from socket and switch state.""" assert self.status == SEND_ANSWER sent = self.socket.send(self._wbuf) if sent == len(self._wbuf): self.status = WAIT_LEN self._wbuf = b'' self.len = 0 else: self._wbuf = self._wbuf[sent:] @locked def ready(self, all_ok, message): """Callback function for switching state and waking up main thread. This function is the only function witch can be called asynchronous. The ready can switch Connection to three states: WAIT_LEN if request was oneway. SEND_ANSWER if request was processed in normal way. CLOSED if request throws unexpected exception. The one wakes up main thread. """ assert self.status == WAIT_PROCESS if not all_ok: self.close() self.wake_up() return self.len = 0 if len(message) == 0: # it was a oneway request, do not write answer self._wbuf = b'' self.status = WAIT_LEN else: self._wbuf = struct.pack('!i', len(message)) + message self.status = SEND_ANSWER self.wake_up() @locked def is_writeable(self): """Return True if connection should be added to write list of select""" return self.status == SEND_ANSWER # it's not necessary, but... @locked def is_readable(self): """Return True if connection should be added to read list of select""" return self.status in (WAIT_LEN, WAIT_MESSAGE) @locked def is_closed(self): """Returns True if connection is closed.""" return self.status == CLOSED def fileno(self): """Returns the file descriptor of the associated socket.""" return self.socket.fileno() def close(self): """Closes connection""" self.status = CLOSED self.socket.close()
Connection
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_profile_metric_provider.py
{ "start": 434, "end": 1073 }
class ____(MetricProvider): domain_keys = ( "batch_id", "table", "row_condition", "condition_parser", ) value_keys = ("profile_path",) @classmethod def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[dict] = None, ): return super()._get_evaluation_dependencies( metric, configuration, execution_engine, runtime_configuration )
DataProfilerProfileMetricProvider
python
numba__numba
numba/cuda/tests/cudadrv/test_cuda_array_slicing.py
{ "start": 179, "end": 1831 }
class ____(CUDATestCase): def test_index_1d(self): arr = np.arange(10) darr = cuda.to_device(arr) x, = arr.shape for i in range(-x, x): self.assertEqual(arr[i], darr[i]) with self.assertRaises(IndexError): darr[-x - 1] with self.assertRaises(IndexError): darr[x] def test_index_2d(self): arr = np.arange(3 * 4).reshape(3, 4) darr = cuda.to_device(arr) x, y = arr.shape for i in range(-x, x): for j in range(-y, y): self.assertEqual(arr[i, j], darr[i, j]) with self.assertRaises(IndexError): darr[-x - 1, 0] with self.assertRaises(IndexError): darr[x, 0] with self.assertRaises(IndexError): darr[0, -y - 1] with self.assertRaises(IndexError): darr[0, y] def test_index_3d(self): arr = np.arange(3 * 4 * 5).reshape(3, 4, 5) darr = cuda.to_device(arr) x, y, z = arr.shape for i in range(-x, x): for j in range(-y, y): for k in range(-z, z): self.assertEqual(arr[i, j, k], darr[i, j, k]) with self.assertRaises(IndexError): darr[-x - 1, 0, 0] with self.assertRaises(IndexError): darr[x, 0, 0] with self.assertRaises(IndexError): darr[0, -y - 1, 0] with self.assertRaises(IndexError): darr[0, y, 0] with self.assertRaises(IndexError): darr[0, 0, -z - 1] with self.assertRaises(IndexError): darr[0, 0, z]
CudaArrayIndexing
python
donnemartin__interactive-coding-challenges
arrays_strings/rotation/test_rotation.py
{ "start": 18, "end": 599 }
class ____(unittest.TestCase): def test_rotation(self): rotation = Rotation() self.assertEqual(rotation.is_rotation('o', 'oo'), False) self.assertEqual(rotation.is_rotation(None, 'foo'), False) self.assertEqual(rotation.is_rotation('', 'foo'), False) self.assertEqual(rotation.is_rotation('', ''), True) self.assertEqual(rotation.is_rotation('foobarbaz', 'barbazfoo'), True) print('Success: test_rotation') def main(): test = TestRotation() test.test_rotation() if __name__ == '__main__': main()
TestRotation
python
getsentry__sentry
src/sentry/snuba/metrics/extraction.py
{ "start": 19902, "end": 41899 }
class ____: """Result of a check for standard and on-demand metric support.""" standard_metrics: bool on_demand_metrics: bool @classmethod def neither(cls) -> Self: return cls(standard_metrics=False, on_demand_metrics=False) @classmethod def both(cls) -> Self: return cls(standard_metrics=True, on_demand_metrics=True) @classmethod def combine(cls, *supported_by: Self) -> Self: return cls( standard_metrics=all(s.standard_metrics for s in supported_by), on_demand_metrics=all(s.on_demand_metrics for s in supported_by), ) def should_use_on_demand_metrics_for_querying(organization: Organization, **kwargs: Any) -> bool: """Helper function to check if an organization can query an specific on-demand function""" components = _extract_aggregate_components(kwargs["aggregate"]) if components is None: return False function, _ = components # This helps us control which functions are allowed to use the new spec version. if function in OPS_REQUIRE_FEAT_FLAG: if not organization: # We need to let devs writting tests that if they intend to use a function that requires a feature flag # that the organization needs to be included in the test. if os.environ.get("PYTEST_CURRENT_TEST"): logger.error("Pass the organization to create the spec for this function.") sentry_sdk.capture_message( f"Organization is required for {function} on-demand metrics." ) return False feat_flag = OPS_REQUIRE_FEAT_FLAG[function] if not features.has(feat_flag, organization): if os.environ.get("PYTEST_CURRENT_TEST"): # This will show up in the logs and help the developer understand why the test is failing logger.error("Add the feature flag to create the spec for this function.") return False supported_by = _query_supported_by(**kwargs) if ( features.has("organizations:on-demand-gen-metrics-deprecation-query-prefill", organization) and supported_by.on_demand_metrics ): return True return should_use_on_demand_metrics(**kwargs) def _query_supported_by( dataset: str | Dataset | None, aggregate: str, query: str, groupbys: Sequence[str] | None = None, prefilling: bool = False, prefilling_for_deprecation: bool = False, ) -> SupportedBy: """On-demand metrics are used if the aggregate and query are supported by on-demand metrics but not standard""" groupbys = groupbys or [] supported_datasets = [Dataset.PerformanceMetrics] # In case we are running a prefill, we want to support also transactions, since our goal is to start extracting # metrics that will be needed after a query is converted from using transactions to metrics. if prefilling or prefilling_for_deprecation: supported_datasets.append(Dataset.Transactions) if not dataset or Dataset(dataset) not in supported_datasets: return SupportedBy(standard_metrics=False, on_demand_metrics=False) components = _extract_aggregate_components(aggregate) if components is None: return SupportedBy(standard_metrics=False, on_demand_metrics=False) function, args = components mri_aggregate = _extract_mri(args) if mri_aggregate is not None: # For now, we do not support MRIs in on demand metrics. return SupportedBy(standard_metrics=True, on_demand_metrics=False) aggregate_supported_by = _get_aggregate_supported_by(function, args) query_supported_by = _get_query_supported_by(query) groupbys_supported_by = _get_groupbys_support(groupbys) supported_by = SupportedBy.combine( aggregate_supported_by, query_supported_by, groupbys_supported_by ) return supported_by def _should_use_on_demand_metrics( dataset: str | Dataset | None, aggregate: str, query: str, groupbys: Sequence[str] | None = None, prefilling: bool = False, prefilling_for_deprecation: bool = False, ) -> bool: """On-demand metrics are used if the aggregate and query are supported by on-demand metrics but not standard""" supported_by = _query_supported_by( dataset, aggregate, query, groupbys, prefilling, prefilling_for_deprecation=prefilling_for_deprecation, ) if prefilling_for_deprecation: return supported_by.on_demand_metrics return not supported_by.standard_metrics and supported_by.on_demand_metrics @metrics.wraps("on_demand_metrics.should_use_on_demand_metrics") def should_use_on_demand_metrics( dataset: str | Dataset | None, aggregate: str, query: str, groupbys: Sequence[str] | None = None, prefilling: bool = False, organization_bulk_query_cache: dict[int, dict[str, bool]] | None = None, prefilling_for_deprecation: bool = False, ) -> bool: if in_random_rollout("on_demand_metrics.cache_should_use_on_demand"): if organization_bulk_query_cache is None: organization_bulk_query_cache = defaultdict(dict) dataset_str = dataset.value if isinstance(dataset, Enum) else str(dataset or "") groupbys_str = ",".join(sorted(groupbys)) if groupbys else "" local_cache_md5 = md5_text( f"{dataset_str}-{aggregate}-{query or ''}-{groupbys_str}-prefilling={prefilling}" ) local_cache_digest_chunk = local_cache_md5.digest()[0] % WIDGET_QUERY_CACHE_MAX_CHUNKS local_cache_key = local_cache_md5.hexdigest() cached_result = organization_bulk_query_cache.get(local_cache_digest_chunk, {}).get( local_cache_key, None ) if cached_result: metrics.incr("on_demand_metrics.should_use_on_demand_metrics.cache_hit") return cached_result else: result = _should_use_on_demand_metrics( dataset=dataset, aggregate=aggregate, query=query, groupbys=groupbys, prefilling=prefilling, prefilling_for_deprecation=prefilling_for_deprecation, ) metrics.incr("on_demand_metrics.should_use_on_demand_metrics.cache_miss") organization_bulk_query_cache[local_cache_digest_chunk][local_cache_key] = result return result return _should_use_on_demand_metrics( dataset=dataset, aggregate=aggregate, query=query, groupbys=groupbys, prefilling=prefilling, prefilling_for_deprecation=prefilling_for_deprecation, ) def _extract_aggregate_components(aggregate: str) -> tuple[str, list[str]] | None: try: if is_equation(aggregate): return None function, args, _ = _parse_function(aggregate) return function, args except InvalidSearchQuery: logger.exception("Failed to parse aggregate: %s", aggregate) return None def _extract_mri(args: list[str]) -> ParsedMRI | None: if len(args) == 0: return None return parse_mri(args[0]) def _get_aggregate_supported_by(function: str, args: list[str]) -> SupportedBy: function_support = _get_function_support(function, args) args_support = _get_args_support(args, function) return SupportedBy.combine(function_support, args_support) def _get_function_support(function: str, args: Sequence[str]) -> SupportedBy: if function == "percentile": return _get_percentile_support(args) return SupportedBy( standard_metrics=True, on_demand_metrics=( function in _SEARCH_TO_METRIC_AGGREGATES or function in _SEARCH_TO_DERIVED_METRIC_AGGREGATES ) and function in _AGGREGATE_TO_METRIC_TYPE, ) def _get_percentile_support(args: Sequence[str]) -> SupportedBy: if len(args) != 2: return SupportedBy.neither() if not _get_percentile_op(args): return SupportedBy.neither() return SupportedBy.both() def _get_percentile_op(args: Sequence[str]) -> MetricOperationType | None: if len(args) != 2: raise ValueError("Percentile function should have 2 arguments") percentile = args[1] if percentile in ["0.5", "0.50"]: return "p50" if percentile == "0.75": return "p75" if percentile in ["0.9", "0.90"]: return "p90" if percentile == "0.95": return "p95" if percentile == "0.99": return "p99" if percentile in ["1", "1.0"]: return "p100" return None def _get_field_support(field: str) -> SupportedBy: standard_metrics = _is_standard_metrics_field(field) on_demand_metrics = _is_on_demand_supported_field(field) return SupportedBy(standard_metrics=standard_metrics, on_demand_metrics=on_demand_metrics) def _get_args_support(fields: Sequence[str], used_in_function: str | None = None) -> SupportedBy: if len(fields) == 0: return SupportedBy.both() if used_in_function == "apdex": # apdex can have two variations, either apdex() or apdex(value). return SupportedBy(on_demand_metrics=True, standard_metrics=False) if used_in_function in ["epm", "eps"]: return SupportedBy.both() arg = fields[0] return _get_field_support(arg) def _get_groupbys_support(groupbys: Sequence[str]) -> SupportedBy: if len(groupbys) == 0: return SupportedBy.both() return SupportedBy.combine(*[_get_field_support(groupby) for groupby in groupbys]) def _get_query_supported_by(query: str) -> SupportedBy: try: parsed_query = parse_search_query(query=query, removed_blacklisted=False) standard_metrics = _is_standard_metrics_query(parsed_query) on_demand_metrics = _is_on_demand_supported_query(parsed_query) return SupportedBy(standard_metrics=standard_metrics, on_demand_metrics=on_demand_metrics) except InvalidSearchQuery: logger.exception("Failed to parse search query: %s", query) return SupportedBy.neither() def _is_standard_metrics_query(tokens: Sequence[QueryToken]) -> bool: """ Recursively checks if any of the supplied token contain search filters that can't be handled by standard metrics. """ for token in tokens: if not _is_standard_metrics_search_filter(token): return False return True def _is_standard_metrics_search_filter(token: QueryToken) -> bool: if isinstance(token, SearchFilter): return _is_standard_metrics_search_term(token.key.name) if isinstance(token, ParenExpression): return _is_standard_metrics_query(token.children) return True def _is_on_demand_supported_query(tokens: Sequence[QueryToken]) -> bool: """ Recursively checks if any of the supplied token contain search filters that can't be handled by standard metrics. """ for token in tokens: if not _is_on_demand_supported_search_filter(token): return False return True def _is_on_demand_supported_search_filter(token: QueryToken | AggregateFilter) -> bool: if isinstance(token, AggregateFilter): return False if isinstance(token, SearchFilter): if not _SEARCH_TO_RELAY_OPERATORS.get(token.operator): return False return ( not _is_excluding_transactions(token) and not _is_error_field(token.key.name) and _is_on_demand_supported_field(token.key.name) ) if isinstance(token, ParenExpression): return _is_on_demand_supported_query(token.children) return True def _is_excluding_transactions(token: SearchFilter) -> bool: if token.key.name != "event.type": return False is_not_transaction = token.operator == "!=" and token.value.raw_value == "transaction" is_error_or_default = token.operator == "=" and token.value.raw_value in ["error", "default"] return is_not_transaction or is_error_or_default def _is_standard_metrics_field(field: str) -> bool: return ( _is_standard_metrics_search_term(field) or is_measurement(field) or is_span_op_breakdown(field) or field == "transaction.duration" ) def _is_error_field(token: str) -> bool: return token.startswith("error.") or token in ERROR_RELATED_TOKENS def _is_standard_metrics_search_term(field: str) -> bool: return field in _STANDARD_METRIC_FIELDS or field in _IGNORED_METRIC_FIELDS def _is_on_demand_supported_field(field: str) -> bool: if field in _IGNORED_METRIC_FIELDS: return True try: _map_field_name(field) return True except ValueError: return False def to_standard_metrics_query(query: str) -> str: """ Converts a query containing on demand search fields to a query that can be run using only standard metrics. This is done by removing conditions requiring on-demand metrics. NOTE: This does **NOT** create an equivalent query. It only creates the best approximation available using only standard metrics. It is used for approximating the volume of an on-demand metrics query using a combination of indexed and metrics data. Examples: "environment:dev AND transaction.duration:>=1s" -> "environment:dev" "environment:dev OR transaction.duration:>=1s" -> "environment:dev" "transaction.duration:>=1s OR browser.version:1" -> "" "transaction.duration:>=1s AND browser.version:1" -> "" """ try: tokens = parse_search_query(query=query, removed_blacklisted=False) except InvalidSearchQuery: logger.exception("Failed to parse search query: %s", query) raise cleaned_query = to_standard_metrics_tokens(tokens) return query_tokens_to_string(cleaned_query) def to_standard_metrics_tokens(tokens: Sequence[QueryToken]) -> list[QueryToken]: """ Converts a query in token form containing on-demand search fields to a query that has all on-demand filters removed and can be run using only standard metrics. """ remaining_tokens = _remove_on_demand_search_filters(tokens) cleaned_query = cleanup_search_query(remaining_tokens) return cleaned_query def query_tokens_to_string(tokens: Sequence[QueryToken]) -> str: """ Converts a list of tokens into a query string. """ ret_val = "" for token in tokens: if isinstance(token, str): ret_val += f" {token}" else: ret_val += f" {token.to_query_string()}" return ret_val.strip() def _remove_on_demand_search_filters(tokens: Sequence[QueryToken]) -> list[QueryToken]: """ Removes tokens that contain filters that can only be handled by on demand metrics. """ ret_val: list[QueryToken] = [] for token in tokens: if isinstance(token, SearchFilter): if _is_standard_metrics_search_filter(token): ret_val.append(token) elif isinstance(token, ParenExpression): ret_val.append(ParenExpression(_remove_on_demand_search_filters(token.children))) else: ret_val.append(token) return ret_val def _remove_blacklisted_search_filters(tokens: Sequence[QueryToken]) -> list[QueryToken]: """ Removes tokens that contain filters that are blacklisted. """ ret_val: list[QueryToken] = [] for token in tokens: if isinstance(token, SearchFilter): if ( token.key.name not in _IGNORED_METRIC_FIELDS and str(token) not in _IGNORED_METRIC_CONDITION ): ret_val.append(token) elif isinstance(token, ParenExpression): ret_val.append(ParenExpression(_remove_blacklisted_search_filters(token.children))) else: ret_val.append(token) return ret_val def _remove_redundant_parentheses(tokens: Sequence[QueryToken]) -> Sequence[QueryToken]: """ Removes redundant parentheses in the form (((expr))) since they are not needed and might lead to parsing issues down the line. """ if len(tokens) == 1 and isinstance(tokens[0], ParenExpression): return _remove_redundant_parentheses(tokens[0].children) return tokens def _deep_sorted(value: Any | dict[Any, Any]) -> Any | dict[Any, Any]: if isinstance(value, dict): return {key: _deep_sorted(value) for key, value in sorted(value.items())} else: return value def are_specs_equal(spec_1: MetricSpec, spec_2: MetricSpec) -> bool: equal = True if spec_1.keys() != spec_2.keys(): equal = False if equal: for key, value in spec_1.items(): if key == "tags": return _compare_lists(spec_1["tags"], spec_2["tags"]) elif spec_2.get(key) != value: equal = False return equal def _compare_lists(list_1: Sequence[Any], list_2: Sequence[Any]) -> bool: if len(list_1) != len(list_2): return False for _, value in enumerate(list_1): if value not in list_2: return False return True TagsSpecsGenerator = Callable[[Project, Optional[Sequence[str]]], list[TagSpec]] def _get_threshold(arguments: Sequence[str] | None) -> float: if not arguments: raise Exception("Threshold parameter required.") return float(arguments[0]) def failure_tag_spec(_1: Project, _2: Sequence[str] | None) -> list[TagSpec]: """This specification tags transactions with a boolean saying if it failed.""" return [ { "key": "failure", "value": "true", "condition": { "inner": { "name": "event.contexts.trace.status", "op": "eq", "value": ["ok", "cancelled", "unknown"], }, "op": "not", }, } ] def apdex_tag_spec(project: Project, arguments: Sequence[str] | None) -> list[TagSpec]: apdex_threshold = _get_threshold(arguments) field = _map_field_name(_get_satisfactory_metric(project)) return [ { "key": "satisfaction", "value": "satisfactory", "condition": {"name": field, "op": "lte", "value": apdex_threshold}, }, { "key": "satisfaction", "value": "tolerable", "condition": { "inner": [ {"name": field, "op": "gt", "value": apdex_threshold}, {"name": field, "op": "lte", "value": apdex_threshold * 4}, ], "op": "and", }, }, { "key": "satisfaction", "value": "frustrated", "condition": {"name": field, "op": "gt", "value": apdex_threshold * 4}, }, ] def count_web_vitals_spec(project: Project, arguments: Sequence[str] | None) -> list[TagSpec]: if not arguments: raise Exception("count_web_vitals requires arguments") if len(arguments) != 2: raise Exception("count web vitals requires a vital name and vital rating") measurement, measurement_rating = arguments field = _map_field_name(measurement) _, vital = measurement.split(".") thresholds = VITAL_THRESHOLDS[vital] if measurement_rating == "good": return [ { "key": "measurement_rating", "value": "matches_hash", "condition": {"name": field, "op": "lt", "value": thresholds["meh"]}, } ] elif measurement_rating == "meh": return [ { "key": "measurement_rating", "value": "matches_hash", "condition": { "inner": [ {"name": field, "op": "gte", "value": thresholds["meh"]}, {"name": field, "op": "lt", "value": thresholds["poor"]}, ], "op": "and", }, } ] elif measurement_rating == "poor": return [ { "key": "measurement_rating", "value": "matches_hash", "condition": {"name": field, "op": "gte", "value": thresholds["poor"]}, } ] return [ # 'any' measurement_rating { "key": "measurement_rating", "value": "matches_hash", "condition": {"name": field, "op": "gte", "value": 0}, } ] def user_misery_tag_spec(project: Project, arguments: Sequence[str] | None) -> list[TagSpec]: """A metric that counts the number of unique users who were frustrated; "frustration" is measured as a response time four times the satisfactory response time threshold (in milliseconds). It highlights transactions that have the highest impact on users.""" threshold = _get_threshold(arguments) field = _map_field_name(_get_satisfactory_metric(project)) return [ { "key": "satisfaction", "value": "frustrated", "condition": {"name": field, "op": "gt", "value": threshold * 4}, } ] # This is used to map custom on-demand operations that requires special tags to a function which generates specs for those tags. _ONDEMAND_OP_TO_SPEC_GENERATOR: dict[MetricOperationType, TagsSpecsGenerator] = { "on_demand_failure_count": failure_tag_spec, "on_demand_failure_rate": failure_tag_spec, "on_demand_count_web_vitals": count_web_vitals_spec, } # Same as `_ONDEMAND_OP_TO_SPEC_GENERATOR` except these ops may have project specific specs. # We use this to opt out of some kinds of organization level cacheing. _ONDEMAND_OP_TO_PROJECT_SPEC_GENERATOR: dict[MetricOperationType, TagsSpecsGenerator] = { "on_demand_apdex": apdex_tag_spec, "on_demand_user_misery": user_misery_tag_spec, } @dataclass(frozen=True)
SupportedBy
python
pyqtgraph__pyqtgraph
pyqtgraph/opengl/items/GLMeshItem.py
{ "start": 544, "end": 13070 }
class ____(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem.GLGraphicsItem>` Displays a 3D triangle mesh. """ def __init__(self, parentItem=None, **kwds): """ ============== ===================================================== **Arguments:** meshdata MeshData object from which to determine geometry for this item. color Default face color used if no vertex or face colors are specified. edgeColor Default edge color to use if no edge colors are specified in the mesh data. drawEdges If True, a wireframe mesh will be drawn. (default=False) drawFaces If True, mesh faces are drawn. (default=True) shader Name of shader program to use when drawing faces. (None for no shader) smooth If True, normal vectors are computed for each vertex and interpolated within each face. computeNormals If False, then computation of normal vectors is disabled. This can provide a performance boost for meshes that do not make use of normals. ============== ===================================================== """ self.opts = { 'meshdata': None, 'color': (1., 1., 1., 1.), 'drawEdges': False, 'drawFaces': True, 'edgeColor': (0.5, 0.5, 0.5, 1.0), 'shader': None, 'smooth': True, 'computeNormals': True, } super().__init__(parentItem=parentItem) glopts = kwds.pop('glOptions', 'opaque') self.setGLOptions(glopts) shader = kwds.pop('shader', None) self.setShader(shader) self.setMeshData(**kwds) ## storage for data compiled from MeshData object self.vertexes = None self.normals = None self.colors = None self.faces = None self.m_vbo_position = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer) self.m_vbo_normal = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer) self.m_vbo_color = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer) self.m_ibo_faces = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.IndexBuffer) self.m_vbo_edgeVerts = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer) self.m_ibo_edges = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.IndexBuffer) def setShader(self, shader): """Set the shader used when rendering faces in the mesh. (see the GL shaders example)""" self.opts['shader'] = shader self.update() def shader(self): shader = self.opts['shader'] if isinstance(shader, shaders.ShaderProgram): return shader else: return shaders.getShaderProgram(shader) def setColor(self, c): """Set the default color to use when no vertex or face colors are specified.""" self.opts['color'] = c self.update() def setMeshData(self, **kwds): """ Set mesh data for this item. This can be invoked two ways: 1. Specify *meshdata* argument with a new MeshData object 2. Specify keyword arguments to be passed to MeshData(..) to create a new instance. """ md = kwds.get('meshdata', None) if md is None: opts = {} for k in ['vertexes', 'faces', 'edges', 'vertexColors', 'faceColors']: try: opts[k] = kwds.pop(k) except KeyError: pass md = MeshData(**opts) self.opts['meshdata'] = md self.opts.update(kwds) self.meshDataChanged() self.update() def meshDataChanged(self): """ This method must be called to inform the item that the MeshData object has been altered. """ self.vertexes = None self.faces = None self.normals = None self.colors = None self.edges = None self.edgeVerts = None self.edgeColors = None self.update() def upload_vertex_buffers(self, dirty_bits): def upload_vbo(vbo, arr): if arr is None: vbo.destroy() return if not vbo.isCreated(): vbo.create() vbo.bind() if vbo.size() != arr.nbytes: vbo.allocate(arr, arr.nbytes) else: vbo.write(0, arr, arr.nbytes) vbo.release() if DirtyFlag.POSITION in dirty_bits: upload_vbo(self.m_vbo_position, self.vertexes) if DirtyFlag.NORMAL in dirty_bits: upload_vbo(self.m_vbo_normal, self.normals) if DirtyFlag.COLOR in dirty_bits: upload_vbo(self.m_vbo_color, self.colors) if DirtyFlag.FACES in dirty_bits: upload_vbo(self.m_ibo_faces, self.faces) if DirtyFlag.EDGE_VERTS in dirty_bits: upload_vbo(self.m_vbo_edgeVerts, self.edgeVerts) if DirtyFlag.EDGES in dirty_bits: upload_vbo(self.m_ibo_edges, self.edges) def parseMeshData(self) -> DirtyFlag: ## interpret vertex / normal data before drawing dirty_bits = DirtyFlag(0) # self.vertexes acts as a flag to determine whether mesh data # has been parsed if self.vertexes is not None: return dirty_bits if self.opts['meshdata'] is not None: md = self.opts['meshdata'] if self.opts['smooth'] and not md.hasFaceIndexedData(): self.vertexes = md.vertexes() dirty_bits |= DirtyFlag.POSITION if self.opts['computeNormals']: self.normals = md.vertexNormals() dirty_bits |= DirtyFlag.NORMAL self.faces = md.faces().astype(np.uint32) dirty_bits |= DirtyFlag.FACES if md.hasVertexColor(): self.colors = md.vertexColors() dirty_bits |= DirtyFlag.COLOR elif md.hasFaceColor(): self.colors = md.faceColors() dirty_bits |= DirtyFlag.COLOR else: self.vertexes = md.vertexes(indexed='faces') dirty_bits |= DirtyFlag.POSITION if self.opts['computeNormals']: if self.opts['smooth']: self.normals = md.vertexNormals(indexed='faces') else: self.normals = md.faceNormals(indexed='faces') dirty_bits |= DirtyFlag.NORMAL self.faces = None if md.hasVertexColor(): self.colors = md.vertexColors(indexed='faces') dirty_bits |= DirtyFlag.COLOR elif md.hasFaceColor(): self.colors = md.faceColors(indexed='faces') dirty_bits |= DirtyFlag.COLOR if self.opts['drawEdges']: if not md.hasFaceIndexedData(): self.edges = md.edges().astype(np.uint32) self.edgeVerts = md.vertexes() else: self.edges = md.edges().astype(np.uint32) self.edgeVerts = md.vertexes(indexed='faces') dirty_bits |= DirtyFlag.EDGE_VERTS dirty_bits |= DirtyFlag.EDGES # NOTE: it is possible for self.vertexes to be None at this point. # this situation is encountered with the bundled animated # GLSurfacePlot example. This occurs because it only sets the # z component within update(). return dirty_bits def paint(self): self.setupGLState() if (dirty_bits := self.parseMeshData()): self.upload_vertex_buffers(dirty_bits) mat_mvp = self.mvpMatrix() mat_mvp = np.array(mat_mvp.data(), dtype=np.float32) mat_normal = self.modelViewMatrix().normalMatrix() mat_normal = np.array(mat_normal.data(), dtype=np.float32) context = QtGui.QOpenGLContext.currentContext() es2_compat = context.hasExtension(b'GL_ARB_ES2_compatibility') if self.opts['drawFaces'] and self.vertexes is not None: shader = self.shader() program = shader.program(es2_compat=es2_compat) enabled_locs = [] if (loc := GL.glGetAttribLocation(program, "a_position")) != -1: self.m_vbo_position.bind() GL.glVertexAttribPointer(loc, 3, GL.GL_FLOAT, False, 0, None) self.m_vbo_position.release() enabled_locs.append(loc) if (loc := GL.glGetAttribLocation(program, "a_normal")) != -1: if self.normals is None: # the shader needs a normal but the user set computeNormals=False... GL.glVertexAttrib3f(loc, 0, 0, 1) else: self.m_vbo_normal.bind() GL.glVertexAttribPointer(loc, 3, GL.GL_FLOAT, False, 0, None) self.m_vbo_normal.release() enabled_locs.append(loc) if (loc := GL.glGetAttribLocation(program, "a_color")) != -1: if self.colors is None: color = self.opts['color'] if isinstance(color, QtGui.QColor): color = color.getRgbF() GL.glVertexAttrib4f(loc, *color) else: self.m_vbo_color.bind() if self.colors.dtype == np.uint8: GL.glVertexAttribPointer(loc, 4, GL.GL_UNSIGNED_BYTE, True, 0, None) else: GL.glVertexAttribPointer(loc, 4, GL.GL_FLOAT, False, 0, None) self.m_vbo_color.release() enabled_locs.append(loc) for loc in enabled_locs: GL.glEnableVertexAttribArray(loc) with shader: # "with shader" will load extra uniforms loc = GL.glGetUniformLocation(program, "u_mvp") GL.glUniformMatrix4fv(loc, 1, False, mat_mvp) if (uloc_normal := GL.glGetUniformLocation(program, "u_normal")) != -1: GL.glUniformMatrix3fv(uloc_normal, 1, False, mat_normal) if (faces := self.faces) is None: GL.glDrawArrays(GL.GL_TRIANGLES, 0, np.prod(self.vertexes.shape[:-1])) else: self.m_ibo_faces.bind() GL.glDrawElements(GL.GL_TRIANGLES, faces.size, GL.GL_UNSIGNED_INT, None) self.m_ibo_faces.release() for loc in enabled_locs: GL.glDisableVertexAttribArray(loc) if self.opts['drawEdges']: shader = shaders.getShaderProgram(None) program = shader.program(es2_compat=es2_compat) enabled_locs = [] if (loc := GL.glGetAttribLocation(program, "a_position")) != -1: self.m_vbo_edgeVerts.bind() GL.glVertexAttribPointer(loc, 3, GL.GL_FLOAT, False, 0, None) self.m_vbo_edgeVerts.release() enabled_locs.append(loc) # edge colors are always just one single color if (loc := GL.glGetAttribLocation(program, "a_color")) != -1: color = self.opts['edgeColor'] if isinstance(color, QtGui.QColor): color = color.getRgbF() GL.glVertexAttrib4f(loc, *color) for loc in enabled_locs: GL.glEnableVertexAttribArray(loc) with program: loc = GL.glGetUniformLocation(program, "u_mvp") GL.glUniformMatrix4fv(loc, 1, False, mat_mvp) self.m_ibo_edges.bind() GL.glDrawElements(GL.GL_LINES, self.edges.size, GL.GL_UNSIGNED_INT, None) self.m_ibo_edges.release() for loc in enabled_locs: GL.glDisableVertexAttribArray(loc)
GLMeshItem
python
ipython__ipython
IPython/core/shellapp.py
{ "start": 5150, "end": 19501 }
class ____(Configurable): """A Mixin for applications that start InteractiveShell instances. Provides configurables for loading extensions and executing files as part of configuring a Shell environment. The following methods should be called by the :meth:`initialize` method of the subclass: - :meth:`init_path` - :meth:`init_shell` (to be implemented by the subclass) - :meth:`init_gui_pylab` - :meth:`init_extensions` - :meth:`init_code` """ extensions = List(Unicode(), help="A list of dotted module names of IPython extensions to load." ).tag(config=True) extra_extensions = List( DottedObjectName(), help=""" Dotted module name(s) of one or more IPython extensions to load. For specifying extra extensions to load on the command-line. .. versionadded:: 7.10 """, ).tag(config=True) reraise_ipython_extension_failures = Bool(False, help="Reraise exceptions encountered loading IPython extensions?", ).tag(config=True) # Extensions that are always loaded (not configurable) default_extensions = List(Unicode(), [u'storemagic']).tag(config=False) hide_initial_ns = Bool(True, help="""Should variables loaded at startup (by startup files, exec_lines, etc.) be hidden from tools like %who?""" ).tag(config=True) exec_files = List(Unicode(), help="""List of files to run at IPython startup.""" ).tag(config=True) exec_PYTHONSTARTUP = Bool(True, help="""Run the file referenced by the PYTHONSTARTUP environment variable at IPython startup.""" ).tag(config=True) file_to_run = Unicode('', help="""A file to be run""").tag(config=True) exec_lines = List(Unicode(), help="""lines of code to run at IPython startup.""" ).tag(config=True) code_to_run = Unicode("", help="Execute the given command string.").tag(config=True) module_to_run = Unicode("", help="Run the module as a script.").tag(config=True) gui = CaselessStrEnum( gui_keys, allow_none=True, help="Enable GUI event loop integration with any of {0}.".format(gui_keys), ).tag(config=True) matplotlib = MatplotlibBackendCaselessStrEnum( allow_none=True, help="""Configure matplotlib for interactive use with the default matplotlib backend. The exact options available depend on what Matplotlib provides at runtime.""", ).tag(config=True) pylab = MatplotlibBackendCaselessStrEnum( allow_none=True, help="""Pre-load matplotlib and numpy for interactive use, selecting a particular matplotlib backend and loop integration. The exact options available depend on what Matplotlib provides at runtime. """, ).tag(config=True) pylab_import_all = Bool( True, help="""If true, IPython will populate the user namespace with numpy, pylab, etc. and an ``import *`` is done from numpy and pylab, when using pylab mode. When False, pylab mode should not import any names into the user namespace. """, ).tag(config=True) ignore_cwd = Bool( False, help="""If True, IPython will not add the current working directory to sys.path. When False, the current working directory is added to sys.path, allowing imports of modules defined in the current directory.""" ).tag(config=True) shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) # whether interact-loop should start interact = Bool(True) user_ns = Instance(dict, args=None, allow_none=True) @observe('user_ns') def _user_ns_changed(self, change): if self.shell is not None: self.shell.user_ns = change['new'] self.shell.init_user_ns() def init_path(self): """Add current working directory, '', to sys.path Unless disabled by ignore_cwd config or sys.flags.safe_path. Unlike Python's default, we insert before the first `site-packages` or `dist-packages` directory, so that it is after the standard library. .. versionchanged:: 7.2 Try to insert after the standard library, instead of first. .. versionchanged:: 8.0 Allow optionally not including the current directory in sys.path .. versionchanged:: 9.7 Respect sys.flags.safe_path (PYTHONSAFEPATH and -P flag) """ if "" in sys.path or self.ignore_cwd or sys.flags.safe_path: return for idx, path in enumerate(sys.path): parent, last_part = os.path.split(path) if last_part in {'site-packages', 'dist-packages'}: break else: # no site-packages or dist-packages found (?!) # back to original behavior of inserting at the front idx = 0 sys.path.insert(idx, '') def init_shell(self): raise NotImplementedError("Override in subclasses") def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" enable = False shell = self.shell if self.pylab: enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all) key = self.pylab elif self.matplotlib: enable = shell.enable_matplotlib key = self.matplotlib elif self.gui: enable = shell.enable_gui key = self.gui if not enable: return try: r = enable(key) except ImportError: self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?") self.shell.showtraceback() return except Exception: self.log.warning("GUI event loop or pylab initialization failed") self.shell.showtraceback() return if isinstance(r, tuple): gui, backend = r[:2] self.log.info("Enabling GUI event loop integration, " "eventloop=%s, matplotlib=%s", gui, backend) if key == "auto": print("Using matplotlib backend: %s" % backend) else: gui = r self.log.info("Enabling GUI event loop integration, " "eventloop=%s", gui) def init_extensions(self): """Load all IPython extensions in IPythonApp.extensions. This uses the :meth:`ExtensionManager.load_extensions` to load all the extensions listed in ``self.extensions``. """ try: self.log.debug("Loading IPython extensions...") extensions = ( self.default_extensions + self.extensions + self.extra_extensions ) for ext in extensions: try: self.log.info("Loading IPython extension: %s", ext) self.shell.extension_manager.load_extension(ext) except: if self.reraise_ipython_extension_failures: raise msg = ("Error in loading extension: {ext}\n" "Check your config files in {location}".format( ext=ext, location=self.profile_dir.location )) self.log.warning(msg, exc_info=True) except: if self.reraise_ipython_extension_failures: raise self.log.warning("Unknown error in loading extensions:", exc_info=True) def init_code(self): """run the pre-flight code, specified via exec_lines""" self._run_startup_files() self._run_exec_lines() self._run_exec_files() # Hide variables defined here from %who etc. if self.hide_initial_ns: self.shell.user_ns_hidden.update(self.shell.user_ns) # command-line execution (ipython -i script.py, ipython -m module) # should *not* be excluded from %whos self._run_cmd_line_code() self._run_module() # flush output, so itwon't be attached to the first cell sys.stdout.flush() sys.stderr.flush() self.shell._sys_modules_keys = set(sys.modules.keys()) def _run_exec_lines(self): """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" if not self.exec_lines: return try: self.log.debug("Running code from IPythonApp.exec_lines...") for line in self.exec_lines: try: self.log.info("Running code in user namespace: %s" % line) self.shell.run_cell(line, store_history=False) except: self.log.warning("Error in executing line in user " "namespace: %s" % line) self.shell.showtraceback() except: self.log.warning("Unknown error in handling IPythonApp.exec_lines:") self.shell.showtraceback() def _exec_file(self, fname, shell_futures=False): try: full_filename = filefind(fname, [u'.', self.ipython_dir]) except IOError: self.log.warning("File not found: %r"%fname) return # Make sure that the running script gets a proper sys.argv as if it # were run from a system shell. save_argv = sys.argv sys.argv = [full_filename] + self.extra_args[1:] try: if os.path.isfile(full_filename): self.log.info("Running file in user namespace: %s" % full_filename) # Ensure that __file__ is always defined to match Python # behavior. with preserve_keys(self.shell.user_ns, '__file__'): self.shell.user_ns['__file__'] = fname if full_filename.endswith('.ipy') or full_filename.endswith('.ipynb'): self.shell.safe_execfile_ipy(full_filename, shell_futures=shell_futures) else: # default to python, even without extension self.shell.safe_execfile(full_filename, self.shell.user_ns, shell_futures=shell_futures, raise_exceptions=True) finally: sys.argv = save_argv def _run_startup_files(self): """Run files from profile startup directory""" startup_dirs = [self.profile_dir.startup_dir] + [ os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS) ] startup_files = [] if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \ not (self.file_to_run or self.code_to_run or self.module_to_run): python_startup = os.environ['PYTHONSTARTUP'] self.log.debug("Running PYTHONSTARTUP file %s...", python_startup) try: self._exec_file(python_startup) except: self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup) self.shell.showtraceback() for startup_dir in startup_dirs[::-1]: startup_files += glob.glob(os.path.join(startup_dir, '*.py')) startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) if not startup_files: return self.log.debug("Running startup files from %s...", startup_dir) try: for fname in sorted(startup_files): self._exec_file(fname) except: self.log.warning("Unknown error in handling startup files:") self.shell.showtraceback() def _run_exec_files(self): """Run files from IPythonApp.exec_files""" if not self.exec_files: return self.log.debug("Running files in IPythonApp.exec_files...") try: for fname in self.exec_files: self._exec_file(fname) except: self.log.warning("Unknown error in handling IPythonApp.exec_files:") self.shell.showtraceback() def _run_cmd_line_code(self): """Run code or file specified at the command-line""" if self.code_to_run: line = self.code_to_run try: self.log.info("Running code given at command line (c=): %s" % line) self.shell.run_cell(line, store_history=False) except: self.log.warning("Error in executing line in user namespace: %s" % line) self.shell.showtraceback() if not self.interact: self.exit(1) # Like Python itself, ignore the second if the first of these is present elif self.file_to_run: fname = self.file_to_run if os.path.isdir(fname): fname = os.path.join(fname, "__main__.py") if not os.path.exists(fname): self.log.warning("File '%s' doesn't exist", fname) if not self.interact: self.exit(2) try: self._exec_file(fname, shell_futures=True) except: self.shell.showtraceback(tb_offset=4) if not self.interact: self.exit(1) def _run_module(self): """Run module specified at the command-line.""" if self.module_to_run: # Make sure that the module gets a proper sys.argv as if it were # run using `python -m`. save_argv = sys.argv sys.argv = [sys.executable] + self.extra_args try: self.shell.safe_run_module(self.module_to_run, self.shell.user_ns) finally: sys.argv = save_argv
InteractiveShellApp
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed7.py
{ "start": 256, "end": 485 }
class ____(TypedDict, total=False, extra_items=int): a: int td1: TD1 = {"a": 1} reveal_type(td1.clear, expected_text="() -> None") reveal_type(td1.popitem, expected_text="() -> tuple[str, int]") td1.clear() td1.popitem()
TD1
python
joke2k__faker
faker/providers/company/sk_SK/__init__.py
{ "start": 45, "end": 327 }
class ____(CompanyProvider): formats = ( "{{last_name}} {{company_suffix}}", "{{last_name}} {{last_name}} {{company_suffix}}", "{{last_name}}", ) company_suffixes = ( "s.r.o.", "v.o.s.", "a.s.", "k.s.", )
Provider
python
pypa__setuptools
setuptools/tests/test_editable_install.py
{ "start": 14238, "end": 27747 }
class ____: """This test focus in getting a particular implementation detail right. If at some point in time the implementation is changed for something different, this test can be modified or even excluded. """ def install_finder(self, finder): loc = {} exec(finder, loc, loc) loc["install"]() def test_packages(self, tmp_path): files = { "src1": { "pkg1": { "__init__.py": "", "subpkg": {"mod1.py": "a = 42"}, }, }, "src2": {"mod2.py": "a = 43"}, } jaraco.path.build(files, prefix=tmp_path) mapping = { "pkg1": str(tmp_path / "src1/pkg1"), "mod2": str(tmp_path / "src2/mod2"), } template = _finder_template(str(uuid4()), mapping, {}) with contexts.save_paths(), contexts.save_sys_modules(): for mod in ("pkg1", "pkg1.subpkg", "pkg1.subpkg.mod1", "mod2"): sys.modules.pop(mod, None) self.install_finder(template) mod1 = import_module("pkg1.subpkg.mod1") mod2 = import_module("mod2") subpkg = import_module("pkg1.subpkg") assert mod1.a == 42 assert mod2.a == 43 expected = str((tmp_path / "src1/pkg1/subpkg").resolve()) assert_path(subpkg, expected) def test_namespace(self, tmp_path): files = {"pkg": {"__init__.py": "a = 13", "text.txt": "abc"}} jaraco.path.build(files, prefix=tmp_path) mapping = {"ns.othername": str(tmp_path / "pkg")} namespaces = {"ns": []} template = _finder_template(str(uuid4()), mapping, namespaces) with contexts.save_paths(), contexts.save_sys_modules(): for mod in ("ns", "ns.othername"): sys.modules.pop(mod, None) self.install_finder(template) pkg = import_module("ns.othername") text = importlib_resources.files(pkg) / "text.txt" expected = str((tmp_path / "pkg").resolve()) assert_path(pkg, expected) assert pkg.a == 13 # Make sure resources can also be found assert text.read_text(encoding="utf-8") == "abc" def test_combine_namespaces(self, tmp_path): files = { "src1": {"ns": {"pkg1": {"__init__.py": "a = 13"}}}, "src2": {"ns": {"mod2.py": "b = 37"}}, } jaraco.path.build(files, prefix=tmp_path) mapping = { "ns.pkgA": str(tmp_path / "src1/ns/pkg1"), "ns": str(tmp_path / "src2/ns"), } namespaces_ = {"ns": [str(tmp_path / "src1"), str(tmp_path / "src2")]} template = _finder_template(str(uuid4()), mapping, namespaces_) with contexts.save_paths(), contexts.save_sys_modules(): for mod in ("ns", "ns.pkgA", "ns.mod2"): sys.modules.pop(mod, None) self.install_finder(template) pkgA = import_module("ns.pkgA") mod2 = import_module("ns.mod2") expected = str((tmp_path / "src1/ns/pkg1").resolve()) assert_path(pkgA, expected) assert pkgA.a == 13 assert mod2.b == 37 def test_combine_namespaces_nested(self, tmp_path): """ Users may attempt to combine namespace packages in a nested way via ``package_dir`` as shown in pypa/setuptools#4248. """ files = { "src": {"my_package": {"my_module.py": "a = 13"}}, "src2": {"my_package2": {"my_module2.py": "b = 37"}}, } stack = jaraco.path.DirectoryStack() with stack.context(tmp_path): jaraco.path.build(files) attrs = { "script_name": "%PEP 517%", "package_dir": { "different_name": "src/my_package", "different_name.subpkg": "src2/my_package2", }, "packages": ["different_name", "different_name.subpkg"], } dist = Distribution(attrs) finder = _TopLevelFinder(dist, str(uuid4())) code = next(v for k, v in finder.get_implementation() if k.endswith(".py")) with contexts.save_paths(), contexts.save_sys_modules(): for mod in attrs["packages"]: sys.modules.pop(mod, None) self.install_finder(code) mod1 = import_module("different_name.my_module") mod2 = import_module("different_name.subpkg.my_module2") expected = str((tmp_path / "src/my_package/my_module.py").resolve()) assert str(Path(mod1.__file__).resolve()) == expected expected = str((tmp_path / "src2/my_package2/my_module2.py").resolve()) assert str(Path(mod2.__file__).resolve()) == expected assert mod1.a == 13 assert mod2.b == 37 def test_dynamic_path_computation(self, tmp_path): # Follows the example in PEP 420 files = { "project1": {"parent": {"child": {"one.py": "x = 1"}}}, "project2": {"parent": {"child": {"two.py": "x = 2"}}}, "project3": {"parent": {"child": {"three.py": "x = 3"}}}, } jaraco.path.build(files, prefix=tmp_path) mapping = {} namespaces_ = {"parent": [str(tmp_path / "project1/parent")]} template = _finder_template(str(uuid4()), mapping, namespaces_) mods = (f"parent.child.{name}" for name in ("one", "two", "three")) with contexts.save_paths(), contexts.save_sys_modules(): for mod in ("parent", "parent.child", "parent.child", *mods): sys.modules.pop(mod, None) self.install_finder(template) one = import_module("parent.child.one") assert one.x == 1 with pytest.raises(ImportError): import_module("parent.child.two") sys.path.append(str(tmp_path / "project2")) two = import_module("parent.child.two") assert two.x == 2 with pytest.raises(ImportError): import_module("parent.child.three") sys.path.append(str(tmp_path / "project3")) three = import_module("parent.child.three") assert three.x == 3 def test_no_recursion(self, tmp_path): # See issue #3550 files = { "pkg": { "__init__.py": "from . import pkg", }, } jaraco.path.build(files, prefix=tmp_path) mapping = { "pkg": str(tmp_path / "pkg"), } template = _finder_template(str(uuid4()), mapping, {}) with contexts.save_paths(), contexts.save_sys_modules(): sys.modules.pop("pkg", None) self.install_finder(template) with pytest.raises(ImportError, match="pkg"): import_module("pkg") def test_similar_name(self, tmp_path): files = { "foo": { "__init__.py": "", "bar": { "__init__.py": "", }, }, } jaraco.path.build(files, prefix=tmp_path) mapping = { "foo": str(tmp_path / "foo"), } template = _finder_template(str(uuid4()), mapping, {}) with contexts.save_paths(), contexts.save_sys_modules(): sys.modules.pop("foo", None) sys.modules.pop("foo.bar", None) self.install_finder(template) with pytest.raises(ImportError, match="foobar"): import_module("foobar") def test_case_sensitivity(self, tmp_path): files = { "foo": { "__init__.py": "", "lowercase.py": "x = 1", "bar": { "__init__.py": "", "lowercase.py": "x = 2", }, }, } jaraco.path.build(files, prefix=tmp_path) mapping = { "foo": str(tmp_path / "foo"), } template = _finder_template(str(uuid4()), mapping, {}) with contexts.save_paths(), contexts.save_sys_modules(): sys.modules.pop("foo", None) self.install_finder(template) with pytest.raises(ImportError, match="'FOO'"): import_module("FOO") with pytest.raises(ImportError, match="'foo\\.LOWERCASE'"): import_module("foo.LOWERCASE") with pytest.raises(ImportError, match="'foo\\.bar\\.Lowercase'"): import_module("foo.bar.Lowercase") with pytest.raises(ImportError, match="'foo\\.BAR'"): import_module("foo.BAR.lowercase") with pytest.raises(ImportError, match="'FOO'"): import_module("FOO.bar.lowercase") mod = import_module("foo.lowercase") assert mod.x == 1 mod = import_module("foo.bar.lowercase") assert mod.x == 2 def test_namespace_case_sensitivity(self, tmp_path): files = { "pkg": { "__init__.py": "a = 13", "foo": { "__init__.py": "b = 37", "bar.py": "c = 42", }, }, } jaraco.path.build(files, prefix=tmp_path) mapping = {"ns.othername": str(tmp_path / "pkg")} namespaces = {"ns": []} template = _finder_template(str(uuid4()), mapping, namespaces) with contexts.save_paths(), contexts.save_sys_modules(): for mod in ("ns", "ns.othername"): sys.modules.pop(mod, None) self.install_finder(template) pkg = import_module("ns.othername") expected = str((tmp_path / "pkg").resolve()) assert_path(pkg, expected) assert pkg.a == 13 foo = import_module("ns.othername.foo") assert foo.b == 37 bar = import_module("ns.othername.foo.bar") assert bar.c == 42 with pytest.raises(ImportError, match="'NS'"): import_module("NS.othername.foo") with pytest.raises(ImportError, match="'ns\\.othername\\.FOO\\'"): import_module("ns.othername.FOO") with pytest.raises(ImportError, match="'ns\\.othername\\.foo\\.BAR\\'"): import_module("ns.othername.foo.BAR") def test_intermediate_packages(self, tmp_path): """ The finder should not import ``fullname`` if the intermediate segments don't exist (see pypa/setuptools#4019). """ files = { "src": { "mypkg": { "__init__.py": "", "config.py": "a = 13", "helloworld.py": "b = 13", "components": { "config.py": "a = 37", }, }, } } jaraco.path.build(files, prefix=tmp_path) mapping = {"mypkg": str(tmp_path / "src/mypkg")} template = _finder_template(str(uuid4()), mapping, {}) with contexts.save_paths(), contexts.save_sys_modules(): for mod in ( "mypkg", "mypkg.config", "mypkg.helloworld", "mypkg.components", "mypkg.components.config", "mypkg.components.helloworld", ): sys.modules.pop(mod, None) self.install_finder(template) config = import_module("mypkg.components.config") assert config.a == 37 helloworld = import_module("mypkg.helloworld") assert helloworld.b == 13 with pytest.raises(ImportError): import_module("mypkg.components.helloworld") def test_pkg_roots(tmp_path): """This test focus in getting a particular implementation detail right. If at some point in time the implementation is changed for something different, this test can be modified or even excluded. """ files = { "a": {"b": {"__init__.py": "ab = 1"}, "__init__.py": "a = 1"}, "d": {"__init__.py": "d = 1", "e": {"__init__.py": "de = 1"}}, "f": {"g": {"h": {"__init__.py": "fgh = 1"}}}, "other": {"__init__.py": "abc = 1"}, "another": {"__init__.py": "abcxyz = 1"}, "yet_another": {"__init__.py": "mnopq = 1"}, } jaraco.path.build(files, prefix=tmp_path) package_dir = { "a.b.c": "other", "a.b.c.x.y.z": "another", "m.n.o.p.q": "yet_another", } packages = [ "a", "a.b", "a.b.c", "a.b.c.x.y", "a.b.c.x.y.z", "d", "d.e", "f", "f.g", "f.g.h", "m.n.o.p.q", ] roots = _find_package_roots(packages, package_dir, tmp_path) assert roots == { "a": str(tmp_path / "a"), "a.b.c": str(tmp_path / "other"), "a.b.c.x.y.z": str(tmp_path / "another"), "d": str(tmp_path / "d"), "f": str(tmp_path / "f"), "m.n.o.p.q": str(tmp_path / "yet_another"), } ns = set(dict(_find_namespaces(packages, roots))) assert ns == {"f", "f.g"} ns = set(_find_virtual_namespaces(roots)) assert ns == {"a.b", "a.b.c.x", "a.b.c.x.y", "m", "m.n", "m.n.o", "m.n.o.p"}
TestFinderTemplate
python
jazzband__django-model-utils
tests/test_choices.py
{ "start": 1871, "end": 2686 }
class ____(TestCase, ChoicesTestsMixin[str]): def setUp(self) -> None: self.STATUS = Choices('DRAFT', 'PUBLISHED') def test_indexing(self) -> None: self.assertEqual(self.STATUS['PUBLISHED'], 'PUBLISHED') def test_iteration(self) -> None: self.assertEqual(tuple(self.STATUS), (('DRAFT', 'DRAFT'), ('PUBLISHED', 'PUBLISHED'))) def test_reversed(self) -> None: self.assertEqual(tuple(reversed(self.STATUS)), (('PUBLISHED', 'PUBLISHED'), ('DRAFT', 'DRAFT'))) def test_contains_value(self) -> None: self.assertTrue('PUBLISHED' in self.STATUS) self.assertTrue('DRAFT' in self.STATUS) def test_doesnt_contain_value(self) -> None: self.assertFalse('UNPUBLISHED' in self.STATUS)
ChoicesTests
python
ray-project__ray
python/ray/data/datasource/file_datasink.py
{ "start": 1061, "end": 6925 }
class ____(Datasink[None]): def __init__( self, path: str, *, filesystem: Optional["pyarrow.fs.FileSystem"] = None, try_create_dir: bool = True, open_stream_args: Optional[Dict[str, Any]] = None, filename_provider: Optional[FilenameProvider] = None, dataset_uuid: Optional[str] = None, file_format: Optional[str] = None, mode: SaveMode = SaveMode.APPEND, ): """Initialize this datasink. Args: path: The folder to write files to. filesystem: The filesystem to write files to. If not provided, the filesystem is inferred from the path. try_create_dir: Whether to create the directory to write files to. open_stream_args: Arguments to pass to ``filesystem.open_output_stream``. filename_provider: A :class:`ray.data.datasource.FilenameProvider` that generates filenames for each row or block. dataset_uuid: The UUID of the dataset being written. If specified, it's included in the filename. file_format: The file extension. If specified, files are written with this extension. """ if open_stream_args is None: open_stream_args = {} if filename_provider is None: filename_provider = _DefaultFilenameProvider( dataset_uuid=dataset_uuid, file_format=file_format ) self._data_context = DataContext.get_current() self.unresolved_path = path paths, self.filesystem = _resolve_paths_and_filesystem(path, filesystem) self.filesystem = RetryingPyFileSystem.wrap( self.filesystem, retryable_errors=self._data_context.retried_io_errors ) assert len(paths) == 1, len(paths) self.path = paths[0] self.try_create_dir = try_create_dir self.open_stream_args = open_stream_args self.filename_provider = filename_provider self.dataset_uuid = dataset_uuid self.file_format = file_format self.mode = mode self.has_created_dir = False def open_output_stream(self, path: str) -> "pyarrow.NativeFile": return self.filesystem.open_output_stream(path, **self.open_stream_args) def on_write_start(self) -> None: from pyarrow.fs import FileType dir_exists = ( self.filesystem.get_file_info(self.path).type is not FileType.NotFound ) if dir_exists: if self.mode == SaveMode.ERROR: raise ValueError( f"Path {self.path} already exists. If this is unexpected, use mode='ignore' to ignore those files" ) if self.mode == SaveMode.IGNORE: logger.warning(f"[SaveMode={self.mode}] Skipping {self.path}") return if self.mode == SaveMode.OVERWRITE: logger.warning(f"[SaveMode={self.mode}] Replacing contents {self.path}") self.filesystem.delete_dir_contents(self.path) self.has_created_dir = self._create_dir(self.path) def _create_dir(self, dest) -> bool: """Create a directory to write files to. If ``try_create_dir`` is ``False``, this method is a no-op. """ from pyarrow.fs import FileType # We should skip creating directories in s3 unless the user specifically # overrides this behavior. PyArrow's s3fs implementation for create_dir # will attempt to check if the parent directory exists before trying to # create the directory (with recursive=True it will try to do this to # all of the directories until the root of the bucket). An IAM Policy that # restricts access to a subset of prefixes within the bucket might cause # the creation of the directory to fail even if the permissions should # allow the data can be written to the specified path. For example if a # a policy only allows users to write blobs prefixed with s3://bucket/foo # a call to create_dir for s3://bucket/foo/bar will fail even though it # should not. parsed_uri = urlparse(dest) is_s3_uri = parsed_uri.scheme == "s3" skip_create_dir_for_s3 = is_s3_uri and not self._data_context.s3_try_create_dir if self.try_create_dir and not skip_create_dir_for_s3: if self.filesystem.get_file_info(dest).type is FileType.NotFound: # Arrow's S3FileSystem doesn't allow creating buckets by default, so we # add a query arg enabling bucket creation if an S3 URI is provided. tmp = add_creatable_buckets_param_if_s3_uri(dest) self.filesystem.create_dir(tmp, recursive=True) return True return False def write( self, blocks: Iterable[Block], ctx: TaskContext, ) -> None: builder = DelegatingBlockBuilder() for block in blocks: builder.add_block(block) block = builder.build() block_accessor = BlockAccessor.for_block(block) if block_accessor.num_rows() == 0: logger.warning(f"Skipped writing empty block to {self.path}") return self.write_block(block_accessor, 0, ctx) def write_block(self, block: BlockAccessor, block_index: int, ctx: TaskContext): raise NotImplementedError def on_write_complete(self, write_result: WriteResult[None]): # If no rows were written, we can delete the directory. if self.has_created_dir and write_result.num_rows == 0: self.filesystem.delete_dir(self.path) @property def supports_distributed_writes(self) -> bool: return not _is_local_scheme(self.unresolved_path) @DeveloperAPI
_FileDatasink
python
crytic__slither
slither/detectors/compiler_bugs/public_mapping_nested.py
{ "start": 2030, "end": 3741 }
class ____(AbstractDetector): """ Detects public mappings with nested variables (returns incorrect values prior to 0.5.x) """ ARGUMENT = "public-mappings-nested" HELP = "Public mappings with nested variables" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#public-mappings-with-nested-variables" WIKI_TITLE = "Public mappings with nested variables" WIKI_DESCRIPTION = "Prior to Solidity 0.5, a public mapping with nested structures returned [incorrect values](https://github.com/ethereum/solidity/issues/5520)." WIKI_EXPLOIT_SCENARIO = """Bob interacts with a contract that has a public mapping with nested structures. The values returned by the mapping are incorrect, breaking Bob's usage""" WIKI_RECOMMENDATION = "Do not use public mapping with nested structures." VULNERABLE_SOLC_VERSIONS = ALL_SOLC_VERSIONS_04 def _detect(self) -> List[Output]: """ Detect public mappings with nested variables (returns incorrect values prior to 0.5.x) Returns: list: {'vuln', 'filename,'contract','func', 'public_nested_mappings'} """ results = [] for contract in self.contracts: public_nested_mappings = detect_public_nested_mappings(contract) if public_nested_mappings: for public_nested_mapping in public_nested_mappings: info = [public_nested_mapping, " is a public mapping with nested variables\n"] json = self.generate_result(info) results.append(json) return results
PublicMappingNested
python
scipy__scipy
scipy/stats/tests/test_morestats.py
{ "start": 48544, "end": 53642 }
class ____: def _perturb(self, g, rng=124987234782812): # g arrays have ties to which statistic is very sensitive; break them rng = np.random.default_rng(rng) return (np.asarray(g) + 1e-10 * rng.standard_normal(len(g))).tolist() @pytest.mark.parametrize('dtype', [None, 'float32', 'float64']) def test_data(self, dtype, xp): if is_numpy(xp) and dtype == 'float32' and xp.__version__ < "2": pytest.skip("Scalar dtypes only respected after NEP 50.") # numbers from R: fligner.test in package stats dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype) x1 = xp.arange(5, dtype=dtype) res = stats.fligner(x1, x1**2) ref = (xp.asarray(3.2282229927203536, dtype=dtype), xp.asarray(0.072379187848207877, dtype=dtype)) xp_assert_close(res[0], ref[0]) xp_assert_close(res[1], ref[1]) def test_trimmed1(self, xp): # Perturb input to break ties in the transformed data # See https://github.com/scipy/scipy/pull/8042 for more details rng = np.random.default_rng(9952379681) g1_ = xp.asarray(self._perturb(g1, rng=rng)) g2_ = xp.asarray(self._perturb(g2, rng=rng)) g3_ = xp.asarray(self._perturb(g3, rng=rng)) # Test that center='trimmed' gives the same result as center='mean' # when proportiontocut=0. Xsq1, pval1 = stats.fligner(g1_, g2_, g3_, center='mean') Xsq2, pval2 = stats.fligner(g1_, g2_, g3_, center='trimmed', proportiontocut=0.0) xp_assert_close(Xsq1, Xsq2) xp_assert_close(pval1, pval2) @pytest.mark.skip_xp_backends(np_only=True, reason="inconsistent tie-breaking across backends") def test_trimmed_nonregression(self, xp): # This is a non-regression test # Expected results are *not* from an external gold standard, # we're just making sure the results remain consistent # in the future in case of changes args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] args = [xp.asarray(arg, dtype=xp.float64) for arg in args] W, pval = stats.fligner(*args, center="trimmed", proportiontocut=0.25) xp_assert_close(W, xp.asarray(15.953569890010614), rtol=5e-14) xp_assert_close(pval, xp.asarray(0.06785752327432863), rtol=5e-14) def test_trimmed_consistency(self, xp): # Tests for consistency across multiple backends when ties are broken rng = np.random.default_rng(4839206199) args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10] args = [self._perturb(arg, rng=rng) for arg in args] ref = stats.fligner(*args, center="trimmed", proportiontocut=0.25) args = [xp.asarray(arg, dtype=xp.float64) for arg in args] res = stats.fligner(*args, center="trimmed", proportiontocut=0.25) xp_assert_close(res.statistic, xp.asarray(ref.statistic), rtol=5e-14) xp_assert_close(res.pvalue, xp.asarray(ref.pvalue), rtol=5e-14) def test_bad_center_value(self, xp): x = xp.linspace(-1, 1, 21) message = "center must be 'mean', 'median' or 'trimmed'." with pytest.raises(ValueError, match=message): stats.fligner(x, x, center='trim') def test_bad_num_args(self, xp): # Too few args raises ValueError. message = "Must provide at least two samples." with pytest.raises(ValueError, match=message): stats.fligner(xp.asarray([1, 2])) @pytest.mark.skip_xp_backends('jax.numpy', reason='lazy -> no _axis_nan_policy') def test_empty_arg(self, xp): x = xp.arange(5.) with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit): res = stats.fligner(x, x**2, xp.asarray([])) xp_assert_equal(res.statistic, xp.asarray(xp.nan)) xp_assert_equal(res.pvalue, xp.asarray(xp.nan)) def mood_cases_with_ties(): # Generate random `x` and `y` arrays with ties both between and within the # samples. Expected results are (statistic, pvalue) from SAS. expected_results = [(-1.76658511464992, .0386488678399305), (-.694031428192304, .2438312498647250), (-1.15093525352151, .1248794365836150)] seeds = [23453254, 1298352315, 987234597] for si, seed in enumerate(seeds): rng = np.random.default_rng(seed) xy = rng.random(100) # Generate random indices to make ties tie_ind = rng.integers(low=0, high=99, size=5) # Generate a random number of ties for each index. num_ties_per_ind = rng.integers(low=1, high=5, size=5) # At each `tie_ind`, mark the next `n` indices equal to that value. for i, n in zip(tie_ind, num_ties_per_ind): for j in range(i + 1, i + n): xy[j] = xy[i] # scramble order of xy before splitting into `x, y` rng.shuffle(xy) x, y = np.split(xy, 2) yield x, y, 'less', *expected_results[si] @make_xp_test_case(stats.mood)
TestFligner
python
coleifer__peewee
tests/regressions.py
{ "start": 37350, "end": 38158 }
class ____(ModelTestCase): requires = [JM] def test_list_value_conversion(self): jm = JM.create(key='k1', data=['i0', 'i1']) jm.key = 'k1-x' jm.save() jm_db = JM.get(JM.key == 'k1-x') self.assertEqual(jm_db.data, ['i0', 'i1']) JM.update(data=['i1', 'i2']).execute() jm_db = JM.get(JM.key == 'k1-x') self.assertEqual(jm_db.data, ['i1', 'i2']) jm2 = JM.create(key='k2', data=['i3', 'i4']) jm_db.data = ['i1', 'i2', 'i3'] jm2.data = ['i4', 'i5'] JM.bulk_update([jm_db, jm2], fields=[JM.key, JM.data]) jm = JM.get(JM.key == 'k1-x') self.assertEqual(jm.data, ['i1', 'i2', 'i3']) jm2 = JM.get(JM.key == 'k2') self.assertEqual(jm2.data, ['i4', 'i5'])
TestListValueConversion
python
kamyu104__LeetCode-Solutions
Python/a-number-after-a-double-reversal.py
{ "start": 29, "end": 196 }
class ____(object): def isSameAfterReversals(self, num): """ :type num: int :rtype: bool """ return num == 0 or num%10
Solution
python
walkccc__LeetCode
solutions/1897. Redistribute Characters to Make All Strings Equal/1897.py
{ "start": 0, "end": 170 }
class ____: def makeEqual(self, words: list[str]) -> bool: return all(c % len(words) == 0 for c in collections.Counter(''.join(words)).values())
Solution
python
spyder-ide__spyder
external-deps/python-lsp-server/pylsp/lsp.py
{ "start": 1034, "end": 1347 }
class ____: File = 1 Module = 2 Namespace = 3 Package = 4 Class = 5 Method = 6 Property = 7 Field = 8 Constructor = 9 Enum = 10 Interface = 11 Function = 12 Variable = 13 Constant = 14 String = 15 Number = 16 Boolean = 17 Array = 18
SymbolKind
python
django__django
tests/generic_views/views.py
{ "start": 5407, "end": 5475 }
class ____(BookConfig, generic.ArchiveIndexView): pass
BookArchive
python
google__pytype
pytype/tests/test_list1.py
{ "start": 69, "end": 2499 }
class ____(test_base.BaseTest): """Tests for builtins.list.""" def test_add(self): ty = self.Infer(""" a = [] a = a + [42] b = [] b = b + [42] b = b + ["foo"] """) self.assertTypesMatchPytd( ty, """ from typing import List, Union a = ... # type: List[int] b = ... # type: List[Union[int, str]] """, ) def test_inplace_add(self): ty = self.Infer(""" a = [] a += [42] b = [] b += [42] b += ["foo"] """) self.assertTypesMatchPytd( ty, """ from typing import List, Union a = ... # type: List[int] b = ... # type: List[Union[int, str]] """, ) def test_inplace_mutates(self): ty = self.Infer(""" a = [] b = a a += [42] """) self.assertTypesMatchPytd( ty, """ from typing import List, Union a = ... # type: List[int] b = ... # type: List[int] """, ) def test_extend_with_empty(self): ty = self.Infer(""" from typing import List v = [] # type: List[str] for x in []: v.extend(x) """) self.assertTypesMatchPytd( ty, """ from typing import Any, List v = ... # type: List[str] x = ... # type: Any """, ) def test_getitem_slot(self): ty, errors = self.InferWithErrors(""" a = [1, '2', 3, 4] b = a[1] c = 1 if __random__ else 2 d = a[c] e = a["s"] # unsupported-operands[e] f = a[-1] g = a[slice(1,2)] # should be List[str] """) self.assertTypesMatchPytd( ty, """ from typing import Any, List, Union a = ... # type: List[Union[int, str]] b = ... # type: str c = ... # type: int d = ... # type: Union[int, str] e = ... # type: Any f = ... # type: int g = ... # type: List[Union[int, str]] """, ) self.assertErrorRegexes(errors, {"e": r"__getitem__ on list"}) def test_index_out_of_range(self): ty = self.Infer(""" a = [0] if __random__ else [] b = 0 if b < len(a): c = a[b] """) self.assertTypesMatchPytd( ty, """ from typing import List a = ... # type: List[int] b = ... # type: int c = ... # type: int """, ) if __name__ == "__main__": test_base.main()
ListTest
python
numba__numba
numba/tests/test_literal_dispatch.py
{ "start": 9891, "end": 11732 }
class ____(TestCase): def make_dummy_type(self): class Dummy(object): def lit(self, a): return a class DummyType(types.Type): def __init__(self): super(DummyType, self).__init__(name="dummy") @register_model(DummyType) class DummyTypeModel(models.StructModel): def __init__(self, dmm, fe_type): members = [] super(DummyTypeModel, self).__init__(dmm, fe_type, members) @intrinsic def init_dummy(typingctx): def codegen(context, builder, signature, args): dummy = cgutils.create_struct_proxy( signature.return_type)(context, builder) return dummy._getvalue() sig = signature(DummyType()) return sig, codegen @overload(Dummy) def dummy_overload(): def ctor(): return init_dummy() return ctor return (DummyType, Dummy) def test_overload_method(self): # from issue #5011 DummyType, Dummy = self.make_dummy_type() @overload_method(DummyType, 'lit') def lit_overload(self, a): def impl(self, a): return literally(a) # <-- using literally here return impl @njit def test_impl(a): d = Dummy() return d.lit(a) # Successful case self.assertEqual(test_impl(5), 5) # Failing case @njit def inside(a): return test_impl(a + 1) with self.assertRaises(errors.TypingError) as raises: inside(4) self.assertIn("Cannot request literal type.", str(raises.exception)) if __name__ == '__main__': unittest.main()
TestLiteralDispatchWithCustomType
python
pytorch__pytorch
torch/utils/data/datapipes/iter/combining.py
{ "start": 26488, "end": 28085 }
class ____(IterDataPipe[tuple[_T_co]]): r""" Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). The output is stopped as soon as the shortest input DataPipe is exhausted. Args: *datapipes: Iterable DataPipes being aggregated Example: >>> # xdoctest: +REQUIRES(module:torchdata) >>> from torchdata.datapipes.iter import IterableWrapper >>> dp1, dp2, dp3 = ( ... IterableWrapper(range(5)), ... IterableWrapper(range(10, 15)), ... IterableWrapper(range(20, 25)), ... ) >>> list(dp1.zip(dp2, dp3)) [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)] """ datapipes: tuple[IterDataPipe] def __init__(self, *datapipes: IterDataPipe) -> None: if not all(isinstance(dp, IterDataPipe) for dp in datapipes): raise TypeError( "All inputs are required to be `IterDataPipe` for `ZipIterDataPipe`." ) super().__init__() self.datapipes = datapipes # type: ignore[assignment] def __iter__(self) -> Iterator[tuple[_T_co]]: iterators = [iter(datapipe) for datapipe in self.datapipes] yield from zip(*iterators, strict=False) def __len__(self) -> int: if all(isinstance(dp, Sized) for dp in self.datapipes): # pyrefly: ignore [bad-argument-type] return min(len(dp) for dp in self.datapipes) else: raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
ZipperIterDataPipe
python
matplotlib__matplotlib
lib/matplotlib/colorizer.py
{ "start": 25806, "end": 34071 }
class ____(_ScalarMappable, artist.Artist): """ Base class for artists that make map data to color using a `.colorizer.Colorizer`. The `.colorizer.Colorizer` applies data normalization before returning RGBA colors from a `~matplotlib.colors.Colormap`. """ def __init__(self, colorizer, **kwargs): """ Parameters ---------- colorizer : `.colorizer.Colorizer` """ _api.check_isinstance(Colorizer, colorizer=colorizer) super().__init__(colorizer=colorizer, **kwargs) @property def colorizer(self): return self._colorizer @colorizer.setter def colorizer(self, cl): _api.check_isinstance(Colorizer, colorizer=cl) self._colorizer.callbacks.disconnect(self._id_colorizer) self._colorizer = cl self._id_colorizer = cl.callbacks.connect('changed', self.changed) def _set_colorizer_check_keywords(self, colorizer, **kwargs): """ Raises a ValueError if any kwarg is not None while colorizer is not None. """ self._check_exclusionary_keywords(colorizer, **kwargs) self.colorizer = colorizer def _auto_norm_from_scale(scale_cls): """ Automatically generate a norm class from *scale_cls*. This differs from `.colors.make_norm_from_scale` in the following points: - This function is not a class decorator, but directly returns a norm class (as if decorating `.Normalize`). - The scale is automatically constructed with ``nonpositive="mask"``, if it supports such a parameter, to work around the difference in defaults between standard scales (which use "clip") and norms (which use "mask"). Note that ``make_norm_from_scale`` caches the generated norm classes (not the instances) and reuses them for later calls. For example, ``type(_auto_norm_from_scale("log")) == LogNorm``. """ # Actually try to construct an instance, to verify whether # ``nonpositive="mask"`` is supported. try: norm = colors.make_norm_from_scale( functools.partial(scale_cls, nonpositive="mask"))( colors.Normalize)() except TypeError: norm = colors.make_norm_from_scale(scale_cls)( colors.Normalize)() return type(norm) def _ensure_norm(norm, n_components=1): if n_components == 1: _api.check_isinstance((colors.Norm, str, None), norm=norm) if norm is None: norm = colors.Normalize() elif isinstance(norm, str): scale_cls = _api.check_getitem(scale._scale_mapping, norm=norm) return _auto_norm_from_scale(scale_cls)() return norm elif n_components > 1: if not np.iterable(norm): _api.check_isinstance((colors.MultiNorm, None, tuple), norm=norm) if norm is None: norm = colors.MultiNorm(['linear']*n_components) else: # iterable, i.e. multiple strings or Normalize objects norm = colors.MultiNorm(norm) if isinstance(norm, colors.MultiNorm) and norm.n_components == n_components: return norm raise ValueError( f"Invalid norm for multivariate colormap with {n_components} inputs") else: # n_components == 0 raise ValueError( "Invalid cmap. A colorizer object must have a cmap with `n_variates` >= 1") def _ensure_cmap(cmap, accept_multivariate=False): """ Ensure that we have a `.Colormap` object. For internal use to preserve type stability of errors. Parameters ---------- cmap : None, str, Colormap - if a `~matplotlib.colors.Colormap`, `~matplotlib.colors.MultivarColormap` or `~matplotlib.colors.BivarColormap`, return it - if a string, look it up in three corresponding databases when not found: raise an error based on the expected shape - if None, look up the default color map in mpl.colormaps accept_multivariate : bool, default False - if False, accept only Colormap, string in mpl.colormaps or None Returns ------- Colormap """ if accept_multivariate: types = (colors.Colormap, colors.BivarColormap, colors.MultivarColormap) mappings = (mpl.colormaps, mpl.multivar_colormaps, mpl.bivar_colormaps) else: types = (colors.Colormap, ) mappings = (mpl.colormaps, ) if isinstance(cmap, types): return cmap cmap_name = mpl._val_or_rc(cmap, "image.cmap") for mapping in mappings: if cmap_name in mapping: return mapping[cmap_name] # this error message is a variant of _api.check_in_list but gives # additional hints as to how to access multivariate colormaps raise ValueError(f"{cmap!r} is not a valid value for cmap" "; supported values for scalar colormaps are " f"{', '.join(map(repr, sorted(mpl.colormaps)))}\n" "See `matplotlib.bivar_colormaps()` and" " `matplotlib.multivar_colormaps()` for" " bivariate and multivariate colormaps") def _ensure_multivariate_data(data, n_components): """ Ensure that the data has dtype with n_components. Input data of shape (n_components, n, m) is converted to an array of shape (n, m) with data type np.dtype(f'{data.dtype}, ' * n_components) Complex data is returned as a view with dtype np.dtype('float64, float64') or np.dtype('float32, float32') If n_components is 1 and data is not of type np.ndarray (i.e. PIL.Image), the data is returned unchanged. If data is None, the function returns None Parameters ---------- n_components : int Number of variates in the data. data : np.ndarray, PIL.Image or None Returns ------- np.ndarray, PIL.Image or None """ if isinstance(data, np.ndarray): if len(data.dtype.descr) == n_components: # pass scalar data # and already formatted data return data elif data.dtype in [np.complex64, np.complex128]: if n_components != 2: raise ValueError("Invalid data entry for multivariate data. " "Complex numbers are incompatible with " f"{n_components} variates.") # pass complex data if data.dtype == np.complex128: dt = np.dtype('float64, float64') else: dt = np.dtype('float32, float32') reconstructed = np.ma.array(np.ma.getdata(data).view(dt)) if np.ma.is_masked(data): for descriptor in dt.descr: reconstructed[descriptor[0]][data.mask] = np.ma.masked return reconstructed if n_components > 1 and len(data) == n_components: # convert data from shape (n_components, n, m) # to (n, m) with a new dtype data = [np.ma.array(part, copy=False) for part in data] dt = np.dtype(', '.join([f'{part.dtype}' for part in data])) fields = [descriptor[0] for descriptor in dt.descr] reconstructed = np.ma.empty(data[0].shape, dtype=dt) for i, f in enumerate(fields): if data[i].shape != reconstructed.shape: raise ValueError("For multivariate data all variates must have same " f"shape, not {data[0].shape} and {data[i].shape}") reconstructed[f] = data[i] if np.ma.is_masked(data[i]): reconstructed[f][data[i].mask] = np.ma.masked return reconstructed if n_components == 1: # PIL.Image gets passed here return data elif n_components == 2: raise ValueError("Invalid data entry for multivariate data. The data" " must contain complex numbers, or have a first dimension 2," " or be of a dtype with 2 fields") else: raise ValueError("Invalid data entry for multivariate data. The shape" f" of the data must have a first dimension {n_components}" f" or be of a dtype with {n_components} fields")
ColorizingArtist
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_audio.py
{ "start": 18055, "end": 26795 }
class ____(PreTrainedModel): config: Data2VecAudioConfig base_model_prefix = "data2vec_audio" main_input_name = "input_values" input_modalities = "audio" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" if isinstance(module, Data2VecAudioFeatureProjection): k = math.sqrt(1 / module.projection.in_features) init.uniform_(module.projection.weight, a=-k, b=k) init.uniform_(module.projection.bias, a=-k, b=k) elif isinstance(module, Data2VecAudioPositionalConvLayer): init.constant_(module.conv.bias, 0) elif isinstance(module, nn.Linear): init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)): if module.bias is not None: init.zeros_(module.bias) if module.weight is not None: init.ones_(module.weight) elif isinstance(module, nn.Conv1d): init.kaiming_normal_(module.weight) if module.bias is not None: k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0])) init.uniform_(module.bias, a=-k, b=k) def _get_feat_extract_output_lengths( self, input_lengths: Union[torch.LongTensor, int], add_adapter: Optional[bool] = None ): """ Computes the output length of the convolutional layers """ add_adapter = self.config.add_adapter if add_adapter is None else add_adapter def _conv_out_length(input_length, kernel_size, stride): # 1D convolutional layer output length formula taken # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1 for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride): input_lengths = _conv_out_length(input_lengths, kernel_size, stride) if add_adapter: for _ in range(self.config.num_adapter_layers): input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride) return input_lengths def _get_feature_vector_attention_mask( self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None ): # Effectively attention_mask.sum(-1), but not inplace to be able to run # on inference mode. non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1] output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter) output_lengths = output_lengths.to(torch.long) batch_size = attention_mask.shape[0] attention_mask = torch.zeros( (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device ) # these two operations makes sure that all values before the output lengths idxs are attended to attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1 attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool() return attention_mask def _compute_mask_indices( shape: tuple[int, int], mask_prob: float, mask_length: int, attention_mask: Optional[torch.LongTensor] = None, min_masks: int = 0, ) -> np.ndarray: """ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: shape: The shape for which to compute masks. This should be of a tuple of size 2 where the first element is the batch size and the second element is the length of the axis to span. mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of independently generated mask spans of length `mask_length` is computed by `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the actual percentage will be smaller. mask_length: size of the mask min_masks: minimum number of masked spans attention_mask: A (right-padded) attention mask which independently shortens the feature axis of each batch dimension. """ batch_size, sequence_length = shape if mask_length < 1: raise ValueError("`mask_length` has to be bigger than 0.") if mask_length > sequence_length: raise ValueError( f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}" f" and `sequence_length`: {sequence_length}`" ) # epsilon is used for probabilistic rounding epsilon = np.random.rand(1).item() def compute_num_masked_span(input_length): """Given input length, compute how many spans should be masked""" num_masked_span = int(mask_prob * input_length / mask_length + epsilon) num_masked_span = max(num_masked_span, min_masks) # make sure num masked span <= sequence_length if num_masked_span * mask_length > sequence_length: num_masked_span = sequence_length // mask_length # make sure num_masked span is also <= input_length - (mask_length - 1) if input_length - (mask_length - 1) < num_masked_span: num_masked_span = max(input_length - (mask_length - 1), 0) return num_masked_span # compute number of masked spans in batch input_lengths = ( attention_mask.detach().sum(-1).tolist() if attention_mask is not None else [sequence_length for _ in range(batch_size)] ) # SpecAugment mask to fill spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool) spec_aug_mask_idxs = [] max_num_masked_span = compute_num_masked_span(sequence_length) if max_num_masked_span == 0: return spec_aug_mask for input_length in input_lengths: # compute num of masked spans for this input num_masked_span = compute_num_masked_span(input_length) # get random indices to mask spec_aug_mask_idx = np.random.choice( np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False ) # pick first sampled index that will serve as a dummy index to pad vector # to ensure same dimension for all batches due to probabilistic rounding # Picking first sample just pads those vectors twice. if len(spec_aug_mask_idx) == 0: # this case can only happen if `input_length` is strictly smaller then # `sequence_length` in which case the last token has to be a padding # token which we can use as a dummy mask id dummy_mask_idx = sequence_length - 1 else: dummy_mask_idx = spec_aug_mask_idx[0] spec_aug_mask_idx = np.concatenate( [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx] ) spec_aug_mask_idxs.append(spec_aug_mask_idx) spec_aug_mask_idxs = np.array(spec_aug_mask_idxs) # expand masked indices to masked spans spec_aug_mask_idxs = np.broadcast_to( spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length) ) spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length) # add offset to the starting indexes so that indexes now create a span offsets = np.arange(mask_length)[None, None, :] offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape( batch_size, max_num_masked_span * mask_length ) spec_aug_mask_idxs = spec_aug_mask_idxs + offsets # ensure that we cannot have indices larger than sequence_length if spec_aug_mask_idxs.max() > sequence_length - 1: spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1 # scatter indices to mask np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1) return spec_aug_mask Data2VecAudioBaseModelOutput = Wav2Vec2BaseModelOutput @auto_docstring
Data2VecAudioPreTrainedModel
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-path-with-teleportations.py
{ "start": 1360, "end": 2414 }
class ____(object): def minCost(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: int """ dp = [[float("inf")]*len(grid[0]) for _ in xrange(len(grid))] dp[-1][-1] = 0 mx = max(max(row) for row in grid) prefix = [float("inf")]*(mx+1) for i in xrange(k+1): for r in reversed(xrange(len(grid))): for c in reversed(xrange(len(grid[0]))): if r+1 < len(grid): dp[r][c] = min(dp[r][c], dp[r+1][c]+grid[r+1][c]) if c+1 < len(grid[0]): dp[r][c] = min(dp[r][c], dp[r][c+1]+grid[r][c+1]) dp[r][c] = min(dp[r][c], prefix[grid[r][c]]) for r in xrange(len(grid)): for c in xrange(len(grid[0])): prefix[grid[r][c]] = min(prefix[grid[r][c]], dp[r][c]) for i in xrange(len(prefix)-1): prefix[i+1] = min(prefix[i+1], prefix[i]) return dp[0][0]
Solution2
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/asset_utils.py
{ "start": 15321, "end": 46651 }
class ____: manifest: Mapping[str, Any] dagster_dbt_translator: Annotated[ "DagsterDbtTranslator", ImportFrom("dagster_dbt.dagster_dbt_translator") ] selection_args: Sequence[str] indirect_selection: Optional[str] dbt_project: Optional[DbtProject] def get_updated_cli_invocation_params_for_context( context: Optional[Union[OpExecutionContext, AssetExecutionContext]], manifest: Mapping[str, Any], dagster_dbt_translator: "DagsterDbtTranslator", ) -> DbtCliInvocationPartialParams: try: assets_def = context.assets_def if context else None except DagsterInvalidPropertyError: # If assets_def is None in an OpExecutionContext, we raise a DagsterInvalidPropertyError, # but we don't want to raise the error here. assets_def = None selection_args: list[str] = [] indirect_selection = os.getenv(DBT_INDIRECT_SELECTION_ENV, None) dbt_project = None if context and assets_def is not None: manifest, dagster_dbt_translator, dbt_project = get_manifest_and_translator_from_dbt_assets( [assets_def] ) # Get project_dir from dbt_project if available project_dir = Path(dbt_project.project_dir) if dbt_project else None target_project = dbt_project selection_args, indirect_selection_override = get_subset_selection_for_context( context=context, manifest=manifest, select=context.op.tags.get(DAGSTER_DBT_SELECT_METADATA_KEY), exclude=context.op.tags.get(DAGSTER_DBT_EXCLUDE_METADATA_KEY), selector=context.op.tags.get(DAGSTER_DBT_SELECTOR_METADATA_KEY), dagster_dbt_translator=dagster_dbt_translator, current_dbt_indirect_selection_env=indirect_selection, ) if ( selection_args[0] == "--select" and project_dir and len(resources := selection_args[1].split(" ")) > _SELECTION_ARGS_THRESHOLD ): temp_project_dir = tempfile.mkdtemp() shutil.copytree(project_dir, temp_project_dir, dirs_exist_ok=True) selectors_path = Path(temp_project_dir) / "selectors.yml" # Delete any existing selectors, we need to create our own if selectors_path.exists(): selectors_path.unlink() selector_name = f"dagster_run_{context.run_id}" temp_selectors = { "selectors": [ { "name": selector_name, "definition": {"union": list(resources)}, } ] } selectors_path.write_text(yaml.safe_dump(temp_selectors)) logger.info( f"DBT selection of {len(resources)} resources exceeds threshold of {_SELECTION_ARGS_THRESHOLD}. " "This may exceed system argument length limits. " f"Executing materialization against temporary copy of DBT project at {temp_project_dir} with ephemeral selector." ) selection_args = ["--selector", selector_name] target_project = replace(dbt_project, project_dir=temp_project_dir) indirect_selection = ( indirect_selection_override if indirect_selection_override else indirect_selection ) else: target_project = dbt_project return DbtCliInvocationPartialParams( manifest=manifest, dagster_dbt_translator=dagster_dbt_translator, selection_args=selection_args, indirect_selection=indirect_selection, dbt_project=target_project, ) ################### # DEFAULT FUNCTIONS ################### def default_asset_key_fn(dbt_resource_props: Mapping[str, Any]) -> AssetKey: """Get the asset key for a dbt node. By default, if the dbt node has a Dagster asset key configured in its metadata, then that is parsed and used. Otherwise: dbt sources: a dbt source's key is the union of its source name and its table name dbt models: a dbt model's key is the union of its model name and any schema configured on the model itself. """ dbt_meta = dbt_resource_props.get("config", {}).get("meta", {}) or dbt_resource_props.get( "meta", {} ) dagster_metadata = dbt_meta.get("dagster", {}) asset_key_config = dagster_metadata.get("asset_key", []) if asset_key_config: return AssetKey(asset_key_config) if dbt_resource_props["resource_type"] == "source": components = [dbt_resource_props["source_name"], dbt_resource_props["name"]] elif dbt_resource_props.get("version"): components = [dbt_resource_props["alias"]] else: configured_schema = dbt_resource_props["config"].get("schema") if configured_schema is not None: components = [configured_schema, dbt_resource_props["name"]] else: components = [dbt_resource_props["name"]] return AssetKey(components) def default_metadata_from_dbt_resource_props( dbt_resource_props: Mapping[str, Any], ) -> Mapping[str, Any]: column_schema = None columns = dbt_resource_props.get("columns", {}) if len(columns) > 0: column_schema = TableSchema( columns=[ TableColumn( name=column_name, type=column_info.get("data_type") or "?", description=column_info.get("description"), tags={tag_name: "" for tag_name in column_info.get("tags", [])}, ) for column_name, column_info in columns.items() ] ) relation_parts = [ relation_part for relation_part in [ dbt_resource_props.get("database"), dbt_resource_props.get("schema"), dbt_resource_props.get("alias"), ] if relation_part ] relation_name = ".".join(relation_parts) if relation_parts else None materialization_type = dbt_resource_props.get("config", {}).get("materialized") return { **DbtMetadataSet(materialization_type=materialization_type), **TableMetadataSet( column_schema=column_schema, table_name=relation_name, ), } def default_group_from_dbt_resource_props(dbt_resource_props: Mapping[str, Any]) -> Optional[str]: """Get the group name for a dbt node. If a Dagster group is configured in the metadata for the node, use that. Otherwise, if a dbt group is configured for the node, use that. """ dagster_metadata = dbt_resource_props.get("meta", {}).get("dagster", {}) dagster_group = dagster_metadata.get("group") if dagster_group: return dagster_group dbt_group = dbt_resource_props.get("config", {}).get("group") if dbt_group: return dbt_group return None def group_from_dbt_resource_props_fallback_to_directory( dbt_resource_props: Mapping[str, Any], ) -> Optional[str]: """Get the group name for a dbt node. Has the same behavior as the default_group_from_dbt_resource_props, except for that, if no group can be determined from config or metadata, falls back to using the subdirectory of the models directory that the source file is in. Args: dbt_resource_props (Mapping[str, Any]): A dictionary representing the dbt resource. """ group_name = default_group_from_dbt_resource_props(dbt_resource_props) if group_name is not None: return group_name fqn = dbt_resource_props.get("fqn", []) # the first component is the package name, and the last component is the model name if len(fqn) < 3: return None return fqn[1] def default_owners_from_dbt_resource_props( dbt_resource_props: Mapping[str, Any], ) -> Optional[Sequence[str]]: dagster_metadata = dbt_resource_props.get("meta", {}).get("dagster", {}) owners_config = dagster_metadata.get("owners") if owners_config: return owners_config owner: Optional[Union[str, Sequence[str]]] = ( (dbt_resource_props.get("group") or {}).get("owner", {}).get("email") ) if not owner: return None return [owner] if isinstance(owner, str) else owner def default_auto_materialize_policy_fn( dbt_resource_props: Mapping[str, Any], ) -> Optional[AutoMaterializePolicy]: dagster_metadata = dbt_resource_props.get("meta", {}).get("dagster", {}) auto_materialize_policy_config = dagster_metadata.get("auto_materialize_policy", {}) if auto_materialize_policy_config.get("type") == "eager": return AutoMaterializePolicy.eager() elif auto_materialize_policy_config.get("type") == "lazy": return AutoMaterializePolicy.lazy() return None def default_description_fn(dbt_resource_props: Mapping[str, Any], display_raw_sql: bool = True): code_block = textwrap.indent( dbt_resource_props.get("raw_sql") or dbt_resource_props.get("raw_code", ""), " " ) description_sections = [ dbt_resource_props.get("description") or f"dbt {dbt_resource_props['resource_type']} {dbt_resource_props['name']}", ] if display_raw_sql: description_sections.append(f"#### Raw SQL:\n```sql\n{code_block}\n```") return "\n\n".join(filter(None, description_sections)) def default_asset_check_fn( manifest: Mapping[str, Any], dagster_dbt_translator: "DagsterDbtTranslator", asset_key: AssetKey, test_unique_id: str, project: Optional[DbtProject], ) -> Optional[AssetCheckSpec]: if not dagster_dbt_translator.settings.enable_asset_checks: return None test_resource_props = get_node(manifest, test_unique_id) parent_unique_ids: set[str] = set(manifest["parent_map"].get(test_unique_id, [])) asset_check_key = get_asset_check_key_for_test( manifest=manifest, dagster_dbt_translator=dagster_dbt_translator, test_unique_id=test_unique_id, project=project, ) if not (asset_check_key and asset_check_key.asset_key == asset_key): return None additional_deps = { dagster_dbt_translator.get_asset_spec(manifest, parent_id, project).key for parent_id in parent_unique_ids } additional_deps.discard(asset_key) severity = test_resource_props.get("config", {}).get("severity", "error") blocking = severity.lower() == "error" return AssetCheckSpec( name=test_resource_props["name"], asset=asset_key, description=test_resource_props.get("meta", {}).get("description"), additional_deps=additional_deps, metadata={DAGSTER_DBT_UNIQUE_ID_METADATA_KEY: test_unique_id}, blocking=blocking, ) def default_code_version_fn(dbt_resource_props: Mapping[str, Any]) -> Optional[str]: code: Optional[str] = dbt_resource_props.get("raw_sql") or dbt_resource_props.get("raw_code") if code: return hashlib.sha1(code.encode("utf-8")).hexdigest() return dbt_resource_props.get("checksum", {}).get("checksum") ################### # DEPENDENCIES ################### def is_non_asset_node(dbt_resource_props: Mapping[str, Any]): # some nodes exist inside the dbt graph but are not assets resource_type = dbt_resource_props["resource_type"] return any( [ resource_type == "metric", resource_type == "semantic_model", resource_type == "saved_query", resource_type == "model" and dbt_resource_props.get("config", {}).get("materialized") == "ephemeral", ] ) def is_valid_upstream_node(dbt_resource_props: Mapping[str, Any]) -> bool: # sources are valid parents, but not assets return dbt_resource_props["resource_type"] in ASSET_RESOURCE_TYPES + ["source"] def get_upstream_unique_ids( manifest: Mapping[str, Any], dbt_resource_props: Mapping[str, Any], ) -> AbstractSet[str]: upstreams = set() for parent_unique_id in dbt_resource_props.get("depends_on", {}).get("nodes", []): parent_node_info = get_node(manifest, parent_unique_id) # for metrics or ephemeral dbt models, BFS to find valid parents if is_non_asset_node(parent_node_info): visited = set() replaced_parent_ids = set() # make a copy to avoid mutating the actual dictionary queue = list(parent_node_info.get("depends_on", {}).get("nodes", [])) while queue: candidate_parent_id = queue.pop() if candidate_parent_id in visited: continue visited.add(candidate_parent_id) candidate_parent_info = get_node(manifest, candidate_parent_id) if is_non_asset_node(candidate_parent_info): queue.extend(candidate_parent_info.get("depends_on", {}).get("nodes", [])) elif is_valid_upstream_node(candidate_parent_info): replaced_parent_ids.add(candidate_parent_id) upstreams |= replaced_parent_ids # ignore nodes which are not assets / sources elif is_valid_upstream_node(parent_node_info): upstreams.add(parent_unique_id) return upstreams def _build_child_map(manifest: Mapping[str, Any]) -> Mapping[str, AbstractSet[str]]: """Manifests produced by early versions of dbt Fusion do not contain a child map, so we need to build it manually.""" if manifest.get("child_map"): return manifest["child_map"] child_map = defaultdict(set) for unique_id, node in manifest["nodes"].items(): for upstream_unique_id in get_upstream_unique_ids(manifest, node): child_map[upstream_unique_id].add(unique_id) return child_map def build_dbt_specs( *, translator: "DagsterDbtTranslator", manifest: Mapping[str, Any], select: str, exclude: str, selector: str, io_manager_key: Optional[str], project: Optional[DbtProject], ) -> tuple[Sequence[AssetSpec], Sequence[AssetCheckSpec]]: selected_unique_ids = select_unique_ids( select=select, exclude=exclude, selector=selector, project=project, manifest_json=manifest ) specs: list[AssetSpec] = [] check_specs: dict[str, AssetCheckSpec] = {} key_by_unique_id: dict[str, AssetKey] = {} child_map = _build_child_map(manifest) for unique_id in selected_unique_ids: resource_props = get_node(manifest, unique_id) resource_type = resource_props["resource_type"] # skip non-assets, such as semantic models, metrics, tests, and ephemeral models if is_non_asset_node(resource_props) or resource_type not in ASSET_RESOURCE_TYPES: continue # get the spec for the given node spec = translator.get_asset_spec( manifest, unique_id, project, ) key_by_unique_id[unique_id] = spec.key # add the io manager key and set the dagster type to Nothing if io_manager_key is not None: spec = spec.with_io_manager_key(io_manager_key) spec = spec.merge_attributes(metadata={SYSTEM_METADATA_KEY_DAGSTER_TYPE: Nothing}) specs.append(spec) # add check specs associated with the asset for child_unique_id in child_map.get(unique_id, []): if child_unique_id not in selected_unique_ids or not child_unique_id.startswith("test"): continue check_spec = translator.get_asset_check_spec( asset_spec=spec, manifest=manifest, unique_id=child_unique_id, project=project, ) if check_spec: check_specs[check_spec.get_python_identifier()] = check_spec # update the keys_by_unqiue_id dictionary to include keys created for upstream # assets. note that this step may need to change once the translator is updated # to no longer rely on `get_asset_key` as a standalone method for upstream_id in get_upstream_unique_ids(manifest, resource_props): spec = translator.get_asset_spec(manifest, upstream_id, project) key_by_unique_id[upstream_id] = spec.key if ( upstream_id.startswith("source") and translator.settings.enable_source_tests_as_checks ): for child_unique_id in child_map.get(upstream_id, []): if not child_unique_id.startswith("test"): continue check_spec = translator.get_asset_check_spec( asset_spec=spec, manifest=manifest, unique_id=child_unique_id, project=project, ) if check_spec: check_specs[check_spec.get_python_identifier()] = check_spec _validate_asset_keys(translator, manifest, key_by_unique_id) return specs, list(check_specs.values()) def _validate_asset_keys( translator: "DagsterDbtTranslator", manifest: Mapping[str, Any], key_by_unique_id: Mapping[str, AssetKey], ) -> None: unique_ids_by_key = defaultdict(set) for unique_id, key in key_by_unique_id.items(): unique_ids_by_key[key].add(unique_id) error_messages = [] for key, unique_ids in unique_ids_by_key.items(): if len(unique_ids) == 1: continue if translator.settings.enable_duplicate_source_asset_keys: resource_types = { get_node(manifest, unique_id)["resource_type"] for unique_id in unique_ids } if resource_types == {"source"}: continue formatted_ids = [ f" - `{id}` ({get_node(manifest, id)['original_file_path']})" for id in sorted(unique_ids) ] error_messages.append( "\n".join( [ f"The following dbt resources have the asset key `{key.path}`:", *formatted_ids, ] ) ) if error_messages: raise DagsterInvalidDefinitionError( "\n\n".join([DUPLICATE_ASSET_KEY_ERROR_MESSAGE, *error_messages]) ) def has_self_dependency(dbt_resource_props: Mapping[str, Any]) -> bool: dagster_metadata = dbt_resource_props.get("meta", {}).get("dagster", {}) has_self_dependency = dagster_metadata.get("has_self_dependency", False) return has_self_dependency def get_asset_check_key_for_test( manifest: Mapping[str, Any], dagster_dbt_translator: "DagsterDbtTranslator", test_unique_id: str, project: Optional[DbtProject], ) -> Optional[AssetCheckKey]: if not test_unique_id.startswith("test"): return None test_resource_props = get_node(manifest, test_unique_id) upstream_unique_ids: AbstractSet[str] = set(test_resource_props["depends_on"]["nodes"]) # If the test is generic, it will have an attached node that we can use. attached_node_unique_id = test_resource_props.get("attached_node") # If the test is singular, infer the attached node from the upstream nodes. if len(upstream_unique_ids) == 1: [attached_node_unique_id] = upstream_unique_ids # If the test is singular, but has multiple dependencies, infer the attached node from # from the dbt meta. attached_node_ref = ( ( test_resource_props.get("config", {}).get("meta", {}) or test_resource_props.get("meta", {}) ) .get("dagster", {}) .get("ref", {}) ) # Attempt to find the attached node from the ref. if attached_node_ref: ref_name, ref_package, ref_version = ( attached_node_ref["name"], attached_node_ref.get("package"), attached_node_ref.get("version"), ) project_name = manifest.get("metadata", {})["project_name"] if not ref_package: ref_package = project_name attached_node_unique_id = None for unique_id, dbt_resource_props in manifest["nodes"].items(): if (ref_name, ref_package, ref_version) == ( dbt_resource_props["name"], dbt_resource_props["package_name"], dbt_resource_props.get("version"), ): attached_node_unique_id = unique_id break if not attached_node_unique_id: return None return AssetCheckKey( name=test_resource_props["name"], asset_key=dagster_dbt_translator.get_asset_spec( manifest, attached_node_unique_id, project, ).key, ) def get_checks_on_sources_upstream_of_selected_assets( assets_def: AssetsDefinition, selected_asset_keys: AbstractSet[AssetKey] ) -> AbstractSet[AssetCheckKey]: upstream_source_keys = assets_def.get_upstream_input_keys(frozenset(selected_asset_keys)) return assets_def.get_checks_targeting_keys(frozenset(upstream_source_keys)) def get_subset_selection_for_context( context: Union[OpExecutionContext, AssetExecutionContext], manifest: Mapping[str, Any], select: Optional[str], exclude: Optional[str], selector: Optional[str], dagster_dbt_translator: "DagsterDbtTranslator", current_dbt_indirect_selection_env: Optional[str], ) -> tuple[list[str], Optional[str]]: """Generate a dbt selection string and DBT_INDIRECT_SELECTION setting to execute the selected resources in a subsetted execution context. See https://docs.getdbt.com/reference/node-selection/syntax#how-does-selection-work. Args: context (Union[OpExecutionContext, AssetExecutionContext]): The execution context for the current execution step. manifest (Mapping[str, Any]): The dbt manifest blob. select (Optional[str]): A dbt selection string to select resources to materialize. exclude (Optional[str]): A dbt selection string to exclude resources from materializing. selector (Optional[str]): A dbt selector to select resources to materialize. dagster_dbt_translator (DagsterDbtTranslator): The translator to link dbt nodes to Dagster assets. current_dbt_indirect_selection_env (Optional[str]): The user's value for the DBT_INDIRECT_SELECTION environment variable. Returns: List[str]: dbt CLI arguments to materialize the selected resources in a subsetted execution context. If the current execution context is not performing a subsetted execution, return CLI arguments composed of the inputed selection and exclusion arguments. Optional[str]: A value for the DBT_INDIRECT_SELECTION environment variable. If None, then the environment variable is not set and will either use dbt's default (eager) or the user's setting. """ default_dbt_selection = [] if select: default_dbt_selection += ["--select", select] if exclude: default_dbt_selection += ["--exclude", exclude] if selector: default_dbt_selection += ["--selector", selector] assets_def = context.assets_def is_asset_subset = assets_def.keys_by_output_name != assets_def.node_keys_by_output_name is_checks_subset = ( assets_def.check_specs_by_output_name != assets_def.node_check_specs_by_output_name ) # It's nice to use the default dbt selection arguments when not subsetting for readability. We # also use dbt indirect selection to avoid hitting cli arg length limits. # https://github.com/dagster-io/dagster/issues/16997#issuecomment-1832443279 # A biproduct is that we'll run singular dbt tests (not currently modeled as asset checks) in # cases when we can use indirection selection, an not when we need to turn it off. if not (is_asset_subset or is_checks_subset): logger.info( "A dbt subsetted execution is not being performed. Using the default dbt selection" f" arguments `{default_dbt_selection}`." ) # default eager indirect selection. This means we'll also run any singular tests (which # aren't modeled as asset checks currently). return default_dbt_selection, None # Explicitly select a dbt resource by its path. Selecting a resource by path is more terse # than selecting it by its fully qualified name. # https://docs.getdbt.com/reference/node-selection/methods#the-path-method selected_asset_resources = get_dbt_resource_names_for_asset_keys( dagster_dbt_translator, manifest, assets_def, context.selected_asset_keys ) # We explicitly use node_check_specs_by_output_name because it contains every single check spec, not just those selected in the currently # executing subset. checks_targeting_selected_sources = get_checks_on_sources_upstream_of_selected_assets( assets_def=assets_def, selected_asset_keys=context.selected_asset_keys ) selected_check_keys = {*context.selected_asset_check_keys, *checks_targeting_selected_sources} # if all asset checks for the subsetted assets are selected, then we can just select the # assets and use indirect selection for the tests. We verify that # 1. all the selected checks are for selected assets # 2. no checks for selected assets are excluded # This also means we'll run any singular tests. selected_checks_on_non_selected_assets = { check_key for check_key in selected_check_keys if check_key.asset_key not in context.selected_asset_keys } all_check_keys = { check_spec.key for check_spec in assets_def.node_check_specs_by_output_name.values() } excluded_checks = all_check_keys.difference(selected_check_keys) excluded_checks_on_selected_assets = [ check_key for check_key in excluded_checks if check_key.asset_key in context.selected_asset_keys ] # note that this will always be false if checks are disabled (which means the assets_def has no # check specs) if excluded_checks_on_selected_assets: # select all assets and tests explicitly, and turn off indirect selection. This risks # hitting the CLI argument length limit, but in the common scenarios that can be launched from the UI # (all checks disabled, only one check and no assets) it's not a concern. # Since we're setting DBT_INDIRECT_SELECTION=empty, we won't run any singular tests. selected_dbt_resources = [ *selected_asset_resources, *get_dbt_test_names_for_check_keys( dagster_dbt_translator, manifest, assets_def, context.selected_asset_check_keys ), ] indirect_selection_override = DBT_EMPTY_INDIRECT_SELECTION logger.info( "Overriding default `DBT_INDIRECT_SELECTION` " f"{current_dbt_indirect_selection_env or 'eager'} with " f"`{indirect_selection_override}` due to additional checks " f"{', '.join([c.to_user_string() for c in selected_checks_on_non_selected_assets])} " f"and excluded checks {', '.join([c.to_user_string() for c in excluded_checks_on_selected_assets])}." ) elif selected_checks_on_non_selected_assets: # explicitly select the tests that won't be run via indirect selection selected_dbt_resources = [ *selected_asset_resources, *get_dbt_test_names_for_check_keys( dagster_dbt_translator, manifest, assets_def, selected_checks_on_non_selected_assets, ), ] indirect_selection_override = None else: selected_dbt_resources = selected_asset_resources indirect_selection_override = None logger.info( "A dbt subsetted execution is being performed. Overriding default dbt selection" f" arguments `{default_dbt_selection}` with arguments: `{selected_dbt_resources}`." ) # Take the union of all the selected resources. # https://docs.getdbt.com/reference/node-selection/set-operators#unions union_selected_dbt_resources = ["--select"] + [" ".join(selected_dbt_resources)] return union_selected_dbt_resources, indirect_selection_override def get_dbt_resource_names_for_asset_keys( translator: "DagsterDbtTranslator", manifest: Mapping[str, Any], assets_def: AssetsDefinition, asset_keys: Iterable[AssetKey], ) -> Sequence[str]: dbt_resource_props_gen = ( get_node( manifest, assets_def.get_asset_spec(key).metadata[DAGSTER_DBT_UNIQUE_ID_METADATA_KEY], ) for key in asset_keys ) # Explicitly select a dbt resource by its file name. # https://docs.getdbt.com/reference/node-selection/methods#the-file-method if translator.settings.enable_dbt_selection_by_name: return [ Path(dbt_resource_props["original_file_path"]).stem for dbt_resource_props in dbt_resource_props_gen ] # Explictly select a dbt resource by its fully qualified name (FQN). # https://docs.getdbt.com/reference/node-selection/methods#the-file-or-fqn-method return [".".join(dbt_resource_props["fqn"]) for dbt_resource_props in dbt_resource_props_gen] def get_dbt_test_names_for_check_keys( translator: "DagsterDbtTranslator", manifest: Mapping[str, Any], assets_def: AssetsDefinition, check_keys: Iterable[AssetCheckKey], ) -> Sequence[str]: dbt_resource_props_gen = ( get_node( manifest, (assets_def.get_spec_for_check_key(key).metadata or {})[ DAGSTER_DBT_UNIQUE_ID_METADATA_KEY ], ) for key in check_keys ) # Explicitly select a dbt test by its test name. # https://docs.getdbt.com/reference/node-selection/test-selection-examples#more-complex-selection. if translator.settings.enable_dbt_selection_by_name: return [asset_check_key.name for asset_check_key in check_keys] # Explictly select a dbt test by its fully qualified name (FQN). # https://docs.getdbt.com/reference/node-selection/methods#the-file-or-fqn-method return [".".join(dbt_resource_props["fqn"]) for dbt_resource_props in dbt_resource_props_gen] def get_node(manifest: Mapping[str, Any], unique_id: str) -> Mapping[str, Any]: """Find a node by unique_id in manifest_json.""" if unique_id in manifest["nodes"]: return manifest["nodes"][unique_id] if unique_id in manifest["sources"]: return manifest["sources"][unique_id] if unique_id in manifest["exposures"]: return manifest["exposures"][unique_id] if unique_id in manifest["metrics"]: return manifest["metrics"][unique_id] if unique_id in manifest.get("semantic_models", {}): return manifest["semantic_models"][unique_id] if unique_id in manifest.get("saved_queries", {}): return manifest["saved_queries"][unique_id] if unique_id in manifest.get("unit_tests", {}): return manifest["unit_tests"][unique_id] check.failed(f"Could not find {unique_id} in dbt manifest")
DbtCliInvocationPartialParams
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 13924, "end": 15593 }
class ____(TestCase): def setUp(self): # Sequence of title/text/attributes is: # # z abc [1, 2, 3] # zz bcd [1, 2, 3] # zzz cde [1, 2, 3] # ... for idx in range(3): label = 'w' * (idx + 1) AttributeModel.objects.create(label=label) for idx in range(10): title = 'z' * (idx + 1) text = ( chr(idx + ord('a')) + chr(idx + ord('b')) + chr(idx + ord('c')) ) SearchFilterModelM2M(title=title, text=text).save() SearchFilterModelM2M.objects.get(title='zz').attributes.add(1, 2, 3) def test_m2m_search(self): class SearchListView(generics.ListAPIView): queryset = SearchFilterModelM2M.objects.all() serializer_class = SearchFilterM2MSerializer filter_backends = (filters.SearchFilter,) search_fields = ('=title', 'text', 'attributes__label') view = SearchListView.as_view() request = factory.get('/', {'search': 'zz'}) response = view(request) assert len(response.data) == 1 def test_must_call_distinct(self): filter_ = filters.SearchFilter() prefixes = [''] + list(filter_.lookup_prefixes) for prefix in prefixes: assert not filter_.must_call_distinct( SearchFilterModelM2M._meta, ["%stitle" % prefix] ) assert filter_.must_call_distinct( SearchFilterModelM2M._meta, ["%stitle" % prefix, "%sattributes__label" % prefix] )
SearchFilterM2MTests
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source_param.py
{ "start": 7587, "end": 8317 }
class ____(TypedDict, total=False): source: Required[Source] """Determines what populates the `item` namespace in this run's data source.""" type: Required[Literal["completions"]] """The type of run data source. Always `completions`.""" input_messages: InputMessages """Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace. """ model: str """The name of the model to use for generating completions (e.g. "o3-mini").""" sampling_params: SamplingParams
CreateEvalCompletionsRunDataSourceParam
python
facebook__pyre-check
client/commands/server_event.py
{ "start": 614, "end": 682 }
class ____: socket_path: Path @dataclasses.dataclass
SocketCreated
python
gevent__gevent
src/greentest/3.12/test_signal.py
{ "start": 44101, "end": 51483 }
class ____(unittest.TestCase): """ Stress signal delivery, especially when a signal arrives in the middle of recomputing the signal state or executing previously tripped signal handlers. """ def setsig(self, signum, handler): old_handler = signal.signal(signum, handler) self.addCleanup(signal.signal, signum, old_handler) def measure_itimer_resolution(self): N = 20 times = [] def handler(signum=None, frame=None): if len(times) < N: times.append(time.perf_counter()) # 1 µs is the smallest possible timer interval, # we want to measure what the concrete duration # will be on this platform signal.setitimer(signal.ITIMER_REAL, 1e-6) self.addCleanup(signal.setitimer, signal.ITIMER_REAL, 0) self.setsig(signal.SIGALRM, handler) handler() while len(times) < N: time.sleep(1e-3) durations = [times[i+1] - times[i] for i in range(len(times) - 1)] med = statistics.median(durations) if support.verbose: print("detected median itimer() resolution: %.6f s." % (med,)) return med def decide_itimer_count(self): # Some systems have poor setitimer() resolution (for example # measured around 20 ms. on FreeBSD 9), so decide on a reasonable # number of sequential timers based on that. reso = self.measure_itimer_resolution() if reso <= 1e-4: return 10000 elif reso <= 1e-2: return 100 else: self.skipTest("detected itimer resolution (%.3f s.) too high " "(> 10 ms.) on this platform (or system too busy)" % (reso,)) @unittest.skipUnless(hasattr(signal, "setitimer"), "test needs setitimer()") def test_stress_delivery_dependent(self): """ This test uses dependent signal handlers. """ N = self.decide_itimer_count() sigs = [] def first_handler(signum, frame): # 1e-6 is the minimum non-zero value for `setitimer()`. # Choose a random delay so as to improve chances of # triggering a race condition. Ideally the signal is received # when inside critical signal-handling routines such as # Py_MakePendingCalls(). signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5) def second_handler(signum=None, frame=None): sigs.append(signum) # Here on Linux, SIGPROF > SIGALRM > SIGUSR1. By using both # ascending and descending sequences (SIGUSR1 then SIGALRM, # SIGPROF then SIGALRM), we maximize chances of hitting a bug. self.setsig(signal.SIGPROF, first_handler) self.setsig(signal.SIGUSR1, first_handler) self.setsig(signal.SIGALRM, second_handler) # for ITIMER_REAL expected_sigs = 0 deadline = time.monotonic() + support.SHORT_TIMEOUT while expected_sigs < N: os.kill(os.getpid(), signal.SIGPROF) expected_sigs += 1 # Wait for handlers to run to avoid signal coalescing while len(sigs) < expected_sigs and time.monotonic() < deadline: time.sleep(1e-5) os.kill(os.getpid(), signal.SIGUSR1) expected_sigs += 1 while len(sigs) < expected_sigs and time.monotonic() < deadline: time.sleep(1e-5) # All ITIMER_REAL signals should have been delivered to the # Python handler self.assertEqual(len(sigs), N, "Some signals were lost") @unittest.skipUnless(hasattr(signal, "setitimer"), "test needs setitimer()") def test_stress_delivery_simultaneous(self): """ This test uses simultaneous signal handlers. """ N = self.decide_itimer_count() sigs = [] def handler(signum, frame): sigs.append(signum) self.setsig(signal.SIGUSR1, handler) self.setsig(signal.SIGALRM, handler) # for ITIMER_REAL expected_sigs = 0 while expected_sigs < N: # Hopefully the SIGALRM will be received somewhere during # initial processing of SIGUSR1. signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5) os.kill(os.getpid(), signal.SIGUSR1) expected_sigs += 2 # Wait for handlers to run to avoid signal coalescing for _ in support.sleeping_retry(support.SHORT_TIMEOUT): if len(sigs) >= expected_sigs: break # All ITIMER_REAL signals should have been delivered to the # Python handler self.assertEqual(len(sigs), N, "Some signals were lost") @unittest.skipIf(sys.platform == "darwin", "crashes due to system bug (FB13453490)") @unittest.skipUnless(hasattr(signal, "SIGUSR1"), "test needs SIGUSR1") @threading_helper.requires_working_threading() def test_stress_modifying_handlers(self): # bpo-43406: race condition between trip_signal() and signal.signal signum = signal.SIGUSR1 num_sent_signals = 0 num_received_signals = 0 do_stop = False def custom_handler(signum, frame): nonlocal num_received_signals num_received_signals += 1 def set_interrupts(): nonlocal num_sent_signals while not do_stop: signal.raise_signal(signum) num_sent_signals += 1 def cycle_handlers(): while num_sent_signals < 100 or num_received_signals < 1: for i in range(20000): # Cycle between a Python-defined and a non-Python handler for handler in [custom_handler, signal.SIG_IGN]: signal.signal(signum, handler) old_handler = signal.signal(signum, custom_handler) self.addCleanup(signal.signal, signum, old_handler) t = threading.Thread(target=set_interrupts) try: ignored = False with support.catch_unraisable_exception() as cm: t.start() cycle_handlers() do_stop = True t.join() if cm.unraisable is not None: # An unraisable exception may be printed out when # a signal is ignored due to the aforementioned # race condition, check it. self.assertIsInstance(cm.unraisable.exc_value, OSError) self.assertIn( f"Signal {signum:d} ignored due to race condition", str(cm.unraisable.exc_value)) ignored = True # bpo-43406: Even if it is unlikely, it's technically possible that # all signals were ignored because of race conditions. if not ignored: # Sanity check that some signals were received, but not all self.assertGreater(num_received_signals, 0) self.assertLessEqual(num_received_signals, num_sent_signals) finally: do_stop = True t.join()
StressTest
python
doocs__leetcode
lcci/17.23.Max Black Square/Solution.py
{ "start": 0, "end": 870 }
class ____: def findSquare(self, matrix: List[List[int]]) -> List[int]: n = len(matrix) down = [[0] * n for _ in range(n)] right = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): for j in range(n - 1, -1, -1): if matrix[i][j] == 0: down[i][j] = down[i + 1][j] + 1 if i + 1 < n else 1 right[i][j] = right[i][j + 1] + 1 if j + 1 < n else 1 for k in range(n, 0, -1): for i in range(n - k + 1): for j in range(n - k + 1): if ( down[i][j] >= k and right[i][j] >= k and right[i + k - 1][j] >= k and down[i][j + k - 1] >= k ): return [i, j, k] return []
Solution
python
aio-libs__aiohttp
tests/test_resolver.py
{ "start": 2511, "end": 2721 }
class ____: def __init__(self, hosts: Collection[str]) -> None: self.nodes = [ FakeAIODNSAddrInfoNode(socket.AF_INET, (h.encode(), 0)) for h in hosts ]
FakeAIODNSAddrInfoIPv4Result
python
joke2k__faker
faker/providers/date_time/ko_KR/__init__.py
{ "start": 46, "end": 796 }
class ____(DateTimeProvider): def day_of_week(self) -> str: day = self.date("%w") DAY_NAMES = { "0": "일요일", "1": "월요일", "2": "화요일", "3": "수요일", "4": "목요일", "5": "금요일", "6": "토요일", } return DAY_NAMES[day] def month_name(self) -> str: month = self.month() MONTH_NAMES = { "01": "1월", "02": "2월", "03": "3월", "04": "4월", "05": "5월", "06": "6월", "07": "7월", "08": "8월", "09": "9월", "10": "10월", "11": "11월", "12": "12월", } return MONTH_NAMES[month]
Provider
python
huggingface__transformers
src/transformers/models/wav2vec2/processing_wav2vec2.py
{ "start": 940, "end": 5620 }
class ____(ProcessorMixin): r""" Constructs a Wav2Vec2 processor which wraps a Wav2Vec2 feature extractor and a Wav2Vec2 CTC tokenizer into a single processor. [`Wav2Vec2Processor`] offers all the functionalities of [`Wav2Vec2FeatureExtractor`] and [`PreTrainedTokenizer`]. See the docstring of [`~Wav2Vec2Processor.__call__`] and [`~Wav2Vec2Processor.decode`] for more information. Args: feature_extractor (`Wav2Vec2FeatureExtractor`): An instance of [`Wav2Vec2FeatureExtractor`]. The feature extractor is a required input. tokenizer ([`PreTrainedTokenizer`]): An instance of [`PreTrainedTokenizer`]. The tokenizer is a required input. """ def __init__(self, feature_extractor, tokenizer): super().__init__(feature_extractor, tokenizer) def __call__( self, audio: Optional[AudioInput] = None, text: Optional[Union[str, list[str], TextInput, PreTokenizedInput]] = None, **kwargs: Unpack[Wav2Vec2ProcessorKwargs], ): """ This method forwards all arguments to [`Wav2Vec2FeatureExtractor.__call__`] and/or [`PreTrainedTokenizer.__call__`] depending on the input modality and returns their outputs. If both modalities are passed, [`Wav2Vec2FeatureExtractor.__call__`] and [`PreTrainedTokenizer.__call__`] are called. Args: audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*): An audio input is passed to [`Wav2Vec2FeatureExtractor.__call__`]. text (`str`, `List[str]`, *optional*): A text input is passed to [`PreTrainedTokenizer.__call__`]. Returns: This method returns the results of each `call` method. If both are used, the output is a dictionary containing the results of both. """ if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.") audio = kwargs.pop("raw_speech") if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process.") output_kwargs = self._merge_kwargs( Wav2Vec2ProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) if audio is not None: inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"]) if text is not None: encodings = self.tokenizer(text, **output_kwargs["text_kwargs"]) if text is None: return inputs elif audio is None: return encodings else: inputs["labels"] = encodings["input_ids"] return inputs def pad(self, *args, **kwargs): """ This method operates on batches of extracted features and/or tokenized text. It forwards all arguments to [`Wav2Vec2FeatureExtractor.pad`] and/or [`PreTrainedTokenizer.pad`] depending on the input modality and returns their outputs. If both modalities are passed, [`Wav2Vec2FeatureExtractor.pad`] and [`PreTrainedTokenizer.pad`] are called. Args: input_features: When the first argument is a dictionary containing a batch of tensors, or the `input_features` argument is present, it is passed to [`Wav2Vec2FeatureExtractor.pad`]. labels: When the `label` argument is present, it is passed to [`PreTrainedTokenizer.pad`]. Returns: This method returns the results of each `pad` method. If both are used, the output is a dictionary containing the results of both. """ input_features = kwargs.pop("input_features", None) labels = kwargs.pop("labels", None) if len(args) > 0: input_features = args[0] args = args[1:] if input_features is not None: input_features = self.feature_extractor.pad(input_features, *args, **kwargs) if labels is not None: labels = self.tokenizer.pad(labels, **kwargs) if labels is None: return input_features elif input_features is None: return labels else: input_features["labels"] = labels["input_ids"] return input_features @property def model_input_names(self): # The processor doesn't return text ids and the model seems to not need them feature_extractor_input_names = self.feature_extractor.model_input_names return feature_extractor_input_names + ["labels"] __all__ = ["Wav2Vec2Processor"]
Wav2Vec2Processor
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_password_is_not_leaked.py
{ "start": 1884, "end": 4563 }
class ____(ColumnMapExpectation): """Expect column values password not leaked (according to haveibeenpwned's API).""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "not_leaked": [ "JuCPJEKcKV2cZVrK", "GFSFJqWRB6Xsgd58", "EzYwf6SyUm8ChcuC", "xzpkvZeXtzd8DN4u", "Gz8nWHWt58gktPM5", ], "some_of_them_leaked": [ "12345", "qwerty", "BazRmDKJWNf5p86z", "gKLU6thg4KxCdsCe", "eagle", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "not_leaked"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "some_of_them_leaked", "mostly": 1}, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.password_is_not_leaked" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], "requirements": ["pwnedpasswords"], } if __name__ == "__main__": ExpectColumnValuesPasswordIsNotLeaked().print_diagnostic_checklist()
ExpectColumnValuesPasswordIsNotLeaked
python
pypa__setuptools
setuptools/_vendor/importlib_metadata/__init__.py
{ "start": 22286, "end": 23665 }
class ____: """ Micro-optimized class for searching a root for children. Root is a path on the file system that may contain metadata directories either as natural directories or within a zip file. >>> FastPath('').children() ['...'] FastPath objects are cached and recycled for any given root. >>> FastPath('foobar') is FastPath('foobar') True """ @functools.lru_cache() # type: ignore def __new__(cls, root): return super().__new__(cls) def __init__(self, root): self.root = root def joinpath(self, child): return pathlib.Path(self.root, child) def children(self): with suppress(Exception): return os.listdir(self.root or '.') with suppress(Exception): return self.zip_children() return [] def zip_children(self): zip_path = zipp.Path(self.root) names = zip_path.root.namelist() self.joinpath = zip_path.joinpath return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) def search(self, name): return self.lookup(self.mtime).search(name) @property def mtime(self): with suppress(OSError): return os.stat(self.root).st_mtime self.lookup.cache_clear() @method_cache def lookup(self, mtime): return Lookup(self)
FastPath
python
run-llama__llama_index
llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-redis/llama_index/storage/chat_store/redis/base.py
{ "start": 902, "end": 15279 }
class ____(BaseChatStore): """Redis chat store.""" redis_url: str = Field(default="redis://localhost:6379", description="Redis URL.") ttl: Optional[int] = Field(default=None, description="Time to live in seconds.") _redis_client: Optional[Redis] = PrivateAttr() _aredis_client: Optional[AsyncRedis] = PrivateAttr() def __init__( self, redis_url: str = "redis://localhost:6379", redis_client: Optional[Redis] = None, aredis_client: Optional[AsyncRedis] = None, ttl: Optional[int] = None, **kwargs: Any, ) -> None: """Initialize.""" super().__init__(ttl=ttl) self._redis_client = redis_client or self._get_client(redis_url, **kwargs) self._aredis_client = aredis_client or self._aget_client(redis_url, **kwargs) @classmethod def class_name(cls) -> str: """Get class name.""" return "RedisChatStore" def set_messages(self, key: str, messages: List[ChatMessage]) -> None: """Set messages for a key.""" self._redis_client.delete(key) for message in messages: self.add_message(key, message) if self.ttl: self._redis_client.expire(key, self.ttl) async def aset_messages(self, key: str, messages: List[ChatMessage]) -> None: await self._aredis_client.delete(key) for message in messages: await self.async_add_message(key, message) if self.ttl: await self._aredis_client.expire(key, self.ttl) def get_messages(self, key: str) -> List[ChatMessage]: """Get messages for a key.""" items = self._redis_client.lrange(key, 0, -1) if len(items) == 0: return [] items_json = [json.loads(m.decode("utf-8")) for m in items] return [_dict_to_message(d) for d in items_json] async def aget_messages(self, key: str) -> List[ChatMessage]: """Get messages for a key.""" items = await self._aredis_client.lrange(key, 0, -1) if len(items) == 0: return [] items_json = [json.loads(m.decode("utf-8")) for m in items] return [_dict_to_message(d) for d in items_json] def add_message( self, key: str, message: ChatMessage, idx: Optional[int] = None ) -> None: """Add a message for a key.""" if idx is None: item = json.dumps(_message_to_dict(message)) self._redis_client.rpush(key, item) else: self._insert_element_at_index(key, idx, message) if self.ttl: self._redis_client.expire(key, self.ttl) async def async_add_message( self, key: str, message: ChatMessage, idx: Optional[int] = None ) -> None: """Add a message for a key.""" if idx is None: item = json.dumps(_message_to_dict(message)) await self._aredis_client.rpush(key, item) else: await self._ainsert_element_at_index(key, idx, message) if self.ttl: await self._aredis_client.expire(key, self.ttl) def delete_messages(self, key: str) -> Optional[List[ChatMessage]]: """Delete messages for a key.""" self._redis_client.delete(key) return None async def adelete_messages(self, key: str) -> Optional[List[ChatMessage]]: """Delete messages for a key.""" await self._aredis_client.delete(key) return None def delete_message(self, key: str, idx: int) -> Optional[ChatMessage]: """Delete specific message for a key.""" current_list = self._redis_client.lrange(key, 0, -1) if 0 <= idx < len(current_list): removed_item = current_list.pop(idx) self._redis_client.delete(key) self._redis_client.lpush(key, *current_list) return removed_item else: return None async def adelete_message(self, key: str, idx: int) -> Optional[ChatMessage]: """Delete specific message for a key.""" current_list = await self._aredis_client.lrange(key, 0, -1) if 0 <= idx < len(current_list): removed_item = current_list.pop(idx) await self._aredis_client.delete(key) await self._aredis_client.lpush(key, *current_list) return removed_item else: return None def delete_last_message(self, key: str) -> Optional[ChatMessage]: """Delete last message for a key.""" return self._redis_client.rpop(key) def get_keys(self) -> List[str]: """Get all keys.""" return [key.decode("utf-8") for key in self._redis_client.keys("*")] def _insert_element_at_index( self, key: str, index: int, message: ChatMessage ) -> List[ChatMessage]: # Step 1: Retrieve the current list current_list = self.get_messages(key) # Step 2: Insert the new element at the desired index in the local list current_list.insert(index, message) # Step 3: Push the modified local list back to Redis self._redis_client.delete(key) # Remove the existing list self.set_messages(key, current_list) return self.get_messages(key) async def _ainsert_element_at_index( self, key: str, index: int, message: ChatMessage ) -> List[ChatMessage]: # Step 1: Retrieve the current list current_list = await self.aget_messages(key) # Step 2: Insert the new element at the desired index in the local list current_list.insert(index, message) # Step 3: Push the modified local list back to Redis await self._aredis_client.delete(key) # Remove the existing list await self.aset_messages(key, current_list) return await self.aget_messages(key) def _redis_cluster_client(self, redis_url: str, **kwargs: Any) -> "Redis": return RedisCluster.from_url(redis_url, **kwargs) # type: ignore def _aredis_cluster_client(self, redis_url: str, **kwargs: Any) -> "AsyncRedis": return AsyncRedisCluster.from_url(redis_url, **kwargs) def _check_for_cluster(self, redis_client: Union["Redis", "AsyncRedis"]) -> bool: try: cluster_info = redis_client.info("cluster") return cluster_info["cluster_enabled"] == 1 except redis.exceptions.RedisError: return False def _redis_sentinel_parser( self, redis_url: str, **kwargs ) -> Tuple[str, List[Tuple[str, int]]]: """ Helper method to parse an (un-official) redis+sentinel url and create a Sentinel connection to fetch the final redis client connection to a replica-master for read-write operations. If username and/or password for authentication is given the same credentials are used for the Redis Sentinel as well as Redis Server. With this implementation using a redis url only it is not possible to use different data for authentication on booth systems. """ parsed_url = urlparse(redis_url) # sentinel needs list with (host, port) tuple, use default port if none available sentinel_list = [(parsed_url.hostname or "localhost", parsed_url.port or 26379)] if parsed_url.path: # "/mymaster/0" first part is service name, optional second part is db number path_parts = parsed_url.path.split("/") service_name = path_parts[1] or "mymaster" if len(path_parts) > 2: kwargs["db"] = path_parts[2] else: service_name = "mymaster" sentinel_args = {} if parsed_url.password: sentinel_args["password"] = parsed_url.password kwargs["password"] = parsed_url.password if parsed_url.username: sentinel_args["username"] = parsed_url.username kwargs["username"] = parsed_url.username # check for all SSL related properties and copy them into sentinel_kwargs too, # add client_name also for arg in kwargs: if arg.startswith("ssl") or arg == "client_name": sentinel_args[arg] = kwargs[arg] return sentinel_args, sentinel_list, service_name, kwargs def _redis_sentinel_client(self, redis_url: str, **kwargs: Any) -> "Redis": ( sentinel_args, sentinel_list, service_name, kwargs, ) = self._redis_sentinel_parser(redis_url, **kwargs) # sentinel user/pass is part of sentinel_kwargs, user/pass for redis server # connection as direct parameter in kwargs sentinel_client = Sentinel( sentinel_list, sentinel_kwargs=sentinel_args, **kwargs ) # redis server might have password but not sentinel - fetch this error and try # again without pass, everything else cannot be handled here -> user needed try: sentinel_client.execute_command("ping") except redis.exceptions.AuthenticationError: exception_info = sys.exc_info() exception = exception_info[1] or None if exception is not None and "no password is set" in exception.args[0]: logging.warning( msg="Redis sentinel connection configured with password but Sentinel \ answered NO PASSWORD NEEDED - Please check Sentinel configuration" ) sentinel_client = Sentinel(sentinel_list, **kwargs) else: raise return sentinel_client.master_for(service_name) def _aredis_sentinel_client(self, redis_url: str, **kwargs: Any) -> "AsyncRedis": ( sentinel_args, sentinel_list, service_name, kwargs, ) = self._redis_sentinel_parser(redis_url, **kwargs) sentinel_client = AsyncSentinel( sentinel_list, sentinel_kwargs=sentinel_args, **kwargs ) try: asyncio.run(sentinel_client.execute_command("ping")) except redis.exceptions.AuthenticationError: exception_info = sys.exc_info() exception = exception_info[1] or None if exception is not None and "no password is set" in exception.args[0]: logging.warning( msg="Redis sentinel connection configured with password but Sentinel \ answered NO PASSWORD NEEDED - Please check Sentinel configuration" ) sentinel_client = AsyncSentinel(sentinel_list, **kwargs) else: raise return sentinel_client.master_for(service_name) def _get_client(self, redis_url: str, **kwargs: Any) -> "Redis": """ Get a redis client from the connection url given. This helper accepts urls for Redis server (TCP with/without TLS or UnixSocket) as well as Redis Sentinel connections. Redis Cluster is not supported. Before creating a connection the existence of the database driver is checked an and ValueError raised otherwise To use, you should have the ``redis`` python package installed. Example: .. code-block:: python redis_client = get_client( redis_url="redis://username:password@localhost:6379" ) To use a redis replication setup with multiple redis server and redis sentinels set "redis_url" to "redis+sentinel://" scheme. With this url format a path is needed holding the name of the redis service within the sentinels to get the correct redis server connection. The default service name is "mymaster". The optional second part of the path is the redis db number to connect to. An optional username or password is used for booth connections to the rediserver and the sentinel, different passwords for server and sentinel are not supported. And as another constraint only one sentinel instance can be given: Example: .. code-block:: python redis_client = get_client( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" ) """ # Initialize with necessary components. redis_client: "Redis" # check if normal redis:// or redis+sentinel:// url if redis_url.startswith("redis+sentinel"): redis_client = self._redis_sentinel_client(redis_url, **kwargs) elif redis_url.startswith( "rediss+sentinel" ): # sentinel with TLS support enables kwargs["ssl"] = True if "ssl_cert_reqs" not in kwargs: kwargs["ssl_cert_reqs"] = "none" redis_client = self._redis_sentinel_client(redis_url, **kwargs) else: # connect to redis server from url, reconnect with cluster client if needed redis_client = redis.from_url(redis_url, **kwargs) if self._check_for_cluster(redis_client): redis_client.close() redis_client = self._redis_cluster_client(redis_url, **kwargs) return redis_client def _aget_client(self, redis_url: str, **kwargs: Any) -> "AsyncRedis": aredis_client: "AsyncRedis" # check if normal redis:// or redis+sentinel:// url if redis_url.startswith("redis+sentinel"): aredis_client = self._aredis_sentinel_client(redis_url, **kwargs) elif redis_url.startswith( "rediss+sentinel" ): # sentinel with TLS support enables kwargs["ssl"] = True if "ssl_cert_reqs" not in kwargs: kwargs["ssl_cert_reqs"] = "none" aredis_client = self._aredis_sentinel_client(redis_url, **kwargs) else: # connect to redis server from url, reconnect with cluster client if needed aredis_client = redis.asyncio.from_url(redis_url, **kwargs) redis_client = redis.from_url(redis_url, **kwargs) is_cluster = self._check_for_cluster(redis_client) redis_client.close() if is_cluster: asyncio.create_task(aredis_client.close()) aredis_client = self._aredis_cluster_client(redis_url, **kwargs) return aredis_client
RedisChatStore
python
apache__thrift
lib/py/src/TMultiplexedProcessor.py
{ "start": 965, "end": 3114 }
class ____(TProcessor): def __init__(self): self.defaultProcessor = None self.services = {} def registerDefault(self, processor): """ If a non-multiplexed processor connects to the server and wants to communicate, use the given processor to handle it. This mechanism allows servers to upgrade from non-multiplexed to multiplexed in a backwards-compatible way and still handle old clients. """ self.defaultProcessor = processor def registerProcessor(self, serviceName, processor): self.services[serviceName] = processor def on_message_begin(self, func): for key in self.services.keys(): self.services[key].on_message_begin(func) def process(self, iprot, oprot): (name, type, seqid) = iprot.readMessageBegin() if type != TMessageType.CALL and type != TMessageType.ONEWAY: raise TProtocolException( TProtocolException.NOT_IMPLEMENTED, "TMultiplexedProtocol only supports CALL & ONEWAY") index = name.find(TMultiplexedProtocol.SEPARATOR) if index < 0: if self.defaultProcessor: return self.defaultProcessor.process( StoredMessageProtocol(iprot, (name, type, seqid)), oprot) else: raise TProtocolException( TProtocolException.NOT_IMPLEMENTED, "Service name not found in message name: " + name + ". " + "Did you forget to use TMultiplexedProtocol in your client?") serviceName = name[0:index] call = name[index + len(TMultiplexedProtocol.SEPARATOR):] if serviceName not in self.services: raise TProtocolException( TProtocolException.NOT_IMPLEMENTED, "Service name not found: " + serviceName + ". " + "Did you forget to call registerProcessor()?") standardMessage = (call, type, seqid) return self.services[serviceName].process( StoredMessageProtocol(iprot, standardMessage), oprot)
TMultiplexedProcessor
python
bokeh__bokeh
release/logger.py
{ "start": 1217, "end": 2466 }
class ____: """""" def __init__(self) -> None: self._scrubbers: list[Scrubber] = [] self._record: list[str] = [] def add_scrubber(self, scrubber: Scrubber) -> None: """""" self._scrubbers.append(scrubber) self._scrubbers.sort(key=len) def record(self, *lines: str) -> tuple[int, int]: """""" if len(lines) == 1 and "\n" in lines[0]: lines = tuple(lines[0].split("\n")) start = len(self._record) for line in lines: line = self._scrub_text(line) self._record.append(line) print(line, flush=True) return (start, len(self._record)) def clear(self) -> None: self._record = [] def dump(self, *, start: int = 0, end: int | None = None, filter_ansi: bool = True) -> str: """""" lines = self._record[start:end] # scrub outbound for good measure full_text = self._scrub_text("\n".join(lines)) if filter_ansi: full_text = _ANSI_ESCAPE.sub("", full_text) return full_text def _scrub_text(self, text: str) -> str: for scrubber in self._scrubbers: text = scrubber.clean(text) return text LOG = Log()
Log
python
FactoryBoy__factory_boy
tests/test_using.py
{ "start": 69948, "end": 74948 }
class ____(unittest.TestCase): def test_post_generation(self): class TestObjectFactory(factory.Factory): class Meta: model = TestObject one = 1 @factory.post_generation def incr_one(self, _create, _increment): self.one += 1 obj = TestObjectFactory.build() self.assertEqual(2, obj.one) self.assertFalse(hasattr(obj, 'incr_one')) obj = TestObjectFactory.build(one=2) self.assertEqual(3, obj.one) self.assertFalse(hasattr(obj, 'incr_one')) def test_post_generation_hook(self): class TestObjectFactory(factory.Factory): class Meta: model = TestObject one = 1 @factory.post_generation def incr_one(self, _create, _increment): self.one += 1 return 42 @classmethod def _after_postgeneration(cls, obj, create, results): obj.create = create obj.results = results obj = TestObjectFactory.build() self.assertEqual(2, obj.one) self.assertFalse(obj.create) self.assertEqual({'incr_one': 42}, obj.results) def test_post_generation_extraction(self): class TestObjectFactory(factory.Factory): class Meta: model = TestObject one = 1 @factory.post_generation def incr_one(self, _create, increment=1): self.one += increment obj = TestObjectFactory.build(incr_one=2) self.assertEqual(3, obj.one) self.assertFalse(hasattr(obj, 'incr_one')) obj = TestObjectFactory.build(one=2, incr_one=2) self.assertEqual(4, obj.one) self.assertFalse(hasattr(obj, 'incr_one')) def test_post_generation_extraction_lambda(self): def my_lambda(obj, create, extracted, **kwargs): self.assertTrue(isinstance(obj, TestObject)) self.assertFalse(create) self.assertEqual(extracted, 42) self.assertEqual(kwargs, {'foo': 13}) class TestObjectFactory(factory.Factory): class Meta: model = TestObject bar = factory.PostGeneration(my_lambda) TestObjectFactory.build(bar=42, bar__foo=13) def test_post_generation_override_with_extra(self): class TestObjectFactory(factory.Factory): class Meta: model = TestObject one = 1 @factory.post_generation def incr_one(self, _create, override, **extra): multiplier = extra.get('multiplier', 1) if override is None: override = 1 self.one += override * multiplier obj = TestObjectFactory.build() self.assertEqual(1 + 1 * 1, obj.one) obj = TestObjectFactory.build(incr_one=2) self.assertEqual(1 + 2 * 1, obj.one) obj = TestObjectFactory.build(incr_one__multiplier=4) self.assertEqual(1 + 1 * 4, obj.one) obj = TestObjectFactory.build(incr_one=2, incr_one__multiplier=5) self.assertEqual(1 + 2 * 5, obj.one) # Passing extras through inherited params class OtherTestObjectFactory(TestObjectFactory): class Params: incr_one__multiplier = 4 obj = OtherTestObjectFactory.build() self.assertEqual(1 + 1 * 4, obj.one) def test_post_generation_method_call(self): class TestObject: def __init__(self, one=None, two=None): self.one = one self.two = two self.extra = None def call(self, *args, **kwargs): self.extra = (args, kwargs) class TestObjectFactory(factory.Factory): class Meta: model = TestObject one = 3 two = 2 post_call = factory.PostGenerationMethodCall('call', one=1) obj = TestObjectFactory.build() self.assertEqual(3, obj.one) self.assertEqual(2, obj.two) self.assertEqual(((), {'one': 1}), obj.extra) obj = TestObjectFactory.build(post_call__one=2, post_call__two=3) self.assertEqual(3, obj.one) self.assertEqual(2, obj.two) self.assertEqual(((), {'one': 2, 'two': 3}), obj.extra) def test_post_generation_extraction_declaration(self): LIBRARY = {} Book = collections.namedtuple('Book', ['author']) class BookFactory(factory.Factory): class Meta: model = Book author = factory.Faker('name') register__reference = factory.Sequence(lambda n: n) @factory.post_generation def register(self, create, extracted, reference=0, **kwargs): LIBRARY[reference] = self book = BookFactory.build() self.assertEqual({0: book}, LIBRARY)
PostGenerationTestCase
python
airbytehq__airbyte
airbyte-integrations/connectors/source-s3/source_s3/v4/source.py
{ "start": 1281, "end": 8967 }
class ____(FileBasedSource): _concurrency_level = DEFAULT_CONCURRENCY @classmethod def read_config(cls, config_path: str) -> Mapping[str, Any]: """ Used to override the default read_config so that when the new file-based S3 connector processes a config in the legacy format, it can be transformed into the new config. This happens in entrypoint before we validate the config against the new spec. """ config = super().read_config(config_path) if not SourceS3._is_v4_config(config): parsed_legacy_config = SourceS3Spec(**config) converted_config = LegacyConfigTransformer.convert(parsed_legacy_config) emit_configuration_as_airbyte_control_message(converted_config) return converted_config return config def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification: s3_spec = SourceS3Spec.schema() s4_spec = self.spec_class.schema() if s3_spec["properties"].keys() & s4_spec["properties"].keys(): raise ValueError("Overlapping properties between V3 and V4") # pragma: no cover for v3_property_key, v3_property_value in s3_spec["properties"].items(): s4_spec["properties"][v3_property_key] = v3_property_value s4_spec["properties"][v3_property_key]["airbyte_hidden"] = True s4_spec["properties"][v3_property_key]["order"] += 100 s4_spec["properties"][v3_property_key]["description"] = ( SourceS3._create_description_with_deprecation_prefix(_V3_DEPRECATION_FIELD_MAPPING.get(v3_property_key, None)) + s4_spec["properties"][v3_property_key]["description"] ) self._clean_required_fields(s4_spec["properties"][v3_property_key]) if is_cloud_environment(): s4_spec["properties"]["endpoint"].update( { "description": "Endpoint to an S3 compatible service. Leave empty to use AWS. " "The custom endpoint must be secure, but the 'https' prefix is not required.", "pattern": "^(?!http://).*$", # ignore-https-check } ) return ConnectorSpecification( documentationUrl=self.spec_class.documentation_url(), connectionSpecification=s4_spec, ) @staticmethod def _is_v4_config(config: Mapping[str, Any]) -> bool: return "streams" in config @staticmethod def _clean_required_fields(v3_field: Dict[str, Any]) -> None: """ Not having V3 fields root level as part of the `required` field is not enough as the platform will create empty objects for those. For example, filling all non-hidden fields from the form will create a config like: ``` { <...> "provider": {}, <...> } ``` As the field `provider` exists, the JSON validation will be applied and as `provider.bucket` is needed, the validation will fail with the following error: ``` "errors": { "connectionConfiguration": { "provider": { "bucket": { "message": "form.empty.error", "type": "required" } } } } ``` Hence, we need to make any V3 nested fields not required. """ if "properties" not in v3_field: return v3_field["required"] = [] for neste_field in v3_field["properties"]: SourceS3._clean_required_fields(neste_field) @staticmethod def _create_description_with_deprecation_prefix(new_fields: Optional[str]) -> str: # pragma: no cover if new_fields: return f"Deprecated and will be removed soon. Please do not use this field anymore and use {new_fields} instead. " return "Deprecated and will be removed soon. Please do not use this field anymore. " @classmethod def launch(cls, args: list[str] | None = None) -> None: """Launch the source using the provided CLI args. If no args are provided, the launch args will be inferred automatically. In the future, we should consider moving this method to the Connector base class, so that all sources and destinations can launch themselves and so none of this code needs to live in the connector itself. """ args = args or sys.argv[1:] catalog_path = AirbyteEntrypoint.extract_catalog(args) # TODO: Delete if not needed: # config_path = AirbyteEntrypoint.extract_config(args) # state_path = AirbyteEntrypoint.extract_state(args) source = cls.create( configured_catalog_path=Path(catalog_path) if catalog_path else None, ) # The following function will wrap the execution in proper error handling. # Failures prior to here may not emit proper Airbyte TRACE or CONNECTION_STATUS messages. launch( source=source, args=args, ) @classmethod def create( cls, *, configured_catalog_path: Path | str | None = None, ) -> SourceS3: """Create a new instance of the source. This is a bit of a hack because (1) the source needs the catalog early, and (2), the constructor asks for things that the caller won't know about, specifically: the stream reader class, the spec class, and the cursor class. We should consider refactoring the constructor so that these inputs don't need to be provided by the caller. This probably requires changes to the base class in the CDK. We prefer to fail in the `launch` method, where proper error handling is in place. """ try: configured_catalog: ConfiguredAirbyteCatalog | None = ( ConfiguredAirbyteCatalogSerializer.load(orjson.loads(Path(configured_catalog_path).read_text())) if configured_catalog_path else None ) except Exception as ex: print( airbyte_message_to_json( AirbyteMessage( type=Type.TRACE, trace=AirbyteTraceMessage( type=TraceType.ERROR, emitted_at=int(datetime.now().timestamp() * 1000), error=AirbyteErrorTraceMessage( message="Error starting the sync. This could be due to an invalid configuration or catalog. Please contact Support for assistance.", stack_trace=traceback.format_exc(), internal_message=str(ex), ), ), ), newline=True, ) ) # Ideally we'd call `raise` here, but sometimes the stack trace bleeds into # the Airbyte logs, which is not ideal. So we'll just exit with an error code instead. sys.exit(1) return cls( # These are the defaults for the source. No need for a caller to change them: stream_reader=SourceS3StreamReader(), spec_class=Config, cursor_cls=Cursor, # This is needed early. (We also will provide it again later.) catalog=configured_catalog, # These will be provided later, after we have wrapped proper error handling. config=None, state=None, )
SourceS3
python
streamlit__streamlit
lib/streamlit/runtime/stats.py
{ "start": 877, "end": 3007 }
class ____(NamedTuple): """Describes a single cache entry. Properties ---------- category_name : str A human-readable name for the cache "category" that the entry belongs to - e.g. "st.memo", "session_state", etc. cache_name : str A human-readable name for cache instance that the entry belongs to. For "st.memo" and other function decorator caches, this might be the name of the cached function. If the cache category doesn't have multiple separate cache instances, this can just be the empty string. byte_length : int The entry's memory footprint in bytes. """ category_name: str cache_name: str byte_length: int def to_metric_str(self) -> str: return f'cache_memory_bytes{{cache_type="{self.category_name}",cache="{self.cache_name}"}} {self.byte_length}' def marshall_metric_proto(self, metric: MetricProto) -> None: """Fill an OpenMetrics `Metric` protobuf object.""" label = metric.labels.add() label.name = "cache_type" label.value = self.category_name label = metric.labels.add() label.name = "cache" label.value = self.cache_name metric_point = metric.metric_points.add() metric_point.gauge_value.int_value = self.byte_length def group_stats(stats: list[CacheStat]) -> list[CacheStat]: """Group a list of CacheStats by category_name and cache_name and sum byte_length.""" def key_function(individual_stat: CacheStat) -> tuple[str, str]: return individual_stat.category_name, individual_stat.cache_name result: list[CacheStat] = [] sorted_stats = sorted(stats, key=key_function) grouped_stats = itertools.groupby(sorted_stats, key=key_function) for (category_name, cache_name), single_group_stats in grouped_stats: result.append( CacheStat( category_name=category_name, cache_name=cache_name, byte_length=sum(item.byte_length for item in single_group_stats), ) ) return result @runtime_checkable
CacheStat
python
falconry__falcon
tests/test_cors_middleware.py
{ "start": 7664, "end": 13755 }
class ____: def test_raises(self): with pytest.raises(ValueError, match='passed to allow_origins'): falcon.CORSMiddleware(allow_origins=['*']) with pytest.raises(ValueError, match='passed to allow_credentials'): falcon.CORSMiddleware(allow_credentials=['*']) @pytest.mark.parametrize( 'allow, fail_origins, success_origins', ( ('*', [None], ['foo', 'bar']), ('test', ['other', 'Test', 'TEST'], ['test']), ( ['foo', 'bar'], ['foo, bar', 'foobar', 'foo,bar', 'Foo', 'BAR'], ['foo', 'bar'], ), ), ) def test_allow_origin(self, make_cors_client, allow, fail_origins, success_origins): client = make_cors_client(falcon.CORSMiddleware(allow_origins=allow)) client.app.add_route('/', CORSHeaderResource()) for origin in fail_origins: h = {'Origin': origin} if origin is not None else {} res = client.simulate_get(headers=h) h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Allow-Origin'.lower() not in h assert 'Access-Control-Allow-Credentials'.lower() not in h assert 'Access-Control-Expose-Headers'.lower() not in h for origin in success_origins: res = client.simulate_get(headers={'Origin': origin}) assert ( res.headers['Access-Control-Allow-Origin'] == '*' if allow == '*' else origin ) h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Allow-Credentials'.lower() not in h assert 'Access-Control-Expose-Headers'.lower() not in h def test_allow_credential_wildcard(self, make_cors_client): client = make_cors_client(falcon.CORSMiddleware(allow_credentials='*')) client.app.add_route('/', CORSHeaderResource()) res = client.simulate_get(headers={'Origin': 'localhost'}) assert res.headers['Access-Control-Allow-Origin'] == 'localhost' assert res.headers['Access-Control-Allow-Credentials'] == 'true' @pytest.mark.parametrize( 'allow, successOrigin', ( (['foo', 'bar'], ['foo', 'bar']), ('foo', ['foo']), ), ) def test_allow_credential_list_or_str(self, make_cors_client, allow, successOrigin): client = make_cors_client(falcon.CORSMiddleware(allow_credentials=allow)) client.app.add_route('/', CORSHeaderResource()) for origin in ('foo, bar', 'foobar', 'foo,bar', 'Foo', 'BAR'): res = client.simulate_get(headers={'Origin': origin}) assert res.headers['Access-Control-Allow-Origin'] == '*' h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Allow-Credentials'.lower() not in h assert 'Access-Control-Expose-Headers'.lower() not in h for origin in successOrigin: res = client.simulate_get(headers={'Origin': origin}) assert res.headers['Access-Control-Allow-Origin'] == origin assert res.headers['Access-Control-Allow-Credentials'] == 'true' h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Expose-Headers'.lower() not in h def test_allow_credential_existing_origin(self, make_cors_client): client = make_cors_client(falcon.CORSMiddleware(allow_credentials='*')) client.app.add_route('/', CORSHeaderResource()) res = client.simulate_delete(headers={'Origin': 'something'}) assert res.headers['Access-Control-Allow-Origin'] == 'example.com' h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Allow-Credentials'.lower() not in h def test_allow_origin_allow_credential(self, make_cors_client): client = make_cors_client( falcon.CORSMiddleware(allow_origins='test', allow_credentials='*') ) client.app.add_route('/', CORSHeaderResource()) for origin in ['foo', 'TEST']: res = client.simulate_get(headers={'Origin': origin}) h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Allow-Origin'.lower() not in h assert 'Access-Control-Allow-Credentials'.lower() not in h assert 'Access-Control-Expose-Headers'.lower() not in h res = client.simulate_get(headers={'Origin': 'test'}) assert res.headers['Access-Control-Allow-Origin'] == 'test' assert res.headers['Access-Control-Allow-Credentials'] == 'true' h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Expose-Headers'.lower() not in h @pytest.mark.parametrize( 'attr, exp', ( ('foo', 'foo'), ('foo, bar', 'foo, bar'), (['foo', 'bar'], 'foo, bar'), ), ) def test_expose_headers(self, make_cors_client, attr, exp): client = make_cors_client( falcon.CORSMiddleware(expose_headers=attr, allow_credentials=None) ) client.app.add_route('/', CORSHeaderResource()) res = client.simulate_get(headers={'Origin': 'something'}) assert res.headers['Access-Control-Allow-Origin'] == '*' assert res.headers['Access-Control-Expose-Headers'] == exp h = dict(res.headers.lower_items()).keys() assert 'Access-Control-Allow-Credentials'.lower() not in h def test_enabled_cors_private_network_headers(self, make_cors_client): client = make_cors_client(falcon.CORSMiddleware(allow_private_network=True)) client.app.add_route('/', CORSHeaderResource()) res = client.simulate_options( '/', headers=( ('Origin', 'localhost'), ('Access-Control-Request-Method', 'GET'), ('Access-Control-Request-Private-Network', 'true'), ), ) assert res.headers['Access-Control-Allow-Private-Network'] == 'true'
TestCustomCorsMiddleware
python
scipy__scipy
scipy/special/_support_alternative_backends.py
{ "start": 463, "end": 28147 }
class ____: # NumPy-only function. IT MUST BE ELEMENTWISE. func: Callable # Number of arguments, not counting out= # This is for testing purposes only, due to the fact that # inspect.signature() just returns *args for ufuncs. n_args: int # @xp_capabilities decorator, for the purpose of # documentation and unit testing. Omit to indicate # full support for all backends. xp_capabilities: Callable[[Callable], Callable] | None = None # Generic implementation to fall back on if there is no native dispatch # available. This is a function that accepts (main namespace, scipy namespace) # and returns the final callable, or None if not available. generic_impl: Callable[ [ModuleType, ModuleType | None], Callable | None ] | None = None # Handle case where a backend uses an alternative name for a function. # Should map backend names to alternative function names. alt_names_map: dict[str, str] | None = None # Some functions only take integer arrays for some arguments. int_only: tuple[bool] | None = None # For testing purposes, whether tests should only use positive values # for some arguments. If bool and equal to True, restrict to positive # values for all arguments. To restrict only some arguments to positive # values, pass a tuple of bool of the same length as the number of # arguments, the ith entry in the tuple controls positive_only for # the ith argument. To make backend specific choices for positive_only, # pass in a dict mapping backend names to bool or tuple[bool]. positive_only: bool | tuple[bool] | dict[str, tuple[bool]] = False # Some special functions are not ufuncs and ufunc-specific tests # should not be applied to these. is_ufunc: bool = True # Some non-ufunc special functions take only Python ints for some arguments. # If so, python_int_only should be a tuple of the same length as the number # of arguments,with value True if the corresponding argument needs to be a # Python int. # Can also take a dict mapping backends to such tuples if an argument being # Python int only is backend specific. python_int_only: dict[str, tuple[bool]] | tuple[bool] | None = None # Some functions which seem to be scalar also accept 0d arrays. scalar_or_0d_only: dict[str, tuple[bool]] | tuple[bool] | None = None # Some functions may not work well with very large integer valued arguments. test_large_ints: bool = True # Some non-ufunc special functions don't decay 0d arrays to scalar. produces_0d: bool = False # Whether or not uses native PyTorch or falls back to NumPy/SciPy. This # is needed because in PyTorch, the default dtype affects promotion # rules when mixing integer and floating dtypes, so relying on a # NumPy/SciPy fallback when the default dtype is other than float64 can lead # to float64 output when native PyTorch would have e.g. float32 output. This # must be accounted for in tests. Not putting this in xp_capabilities for now, # but in the future I think it's likely we may want to add a warning to # xp_capabilities when not using native PyTorch on CPU. torch_native: bool = True @property def name(self): return self.func.__name__ # These are needed by @lru_cache below def __hash__(self): return hash(self.func) def __eq__(self, other): return isinstance(other, _FuncInfo) and self.func == other.func @property def wrapper(self): if self.name in globals(): # Already initialised. We are likely in a unit test. # Return function potentially overridden by xpx.testing.lazy_xp_function. import scipy.special return getattr(scipy.special, self.name) if SCIPY_ARRAY_API: @functools.wraps(self.func) def wrapped(*args, **kwargs): xp = array_namespace(*args) return self._wrapper_for(xp)(*args, **kwargs) # Allow pickling the function. Normally this is done by @wraps, # but in this case it doesn't work because self.func is a ufunc. wrapped.__module__ = "scipy.special" wrapped.__qualname__ = self.name func = wrapped else: func = self.func capabilities = self.xp_capabilities or xp_capabilities() # In order to retain a naked ufunc when SCIPY_ARRAY_API is # disabled, xp_capabilities must apply its changes in place. cap_func = capabilities(func) assert cap_func is func return func @functools.lru_cache(1000) def _wrapper_for(self, xp): if is_numpy(xp): return self.func # If a native implementation is available, use that spx = scipy_namespace_for(xp) f = _get_native_func(xp, spx, self.name, alt_names_map=self.alt_names_map) if f is not None: return f # If generic Array API implementation is available, use that if self.generic_impl is not None: f = self.generic_impl(xp, spx) if f is not None: return f if is_marray(xp): # Unwrap the array, apply the function on the wrapped namespace, # and then re-wrap it. # IMPORTANT: this only works because all functions in this module # are elementwise. Otherwise, we would not be able to define a # general rule for mask propagation. _f = globals()[self.name] # Allow nested wrapping def f(*args, _f=_f, xp=xp, **kwargs): data_args = [arg.data for arg in args] out = _f(*data_args, **kwargs) mask = functools.reduce(operator.or_, (arg.mask for arg in args)) return xp.asarray(out, mask=mask) return f if is_dask(xp): # Apply the function to each block of the Dask array. # IMPORTANT: map_blocks works only because all functions in this module # are elementwise. It would be a grave mistake to apply this to gufuncs # or any other function with reductions, as they would change their # output depending on chunking! _f = globals()[self.name] # Allow nested wrapping def f(*args, _f=_f, xp=xp, **kwargs): # Hide dtype kwarg from map_blocks return xp.map_blocks(functools.partial(_f, **kwargs), *args) return f # As a final resort, use the NumPy/SciPy implementation _f = self.func def f(*args, _f=_f, xp=xp, **kwargs): # TODO use xpx.lazy_apply to add jax.jit support # (but dtype propagation can be non-trivial) args = [np.asarray(arg) for arg in args] out = _f(*args, **kwargs) return xp.asarray(out) return f def _get_native_func(xp, spx, f_name, *, alt_names_map=None): if alt_names_map is None: alt_names_map = {} f_name = alt_names_map.get(get_native_namespace_name(xp), f_name) f = getattr(spx.special, f_name, None) if spx else None if f is None and hasattr(xp, 'special'): # Currently dead branch, in anticipation of 'special' Array API extension # https://github.com/data-apis/array-api/issues/725 f = getattr(xp.special, f_name, None) return f def _rel_entr(xp, spx): def __rel_entr(x, y, *, xp=xp): # https://github.com/data-apis/array-api-extra/issues/160 mxp = array_namespace(x._meta, y._meta) if is_dask(xp) else xp x, y = xp_promote(x, y, broadcast=True, force_floating=True, xp=xp) xy_pos = (x > 0) & (y > 0) xy_inf = xp.isinf(x) & xp.isinf(y) res = xpx.apply_where( xy_pos & ~xy_inf, (x, y), # Note: for very large x, this can overflow. lambda x, y: x * (mxp.log(x) - mxp.log(y)), fill_value=xp.inf ) res = xpx.at(res)[(x == 0) & (y >= 0)].set(0) res = xpx.at(res)[xp.isnan(x) | xp.isnan(y) | (xy_pos & xy_inf)].set(xp.nan) return res return __rel_entr def _xlogy(xp, spx): def __xlogy(x, y, *, xp=xp): x, y = xp_promote(x, y, force_floating=True, xp=xp) with np.errstate(divide='ignore', invalid='ignore'): temp = x * xp.log(y) return xp.where(x == 0., 0., temp) return __xlogy def _chdtr(xp, spx): # The difference between this and just using `gammainc` # defined by `get_array_special_func` is that if `gammainc` # isn't found, we don't want to use the SciPy version; we'll # return None here and use the SciPy version of `chdtr`. gammainc = _get_native_func(xp, spx, 'gammainc') if gammainc is None: return None def __chdtr(v, x): res = gammainc(v / 2, x / 2) # this is almost all we need # The rest can be removed when google/jax#20507 is resolved mask = (v == 0) & (x > 0) # JAX returns NaN res = xp.where(mask, 1., res) mask = xp.isinf(v) & xp.isinf(x) # JAX returns 1.0 return xp.where(mask, xp.nan, res) return __chdtr def _chdtrc(xp, spx): # The difference between this and just using `gammaincc` # defined by `get_array_special_func` is that if `gammaincc` # isn't found, we don't want to use the SciPy version; we'll # return None here and use the SciPy version of `chdtrc`. gammaincc = _get_native_func(xp, spx, 'gammaincc') if gammaincc is None: return None def __chdtrc(v, x): res = xp.where(x >= 0, gammaincc(v/2, x/2), 1) i_nan = ((x == 0) & (v == 0)) | xp.isnan(x) | xp.isnan(v) | (v <= 0) res = xp.where(i_nan, xp.nan, res) return res return __chdtrc def _betaincc(xp, spx): betainc = _get_native_func(xp, spx, 'betainc') if betainc is None: return None def __betaincc(a, b, x): # not perfect; might want to just rely on SciPy return betainc(b, a, 1-x) return __betaincc def _stdtr(xp, spx): betainc = _get_native_func(xp, spx, 'betainc') if betainc is None: return None def __stdtr(df, t): x = df / (t ** 2 + df) tail = betainc(df / 2, 0.5, x) / 2 return xp.where(t < 0, tail, 1 - tail) return __stdtr def _stdtrit(xp, spx): # Need either native stdtr or native betainc stdtr = _get_native_func(xp, spx, 'stdtr') or _stdtr(xp, spx) # If betainc is not defined, the root-finding would be done with `xp` # despite `stdtr` being evaluated with SciPy/NumPy `stdtr`. Save the # conversions: in this case, just evaluate `stdtrit` with SciPy/NumPy. if stdtr is None: return None from scipy.optimize.elementwise import bracket_root, find_root def __stdtrit(df, p): def fun(t, df, p): return stdtr(df, t) - p res_bracket = bracket_root(fun, xp.zeros_like(p), args=(df, p)) res_root = find_root(fun, res_bracket.bracket, args=(df, p)) return res_root.x return __stdtrit # Inventory of automatically dispatched functions # IMPORTANT: these must all be **elementwise** functions! # PyTorch doesn't implement `betainc`. # On torch CPU we can fall back to NumPy, but on GPU it won't work. _needs_betainc = xp_capabilities(cpu_only=True, exceptions=["jax.numpy", "cupy"]) _special_funcs = ( _FuncInfo( _ufuncs.bdtr, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(False, True, False), torch_native=False, ), _FuncInfo( _ufuncs.bdtrc, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(False, True, False), torch_native=False, ), _FuncInfo( _ufuncs.bdtri, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(False, True, False), torch_native=False, ), _FuncInfo(_ufuncs.betainc, 3, _needs_betainc, torch_native=False), _FuncInfo(_ufuncs.betaincc, 3, _needs_betainc, generic_impl=_betaincc, torch_native=False), _FuncInfo( _ufuncs.betaincinv, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), test_large_ints=False, positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.betaln, 2, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), # For betaln, nan mismatches can occur at negative integer a or b of # sufficiently large magnitude. positive_only={"jax.numpy": True}, torch_native=False, ), _FuncInfo( _ufuncs.binom, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.boxcox, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.boxcox1p, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.cbrt, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.chdtr, 2, generic_impl=_chdtr), _FuncInfo(_ufuncs.chdtrc, 2, generic_impl=_chdtrc, # scipy/scipy#20972 positive_only={"cupy": True, "jax.numpy": True, "torch": True}), _FuncInfo( _ufuncs.chdtri, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.cosdg, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), test_large_ints=False, torch_native=False, ), _FuncInfo( _ufuncs.cosm1, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.cotdg, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.ellipk, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.ellipkm1, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.entr, 1), _FuncInfo(_ufuncs.erf, 1), _FuncInfo(_ufuncs.erfc, 1), _FuncInfo( _ufuncs.erfcx, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.erfinv, 1), _FuncInfo( _ufuncs.exp1, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.exp10, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.exp2, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.exprel, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.expi, 1, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), torch_native=False, ), _FuncInfo(_ufuncs.expit, 1), _FuncInfo( _ufuncs.expn, 2, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), # Inconsistent behavior for negative n. expn is not defined here without # taking analytic continuation. positive_only=True, int_only=(True, False), test_large_ints=False, torch_native=False, ), _FuncInfo( _ufuncs.fdtr, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.fdtrc, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.fdtri, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.gamma, 1, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), torch_native=False, ), _FuncInfo(_ufuncs.gammainc, 2), _FuncInfo( _ufuncs.gammaincc, 2, # google/jax#20699 positive_only={"jax.numpy": True}, ), _FuncInfo( _ufuncs.gammainccinv, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.gammaincinv, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.gammaln, 1), _FuncInfo( _ufuncs.gammasgn, 1, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), torch_native=False, ), _FuncInfo( _ufuncs.gdtr, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.gdtrc, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.huber, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.hyp1f1, 3, xp_capabilities(cpu_only=True, exceptions=["jax.numpy"]), positive_only={"jax.numpy": True}, test_large_ints=False, torch_native=False, ), # Comment out when jax>=0.6.1 is available in Conda for CI. # (or add version requirements to xp_capabilities). # _FuncInfo( # _ufuncs.hyp2f1, 4, # xp_capabilities(cpu_only=True, exceptions=["jax.numpy"]), # positive_only={"jax.numpy": True}, test_large_ints=False, # torch_native=False, # ), _FuncInfo( _ufuncs.inv_boxcox, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _ufuncs.inv_boxcox1p, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.i0, 1), _FuncInfo(_ufuncs.i0e, 1), _FuncInfo(_ufuncs.i1, 1), _FuncInfo(_ufuncs.i1e, 1), _FuncInfo( _ufuncs.j0, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "bessel_j0"}, test_large_ints=False, ), _FuncInfo( _ufuncs.j1, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "bessel_j1"}, test_large_ints=False, ), _FuncInfo( _ufuncs.k0, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "modified_bessel_k0"}, ), _FuncInfo( _ufuncs.k0e, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "scaled_modified_bessel_k0"}, test_large_ints=False, ), _FuncInfo( _ufuncs.k1, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "modified_bessel_k1"}, ), _FuncInfo( _ufuncs.k1e, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "scaled_modified_bessel_k1"}, test_large_ints=False), _FuncInfo( _ufuncs.kl_div, 2, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), torch_native=False, ), _FuncInfo(_ufuncs.log_ndtr, 1), _FuncInfo( _ufuncs.loggamma, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.logit, 1), _FuncInfo( _ufuncs.lpmv, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, test_large_ints=False, ), _FuncInfo( _spfun_stats.multigammaln, 2, is_ufunc=False, python_int_only={ "cupy": [False, True], "jax.numpy": [False, True], "torch": [False, True], }, scalar_or_0d_only={ "array_api_strict": [False, True], "numpy": [False, True], "dask.array": [False, True], "marray": [False, True], }, int_only=(False, True), test_large_ints=False, positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.nbdtr, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(True, True, False), positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.nbdtrc, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(True, True, False), positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.nbdtri, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(True, True, False), positive_only=True, torch_native=False, ), _FuncInfo(_ufuncs.ndtr, 1), _FuncInfo(_ufuncs.ndtri, 1), _FuncInfo( _ufuncs.pdtr, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.pdtrc, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.pdtri, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), int_only=(True, False), positive_only=True, torch_native=False, ), _FuncInfo( _ufuncs.poch, 2, xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]), test_large_ints=False, torch_native=False, ), _FuncInfo( _ufuncs.pseudo_huber, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _basic.polygamma, 2, int_only=(True, False), is_ufunc=False, scalar_or_0d_only={"torch": (True, False)}, produces_0d=True, positive_only={"torch": (True, False), "jax.numpy": True}, test_large_ints=False, ), _FuncInfo(_ufuncs.psi, 1, alt_names_map={"jax.numpy": "digamma"}), _FuncInfo( _ufuncs.radian, 3, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo(_ufuncs.rel_entr, 2, generic_impl=_rel_entr), _FuncInfo( _ufuncs.rgamma, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), _FuncInfo( _basic.sinc, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), is_ufunc=False, ), _FuncInfo( _ufuncs.sindg, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), test_large_ints=False, torch_native=False, ), _FuncInfo( _ufuncs.spence, 1, xp_capabilities(cpu_only=True, exceptions=["jax.numpy"]), torch_native=False, ), _FuncInfo(_ufuncs.stdtr, 2, _needs_betainc, generic_impl=_stdtr, torch_native=False), _FuncInfo( _ufuncs.stdtrit, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], # needs betainc skip_backends=[("jax.numpy", "no scipy.optimize support")], ), generic_impl=_stdtrit, torch_native=False, ), _FuncInfo( _ufuncs.tandg, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), test_large_ints=False, torch_native=False, ), _FuncInfo(_ufuncs.xlog1py, 2), _FuncInfo(_ufuncs.xlogy, 2, generic_impl=_xlogy), _FuncInfo( _ufuncs.y0, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "bessel_y0"}, test_large_ints=False, ), _FuncInfo( _ufuncs.y1, 1, xp_capabilities( cpu_only=True, exceptions=["cupy", "torch"], jax_jit=False, ), alt_names_map={"torch": "bessel_y1"}, test_large_ints=False, ), _FuncInfo( _ufuncs.yn, 2, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), positive_only={"cupy": (True, False)}, int_only=(True, False), test_large_ints=False, torch_native=False, ), _FuncInfo( _basic.zeta, 2, is_ufunc=False, positive_only={"jax.numpy": True, "torch": (True, False)}, test_large_ints=False, ), _FuncInfo( _ufuncs.zetac, 1, xp_capabilities( cpu_only=True, exceptions=["cupy"], jax_jit=False, ), torch_native=False, ), ) # Override ufuncs. # When SCIPY_ARRAY_API is disabled, this exclusively updates the docstrings in place # and populates the xp_capabilities table, while retaining the original ufuncs. globals().update({nfo.func.__name__: nfo.wrapper for nfo in _special_funcs}) # digamma is an alias for psi. Define here so it also has alternative backend # support. Add noqa because the linter gets confused by the sneaky way psi # is inserted into globals above. digamma = psi # noqa: F821 __all__ = [nfo.func.__name__ for nfo in _special_funcs] + ["digamma"]
_FuncInfo
python
pypa__pip
src/pip/_internal/cli/command_context.py
{ "start": 176, "end": 817 }
class ____: def __init__(self) -> None: super().__init__() self._in_main_context = False self._main_context = ExitStack() @contextmanager def main_context(self) -> Generator[None, None, None]: assert not self._in_main_context self._in_main_context = True try: with self._main_context: yield finally: self._in_main_context = False def enter_context(self, context_provider: AbstractContextManager[_T]) -> _T: assert self._in_main_context return self._main_context.enter_context(context_provider)
CommandContextMixIn
python
arrow-py__arrow
tests/test_locales.py
{ "start": 126118, "end": 128185 }
class ____: def test_format_timeframe(self): assert self.locale._format_timeframe("now", 0) == "sasa hivi" assert self.locale._format_timeframe("second", 1) == "sekunde" assert self.locale._format_timeframe("seconds", 3) == "sekunde 3" assert self.locale._format_timeframe("seconds", 30) == "sekunde 30" assert self.locale._format_timeframe("minute", 1) == "dakika moja" assert self.locale._format_timeframe("minutes", 4) == "dakika 4" assert self.locale._format_timeframe("minutes", 40) == "dakika 40" assert self.locale._format_timeframe("hour", 1) == "saa moja" assert self.locale._format_timeframe("hours", 5) == "saa 5" assert self.locale._format_timeframe("hours", 23) == "saa 23" assert self.locale._format_timeframe("day", 1) == "siku moja" assert self.locale._format_timeframe("days", 6) == "siku 6" assert self.locale._format_timeframe("days", 12) == "siku 12" assert self.locale._format_timeframe("month", 1) == "mwezi moja" assert self.locale._format_timeframe("months", 7) == "miezi 7" assert self.locale._format_timeframe("week", 1) == "wiki moja" assert self.locale._format_timeframe("weeks", 2) == "wiki 2" assert self.locale._format_timeframe("months", 11) == "miezi 11" assert self.locale._format_timeframe("year", 1) == "mwaka moja" assert self.locale._format_timeframe("years", 8) == "miaka 8" assert self.locale._format_timeframe("years", 12) == "miaka 12" def test_format_relative_now(self): result = self.locale._format_relative("sasa hivi", "now", 0) assert result == "sasa hivi" def test_format_relative_past(self): result = self.locale._format_relative("saa moja", "hour", 1) assert result == "muda wa saa moja" def test_format_relative_future(self): result = self.locale._format_relative("saa moja", "hour", -1) assert result == "saa moja iliyopita" @pytest.mark.usefixtures("lang_locale")
TestSwahiliLocale
python
tensorflow__tensorflow
tensorflow/python/debug/cli/debugger_cli_common_test.py
{ "start": 41508, "end": 44586 }
class ____(test_util.TensorFlowTestCase): def setUp(self): self.menu = debugger_cli_common.Menu() self.assertEqual(0, self.menu.num_items()) self.node1 = debugger_cli_common.MenuItem("water flower", "water_flower") self.node2 = debugger_cli_common.MenuItem( "measure wavelength", "measure_wavelength") self.menu.append(self.node1) self.menu.append(self.node2) self.assertEqual(2, self.menu.num_items()) def testFormatAsSingleLineWithStrItemAttrsWorks(self): output = self.menu.format_as_single_line( prefix="Menu: ", divider=", ", enabled_item_attrs="underline") self.assertEqual(["Menu: water flower, measure wavelength, "], output.lines) self.assertEqual((6, 18, [self.node1, "underline"]), output.font_attr_segs[0][0]) self.assertEqual((20, 38, [self.node2, "underline"]), output.font_attr_segs[0][1]) self.assertEqual({}, output.annotations) def testFormatAsSingleLineWithListItemAttrsWorks(self): output = self.menu.format_as_single_line( prefix="Menu: ", divider=", ", enabled_item_attrs=["underline", "bold"]) self.assertEqual(["Menu: water flower, measure wavelength, "], output.lines) self.assertEqual((6, 18, [self.node1, "underline", "bold"]), output.font_attr_segs[0][0]) self.assertEqual((20, 38, [self.node2, "underline", "bold"]), output.font_attr_segs[0][1]) self.assertEqual({}, output.annotations) def testFormatAsSingleLineWithNoneItemAttrsWorks(self): output = self.menu.format_as_single_line(prefix="Menu: ", divider=", ") self.assertEqual(["Menu: water flower, measure wavelength, "], output.lines) self.assertEqual((6, 18, [self.node1]), output.font_attr_segs[0][0]) self.assertEqual((20, 38, [self.node2]), output.font_attr_segs[0][1]) self.assertEqual({}, output.annotations) def testInsertNode(self): self.assertEqual(["water flower", "measure wavelength"], self.menu.captions()) node2 = debugger_cli_common.MenuItem("write poem", "write_poem") self.menu.insert(1, node2) self.assertEqual(["water flower", "write poem", "measure wavelength"], self.menu.captions()) output = self.menu.format_as_single_line(prefix="Menu: ", divider=", ") self.assertEqual(["Menu: water flower, write poem, measure wavelength, "], output.lines) def testFormatAsSingleLineWithDisabledNode(self): node2 = debugger_cli_common.MenuItem( "write poem", "write_poem", enabled=False) self.menu.append(node2) output = self.menu.format_as_single_line( prefix="Menu: ", divider=", ", disabled_item_attrs="bold") self.assertEqual(["Menu: water flower, measure wavelength, write poem, "], output.lines) self.assertEqual((6, 18, [self.node1]), output.font_attr_segs[0][0]) self.assertEqual((20, 38, [self.node2]), output.font_attr_segs[0][1]) self.assertEqual((40, 50, ["bold"]), output.font_attr_segs[0][2])
MenuTest
python
python-openxml__python-docx
src/docx/oxml/text/run.py
{ "start": 7510, "end": 8052 }
class ____(BaseOxmlElement): """`<w:noBreakHyphen>` element, a hyphen ineligible for a line-wrap position. This maps to a plain-text dash ("-"). NOTE: this complex-type name does not exist in the schema, where `w:noBreakHyphen` maps to `CT_Empty`. This name was added to give it behavior distinguished from the many other elements represented in the schema by CT_Empty. """ def __str__(self) -> str: """Text equivalent of this element, a single dash character ("-").""" return "-"
CT_NoBreakHyphen
python
spack__spack
lib/spack/spack/database.py
{ "start": 72585, "end": 72710 }
class ____(SpackError): """Raised when an operation would need to lock an upstream database"""
UpstreamDatabaseLockingError
python
langchain-ai__langchain
libs/core/langchain_core/prompts/chat.py
{ "start": 22702, "end": 25566 }
class ____(BasePromptTemplate, ABC): """Base class for chat prompt templates.""" @property @override def lc_attributes(self) -> dict: return {"input_variables": self.input_variables} def format(self, **kwargs: Any) -> str: """Format the chat template into a string. Args: **kwargs: keyword arguments to use for filling in template variables in all the template messages in this chat template. Returns: formatted string. """ return self.format_prompt(**kwargs).to_string() async def aformat(self, **kwargs: Any) -> str: """Async format the chat template into a string. Args: **kwargs: keyword arguments to use for filling in template variables in all the template messages in this chat template. Returns: formatted string. """ return (await self.aformat_prompt(**kwargs)).to_string() def format_prompt(self, **kwargs: Any) -> ChatPromptValue: """Format prompt. Should return a ChatPromptValue. Args: **kwargs: Keyword arguments to use for formatting. Returns: ChatPromptValue. """ messages = self.format_messages(**kwargs) return ChatPromptValue(messages=messages) async def aformat_prompt(self, **kwargs: Any) -> ChatPromptValue: """Async format prompt. Should return a ChatPromptValue. Args: **kwargs: Keyword arguments to use for formatting. Returns: PromptValue. """ messages = await self.aformat_messages(**kwargs) return ChatPromptValue(messages=messages) @abstractmethod def format_messages(self, **kwargs: Any) -> list[BaseMessage]: """Format kwargs into a list of messages. Returns: List of messages. """ async def aformat_messages(self, **kwargs: Any) -> list[BaseMessage]: """Async format kwargs into a list of messages. Returns: List of messages. """ return self.format_messages(**kwargs) def pretty_repr( self, html: bool = False, # noqa: FBT001,FBT002 ) -> str: """Human-readable representation. Args: html: Whether to format as HTML. Returns: Human-readable representation. """ raise NotImplementedError def pretty_print(self) -> None: """Print a human-readable representation.""" print(self.pretty_repr(html=is_interactive_env())) # noqa: T201 MessageLike = BaseMessagePromptTemplate | BaseMessage | BaseChatPromptTemplate MessageLikeRepresentation = ( MessageLike | tuple[str | type, str | list[dict] | list[object]] | str | dict[str, Any] )
BaseChatPromptTemplate
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pep8_naming/ignore_names/N803.py
{ "start": 110, "end": 264 }
class ____: def method(self, _, a, badAllowed): return _, a, badAllowed def method(self, _, a, stillBad): return _, a, stillBad
Class
python
kamyu104__LeetCode-Solutions
Python/unit-conversion-i.py
{ "start": 35, "end": 645 }
class ____(object): def baseUnitConversions(self, conversions): """ :type conversions: List[List[int]] :rtype: List[int] """ MOD = 10**9+7 adj = [[] for _ in xrange(len(conversions)+1)] for u, v, w in conversions: adj[u].append((v, w)) result = [0]*len(adj) result[0] = 1 q = [0] while q: new_q = [] for u in q: for v, w in adj[u]: result[v] = (result[u]*w)%MOD new_q.append(v) q = new_q return result
Solution
python
weaviate__weaviate-python-client
weaviate/connect/v4.py
{ "start": 3013, "end": 34131 }
class ____: def __init__( self, connection_params: ConnectionParams, auth_client_secret: Optional[AuthCredentials], timeout_config: TimeoutConfig, proxies: Union[str, Proxies, None], trust_env: bool, additional_headers: Optional[Dict[str, Any]], connection_config: ConnectionConfig, embedded_db: Optional[EmbeddedV4] = None, skip_init_checks: bool = False, ): self.url = connection_params._http_url self.embedded_db = embedded_db self._api_version_path = "/v1" self.__additional_headers = {} self._auth = auth_client_secret self._client: Optional[HttpClient] = None self._connection_params = connection_params self._grpc_stub: Optional[weaviate_pb2_grpc.WeaviateStub] = None self._grpc_channel: Union[AsyncChannel, SyncChannel, None] = None self.timeout_config = timeout_config self.__connection_config = connection_config self.__trust_env = trust_env self._weaviate_version = _ServerVersion.from_string("") self._grpc_max_msg_size: Optional[int] = None self._connected = False self._skip_init_checks = skip_init_checks self._headers = {"content-type": "application/json"} self.__add_weaviate_embedding_service_header(connection_params.http.host) if additional_headers is not None: _validate_input(_ValidateArgument([dict], "additional_headers", additional_headers)) self.__additional_headers = additional_headers for key, value in additional_headers.items(): if value is None: raise WeaviateInvalidInputError( f"Value for key '{key}' in headers cannot be None." ) self._headers[key.lower()] = value self._proxies: Dict[str, str] = _get_proxies(proxies, trust_env) # auth secrets can contain more information than a header (refresh tokens and lifetime) and therefore take # precedent over headers if "authorization" in self._headers and auth_client_secret is not None: _Warnings.auth_header_and_auth_secret() self._headers.pop("authorization") # if there are API keys included add them right away to headers if auth_client_secret is not None and isinstance(auth_client_secret, AuthApiKey): self._headers["authorization"] = "Bearer " + auth_client_secret.api_key self._prepare_grpc_headers() def __add_weaviate_embedding_service_header(self, wcd_host: str) -> None: if is_weaviate_domain(wcd_host): self._headers["X-Weaviate-Cluster-URL"] = "https://" + wcd_host def set_integrations(self, integrations_config: List[_IntegrationConfig]) -> None: for integration in integrations_config: self._headers.update(integration._to_header()) self.__additional_headers.update(integration._to_header()) @overload def _make_client(self, colour: Literal["async"]) -> AsyncClient: ... @overload def _make_client(self, colour: Literal["sync"]) -> Client: ... def _make_client(self, colour: executor.Colour) -> Union[AsyncClient, Client]: if colour == "async": return AsyncClient( headers=self._headers, mounts=self._make_mounts(colour), trust_env=self.__trust_env, ) if colour == "sync": return Client( headers=self._headers, mounts=self._make_mounts(colour), trust_env=self.__trust_env, ) @overload def _make_mounts(self, colour: Literal["async"]) -> Dict[str, AsyncHTTPTransport]: ... @overload def _make_mounts(self, colour: Literal["sync"]) -> Dict[str, HTTPTransport]: ... def _make_mounts( self, colour: executor.Colour ) -> Union[Dict[str, AsyncHTTPTransport], Dict[str, HTTPTransport]]: if colour == "async": return { (f"{key}://" if key == "http" or key == "https" else key): AsyncHTTPTransport( limits=Limits( max_connections=self.__connection_config.session_pool_maxsize, max_keepalive_connections=self.__connection_config.session_pool_connections, ), proxy=Proxy(url=proxy), retries=self.__connection_config.session_pool_max_retries, trust_env=self.__trust_env, ) for key, proxy in self._proxies.items() if key != "grpc" } if colour == "sync": return { f"{key}://" if key == "http" or key == "https" else key: HTTPTransport( limits=Limits( max_connections=self.__connection_config.session_pool_maxsize, max_keepalive_connections=self.__connection_config.session_pool_connections, ), proxy=Proxy(url=proxy), retries=self.__connection_config.session_pool_max_retries, trust_env=self.__trust_env, ) for key, proxy in self._proxies.items() if key != "grpc" } def is_connected(self) -> bool: return self._connected def get_current_bearer_token(self) -> str: if "authorization" in self._headers: return self._headers["authorization"] elif isinstance(self._client, (OAuth2Client, AsyncOAuth2Client)): return f"Bearer {self._client.token['access_token']}" return "" def _prepare_grpc_headers(self) -> None: self.__metadata_list: List[Tuple[str, str]] = [] if len(self.additional_headers): for key, val in self.additional_headers.items(): if val is not None: self.__metadata_list.append((key.lower(), val)) if self._auth is not None: if "X-Weaviate-Cluster-URL" in self._headers: self.__metadata_list.append( ("x-weaviate-cluster-url", self._headers["X-Weaviate-Cluster-URL"]) ) if isinstance(self._auth, AuthApiKey): self.__metadata_list.append(("authorization", "Bearer " + self._auth.api_key)) else: self.__metadata_list.append( ("authorization", "dummy_will_be_refreshed_for_each_call") ) if len(self.__metadata_list) > 0: self.__grpc_headers: Optional[Tuple[Tuple[str, str], ...]] = tuple(self.__metadata_list) else: self.__grpc_headers = None def grpc_headers(self) -> Optional[Tuple[Tuple[str, str], ...]]: if self._auth is None or isinstance(self._auth, AuthApiKey): return self.__grpc_headers assert self.__grpc_headers is not None access_token = self.get_current_bearer_token() # auth is last entry in list, rest is static self.__metadata_list[len(self.__metadata_list) - 1] = ( "authorization", access_token, ) return tuple(self.__metadata_list) def _ping_grpc(self, colour: executor.Colour) -> Union[None, Awaitable[None]]: """Performs a grpc health check and raises WeaviateGRPCUnavailableError if not.""" assert self._grpc_channel is not None try: res = self._grpc_channel.unary_unary( "/grpc.health.v1.Health/Check", request_serializer=health_weaviate_pb2.WeaviateHealthCheckRequest.SerializeToString, response_deserializer=health_weaviate_pb2.WeaviateHealthCheckResponse.FromString, )(health_weaviate_pb2.WeaviateHealthCheckRequest(), timeout=self.timeout_config.init) if colour == "async": async def execute(): assert isinstance(res, Awaitable) try: return self.__handle_ping_response( cast(health_weaviate_pb2.WeaviateHealthCheckResponse, await res) ) except Exception as e: self.__handle_ping_exception(e) return execute() assert not isinstance(res, Awaitable) self.__handle_ping_response(cast(health_weaviate_pb2.WeaviateHealthCheckResponse, res)) return None except Exception as e: self.__handle_ping_exception(e) return None def __handle_ping_response(self, res: health_weaviate_pb2.WeaviateHealthCheckResponse) -> None: if res.status != health_weaviate_pb2.WeaviateHealthCheckResponse.SERVING: raise WeaviateGRPCUnavailableError( f"v{self.server_version}", self._connection_params._grpc_address ) return None def __handle_ping_exception(self, e: Exception) -> None: raise WeaviateGRPCUnavailableError( f"v{self.server_version}", self._connection_params._grpc_address ) from e @property def grpc_stub(self) -> Optional[weaviate_pb2_grpc.WeaviateStub]: if not self.is_connected(): raise WeaviateClosedClientError() return self._grpc_stub def __del__(self) -> None: if self._client is not None or self._grpc_channel is not None: _Warnings.unclosed_connection() @property def server_version(self) -> str: """Version of the weaviate instance.""" return str(self._weaviate_version) def get_proxies(self) -> Dict[str, str]: return self._proxies @property def additional_headers(self) -> Dict[str, str]: return self.__additional_headers def __make_clients(self, colour: Literal["async", "sync"]) -> None: self._client = self._make_client(colour) def open_connection_grpc(self, colour: executor.Colour) -> None: channel = self._connection_params._grpc_channel( proxies=self._proxies, grpc_msg_size=self._grpc_max_msg_size, is_async=colour == "async", ) self._grpc_channel = channel assert self._grpc_channel is not None self._grpc_stub = weaviate_pb2_grpc.WeaviateStub(self._grpc_channel) def _open_connections_rest( self, auth_client_secret: Optional[AuthCredentials], colour: executor.Colour ) -> Union[None, Awaitable[None]]: # API keys are separate from OIDC and do not need any config from weaviate if auth_client_secret is not None and isinstance(auth_client_secret, AuthApiKey): self.__make_clients(colour) return executor.empty(colour) if "authorization" in self._headers and auth_client_secret is None: self.__make_clients(colour) return executor.empty(colour) # no need to check OIDC if no auth is provided and users dont want any checks at initialization time if self._skip_init_checks and auth_client_secret is None: self.__make_clients(colour) return executor.empty(colour) oidc_url = self.url + self._api_version_path + "/.well-known/openid-configuration" if colour == "async": async def get_oidc() -> None: async with self._make_client("async") as client: try: response = await client.get(oidc_url) except Exception as e: raise WeaviateConnectionError( f"Error: {e}. \nIs Weaviate running and reachable at {self.url}?" ) res = self.__process_oidc_response(response, auth_client_secret, oidc_url, colour) if isinstance(res, Awaitable): return await res else: return res return get_oidc() with self._make_client("sync") as client: try: response = client.get(oidc_url) except Exception as e: raise WeaviateConnectionError( f"Error: {e}. \nIs Weaviate running and reachable at {self.url}?" ) res = self.__process_oidc_response(response, auth_client_secret, oidc_url, colour) assert not isinstance(res, Awaitable) return res def __process_oidc_response( self, response: Response, auth_client_secret: Optional[AuthCredentials], oidc_url: str, colour: executor.Colour, ) -> Union[None, Awaitable[None]]: if response.status_code == 200: # Some setups are behind proxies that return some default page - for example a login - for all requests. # If the response is not json, we assume that this is the case and try unauthenticated access. Any auth # header provided by the user is unaffected. try: resp = response.json() except Exception: _Warnings.auth_cannot_parse_oidc_config(oidc_url) self.__make_clients(colour) return executor.empty(colour) if auth_client_secret is not None: if colour == "async": async def execute() -> None: _auth = await executor.aresult( _Auth.use( oidc_config=resp, credentials=auth_client_secret, make_mounts=lambda: self._make_mounts("async"), colour=colour, ) ) try: self._client = await _auth.aresult(_auth.get_auth_session()) except HTTPError as e: raise AuthenticationFailedError( f"Failed to authenticate with OIDC: {repr(e)}" ) if isinstance(auth_client_secret, AuthClientCredentials): # credentials should only be saved for client credentials, otherwise use refresh token self._create_background_token_refresh(_auth) else: self._create_background_token_refresh() return execute() else: _auth = executor.result( _Auth.use( oidc_config=resp, credentials=auth_client_secret, make_mounts=lambda: self._make_mounts("sync"), colour=colour, ) ) try: self._client = _auth.result(_auth.get_auth_session()) except HTTPError as e: raise AuthenticationFailedError( f"Failed to authenticate with OIDC: {repr(e)}" ) if isinstance(auth_client_secret, AuthClientCredentials): # credentials should only be saved for client credentials, otherwise use refresh token self._create_background_token_refresh(_auth) else: self._create_background_token_refresh() else: msg = f""""No login credentials provided. The weaviate instance at {self.url} requires login credentials. Please check our documentation at https://weaviate.io/developers/weaviate/client-libraries/python#authentication for more information about how to use authentication.""" if is_weaviate_domain(self.url): msg += """ You can instantiate the client with login credentials for Weaviate Cloud using client = weaviate.connect_to_weaviate_cloud( url=YOUR_WEAVIATE_URL, auth_client_secret=wvc.init.Auth.api_key("YOUR_API_KEY") ) """ raise AuthenticationFailedError(msg) elif response.status_code == 404 and auth_client_secret is not None: _Warnings.auth_with_anon_weaviate() self.__make_clients(colour) else: self.__make_clients(colour) return executor.empty(colour) def _create_background_token_refresh(self, _auth: Optional[_Auth] = None) -> None: """Create a background thread that periodically refreshes access and refresh tokens. While the underlying library refreshes tokens, it does not have an internal cronjob that checks every X-seconds if a token has expired. If there is no activity for longer than the refresh tokens lifetime, it will expire. Therefore, refresh manually shortly before expiration time is up. """ assert isinstance(self._client, (OAuth2Client, AsyncOAuth2Client)) if "refresh_token" not in self._client.token and _auth is None: return # make an event loop sidecar thread for running async token refreshing event_loop = ( _EventLoopSingleton.get_instance() if isinstance(self._client, AsyncOAuth2Client) else None ) expires_in: int = self._client.token.get( "expires_in", 60 ) # use 1minute as token lifetime if not supplied self._shutdown_background_event = Event() def refresh_token() -> None: if isinstance(self._client, AsyncOAuth2Client): assert event_loop is not None self._client.token = event_loop.run_until_complete( self._client.refresh_token, url=self._client.metadata["token_endpoint"], ) elif isinstance(self._client, OAuth2Client): self._client.token = self._client.refresh_token( url=self._client.metadata["token_endpoint"] ) def refresh_session() -> None: assert _auth is not None if isinstance(self._client, AsyncOAuth2Client): assert event_loop is not None new_session = event_loop.run_until_complete( _auth.aresult, result=_auth.get_auth_session() ) self._client.token = event_loop.run_until_complete(new_session.fetch_token) elif isinstance(self._client, OAuth2Client): new_session = _auth.result(_auth.get_auth_session()) self._client.token = new_session.fetch_token() def update_refresh_time() -> int: assert isinstance(self._client, (OAuth2Client, AsyncOAuth2Client)) return self._client.token.get("expires_in", 60) - 30 def periodic_refresh_token(refresh_time: int, _auth: Optional[_Auth]) -> None: while ( self._shutdown_background_event is not None and not self._shutdown_background_event.is_set() ): # use refresh token when available time.sleep(max(refresh_time, 1)) try: if self._client is None: continue elif ( isinstance(self._client, (OAuth2Client, AsyncOAuth2Client)) and "refresh_token" in self._client.token ): refresh_token() else: # client credentials usually does not contain a refresh token => get a new token using the # saved credentials refresh_session() refresh_time = update_refresh_time() except HTTPError as exc: # retry again after one second, might be an unstable connection refresh_time = 1 _Warnings.token_refresh_failed(exc) demon = Thread( target=periodic_refresh_token, args=(expires_in, _auth), daemon=True, name="TokenRefresh", ) demon.start() def __get_latest_headers(self) -> Dict[str, str]: if "authorization" in self._headers: return self._headers auth_token = self.get_current_bearer_token() if auth_token == "": return self._headers # bearer token can change over time (OIDC) so we need to get the current one for each request copied_headers = copy(self._headers) copied_headers.update({"authorization": self.get_current_bearer_token()}) return copied_headers def __get_timeout( self, method: Literal["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"], is_gql_query: bool, ) -> Timeout: """Get the timeout for the request. In this way, the client waits the `httpx` default of 5s when connecting to a socket (connect), writing chunks (write), and acquiring a connection from the pool (pool), but a custom amount as specified for reading the response (read). From the PoV of the user, a request is considered to be timed out if no response is received within the specified time. They specify the times depending on how they expect Weaviate to behave. For example, a query might take longer than an insert or vice versa but, in either case, the user only cares about how long it takes for a response to be received. https://www.python-httpx.org/advanced/timeouts/ """ timeout = None if method == "DELETE" or method == "PATCH" or method == "PUT": timeout = self.timeout_config.insert elif method == "GET" or method == "HEAD": timeout = self.timeout_config.query elif method == "POST" and is_gql_query: timeout = self.timeout_config.query elif method == "POST" and not is_gql_query: timeout = self.timeout_config.insert return Timeout( timeout=5.0, read=timeout, pool=self.__connection_config.session_pool_timeout, ) def __handle_exceptions(self, e: Exception, error_msg: str) -> None: if isinstance(e, RuntimeError): raise WeaviateClosedClientError() from e if isinstance(e, ConnectError): raise WeaviateConnectionError(error_msg) from e if isinstance(e, ReadTimeout): raise WeaviateTimeoutError(error_msg) from e raise e def __handle_response( self, response: Response, error_msg: str, status_codes: Optional[_ExpectedStatusCodes], ) -> Response: if response.status_code == 403: raise InsufficientPermissionsError(response) if status_codes is not None and response.status_code not in status_codes.ok: raise UnexpectedStatusCodeError(error_msg, response) return response def _send( self, method: Literal["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"], *, url: str, error_msg: str, status_codes: Optional[_ExpectedStatusCodes], is_gql_query: bool = False, weaviate_object: Optional[JSONPayload] = None, params: Optional[Dict[str, Any]] = None, check_is_connected: bool = True, ) -> executor.Result[Response]: if check_is_connected and not self.is_connected(): raise WeaviateClosedClientError() if self.embedded_db is not None: self.embedded_db.ensure_running() assert self._client is not None request = self._client.build_request( method, url, json=weaviate_object, params=params, headers=self.__get_latest_headers(), timeout=self.__get_timeout(method, is_gql_query), ) def resp(res: Response) -> Response: return self.__handle_response(res, error_msg, status_codes) def exc(e: Exception) -> None: self.__handle_exceptions(e, error_msg) return executor.execute( response_callback=resp, exception_callback=exc, method=self._client.send, request=request, ) def close(self, colour: executor.Colour) -> executor.Result[None]: if self.embedded_db is not None: self.embedded_db.stop() if colour == "async": async def execute() -> None: if self._client is not None: assert isinstance(self._client, AsyncClient) await self._client.aclose() self._client = None if self._grpc_stub is not None: assert self._grpc_channel is not None assert isinstance(self._grpc_channel, AsyncChannel) await self._grpc_channel.close() self._grpc_stub = None self._grpc_channel = None self._connected = False return execute() if self._client is not None: assert isinstance(self._client, Client) self._client.close() self._client = None if self._grpc_stub is not None: assert self._grpc_channel is not None assert isinstance(self._grpc_channel, SyncChannel) self._grpc_channel.close() self._grpc_stub = None self._grpc_channel = None self._connected = False def _check_package_version(self, colour: executor.Colour) -> executor.Result[None]: def resp(res: Response) -> None: pkg_info: dict = res.json().get("info", {}) latest_version = pkg_info.get("version", "unknown version") if is_weaviate_client_too_old(client_version, latest_version): _Warnings.weaviate_client_too_old_vs_latest(client_version, latest_version) try: if colour == "async": async def _execute() -> None: async with AsyncClient() as client: res = await client.get(PYPI_PACKAGE_URL, timeout=self.timeout_config.init) return resp(res) return _execute() with Client() as client: res = client.get(PYPI_PACKAGE_URL, timeout=self.timeout_config.init) return resp(res) except RequestError: pass # ignore any errors related to requests, it is a best-effort warning def delete( self, path: str, weaviate_object: Optional[JSONPayload] = None, params: Optional[Dict[str, Any]] = None, error_msg: str = "", status_codes: Optional[_ExpectedStatusCodes] = None, ) -> executor.Result[Response]: return self._send( "DELETE", url=self.url + self._api_version_path + path, weaviate_object=weaviate_object, params=params, error_msg=error_msg, status_codes=status_codes, ) def patch( self, path: str, weaviate_object: JSONPayload, params: Optional[Dict[str, Any]] = None, error_msg: str = "", status_codes: Optional[_ExpectedStatusCodes] = None, ) -> executor.Result[Response]: return self._send( "PATCH", url=self.url + self._api_version_path + path, weaviate_object=weaviate_object, params=params, error_msg=error_msg, status_codes=status_codes, ) def post( self, path: str, weaviate_object: JSONPayload, params: Optional[Dict[str, Any]] = None, error_msg: str = "", status_codes: Optional[_ExpectedStatusCodes] = None, is_gql_query: bool = False, ) -> executor.Result[Response]: return self._send( "POST", url=self.url + self._api_version_path + path, weaviate_object=weaviate_object, params=params, error_msg=error_msg, status_codes=status_codes, is_gql_query=is_gql_query, ) def put( self, path: str, weaviate_object: JSONPayload, params: Optional[Dict[str, Any]] = None, error_msg: str = "", status_codes: Optional[_ExpectedStatusCodes] = None, ) -> executor.Result[Response]: return self._send( "PUT", url=self.url + self._api_version_path + path, weaviate_object=weaviate_object, params=params, error_msg=error_msg, status_codes=status_codes, ) def get( self, path: str, params: Optional[Dict[str, Any]] = None, error_msg: str = "", status_codes: Optional[_ExpectedStatusCodes] = None, check_is_connected: bool = True, ) -> executor.Result[Response]: return self._send( "GET", url=self.url + self._api_version_path + path, params=params, error_msg=error_msg, status_codes=status_codes, check_is_connected=check_is_connected, ) def head( self, path: str, params: Optional[Dict[str, Any]] = None, error_msg: str = "", status_codes: Optional[_ExpectedStatusCodes] = None, ) -> executor.Result[Response]: return self._send( "HEAD", url=self.url + self._api_version_path + path, params=params, error_msg=error_msg, status_codes=status_codes, ) def get_meta(self, check_is_connected: bool = True) -> executor.Result[Dict[str, str]]: def resp(res: Response) -> Dict[str, str]: data = _decode_json_response_dict(res, "Meta endpoint") assert data is not None return data return executor.execute( response_callback=resp, method=self.get, path="/meta", check_is_connected=check_is_connected, ) def get_open_id_configuration(self) -> executor.Result[Optional[Dict[str, Any]]]: def resp(res: Response) -> Optional[Dict[str, Any]]: if res.status_code == 200: return _decode_json_response_dict(res, "OpenID Configuration") if res.status_code == 404: return None raise UnexpectedStatusCodeError("Meta endpoint", res) return executor.execute( response_callback=resp, method=self.get, path="/.well-known/openid-configuration", )
_ConnectionBase
python
kamyu104__LeetCode-Solutions
Python/maximum-profit-in-job-scheduling.py
{ "start": 66, "end": 614 }
class ____(object): def jobScheduling(self, startTime, endTime, profit): """ :type startTime: List[int] :type endTime: List[int] :type profit: List[int] :rtype: int """ jobs = sorted(itertools.izip(endTime, startTime, profit)) dp = [(0, 0)] for e, s, p in jobs: i = bisect.bisect_right(dp, (s+1, 0))-1 if dp[i][1]+p > dp[-1][1]: dp.append((e, dp[i][1]+p)) return dp[-1][1] # Time: O(nlogn) # Space: O(n) import heapq
Solution
python
google__flatbuffers
tests/py_flexbuffers_test.py
{ "start": 3546, "end": 8749 }
class ____(unittest.TestCase): """Tests to check FlexBuffer utility functions.""" def _test_type_predicate(self, pred, types): for type_ in types: with self.subTest(type=type_, pred=pred): self.assertTrue(pred(type_)) for type_ in set(Type).difference(types): with self.subTest(type=type_, pred=pred): self.assertFalse(pred(type_)) def test_inline_types(self): self._test_type_predicate( Type.IsInline, (Type.NULL, Type.INT, Type.UINT, Type.FLOAT, Type.BOOL) ) def test_typed_vector(self): self._test_type_predicate( Type.IsTypedVector, ( Type.VECTOR_INT, Type.VECTOR_UINT, Type.VECTOR_FLOAT, Type.VECTOR_KEY, Type.VECTOR_STRING_DEPRECATED, Type.VECTOR_BOOL, ), ) self._test_type_predicate( Type.IsTypedVectorElementType, (Type.INT, Type.UINT, Type.FLOAT, Type.KEY, Type.STRING, Type.BOOL), ) with self.assertRaises(ValueError): Type.ToTypedVectorElementType(Type.VECTOR) self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_INT), Type.INT) self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_UINT), Type.UINT) self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_FLOAT), Type.FLOAT) self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_KEY), Type.KEY) self.assertIs( Type.ToTypedVectorElementType(Type.VECTOR_STRING_DEPRECATED), Type.STRING, ) self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_BOOL), Type.BOOL) with self.assertRaises(ValueError): Type.ToTypedVector(Type.VECTOR) self.assertIs(Type.ToTypedVector(Type.INT), Type.VECTOR_INT) self.assertIs(Type.ToTypedVector(Type.UINT), Type.VECTOR_UINT) self.assertIs(Type.ToTypedVector(Type.FLOAT), Type.VECTOR_FLOAT) self.assertIs(Type.ToTypedVector(Type.KEY), Type.VECTOR_KEY) self.assertIs( Type.ToTypedVector(Type.STRING), Type.VECTOR_STRING_DEPRECATED ) self.assertIs(Type.ToTypedVector(Type.BOOL), Type.VECTOR_BOOL) def test_fixed_typed_vector(self): self._test_type_predicate( Type.IsFixedTypedVector, ( Type.VECTOR_INT2, Type.VECTOR_UINT2, Type.VECTOR_FLOAT2, Type.VECTOR_INT3, Type.VECTOR_UINT3, Type.VECTOR_FLOAT3, Type.VECTOR_INT4, Type.VECTOR_UINT4, Type.VECTOR_FLOAT4, ), ) self._test_type_predicate( Type.IsFixedTypedVectorElementType, (Type.INT, Type.UINT, Type.FLOAT) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_INT2), (Type.INT, 2) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_UINT2), (Type.UINT, 2) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_FLOAT2), (Type.FLOAT, 2) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_INT3), (Type.INT, 3) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_UINT3), (Type.UINT, 3) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_FLOAT3), (Type.FLOAT, 3) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_INT4), (Type.INT, 4) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_UINT4), (Type.UINT, 4) ) self.assertEqual( Type.ToFixedTypedVectorElementType(Type.VECTOR_FLOAT4), (Type.FLOAT, 4) ) # Invalid size for type_ in Type.INT, Type.UINT, Type.FLOAT: with self.assertRaises(ValueError): Type.ToTypedVector(type_, 1) with self.assertRaises(ValueError): Type.ToTypedVector(type_, 5) # Invalid element type for length in 1, 2, 3, 4, 5: with self.assertRaises(ValueError): Type.ToTypedVector(Type.STRING, length) self.assertIs(Type.ToTypedVector(Type.INT, 2), Type.VECTOR_INT2) self.assertIs(Type.ToTypedVector(Type.INT, 3), Type.VECTOR_INT3) self.assertIs(Type.ToTypedVector(Type.INT, 4), Type.VECTOR_INT4) self.assertIs(Type.ToTypedVector(Type.UINT, 2), Type.VECTOR_UINT2) self.assertIs(Type.ToTypedVector(Type.UINT, 3), Type.VECTOR_UINT3) self.assertIs(Type.ToTypedVector(Type.UINT, 4), Type.VECTOR_UINT4) self.assertIs(Type.ToTypedVector(Type.FLOAT, 2), Type.VECTOR_FLOAT2) self.assertIs(Type.ToTypedVector(Type.FLOAT, 3), Type.VECTOR_FLOAT3) self.assertIs(Type.ToTypedVector(Type.FLOAT, 4), Type.VECTOR_FLOAT4) def test_width(self): for x in range(1 << 10): self.assertEqual(flexbuffers.BitWidth.U(x), LOG2[uint_size(x)]) for x in range(-(1 << 10), 1 << 10): self.assertEqual(flexbuffers.BitWidth.I(x), LOG2[int_size(x)]) def test_padding(self): self.assertEqual(flexbuffers._PaddingBytes(0, 4), 0) self.assertEqual(flexbuffers._PaddingBytes(0, 8), 0) self.assertEqual(flexbuffers._PaddingBytes(0, 16), 0) self.assertEqual(flexbuffers._PaddingBytes(1, 8), 7) self.assertEqual(flexbuffers._PaddingBytes(17, 8), 7) self.assertEqual(flexbuffers._PaddingBytes(42, 2), 0)
UtilTest
python
pypa__warehouse
tests/unit/admin/views/test_projects.py
{ "start": 18853, "end": 22072 }
class ____: def test_add_observation(self, db_request): project = ProjectFactory.create() observer = ObserverFactory.create() user = UserFactory.create(observer=observer) db_request.route_path = pretend.call_recorder( lambda *a, **kw: "/admin/projects/" ) db_request.matchdict["project_name"] = project.normalized_name db_request.POST["kind"] = ObservationKind.IsSpam.value[0] db_request.POST["summary"] = "This is a summary" db_request.user = user views.add_project_observation(project, db_request) assert len(project.observations) == 1 def test_no_user_observer(self, db_request): project = ProjectFactory.create() user = UserFactory.create() db_request.route_path = pretend.call_recorder( lambda *a, **kw: "/admin/projects/" ) db_request.matchdict["project_name"] = project.normalized_name db_request.POST["kind"] = ObservationKind.IsSpam.value[0] db_request.POST["summary"] = "This is a summary" db_request.user = user views.add_project_observation(project, db_request) assert len(project.observations) == 1 def test_no_kind_errors(self): project = pretend.stub(name="foo", normalized_name="foo") request = pretend.stub( POST={}, session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)), route_path=lambda *a, **kw: "/foo/bar/", ) with pytest.raises(HTTPSeeOther) as exc: views.add_project_observation(project, request) assert exc.value.status_code == 303 assert exc.value.headers["Location"] == "/foo/bar/" assert request.session.flash.calls == [ pretend.call("Provide a kind", queue="error") ] def test_invalid_kind_errors(self): project = pretend.stub(name="foo", normalized_name="foo") request = pretend.stub( POST={"kind": "not a valid kind"}, session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)), route_path=lambda *a, **kw: "/foo/bar/", ) with pytest.raises(HTTPSeeOther) as exc: views.add_project_observation(project, request) assert exc.value.status_code == 303 assert exc.value.headers["Location"] == "/foo/bar/" assert request.session.flash.calls == [ pretend.call("Invalid kind", queue="error") ] def test_no_summary_errors(self): project = pretend.stub(name="foo", normalized_name="foo") request = pretend.stub( POST={"kind": ObservationKind.IsSpam.value[0]}, session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)), route_path=lambda *a, **kw: "/foo/bar/", ) with pytest.raises(HTTPSeeOther) as exc: views.add_project_observation(project, request) assert exc.value.status_code == 303 assert exc.value.headers["Location"] == "/foo/bar/" assert request.session.flash.calls == [ pretend.call("Provide a summary", queue="error") ]
TestProjectAddObservation