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
django-haystack__django-haystack
test_haystack/core/models.py
{ "start": 1492, "end": 1690 }
class ____(models.Manager): def get_queryset(self): return super().get_queryset().filter(deleted=False) def complete_set(self): return super().get_queryset()
SoftDeleteManager
python
huggingface__transformers
src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py
{ "start": 11233, "end": 11766 }
class ____(nn.Module): def __init__(self, config: ASTConfig): super().__init__() self.config = config self.layer = nn.ModuleList([ASTLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward(self, hidden_states: torch.Tensor) -> BaseModelOutput: for i, layer_module in enumerate(self.layer): hidden_states = layer_module(hidden_states) return BaseModelOutput(last_hidden_state=hidden_states) @auto_docstring
ASTEncoder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_product_search_query_performance_report.py
{ "start": 1861, "end": 9392 }
class ____(TestBaseProductSearchQueryPerformanceReport): stream_name = "product_search_query_performance_report_daily" report_file = "product_search_query_performance_report_daily" records_number = 8 state_file = "product_search_query_performance_report_daily_state" incremental_report_file = "product_search_query_performance_report_daily_incremental" incremental_report_file_with_records_further_cursor = ( "product_search_query_performance_report_daily_incremental_with_records_further_cursor" ) report_file_with_records_further_start_date = "product_search_query_performance_report_daily_with_records_further_start_date" state_file = "product_search_query_performance_report_state" state_file_legacy = "product_search_query_performance_report_state" def mock_report_apis(self): super().mock_report_apis() self.mock_generate_report_api( endpoint="Submit", response_template="generate_report", body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "ProductSearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "ProductSearchQueryPerformanceReportRequest", "Aggregation": "Daily", "Columns": ["TimePeriod", "AccountId", "AccountNumber", "AccountName", "AdId", "AdGroupId", "AdGroupName", "CampaignId", "CampaignName", "DestinationUrl", "DeviceType", "DeviceOS", "Language", "SearchQuery", "Network", "MerchantProductId", "Title", "ClickTypeId", "TotalClicksOnAdElements", "ClickType", "AdGroupCriterionId", "ProductGroup", "PartitionType", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "Conversions", "ConversionRate", "Assists", "CostPerAssist", "Revenue", "CostPerConversion", "RevenuePerConversion", "RevenuePerAssist", "CustomerId", "CustomerName", "AssistedImpressions", "AssistedClicks", "AssistedConversions", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AssistedConversionsQualified", "AllConversionsQualified", "CampaignType", "AssetGroupId", "AssetGroupName"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2024}, "CustomDateRangeEnd": {"Day": 6, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}', ) self.mock_generate_report_api( endpoint="Submit", response_template="generate_report", body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "ProductSearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "ProductSearchQueryPerformanceReportRequest", "Aggregation": "Daily", "Columns": ["TimePeriod", "AccountId", "AccountNumber", "AccountName", "AdId", "AdGroupId", "AdGroupName", "CampaignId", "CampaignName", "DestinationUrl", "DeviceType", "DeviceOS", "Language", "SearchQuery", "Network", "MerchantProductId", "Title", "ClickTypeId", "TotalClicksOnAdElements", "ClickType", "AdGroupCriterionId", "ProductGroup", "PartitionType", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "Conversions", "ConversionRate", "Assists", "CostPerAssist", "Revenue", "CostPerConversion", "RevenuePerConversion", "RevenuePerAssist", "CustomerId", "CustomerName", "AssistedImpressions", "AssistedClicks", "AssistedConversions", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AssistedConversionsQualified", "AllConversionsQualified", "CampaignType", "AssetGroupId", "AssetGroupName"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2024}, "CustomDateRangeEnd": {"Day": 8, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}', ) self.mock_generate_report_api( endpoint="Submit", response_template="generate_report", body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "ProductSearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "ProductSearchQueryPerformanceReportRequest", "Aggregation": "Daily", "Columns": ["TimePeriod", "AccountId", "AccountNumber", "AccountName", "AdId", "AdGroupId", "AdGroupName", "CampaignId", "CampaignName", "DestinationUrl", "DeviceType", "DeviceOS", "Language", "SearchQuery", "Network", "MerchantProductId", "Title", "ClickTypeId", "TotalClicksOnAdElements", "ClickType", "AdGroupCriterionId", "ProductGroup", "PartitionType", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "Conversions", "ConversionRate", "Assists", "CostPerAssist", "Revenue", "CostPerConversion", "RevenuePerConversion", "RevenuePerAssist", "CustomerId", "CustomerName", "AssistedImpressions", "AssistedClicks", "AssistedConversions", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AssistedConversionsQualified", "AllConversionsQualified", "CampaignType", "AssetGroupId", "AssetGroupName"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 1, "Month": 1, "Year": 2023}, "CustomDateRangeEnd": {"Day": 6, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}', ) self.mock_generate_report_api( endpoint="Submit", response_template="generate_report", body=b'{"ReportRequest": {"ExcludeColumnHeaders": false, "ExcludeReportFooter": true, "ExcludeReportHeader": true, "Format": "Csv", "FormatVersion": "2.0", "ReportName": "ProductSearchQueryPerformanceReport", "ReturnOnlyCompleteData": false, "Type": "ProductSearchQueryPerformanceReportRequest", "Aggregation": "Daily", "Columns": ["TimePeriod", "AccountId", "AccountNumber", "AccountName", "AdId", "AdGroupId", "AdGroupName", "CampaignId", "CampaignName", "DestinationUrl", "DeviceType", "DeviceOS", "Language", "SearchQuery", "Network", "MerchantProductId", "Title", "ClickTypeId", "TotalClicksOnAdElements", "ClickType", "AdGroupCriterionId", "ProductGroup", "PartitionType", "Impressions", "Clicks", "Ctr", "AverageCpc", "Spend", "Conversions", "ConversionRate", "Assists", "CostPerAssist", "Revenue", "CostPerConversion", "RevenuePerConversion", "RevenuePerAssist", "CustomerId", "CustomerName", "AssistedImpressions", "AssistedClicks", "AssistedConversions", "AllConversions", "AllRevenue", "AllConversionRate", "AllCostPerConversion", "AllRevenuePerConversion", "Goal", "GoalType", "AbsoluteTopImpressionRatePercent", "AverageCpm", "ConversionsQualified", "AssistedConversionsQualified", "AllConversionsQualified", "CampaignType", "AssetGroupId", "AssetGroupName"], "Scope": {"AccountIds": [180535609]}, "Time": {"CustomDateRangeStart": {"Day": 6, "Month": 5, "Year": 2024}, "CustomDateRangeEnd": {"Day": 8, "Month": 5, "Year": 2024}, "ReportTimeZone": "GreenwichMeanTimeDublinEdinburghLisbonLondon"}}}', )
TestProductSearchQueryPerformanceReportDailyStream
python
tiangolo__fastapi
tests/test_openapi_model_description_trim_on_formfeed.py
{ "start": 120, "end": 660 }
class ____(BaseModel): """ A model with a form feed character in the title. \f Text after form feed character. """ @app.get("/foo") def foo(v: MyModel): # pragma: no cover pass client = TestClient(app) def test_openapi(): response = client.get("/openapi.json") assert response.status_code == 200, response.text openapi_schema = response.json() assert openapi_schema["components"]["schemas"]["MyModel"]["description"] == ( "A model with a form feed character in the title.\n" )
MyModel
python
kamyu104__LeetCode-Solutions
Python/calculate-digit-sum-of-a-string.py
{ "start": 172, "end": 446 }
class ____(object): def digitSum(self, s, k): """ :type s: str :type k: int :rtype: str """ while len(s) > k: s = "".join(map(str, (sum(map(int, s[i:i+k])) for i in xrange(0, len(s), k)))) return s
Solution
python
huggingface__transformers
tests/models/lxmert/test_modeling_lxmert.py
{ "start": 1263, "end": 17947 }
class ____: def __init__( self, parent, vocab_size=300, hidden_size=28, num_attention_heads=2, num_labels=2, intermediate_size=64, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02, pad_token_id=0, num_qa_labels=30, num_object_labels=16, num_attr_labels=4, num_visual_features=10, l_layers=1, x_layers=1, r_layers=1, visual_feat_dim=128, visual_pos_dim=4, visual_loss_normalizer=6.67, seq_length=20, batch_size=4, is_training=True, task_matched=True, task_mask_lm=True, task_obj_predict=True, task_qa=True, visual_obj_loss=True, visual_attr_loss=True, visual_feat_loss=True, use_token_type_ids=True, use_lang_mask=True, output_attentions=False, output_hidden_states=False, scope=None, ): self.parent = parent self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads self.num_labels = num_labels self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range self.pad_token_id = pad_token_id self.num_qa_labels = num_qa_labels self.num_object_labels = num_object_labels self.num_attr_labels = num_attr_labels self.l_layers = l_layers self.x_layers = x_layers self.r_layers = r_layers self.visual_feat_dim = visual_feat_dim self.visual_pos_dim = visual_pos_dim self.visual_loss_normalizer = visual_loss_normalizer self.seq_length = seq_length self.batch_size = batch_size self.is_training = is_training self.use_lang_mask = use_lang_mask self.task_matched = task_matched self.task_mask_lm = task_mask_lm self.task_obj_predict = task_obj_predict self.task_qa = task_qa self.visual_obj_loss = visual_obj_loss self.visual_attr_loss = visual_attr_loss self.visual_feat_loss = visual_feat_loss self.num_visual_features = num_visual_features self.use_token_type_ids = use_token_type_ids self.output_attentions = output_attentions self.output_hidden_states = output_hidden_states self.scope = scope self.num_hidden_layers = {"vision": r_layers, "cross_encoder": x_layers, "language": l_layers} def prepare_config_and_inputs(self): output_attentions = self.output_attentions input_ids = ids_tensor([self.batch_size, self.seq_length], vocab_size=self.vocab_size) visual_feats = torch.rand(self.batch_size, self.num_visual_features, self.visual_feat_dim, device=torch_device) bounding_boxes = torch.rand(self.batch_size, self.num_visual_features, 4, device=torch_device) input_mask = None if self.use_lang_mask: input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) obj_labels = None if self.task_obj_predict: obj_labels = {} if self.visual_attr_loss and self.task_obj_predict: obj_labels["attr"] = ( ids_tensor([self.batch_size, self.num_visual_features], self.num_attr_labels), ids_tensor([self.batch_size, self.num_visual_features], self.num_attr_labels), ) if self.visual_feat_loss and self.task_obj_predict: obj_labels["feat"] = ( ids_tensor( [self.batch_size, self.num_visual_features, self.visual_feat_dim], self.num_visual_features ), ids_tensor([self.batch_size, self.num_visual_features], self.num_visual_features), ) if self.visual_obj_loss and self.task_obj_predict: obj_labels["obj"] = ( ids_tensor([self.batch_size, self.num_visual_features], self.num_object_labels), ids_tensor([self.batch_size, self.num_visual_features], self.num_object_labels), ) ans = None if self.task_qa: ans = ids_tensor([self.batch_size], self.num_qa_labels) masked_lm_labels = None if self.task_mask_lm: masked_lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) matched_label = None if self.task_matched: matched_label = ids_tensor([self.batch_size], self.num_labels) config = self.get_config() return ( config, input_ids, visual_feats, bounding_boxes, token_type_ids, input_mask, obj_labels, masked_lm_labels, matched_label, ans, output_attentions, ) def get_config(self): return LxmertConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_attention_heads=self.num_attention_heads, num_labels=self.num_labels, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, num_qa_labels=self.num_qa_labels, num_object_labels=self.num_object_labels, num_attr_labels=self.num_attr_labels, l_layers=self.l_layers, x_layers=self.x_layers, r_layers=self.r_layers, visual_feat_dim=self.visual_feat_dim, visual_pos_dim=self.visual_pos_dim, visual_loss_normalizer=self.visual_loss_normalizer, task_matched=self.task_matched, task_mask_lm=self.task_mask_lm, task_obj_predict=self.task_obj_predict, task_qa=self.task_qa, visual_obj_loss=self.visual_obj_loss, visual_attr_loss=self.visual_attr_loss, visual_feat_loss=self.visual_feat_loss, output_attentions=self.output_attentions, output_hidden_states=self.output_hidden_states, ) def create_and_check_lxmert_model( self, config, input_ids, visual_feats, bounding_boxes, token_type_ids, input_mask, obj_labels, masked_lm_labels, matched_label, ans, output_attentions, ): model = LxmertModel(config=config) model.to(torch_device) model.eval() result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, output_attentions=output_attentions, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, output_attentions=not output_attentions, ) result = model(input_ids, visual_feats, bounding_boxes, return_dict=False) result = model(input_ids, visual_feats, bounding_boxes, return_dict=True) self.parent.assertEqual(result.language_output.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual( result.vision_output.shape, (self.batch_size, self.num_visual_features, self.hidden_size) ) self.parent.assertEqual(result.pooled_output.shape, (self.batch_size, self.hidden_size)) def create_and_check_lxmert_for_question_answering( self, config, input_ids, visual_feats, bounding_boxes, token_type_ids, input_mask, obj_labels, masked_lm_labels, matched_label, ans, output_attentions, ): model = LxmertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, labels=ans, output_attentions=output_attentions, ) result = model(input_ids, visual_feats, bounding_boxes, labels=ans) result = model( input_ids, visual_feats, bounding_boxes, labels=ans, token_type_ids=token_type_ids, attention_mask=input_mask, output_attentions=output_attentions, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, labels=ans, output_attentions=not output_attentions, ) self.parent.assertEqual(result.question_answering_score.shape, (self.batch_size, self.num_qa_labels)) def create_and_check_lxmert_for_pretraining( self, config, input_ids, visual_feats, bounding_boxes, token_type_ids, input_mask, obj_labels, masked_lm_labels, matched_label, ans, output_attentions, ): model = LxmertForPreTraining(config=config) model.to(torch_device) model.eval() result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, masked_lm_labels=masked_lm_labels, obj_labels=obj_labels, matched_label=matched_label, ans=ans, output_attentions=output_attentions, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, masked_lm_labels=masked_lm_labels, output_attentions=not output_attentions, return_dict=False, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, masked_lm_labels=masked_lm_labels, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, obj_labels=obj_labels, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, matched_label=matched_label, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, ans=ans, ) result = model( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, masked_lm_labels=masked_lm_labels, obj_labels=obj_labels, matched_label=matched_label, ans=ans, output_attentions=not output_attentions, ) self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def resize_lxmert_num_qa_labels( self, config, input_ids, visual_feats, bounding_boxes, token_type_ids, input_mask, obj_labels, masked_lm_labels, matched_label, ans, output_attentions, ): start_labels = config.num_qa_labels num_large_labels = config.num_qa_labels * 2 num_small_labels = int(config.num_qa_labels * 2) less_labels_ans = ids_tensor([self.batch_size], num_small_labels) more_labels_ans = ids_tensor([self.batch_size], num_large_labels) model_pretrain = LxmertForPreTraining(config=config).to(torch_device) model_qa = LxmertForQuestionAnswering(config=config).to(torch_device) config.num_labels = num_small_labels end_labels = config.num_labels result_pretrain = model_pretrain( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, ans=ans, ) result_qa = model_qa( input_ids, visual_feats, bounding_boxes, labels=ans, token_type_ids=token_type_ids, attention_mask=input_mask, ) model_pretrain.resize_num_qa_labels(num_small_labels) model_qa.resize_num_qa_labels(num_small_labels) result_pretrain_less = model_pretrain( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, ans=less_labels_ans, ) result_qa_less = model_qa( input_ids, visual_feats, bounding_boxes, labels=less_labels_ans, token_type_ids=token_type_ids, attention_mask=input_mask, ) model_pretrain.resize_num_qa_labels(num_large_labels) model_qa.resize_num_qa_labels(num_large_labels) result_pretrain_more = model_pretrain( input_ids, visual_feats, bounding_boxes, token_type_ids=token_type_ids, attention_mask=input_mask, ans=more_labels_ans, ) result_qa_more = model_qa( input_ids, visual_feats, bounding_boxes, labels=more_labels_ans, token_type_ids=token_type_ids, attention_mask=input_mask, ) model_qa_labels = model_qa.num_qa_labels self.parent.assertNotEqual(start_labels, end_labels) self.parent.assertNotEqual(model_qa_labels, start_labels) self.parent.assertEqual(result_qa.question_answering_score.shape, (self.batch_size, start_labels)) self.parent.assertEqual(result_pretrain.question_answering_score.shape, (self.batch_size, start_labels)) self.parent.assertEqual(result_qa_less.question_answering_score.shape, (self.batch_size, num_small_labels)) self.parent.assertEqual( result_pretrain_less.question_answering_score.shape, (self.batch_size, num_small_labels) ) self.parent.assertEqual(result_qa_more.question_answering_score.shape, (self.batch_size, num_large_labels)) self.parent.assertEqual( result_pretrain_more.question_answering_score.shape, (self.batch_size, num_large_labels) ) def prepare_config_and_inputs_for_common(self, return_obj_labels=False): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, visual_feats, bounding_boxes, token_type_ids, input_mask, obj_labels, masked_lm_labels, matched_label, ans, output_attentions, ) = config_and_inputs inputs_dict = { "input_ids": input_ids, "visual_feats": visual_feats, "visual_pos": bounding_boxes, "token_type_ids": token_type_ids, "attention_mask": input_mask, } if return_obj_labels: inputs_dict["obj_labels"] = obj_labels else: config.task_obj_predict = False return config, inputs_dict @require_torch
LxmertModelTester
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 62705, "end": 63453 }
class ____(BaseModel, extra="forbid"): type: "IntegerIndexType" = Field(..., description="") lookup: Optional[bool] = Field(default=None, description="If true - support direct lookups. Default is true.") range: Optional[bool] = Field(default=None, description="If true - support ranges filters. Default is true.") is_principal: Optional[bool] = Field( default=None, description="If true - use this key to organize storage of the collection data. This option assumes that this key will be used in majority of filtered requests. Default is false.", ) on_disk: Optional[bool] = Field( default=None, description="If true, store the index on disk. Default: false. Default is false." )
IntegerIndexParams
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/sagemaker.py
{ "start": 1246, "end": 3460 }
class ____(AwsBaseSensor[SageMakerHook]): """ Contains general sensor behavior for SageMaker. Subclasses should implement get_sagemaker_response() and state_from_response() methods. Subclasses should also implement NON_TERMINAL_STATES and FAILED_STATE methods. """ aws_hook_class = SageMakerHook ui_color = "#ededed" def __init__(self, *, resource_type: str = "job", **kwargs): super().__init__(**kwargs) self.resource_type = resource_type # only used for logs, to say what kind of resource we are sensing def poke(self, context: Context): response = self.get_sagemaker_response() if response["ResponseMetadata"]["HTTPStatusCode"] != 200: self.log.info("Bad HTTP response: %s", response) return False state = self.state_from_response(response) self.log.info("%s currently %s", self.resource_type, state) if state in self.non_terminal_states(): return False if state in self.failed_states(): failed_reason = self.get_failed_reason_from_response(response) raise AirflowException( f"Sagemaker {self.resource_type} failed for the following reason: {failed_reason}" ) return True def non_terminal_states(self) -> set[str]: """Return states with should not terminate.""" raise NotImplementedError("Please implement non_terminal_states() in subclass") def failed_states(self) -> set[str]: """Return states with are considered failed.""" raise NotImplementedError("Please implement failed_states() in subclass") def get_sagemaker_response(self) -> dict: """Check status of a SageMaker task.""" raise NotImplementedError("Please implement get_sagemaker_response() in subclass") def get_failed_reason_from_response(self, response: dict) -> str: """Extract the reason for failure from an AWS response.""" return "Unknown" def state_from_response(self, response: dict) -> str: """Extract the state from an AWS response.""" raise NotImplementedError("Please implement state_from_response() in subclass")
SageMakerBaseSensor
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 186512, "end": 206280 }
class ____: @pytest.mark.parametrize( ("filename", "expected"), [ ( "crl_idp_fullname_indirect_crl.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=True, only_contains_attribute_certs=False, ), ), ( "crl_idp_fullname_only.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), ), ( "crl_idp_fullname_only_aa.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=True, ), ), ( "crl_idp_fullname_only_user.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=True, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), ), ( "crl_idp_only_ca.pem", x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA", ) ] ), only_contains_user_certs=False, only_contains_ca_certs=True, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), ), ( "crl_idp_reasons_only.pem", x509.IssuingDistributionPoint( full_name=None, relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=frozenset( [x509.ReasonFlags.key_compromise] ), indirect_crl=False, only_contains_attribute_certs=False, ), ), ( "crl_idp_relative_user_all_reasons.pem", x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA", ) ] ), only_contains_user_certs=True, only_contains_ca_certs=False, only_some_reasons=frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, x509.ReasonFlags.affiliation_changed, x509.ReasonFlags.superseded, x509.ReasonFlags.cessation_of_operation, x509.ReasonFlags.certificate_hold, x509.ReasonFlags.privilege_withdrawn, x509.ReasonFlags.aa_compromise, ] ), indirect_crl=False, only_contains_attribute_certs=False, ), ), ( "crl_idp_relativename_only.pem", x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA", ) ] ), only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), ), ], ) def test_vectors(self, filename, expected, backend): crl = _load_cert( os.path.join("x509", "custom", filename), x509.load_pem_x509_crl, ) idp = crl.extensions.get_extension_for_class( x509.IssuingDistributionPoint ).value assert idp == expected @pytest.mark.parametrize( ( "error", "only_contains_user_certs", "only_contains_ca_certs", "indirect_crl", "only_contains_attribute_certs", "only_some_reasons", "full_name", "relative_name", ), [ ( TypeError, False, False, False, False, "notafrozenset", None, None, ), ( TypeError, False, False, False, False, frozenset(["bad"]), None, None, ), ( ValueError, False, False, False, False, frozenset([x509.ReasonFlags.unspecified]), None, None, ), ( ValueError, False, False, False, False, frozenset([x509.ReasonFlags.remove_from_crl]), None, None, ), (TypeError, "notabool", False, False, False, None, None, None), (TypeError, False, "notabool", False, False, None, None, None), (TypeError, False, False, "notabool", False, None, None, None), (TypeError, False, False, False, "notabool", None, None, None), (ValueError, True, True, False, False, None, None, None), (ValueError, False, False, False, False, None, None, None), ], ) def test_invalid_init( self, error, only_contains_user_certs, only_contains_ca_certs, indirect_crl, only_contains_attribute_certs, only_some_reasons, full_name, relative_name, ): with pytest.raises(error): x509.IssuingDistributionPoint( full_name, relative_name, only_contains_user_certs, only_contains_ca_certs, only_some_reasons, indirect_crl, only_contains_attribute_certs, ) def test_repr(self): idp = x509.IssuingDistributionPoint( None, None, False, False, frozenset([x509.ReasonFlags.key_compromise]), False, False, ) assert repr(idp) == ( "<IssuingDistributionPoint(full_name=None, relative_name=None," " only_contains_user_certs=False, only_contains_ca_certs=False" ", only_some_reasons=frozenset({<ReasonFlags.key_compromise: '" "keyCompromise'>}), indirect_crl=False, only_contains_attribut" "e_certs=False)>" ) def test_eq(self): idp1 = x509.IssuingDistributionPoint( only_contains_user_certs=False, only_contains_ca_certs=False, indirect_crl=False, only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), ) idp2 = x509.IssuingDistributionPoint( only_contains_user_certs=False, only_contains_ca_certs=False, indirect_crl=False, only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), ) assert idp1 == idp2 def test_ne(self): idp1 = x509.IssuingDistributionPoint( only_contains_user_certs=False, only_contains_ca_certs=False, indirect_crl=False, only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), ) idp2 = x509.IssuingDistributionPoint( only_contains_user_certs=True, only_contains_ca_certs=False, indirect_crl=False, only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), ) assert idp1 != idp2 assert idp1 != object() def test_hash(self): idp1 = x509.IssuingDistributionPoint( None, None, True, False, None, False, False ) idp2 = x509.IssuingDistributionPoint( None, None, True, False, None, False, False ) idp3 = x509.IssuingDistributionPoint( None, x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), True, False, None, False, False, ) assert hash(idp1) == hash(idp2) assert hash(idp1) != hash(idp3) def test_hash_with_full_name(self): idp1 = x509.IssuingDistributionPoint( full_name=[x509.DNSName("example.com")], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ) idp2 = x509.IssuingDistributionPoint( full_name=[x509.DNSName("example.com")], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ) idp3 = x509.IssuingDistributionPoint( full_name=[x509.DNSName("other.com")], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ) assert hash(idp1) == hash(idp2) assert hash(idp1) != hash(idp3) @pytest.mark.parametrize( "idp", [ x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=True, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=True, ), x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( "http://myhost.com/myca.crl" ) ], relative_name=None, only_contains_user_certs=True, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), only_contains_user_certs=False, only_contains_ca_certs=True, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=None, relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=True, only_some_reasons=frozenset([x509.ReasonFlags.key_compromise]), indirect_crl=False, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ), x509.NameAttribute( oid=x509.NameOID.COMMON_NAME, value="cryptography" ), ] ), only_contains_user_certs=True, only_contains_ca_certs=False, only_some_reasons=frozenset( [ x509.ReasonFlags.key_compromise, x509.ReasonFlags.ca_compromise, x509.ReasonFlags.affiliation_changed, x509.ReasonFlags.privilege_withdrawn, x509.ReasonFlags.aa_compromise, ] ), indirect_crl=False, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA" ) ] ), only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), ], ) def test_generate(self, rsa_key_2048: rsa.RSAPrivateKey, idp, backend): key = rsa_key_2048 last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) builder = ( x509.CertificateRevocationListBuilder() .issuer_name( x509.Name( [ x509.NameAttribute( NameOID.COMMON_NAME, "cryptography.io CA" ) ] ) ) .last_update(last_update) .next_update(next_update) .add_extension(idp, True) ) crl = builder.sign(key, hashes.SHA256(), backend) ext = crl.extensions.get_extension_for_class( x509.IssuingDistributionPoint ) assert ext.critical is True assert ext.value == idp def test_public_bytes(self): ext = x509.IssuingDistributionPoint( full_name=None, relative_name=x509.RelativeDistinguishedName( [ x509.NameAttribute( oid=x509.NameOID.ORGANIZATION_NAME, value="PyCA", ) ] ), only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ) assert ( ext.public_bytes() == b"0\x11\xa0\x0f\xa1\r0\x0b\x06\x03U\x04\n\x0c\x04PyCA" )
TestIssuingDistributionPointExtension
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/__init__.py
{ "start": 25664, "end": 27899 }
class ____: """Sanity test target information.""" def __init__(self, targets: tuple[TestTarget, ...], include: tuple[TestTarget, ...]) -> None: self.targets = targets self.include = include @staticmethod def create(include: list[str], exclude: list[str], require: list[str]) -> SanityTargets: """Create a SanityTargets instance from the given include, exclude and require lists.""" _targets = SanityTargets.get_targets() _include = walk_internal_targets(_targets, include, exclude, require) return SanityTargets(_targets, _include) @staticmethod def filter_and_inject_targets(test: SanityTest, targets: c.Iterable[TestTarget]) -> list[TestTarget]: """Filter and inject targets based on test requirements and the given target list.""" test_targets = list(targets) if not test.include_symlinks: # remove all symlinks unless supported by the test test_targets = [target for target in test_targets if not target.symlink] if not test.include_directories or not test.include_symlinks: # exclude symlinked directories unless supported by the test test_targets = [target for target in test_targets if not target.path.endswith(os.path.sep)] if test.include_directories: # include directories containing any of the included files test_targets += tuple(TestTarget(path, None, None, '') for path in paths_to_dirs([target.path for target in test_targets])) if not test.include_symlinks: # remove all directory symlinks unless supported by the test test_targets = [target for target in test_targets if not target.symlink] return test_targets @staticmethod def get_targets() -> tuple[TestTarget, ...]: """Return a tuple of sanity test targets. Uses a cached version when available.""" try: return SanityTargets.get_targets.targets # type: ignore[attr-defined] except AttributeError: targets = tuple(sorted(walk_sanity_targets())) SanityTargets.get_targets.targets = targets # type: ignore[attr-defined] return targets
SanityTargets
python
joke2k__faker
tests/providers/test_currency.py
{ "start": 4904, "end": 5329 }
class ____: """Test cs_CZ currency provider""" num_samples = 100 @classmethod def setup_class(cls): from faker.providers.currency.cs_CZ import Provider as CsCzCurrencyProvider cls.provider = CsCzCurrencyProvider def test_pricetag(self, faker, num_samples): for _ in range(num_samples): pricetag = faker.pricetag() assert isinstance(pricetag, str)
TestCsCz
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/guess_the_number_game.py
{ "start": 83, "end": 3536 }
class ____(MultiAgentEnv): """ We have two players, 0 and 1. Agent 0 has to pick a number between 0, MAX-1 at reset. Agent 1 has to guess the number by asking N questions of whether of the form of "a <number> is higher|lower|equal to the picked number. The action space is MultiDiscrete [3, MAX]. For the first index 0 means lower, 1 means higher and 2 means equal. The environment answers with yes (1) or no (0) on the reward function. Every time step that agent 1 wastes agent 0 gets a reward of 1. After N steps the game is terminated. If agent 1 guesses the number correctly, it gets a reward of 100 points, otherwise it gets a reward of 0. On the other hand if agent 0 wins they win 100 points. The optimal policy controlling agent 1 should converge to a binary search strategy. """ MAX_NUMBER = 3 MAX_STEPS = 20 def __init__(self, config=None): super().__init__() self._agent_ids = {0, 1} self.max_number = config.get("max_number", self.MAX_NUMBER) self.max_steps = config.get("max_steps", self.MAX_STEPS) self._number = None self.observation_space = gym.spaces.Discrete(2) self.action_space = gym.spaces.MultiDiscrete([3, self.max_number]) def reset(self, *, seed=None, options=None): self._step = 0 self._number = None # agent 0 has to pick a number. So the returned obs does not matter. return {0: 0}, {} def step(self, action_dict): # get agent 0's action agent_0_action = action_dict.get(0) if agent_0_action is not None: # ignore the first part of the action and look at the number self._number = agent_0_action[1] # next obs should tell agent 1 to start guessing. # the returned reward and dones should be on agent 0 who picked a # number. return ( {1: 0}, {0: 0}, {0: False, "__all__": False}, {0: False, "__all__": False}, {}, ) if self._number is None: raise ValueError( "No number is selected by agent 0. Have you restarted " "the environment?" ) # get agent 1's action direction, number = action_dict.get(1) info = {} # always the same, we don't need agent 0 to act ever again, agent 1 should keep # guessing. obs = {1: 0} guessed_correctly = False terminated = {1: False, "__all__": False} truncated = {1: False, "__all__": False} # everytime agent 1 does not guess correctly agent 0 gets a reward of 1. if direction == 0: # lower reward = {1: int(number > self._number), 0: 1} elif direction == 1: # higher reward = {1: int(number < self._number), 0: 1} else: # equal guessed_correctly = number == self._number reward = {1: guessed_correctly * 100, 0: guessed_correctly * -100} terminated = {1: guessed_correctly, "__all__": guessed_correctly} self._step += 1 if self._step >= self.max_steps: # max number of steps episode is over truncated["__all__"] = True if not guessed_correctly: reward[0] = 100 # agent 0 wins return obs, reward, terminated, truncated, info
GuessTheNumberGame
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_browser.py
{ "start": 2318, "end": 20445 }
class ____: @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.BrowserSessionManager") def test_init(self, mock_browser_session_manager): tool_spec = AgentCoreBrowserToolSpec(region="us-east-1") assert tool_spec.region == "us-east-1" assert tool_spec._browser_clients == {} mock_browser_session_manager.assert_called_once_with(region="us-east-1") @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_aws_region") @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.BrowserSessionManager") def test_init_default_region( self, mock_browser_session_manager, mock_get_aws_region ): mock_get_aws_region.return_value = "us-west-2" tool_spec = AgentCoreBrowserToolSpec() assert tool_spec.region == "us-west-2" mock_get_aws_region.assert_called_once() mock_browser_session_manager.assert_called_once_with(region="us-west-2") @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.BrowserClient") def test_get_or_create_browser_client_new(self, mock_browser_client): mock_instance = MagicMock() mock_browser_client.return_value = mock_instance tool_spec = AgentCoreBrowserToolSpec(region="us-east-1") client = tool_spec._get_or_create_browser_client("test-thread") assert client == mock_instance assert "test-thread" in tool_spec._browser_clients assert tool_spec._browser_clients["test-thread"] == mock_instance mock_browser_client.assert_called_once_with("us-east-1") @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.BrowserClient") def test_get_or_create_browser_client_existing(self, mock_browser_client): mock_instance = MagicMock() tool_spec = AgentCoreBrowserToolSpec(region="us-east-1") tool_spec._browser_clients["test-thread"] = mock_instance client = tool_spec._get_or_create_browser_client("test-thread") assert client == mock_instance mock_browser_client.assert_not_called() def test_navigate_browser_invalid_url(self): tool_spec = AgentCoreBrowserToolSpec() result = tool_spec.navigate_browser( url="ftp://example.com", thread_id="test-thread" ) assert "URL scheme must be 'http' or 'https'" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_navigate_browser(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_response = MagicMock() mock_response.status = 200 mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.goto.return_value = mock_response tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.navigate_browser( url="https://example.com", thread_id="test-thread" ) mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.goto.assert_called_once_with("https://example.com") mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "Navigated to https://example.com with status code 200" in result def test_navigate_browser_exception(self): mock_session_manager = MagicMock() mock_session_manager.get_sync_browser.side_effect = Exception("Test error") tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.navigate_browser( url="https://example.com", thread_id="test-thread" ) assert "Error navigating to URL: Test error" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_click_element(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.click_element(selector="#button", thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.click.assert_called_once_with("#button", timeout=5000) mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "Clicked on element with selector '#button'" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_click_element_not_found(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.click.side_effect = Exception("Element not found") tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.click_element(selector="#button", thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.click.assert_called_once_with("#button", timeout=5000) mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "Unable to click on element with selector '#button'" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_extract_text_whole_page(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.content.return_value = "<html><body>Hello World</body></html>" tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.extract_text(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.content.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert result == "<html><body>Hello World</body></html>" @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_extract_text_with_selector(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_element = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.query_selector.return_value = mock_element mock_element.text_content.return_value = "Hello World" tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.extract_text(selector="#content", thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.query_selector.assert_called_once_with("#content") mock_element.text_content.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert result == "Hello World" @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_extract_text_selector_not_found(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.query_selector.return_value = None tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.extract_text(selector="#content", thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.query_selector.assert_called_once_with("#content") mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "No element found with selector '#content'" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_extract_hyperlinks(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.eval_on_selector_all.return_value = [ {"text": "Link 1", "href": "https://example.com/1"}, {"text": "Link 2", "href": "https://example.com/2"}, ] tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.extract_hyperlinks(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.eval_on_selector_all.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "1. Link 1: https://example.com/1" in result assert "2. Link 2: https://example.com/2" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_extract_hyperlinks_no_links(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.eval_on_selector_all.return_value = [] tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.extract_hyperlinks(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.eval_on_selector_all.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "No hyperlinks found on the page" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_get_elements(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_element1 = MagicMock() mock_element2 = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.query_selector_all.return_value = [mock_element1, mock_element2] mock_element1.evaluate.side_effect = [ "div", {"id": "div1", "class": "container"}, ] mock_element1.text_content.return_value = "Content 1" mock_element2.evaluate.side_effect = [ "div", {"id": "div2", "class": "container"}, ] mock_element2.text_content.return_value = "Content 2" tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.get_elements( selector="div.container", thread_id="test-thread" ) mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.query_selector_all.assert_called_once_with("div.container") mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "Found 2 element(s) matching selector 'div.container'" in result assert '1. <div id="div1", class="container">Content 1</div>' in result assert '2. <div id="div2", class="container">Content 2</div>' in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_get_elements_not_found(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.query_selector_all.return_value = [] tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.get_elements( selector="div.container", thread_id="test-thread" ) mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.query_selector_all.assert_called_once_with("div.container") mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "No elements found matching selector 'div.container'" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_navigate_back(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_response = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.go_back.return_value = mock_response mock_page.url = "https://example.com/previous" tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.navigate_back(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.go_back.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "Navigated back to https://example.com/previous" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_navigate_back_no_history(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.go_back.return_value = None tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.navigate_back(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.go_back.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "Could not navigate back" in result @patch("llama_index.tools.aws_bedrock_agentcore.browser.base.get_current_page") def test_current_webpage(self, mock_get_current_page): mock_session_manager = MagicMock() mock_browser = MagicMock() mock_page = MagicMock() mock_session_manager.get_sync_browser.return_value = mock_browser mock_get_current_page.return_value = mock_page mock_page.url = "https://example.com" mock_page.title.return_value = "Example Website" mock_page.evaluate.return_value = { "width": 1024, "height": 768, "links": 10, "images": 5, "forms": 2, } tool_spec = AgentCoreBrowserToolSpec() tool_spec._session_manager = mock_session_manager result = tool_spec.current_webpage(thread_id="test-thread") mock_session_manager.get_sync_browser.assert_called_once_with("test-thread") mock_get_current_page.assert_called_once_with(mock_browser) mock_page.title.assert_called_once() mock_page.evaluate.assert_called_once() mock_session_manager.release_sync_browser.assert_called_once_with("test-thread") assert "URL: https://example.com" in result assert "Title: Example Website" in result assert "Viewport size: 1024x768" in result assert "Links: 10" in result assert "Images: 5" in result assert "Forms: 2" in result def test_cleanup_thread(self): mock_browser_client = MagicMock() tool_spec = AgentCoreBrowserToolSpec() tool_spec._browser_clients = {"test-thread": mock_browser_client} # Call cleanup synchronously for testing tool_spec._browser_clients["test-thread"].stop = MagicMock() # Simulate cleanup tool_spec._browser_clients["test-thread"].stop() del tool_spec._browser_clients["test-thread"] mock_browser_client.stop.assert_called_once() assert "test-thread" not in tool_spec._browser_clients
TestAgentCoreBrowserToolSpec
python
python__mypy
mypy/plugins/default.py
{ "start": 2632, "end": 23461 }
class ____(Plugin): """Type checker plugin that is enabled by default.""" def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: if fullname == "_ctypes.Array": return array_constructor_callback elif fullname == "functools.singledispatch": return create_singledispatch_function_callback elif fullname == "functools.partial": return partial_new_callback elif fullname == "enum.member": return enum_member_callback return None def get_function_signature_hook( self, fullname: str ) -> Callable[[FunctionSigContext], FunctionLike] | None: if fullname in ("attr.evolve", "attrs.evolve", "attr.assoc", "attrs.assoc"): return evolve_function_sig_callback elif fullname in ("attr.fields", "attrs.fields"): return fields_function_sig_callback elif fullname == "dataclasses.replace": return replace_function_sig_callback return None def get_method_signature_hook( self, fullname: str ) -> Callable[[MethodSigContext], FunctionLike] | None: if fullname == "typing.Mapping.get": return typed_dict_get_signature_callback elif fullname in TD_SETDEFAULT_NAMES: return typed_dict_setdefault_signature_callback elif fullname in TD_POP_NAMES: return typed_dict_pop_signature_callback elif fullname == "_ctypes.Array.__setitem__": return array_setitem_callback elif fullname == SINGLEDISPATCH_CALLABLE_CALL_METHOD: return call_singledispatch_function_callback elif fullname in TD_UPDATE_METHOD_NAMES: return typed_dict_update_signature_callback return None def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: if fullname == "typing.Mapping.get": return typed_dict_get_callback elif fullname == "builtins.int.__pow__": return int_pow_callback elif fullname == "builtins.int.__neg__": return int_neg_callback elif fullname == "builtins.int.__pos__": return int_pos_callback elif fullname in ("builtins.tuple.__mul__", "builtins.tuple.__rmul__"): return tuple_mul_callback elif fullname in TD_SETDEFAULT_NAMES: return typed_dict_setdefault_callback elif fullname in TD_POP_NAMES: return typed_dict_pop_callback elif fullname in TD_DELITEM_NAMES: return typed_dict_delitem_callback elif fullname == "_ctypes.Array.__getitem__": return array_getitem_callback elif fullname == "_ctypes.Array.__iter__": return array_iter_callback elif fullname == SINGLEDISPATCH_REGISTER_METHOD: return singledispatch_register_callback elif fullname == SINGLEDISPATCH_REGISTER_CALLABLE_CALL_METHOD: return call_singledispatch_function_after_register_argument elif fullname == "functools.partial.__call__": return partial_call_callback return None def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: if fullname == "_ctypes.Array.value": return array_value_callback elif fullname == "_ctypes.Array.raw": return array_raw_callback elif fullname in ENUM_NAME_ACCESS: return enum_name_callback elif fullname in ENUM_VALUE_ACCESS: return enum_value_callback return None def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: # These dataclass and attrs hooks run in the main semantic analysis pass # and only tag known dataclasses/attrs classes, so that the second # hooks (in get_class_decorator_hook_2) can detect dataclasses/attrs classes # in the MRO. if fullname in dataclass_makers: return dataclass_tag_callback if ( fullname in attr_class_makers or fullname in attr_dataclass_makers or fullname in attr_frozen_makers or fullname in attr_define_makers ): return attr_tag_callback return None def get_class_decorator_hook_2( self, fullname: str ) -> Callable[[ClassDefContext], bool] | None: if fullname in dataclass_makers: return dataclass_class_maker_callback elif fullname in functools_total_ordering_makers: return functools_total_ordering_maker_callback elif fullname in attr_class_makers: return attr_class_maker_callback elif fullname in attr_dataclass_makers: return partial(attr_class_maker_callback, auto_attribs_default=True) elif fullname in attr_frozen_makers: return partial( attr_class_maker_callback, auto_attribs_default=None, frozen_default=True ) elif fullname in attr_define_makers: return partial( attr_class_maker_callback, auto_attribs_default=None, slots_default=True ) return None def typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType: """Try to infer a better signature type for TypedDict.get. This is used to get better type context for the second argument that depends on a TypedDict value type. """ signature = ctx.default_signature if ( isinstance(ctx.type, TypedDictType) and len(ctx.args) == 2 and len(ctx.args[0]) == 1 and isinstance(ctx.args[0][0], StrExpr) and len(signature.arg_types) == 2 and len(signature.variables) == 1 and len(ctx.args[1]) == 1 ): key = ctx.args[0][0].value value_type = get_proper_type(ctx.type.items.get(key)) ret_type = signature.ret_type if value_type: default_arg = ctx.args[1][0] if ( isinstance(value_type, TypedDictType) and isinstance(default_arg, DictExpr) and len(default_arg.items) == 0 ): # Caller has empty dict {} as default for typed dict. value_type = value_type.copy_modified(required_keys=set()) # Tweak the signature to include the value type as context. It's # only needed for type inference since there's a union with a type # variable that accepts everything. tv = signature.variables[0] assert isinstance(tv, TypeVarType) return signature.copy_modified( arg_types=[signature.arg_types[0], make_simplified_union([value_type, tv])], ret_type=ret_type, ) return signature def typed_dict_get_callback(ctx: MethodContext) -> Type: """Infer a precise return type for TypedDict.get with literal first argument.""" if ( isinstance(ctx.type, TypedDictType) and len(ctx.arg_types) >= 1 and len(ctx.arg_types[0]) == 1 ): keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0]) if keys is None: return ctx.default_return_type default_type: Type default_arg: Expression | None if len(ctx.arg_types) <= 1 or not ctx.arg_types[1]: default_arg = None default_type = NoneType() elif len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1: default_arg = ctx.args[1][0] default_type = ctx.arg_types[1][0] else: return ctx.default_return_type output_types: list[Type] = [] for key in keys: value_type: Type | None = ctx.type.items.get(key) if value_type is None: return ctx.default_return_type if key in ctx.type.required_keys: output_types.append(value_type) else: # HACK to deal with get(key, {}) if ( isinstance(default_arg, DictExpr) and len(default_arg.items) == 0 and isinstance(vt := get_proper_type(value_type), TypedDictType) ): output_types.append(vt.copy_modified(required_keys=set())) else: output_types.append(value_type) output_types.append(default_type) # for nicer reveal_type, put default at the end, if it is present if default_type in output_types: output_types = [t for t in output_types if t != default_type] + [default_type] return make_simplified_union(output_types) return ctx.default_return_type def typed_dict_pop_signature_callback(ctx: MethodSigContext) -> CallableType: """Try to infer a better signature type for TypedDict.pop. This is used to get better type context for the second argument that depends on a TypedDict value type. """ signature = ctx.default_signature str_type = ctx.api.named_generic_type("builtins.str", []) if ( isinstance(ctx.type, TypedDictType) and len(ctx.args) == 2 and len(ctx.args[0]) == 1 and isinstance(ctx.args[0][0], StrExpr) and len(signature.arg_types) == 2 and len(signature.variables) == 1 and len(ctx.args[1]) == 1 ): key = ctx.args[0][0].value value_type = ctx.type.items.get(key) if value_type: # Tweak the signature to include the value type as context. It's # only needed for type inference since there's a union with a type # variable that accepts everything. tv = signature.variables[0] assert isinstance(tv, TypeVarType) typ = make_simplified_union([value_type, tv]) return signature.copy_modified(arg_types=[str_type, typ], ret_type=typ) return signature.copy_modified(arg_types=[str_type, signature.arg_types[1]]) def typed_dict_pop_callback(ctx: MethodContext) -> Type: """Type check and infer a precise return type for TypedDict.pop.""" if ( isinstance(ctx.type, TypedDictType) and len(ctx.arg_types) >= 1 and len(ctx.arg_types[0]) == 1 ): key_expr = ctx.args[0][0] keys = try_getting_str_literals(key_expr, ctx.arg_types[0][0]) if keys is None: ctx.api.fail( message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL, key_expr, code=codes.LITERAL_REQ, ) return AnyType(TypeOfAny.from_error) value_types = [] for key in keys: if key in ctx.type.required_keys or key in ctx.type.readonly_keys: ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, key_expr) value_type = ctx.type.items.get(key) if value_type: value_types.append(value_type) else: ctx.api.msg.typeddict_key_not_found(ctx.type, key, key_expr) return AnyType(TypeOfAny.from_error) if len(ctx.args[1]) == 0: return make_simplified_union(value_types) elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1: return make_simplified_union([*value_types, ctx.arg_types[1][0]]) return ctx.default_return_type def typed_dict_setdefault_signature_callback(ctx: MethodSigContext) -> CallableType: """Try to infer a better signature type for TypedDict.setdefault. This is used to get better type context for the second argument that depends on a TypedDict value type. """ signature = ctx.default_signature str_type = ctx.api.named_generic_type("builtins.str", []) if ( isinstance(ctx.type, TypedDictType) and len(ctx.args) == 2 and len(ctx.args[0]) == 1 and isinstance(ctx.args[0][0], StrExpr) and len(signature.arg_types) == 2 and len(ctx.args[1]) == 1 ): key = ctx.args[0][0].value value_type = ctx.type.items.get(key) if value_type: return signature.copy_modified(arg_types=[str_type, value_type]) return signature.copy_modified(arg_types=[str_type, signature.arg_types[1]]) def typed_dict_setdefault_callback(ctx: MethodContext) -> Type: """Type check TypedDict.setdefault and infer a precise return type.""" if ( isinstance(ctx.type, TypedDictType) and len(ctx.arg_types) == 2 and len(ctx.arg_types[0]) == 1 and len(ctx.arg_types[1]) == 1 ): key_expr = ctx.args[0][0] keys = try_getting_str_literals(key_expr, ctx.arg_types[0][0]) if keys is None: ctx.api.fail( message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL, key_expr, code=codes.LITERAL_REQ, ) return AnyType(TypeOfAny.from_error) assigned_readonly_keys = ctx.type.readonly_keys & set(keys) if assigned_readonly_keys: ctx.api.msg.readonly_keys_mutated(assigned_readonly_keys, context=key_expr) default_type = ctx.arg_types[1][0] default_expr = ctx.args[1][0] value_types = [] for key in keys: value_type = ctx.type.items.get(key) if value_type is None: ctx.api.msg.typeddict_key_not_found(ctx.type, key, key_expr) return AnyType(TypeOfAny.from_error) # The signature_callback above can't always infer the right signature # (e.g. when the expression is a variable that happens to be a Literal str) # so we need to handle the check ourselves here and make sure the provided # default can be assigned to all key-value pairs we're updating. if not is_subtype(default_type, value_type): ctx.api.msg.typeddict_setdefault_arguments_inconsistent( default_type, value_type, default_expr ) return AnyType(TypeOfAny.from_error) value_types.append(value_type) return make_simplified_union(value_types) return ctx.default_return_type def typed_dict_delitem_callback(ctx: MethodContext) -> Type: """Type check TypedDict.__delitem__.""" if ( isinstance(ctx.type, TypedDictType) and len(ctx.arg_types) == 1 and len(ctx.arg_types[0]) == 1 ): key_expr = ctx.args[0][0] keys = try_getting_str_literals(key_expr, ctx.arg_types[0][0]) if keys is None: ctx.api.fail( message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL, key_expr, code=codes.LITERAL_REQ, ) return AnyType(TypeOfAny.from_error) for key in keys: if key in ctx.type.required_keys or key in ctx.type.readonly_keys: ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, key_expr) elif key not in ctx.type.items: ctx.api.msg.typeddict_key_not_found(ctx.type, key, key_expr) return ctx.default_return_type _TP_DICT_MUTATING_METHODS: Final = frozenset({"update of TypedDict", "__ior__ of TypedDict"}) def typed_dict_update_signature_callback(ctx: MethodSigContext) -> CallableType: """Try to infer a better signature type for methods that update `TypedDict`. This includes: `TypedDict.update`, `TypedDict.__or__`, `TypedDict.__ror__`, and `TypedDict.__ior__`. """ signature = ctx.default_signature if isinstance(ctx.type, TypedDictType) and len(signature.arg_types) == 1: arg_type = get_proper_type(signature.arg_types[0]) if not isinstance(arg_type, TypedDictType): return signature arg_type = arg_type.as_anonymous() arg_type = arg_type.copy_modified(required_keys=set()) if ctx.args and ctx.args[0]: if signature.name in _TP_DICT_MUTATING_METHODS: # If we want to mutate this object in place, we need to set this flag, # it will trigger an extra check in TypedDict's checker. arg_type.to_be_mutated = True with ctx.api.msg.filter_errors( filter_errors=lambda name, info: info.code != codes.TYPEDDICT_READONLY_MUTATED, save_filtered_errors=True, ): inferred = get_proper_type( ctx.api.get_expression_type(ctx.args[0][0], type_context=arg_type) ) if arg_type.to_be_mutated: arg_type.to_be_mutated = False # Done! possible_tds = [] if isinstance(inferred, TypedDictType): possible_tds = [inferred] elif isinstance(inferred, UnionType): possible_tds = [ t for t in get_proper_types(inferred.relevant_items()) if isinstance(t, TypedDictType) ] items = [] for td in possible_tds: item = arg_type.copy_modified( required_keys=(arg_type.required_keys | td.required_keys) & arg_type.items.keys() ) if not ctx.api.options.extra_checks: item = item.copy_modified(item_names=list(td.items)) items.append(item) if items: arg_type = make_simplified_union(items) return signature.copy_modified(arg_types=[arg_type]) return signature def int_pow_callback(ctx: MethodContext) -> Type: """Infer a more precise return type for int.__pow__.""" # int.__pow__ has an optional modulo argument, # so we expect 2 argument positions if len(ctx.arg_types) == 2 and len(ctx.arg_types[0]) == 1 and len(ctx.arg_types[1]) == 0: arg = ctx.args[0][0] if isinstance(arg, IntExpr): exponent = arg.value elif isinstance(arg, UnaryExpr) and arg.op == "-" and isinstance(arg.expr, IntExpr): exponent = -arg.expr.value else: # Right operand not an int literal or a negated literal -- give up. return ctx.default_return_type if exponent >= 0: return ctx.api.named_generic_type("builtins.int", []) else: return ctx.api.named_generic_type("builtins.float", []) return ctx.default_return_type def int_neg_callback(ctx: MethodContext, multiplier: int = -1) -> Type: """Infer a more precise return type for int.__neg__ and int.__pos__. This is mainly used to infer the return type as LiteralType if the original underlying object is a LiteralType object. """ if isinstance(ctx.type, Instance) and ctx.type.last_known_value is not None: value = ctx.type.last_known_value.value fallback = ctx.type.last_known_value.fallback if isinstance(value, int): if is_literal_type_like(ctx.api.type_context[-1]): return LiteralType(value=multiplier * value, fallback=fallback) else: return ctx.type.copy_modified( last_known_value=LiteralType( value=multiplier * value, fallback=fallback, line=ctx.type.line, column=ctx.type.column, ) ) elif isinstance(ctx.type, LiteralType): value = ctx.type.value fallback = ctx.type.fallback if isinstance(value, int): return LiteralType(value=multiplier * value, fallback=fallback) return ctx.default_return_type def int_pos_callback(ctx: MethodContext) -> Type: """Infer a more precise return type for int.__pos__. This is identical to __neg__, except the value is not inverted. """ return int_neg_callback(ctx, +1) def tuple_mul_callback(ctx: MethodContext) -> Type: """Infer a more precise return type for tuple.__mul__ and tuple.__rmul__. This is used to return a specific sized tuple if multiplied by Literal int """ if not isinstance(ctx.type, TupleType): return ctx.default_return_type arg_type = get_proper_type(ctx.arg_types[0][0]) if isinstance(arg_type, Instance) and arg_type.last_known_value is not None: value = arg_type.last_known_value.value if isinstance(value, int): return ctx.type.copy_modified(items=ctx.type.items * value) elif isinstance(arg_type, LiteralType): value = arg_type.value if isinstance(value, int): return ctx.type.copy_modified(items=ctx.type.items * value) return ctx.default_return_type
DefaultPlugin
python
numpy__numpy
numpy/lib/tests/test_ufunclike.py
{ "start": 146, "end": 3015 }
class ____: def test_isposinf(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape, bool) tgt = np.array([True, False, False, False, False, False]) res = isposinf(a) assert_equal(res, tgt) res = isposinf(a, out) assert_equal(res, tgt) assert_equal(out, tgt) a = a.astype(np.complex128) with assert_raises(TypeError): isposinf(a) def test_isneginf(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape, bool) tgt = np.array([False, True, False, False, False, False]) res = isneginf(a) assert_equal(res, tgt) res = isneginf(a, out) assert_equal(res, tgt) assert_equal(out, tgt) a = a.astype(np.complex128) with assert_raises(TypeError): isneginf(a) def test_fix(self): a = np.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]]) out = np.zeros(a.shape, float) tgt = np.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]]) res = fix(a) assert_equal(res, tgt) res = fix(a, out) assert_equal(res, tgt) assert_equal(out, tgt) assert_equal(fix(3.14), 3) def test_fix_with_subclass(self): class MyArray(np.ndarray): def __new__(cls, data, metadata=None): res = np.array(data, copy=True).view(cls) res.metadata = metadata return res def __array_wrap__(self, obj, context=None, return_scalar=False): if not isinstance(obj, MyArray): obj = obj.view(MyArray) if obj.metadata is None: obj.metadata = self.metadata return obj def __array_finalize__(self, obj): self.metadata = getattr(obj, 'metadata', None) return self a = np.array([1.1, -1.1]) m = MyArray(a, metadata='foo') f = fix(m) assert_array_equal(f, np.array([1, -1])) assert_(isinstance(f, MyArray)) assert_equal(f.metadata, 'foo') # check 0d arrays don't decay to scalars m0d = m[0, ...] m0d.metadata = 'bar' f0d = fix(m0d) assert_(isinstance(f0d, MyArray)) assert_equal(f0d.metadata, 'bar') def test_scalar(self): x = np.inf actual = np.isposinf(x) expected = np.True_ assert_equal(actual, expected) assert_equal(type(actual), type(expected)) x = -3.4 actual = np.fix(x) expected = np.float64(-3.0) assert_equal(actual, expected) assert_equal(type(actual), type(expected)) out = np.array(0.0) actual = np.fix(x, out=out) assert_(actual is out)
TestUfunclike
python
huggingface__transformers
src/transformers/models/timesformer/modeling_timesformer.py
{ "start": 17954, "end": 19456 }
class ____(nn.Module): def __init__(self, config: TimesformerConfig) -> None: super().__init__() self.config = config self.layer = nn.ModuleList([TimesformerLayer(config, ind) for ind in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, output_attentions: bool = False, output_hidden_states: bool = False, return_dict: bool = True, ) -> Union[tuple, BaseModelOutput]: all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module(hidden_states, output_attentions) hidden_states = layer_outputs[0] if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions, ) @auto_docstring
TimesformerEncoder
python
faif__python-patterns
patterns/structural/facade.py
{ "start": 1289, "end": 1560 }
class ____: """ Simple CPU representation. """ def freeze(self) -> None: print("Freezing processor.") def jump(self, position: str) -> None: print("Jumping to:", position) def execute(self) -> None: print("Executing.")
CPU
python
doocs__leetcode
solution/0300-0399/0394.Decode String/Solution.py
{ "start": 0, "end": 455 }
class ____: def decodeString(self, s: str) -> str: s1, s2 = [], [] num, res = 0, '' for c in s: if c.isdigit(): num = num * 10 + int(c) elif c == '[': s1.append(num) s2.append(res) num, res = 0, '' elif c == ']': res = s2.pop() + res * s1.pop() else: res += c return res
Solution
python
graphql-python__graphene
graphene/relay/tests/test_connection.py
{ "start": 272, "end": 9327 }
class ____(ObjectType): class Meta: interfaces = [Node] field = String() def test_connection(): class MyObjectConnection(Connection): extra = String() class Meta: node = MyObject class Edge: other = String() assert MyObjectConnection._meta.name == "MyObjectConnection" fields = MyObjectConnection._meta.fields assert list(fields) == ["page_info", "edges", "extra"] edge_field = fields["edges"] pageinfo_field = fields["page_info"] assert isinstance(edge_field, Field) assert isinstance(edge_field.type, NonNull) assert isinstance(edge_field.type.of_type, List) assert edge_field.type.of_type.of_type == MyObjectConnection.Edge assert isinstance(pageinfo_field, Field) assert isinstance(pageinfo_field.type, NonNull) assert pageinfo_field.type.of_type == PageInfo def test_connection_inherit_abstracttype(): class BaseConnection: extra = String() class MyObjectConnection(BaseConnection, Connection): class Meta: node = MyObject assert MyObjectConnection._meta.name == "MyObjectConnection" fields = MyObjectConnection._meta.fields assert list(fields) == ["page_info", "edges", "extra"] def test_connection_extra_abstract_fields(): class ConnectionWithNodes(Connection): class Meta: abstract = True @classmethod def __init_subclass_with_meta__(cls, node=None, name=None, **options): _meta = ConnectionOptions(cls) _meta.fields = { "nodes": Field( NonNull(List(node)), description="Contains all the nodes in this connection.", ), } return super(ConnectionWithNodes, cls).__init_subclass_with_meta__( node=node, name=name, _meta=_meta, **options ) class MyObjectConnection(ConnectionWithNodes): class Meta: node = MyObject class Edge: other = String() assert MyObjectConnection._meta.name == "MyObjectConnection" fields = MyObjectConnection._meta.fields assert list(fields) == ["nodes", "page_info", "edges"] edge_field = fields["edges"] pageinfo_field = fields["page_info"] nodes_field = fields["nodes"] assert isinstance(edge_field, Field) assert isinstance(edge_field.type, NonNull) assert isinstance(edge_field.type.of_type, List) assert edge_field.type.of_type.of_type == MyObjectConnection.Edge assert isinstance(pageinfo_field, Field) assert isinstance(pageinfo_field.type, NonNull) assert pageinfo_field.type.of_type == PageInfo assert isinstance(nodes_field, Field) assert isinstance(nodes_field.type, NonNull) assert isinstance(nodes_field.type.of_type, List) assert nodes_field.type.of_type.of_type == MyObject def test_connection_override_fields(): class ConnectionWithNodes(Connection): class Meta: abstract = True @classmethod def __init_subclass_with_meta__(cls, node=None, name=None, **options): _meta = ConnectionOptions(cls) base_name = ( re.sub("Connection$", "", name or cls.__name__) or node._meta.name ) edge_class = get_edge_class(cls, node, base_name) _meta.fields = { "page_info": Field( NonNull( PageInfo, name="pageInfo", required=True, description="Pagination data for this connection.", ) ), "edges": Field( NonNull(List(NonNull(edge_class))), description="Contains the nodes in this connection.", ), } return super(ConnectionWithNodes, cls).__init_subclass_with_meta__( node=node, name=name, _meta=_meta, **options ) class MyObjectConnection(ConnectionWithNodes): class Meta: node = MyObject assert MyObjectConnection._meta.name == "MyObjectConnection" fields = MyObjectConnection._meta.fields assert list(fields) == ["page_info", "edges"] edge_field = fields["edges"] pageinfo_field = fields["page_info"] assert isinstance(edge_field, Field) assert isinstance(edge_field.type, NonNull) assert isinstance(edge_field.type.of_type, List) assert isinstance(edge_field.type.of_type.of_type, NonNull) assert edge_field.type.of_type.of_type.of_type.__name__ == "MyObjectEdge" # This page info is NonNull assert isinstance(pageinfo_field, Field) assert isinstance(edge_field.type, NonNull) assert pageinfo_field.type.of_type == PageInfo def test_connection_name(): custom_name = "MyObjectCustomNameConnection" class BaseConnection: extra = String() class MyObjectConnection(BaseConnection, Connection): class Meta: node = MyObject name = custom_name assert MyObjectConnection._meta.name == custom_name def test_edge(): class MyObjectConnection(Connection): class Meta: node = MyObject class Edge: other = String() Edge = MyObjectConnection.Edge assert Edge._meta.name == "MyObjectEdge" edge_fields = Edge._meta.fields assert list(edge_fields) == ["node", "cursor", "other"] assert isinstance(edge_fields["node"], Field) assert edge_fields["node"].type == MyObject assert isinstance(edge_fields["other"], Field) assert edge_fields["other"].type == String def test_edge_with_bases(): class BaseEdge: extra = String() class MyObjectConnection(Connection): class Meta: node = MyObject class Edge(BaseEdge): other = String() Edge = MyObjectConnection.Edge assert Edge._meta.name == "MyObjectEdge" edge_fields = Edge._meta.fields assert list(edge_fields) == ["node", "cursor", "extra", "other"] assert isinstance(edge_fields["node"], Field) assert edge_fields["node"].type == MyObject assert isinstance(edge_fields["other"], Field) assert edge_fields["other"].type == String def test_edge_with_nonnull_node(): class MyObjectConnection(Connection): class Meta: node = NonNull(MyObject) edge_fields = MyObjectConnection.Edge._meta.fields assert isinstance(edge_fields["node"], Field) assert isinstance(edge_fields["node"].type, NonNull) assert edge_fields["node"].type.of_type == MyObject def test_pageinfo(): assert PageInfo._meta.name == "PageInfo" fields = PageInfo._meta.fields assert list(fields) == [ "has_next_page", "has_previous_page", "start_cursor", "end_cursor", ] def test_connectionfield(): class MyObjectConnection(Connection): class Meta: node = MyObject field = ConnectionField(MyObjectConnection) assert field.args == { "before": Argument(String), "after": Argument(String), "first": Argument(Int), "last": Argument(Int), } def test_connectionfield_node_deprecated(): field = ConnectionField(MyObject) with raises(Exception) as exc_info: field.type assert "ConnectionFields now need a explicit ConnectionType for Nodes." in str( exc_info.value ) def test_connectionfield_custom_args(): class MyObjectConnection(Connection): class Meta: node = MyObject field = ConnectionField( MyObjectConnection, before=String(required=True), extra=String() ) assert field.args == { "before": Argument(NonNull(String)), "after": Argument(String), "first": Argument(Int), "last": Argument(Int), "extra": Argument(String), } def test_connectionfield_required(): class MyObjectConnection(Connection): class Meta: node = MyObject class Query(ObjectType): test_connection = ConnectionField(MyObjectConnection, required=True) def resolve_test_connection(root, info, **args): return [] schema = Schema(query=Query) executed = schema.execute("{ testConnection { edges { cursor } } }") assert not executed.errors assert executed.data == {"testConnection": {"edges": []}} def test_connectionfield_strict_types(): class MyObjectConnection(Connection): class Meta: node = MyObject strict_types = True connection_field = ConnectionField(MyObjectConnection) edges_field_type = connection_field.type._meta.fields["edges"].type assert isinstance(edges_field_type, NonNull) edges_list_element_type = edges_field_type.of_type.of_type assert isinstance(edges_list_element_type, NonNull) node_field = edges_list_element_type.of_type._meta.fields["node"] assert isinstance(node_field.type, NonNull)
MyObject
python
ApeWorX__ape
src/ape_ethereum/proxies.py
{ "start": 2883, "end": 4054 }
class ____(ProxyInfoAPI): type: ProxyType def __init__(self, **kwargs): abi = kwargs.pop("abi", None) super().__init__(**kwargs) self._abi = abi @property def abi(self) -> Optional[MethodABI]: return self._abi MASTER_COPY_ABI = MethodABI( type="function", name="masterCopy", stateMutability="view", outputs=[ABIType(type="address")], ) PROXY_TYPE_ABI = MethodABI( type="function", name="proxyType", stateMutability="view", outputs=[ABIType(type="uint256")], ) IMPLEMENTATION_ABI = MethodABI( type="function", name="implementation", stateMutability="view", outputs=[ABIType(type="address")], ) def _make_minimal_proxy(address: str = MINIMAL_PROXY_TARGET_PLACEHOLDER) -> ContractContainer: address = address.replace("0x", "") code = cast(HexStr, MINIMAL_PROXY_BYTES.replace(MINIMAL_PROXY_TARGET_PLACEHOLDER, address)) bytecode = {"bytecode": code} contract_type = ContractType(abi=[], deploymentBytecode=bytecode) return ContractContainer(contract_type=contract_type) minimal_proxy = LazyObject(_make_minimal_proxy, globals(), "minimal_proxy")
ProxyInfo
python
mlflow__mlflow
mlflow/models/resources.py
{ "start": 8666, "end": 10346 }
class ____(DatabricksResource): """ Defines a Databricks Lakebase Database Instance dependency for Model Serving Args: database_instance_name (str): The name of the lakebase/database instance used by the model on_behalf_of_user (Optional[bool]): If True, the resource is accessed with with the permission of the invoker of the model in the serving endpoint. If set to None or False, the resource is accessed with the permissions of the creator """ @property def type(self) -> ResourceType: return ResourceType.LAKEBASE def __init__(self, database_instance_name: str, on_behalf_of_user: bool | None = None): super().__init__(database_instance_name, on_behalf_of_user) def _get_resource_class_by_type(target_uri: str, resource_type: ResourceType): resource_classes = { "databricks": { ResourceType.UC_CONNECTION.value: DatabricksUCConnection, ResourceType.SERVING_ENDPOINT.value: DatabricksServingEndpoint, ResourceType.VECTOR_SEARCH_INDEX.value: DatabricksVectorSearchIndex, ResourceType.SQL_WAREHOUSE.value: DatabricksSQLWarehouse, ResourceType.FUNCTION.value: DatabricksFunction, ResourceType.GENIE_SPACE.value: DatabricksGenieSpace, ResourceType.TABLE.value: DatabricksTable, ResourceType.APP.value: DatabricksApp, ResourceType.LAKEBASE.value: DatabricksLakebase, } } resource = resource_classes.get(target_uri) if resource is None: raise ValueError(f"Unsupported target URI: {target_uri}") return resource.get(resource_type)
DatabricksLakebase
python
doocs__leetcode
solution/1300-1399/1386.Cinema Seat Allocation/Solution.py
{ "start": 0, "end": 460 }
class ____: def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int: d = defaultdict(int) for i, j in reservedSeats: d[i] |= 1 << (10 - j) masks = (0b0111100000, 0b0000011110, 0b0001111000) ans = (n - len(d)) * 2 for x in d.values(): for mask in masks: if (x & mask) == 0: x |= mask ans += 1 return ans
Solution
python
python-markdown__markdown
tests/test_apis.py
{ "start": 25378, "end": 25637 }
class ____(inlinepatterns.InlineProcessor): """ Return a simple text of `group(1)` of a Pattern. """ def handleMatch(self, m, data): return markdown.util.AtomicString('<b>atomic</b>'), m.start(0), m.end(0)
_InlineProcessorThatReturnsAtomicString
python
getsentry__sentry
tests/sentry/models/test_project.py
{ "start": 2347, "end": 27397 }
class ____(APITestCase, TestCase): def test_member_set_simple(self) -> None: user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org) project = self.create_project(teams=[team]) member = OrganizationMember.objects.get(user_id=user.id, organization=org) OrganizationMemberTeam.objects.create(organizationmember=member, team=team) assert list(project.member_set.all()) == [member] def test_inactive_global_member(self) -> None: user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org) project = self.create_project(teams=[team]) OrganizationMember.objects.get(user_id=user.id, organization=org) assert list(project.member_set.all()) == [] def test_transfer_to_organization(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) to_org = self.create_organization() project = self.create_project(teams=[team]) project_other = self.create_project(teams=[team]) rule = Rule.objects.create( project=project, environment_id=Environment.get_or_create(project, "production").id, label="Golden Rule", data={}, ) environment_from_new = self.create_environment(organization=from_org) environment_from_existing = self.create_environment(organization=from_org) environment_to_existing = self.create_environment( organization=to_org, name=environment_from_existing.name ) monitor = Monitor.objects.create( name="test-monitor", slug="test-monitor", organization_id=from_org.id, project_id=project.id, config={"schedule": [1, "month"], "schedule_type": ScheduleType.INTERVAL}, ) monitor_also = Monitor.objects.create( name="test-monitor-also", slug="test-monitor-also", organization_id=from_org.id, project_id=project.id, config={"schedule": [1, "month"], "schedule_type": ScheduleType.INTERVAL}, ) monitor_env_new = MonitorEnvironment.objects.create( monitor=monitor_also, environment_id=environment_from_new.id ) monitor_env_existing = MonitorEnvironment.objects.create( monitor=monitor_also, environment_id=environment_from_existing.id ) monitor_other = Monitor.objects.create( name="test-monitor-other", slug="test-monitor-other", organization_id=from_org.id, project_id=project_other.id, config={"schedule": [1, "month"], "schedule_type": ScheduleType.INTERVAL}, ) monitor_to = Monitor.objects.create( name="test-monitor", slug="test-monitor", organization_id=to_org.id, project_id=self.create_project(name="other-project").id, config={"schedule": [1, "month"], "schedule_type": ScheduleType.INTERVAL}, ) project.transfer_to(organization=to_org) project = Project.objects.get(id=project.id) assert project.teams.count() == 0 assert project.organization_id == to_org.id updated_rule = project.rule_set.get(label="Golden Rule") assert updated_rule.id == rule.id assert updated_rule.environment_id != rule.environment_id assert updated_rule.environment_id == Environment.get_or_create(project, "production").id # check to make sure old monitor is scheduled for deletion assert RegionScheduledDeletion.objects.filter( object_id=monitor.id, model_name="Monitor" ).exists() updated_monitor = Monitor.objects.get(slug="test-monitor-also") assert updated_monitor.id == monitor_also.id assert updated_monitor.organization_id == to_org.id assert updated_monitor.project_id == project.id monitor_env_new.refresh_from_db() environment_to_new = Environment.objects.get(id=monitor_env_new.environment_id) assert environment_to_new.organization_id == to_org.id assert environment_to_new.name == environment_from_new.name monitor_env_existing.refresh_from_db() assert monitor_env_existing.environment_id == environment_to_existing.id unmoved_monitor = Monitor.objects.get(slug="test-monitor-other") assert unmoved_monitor.id == monitor_other.id assert unmoved_monitor.organization_id == from_org.id assert unmoved_monitor.project_id == project_other.id existing_monitor = Monitor.objects.get(id=monitor_to.id) assert existing_monitor.id == monitor_to.id assert existing_monitor.organization_id == to_org.id assert existing_monitor.project_id == monitor_to.project_id def test_transfer_to_organization_slug_collision(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) project = self.create_project(teams=[team], slug="matt") to_org = self.create_organization() # conflicting project slug self.create_project(slug="matt", organization=to_org) assert Project.objects.filter(organization=to_org).count() == 1 project.transfer_to(organization=to_org) project = Project.objects.get(id=project.id) assert project.teams.count() == 0 assert project.organization_id == to_org.id assert project.slug != "matt" assert Project.objects.filter(organization=to_org).count() == 2 assert Project.objects.filter(organization=from_org).count() == 0 def test_transfer_to_organization_releases(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) to_org = self.create_organization() project = self.create_project(teams=[team]) def project_props(proj: Project): return { "id": proj.id, "slug": proj.slug, "name": proj.name, "forced_color": proj.forced_color, "public": proj.public, "date_added": proj.date_added, "status": proj.status, "first_event": proj.first_event, "flags": proj.flags, "platform": proj.platform, } project_before = project_props(project) environment = Environment.get_or_create(project, "production") release = Release.get_or_create(project=project, version="1.0") ReleaseProjectEnvironment.objects.create( project=project, release=release, environment=environment ) assert Environment.objects.filter(id=environment.id).exists() assert Environment.objects.filter(organization_id=from_org.id, projects=project).exists() assert EnvironmentProject.objects.filter(environment=environment, project=project).exists() assert ReleaseProjectEnvironment.objects.filter( project=project, release=release, environment=environment ).exists() assert ReleaseProject.objects.filter(project=project, release=release).exists() project.transfer_to(organization=to_org) project = Project.objects.get(id=project.id) project_after = project_props(project) assert project_before == project_after assert project.teams.count() == 0 assert project.organization_id == to_org.id assert Environment.objects.filter(id=environment.id).exists() assert not EnvironmentProject.objects.filter( environment=environment, project=project ).exists() assert not ReleaseProjectEnvironment.objects.filter( project=project, release=release, environment=environment ).exists() assert not ReleaseProject.objects.filter(project=project, release=release).exists() def test_delete_on_transfer_repository_project_path_configs(self) -> None: from_org = self.create_organization() to_org = self.create_organization() team = self.create_team(organization=from_org) project = self.create_project(teams=[team]) with assume_test_silo_mode(SiloMode.CONTROL): integration, org_integration = self.create_provider_integration_for( from_org, self.user, provider="github" ) repository = Repository.objects.create( organization_id=from_org.id, name="example-repo", integration_id=integration.id, ) repository_project_path_config = RepositoryProjectPathConfig.objects.create( repository=repository, project=project, organization_integration_id=org_integration.id, organization_id=from_org.id, integration_id=integration.id, stack_root="/app", source_root="/src", default_branch="main", ) ProjectCodeOwners.objects.create( project=project, repository_project_path_config=repository_project_path_config, raw="*.py @getsentry/test-team", ) project.transfer_to(organization=to_org) assert RepositoryProjectPathConfig.objects.filter(organization_id=from_org.id).count() == 0 assert RepositoryProjectPathConfig.objects.filter(organization_id=to_org.id).count() == 0 assert RepositoryProjectPathConfig.objects.filter(project_id=project.id).count() == 0 assert ProjectCodeOwners.objects.filter(project_id=project.id).count() == 0 def test_transfer_to_organization_alert_rules(self) -> None: from_org = self.create_organization() from_user = self.create_user() self.create_member(user=from_user, role="member", organization=from_org) team = self.create_team(organization=from_org) to_org = self.create_organization() to_team = self.create_team(organization=to_org) to_user = self.create_user() self.create_member(user=to_user, role="member", organization=to_org) project = self.create_project(teams=[team]) environment = Environment.get_or_create(project, "production") # should lose their owners alert_rule = self.create_alert_rule( organization=self.organization, projects=[project], owner=Actor.from_identifier(f"team:{team.id}"), environment=environment, ) snuba_query = SnubaQuery.objects.filter(id=alert_rule.snuba_query_id).get() rule1 = Rule.objects.create(label="another test rule", project=project, owner_team=team) rule2 = Rule.objects.create( label="rule4", project=project, owner_user_id=from_user.id, ) # should keep their owners rule3 = Rule.objects.create(label="rule2", project=project, owner_team=to_team) rule4 = Rule.objects.create( label="rule3", project=project, owner_user_id=to_user.id, ) assert EnvironmentProject.objects.count() == 1 assert snuba_query.environment is not None assert snuba_query.environment.id == environment.id project.transfer_to(organization=to_org) alert_rule.refresh_from_db() rule1.refresh_from_db() rule2.refresh_from_db() rule3.refresh_from_db() rule4.refresh_from_db() snuba_query.refresh_from_db() assert ( Environment.objects.exclude(id=environment.id).count() == 1 ) # not the same as the from_org env assert EnvironmentProject.objects.count() == 1 assert snuba_query.environment != environment assert alert_rule.organization_id == to_org.id assert alert_rule.user_id is None assert alert_rule.team_id is None for rule in (rule1, rule2): assert rule.owner_user_id is None assert rule.owner_team_id is None assert rule3.owner_user_id is None assert rule3.owner_team_id assert rule4.owner_user_id assert rule4.owner_team_id is None def test_transfer_to_organization_external_issues(self) -> None: from_org = self.create_organization() to_org = self.create_organization() project = self.create_project(organization=from_org) group = self.create_group(project=project) other_project = self.create_project(organization=from_org) other_group = self.create_group(project=other_project) self.integration = self.create_integration( organization=self.organization, provider="jira", name="Jira", external_id="jira:1", ) ext_issue = ExternalIssue.objects.create( organization_id=from_org.id, integration_id=self.integration.id, key="123", ) other_ext_issue = ExternalIssue.objects.create( organization_id=from_org.id, integration_id=self.integration.id, key="124", ) group_link = GroupLink.objects.create( group_id=group.id, project_id=group.project_id, linked_type=GroupLink.LinkedType.issue, linked_id=ext_issue.id, ) other_group_link = GroupLink.objects.create( group_id=other_group.id, project_id=other_group.project_id, linked_type=GroupLink.LinkedType.issue, linked_id=other_ext_issue.id, ) project.transfer_to(organization=to_org) project.refresh_from_db() other_project.refresh_from_db() ext_issue.refresh_from_db() other_ext_issue.refresh_from_db() group_link.refresh_from_db() other_group_link.refresh_from_db() assert project.organization_id == to_org.id assert ext_issue.organization_id == to_org.id assert group_link.project_id == project.id assert other_project.organization_id == from_org.id assert other_ext_issue.organization_id == from_org.id assert other_group_link.project_id == other_project.id def test_get_absolute_url(self) -> None: url = self.project.get_absolute_url() assert ( url == f"http://testserver/organizations/{self.organization.slug}/issues/?project={self.project.id}" ) url = self.project.get_absolute_url(params={"q": "all"}) assert ( url == f"http://testserver/organizations/{self.organization.slug}/issues/?q=all&project={self.project.id}" ) @with_feature("system:multi-region") def test_get_absolute_url_customer_domains(self) -> None: url = self.project.get_absolute_url() assert ( url == f"http://{self.organization.slug}.testserver/issues/?project={self.project.id}" ) def test_get_next_short_id_simple(self) -> None: with patch("sentry.models.Counter.increment", return_value=1231): assert self.project.next_short_id() == 1231 def test_next_short_id_increments_by_one_if_no_delta_passed(self) -> None: assert self.project.next_short_id() == 1 assert self.project.next_short_id() == 2 def test_get_next_short_id_increments_by_delta_value(self) -> None: assert self.project.next_short_id() == 1 assert self.project.next_short_id(delta=2) == 3 def test_add_team(self) -> None: team = self.create_team(organization=self.organization) assert self.project.add_team(team) teams = self.project.teams.all() assert team.id in {t.id for t in teams} @patch("sentry.models.project.locks.get") def test_lock_is_acquired_when_creating_project(self, mock_lock: MagicMock) -> None: # self.organization is cached property, which means it will be created # only if it is accessed, so we need to simulate access and all potential mock # calls before resetting the mock assert self.organization # Ensure the mock starts clean before the save operation mock_lock.reset_mock() Project.objects.create(organization=self.organization) assert mock_lock.call_count == 3 # 1 lock for cached org, 2 locks for default detectors @patch("sentry.models.project.locks.get") def test_lock_is_not_acquired_when_updating_project(self, mock_lock: MagicMock) -> None: # self.project is cached property, which means it will be created # only if it is accessed, so we need to simulate access and all potential mock # calls before resetting the mock assert self.project # Ensure the mock starts clean before the save operation mock_lock.reset_mock() self.project.save() assert mock_lock.call_count == 0 def test_remove_team_clears_alerts(self) -> None: team = self.create_team(organization=self.organization) assert self.project.add_team(team) rule = Rule.objects.create(project=self.project, label="issa rule", owner_team_id=team.id) alert_rule = self.create_alert_rule( organization=self.organization, owner=Actor.from_id(team_id=team.id) ) self.project.remove_team(team) rule.refresh_from_db() assert rule.owner_team_id is None assert rule.owner_user_id is None alert_rule.refresh_from_db() assert alert_rule.team_id is None assert alert_rule.user_id is None def test_project_detectors(self) -> None: project = self.create_project(create_default_detectors=True) assert Detector.objects.filter(project=project, type=ErrorGroupType.slug).count() == 1 assert Detector.objects.filter(project=project, type=IssueStreamGroupType.slug).count() == 1 def test_transfer_to_organization_with_metric_issue_detector_and_workflow(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) to_org = self.create_organization() project = self.create_project(teams=[team]) detector = self.create_detector(project=project) data_source = self.create_data_source(organization=from_org) data_source.detectors.add(detector) workflow = self.create_workflow(organization=from_org) self.create_detector_workflow(detector=detector, workflow=workflow) project.transfer_to(organization=to_org) project.refresh_from_db() detector.refresh_from_db() data_source.refresh_from_db() workflow.refresh_from_db() assert project.organization_id == to_org.id assert detector.project_id == project.id assert data_source.organization_id == to_org.id assert workflow.organization_id == to_org.id assert DetectorWorkflow.objects.filter(detector=detector, workflow=workflow).exists() def test_transfer_to_organization_with_workflow_data_condition_groups(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) to_org = self.create_organization() project = self.create_project(teams=[team]) detector = self.create_detector(project=project) workflow = self.create_workflow(organization=from_org) self.create_detector_workflow(detector=detector, workflow=workflow) condition_group = self.create_data_condition_group(organization=from_org) self.create_workflow_data_condition_group( workflow=workflow, condition_group=condition_group ) project.transfer_to(organization=to_org) project.refresh_from_db() detector.refresh_from_db() workflow.refresh_from_db() condition_group.refresh_from_db() assert project.organization_id == to_org.id assert detector.project_id == project.id assert workflow.organization_id == to_org.id assert condition_group.organization_id == to_org.id wdcg = condition_group.workflowdataconditiongroup_set.first() assert wdcg is not None assert wdcg.workflow_id == workflow.id def test_transfer_to_organization_does_not_transfer_shared_workflows(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) to_org = self.create_organization() project_a = self.create_project(teams=[team], name="Project A") project_b = self.create_project(teams=[team], organization=from_org, name="Project B") detector_a = self.create_detector(project=project_a) detector_b = self.create_detector(project=project_b) shared_workflow = self.create_workflow(organization=from_org, name="Shared Workflow") self.create_detector_workflow(detector=detector_a, workflow=shared_workflow) self.create_detector_workflow(detector=detector_b, workflow=shared_workflow) exclusive_workflow = self.create_workflow(organization=from_org, name="Exclusive Workflow") self.create_detector_workflow(detector=detector_a, workflow=exclusive_workflow) shared_dcg = self.create_data_condition_group(organization=from_org) self.create_workflow_data_condition_group( workflow=shared_workflow, condition_group=shared_dcg ) exclusive_dcg = self.create_data_condition_group(organization=from_org) self.create_workflow_data_condition_group( workflow=exclusive_workflow, condition_group=exclusive_dcg ) project_a.transfer_to(organization=to_org) project_a.refresh_from_db() project_b.refresh_from_db() detector_a.refresh_from_db() detector_b.refresh_from_db() shared_workflow.refresh_from_db() exclusive_workflow.refresh_from_db() shared_dcg.refresh_from_db() exclusive_dcg.refresh_from_db() assert project_a.organization_id == to_org.id assert project_b.organization_id == from_org.id assert detector_a.project_id == project_a.id assert detector_b.project_id == project_b.id assert shared_workflow.organization_id == from_org.id assert exclusive_workflow.organization_id == to_org.id assert shared_dcg.organization_id == from_org.id assert exclusive_dcg.organization_id == to_org.id assert DetectorWorkflow.objects.filter( detector=detector_a, workflow=shared_workflow ).exists() assert DetectorWorkflow.objects.filter( detector=detector_b, workflow=shared_workflow ).exists() assert DetectorWorkflow.objects.filter( detector=detector_a, workflow=exclusive_workflow ).exists() def test_transfer_to_organization_with_detector_workflow_condition_group(self) -> None: from_org = self.create_organization() team = self.create_team(organization=from_org) to_org = self.create_organization() project = self.create_project(teams=[team]) detector = self.create_detector(project=project) workflow_condition_group = self.create_data_condition_group(organization=from_org) detector.workflow_condition_group = workflow_condition_group detector.save() project.transfer_to(organization=to_org) project.refresh_from_db() detector.refresh_from_db() workflow_condition_group.refresh_from_db() assert project.organization_id == to_org.id assert detector.project_id == project.id assert workflow_condition_group.organization_id == to_org.id assert detector.workflow_condition_group_id == workflow_condition_group.id def test_transfer_to_organization_with_workflow_when_condition_groups(self) -> None: from_org = self.create_organization() to_org = self.create_organization() team = self.create_team(organization=from_org) project = self.create_project(teams=[team]) detector = self.create_detector(project=project) when_condition_group = self.create_data_condition_group(organization=from_org) workflow = self.create_workflow( organization=from_org, when_condition_group=when_condition_group ) self.create_detector_workflow(detector=detector, workflow=workflow) project.transfer_to(organization=to_org) project.refresh_from_db() detector.refresh_from_db() workflow.refresh_from_db() when_condition_group.refresh_from_db() assert project.organization_id == to_org.id assert detector.project_id == project.id assert workflow.organization_id == to_org.id assert when_condition_group.organization_id == to_org.id
ProjectTest
python
huggingface__transformers
tests/models/voxtral/test_modeling_voxtral.py
{ "start": 9155, "end": 31597 }
class ____(unittest.TestCase): def setUp(self): self.checkpoint_name = "mistralai/Voxtral-Mini-3B-2507" self.dtype = torch.bfloat16 self.processor = AutoProcessor.from_pretrained(self.checkpoint_name) def tearDown(self): cleanup(torch_device, gc_collect=True) @slow def test_mini_single_turn_audio_only(self): """ reproducer: https://gist.github.com/eustlb/c5e0e0a12e84e3d575151ba63d17e4cf disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ conversation = [ { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav", }, ], } ] model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_chat_template(conversation) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ 'The audio is a humorous exchange between two individuals, likely friends or acquaintances, about tattoos. Here\'s a breakdown:\n\n1. **Initial Reaction**: One person (let\'s call him A) is surprised to see the other person (let\'s call him B) has a tattoo. A asks if B has a tattoo, and B confirms.\n\n2. **Tattoo Description**: B then asks A what his tattoo says, and A responds with "sweet." This exchange is repeated multiple times, with B asking A what his tattoo says, and A always responding with "sweet."\n\n3. **Misunderstanding**: B seems to be genuinely curious about the meaning of the tattoo, but A is either not paying attention or not understanding the question. This leads to a series of repetitive responses from A.\n\n4. **Clarification**: Eventually, B clarifies that he wants to know what A\'s tattoo says, not what A thinks B\'s tattoo says. A then realizes his mistake and apologizes.\n\n5. **Final Answer**: B then asks A what his tattoo says, and A finally responds with "dude," which is the actual meaning of his tattoo.\n\n6. **Final Joke**: B then jokes that A\'s tattoo says "sweet," which is a play on words, as "sweet" can also mean "good" or "nice."\n\nThroughout the conversation, there\'s a lot of repetition and misunderstanding, which adds to the humor. The final joke about the tattoo saying "sweet" is a clever twist on the initial confusion.' ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) @slow def test_mini_single_turn_text_and_audio(self): """ reproducer: https://gist.github.com/eustlb/c5e0e0a12e84e3d575151ba63d17e4cf disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ conversation = [ { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", }, {"type": "text", "text": "What can you tell me about this audio?"}, ], } ] model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_chat_template(conversation) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) # fmt: off EXPECTED_OUTPUTS = Expectations( { (None, None): ["What can you tell me about this audio?This audio is a farewell address by President Barack Obama, delivered in Chicago. In the speech, he reflects on his eight years in office, highlighting the resilience, hope, and unity of the American people. He acknowledges the diverse perspectives and conversations he had with the public, which kept him honest and inspired. The president also emphasizes the importance of self-government and civic engagement, encouraging Americans to participate in their democracy actively. He expresses optimism about the country's future and looks forward to continuing his work as a citizen. The audio concludes with a heartfelt thank you and a blessing for the United States."], ("xpu", None): ["What can you tell me about this audio?This audio is a farewell address by President Barack Obama, delivered in Chicago. In the speech, he reflects on his eight years in office, highlighting the resilience, hope, and unity of the American people. He emphasizes the importance of self-government and active citizenship, encouraging listeners to engage in their communities and participate in democracy. The president expresses his optimism about the country's future and his commitment to continuing to serve as a citizen. He concludes the speech with a heartfelt thank you and a blessing for the United States."], } ) # fmt: on EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) @slow def test_mini_single_turn_text_and_multiple_audios(self): """ reproducer: https://gist.github.com/eustlb/c5e0e0a12e84e3d575151ba63d17e4cf disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ conversation = [ { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/mary_had_lamb.mp3", }, { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/winning_call.mp3", }, {"type": "text", "text": "What sport and what nursery rhyme are referenced?"}, ], } ] model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_chat_template(conversation) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ 'What sport and what nursery rhyme are referenced?The audio references both a nursery rhyme and a baseball game. The nursery rhyme is "Mary Had a Little Lamb," and the baseball game is the American League Championship.' ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) @slow def test_mini_single_turn_text_only(self): """ reproducer: https://gist.github.com/eustlb/c5e0e0a12e84e3d575151ba63d17e4cf disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ conversation = [ { "role": "user", "content": [ {"type": "text", "text": "Hello, how are you doing today?"}, ], } ] model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_chat_template(conversation) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ "Hello, how are you doing today?Hello! I'm functioning as intended, thank you. How about you? How's your day going?" ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) @slow def test_mini_single_turn_text_and_multiple_audios_batched(self): """ reproducer: https://gist.github.com/eustlb/c5e0e0a12e84e3d575151ba63d17e4cf disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ conversations = [ [ { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", }, { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3", }, { "type": "text", "text": "Who's speaking in the speach and what city's weather is being discussed?", }, ], } ], [ { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/winning_call.mp3", }, {"type": "text", "text": "What can you tell me about this audio?"}, ], } ], ] model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_chat_template(conversations) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ "Who's speaking in the speach and what city's weather is being discussed?The speaker in the speech is Barack Obama, and the weather being discussed is in Barcelona, Spain.", 'What can you tell me about this audio?This audio is a commentary of a baseball game, specifically a home run hit by Edgar Martinez. Here are some key points:\n\n- **Game Context**: The game is likely a playoff or championship game, as the commentator mentions the American League Championship.\n- **Play Description**: Edgar Martinez hits a home run, which is described as a "line drive" and a "base hit."\n- **Team Involvement**: The team is the Mariners, and the commentator is excited about their chances to win the championship.\n- **Emotional Tone**: The commentator is enthusiastic and surprised, using phrases like "I don\'t believe it" and "my, oh my" to express their excitement.\n- **Game Moment**: The play involves a throw to the plate that is described as "late," indicating a close call or a potential error.\n\nThe audio captures the thrill and tension of a high-stakes baseball moment.', ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) @slow def test_mini_multi_turn_text_and_audio(self): """ reproducer: https://gist.github.com/eustlb/c5e0e0a12e84e3d575151ba63d17e4cf disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ conversations = [ [ { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", }, { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/bcn_weather.mp3", }, {"type": "text", "text": "Describe briefly what you can hear."}, ], }, { "role": "assistant", "content": "The audio begins with the speaker delivering a farewell address in Chicago, reflecting on his eight years as president and expressing gratitude to the American people. The audio then transitions to a weather report, stating that it was 35 degrees in Barcelona the previous day, but the temperature would drop to minus 20 degrees the following day.", }, { "role": "user", "content": [ { "type": "audio", "path": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav", }, {"type": "text", "text": "Ok, now compare this new audio with the previous one."}, ], }, ] ] model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_chat_template(conversations) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ 'Describe briefly what you can hear.The audio begins with the speaker delivering a farewell address in Chicago, reflecting on his eight years as president and expressing gratitude to the American people. The audio then transitions to a weather report, stating that it was 35 degrees in Barcelona the previous day, but the temperature would drop to minus 20 degrees the following day.Ok, now compare this new audio with the previous one.The new audio is a humorous conversation between two friends, one of whom has a tattoo. The speaker is excited to see the tattoo and asks what it says. The other friend repeatedly says "sweet" in response, leading to a playful exchange. The speaker then realizes the joke and says "your tattoo says dude, your tattoo says sweet, got it?" The previous audio was a political speech by a president, reflecting on his time in office and expressing gratitude to the American people. The new audio is a casual, light-hearted conversation with no political context.' ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) @slow def test_transcribe_mode_audio_input(self): """ To test transcribe mode of the model, WER evaluation has been run to compare with the declared model performances. see https://github.com/huggingface/transformers/pull/39429 PR's descrition. disclaimer: Perfect token matching cannot be achieved due to floating-point arithmetic differences between vLLM and Transformers implementations. """ # test without language detection model = VoxtralForConditionalGeneration.from_pretrained( self.checkpoint_name, dtype=self.dtype, device_map=torch_device ) inputs = self.processor.apply_transcription_request( language="en", audio="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", model_id=self.checkpoint_name, ) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ "This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye-to-eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners and on distant military outposts, All these conversations are what have kept me honest, kept me inspired, and kept me going. Every day, I learned from you. You made me a better president, and you made me a better man. Over the course of these eight years, I've seen the goodness, the resilience, and the hope of the American people. I've seen neighbors looking out for each other as we rescued our economy from the worst crisis of our lifetimes. I've hugged cancer survivors who finally know the security of affordable health care. I've seen communities like Joplin rebuild from disaster, and cities like Boston show the world that no terrorist will ever break the American spirit. I've seen the hopeful faces of young graduates and our newest military officers. I've mourned with grieving families searching for answers, and I found grace in a Charleston church. I've seen our scientists help a paralyzed man regain his sense of touch, and our wounded warriors walk again. I've seen our doctors and volunteers rebuild after earthquakes and stop pandemics in their tracks. I've learned from students who are building robots and curing diseases and who will change the world in ways we can't even imagine. I've seen the youngest of children remind us of our obligations to care for our refugees, to work in peace, and above all, to look out for each other. That's what's possible when we come together in the slow, hard, sometimes frustrating, but always vital work of self-government. But we can't take our democracy for granted. All of us, regardless of party, should throw ourselves into the work of citizenship. Not just when there's an election. Not just when our own narrow interest is at stake. But over the full span of a lifetime. If you're tired of arguing with strangers on the Internet, try to talk with one in real life. If something needs fixing, lace up your shoes and do some organizing. If you're disappointed by your elected officials, then grab a clipboard, get some signatures, and run for office yourself. Our success depends on our" ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT) # test with language detection, i.e. language=None inputs = self.processor.apply_transcription_request( audio="https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/obama.mp3", model_id=self.checkpoint_name, ) inputs = inputs.to(torch_device, dtype=self.dtype) outputs = model.generate(**inputs, do_sample=False, max_new_tokens=500) decoded_outputs = self.processor.batch_decode(outputs, skip_special_tokens=True) EXPECTED_OUTPUT = [ "This week, I traveled to Chicago to deliver my final farewell address to the nation, following in the tradition of presidents before me. It was an opportunity to say thank you. Whether we've seen eye-to-eye or rarely agreed at all, my conversations with you, the American people, in living rooms and schools, at farms and on factory floors, at diners and on distant military outposts, All these conversations are what have kept me honest, kept me inspired, and kept me going. Every day, I learned from you. You made me a better president, and you made me a better man. Over the course of these eight years, I've seen the goodness, the resilience, and the hope of the American people. I've seen neighbors looking out for each other as we rescued our economy from the worst crisis of our lifetimes. I've hugged cancer survivors who finally know the security of affordable health care. I've seen communities like Joplin rebuild from disaster, and cities like Boston show the world that no terrorist will ever break the American spirit. I've seen the hopeful faces of young graduates and our newest military officers. I've mourned with grieving families searching for answers, and I found grace in a Charleston church. I've seen our scientists help a paralyzed man regain his sense of touch, and our wounded warriors walk again. I've seen our doctors and volunteers rebuild after earthquakes and stop pandemics in their tracks. I've learned from students who are building robots and curing diseases and who will change the world in ways we can't even imagine. I've seen the youngest of children remind us of our obligations to care for our refugees, to work in peace, and above all, to look out for each other. That's what's possible when we come together in the slow, hard, sometimes frustrating, but always vital work of self-government. But we can't take our democracy for granted. All of us, regardless of party, should throw ourselves into the work of citizenship. Not just when there's an election. Not just when our own narrow interest is at stake. But over the full span of a lifetime. If you're tired of arguing with strangers on the Internet, try to talk with one in real life. If something needs fixing, lace up your shoes and do some organizing. If you're disappointed by your elected officials, then grab a clipboard, get some signatures, and run for office yourself. Our success depends on our" ] self.assertEqual(decoded_outputs, EXPECTED_OUTPUT)
VoxtralForConditionalGenerationIntegrationTest
python
pymupdf__PyMuPDF
src/table.py
{ "start": 64449, "end": 68078 }
class ____: vertical_strategy: str = "lines" horizontal_strategy: str = "lines" explicit_vertical_lines: list = None explicit_horizontal_lines: list = None snap_tolerance: float = DEFAULT_SNAP_TOLERANCE snap_x_tolerance: float = UNSET snap_y_tolerance: float = UNSET join_tolerance: float = DEFAULT_JOIN_TOLERANCE join_x_tolerance: float = UNSET join_y_tolerance: float = UNSET edge_min_length: float = 3 min_words_vertical: float = DEFAULT_MIN_WORDS_VERTICAL min_words_horizontal: float = DEFAULT_MIN_WORDS_HORIZONTAL intersection_tolerance: float = 3 intersection_x_tolerance: float = UNSET intersection_y_tolerance: float = UNSET text_settings: dict = None def __post_init__(self) -> "TableSettings": """Clean up user-provided table settings. Validates that the table settings provided consists of acceptable values and returns a cleaned up version. The cleaned up version fills out the missing values with the default values in the provided settings. TODO: Can be further used to validate that the values are of the correct type. For example, raising a value error when a non-boolean input is provided for the key ``keep_blank_chars``. :param table_settings: User-provided table settings. :returns: A cleaned up version of the user-provided table settings. :raises ValueError: When an unrecognised key is provided. """ for setting in NON_NEGATIVE_SETTINGS: if (getattr(self, setting) or 0) < 0: raise ValueError(f"Table setting '{setting}' cannot be negative") for orientation in ["horizontal", "vertical"]: strategy = getattr(self, orientation + "_strategy") if strategy not in TABLE_STRATEGIES: raise ValueError( f"{orientation}_strategy must be one of" f'{{{",".join(TABLE_STRATEGIES)}}}' ) if self.text_settings is None: self.text_settings = {} # This next section is for backwards compatibility for attr in ["x_tolerance", "y_tolerance"]: if attr not in self.text_settings: self.text_settings[attr] = self.text_settings.get("tolerance", 3) if "tolerance" in self.text_settings: del self.text_settings["tolerance"] # End of that section for attr, fallback in [ ("snap_x_tolerance", "snap_tolerance"), ("snap_y_tolerance", "snap_tolerance"), ("join_x_tolerance", "join_tolerance"), ("join_y_tolerance", "join_tolerance"), ("intersection_x_tolerance", "intersection_tolerance"), ("intersection_y_tolerance", "intersection_tolerance"), ]: if getattr(self, attr) is UNSET: setattr(self, attr, getattr(self, fallback)) return self @classmethod def resolve(cls, settings=None): if settings is None: return cls() elif isinstance(settings, cls): return settings elif isinstance(settings, dict): core_settings = {} text_settings = {} for k, v in settings.items(): if k[:5] == "text_": text_settings[k[5:]] = v else: core_settings[k] = v core_settings["text_settings"] = text_settings return cls(**core_settings) else: raise ValueError(f"Cannot resolve settings: {settings}")
TableSettings
python
huggingface__transformers
src/transformers/models/llava_next_video/processing_llava_next_video.py
{ "start": 1461, "end": 15155 }
class ____(ProcessorMixin): r""" Constructs a LLaVa-NeXT-Video processor which wraps a LLaVa-NeXT image processor, LLaVa-NeXT-Video video processor and a LLaMa tokenizer into a single processor. [`LlavaNextVideoProcessor`] offers all the functionalities of [`LlavaNextImageProcessor`], [`LlavaNextVideoVideoProcessor`] and [`LlamaTokenizerFast`]. See the [`~LlavaNextVideoProcessor.__call__`] and [`~LlavaNextVideoProcessor.decode`] for more information. Args: video_processor ([`LlavaNextVideoVideoProcessor`], *optional*): The video processor is a required input. image_processor ([`LlavaNextImageProcessor`], *optional*): The image processor is a required input. tokenizer ([`LlamaTokenizerFast`], *optional*): The tokenizer is a required input. chat_template (`str`, *optional*): Jinja chat template that will be used in tokenizer's `apply_chat_template` patch_size (`int`, *optional*): Patch size from the vision tower. vision_feature_select_strategy (`str`, *optional*): The feature selection strategy used to select the vision feature from the vision backbone. Should be same as in model's config video_token (`str`, *optional*, defaults to `"<video>"`): Special token used to denote video location. image_token (`str`, *optional*, defaults to `"<image>"`): Special token used to denote image location. num_additional_image_tokens (`int`, *optional*, defaults to 0): Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other extra tokens appended, no need to set this arg. """ # video and image processor share same args, but have different processing logic # only image processor config is saved in the hub def __init__( self, video_processor=None, image_processor=None, tokenizer=None, chat_template=None, patch_size=None, vision_feature_select_strategy=None, video_token="<video>", image_token="<image>", num_additional_image_tokens=0, **kwargs, ): self.patch_size = patch_size self.num_additional_image_tokens = num_additional_image_tokens self.vision_feature_select_strategy = vision_feature_select_strategy self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token self.video_token = tokenizer.video_token if hasattr(tokenizer, "video_token") else video_token self.image_token_id = ( tokenizer.image_token_id if getattr(tokenizer, "image_token_id", None) else tokenizer.convert_tokens_to_ids(self.image_token) ) self.video_token_id = ( tokenizer.video_token_id if getattr(tokenizer, "video_token_id", None) else tokenizer.convert_tokens_to_ids(self.video_token) ) super().__init__(video_processor, image_processor, tokenizer, chat_template=chat_template) def __call__( self, images: Optional[ImageInput] = None, text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None, videos: Optional[VideoInput] = None, **kwargs: Unpack[LlavaNextVideoProcessorKwargs], ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to LlavaNextImageProcessor's [`~LlavaNextImageProcessor.__call__`] if `images` is not `None`. To prepare the video(s), this method forwards the `videos` and `kwargs` arguments to LlavaNextVideoVideoProcessor's [`~LlavaNextVideoVideoProcessor.__call__`] if `videos` is not `None`. Please refer to the docstring of the above two methods for more information. Args: text (`str`, `list[str]`, `list[list[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`): The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields: - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not `None`). - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. """ output_kwargs = self._merge_kwargs( LlavaNextVideoProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) if images is not None: image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"]) else: image_inputs = {} if videos is not None: videos_inputs = self.video_processor(videos, **output_kwargs["videos_kwargs"]) else: videos_inputs = {} if isinstance(text, str): text = [text] elif not isinstance(text, list) and not isinstance(text[0], str): raise TypeError("Invalid input text. Please provide a string, or a list of strings") if image_inputs: image_sizes = iter(image_inputs["image_sizes"]) height, width = get_image_size(to_numpy_array(image_inputs["pixel_values"][0][0])) prompt_strings = [] for sample in text: while self.image_token in sample: image_size = next(image_sizes) if not isinstance(image_size, (list, tuple)): # cast to list to avoid numerical precision errors when calculating unpadding image_size = image_size.tolist() orig_height, orig_width = image_size num_image_tokens = self._get_number_of_features(orig_height, orig_width, height, width) if self.vision_feature_select_strategy == "default": num_image_tokens -= 1 sample = sample.replace(self.image_token, "<placeholder>" * num_image_tokens, 1) prompt_strings.append(sample) text = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings] # videos are easier, simply get frames and multiply if videos_inputs: one_video = videos_inputs.get("pixel_values_videos")[0] if isinstance(one_video, (list, tuple)): one_video = np.array(one_video) else: one_video = to_numpy_array(one_video) height, width = get_image_size(one_video[0]) num_frames = one_video.shape[0] # frame dim is always after batch dim # no `self.num_additional_image_tokens` added because video always has a default feature selection strategy num_image_tokens = (height // self.patch_size) * (width // self.patch_size) num_video_tokens = num_image_tokens // 4 * num_frames # divide by 4 needed for avg pooling layer prompt_strings = [] for sample in text: sample = sample.replace(self.video_token, self.video_token * num_video_tokens) prompt_strings.append(sample) text = prompt_strings return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None) text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"]) self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"]) return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors) # Copied from transformers.models.llava_next.processing_llava_next.LlavaNextProcessor._get_number_of_features def _get_number_of_features(self, orig_height: int, orig_width: int, height: int, width: int) -> int: image_grid_pinpoints = self.image_processor.image_grid_pinpoints height_best_resolution, width_best_resolution = select_best_resolution( [orig_height, orig_width], image_grid_pinpoints ) scale_height, scale_width = height_best_resolution // height, width_best_resolution // width patches_height = height // self.patch_size patches_width = width // self.patch_size unpadded_features, newline_features = self._get_unpadded_features( orig_height, orig_width, patches_height, patches_width, scale_height, scale_width ) # The base patch covers the entire image (+1 for the CLS) base_features = patches_height * patches_width + self.num_additional_image_tokens num_image_tokens = unpadded_features + newline_features + base_features return num_image_tokens # Copied from transformers.models.llava_next.processing_llava_next.LlavaNextProcessor._get_unpadded_features def _get_unpadded_features(self, height, width, patches_height, patches_width, scale_height, scale_width): """ Get number of features for a given image with height/width. LLaVA-NeXT is different from LLaVA because it divided each image into patches depending on its resolution. Therefore we need to calculate how many patches an image is divided into and get the number of features from that. """ current_height = patches_height * scale_height current_width = patches_width * scale_width original_aspect_ratio = width / height current_aspect_ratio = current_width / current_height if original_aspect_ratio > current_aspect_ratio: new_height = int(round(height * (current_width / width), 7)) padding = (current_height - new_height) // 2 current_height -= padding * 2 else: new_width = int(round(width * (current_height / height), 7)) padding = (current_width - new_width) // 2 current_width -= padding * 2 unpadded_features = current_height * current_width newline_features = current_height return (unpadded_features, newline_features) def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs): """ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes. Args: image_sizes (list[list[str]], *optional*): The input sizes formatted as (height, width) per each image. Returns: `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided input modalities, along with other useful data. """ vision_data = {} if image_sizes is not None: images_kwargs = LlavaNextVideoProcessorKwargs._defaults.get("images_kwargs", {}) images_kwargs.update(kwargs) size = images_kwargs.get("size", None) or self.image_processor.size size = ( (size["shortest_edge"], size["shortest_edge"]) if "shortest_edge" in size else (min(size["height"], size["width"]), min(size["height"], size["width"])) ) processed_height, processed_width = size batch_num_image_tokens = [] num_image_patches = [1] * len(image_sizes) # llava-next doesn't batch pixels as Idefics, thus `1` patch` for image_size in image_sizes: orig_height, orig_width = image_size num_image_tokens = self._get_number_of_features( orig_height, orig_width, processed_height, processed_width ) if self.vision_feature_select_strategy == "default": num_image_tokens -= 1 batch_num_image_tokens.append(num_image_tokens) vision_data.update({"num_image_tokens": batch_num_image_tokens, "num_image_patches": num_image_patches}) return MultiModalData(**vision_data) __all__ = ["LlavaNextVideoProcessor"]
LlavaNextVideoProcessor
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/automap.py
{ "start": 36053, "end": 51788 }
class ____: """Base class for an "automap" schema. The :class:`.AutomapBase` class can be compared to the "declarative base" class that is produced by the :func:`.declarative.declarative_base` function. In practice, the :class:`.AutomapBase` class is always used as a mixin along with an actual declarative base. A new subclassable :class:`.AutomapBase` is typically instantiated using the :func:`.automap_base` function. .. seealso:: :ref:`automap_toplevel` """ __abstract__ = True classes: ClassVar[Properties[Type[Any]]] """An instance of :class:`.util.Properties` containing classes. This object behaves much like the ``.c`` collection on a table. Classes are present under the name they were given, e.g.:: Base = automap_base() Base.prepare(autoload_with=some_engine) User, Address = Base.classes.User, Base.classes.Address For class names that overlap with a method name of :class:`.util.Properties`, such as ``items()``, the getitem form is also supported:: Item = Base.classes["items"] """ by_module: ClassVar[ByModuleProperties] """An instance of :class:`.util.Properties` containing a hierarchal structure of dot-separated module names linked to classes. This collection is an alternative to the :attr:`.AutomapBase.classes` collection that is useful when making use of the :paramref:`.AutomapBase.prepare.modulename_for_table` parameter, which will apply distinct ``__module__`` attributes to generated classes. The default ``__module__`` an automap-generated class is ``sqlalchemy.ext.automap``; to access this namespace using :attr:`.AutomapBase.by_module` looks like:: User = Base.by_module.sqlalchemy.ext.automap.User If a class had a ``__module__`` of ``mymodule.account``, accessing this namespace looks like:: MyClass = Base.by_module.mymodule.account.MyClass .. versionadded:: 2.0 .. seealso:: :ref:`automap_by_module` """ metadata: ClassVar[MetaData] """Refers to the :class:`_schema.MetaData` collection that will be used for new :class:`_schema.Table` objects. .. seealso:: :ref:`orm_declarative_metadata` """ _sa_automapbase_bookkeeping: ClassVar[_Bookkeeping] @classmethod @util.deprecated_params( engine=( "2.0", "The :paramref:`_automap.AutomapBase.prepare.engine` parameter " "is deprecated and will be removed in a future release. " "Please use the " ":paramref:`_automap.AutomapBase.prepare.autoload_with` " "parameter.", ), reflect=( "2.0", "The :paramref:`_automap.AutomapBase.prepare.reflect` " "parameter is deprecated and will be removed in a future " "release. Reflection is enabled when " ":paramref:`_automap.AutomapBase.prepare.autoload_with` " "is passed.", ), ) def prepare( cls: Type[AutomapBase], autoload_with: Optional[Engine] = None, engine: Optional[Any] = None, reflect: bool = False, schema: Optional[str] = None, classname_for_table: Optional[PythonNameForTableType] = None, modulename_for_table: Optional[PythonNameForTableType] = None, collection_class: Optional[Any] = None, name_for_scalar_relationship: Optional[ NameForScalarRelationshipType ] = None, name_for_collection_relationship: Optional[ NameForCollectionRelationshipType ] = None, generate_relationship: Optional[GenerateRelationshipType] = None, reflection_options: Union[ Dict[_KT, _VT], immutabledict[_KT, _VT] ] = util.EMPTY_DICT, ) -> None: """Extract mapped classes and relationships from the :class:`_schema.MetaData` and perform mappings. For full documentation and examples see :ref:`automap_basic_use`. :param autoload_with: an :class:`_engine.Engine` or :class:`_engine.Connection` with which to perform schema reflection; when specified, the :meth:`_schema.MetaData.reflect` method will be invoked within the scope of this method. :param engine: legacy; use :paramref:`.AutomapBase.autoload_with`. Used to indicate the :class:`_engine.Engine` or :class:`_engine.Connection` with which to reflect tables with, if :paramref:`.AutomapBase.reflect` is True. :param reflect: legacy; use :paramref:`.AutomapBase.autoload_with`. Indicates that :meth:`_schema.MetaData.reflect` should be invoked. :param classname_for_table: callable function which will be used to produce new class names, given a table name. Defaults to :func:`.classname_for_table`. :param modulename_for_table: callable function which will be used to produce the effective ``__module__`` for an internally generated class, to allow for multiple classes of the same name in a single automap base which would be in different "modules". Defaults to ``None``, which will indicate that ``__module__`` will not be set explicitly; the Python runtime will use the value ``sqlalchemy.ext.automap`` for these classes. When assigning ``__module__`` to generated classes, they can be accessed based on dot-separated module names using the :attr:`.AutomapBase.by_module` collection. Classes that have an explicit ``__module_`` assigned using this hook do **not** get placed into the :attr:`.AutomapBase.classes` collection, only into :attr:`.AutomapBase.by_module`. .. versionadded:: 2.0 .. seealso:: :ref:`automap_by_module` :param name_for_scalar_relationship: callable function which will be used to produce relationship names for scalar relationships. Defaults to :func:`.name_for_scalar_relationship`. :param name_for_collection_relationship: callable function which will be used to produce relationship names for collection-oriented relationships. Defaults to :func:`.name_for_collection_relationship`. :param generate_relationship: callable function which will be used to actually generate :func:`_orm.relationship` and :func:`.backref` constructs. Defaults to :func:`.generate_relationship`. :param collection_class: the Python collection class that will be used when a new :func:`_orm.relationship` object is created that represents a collection. Defaults to ``list``. :param schema: Schema name to reflect when reflecting tables using the :paramref:`.AutomapBase.prepare.autoload_with` parameter. The name is passed to the :paramref:`_schema.MetaData.reflect.schema` parameter of :meth:`_schema.MetaData.reflect`. When omitted, the default schema in use by the database connection is used. .. note:: The :paramref:`.AutomapBase.prepare.schema` parameter supports reflection of a single schema at a time. In order to include tables from many schemas, use multiple calls to :meth:`.AutomapBase.prepare`. For an overview of multiple-schema automap including the use of additional naming conventions to resolve table name conflicts, see the section :ref:`automap_by_module`. .. versionadded:: 2.0 :meth:`.AutomapBase.prepare` supports being directly invoked any number of times, keeping track of tables that have already been processed to avoid processing them a second time. :param reflection_options: When present, this dictionary of options will be passed to :meth:`_schema.MetaData.reflect` to supply general reflection-specific options like ``only`` and/or dialect-specific options like ``oracle_resolve_synonyms``. .. versionadded:: 1.4 """ for mr in cls.__mro__: if "_sa_automapbase_bookkeeping" in mr.__dict__: automap_base = cast("Type[AutomapBase]", mr) break else: assert False, "Can't locate automap base in class hierarchy" glbls = globals() if classname_for_table is None: classname_for_table = glbls["classname_for_table"] if name_for_scalar_relationship is None: name_for_scalar_relationship = glbls[ "name_for_scalar_relationship" ] if name_for_collection_relationship is None: name_for_collection_relationship = glbls[ "name_for_collection_relationship" ] if generate_relationship is None: generate_relationship = glbls["generate_relationship"] if collection_class is None: collection_class = list if autoload_with: reflect = True if engine: autoload_with = engine if reflect: assert autoload_with opts = dict( schema=schema, extend_existing=True, autoload_replace=False, ) if reflection_options: opts.update(reflection_options) cls.metadata.reflect(autoload_with, **opts) # type: ignore[arg-type] # noqa: E501 with _CONFIGURE_MUTEX: table_to_map_config: Union[ Dict[Optional[Table], _DeferredDeclarativeConfig], Dict[Table, _DeferredDeclarativeConfig], ] = { cast("Table", m.local_table): m for m in _DeferredDeclarativeConfig.classes_for_base( cls, sort=False ) } many_to_many: List[ Tuple[Table, Table, List[ForeignKeyConstraint], Table] ] many_to_many = [] bookkeeping = automap_base._sa_automapbase_bookkeeping metadata_tables = cls.metadata.tables for table_key in set(metadata_tables).difference( bookkeeping.table_keys ): table = metadata_tables[table_key] bookkeeping.table_keys.add(table_key) lcl_m2m, rem_m2m, m2m_const = _is_many_to_many(cls, table) if lcl_m2m is not None: assert rem_m2m is not None assert m2m_const is not None many_to_many.append((lcl_m2m, rem_m2m, m2m_const, table)) elif not table.primary_key: continue elif table not in table_to_map_config: clsdict: Dict[str, Any] = {"__table__": table} if modulename_for_table is not None: new_module = modulename_for_table( cls, table.name, table ) if new_module is not None: clsdict["__module__"] = new_module else: new_module = None newname = classname_for_table(cls, table.name, table) if new_module is None and newname in cls.classes: util.warn( "Ignoring duplicate class name " f"'{newname}' " "received in automap base for table " f"{table.key} without " "``__module__`` being set; consider using the " "``modulename_for_table`` hook" ) continue mapped_cls = type( newname, (automap_base,), clsdict, ) map_config = _DeferredDeclarativeConfig.config_for_cls( mapped_cls ) assert map_config.cls.__name__ == newname if new_module is None: cls.classes[newname] = mapped_cls by_module_properties: ByModuleProperties = cls.by_module for token in map_config.cls.__module__.split("."): if token not in by_module_properties: by_module_properties[token] = util.Properties({}) props = by_module_properties[token] # we can assert this because the clsregistry # module would have raised if there was a mismatch # between modules/classes already. # see test_cls_schema_name_conflict assert isinstance(props, Properties) by_module_properties = props by_module_properties[map_config.cls.__name__] = mapped_cls table_to_map_config[table] = map_config for map_config in table_to_map_config.values(): _relationships_for_fks( automap_base, map_config, table_to_map_config, collection_class, name_for_scalar_relationship, name_for_collection_relationship, generate_relationship, ) for lcl_m2m, rem_m2m, m2m_const, table in many_to_many: _m2m_relationship( automap_base, lcl_m2m, rem_m2m, m2m_const, table, table_to_map_config, collection_class, name_for_scalar_relationship, name_for_collection_relationship, generate_relationship, ) for map_config in _DeferredDeclarativeConfig.classes_for_base( automap_base ): map_config.map() _sa_decl_prepare = True """Indicate that the mapping of classes should be deferred. The presence of this attribute name indicates to declarative that the call to mapper() should not occur immediately; instead, information about the table and attributes to be mapped are gathered into an internal structure called _DeferredMapperConfig. These objects can be collected later using classes_for_base(), additional mapping decisions can be made, and then the map() method will actually apply the mapping. The only real reason this deferral of the whole thing is needed is to support primary key columns that aren't reflected yet when the class is declared; everything else can theoretically be added to the mapper later. However, the _DeferredMapperConfig is a nice interface in any case which exists at that not usually exposed point at which declarative has the class and the Table but hasn't called mapper() yet. """ @classmethod def _sa_raise_deferred_config(cls) -> NoReturn: raise orm_exc.UnmappedClassError( cls, msg="Class %s is a subclass of AutomapBase. " "Mappings are not produced until the .prepare() " "method is called on the class hierarchy." % orm_exc._safe_cls_name(cls), ) @dataclasses.dataclass
AutomapBase
python
tqdm__tqdm
tests/tests_itertools.py
{ "start": 156, "end": 628 }
class ____(object): def __init__(self, iterable): self._it = iterable def __iter__(self): for i in self._it: yield i def test_product(): """Test contrib.itertools.product""" with closing(StringIO()) as our_file: a = range(9) assert list(product(a, a[::-1], file=our_file)) == list(it.product(a, a[::-1])) assert list(product(a, NoLenIter(a), file=our_file)) == list(it.product(a, NoLenIter(a)))
NoLenIter
python
python-openxml__python-docx
src/docx/opc/pkgreader.py
{ "start": 6410, "end": 8640 }
class ____: """Value object representing a serialized relationship in an OPC package. Serialized, in this case, means any target part is referred to via its partname rather than a direct link to an in-memory |Part| object. """ def __init__(self, baseURI, rel_elm): super(_SerializedRelationship, self).__init__() self._baseURI = baseURI self._rId = rel_elm.rId self._reltype = rel_elm.reltype self._target_mode = rel_elm.target_mode self._target_ref = rel_elm.target_ref @property def is_external(self): """True if target_mode is ``RTM.EXTERNAL``""" return self._target_mode == RTM.EXTERNAL @property def reltype(self): """Relationship type, like ``RT.OFFICE_DOCUMENT``""" return self._reltype @property def rId(self): """Relationship id, like 'rId9', corresponds to the ``Id`` attribute on the ``CT_Relationship`` element.""" return self._rId @property def target_mode(self): """String in ``TargetMode`` attribute of ``CT_Relationship`` element, one of ``RTM.INTERNAL`` or ``RTM.EXTERNAL``.""" return self._target_mode @property def target_ref(self): """String in ``Target`` attribute of ``CT_Relationship`` element, a relative part reference for internal target mode or an arbitrary URI, e.g. an HTTP URL, for external target mode.""" return self._target_ref @property def target_partname(self): """|PackURI| instance containing partname targeted by this relationship. Raises ``ValueError`` on reference if target_mode is ``'External'``. Use :attr:`target_mode` to check before referencing. """ if self.is_external: msg = ( "target_partname attribute on Relationship is undefined w" 'here TargetMode == "External"' ) raise ValueError(msg) # lazy-load _target_partname attribute if not hasattr(self, "_target_partname"): self._target_partname = PackURI.from_rel_ref(self._baseURI, self.target_ref) return self._target_partname
_SerializedRelationship
python
scikit-learn__scikit-learn
sklearn/exceptions.py
{ "start": 2772, "end": 3318 }
class ____(UserWarning): """Custom warning to notify potential issues with data dimensionality. For example, in random projection, this warning is raised when the number of components, which quantifies the dimensionality of the target projection space, is higher than the number of features, which quantifies the dimensionality of the original source space, to imply that the dimensionality of the problem will not be reduced. .. versionchanged:: 0.18 Moved from sklearn.utils. """
DataDimensionalityWarning
python
pytest-dev__pytest-xdist
testing/acceptance_test.py
{ "start": 41949, "end": 45354 }
class ____: def test_by_module(self, pytester: pytest.Pytester) -> None: test_file = """ import pytest class TestA: @pytest.mark.parametrize('i', range(10)) def test(self, i): pass class TestB: @pytest.mark.parametrize('i', range(10)) def test(self, i): pass """ pytester.makepyfile(test_a=test_file, test_b=test_file) result = pytester.runpytest("-n2", "--dist=loadfile", "-v") test_a_workers_and_test_count = get_workers_and_test_count_by_prefix( "test_a.py::TestA", result.outlines ) test_b_workers_and_test_count = get_workers_and_test_count_by_prefix( "test_b.py::TestB", result.outlines ) assert test_a_workers_and_test_count in ( {"gw0": 10}, {"gw1": 0}, ) or test_a_workers_and_test_count in ({"gw0": 0}, {"gw1": 10}) assert test_b_workers_and_test_count in ( {"gw0": 10}, {"gw1": 0}, ) or test_b_workers_and_test_count in ({"gw0": 0}, {"gw1": 10}) def test_by_class(self, pytester: pytest.Pytester) -> None: pytester.makepyfile( test_a=""" import pytest class TestA: @pytest.mark.parametrize('i', range(10)) def test(self, i): pass class TestB: @pytest.mark.parametrize('i', range(10)) def test(self, i): pass """ ) result = pytester.runpytest("-n2", "--dist=loadfile", "-v") test_a_workers_and_test_count = get_workers_and_test_count_by_prefix( "test_a.py::TestA", result.outlines ) test_b_workers_and_test_count = get_workers_and_test_count_by_prefix( "test_a.py::TestB", result.outlines ) assert test_a_workers_and_test_count in ( {"gw0": 10}, {"gw1": 0}, ) or test_a_workers_and_test_count in ({"gw0": 0}, {"gw1": 10}) assert test_b_workers_and_test_count in ( {"gw0": 10}, {"gw1": 0}, ) or test_b_workers_and_test_count in ({"gw0": 0}, {"gw1": 10}) def test_module_single_start(self, pytester: pytest.Pytester) -> None: """Fix test suite never finishing in case all workers start with a single test (#277).""" test_file1 = """ import pytest def test(): pass """ test_file2 = """ import pytest def test_1(): pass def test_2(): pass """ pytester.makepyfile(test_a=test_file1, test_b=test_file1, test_c=test_file2) result = pytester.runpytest("-n2", "--dist=loadfile", "-v") a = get_workers_and_test_count_by_prefix("test_a.py::test", result.outlines) b = get_workers_and_test_count_by_prefix("test_b.py::test", result.outlines) c1 = get_workers_and_test_count_by_prefix("test_c.py::test_1", result.outlines) c2 = get_workers_and_test_count_by_prefix("test_c.py::test_2", result.outlines) assert a in ({"gw0": 1}, {"gw1": 1}) assert b in ({"gw0": 1}, {"gw1": 1}) assert a.items() != b.items() assert c1 == c2
TestFileScope
python
catalyst-team__catalyst
tests/catalyst/runners/test_reid.py
{ "start": 5789, "end": 11469 }
class ____(dl.SupervisedRunner): """Custom runner for metric learning pipeline""" def handle_batch(self, batch: Dict[str, torch.Tensor]) -> None: """ Handle batch for train and valid loaders Args: batch: batch to process """ if self.is_train_loader: images, targets = batch["features"].float(), batch["targets"].long() features = self.model(images) self.batch = { "embeddings": features, "targets": targets, "images": images, } else: images, targets, is_query = ( batch["features"].float(), batch["targets"].long(), batch["is_query"].bool(), ) features = self.model(images) self.batch = { "embeddings": features, "targets": targets, "is_query": is_query, } def test_metric_learning_pipeline(): """ Test if classification pipeline can run and compute metrics. In this test we check that LoaderMetricCallback works with CMCMetric (ICallbackLoaderMetric). """ with TemporaryDirectory() as tmp_dir: dataset_train = MnistMLDataset(root=tmp_dir, download=True) sampler = BatchBalanceClassSampler( labels=dataset_train.get_labels(), num_classes=3, num_samples=10, num_batches=10, ) train_loader = DataLoader( dataset=dataset_train, batch_sampler=sampler, num_workers=0 ) dataset_val = MnistQGDataset(root=tmp_dir, gallery_fraq=0.2) val_loader = DataLoader(dataset=dataset_val, batch_size=1024) model = DummyModel(num_features=28 * 28, num_classes=NUM_CLASSES) optimizer = Adam(model.parameters(), lr=0.001) sampler_inbatch = HardTripletsSampler(norm_required=False) criterion = TripletMarginLossWithSampler( margin=0.5, sampler_inbatch=sampler_inbatch ) callbacks = OrderedDict( { "cmc": dl.ControlFlowCallbackWrapper( dl.CMCScoreCallback( embeddings_key="embeddings", labels_key="targets", is_query_key="is_query", topk=[1], ), loaders="valid", ), "control": dl.PeriodicLoaderCallback( valid_loader_key="valid", valid_metric_key="cmc", minimize=False, valid=2, ), } ) runner = CustomRunner(input_key="features", output_key="embeddings") runner.train( model=model, criterion=criterion, optimizer=optimizer, callbacks=callbacks, loaders=OrderedDict({"train": train_loader, "valid": val_loader}), verbose=False, valid_loader="valid", num_epochs=4, ) assert "cmc01" in runner.loader_metrics def test_reid_pipeline(): """This test checks that reid pipeline runs and compute metrics with ReidCMCScoreCallback""" with TemporaryDirectory() as logdir: # 1. train and valid loaders train_dataset = MnistMLDataset(root=DATA_ROOT) sampler = BatchBalanceClassSampler( labels=train_dataset.get_labels(), num_classes=3, num_samples=10, num_batches=20, ) train_loader = DataLoader( dataset=train_dataset, batch_sampler=sampler, num_workers=0 ) valid_dataset = MnistReIDQGDataset(root=DATA_ROOT, gallery_fraq=0.2) valid_loader = DataLoader(dataset=valid_dataset, batch_size=1024) # 2. model and optimizer model = MnistSimpleNet(out_features=16) optimizer = Adam(model.parameters(), lr=0.001) # 3. criterion with triplets sampling sampler_inbatch = AllTripletsSampler(max_output_triplets=1000) criterion = TripletMarginLossWithSampler( margin=0.5, sampler_inbatch=sampler_inbatch ) # 4. training with catalyst Runner callbacks = [ dl.ControlFlowCallbackWrapper( dl.CriterionCallback( input_key="embeddings", target_key="targets", metric_key="loss" ), loaders="train", ), dl.ControlFlowCallbackWrapper( dl.ReidCMCScoreCallback( embeddings_key="embeddings", pids_key="targets", cids_key="cids", is_query_key="is_query", topk=[1], ), loaders="valid", ), dl.PeriodicLoaderCallback( valid_loader_key="valid", valid_metric_key="cmc01", minimize=False, valid=2, ), ] runner = ReIDCustomRunner() runner.train( model=model, criterion=criterion, optimizer=optimizer, callbacks=callbacks, loaders=OrderedDict({"train": train_loader, "valid": valid_loader}), verbose=False, logdir=logdir, valid_loader="valid", valid_metric="cmc01", minimize_valid_metric=False, num_epochs=10, ) assert "cmc01" in runner.loader_metrics assert runner.loader_metrics["cmc01"] > 0.65
CustomRunner
python
kamyu104__LeetCode-Solutions
Python/split-array-with-same-average.py
{ "start": 33, "end": 849 }
class ____(object): def splitArraySameAverage(self, A): """ :type A: List[int] :rtype: bool """ def possible(total, n): for i in xrange(1, n//2+1): if total*i%n == 0: return True return False n, s = len(A), sum(A) if not possible(n, s): return False sums = [set() for _ in xrange(n//2+1)] sums[0].add(0) for num in A: # O(n) times for i in reversed(xrange(1, n//2+1)): # O(n) times for prev in sums[i-1]: # O(1) + O(2) + ... O(n/2) = O(n^2) times sums[i].add(prev+num) for i in xrange(1, n//2+1): if s*i%n == 0 and s*i//n in sums[i]: return True return False
Solution
python
jupyterlab__jupyterlab
jupyterlab/commands.py
{ "start": 19708, "end": 86137 }
class ____: def __init__(self, options): """Create a new _AppHandler object""" options = _ensure_options(options) self._options = options self.app_dir = options.app_dir self.sys_dir = get_app_dir() if options.use_sys_dir else self.app_dir self.logger = options.logger # Make a deep copy of the core data so we don't influence the original copy self.core_data = deepcopy(options.core_config._data) self.labextensions_path = options.labextensions_path self.verbose = options.verbose self.kill_event = options.kill_event self.registry = options.registry self.skip_full_build_check = options.skip_full_build_check # Do this last since it relies on other attributes self.info = self._get_app_info() # Migrate from 4.0 which did not have "locked" status try: self._maybe_mirror_disabled_in_locked(level="sys_prefix") except (PermissionError, OSError): try: self.logger.info( "`sys_prefix` level settings are read-only, using `user` level for migration to `lockedExtensions`" ) self._maybe_mirror_disabled_in_locked(level="user") except (PermissionError, OSError): self.logger.warning( "Both `sys_prefix` and `user` level settings are read-only, cannot auto-migrate `disabledExtensions` to `lockedExtensions`" ) def install_extension(self, extension, existing=None, pin=None): """Install an extension package into JupyterLab. The extension is first validated. Returns `True` if a rebuild is recommended, `False` otherwise. """ extension = _normalize_path(extension) extensions = self.info["extensions"] # Check for a core extensions. if extension in self.info["core_extensions"]: config = self._read_build_config() uninstalled = config.get("uninstalled_core_extensions", []) if extension in uninstalled: self.logger.info(f"Installing core extension {extension}") uninstalled.remove(extension) config["uninstalled_core_extensions"] = uninstalled self._write_build_config(config) return True return False # Create the app dirs if needed. self._ensure_app_dirs() # Install the package using a temporary directory. with TemporaryDirectory() as tempdir: info = self._install_extension(extension, tempdir, pin=pin) name = info["name"] # Local directories get name mangled and stored in metadata. if info["is_dir"]: config = self._read_build_config() local = config.setdefault("local_extensions", {}) local[name] = info["source"] self._write_build_config(config) # Remove an existing extension with the same name and different path if name in extensions: other = extensions[name] if other["path"] != info["path"] and other["location"] == "app": os.remove(other["path"]) return True def build( self, name=None, version=None, static_url=None, clean_staging=False, production=True, minimize=True, ): """Build the application.""" if production is None: production = not (self.info["linked_packages"] or self.info["local_extensions"]) if not production: minimize = False # If splicing, make sure the source packages are built if self._options.splice_source: ensure_node_modules(REPO_ROOT, logger=self.logger) self._run(["node", YARN_PATH, "build:packages"], cwd=REPO_ROOT) info = ["production" if production else "development"] if production: info.append("minimized" if minimize else "not minimized") self.logger.info(f"Building jupyterlab assets ({', '.join(info)})") # Set up the build directory. app_dir = self.app_dir self._populate_staging( name=name, version=version, static_url=static_url, clean=clean_staging ) staging = pjoin(app_dir, "staging") # Make sure packages are installed. ret = self._run(["node", YARN_PATH, "install"], cwd=staging) if ret != 0: msg = "npm dependencies failed to install" self.logger.debug(msg) raise RuntimeError(msg) # Build the app. dedupe_yarn(staging, self.logger) command = f"build:{'prod' if production else 'dev'}{':minimize' if minimize else ''}" ret = self._run(["node", YARN_PATH, "run", command], cwd=staging) if ret != 0: msg = "JupyterLab failed to build" self.logger.debug(msg) raise RuntimeError(msg) def watch(self): """Start the application watcher and then run the watch in the background. """ staging = pjoin(self.app_dir, "staging") self._populate_staging() # Make sure packages are installed. self._run(["node", YARN_PATH, "install"], cwd=staging) dedupe_yarn(staging, self.logger) proc = WatchHelper( ["node", YARN_PATH, "run", "watch"], cwd=pjoin(self.app_dir, "staging"), startup_regex=WEBPACK_EXPECT, logger=self.logger, ) return [proc] def list_extensions(self): # noqa """Print an output of the extensions.""" self._ensure_disabled_info() logger = self.logger info = self.info version = info["version"] logger.info(f"JupyterLab v{version}") if info["federated_extensions"] or info["extensions"]: info["compat_errors"] = self._get_extension_compat() if info["federated_extensions"]: self._list_federated_extensions() if info["extensions"]: logger.info("Other labextensions (built into JupyterLab)") self._list_extensions(info, "app") self._list_extensions(info, "sys") local = info["local_extensions"] if local: logger.info("\n local extensions:") for name in sorted(local): logger.info(f" {name}: {local[name]}") linked_packages = info["linked_packages"] if linked_packages: logger.info("\n linked packages:") for key in sorted(linked_packages): source = linked_packages[key]["source"] logger.info(f" {key}: {source}") uninstalled_core = info["uninstalled_core"] if uninstalled_core: logger.info("\nUninstalled core extensions:") [logger.info(f" {item}") for item in sorted(uninstalled_core)] all_exts = ( list(info["federated_extensions"]) + list(info["extensions"]) + list(info["core_extensions"]) ) # Ignore disabled extensions that are not installed disabled = [i for i in info["disabled"] if i.partition(":")[0] in all_exts] if disabled: logger.info("\nDisabled extensions:") for item in sorted(disabled): # Show that all plugins will be disabled if the whole extension matches if item in all_exts: item += " (all plugins)" # noqa PLW2901 logger.info(f" {item}") # Here check if modules are improperly shadowed improper_shadowed = [] for ext_name in self.info["shadowed_exts"]: source_version = self.info["extensions"][ext_name]["version"] prebuilt_version = self.info["federated_extensions"][ext_name]["version"] if not gte(prebuilt_version, source_version, True): improper_shadowed.append(ext_name) if improper_shadowed: logger.info( "\nThe following source extensions are overshadowed by older prebuilt extensions:" ) [logger.info(f" {name}") for name in sorted(improper_shadowed)] messages = self.build_check(fast=True) if messages: logger.info("\nBuild recommended, please run `jupyter lab build`:") [logger.info(f" {item}") for item in messages] def build_check(self, fast=None): # noqa """Determine whether JupyterLab should be built. Returns a list of messages. """ if fast is None: fast = self.skip_full_build_check app_dir = self.app_dir local = self.info["local_extensions"] linked = self.info["linked_packages"] messages = [] # Check for no application. pkg_path = pjoin(app_dir, "static", "package.json") if not osp.exists(pkg_path): return ["No built application"] static_data = self.info["static_data"] old_jlab = static_data["jupyterlab"] old_deps = static_data.get("dependencies", {}) # Look for mismatched version. static_version = old_jlab.get("version", "") if not static_version.endswith("-spliced"): core_version = old_jlab["version"] if Version(static_version) != Version(core_version): msg = f"Version mismatch: {static_version} (built), {core_version} (current)" return [msg] shadowed_exts = self.info["shadowed_exts"] # Look for mismatched extensions. new_package = self._get_package_template(silent=fast) new_jlab = new_package["jupyterlab"] new_deps = new_package.get("dependencies", {}) for ext_type in ["extensions", "mimeExtensions"]: # Extensions that were added. for ext in new_jlab[ext_type]: if ext in shadowed_exts: continue if ext not in old_jlab[ext_type]: messages.append(f"{ext} needs to be included in build") # Extensions that were removed. for ext in old_jlab[ext_type]: if ext in shadowed_exts: continue if ext not in new_jlab[ext_type]: messages.append(f"{ext} needs to be removed from build") # Look for mismatched dependencies src_pkg_dir = pjoin(REPO_ROOT, "packages") for pkg, dep in new_deps.items(): if old_deps.get(pkg, "").startswith(src_pkg_dir): continue if pkg not in old_deps: continue # Skip local and linked since we pick them up separately. if pkg in local or pkg in linked: continue if old_deps[pkg] != dep: msg = f"{pkg} changed from {old_deps[pkg]} to {new_deps[pkg]}" messages.append(msg) # Look for updated local extensions. for name, source in local.items(): if fast or name in shadowed_exts: continue dname = pjoin(app_dir, "extensions") if self._check_local(name, source, dname): messages.append(f"{name} content changed") # Look for updated linked packages. for name, item in linked.items(): if fast or name in shadowed_exts: continue dname = pjoin(app_dir, "staging", "linked_packages") if self._check_local(name, item["source"], dname): messages.append(f"{name} content changed") return messages def uninstall_extension(self, name): """Uninstall an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ info = self.info logger = self.logger if name in info["federated_extensions"]: if ( info["federated_extensions"][name] .get("install", {}) .get("uninstallInstructions", None) ): instructions = info["federated_extensions"][name]["install"][ "uninstallInstructions" ] logger.error(f"JupyterLab cannot uninstall this extension. {instructions}") else: logger.error( f"JupyterLab cannot uninstall {name} since it was installed outside of JupyterLab. Use the same method used to install this extension to uninstall this extension." ) return False # Allow for uninstalled core extensions. if name in info["core_extensions"]: config = self._read_build_config() uninstalled = config.get("uninstalled_core_extensions", []) if name not in uninstalled: logger.info(f"Uninstalling core extension {name}") uninstalled.append(name) config["uninstalled_core_extensions"] = uninstalled self._write_build_config(config) return True return False local = info["local_extensions"] for extname, data in info["extensions"].items(): path = data["path"] if extname == name: msg = f"Uninstalling {name} from {osp.dirname(path)}" logger.info(msg) os.remove(path) # Handle local extensions. if extname in local: config = self._read_build_config() data = config.setdefault("local_extensions", {}) # noqa PLW2901 del data[extname] self._write_build_config(config) return True logger.warning(f'No labextension named "{name}" installed') return False def uninstall_all_extensions(self): """Uninstalls all extensions Returns `True` if a rebuild is recommended, `False` otherwise """ should_rebuild = False for extname, _ in self.info["extensions"].items(): uninstalled = self.uninstall_extension(extname) should_rebuild = should_rebuild or uninstalled return should_rebuild def update_all_extensions(self): """Update all non-local extensions. Returns `True` if a rebuild is recommended, `False` otherwise. """ should_rebuild = False for extname, _ in self.info["extensions"].items(): if extname in self.info["local_extensions"]: continue updated = self._update_extension(extname) # Rebuild if at least one update happens: should_rebuild = should_rebuild or updated return should_rebuild def update_extension(self, name): """Update an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ if name not in self.info["extensions"]: self.logger.warning(f'No labextension named "{name}" installed') return False return self._update_extension(name) def _update_extension(self, name): """Update an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ data = self.info["extensions"][name] if data["alias_package_source"]: self.logger.warning(f"Skipping updating pinned extension '{name}'.") return False try: latest = self._latest_compatible_package_version(name) except URLError: return False if latest is None: self.logger.warning(f"No compatible version found for {name}!") return False if latest == data["version"]: self.logger.info(f"Extension {name!r} already up to date") return False self.logger.info(f"Updating {name} to version {latest}") return self.install_extension(f"{name}@{latest}") def link_package(self, path): """Link a package at the given path. Returns `True` if a rebuild is recommended, `False` otherwise. """ path = _normalize_path(path) if not osp.exists(path) or not osp.isdir(path): msg = f'Cannot install "{path}" only link local directories' raise ValueError(msg) with TemporaryDirectory() as tempdir: info = self._extract_package(path, tempdir) messages = _validate_extension(info["data"]) if not messages: return self.install_extension(path) # Warn that it is a linked package. self.logger.warning( f"Installing {path} as a linked package because it does not have extension metadata:" ) [self.logger.warning(f" {m}") for m in messages] # Add to metadata. config = self._read_build_config() linked = config.setdefault("linked_packages", {}) linked[info["name"]] = info["source"] self._write_build_config(config) return True def unlink_package(self, path): """Unlink a package by name or at the given path. A ValueError is raised if the path is not an unlinkable package. Returns `True` if a rebuild is recommended, `False` otherwise. """ path = _normalize_path(path) config = self._read_build_config() linked = config.setdefault("linked_packages", {}) found = None for name, source in linked.items(): if path in {name, source}: found = name if found: del linked[found] else: local = config.setdefault("local_extensions", {}) for name, source in local.items(): if path in {name, source}: found = name if found: del local[found] path = self.info["extensions"][found]["path"] os.remove(path) if not found: msg = f"No linked package for {path}" raise ValueError(msg) self._write_build_config(config) return True def _is_extension_locked(self, extension, level="sys_prefix", include_higher_levels=True): app_settings_dir = osp.join(self.app_dir, "settings") page_config = get_static_page_config( app_settings_dir=app_settings_dir, logger=self.logger, level=level, include_higher_levels=True, ) locked = page_config.get("lockedExtensions", {}) return locked.get(extension, False) def toggle_extension(self, extension, value, level="sys_prefix"): """Enable or disable a lab extension. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_settings_dir = osp.join(self.app_dir, "settings") # If extension is locked at a higher level, we don't toggle it. # The highest level at which an extension can be locked is system, # so we do not need to check levels above that one. if level != "system": allowed = get_allowed_levels() if self._is_extension_locked( extension, level=allowed[allowed.index(level) + 1], include_higher_levels=True ): self.logger.info("Extension locked at a higher level, cannot toggle status") return False complete_page_config = get_static_page_config( app_settings_dir=app_settings_dir, logger=self.logger, level="all" ) level_page_config = get_static_page_config( app_settings_dir=app_settings_dir, logger=self.logger, level=level ) disabled = complete_page_config.get("disabledExtensions", {}) disabled_at_level = level_page_config.get("disabledExtensions", {}) did_something = False is_disabled = disabled.get(extension, False) if value and not is_disabled: disabled_at_level[extension] = True did_something = True elif not value and is_disabled: disabled_at_level[extension] = False did_something = True if did_something: level_page_config["disabledExtensions"] = disabled_at_level write_page_config(level_page_config, level=level) return did_something def _maybe_mirror_disabled_in_locked(self, level="sys_prefix"): """Lock all extensions that were previously disabled. This exists to facilitate migration from 4.0 (which did not include lock function) to 4.1 which exposes the plugin management to users in UI. Returns `True` if migration happened, `False` otherwise. """ app_settings_dir = osp.join(self.app_dir, "settings") page_config = get_static_page_config( app_settings_dir=app_settings_dir, logger=self.logger, level=level ) if "lockedExtensions" in page_config: # short-circuit if migration already happened return False # copy disabled onto lockedExtensions, ensuring the mapping format disabled = page_config.get("disabledExtensions", {}) if isinstance(disabled, list): disabled = dict.fromkeys(disabled, True) # Short circuit if disabled is empty if not disabled: return False page_config["lockedExtensions"] = disabled write_page_config(page_config, level=level) return True def toggle_extension_lock(self, extension, value, level="sys_prefix"): """Lock or unlock a lab extension (/plugin).""" app_settings_dir = osp.join(self.app_dir, "settings") # The highest level at which an extension can be locked is system, # so we do not need to check levels above that one. if level != "system": allowed = get_allowed_levels() if self._is_extension_locked( extension, level=allowed[allowed.index(level) + 1], include_higher_levels=True ): self.logger.info("Extension locked at a higher level, cannot toggle") return False page_config = get_static_page_config( app_settings_dir=app_settings_dir, logger=self.logger, level=level ) locked = page_config.get("lockedExtensions", {}) locked[extension] = value page_config["lockedExtensions"] = locked write_page_config(page_config, level=level) def check_extension(self, extension, check_installed_only=False): """Check if a lab extension is enabled or disabled""" self._ensure_disabled_info() info = self.info if extension in info["core_extensions"]: return self._check_core_extension(extension, info, check_installed_only) if extension in info["linked_packages"]: self.logger.info(f"{extension}:{GREEN_ENABLED}") return True return self._check_common_extension(extension, info, check_installed_only) def _check_core_extension(self, extension, info, check_installed_only): """Check if a core extension is enabled or disabled""" if extension in info["uninstalled_core"]: self.logger.info(f"{extension}:{RED_X}") return False if check_installed_only: self.logger.info(f"{extension}: {GREEN_OK}") return True if extension in info["disabled_core"]: self.logger.info(f"{extension}: {RED_DISABLED}") return False self.logger.info(f"{extension}:{GREEN_ENABLED}") return True def _check_common_extension(self, extension, info, check_installed_only): """Check if a common (non-core) extension is enabled or disabled""" if extension not in info["extensions"]: self.logger.info(f"{extension}:{RED_X}") return False errors = self._get_extension_compat()[extension] if errors: self.logger.info(f"{extension}:{RED_X} (compatibility errors)") return False if check_installed_only: self.logger.info(f"{extension}: {GREEN_OK}") return True if _is_disabled(extension, info["disabled"]): self.logger.info(f"{extension}: {RED_DISABLED}") return False self.logger.info(f"{extension}:{GREEN_ENABLED}") return True def _get_app_info(self): """Get information about the app.""" info = {} info["core_data"] = core_data = self.core_data info["extensions"] = extensions = self._get_extensions(core_data) info["local_extensions"] = self._get_local_extensions() info["linked_packages"] = self._get_linked_packages() info["app_extensions"] = app = [] info["sys_extensions"] = sys = [] for name, data in extensions.items(): data["is_local"] = name in info["local_extensions"] if data["location"] == "app": app.append(name) else: sys.append(name) info["uninstalled_core"] = self._get_uninstalled_core_extensions() info["static_data"] = _get_static_data(self.app_dir) app_data = info["static_data"] or core_data info["version"] = app_data["jupyterlab"]["version"] info["staticUrl"] = app_data["jupyterlab"].get("staticUrl", "") info["sys_dir"] = self.sys_dir info["app_dir"] = self.app_dir info["core_extensions"] = _get_core_extensions(self.core_data) info["federated_extensions"] = get_federated_extensions(self.labextensions_path) info["shadowed_exts"] = [ ext for ext in info["extensions"] if ext in info["federated_extensions"] ] return info def _ensure_disabled_info(self): info = self.info if "disabled" in info: return labextensions_path = self.labextensions_path app_settings_dir = osp.join(self.app_dir, "settings") page_config = get_page_config( labextensions_path, app_settings_dir=app_settings_dir, logger=self.logger ) disabled = page_config.get("disabledExtensions", {}) # handle disabledExtensions specified as a list (jupyterlab_server < 2.10) # see https://github.com/jupyterlab/jupyterlab_server/pull/192 for more info if isinstance(disabled, list): disabled = dict.fromkeys(disabled, True) info["disabled"] = disabled locked = page_config.get("lockedExtensions", {}) if isinstance(locked, list): locked = dict.fromkeys(locked, True) info["locked"] = locked disabled_core = [] for key in info["core_extensions"]: if key in info["disabled"]: disabled_core.append(key) info["disabled_core"] = disabled_core def _populate_staging(self, name=None, version=None, static_url=None, clean=False): # noqa """Set up the assets in the staging directory.""" app_dir = self.app_dir staging = pjoin(app_dir, "staging") if clean and osp.exists(staging): self.logger.info(f"Cleaning {staging}") _rmtree(staging, self.logger) self._ensure_app_dirs() if not version: version = self.info["core_data"]["jupyterlab"]["version"] splice_source = self._options.splice_source if splice_source: self.logger.debug("Splicing dev packages into app directory.") source_dir = DEV_DIR version = __version__ + "-spliced" else: source_dir = pjoin(HERE, "staging") # Look for mismatched version. pkg_path = pjoin(staging, "package.json") if osp.exists(pkg_path): with open(pkg_path) as fid: data = json.load(fid) if data["jupyterlab"].get("version", "") != version: _rmtree(staging, self.logger) os.makedirs(staging) for fname in [ "index.js", "bootstrap.js", "publicpath.js", "webpack.config.js", "webpack.prod.config.js", "webpack.prod.minimize.config.js", ]: target = pjoin(staging, fname) shutil.copy(pjoin(source_dir, fname), target) for fname in [".yarnrc.yml", "yarn.js"]: target = pjoin(staging, fname) shutil.copy(pjoin(HERE, "staging", fname), target) # Ensure a clean templates directory templates = pjoin(staging, "templates") if osp.exists(templates): _rmtree(templates, self.logger) try: shutil.copytree(pjoin(source_dir, "templates"), templates) except shutil.Error as error: # `copytree` throws an error if copying to + from NFS even though # the copy is successful (see https://bugs.python.org/issue24564 # and https://github.com/jupyterlab/jupyterlab/issues/5233) real_error = "[Errno 22]" not in str(error) and "[Errno 5]" not in str(error) if real_error or not osp.exists(templates): raise # Ensure a clean linked packages directory. linked_dir = pjoin(staging, "linked_packages") if osp.exists(linked_dir): _rmtree(linked_dir, self.logger) os.makedirs(linked_dir) # Template the package.json file. # Update the local extensions. extensions = self.info["extensions"] removed = False for key, source in self.info["local_extensions"].items(): # Handle a local extension that was removed. if key not in extensions: config = self._read_build_config() data = config.setdefault("local_extensions", {}) del data[key] self._write_build_config(config) removed = True continue dname = pjoin(app_dir, "extensions") self._update_local(key, source, dname, extensions[key], "local_extensions") # Update the list of local extensions if any were removed. if removed: self.info["local_extensions"] = self._get_local_extensions() # Update the linked packages. linked = self.info["linked_packages"] for key, item in linked.items(): dname = pjoin(staging, "linked_packages") self._update_local(key, item["source"], dname, item, "linked_packages") # Then get the package template. data = self._get_package_template() jlab = data["jupyterlab"] if version: jlab["version"] = version if name: jlab["name"] = name if static_url: jlab["staticUrl"] = static_url # Handle splicing of packages if splice_source: # Splice workspace tree as linked dependencies for path in glob(pjoin(REPO_ROOT, "packages", "*", "package.json")): local_path = osp.dirname(osp.abspath(path)) pkg_data = json.loads(Path(path).read_text(encoding="utf-8")) name = pkg_data["name"] if name in data["dependencies"]: data["dependencies"][name] = local_path jlab["linkedPackages"][name] = local_path if name in data["resolutions"]: data["resolutions"][name] = local_path # splice the builder as well local_path = osp.abspath(pjoin(REPO_ROOT, "builder")) data["devDependencies"]["@jupyterlab/builder"] = local_path target = osp.join(staging, "node_modules", "@jupyterlab", "builder") # Remove node_modules so it gets re-populated node_modules = pjoin(staging, "node_modules") if osp.exists(node_modules): shutil.rmtree(node_modules, ignore_errors=True) # Write the package file pkg_path = pjoin(staging, "package.json") with open(pkg_path, "w") as fid: json.dump(data, fid, indent=4) # copy known-good yarn.lock if missing lock_path = pjoin(staging, "yarn.lock") lock_template = pjoin(HERE, "staging", "yarn.lock") if not osp.exists(lock_path): shutil.copy(lock_template, lock_path) os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD) def _get_package_template(self, silent=False): # noqa """Get the template the for staging package.json file.""" logger = self.logger # make a deep copy of the data so we don't influence the core data data = deepcopy(self.info["core_data"]) local = self.info["local_extensions"] linked = self.info["linked_packages"] extensions = self.info["extensions"] shadowed_exts = self.info["shadowed_exts"] jlab = data["jupyterlab"] def format_path(path): path = osp.relpath(path, osp.abspath(osp.realpath(pjoin(self.app_dir, "staging")))) path = "file:" + path.replace(os.sep, "/") if os.name == "nt": path = path.lower() return path jlab["linkedPackages"] = {} # Handle local extensions. for key, source in local.items(): if key in shadowed_exts: continue jlab["linkedPackages"][key] = source data["resolutions"][key] = "file:" + self.info["extensions"][key]["path"] # Handle linked packages. for key, item in linked.items(): if key in shadowed_exts: continue path = pjoin(self.app_dir, "staging", "linked_packages") path = pjoin(path, item["filename"]) data["dependencies"][key] = format_path(path) jlab["linkedPackages"][key] = item["source"] data["resolutions"][key] = format_path(path) data["jupyterlab"]["extensionMetadata"] = {} # Handle extensions compat_errors = self._get_extension_compat() for key, value in extensions.items(): # Reject incompatible extensions with a message. errors = compat_errors[key] if errors: if not silent: _log_single_compat_errors(logger, key, value["version"], errors) continue data["dependencies"][key] = format_path(value["path"]) jlab_data = value["jupyterlab"] for item in ["extension", "mimeExtension"]: ext = jlab_data.get(item, False) if not ext: continue if ext is True: ext = "" jlab[item + "s"][key] = ext # Add metadata for the extension data["jupyterlab"]["extensionMetadata"][key] = jlab_data # Handle uninstalled core extensions. for item in self.info["uninstalled_core"]: if item in jlab["extensions"]: data["jupyterlab"]["extensions"].pop(item) elif item in jlab["mimeExtensions"]: data["jupyterlab"]["mimeExtensions"].pop(item) # Remove from dependencies as well. if item in data["dependencies"]: data["dependencies"].pop(item) return data def _check_local(self, name, source, dname): """Check if a local package has changed. `dname` is the directory name of existing package tar archives. """ # Extract the package in a temporary directory. with TemporaryDirectory() as tempdir: info = self._extract_package(source, tempdir) # Test if the file content has changed. # This relies on `_extract_package` adding the hashsum # to the filename, allowing a simple exist check to # compare the hash to the "cache" in dname. target = pjoin(dname, info["filename"]) return not osp.exists(target) def _update_local(self, name, source, dname, data, dtype): """Update a local dependency. Return `True` if changed.""" # Extract the package in a temporary directory. existing = data["filename"] if not osp.exists(pjoin(dname, existing)): existing = "" with TemporaryDirectory() as tempdir: info = self._extract_package(source, tempdir) # Bail if the file content has not changed. if info["filename"] == existing: return existing shutil.move(info["path"], pjoin(dname, info["filename"])) # Remove the previous tarball and return the new file name. if existing: os.remove(pjoin(dname, existing)) data["filename"] = info["filename"] data["path"] = pjoin(data["tar_dir"], data["filename"]) return info["filename"] def _get_extensions(self, core_data): """Get the extensions for the application.""" app_dir = self.app_dir extensions = {} # Get system level packages. sys_path = pjoin(self.sys_dir, "extensions") app_path = pjoin(self.app_dir, "extensions") extensions = self._get_extensions_in_dir(self.sys_dir, core_data) # Look in app_dir if different. app_path = pjoin(app_dir, "extensions") if app_path == sys_path or not osp.exists(app_path): return extensions extensions.update(self._get_extensions_in_dir(app_dir, core_data)) return extensions def _get_extensions_in_dir(self, dname, core_data): """Get the extensions in a given directory.""" extensions = {} location = "app" if dname == self.app_dir else "sys" for target in glob(pjoin(dname, "extensions", "*.tgz")): data = read_package(target) deps = data.get("dependencies", {}) name = data["name"] jlab = data.get("jupyterlab", {}) path = osp.abspath(target) filename = osp.basename(target) if filename.startswith(PIN_PREFIX): alias = filename[len(PIN_PREFIX) : -len(".tgz")] else: alias = None url = get_package_url(data) extensions[alias or name] = { "description": data.get("description", ""), "path": path, "filename": osp.basename(path), "url": url, "version": data["version"], # Only save the package name if the extension name is an alias "alias_package_source": name if alias else None, "jupyterlab": jlab, "dependencies": deps, "tar_dir": osp.dirname(path), "location": location, } return extensions def _get_extension_compat(self): """Get the extension compatibility info.""" compat = {} core_data = self.info["core_data"] seen = set() for name, data in self.info["federated_extensions"].items(): deps = data["dependencies"] compat[name] = _validate_compatibility(name, deps, core_data) seen.add(name) for name, data in self.info["extensions"].items(): if name in seen: continue deps = data["dependencies"] compat[name] = _validate_compatibility(name, deps, core_data) return compat def _get_local_extensions(self): """Get the locally installed extensions.""" return self._get_local_data("local_extensions") def _get_linked_packages(self): """Get the linked packages.""" info = self._get_local_data("linked_packages") dname = pjoin(self.app_dir, "staging", "linked_packages") for name, source in info.items(): info[name] = {"source": source, "filename": "", "tar_dir": dname} if not osp.exists(dname): return info for path in glob(pjoin(dname, "*.tgz")): path = osp.abspath(path) # noqa PLW2901 data = read_package(path) name = data["name"] if name not in info: self.logger.warning(f"Removing orphaned linked package {name}") os.remove(path) continue item = info[name] item["filename"] = osp.basename(path) item["path"] = path item["version"] = data["version"] item["data"] = data return info def _get_uninstalled_core_extensions(self): """Get the uninstalled core extensions.""" config = self._read_build_config() return config.get("uninstalled_core_extensions", []) def _ensure_app_dirs(self): """Ensure that the application directories exist""" dirs = ["extensions", "settings", "staging", "schemas", "themes"] for dname in dirs: path = pjoin(self.app_dir, dname) if not osp.exists(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise def _list_extensions(self, info, ext_type): """List the extensions of a given type.""" self._ensure_disabled_info() logger = self.logger names = info[f"{ext_type}_extensions"] if not names: return dname = info[f"{ext_type}_dir"] error_accumulator = {} logger.info(f" {ext_type} dir: {dname}") for name in sorted(names): if name in info["federated_extensions"]: continue data = info["extensions"][name] version = data["version"] errors = info["compat_errors"][name] extra = self._compose_extra_status(name, info, data, errors) # If we have the package name in the data, this means this extension's name is the alias name alias_package_source = data["alias_package_source"] if alias_package_source: logger.info(f" {name} {alias_package_source} v{version}{extra}") else: logger.info(f" {name} v{version}{extra}") if errors: error_accumulator[name] = (version, errors) # Write all errors at end: _log_multiple_compat_errors(logger, error_accumulator, self.verbose) # Write a blank line separator logger.info("") def _list_federated_extensions(self): self._ensure_disabled_info() info = self.info logger = self.logger error_accumulator = {} ext_dirs = dict.fromkeys(self.labextensions_path, False) for value in info["federated_extensions"].values(): ext_dirs[value["ext_dir"]] = True for ext_dir, has_exts in ext_dirs.items(): if not has_exts: continue logger.info(ext_dir) for name in info["federated_extensions"]: data = info["federated_extensions"][name] if data["ext_dir"] != ext_dir: continue version = data["version"] errors = info["compat_errors"][name] extra = self._compose_extra_status(name, info, data, errors) install = data.get("install") if install: extra += " ({}, {})".format(install["packageManager"], install["packageName"]) logger.info(f" {name} v{version}{extra}") if errors: error_accumulator[name] = (version, errors) # Add a spacer line after logger.info("") # Write all errors at end: _log_multiple_compat_errors(logger, error_accumulator, self.verbose) def _compose_extra_status(self, name: str, info: dict, data: dict, errors) -> str: extra = "" if _is_disabled(name, info["disabled"]): extra += f" {RED_DISABLED}" else: extra += f" {GREEN_ENABLED}" if errors: extra += f" {RED_X}" else: extra += f" {GREEN_OK}" if data["is_local"]: extra += "*" lock_status = _is_locked(name, info["locked"]) if lock_status.entire_extension_locked: extra += " 🔒 (all plugins locked)" elif lock_status.locked_plugins: plugin_list = ", ".join(sorted(lock_status.locked_plugins)) extra += f" 🔒 (plugins: {plugin_list} locked)" return extra def _read_build_config(self): """Get the build config data for the app dir.""" target = pjoin(self.app_dir, "settings", "build_config.json") if not osp.exists(target): return {} else: with open(target) as fid: return json.load(fid) def _write_build_config(self, config): """Write the build config to the app dir.""" self._ensure_app_dirs() target = pjoin(self.app_dir, "settings", "build_config.json") with open(target, "w") as fid: json.dump(config, fid, indent=4) def _get_local_data(self, source): """Get the local data for extensions or linked packages.""" config = self._read_build_config() data = config.setdefault(source, {}) dead = [] for name, source_ in data.items(): if not osp.exists(source_): dead.append(name) for name in dead: link_type = source.replace("_", " ") msg = f'**Note: Removing dead {link_type} "{name}"' self.logger.warning(msg) del data[name] if dead: self._write_build_config(config) return data def _install_extension(self, extension, tempdir, pin=None): """Install an extension with validation and return the name and path.""" info = self._extract_package(extension, tempdir, pin=pin) data = info["data"] # Check for compatible version unless: # - A specific version was requested (@ in name, # but after first char to allow for scope marker). # - Package is locally installed. allow_fallback = "@" not in extension[1:] and not info["is_dir"] name = info["name"] # Verify that the package is an extension. messages = _validate_extension(data) if messages: all_messages = "\n".join(messages) msg = f'"{extension}" is not a valid extension:\n{all_messages}' if allow_fallback: try: version = self._latest_compatible_package_version(name) except URLError: raise ValueError(msg) from None else: raise ValueError(msg) # Verify package compatibility. deps = data.get("dependencies", {}) errors = _validate_compatibility(extension, deps, self.core_data) if errors: msg = _format_compatibility_errors(data["name"], data["version"], errors) if allow_fallback: try: version = self._latest_compatible_package_version(name) except URLError: # We cannot add any additional information to error message raise ValueError(msg) from None if version and name: self.logger.debug(f"Incompatible extension:\n{name}") self.logger.debug(f"Found compatible version: {version}") with TemporaryDirectory() as tempdir2: return self._install_extension(f"{name}@{version}", tempdir2) # Extend message to better guide the user what to do: conflicts = "\n".join(msg.splitlines()[2:]) msg = "".join((self._format_no_compatible_package_version(name), "\n\n", conflicts)) raise ValueError(msg) # Move the file to the app directory. target = pjoin(self.app_dir, "extensions", info["filename"]) if osp.exists(target): os.remove(target) shutil.move(info["path"], target) info["path"] = target return info def _extract_package(self, source, tempdir, pin=None): """Call `npm pack` for an extension. The pack command will download the package tar if `source` is a package name, or run `npm pack` locally if `source` is a directory. """ is_dir = osp.exists(source) and osp.isdir(source) if is_dir and not osp.exists(pjoin(source, "node_modules")): self._run(["node", YARN_PATH, "install"], cwd=source) info = {"source": source, "is_dir": is_dir} ret = self._run([which("npm"), "pack", source], cwd=tempdir) if ret != 0: msg = f'"{source}" is not a valid npm package' raise ValueError(msg) path = glob(pjoin(tempdir, "*.tgz"))[0] info["data"] = read_package(path) if is_dir: info["sha"] = sha = _tarsum(path) target = path.replace(".tgz", f"-{sha}.tgz") shutil.move(path, target) info["path"] = target else: info["path"] = path if pin: old_path = info["path"] new_path = pjoin(osp.dirname(old_path), f"{PIN_PREFIX}{pin}.tgz") shutil.move(old_path, new_path) info["path"] = new_path info["filename"] = osp.basename(info["path"]) info["name"] = info["data"]["name"] info["version"] = info["data"]["version"] return info def _latest_compatible_package_version(self, name): """Get the latest compatible version of a package""" core_data = self.info["core_data"] try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: return versions = metadata.get("versions", {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) for version, data in sorted(versions.items(), key=sort_key, reverse=True): deps = data.get("dependencies", {}) errors = _validate_compatibility(name, deps, core_data) if not errors: # Found a compatible version # skip deprecated versions if "deprecated" in data: self.logger.debug( f"Disregarding compatible version of package as it is deprecated: {name}@{version}" ) continue # Verify that the version is a valid extension. with TemporaryDirectory() as tempdir: info = self._extract_package(f"{name}@{version}", tempdir) if _validate_extension(info["data"]): # Invalid, do not consider other versions return # Valid return version def latest_compatible_package_versions(self, names): """Get the latest compatible versions of several packages Like _latest_compatible_package_version, but optimized for retrieving the latest version for several packages in one go. """ core_data = self.info["core_data"] keys = [] for name in names: try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: continue versions = metadata.get("versions", {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) for version, data in sorted(versions.items(), key=sort_key, reverse=True): # skip deprecated versions if "deprecated" in data: continue deps = data.get("dependencies", {}) errors = _validate_compatibility(name, deps, core_data) if not errors: # Found a compatible version keys.append(f"{name}@{version}") break # break inner for versions = {} if not keys: return versions with TemporaryDirectory() as tempdir: ret = self._run([which("npm"), "pack", *keys], cwd=tempdir) if ret != 0: msg = f'"{keys}" is not a valid npm package' raise ValueError(msg) for key in keys: fname = ( key[0].replace("@", "") + key[1:].replace("@", "-").replace("/", "-") + ".tgz" ) data = read_package(osp.join(tempdir, fname)) # Verify that the version is a valid extension. if not _validate_extension(data): # Valid versions[data["name"]] = data["version"] return versions def _format_no_compatible_package_version(self, name): """Get the latest compatible version of a package""" core_data = self.info["core_data"] # Whether lab version is too new: lab_newer_than_latest = False # Whether the latest version of the extension depend on a "future" version # of a singleton package (from the perspective of current lab version): latest_newer_than_lab = False try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: pass else: versions = metadata.get("versions", {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) store = tuple(sorted(versions.items(), key=sort_key, reverse=True)) latest_deps = store[0][1].get("dependencies", {}) core_deps = core_data["resolutions"] singletons = core_data["jupyterlab"]["singletonPackages"] for key, value in latest_deps.items(): if key in singletons: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. c = _compare_ranges(core_deps[key], value, drop_prerelease1=True) lab_newer_than_latest = lab_newer_than_latest or c < 0 latest_newer_than_lab = latest_newer_than_lab or c > 0 if lab_newer_than_latest: # All singleton deps in current version of lab are newer than those # in the latest version of the extension return ( f'The extension "{name}" does not yet support the current version of JupyterLab.\n' ) parts = [ f"No version of {name} could be found that is compatible with " "the current version of JupyterLab." ] if latest_newer_than_lab: parts.extend( ( "However, it seems to support a new version of JupyterLab.", "Consider upgrading JupyterLab.", ) ) return " ".join(parts) def _run(self, cmd, **kwargs): """Run the command using our logger and abort callback. Returns the exit code. """ if self.kill_event.is_set(): msg = "Command was killed" raise ValueError(msg) kwargs["logger"] = self.logger kwargs["kill_event"] = self.kill_event proc = ProgressProcess(cmd, **kwargs) return proc.wait() def _node_check(logger): """Check for the existence of nodejs with the correct version.""" node = which("node") try: output = subprocess.check_output([node, "node-version-check.js"], cwd=HERE) # noqa S603 logger.debug(output.decode("utf-8")) except Exception: data = CoreConfig()._data ver = data["engines"]["node"] msg = f"Please install nodejs {ver} before continuing. nodejs may be installed using conda or directly from the nodejs website." raise ValueError(msg) from None def _yarn_config(logger): """Get the yarn configuration. Returns ------- {"yarn config": dict, "npm config": dict} if unsuccessful, the subdictionaries are empty """ configuration = {"yarn config": {}, "npm config": {}} try: node = which("node") except ValueError: # Node not found == user with no need for building jupyterlab logger.debug("NodeJS was not found. Yarn user configuration is ignored.") return configuration try: output_binary = subprocess.check_output( # noqa S603 [node, YARN_PATH, "config", "--json"], stderr=subprocess.PIPE, cwd=HERE, ) output = output_binary.decode("utf-8") lines = iter(output.splitlines()) try: for line in lines: info = json.loads(line) if info["type"] == "info": key = info["data"] inspect = json.loads(next(lines)) if inspect["type"] == "inspect": configuration[key] = inspect["data"] except StopIteration: pass logger.debug("Yarn configuration loaded.") except subprocess.CalledProcessError as e: logger.error( "Fail to get yarn configuration. {!s}{!s}".format( e.stderr.decode("utf-8"), e.output.decode("utf-8") ) ) except Exception as e: logger.error(f"Fail to get yarn configuration. {e!s}") return configuration def _ensure_logger(logger=None): """Ensure that we have a logger""" return logger or logging.getLogger("jupyterlab") def _normalize_path(extension): """Normalize a given extension if it is a path.""" extension = osp.expanduser(extension) if osp.exists(extension): extension = osp.abspath(extension) return extension def _rmtree(path, logger): """Remove a tree, logging errors""" def onerror(*exc_info): logger.debug("Error in shutil.rmtree", exc_info=exc_info) shutil.rmtree(path, onerror=onerror) def _unlink(path, logger): """Remove a file, logging errors""" try: os.unlink(path) except Exception: logger.debug("Error in os.unlink", exc_info=sys.exc_info()) def _rmtree_star(path, logger): """Remove all files/trees within a dir, logging errors""" for filename in os.listdir(path): file_path = osp.join(path, filename) if osp.isfile(file_path) or osp.islink(file_path): _unlink(file_path, logger) elif osp.isdir(file_path): _rmtree(file_path, logger) def _validate_extension(data): # noqa """Detect if a package is an extension using its metadata. Returns any problems it finds. """ jlab = data.get("jupyterlab", None) if jlab is None: return ["No `jupyterlab` key"] if not isinstance(jlab, dict): return ["The `jupyterlab` key must be a JSON object"] extension = jlab.get("extension", False) mime_extension = jlab.get("mimeExtension", False) theme_path = jlab.get("themePath", "") schema_dir = jlab.get("schemaDir", "") messages = [] if not extension and not mime_extension: messages.append("No `extension` or `mimeExtension` key present") if extension == mime_extension: msg = "`mimeExtension` and `extension` must point to different modules" messages.append(msg) files = data["jupyterlab_extracted_files"] main = data.get("main", "index.js") if not main.endswith(".js"): main += ".js" if extension is True: extension = main elif extension and not extension.endswith(".js"): extension += ".js" if mime_extension is True: mime_extension = main elif mime_extension and not mime_extension.endswith(".js"): mime_extension += ".js" if extension and extension not in files: messages.append(f'Missing extension module "{extension}"') if mime_extension and mime_extension not in files: messages.append(f'Missing mimeExtension module "{mime_extension}"') if theme_path and not any(f.startswith(str(Path(theme_path))) for f in files): messages.append(f'themePath is empty: "{theme_path}"') if schema_dir and not any(f.startswith(str(Path(schema_dir))) for f in files): messages.append(f'schemaDir is empty: "{schema_dir}"') return messages def _tarsum(input_file): """ Compute the recursive sha sum of a tar file. """ chunk_size = 100 * 1024 h = hashlib.new("sha1") # noqa: S324 with tarfile.open(input_file, "r") as tar: for member in tar: if not member.isfile(): continue with tar.extractfile(member) as f: if f: # Check if f is not None (safety check) data = f.read(chunk_size) while data: h.update(data) data = f.read(chunk_size) return h.hexdigest() def _get_static_data(app_dir): """Get the data for the app static dir.""" target = pjoin(app_dir, "static", "package.json") if osp.exists(target): with open(target) as fid: return json.load(fid) else: return None def _validate_compatibility(extension, deps, core_data): """Validate the compatibility of an extension.""" core_deps = core_data["resolutions"] singletons = core_data["jupyterlab"]["singletonPackages"] errors = [] for key, value in deps.items(): if key in singletons: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. overlap = _test_overlap(core_deps[key], value, drop_prerelease1=True) if overlap is False: errors.append((key, core_deps[key], value)) return errors def _test_overlap(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): """Test whether two version specs overlap. Returns `None` if we cannot determine compatibility, otherwise whether there is an overlap """ cmp = _compare_ranges( spec1, spec2, drop_prerelease1=drop_prerelease1, drop_prerelease2=drop_prerelease2 ) if cmp is None: return return cmp == 0 def _compare_ranges(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): # noqa """Test whether two version specs overlap. Returns `None` if we cannot determine compatibility, otherwise return 0 if there is an overlap, 1 if spec1 is lower/older than spec2, and -1 if spec1 is higher/newer than spec2. """ # Test for overlapping semver ranges. r1 = Range(spec1, True) r2 = Range(spec2, True) # If either range is empty, we cannot verify. if not r1.range or not r2.range: return # Set return_value to a sentinel value return_value = False # r1.set may be a list of ranges if the range involved an ||, so we need to test for overlaps between each pair. for r1set, r2set in itertools.product(r1.set, r2.set): x1 = r1set[0].semver x2 = r1set[-1].semver y1 = r2set[0].semver y2 = r2set[-1].semver if x1.prerelease and drop_prerelease1: x1 = x1.inc("patch") if y1.prerelease and drop_prerelease2: y1 = y1.inc("patch") o1 = r1set[0].operator o2 = r2set[0].operator # We do not handle (<) specifiers. if o1.startswith("<") or o2.startswith("<"): continue # Handle single value specifiers. lx = lte if x1 == x2 else lt ly = lte if y1 == y2 else lt gx = gte if x1 == x2 else gt gy = gte if x1 == x2 else gt # Handle unbounded (>) specifiers. def noop(x, y, z): return True if x1 == x2 and o1.startswith(">"): lx = noop if y1 == y2 and o2.startswith(">"): ly = noop # Check for overlap. if ( (gte(x1, y1, True) and ly(x1, y2, True)) or (gy(x2, y1, True) and ly(x2, y2, True)) or (gte(y1, x1, True) and lx(y1, x2, True)) or (gx(y2, x1, True) and lx(y2, x2, True)) ): # if we ever find an overlap, we can return immediately return 0 if gte(y1, x2, True): if return_value is False: # We can possibly return 1 return_value = 1 elif return_value == -1: # conflicting information, so we must return None return_value = None continue if gte(x1, y2, True): if return_value is False: return_value = -1 elif return_value == 1: # conflicting information, so we must return None return_value = None continue msg = "Unexpected case comparing version ranges" raise AssertionError(msg) if return_value is False: return_value = None return return_value def _is_disabled(name, disabled=None): """Test whether the package is disabled.""" disabled = disabled or {} for pattern, value in disabled.items(): # skip packages explicitly marked as not disabled if value is False: continue if name == pattern: return True if re.compile(pattern).match(name) is not None: return True return False @dataclass(frozen=True)
_AppHandler
python
huggingface__transformers
src/transformers/models/aria/modeling_aria.py
{ "start": 31510, "end": 34696 }
class ____(AriaTextPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config: AriaTextConfig): super().__init__(config) self.model = AriaTextModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" Example: ```python >>> from transformers import AutoTokenizer, AriaTextForCausalLM >>> model = AriaTextForCausalLM.from_pretrained("meta-aria_text/AriaText-2-7b-hf") >>> tokenizer = AutoTokenizer.from_pretrained("meta-aria_text/AriaText-2-7b-hf") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" outputs: BaseModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @dataclass @auto_docstring( custom_intro=""" Base class for Aria causal language model (or autoregressive) outputs. """ )
AriaTextForCausalLM
python
docker__docker-py
tests/integration/credentials/store_test.py
{ "start": 202, "end": 3105 }
class ____: def teardown_method(self): for server in self.tmp_keys: try: self.store.erase(server) except StoreError: pass def setup_method(self): self.tmp_keys = [] if sys.platform.startswith('linux'): if shutil.which(f"docker-credential-{DEFAULT_LINUX_STORE}"): self.store = Store(DEFAULT_LINUX_STORE) elif shutil.which('docker-credential-pass'): self.store = Store('pass') else: raise Exception('No supported docker-credential store in PATH') elif sys.platform.startswith('darwin'): self.store = Store(DEFAULT_OSX_STORE) def get_random_servername(self): res = f'pycreds_test_{random.getrandbits(32):x}' self.tmp_keys.append(res) return res def test_store_and_get(self): key = self.get_random_servername() self.store.store(server=key, username='user', secret='pass') data = self.store.get(key) assert data == { 'ServerURL': key, 'Username': 'user', 'Secret': 'pass' } def test_get_nonexistent(self): key = self.get_random_servername() with pytest.raises(CredentialsNotFound): self.store.get(key) def test_store_and_erase(self): key = self.get_random_servername() self.store.store(server=key, username='user', secret='pass') self.store.erase(key) with pytest.raises(CredentialsNotFound): self.store.get(key) def test_unicode_strings(self): key = self.get_random_servername() key = key self.store.store(server=key, username='user', secret='pass') data = self.store.get(key) assert data self.store.erase(key) with pytest.raises(CredentialsNotFound): self.store.get(key) def test_list(self): names = (self.get_random_servername(), self.get_random_servername()) self.store.store(names[0], username='sakuya', secret='izayoi') self.store.store(names[1], username='reimu', secret='hakurei') data = self.store.list() assert names[0] in data assert data[names[0]] == 'sakuya' assert names[1] in data assert data[names[1]] == 'reimu' def test_execute_with_env_override(self): self.store.exe = 'env' self.store.environment = {'FOO': 'bar'} data = self.store._execute('--null', '') assert b'\0FOO=bar\0' in data assert 'FOO' not in os.environ def test_unavailable_store(self): some_unavailable_store = None with pytest.warns(UserWarning): some_unavailable_store = Store('that-does-not-exist') with pytest.raises(StoreError): some_unavailable_store.get('anything-this-does-not-matter')
TestStore
python
Netflix__metaflow
metaflow/plugins/uv/uv_environment.py
{ "start": 237, "end": 2719 }
class ____(MetaflowEnvironment): TYPE = "uv" def __init__(self, flow): super().__init__(flow) self.flow = flow def validate_environment(self, logger, datastore_type): self.datastore_type = datastore_type self.logger = logger def init_environment(self, echo, only_steps=None): self.logger("Bootstrapping uv...") def executable(self, step_name, default=None): return "uv run --no-sync python" def add_to_package(self): # NOTE: We treat uv.lock and pyproject.toml as regular project assets and ship these along user code as part of the code package # These are the minimal required files to reproduce the UV environment on the remote platform. def _find(filename): current_dir = os.getcwd() while True: file_path = os.path.join(current_dir, filename) if os.path.isfile(file_path): return file_path parent_dir = os.path.dirname(current_dir) if parent_dir == current_dir: # Reached root raise UVException( f"Could not find {filename} in current directory or any parent directory" ) current_dir = parent_dir pyproject_path = _find("pyproject.toml") uv_lock_path = _find("uv.lock") files = [ (uv_lock_path, "uv.lock", ContentType.OTHER_CONTENT), (pyproject_path, "pyproject.toml", ContentType.OTHER_CONTENT), ] return files def pylint_config(self): config = super().pylint_config() # Disable (import-error) in pylint config.append("--disable=F0401") return config def bootstrap_commands(self, step_name, datastore_type): return [ "echo 'Bootstrapping uv project...'", "flush_mflogs", # We have to prevent the tracing module from loading, as the bootstrapping process # uses the internal S3 client which would fail to import tracing due to the required # dependencies being bundled into the conda environment, which is yet to be # initialized at this point. 'DISABLE_TRACING=True python -m metaflow.plugins.uv.bootstrap "%s"' % datastore_type, "echo 'uv project bootstrapped.'", "flush_mflogs", "export PATH=$PATH:$(pwd)/uv_install", ]
UVEnvironment
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 54809, "end": 55731 }
class ____(Operation): def call(self, x, y): return backend.numpy.left_shift(x, y) def compute_output_spec(self, x, y): if isinstance(y, int): dtype = x.dtype else: dtype = dtypes.result_type(x.dtype, y.dtype) return KerasTensor(x.shape, dtype=dtype) @keras_export(["keras.ops.left_shift", "keras.ops.numpy.left_shift"]) def left_shift(x, y): """Shift the bits of an integer to the left. Bits are shifted to the left by appending `y` 0s at the right of `x`. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying `x` by `2**y`. Args: x: Input integer tensor. y: Input integer tensor. Returns: Result tensor. """ if any_symbolic_tensors((x, y)): return LeftShift().symbolic_call(x, y) return backend.numpy.left_shift(x, y)
LeftShift
python
sympy__sympy
sympy/polys/domains/characteristiczero.py
{ "start": 152, "end": 382 }
class ____(Domain): """Domain that has infinite number of elements. """ has_CharacteristicZero = True def characteristic(self): """Return the characteristic of this domain. """ return 0
CharacteristicZero
python
getsentry__sentry
tests/sentry/api/test_permissions.py
{ "start": 2812, "end": 7361 }
class ____(DRFPermissionTestCase): user_permission = DemoSafePermission() def setUp(self) -> None: super().setUp() self.normal_user = self.create_user( id=1, ) self.readonly_user = self.create_user(id=2) self.organization = self.create_organization(owner=self.normal_user) self.org_member_scopes = self.create_member( organization_id=self.organization.id, user_id=self.readonly_user.id ).get_scopes() def _get_rpc_context(self, user): rpc_context = organization_service.get_organization_by_id( id=self.organization.id, user_id=user.id ) assert rpc_context return rpc_context @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]}) def test_safe_methods(self) -> None: for method in ("GET", "HEAD", "OPTIONS"): assert self.user_permission.has_permission( self.make_request(self.readonly_user, method=method), APIView() ) assert self.user_permission.has_permission( self.make_request(self.normal_user, method=method), APIView() ) @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]}) def test_unsafe_methods(self) -> None: for method in ("POST", "PUT", "PATCH", "DELETE"): assert not self.user_permission.has_permission( self.make_request(self.readonly_user, method=method), APIView() ) assert self.user_permission.has_permission( self.make_request(self.normal_user, method=method), APIView() ) @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]}) def test_safe_method_demo_mode_disabled(self) -> None: for method in ("GET", "HEAD", "OPTIONS"): assert not self.user_permission.has_permission( self.make_request(self.readonly_user, method=method), APIView() ) assert self.user_permission.has_permission( self.make_request(self.normal_user, method=method), APIView() ) @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]}) def test_unsafe_methods_demo_mode_disabled(self) -> None: for method in ("POST", "PUT", "PATCH", "DELETE"): assert not self.user_permission.has_permission( self.make_request(self.readonly_user, method=method), APIView() ) assert self.user_permission.has_permission( self.make_request(self.normal_user, method=method), APIView() ) @override_options({"demo-mode.enabled": False, "demo-mode.users": [2]}) def test_determine_access_disabled(self) -> None: self.user_permission.determine_access( request=self.make_request(self.normal_user), organization=self._get_rpc_context(self.normal_user), ) readonly_rpc_context = self._get_rpc_context(self.readonly_user) self.user_permission.determine_access( request=self.make_request(self.readonly_user), organization=readonly_rpc_context, ) assert readonly_rpc_context.member.scopes == list(self.org_member_scopes) @override_options({"demo-mode.enabled": True, "demo-mode.users": [2]}) def test_determine_access(self) -> None: self.user_permission.determine_access( request=self.make_request(self.normal_user), organization=self._get_rpc_context(self.normal_user), ) readonly_rpc_context = self._get_rpc_context(self.readonly_user) self.user_permission.determine_access( request=self.make_request(self.readonly_user), organization=readonly_rpc_context, ) assert readonly_rpc_context.member.scopes == sorted(READONLY_SCOPES) @override_options({"demo-mode.enabled": False, "demo-mode.users": []}) def test_determine_access_no_demo_users(self) -> None: self.user_permission.determine_access( request=self.make_request(self.normal_user), organization=self._get_rpc_context(self.normal_user), ) readonly_rpc_context = self._get_rpc_context(self.readonly_user) self.user_permission.determine_access( request=self.make_request(self.readonly_user), organization=readonly_rpc_context, ) assert readonly_rpc_context.member.scopes == list(self.org_member_scopes)
DemoSafePermissionsTest
python
sqlalchemy__sqlalchemy
examples/space_invaders/space_invaders.py
{ "start": 7468, "end": 7606 }
class ____(Glyph): """Describe a glyph representing the player.""" __mapper_args__ = {"polymorphic_identity": "player"}
PlayerGlyph
python
sympy__sympy
sympy/functions/elementary/trigonometric.py
{ "start": 100804, "end": 108900 }
class ____(InverseTrigonometricFunction): r""" The inverse secant function. Returns the arc secant of x (measured in radians). Explanation =========== ``asec(x)`` will evaluate automatically in the cases $x \in \{\infty, -\infty, 0, 1, -1\}$ and for some instances when the result is a rational multiple of $\pi$ (see the eval class method). ``asec(x)`` has branch cut in the interval $[-1, 1]$. For complex arguments, it can be defined [4]_ as .. math:: \operatorname{sec^{-1}}(z) = -i\frac{\log\left(\sqrt{1 - z^2} + 1\right)}{z} At ``x = 0``, for positive branch cut, the limit evaluates to ``zoo``. For negative branch cut, the limit .. math:: \lim_{z \to 0}-i\frac{\log\left(-\sqrt{1 - z^2} + 1\right)}{z} simplifies to :math:`-i\log\left(z/2 + O\left(z^3\right)\right)` which ultimately evaluates to ``zoo``. As ``acos(x) = asec(1/x)``, a similar argument can be given for ``acos(x)``. Examples ======== >>> from sympy import asec, oo >>> asec(1) 0 >>> asec(-1) pi >>> asec(0) zoo >>> asec(-oo) pi/2 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.atan sympy.functions.elementary.trigonometric.acot sympy.functions.elementary.trigonometric.atan2 References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_trigonometric_functions .. [2] https://dlmf.nist.gov/4.23 .. [3] https://functions.wolfram.com/ElementaryFunctions/ArcSec .. [4] https://reference.wolfram.com/language/ref/ArcSec.html """ @classmethod def eval(cls, arg): if arg.is_zero: return S.ComplexInfinity if arg.is_Number: if arg is S.NaN: return S.NaN elif arg is S.One: return S.Zero elif arg is S.NegativeOne: return pi if arg in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]: return pi/2 if arg.is_number: acsc_table = cls._acsc_table() if arg in acsc_table: return pi/2 - acsc_table[arg] elif -arg in acsc_table: return pi/2 + acsc_table[-arg] if arg.is_infinite: return pi/2 if arg.is_Mul and len(arg.args) == 2 and arg.args[0] == -1: narg = arg.args[1] minus = True else: narg = arg minus = False if isinstance(narg, sec): # asec(sec(x)) = x or asec(-sec(x)) = pi - x ang = narg.args[0] if ang.is_comparable: if minus: ang = pi - ang ang %= 2*pi # restrict to [0,2*pi) if ang > pi: # restrict to [0,pi] ang = 2*pi - ang return ang if isinstance(narg, csc): # asec(x) + acsc(x) = pi/2 ang = narg.args[0] if ang.is_comparable: if minus: pi/2 + acsc(narg) return pi/2 - acsc(narg) def fdiff(self, argindex=1): if argindex == 1: return 1/(self.args[0]**2*sqrt(1 - 1/self.args[0]**2)) else: raise ArgumentIndexError(self, argindex) def inverse(self, argindex=1): """ Returns the inverse of this function. """ return sec @staticmethod @cacheit def taylor_term(n, x, *previous_terms): if n == 0: return S.ImaginaryUnit*log(2 / x) elif n < 0 or n % 2 == 1: return S.Zero else: x = sympify(x) if len(previous_terms) > 2 and n > 2: p = previous_terms[-2] return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2) else: k = n // 2 R = RisingFactorial(S.Half, k) * n F = factorial(k) * n // 2 * n // 2 return -S.ImaginaryUnit * R / F * x**n / 4 def _eval_as_leading_term(self, x, logx, cdir): arg = self.args[0] x0 = arg.subs(x, 0).cancel() if x0 is S.NaN: return self.func(arg.as_leading_term(x)) # Handling branch points if x0 == 1: return sqrt(2)*sqrt((arg - S.One).as_leading_term(x)) if x0 in (-S.One, S.Zero): return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir) # Handling points lying on branch cuts (-1, 1) if x0.is_real and (1 - x0**2).is_positive: ndir = arg.dir(x, cdir if cdir else 1) if im(ndir).is_negative: if x0.is_positive: return -self.func(x0) elif im(ndir).is_positive: if x0.is_negative: return 2*pi - self.func(x0) else: return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir).expand() return self.func(x0) def _eval_nseries(self, x, n, logx, cdir=0): # asec from sympy.series.order import O arg0 = self.args[0].subs(x, 0) # Handling branch points if arg0 is S.One: t = Dummy('t', positive=True) ser = asec(S.One + t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne + self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) if arg0 is S.NegativeOne: t = Dummy('t', positive=True) ser = asec(S.NegativeOne - t**2).rewrite(log).nseries(t, 0, 2*n) arg1 = S.NegativeOne - self.args[0] f = arg1.as_leading_term(x) g = (arg1 - f)/ f res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx) res = (res1.removeO()*sqrt(f)).expand() return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x) res = super()._eval_nseries(x, n=n, logx=logx) if arg0 is S.ComplexInfinity: return res # Handling points lying on branch cuts (-1, 1) if arg0.is_real and (1 - arg0**2).is_positive: ndir = self.args[0].dir(x, cdir if cdir else 1) if im(ndir).is_negative: if arg0.is_positive: return -res elif im(ndir).is_positive: if arg0.is_negative: return 2*pi - res else: return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir) return res def _eval_is_extended_real(self): x = self.args[0] if x.is_extended_real is False: return False return fuzzy_or(((x - 1).is_nonnegative, (-x - 1).is_nonnegative)) def _eval_rewrite_as_log(self, arg, **kwargs): return pi/2 + S.ImaginaryUnit*log(S.ImaginaryUnit/arg + sqrt(1 - 1/arg**2)) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _eval_rewrite_as_asin(self, arg, **kwargs): return pi/2 - asin(1/arg) def _eval_rewrite_as_acos(self, arg, **kwargs): return acos(1/arg) def _eval_rewrite_as_atan(self, x, **kwargs): sx2x = sqrt(x**2)/x return pi/2*(1 - sx2x) + sx2x*atan(sqrt(x**2 - 1)) def _eval_rewrite_as_acot(self, x, **kwargs): sx2x = sqrt(x**2)/x return pi/2*(1 - sx2x) + sx2x*acot(1/sqrt(x**2 - 1)) def _eval_rewrite_as_acsc(self, arg, **kwargs): return pi/2 - acsc(arg)
asec
python
dagster-io__dagster
examples/docs_projects/project_ask_ai_dagster/src/project_ask_ai_dagster/defs/retrieval.py
{ "start": 286, "end": 4043 }
class ____(dg.Config): question: str # end_config @dg.asset( deps=[github_issues_embeddings, github_discussions_embeddings, docs_embedding], kinds={"pinecone", "openai"}, group_name="retrieval", description="""A Retrieval-Augmented Generation (RAG) asset that answers Dagster-related questions using embedded documentation and GitHub content. Takes a user question, converts it to an embedding vector, searches across Pinecone indexes of Dagster docs and GitHub content, and uses GPT-4 to generate an answer based on the retrieved context. Returns the answer along with source metadata. Args: context: Dagster execution context config: Contains the user's question pinecone: Client for vector similarity search openai: Client for embeddings and LLM completion Returns: MaterializeResult containing: - The original question - AI-generated answer - Source contexts used (with URLs and relevance scores) """, ) def query( context: dg.AssetExecutionContext, config: AskAI, pinecone: PineconeResource, openai: OpenAIResource, ) -> dg.MaterializeResult: # start_query with openai.get_client(context) as client: question_embedding = ( client.embeddings.create(model="text-embedding-3-small", input=config.question) .data[0] .embedding ) results = [] for namespace in ["dagster-github", "dagster-docs"]: index_obj, namespace_kwargs = pinecone.get_index("dagster-knowledge", namespace=namespace) search_results = index_obj.query( vector=question_embedding, top_k=3, include_metadata=True, **namespace_kwargs ) results.extend(search_results.matches) results.sort(key=lambda x: x.score, reverse=True) results = results[:3] # end_query if not search_results.matches: # pyright: ignore[reportPossiblyUnboundVariable] return dg.MaterializeResult( metadata={ "question": config.question, "answer": "No relevant information found.", "sources": [], } ) # Format context from search results contexts = [] sources = [] for match in search_results.matches: # pyright: ignore[reportPossiblyUnboundVariable] contexts.append(match.metadata.get("text", "")) sources.append( { "type": match.metadata.get("source", "unknown"), "title": match.metadata.get("title", "unknown"), "url": match.metadata.get("url", "unknown"), "created_at": match.metadata.get("created_at", "unknown"), "score": match.score, } ) # start_prompt # Create prompt with context prompt_template = """ You are a experienced data engineer and Dagster expert. Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. Context: {full_context} Question: {question} Answer: Let me help you with that. """ formatted_prompt = prompt_template.format( full_context="\n\n".join(contexts), question=config.question ) # Get response from OpenAI with openai.get_client(context) as client: response = client.chat.completions.create( model="gpt-4-turbo-preview", messages=[{"role": "user", "content": formatted_prompt}] ) # end_prompt return dg.MaterializeResult( metadata={ "question": config.question, "answer": response.choices[0].message.content, "sources": sources, } )
AskAI
python
numba__numba
numba/cuda/tests/cudapy/test_caching.py
{ "start": 9207, "end": 12135 }
class ____(SerialMixin, DispatcherCacheUsecasesTest): here = os.path.dirname(__file__) usecases_file = os.path.join(here, "cache_with_cpu_usecases.py") modname = "cuda_and_cpu_caching_test_fodder" def setUp(self): DispatcherCacheUsecasesTest.setUp(self) CUDATestCase.setUp(self) def tearDown(self): CUDATestCase.tearDown(self) DispatcherCacheUsecasesTest.tearDown(self) def test_cpu_and_cuda_targets(self): # The same function jitted for CPU and CUDA targets should maintain # separate caches for each target. self.check_pycache(0) mod = self.import_module() self.check_pycache(0) f_cpu = mod.assign_cpu f_cuda = mod.assign_cuda self.assertPreciseEqual(f_cpu(5), 5) self.check_pycache(2) # 1 index, 1 data self.assertPreciseEqual(f_cuda(5), 5) self.check_pycache(3) # 1 index, 2 data self.check_hits(f_cpu.func, 0, 1) self.check_hits(f_cuda.func, 0, 1) self.assertPreciseEqual(f_cpu(5.5), 5.5) self.check_pycache(4) # 1 index, 3 data self.assertPreciseEqual(f_cuda(5.5), 5.5) self.check_pycache(5) # 1 index, 4 data self.check_hits(f_cpu.func, 0, 2) self.check_hits(f_cuda.func, 0, 2) def test_cpu_and_cuda_reuse(self): # Existing cache files for the CPU and CUDA targets are reused. mod = self.import_module() mod.assign_cpu(5) mod.assign_cpu(5.5) mod.assign_cuda(5) mod.assign_cuda(5.5) mtimes = self.get_cache_mtimes() # Two signatures compiled self.check_hits(mod.assign_cpu.func, 0, 2) self.check_hits(mod.assign_cuda.func, 0, 2) mod2 = self.import_module() self.assertIsNot(mod, mod2) f_cpu = mod2.assign_cpu f_cuda = mod2.assign_cuda f_cpu(2) self.check_hits(f_cpu.func, 1, 0) f_cpu(2.5) self.check_hits(f_cpu.func, 2, 0) f_cuda(2) self.check_hits(f_cuda.func, 1, 0) f_cuda(2.5) self.check_hits(f_cuda.func, 2, 0) # The files haven't changed self.assertEqual(self.get_cache_mtimes(), mtimes) self.run_in_separate_process() self.assertEqual(self.get_cache_mtimes(), mtimes) def get_different_cc_gpus(): # Find two GPUs with different Compute Capabilities and return them as a # tuple. If two GPUs with distinct Compute Capabilities cannot be found, # then None is returned. first_gpu = cuda.gpus[0] with first_gpu: first_cc = cuda.current_context().device.compute_capability for gpu in cuda.gpus[1:]: with gpu: cc = cuda.current_context().device.compute_capability if cc != first_cc: return (first_gpu, gpu) return None @skip_on_cudasim('Simulator does not implement caching')
CUDAAndCPUCachingTest
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 15839, "end": 21578 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): global people, engineers, managers, cars people = Table( "people", metadata, Column( "person_id", Integer, primary_key=True, test_needs_autoincrement=True, ), Column("name", String(50)), ) engineers = Table( "engineers", metadata, Column( "person_id", Integer, ForeignKey("people.person_id"), primary_key=True, ), Column("status", String(30)), ) managers = Table( "managers", metadata, Column( "person_id", Integer, ForeignKey("people.person_id"), primary_key=True, ), Column("longer_status", String(70)), ) cars = Table( "cars", metadata, Column( "car_id", Integer, primary_key=True, test_needs_autoincrement=True, ), Column("owner", Integer, ForeignKey("people.person_id")), ) def test_many_to_one_polymorphic(self): """in this test, the polymorphic union is between two subclasses, but does not include the base table by itself in the union. however, the primaryjoin condition is going to be against the base table, and its a many-to-one relationship (unlike the test in polymorph.py) so the column in the base table is explicit. Can the ClauseAdapter figure out how to alias the primaryjoin to the polymorphic union ?""" # class definitions class Person: def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __repr__(self): return "Ordinary person %s" % self.name class Engineer(Person): def __repr__(self): return "Engineer %s, status %s" % (self.name, self.status) class Manager(Person): def __repr__(self): return "Manager %s, status %s" % ( self.name, self.longer_status, ) class Car: def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __repr__(self): return "Car number %d" % self.car_id # create a union that represents both types of joins. employee_join = polymorphic_union( { "engineer": people.join(engineers), "manager": people.join(managers), }, "type", "employee_join", ) person_mapper = self.mapper_registry.map_imperatively( Person, people, with_polymorphic=("*", employee_join), polymorphic_on=employee_join.c.type, polymorphic_identity="person", ) self.mapper_registry.map_imperatively( Engineer, engineers, with_polymorphic=([Engineer], people.join(engineers)), inherits=person_mapper, polymorphic_identity="engineer", ) self.mapper_registry.map_imperatively( Manager, managers, with_polymorphic=([Manager], people.join(managers)), inherits=person_mapper, polymorphic_identity="manager", ) self.mapper_registry.map_imperatively( Car, cars, properties={"employee": relationship(person_mapper)} ) session = fixture_session() # creating 5 managers named from M1 to E5 for i in range(1, 5): session.add(Manager(name="M%d" % i, longer_status="YYYYYYYYY")) # creating 5 engineers named from E1 to E5 for i in range(1, 5): session.add(Engineer(name="E%d" % i, status="X")) session.flush() engineer4 = ( session.query(Engineer).filter(Engineer.name == "E4").first() ) manager3 = session.query(Manager).filter(Manager.name == "M3").first() car1 = Car(employee=engineer4) session.add(car1) car2 = Car(employee=manager3) session.add(car2) session.flush() session.expunge_all() def go(): testcar = session.get( Car, car1.car_id, options=[joinedload(Car.employee)] ) assert str(testcar.employee) == "Engineer E4, status X" self.assert_sql_count(testing.db, go, 1) car1 = session.get(Car, car1.car_id) usingGet = session.get(person_mapper, car1.owner) usingProperty = car1.employee assert str(engineer4) == "Engineer E4, status X" assert str(usingGet) == "Engineer E4, status X" assert str(usingProperty) == "Engineer E4, status X" session.expunge_all() # and now for the lightning round, eager ! def go(): testcar = session.get( Car, car1.car_id, options=[joinedload(Car.employee)], ) assert str(testcar.employee) == "Engineer E4, status X" self.assert_sql_count(testing.db, go, 1) session.expunge_all() s = session.query(Car) c = s.join(Car.employee).filter(Person.name == "E4")[0] assert c.car_id == car1.car_id
RelationshipTest4
python
pytorch__pytorch
torch/_strobelight/compile_time_profiler.py
{ "start": 2481, "end": 7565 }
class ____: success_profile_count: int = 0 failed_profile_count: int = 0 ignored_profile_runs: int = 0 inside_profile_compile_time: bool = False enabled: bool = False # A regex that can be used to filter out what frames to profile. ex: "1/.*" frame_id_filter: Optional[str] = os.environ.get("COMPILE_STROBELIGHT_FRAME_FILTER") # A unique identifier that is used as the run_user_name in the strobelight profile to # associate all compile time profiles together. identifier: Optional[str] = None current_phase: Optional[str] = None profiler: Optional[Any] = None max_stack_length: int = int( os.environ.get("COMPILE_STROBELIGHT_MAX_STACK_LENGTH", 500) ) max_profile_time: int = int( os.environ.get("COMPILE_STROBELIGHT_MAX_PROFILE_TIME", 60 * 30) ) # Collect sample each x cycles. sample_each: int = int( float(os.environ.get("COMPILE_STROBELIGHT_SAMPLE_RATE", 1e7)) ) @classmethod def get_frame(cls) -> str: from torch._guards import CompileContext return (str)(CompileContext.current_trace_id()) @classmethod def enable(cls, profiler_class: Any = StrobelightCLIFunctionProfiler) -> None: if cls.enabled: logger.info("compile time strobelight profiling already enabled") return logger.info("compile time strobelight profiling enabled") if profiler_class is StrobelightCLIFunctionProfiler: import shutil if not shutil.which("strobeclient"): logger.info( "strobeclient not found, can't enable compile time strobelight profiling, seems" "like you are not on a FB machine." ) return cls.enabled = True cls._cls_init() # profiler_class should have public API similar to that of StrobelightCLIFunctionProfiler. # we have pass different functionProfilerClass for meta-internal fbcode targets. # NB: the actual implementation in Meta is at # fbcode/caffe2/fb/strobelight/function_profiler.py cls.profiler = profiler_class( sample_each=cls.sample_each, max_profile_duration_sec=cls.max_profile_time, stack_max_len=cls.max_stack_length, async_stack_max_len=cls.max_stack_length, run_user_name="pt2-profiler/" + os.environ.get("USER", os.environ.get("USERNAME", "")), sample_tags={cls.identifier}, # pyrefly: ignore # bad-argument-type ) @classmethod def _cls_init(cls) -> None: cls.identifier = "{date}{pid}{hostname}".format( date=datetime.now().strftime("%Y-%m-%d-%H:%M:%S"), pid=os.getpid(), hostname=gethostname(), ) logger.info("Unique sample tag for this run is: %s", cls.identifier) logger.info( "URL to access the strobelight profile at the end of the run: %s", get_strobelight_url(cls.identifier), ) @classmethod def _log_stats(cls) -> None: logger.info( "%s strobelight success runs out of %s non-recursive compilation events.", cls.success_profile_count, cls.success_profile_count + cls.failed_profile_count, ) # TODO use threadlevel meta data to tags to record phases. @classmethod def profile_compile_time( cls, func: Any, phase_name: str, *args: Any, **kwargs: Any ) -> Any: def skip() -> Any: return func(*args, **kwargs) if not cls.enabled: return skip() if cls.profiler is None: logger.error("profiler is not set") return frame_id = cls.get_frame() if cls.inside_profile_compile_time: cls.ignored_profile_runs += 1 logger.info( "profile_compile_time is requested for phase: %s, frame %s, while already in running phase: %s," "frame %s, recursive call ignored", phase_name, frame_id, cls.current_phase, frame_id, ) return skip() if cls.frame_id_filter is not None: should_run = re.match(cls.frame_id_filter, frame_id) is not None if not should_run: logger.info( "profiling frame %s is skipped due to frame_id_filter %s", frame_id, cls.frame_id_filter, ) return skip() cls.inside_profile_compile_time = True cls.current_phase = phase_name logger.info("profiling frame %s", frame_id) work_result = cls.profiler.profile(func, *args, **kwargs) if cls.profiler.profile_result is not None: cls.success_profile_count += 1 else: cls.failed_profile_count += 1 cls._log_stats() cls.inside_profile_compile_time = False return work_result
StrobelightCompileTimeProfiler
python
skorch-dev__skorch
skorch/tests/test_hf.py
{ "start": 19686, "end": 19757 }
class ____(AccelerateMixin, NeuralNetClassifier): pass
AcceleratedNet
python
marshmallow-code__marshmallow
tests/test_options.py
{ "start": 411, "end": 2756 }
class ____: def test_declared_field_order_is_maintained_on_dump(self, user): ser = UserSchema() data = ser.dump(user) keys = list(data) assert keys == [ "name", "email", "age", "created", "id", "homepage", "birthdate", ] def test_declared_field_order_is_maintained_on_load(self, serialized_user): schema = UserSchema(unknown=EXCLUDE) data = schema.load(serialized_user) keys = list(data) assert keys == [ "name", "email", "age", "created", "id", "homepage", "birthdate", ] def test_nested_field_order_with_only_arg_is_maintained_on_dump(self, user): schema = ProfileSchema() data = schema.dump({"user": user}) user_data = data["user"] keys = list(user_data) assert keys == [ "name", "email", "age", "created", "id", "homepage", "birthdate", ] def test_nested_field_order_with_only_arg_is_maintained_on_load(self): schema = ProfileSchema() data = schema.load( { "user": { "name": "Foo", "email": "Foo@bar.com", "age": 42, "created": dt.datetime.now().isoformat(), "id": 123, "homepage": "http://foo.com", "birthdate": dt.datetime.now().date().isoformat(), } } ) user_data = data["user"] keys = list(user_data) assert keys == [ "name", "email", "age", "created", "id", "homepage", "birthdate", ] def test_nested_field_order_with_exclude_arg_is_maintained(self, user): class HasNestedExclude(Schema): user = fields.Nested(UserSchema, exclude=("birthdate",)) ser = HasNestedExclude() data = ser.dump({"user": user}) user_data = data["user"] keys = list(user_data) assert keys == ["name", "email", "age", "created", "id", "homepage"]
TestFieldOrdering
python
oauthlib__oauthlib
tests/oauth1/rfc5849/test_parameters.py
{ "start": 247, "end": 3795 }
class ____(TestCase): auth_only_params = [ ('oauth_consumer_key', "9djdj82h48djs9d2"), ('oauth_token', "kkk9d7dh3k39sjv7"), ('oauth_signature_method', "HMAC-SHA1"), ('oauth_timestamp', "137131201"), ('oauth_nonce', "7d8f3e4a"), ('oauth_signature', "bYT5CMsGcbgUdFHObYMEfcx6bsw=") ] auth_and_data = list(auth_only_params) auth_and_data.append(('data_param_foo', 'foo')) auth_and_data.append(('data_param_1', '1')) realm = 'testrealm' norealm_authorization_header = ' '.join(( 'OAuth', 'oauth_consumer_key="9djdj82h48djs9d2",', 'oauth_token="kkk9d7dh3k39sjv7",', 'oauth_signature_method="HMAC-SHA1",', 'oauth_timestamp="137131201",', 'oauth_nonce="7d8f3e4a",', 'oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"', )) withrealm_authorization_header = ' '.join(( 'OAuth', 'realm="testrealm",', 'oauth_consumer_key="9djdj82h48djs9d2",', 'oauth_token="kkk9d7dh3k39sjv7",', 'oauth_signature_method="HMAC-SHA1",', 'oauth_timestamp="137131201",', 'oauth_nonce="7d8f3e4a",', 'oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"', )) def test_append_params(self): unordered_1 = [ ('oauth_foo', 'foo'), ('lala', 123), ('oauth_baz', 'baz'), ('oauth_bar', 'bar'), ] unordered_2 = [ ('teehee', 456), ('oauth_quux', 'quux'), ] expected = [ ('teehee', 456), ('lala', 123), ('oauth_quux', 'quux'), ('oauth_foo', 'foo'), ('oauth_baz', 'baz'), ('oauth_bar', 'bar'), ] self.assertEqual(_append_params(unordered_1, unordered_2), expected) def test_prepare_headers(self): self.assertEqual( prepare_headers(self.auth_only_params, {}), {'Authorization': self.norealm_authorization_header}) self.assertEqual( prepare_headers(self.auth_only_params, {}, realm=self.realm), {'Authorization': self.withrealm_authorization_header}) def test_prepare_headers_ignore_data(self): self.assertEqual( prepare_headers(self.auth_and_data, {}), {'Authorization': self.norealm_authorization_header}) self.assertEqual( prepare_headers(self.auth_and_data, {}, realm=self.realm), {'Authorization': self.withrealm_authorization_header}) def test_prepare_form_encoded_body(self): existing_body = '' form_encoded_body = 'data_param_foo=foo&data_param_1=1&oauth_consumer_key=9djdj82h48djs9d2&oauth_token=kkk9d7dh3k39sjv7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131201&oauth_nonce=7d8f3e4a&oauth_signature=bYT5CMsGcbgUdFHObYMEfcx6bsw%3D' self.assertEqual( urlencode(prepare_form_encoded_body(self.auth_and_data, existing_body)), form_encoded_body) def test_prepare_request_uri_query(self): url = 'http://notarealdomain.com/foo/bar/baz?some=args&go=here' request_uri_query = 'http://notarealdomain.com/foo/bar/baz?some=args&go=here&data_param_foo=foo&data_param_1=1&oauth_consumer_key=9djdj82h48djs9d2&oauth_token=kkk9d7dh3k39sjv7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131201&oauth_nonce=7d8f3e4a&oauth_signature=bYT5CMsGcbgUdFHObYMEfcx6bsw%3D' self.assertEqual( prepare_request_uri_query(self.auth_and_data, url), request_uri_query)
ParameterTests
python
getsentry__sentry
src/sentry/web/frontend/debug/mail.py
{ "start": 13728, "end": 14701 }
class ____: def __init__(self, request, activity): self.request = request self.email = EMAIL_CLASSES_BY_TYPE[activity.type](activity) def get_context(self): context = self.email.get_base_context() context["reason"] = get_random(self.request).choice( list(GroupSubscriptionReason.descriptions.values()) ) context.update(self.email.get_context()) add_unsubscribe_link(context) return context def text_body(self): txt_template = f"{self.email.template_path}.txt" return render_to_string(txt_template, context=self.get_context()) def html_body(self): html_template = f"{self.email.template_path}.html" try: return inline_css(render_to_string(html_template, context=self.get_context())) except Exception: import traceback traceback.print_exc() raise @internal_region_silo_view
ActivityMailPreview
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-alibabacloud-aisearch/llama_index/readers/alibabacloud_aisearch/base.py
{ "start": 7803, "end": 10961 }
class ____(AlibabaCloudAISearchDocumentReader): """ For further details, please visit `https://help.aliyun.com/zh/open-search/search-platform/developer-reference/opensearch-api-details`. """ service_id: str = "ops-image-analyze-ocr-001" # upload a document and get back a task_id @aretry_decorator async def _create_task( self, file_path: str, file_type: str, **load_kwargs: Any, ) -> str: if file_path.startswith("data:"): prefix, content = file_path.split(",") if not file_type: m = re.match(r"^data:image/(\w+);base64$", prefix) file_type = m.group(1) file_name = f"image.{file_type}" document = CreateImageAnalyzeTaskRequestDocument( content=content, file_name=file_name, file_type=file_type, ) elif file_path.startswith("http"): file_name = os.path.basename(file_path.split("?")[0].split("#")[0]) if not file_type: file_type = os.path.splitext(file_name)[1][1:] document = CreateImageAnalyzeTaskRequestDocument( url=file_path, file_name=file_name, file_type=file_type, ) else: file_name = os.path.basename(file_path) if not file_type: file_type = os.path.splitext(file_name)[1][1:] document = CreateImageAnalyzeTaskRequestDocument( content=base64.b64encode(open(file_path, "rb").read()).decode(), file_name=file_name, file_type=file_type, ) if not file_type: raise ValueError( "The file_type cannot be determined based on the file extension. Please specify it manually." ) request = CreateImageAnalyzeTaskRequest(document=document) response: CreateImageAnalyzeTaskResponse = ( await self._client.create_image_analyze_task_async( self.workspace_name, self.service_id, request ) ) return response.body.result.task_id async def _get_task_result(self, task_id: str) -> Document: request = GetImageAnalyzeTaskStatusRequest(task_id=task_id) while True: response: GetImageAnalyzeTaskStatusResponse = ( await self._client.get_image_analyze_task_status_async( self.workspace_name, self.service_id, request ) ) status = response.body.result.status if status == "PENDING": await asyncio.sleep(self.check_interval) elif status == "SUCCESS": data = response.body.result.data return Document( text=data.content, mimetype=f"text/{data.content_type}", ) else: raise RuntimeError( f"Failed to parse the file, error: {response.body.result.error}, task id: {task_id}" )
AlibabaCloudAISearchImageReader
python
plotly__plotly.py
plotly/graph_objs/treemap/_tiling.py
{ "start": 233, "end": 6647 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "treemap" _path_str = "treemap.tiling" _valid_props = {"flip", "packing", "pad", "squarifyratio"} @property def flip(self): """ Determines if the positions obtained from solver are flipped on each axis. The 'flip' property is a flaglist and may be specified as a string containing: - Any combination of ['x', 'y'] joined with '+' characters (e.g. 'x+y') Returns ------- Any """ return self["flip"] @flip.setter def flip(self, val): self["flip"] = val @property def packing(self): """ Determines d3 treemap solver. For more info please refer to https://github.com/d3/d3-hierarchy#treemap-tiling The 'packing' property is an enumeration that may be specified as: - One of the following enumeration values: ['squarify', 'binary', 'dice', 'slice', 'slice-dice', 'dice-slice'] Returns ------- Any """ return self["packing"] @packing.setter def packing(self, val): self["packing"] = val @property def pad(self): """ Sets the inner padding (in px). The 'pad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["pad"] @pad.setter def pad(self, val): self["pad"] = val @property def squarifyratio(self): """ When using "squarify" `packing` algorithm, according to https:/ /github.com/d3/d3- hierarchy/blob/v3.1.1/README.md#squarify_ratio this option specifies the desired aspect ratio of the generated rectangles. The ratio must be specified as a number greater than or equal to one. Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio; for example, a ratio of two will attempt to produce a mixture of rectangles whose width:height ratio is either 2:1 or 1:2. When using "squarify", unlike d3 which uses the Golden Ratio i.e. 1.618034, Plotly applies 1 to increase squares in treemap layouts. The 'squarifyratio' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["squarifyratio"] @squarifyratio.setter def squarifyratio(self, val): self["squarifyratio"] = val @property def _prop_descriptions(self): return """\ flip Determines if the positions obtained from solver are flipped on each axis. packing Determines d3 treemap solver. For more info please refer to https://github.com/d3/d3-hierarchy#treemap- tiling pad Sets the inner padding (in px). squarifyratio When using "squarify" `packing` algorithm, according to https://github.com/d3/d3- hierarchy/blob/v3.1.1/README.md#squarify_ratio this option specifies the desired aspect ratio of the generated rectangles. The ratio must be specified as a number greater than or equal to one. Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio; for example, a ratio of two will attempt to produce a mixture of rectangles whose width:height ratio is either 2:1 or 1:2. When using "squarify", unlike d3 which uses the Golden Ratio i.e. 1.618034, Plotly applies 1 to increase squares in treemap layouts. """ def __init__( self, arg=None, flip=None, packing=None, pad=None, squarifyratio=None, **kwargs ): """ Construct a new Tiling object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.Tiling` flip Determines if the positions obtained from solver are flipped on each axis. packing Determines d3 treemap solver. For more info please refer to https://github.com/d3/d3-hierarchy#treemap- tiling pad Sets the inner padding (in px). squarifyratio When using "squarify" `packing` algorithm, according to https://github.com/d3/d3- hierarchy/blob/v3.1.1/README.md#squarify_ratio this option specifies the desired aspect ratio of the generated rectangles. The ratio must be specified as a number greater than or equal to one. Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio; for example, a ratio of two will attempt to produce a mixture of rectangles whose width:height ratio is either 2:1 or 1:2. When using "squarify", unlike d3 which uses the Golden Ratio i.e. 1.618034, Plotly applies 1 to increase squares in treemap layouts. Returns ------- Tiling """ super().__init__("tiling") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.treemap.Tiling constructor must be a dict or an instance of :class:`plotly.graph_objs.treemap.Tiling`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("flip", arg, flip) self._set_property("packing", arg, packing) self._set_property("pad", arg, pad) self._set_property("squarifyratio", arg, squarifyratio) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Tiling
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/buffer.py
{ "start": 2077, "end": 2727 }
class ____: @staticmethod def rewards_key(name: str) -> AgentBufferKey: return RewardSignalKeyPrefix.REWARDS, name @staticmethod def value_estimates_key(name: str) -> AgentBufferKey: return RewardSignalKeyPrefix.RETURNS, name @staticmethod def returns_key(name: str) -> AgentBufferKey: return RewardSignalKeyPrefix.RETURNS, name @staticmethod def advantage_key(name: str) -> AgentBufferKey: return RewardSignalKeyPrefix.ADVANTAGE, name @staticmethod def baseline_estimates_key(name: str) -> AgentBufferKey: return RewardSignalKeyPrefix.BASELINES, name
RewardSignalUtil
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_indexing.py
{ "start": 47747, "end": 48382 }
class ____(TestCase): """Tests that array_likes only valid if can safely cast to integer. For instance, lists give IndexError when they cannot be safely cast to an integer. """ @skip( reason=( "torch consumes floats by way of falling back on its deprecated " "__index__ behaviour, no bother raising here" ) ) def test_basic(self): a = np.arange(10) assert_raises(IndexError, a.__getitem__, [0.5, 1.5]) assert_raises(IndexError, a.__getitem__, (["1", "2"],)) # The following is valid a.__getitem__([])
TestNonIntegerArrayLike
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qrnn_test.py
{ "start": 513, "end": 1934 }
class ____(op_bench.TorchBenchmarkBase): def init(self, I, H, NL, B, D, dtype): sequence_len = 128 batch_size = 16 # The quantized.dynamic.LSTM has a bug. That's why we create a regular # LSTM, and quantize it later. See issue #31192. cell_nn = nn.LSTM( input_size=I, hidden_size=H, num_layers=NL, bias=B, batch_first=False, dropout=0.0, bidirectional=D, ) cell_temp = nn.Sequential(cell_nn) self.cell = torch.ao.quantization.quantize_dynamic( cell_temp, {nn.LSTM, nn.Linear}, dtype=dtype )[0] x = torch.randn( sequence_len, # sequence length batch_size, # batch size I, # Number of features in X ) h = torch.randn( NL * (D + 1), # layer_num * dir_num batch_size, # batch size H, # hidden size ) c = torch.randn( NL * (D + 1), # layer_num * dir_num batch_size, # batch size H, # hidden size ) self.inputs = {"x": x, "h": h, "c": c} self.set_module_name("QLSTM") def forward(self, x, h, c): return self.cell(x, (h, c))[0] op_bench.generate_pt_test(qrnn_configs, LSTMBenchmark) if __name__ == "__main__": op_bench.benchmark_runner.main()
LSTMBenchmark
python
crytic__slither
slither/core/expressions/new_contract.py
{ "start": 61, "end": 755 }
class ____(Expression): def __init__(self, contract_name: str) -> None: super().__init__() self._contract_name: str = contract_name self._gas = None self._value = None self._salt = None @property def contract_name(self) -> str: return self._contract_name @property def call_value(self): return self._value @call_value.setter def call_value(self, v): self._value = v @property def call_salt(self): return self._salt @call_salt.setter def call_salt(self, salt): self._salt = salt def __str__(self) -> str: return "new " + str(self._contract_name)
NewContract
python
django__django
django/db/models/functions/math.py
{ "start": 588, "end": 685 }
class ____(NumericOutputFieldMixin, Transform): function = "ATAN" lookup_name = "atan"
ATan
python
weaviate__weaviate-python-client
integration/conftest.py
{ "start": 6778, "end": 7931 }
class ____(Protocol): """Typing for fixture.""" async def __call__( self, name: str = "", properties: Optional[List[Property]] = None, references: Optional[List[_ReferencePropertyBase]] = None, vectorizer_config: Optional[ Union[_VectorizerConfigCreate, List[_NamedVectorConfigCreate]] ] = None, inverted_index_config: Optional[_InvertedIndexConfigCreate] = None, multi_tenancy_config: Optional[_MultiTenancyConfigCreate] = None, generative_config: Optional[_GenerativeProvider] = None, headers: Optional[Dict[str, str]] = None, ports: Tuple[int, int] = (8080, 50051), data_model_properties: Optional[Type[Properties]] = None, data_model_refs: Optional[Type[Properties]] = None, replication_config: Optional[_ReplicationConfigCreate] = None, vector_index_config: Optional[_VectorIndexConfigCreate] = None, description: Optional[str] = None, reranker_config: Optional[_RerankerProvider] = None, ) -> CollectionAsync[Any, Any]: """Typing for fixture.""" ...
AsyncCollectionFactory
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
{ "start": 42473, "end": 45369 }
class ____(TestCase): def test_subconfig_with_multiple_items(self): # This had a bug where subsequent items would get merged into the same dict. class Schema: the_items = c.ConfigItems( ("value", c.Type(str)), ) conf = self.get_config( Schema, { 'the_items': [ {'value': 'a'}, {'value': 'b'}, ] }, ) self.assertEqual(conf['the_items'], [{'value': 'a'}, {'value': 'b'}]) def test_optional(self): class Schema: sub = c.ListOfItems( c.SubConfig( ('opt', c.Type(int)), validate=True, ), default=[], ) conf = self.get_config(Schema, {}) self.assertEqual(conf['sub'], []) conf = self.get_config(Schema, {'sub': None}) self.assertEqual(conf['sub'], []) conf = self.get_config(Schema, {'sub': [{'opt': 1}, {}]}) self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': None}]) conf = self.get_config(Schema, {'sub': []}) conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]}) self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': 2}]) def test_required(self): class Schema: sub = c.ListOfItems( c.SubConfig( ('opt', c.Type(int, required=True)), validate=True, ) ) with self.expect_error(sub="Required configuration not provided."): conf = self.get_config(Schema, {}) with self.expect_error(sub="Required configuration not provided."): conf = self.get_config(Schema, {'sub': None}) with self.expect_error( sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>" ): conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]}) conf = self.get_config(Schema, {'sub': []}) conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]}) self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': 2}]) with self.expect_error( sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>" ): self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]}) with self.expect_error( sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>" ): conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]}) with self.expect_error( sub="The configuration is invalid. Expected a key-value mapping " "(dict) but received: <class 'int'>" ): conf = self.get_config(Schema, {'sub': [1, 2]})
ConfigItemsTest
python
huggingface__transformers
src/transformers/models/xlnet/modeling_xlnet.py
{ "start": 31095, "end": 32372 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Total span extraction loss is the sum of a Cross-Entropy for the start and end positions. start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`): Span-start scores (before SoftMax). end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`): Span-end scores (before SoftMax). mems (`list[torch.FloatTensor]` of length `config.n_layers`): Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as `input_ids` as they have already been computed. """ loss: Optional[torch.FloatTensor] = None start_logits: Optional[torch.FloatTensor] = None end_logits: Optional[torch.FloatTensor] = None mems: Optional[list[torch.FloatTensor]] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass @auto_docstring( custom_intro=""" Output type of [`XLNetForQuestionAnswering`]. """ )
XLNetForQuestionAnsweringSimpleOutput
python
django__django
tests/delete_regress/models.py
{ "start": 527, "end": 636 }
class ____(models.Model): name = models.CharField(max_length=25) awards = GenericRelation(Award)
Person
python
facelessuser__soupsieve
tests/test_level4/test_read_only.py
{ "start": 54, "end": 1790 }
class ____(util.TestCase): """Test read only selectors.""" def test_read_only(self): """Test read only.""" markup = """ <body> <input id="0"> <textarea id="1"></textarea> <input id="2"> <input id="3" disabled> <input id="4" type="email"> <input id="5" type="number"> <input id="6" type="password"> <input id="7" type="search"> <input id="8" type="tel"> <input id="9" type="text"> <input id="10" type="url"> <input id="11" type=""> <input id="12" type> <input id="13" type="button"> <input id="14" type="checkbox"> <input id="15" type="color"> <input id="16" type="date"> <input id="17" type="datetime-local"> <input id="18" type="file"> <input id="19" type="hidden"> <input id="20" type="image"> <input id="21" type="month"> <input id="22" type="radio"> <input id="23" type="range"> <input id="24" type="reset"> <input id="25" type="submit"> <input id="26" type="time"> <input id="27" type="week"> <p id="28" contenteditable="">Text</p> <p id="29" contenteditable="true">Text</p> <p id="30" contenteditable="TRUE">Text</p> <p id="31" contenteditable="false">Text</p> <p id="32">Text</p> <input id="33" type="number" readonly> </body> """ self.assert_selector( markup, "body :read-only", [ '3', '13', '14', '15', '18', '19', '20', '22', '23', '24', '25', '31', '32', '33' ], flags=util.HTML )
TestReadOnly
python
redis__redis-py
redis/commands/cluster.py
{ "start": 30745, "end": 31663 }
class ____( ClusterMultiKeyCommands, ClusterManagementCommands, ACLCommands, PubSubCommands, ClusterDataAccessCommands, ScriptCommands, FunctionCommands, ModuleCommands, RedisModuleCommands, ): """ A class for all Redis Cluster commands For key-based commands, the target node(s) will be internally determined by the keys' hash slot. Non-key-based commands can be executed with the 'target_nodes' argument to target specific nodes. By default, if target_nodes is not specified, the command will be executed on the default cluster node. :param :target_nodes: type can be one of the followings: - nodes flag: ALL_NODES, PRIMARIES, REPLICAS, RANDOM - 'ClusterNode' - 'list(ClusterNodes)' - 'dict(any:clusterNodes)' for example: r.cluster_info(target_nodes=RedisCluster.ALL_NODES) """
RedisClusterCommands
python
doocs__leetcode
solution/2100-2199/2151.Maximum Good People Based on Statements/Solution.py
{ "start": 0, "end": 485 }
class ____: def maximumGood(self, statements: List[List[int]]) -> int: def check(mask: int) -> int: cnt = 0 for i, row in enumerate(statements): if mask >> i & 1: for j, x in enumerate(row): if x < 2 and (mask >> j & 1) != x: return 0 cnt += 1 return cnt return max(check(i) for i in range(1, 1 << len(statements)))
Solution
python
PyCQA__isort
tests/unit/test_exceptions.py
{ "start": 3353, "end": 3711 }
class ____(TestISortError): def setup_class(self): self.instance: exceptions.UnsupportedSettings = exceptions.UnsupportedSettings( {"apply": {"value": "true", "source": "/"}} ) def test_variables(self): assert self.instance.unsupported_settings == {"apply": {"value": "true", "source": "/"}}
TestUnsupportedSettings
python
pypa__hatch
backend/src/hatchling/cli/dep/core.py
{ "start": 221, "end": 5316 }
class ____: def __init__(self, sys_path: list[str]) -> None: self._resolver = Distribution.discover(context=DistributionFinder.Context(path=sys_path)) self._distributions: dict[str, Distribution] = {} self._search_exhausted = False self._canonical_regex = re.compile(r"[-_.]+") def __getitem__(self, item: str) -> Distribution | None: item = self._canonical_regex.sub("-", item).lower() possible_distribution = self._distributions.get(item) if possible_distribution is not None: return possible_distribution # Be safe even though the code as-is will never reach this since # the first unknown distribution will fail fast if self._search_exhausted: # no cov return None for distribution in self._resolver: name = distribution.metadata["Name"] if name is None: continue name = self._canonical_regex.sub("-", name).lower() self._distributions[name] = distribution if name == item: return distribution self._search_exhausted = True return None def dependency_in_sync( requirement: Requirement, environment: dict[str, str], installed_distributions: DistributionCache ) -> bool: if requirement.marker and not requirement.marker.evaluate(environment): return True distribution = installed_distributions[requirement.name] if distribution is None: return False extras = requirement.extras if extras: transitive_requirements: list[str] = distribution.metadata.get_all("Requires-Dist", []) if not transitive_requirements: return False available_extras: list[str] = distribution.metadata.get_all("Provides-Extra", []) for requirement_string in transitive_requirements: transitive_requirement = Requirement(requirement_string) if not transitive_requirement.marker: continue for extra in extras: # FIXME: This may cause a build to never be ready if newer versions do not provide the desired # extra and it's just a user error/typo. See: https://github.com/pypa/pip/issues/7122 if extra not in available_extras: return False extra_environment = dict(environment) extra_environment["extra"] = extra if not dependency_in_sync(transitive_requirement, extra_environment, installed_distributions): return False if requirement.specifier and not requirement.specifier.contains(distribution.version): return False # TODO: handle https://discuss.python.org/t/11938 if requirement.url: direct_url_file = distribution.read_text("direct_url.json") if direct_url_file is not None: import json # https://packaging.python.org/specifications/direct-url/ direct_url_data = json.loads(direct_url_file) if "vcs_info" in direct_url_data: url = direct_url_data["url"] vcs_info = direct_url_data["vcs_info"] vcs = vcs_info["vcs"] commit_id = vcs_info["commit_id"] requested_revision = vcs_info.get("requested_revision") # Try a few variations, see https://peps.python.org/pep-0440/#direct-references if ( requested_revision and requirement.url == f"{vcs}+{url}@{requested_revision}#{commit_id}" ) or requirement.url == f"{vcs}+{url}@{commit_id}": return True if requirement.url in {f"{vcs}+{url}", f"{vcs}+{url}@{requested_revision}"}: import subprocess if vcs == "git": vcs_cmd = [vcs, "ls-remote", url] if requested_revision: vcs_cmd.append(requested_revision) # TODO: add elifs for hg, svn, and bzr https://github.com/pypa/hatch/issues/760 else: return False result = subprocess.run(vcs_cmd, capture_output=True, text=True) # noqa: PLW1510 if result.returncode or not result.stdout.strip(): return False latest_commit_id, *_ = result.stdout.split() return commit_id == latest_commit_id return False return True def dependencies_in_sync( requirements: list[Requirement], sys_path: list[str] | None = None, environment: dict[str, str] | None = None ) -> bool: if sys_path is None: sys_path = sys.path if environment is None: environment = default_environment() # type: ignore[assignment] installed_distributions = DistributionCache(sys_path) return all(dependency_in_sync(requirement, environment, installed_distributions) for requirement in requirements) # type: ignore[arg-type]
DistributionCache
python
pypa__pip
src/pip/_vendor/resolvelib/resolvers/exceptions.py
{ "start": 202, "end": 449 }
class ____(Exception): """A base class for all exceptions raised by this module. Exceptions derived by this class should all be handled in this module. Any bubbling pass the resolver should be treated as a bug. """
ResolverException
python
optuna__optuna
optuna/storages/_rdb/models.py
{ "start": 2470, "end": 3180 }
class ____(BaseModel): __tablename__ = "study_directions" __table_args__: Any = (UniqueConstraint("study_id", "objective"),) study_direction_id = _Column(Integer, primary_key=True) direction = _Column(Enum(StudyDirection), nullable=False) study_id = _Column(Integer, ForeignKey("studies.study_id"), nullable=False) objective = _Column(Integer, nullable=False) study = orm.relationship( StudyModel, backref=orm.backref("directions", cascade="all, delete-orphan") ) @classmethod def where_study_id(cls, study_id: int, session: orm.Session) -> list["StudyDirectionModel"]: return session.query(cls).filter(cls.study_id == study_id).all()
StudyDirectionModel
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 12745, "end": 14258 }
class ____(MaskedUfuncTests): # multiply.reduce does not work with units, so test only for plain array. # Similarly, modf only works for dimensionless, but we are using it just # to check multiple outputs get the right mask. @pytest.mark.parametrize("axis", (0, 1, None)) def test_multiply_reduce(self, axis): ma_reduce = np.multiply.reduce(self.ma, axis=axis) expected_data = np.multiply.reduce(self.a, axis=axis) expected_mask = np.logical_or.reduce(self.ma.mask, axis=axis) assert_array_equal(ma_reduce.unmasked, expected_data) assert_array_equal(ma_reduce.mask, expected_mask) def test_ufunc_two_out(self): out0 = np.empty_like(self.ma) out0_mask = out0.mask out1 = np.empty_like(self.ma) out1_mask = out1.mask res0, res1 = np.modf(self.ma, out=(out0, out1)) assert res0 is out0 assert res1 is out1 assert out0.mask is out0_mask assert out1.mask is out1_mask assert_array_equal(out0.mask, self.mask_a) assert_array_equal(out1.mask, self.mask_a) def test_ufunc_not_implemented_for_other(self): """ If the unmasked operation returns NotImplemented, this should lead to a TypeError also for the masked version. """ a = np.array([1, 2]) b = 3 * u.m with pytest.raises(TypeError): a & b ma = Masked(a) with pytest.raises(TypeError): ma & b
TestMaskedArrayUfuncs
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/no_self_use.py
{ "start": 891, "end": 988 }
class ____(Base): @override def abstract_method(self): print("concrete method")
Sub
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/executors/batch/utils.py
{ "start": 5145, "end": 5274 }
class ____(Exception): """Thrown when something unexpected has occurred within the AWS Batch ecosystem."""
BatchExecutorException
python
apache__airflow
dev/breeze/src/airflow_breeze/global_constants.py
{ "start": 7760, "end": 8504 }
class ____(Enum): AIRFLOW = "apache_airflow" PROVIDERS = "apache_airflow_providers" TASK_SDK = "apache_airflow_task_sdk" AIRFLOW_CTL = "apache_airflow_ctl" PYTHON_CLIENT = "apache_airflow_python_client" HELM_CHART = "helm-chart" DESTINATION_LOCATIONS = [ "s3://live-docs-airflow-apache-org/docs/", "s3://staging-docs-airflow-apache-org/docs/", ] PACKAGES_METADATA_EXCLUDE_NAMES = ["docker-stack", "apache-airflow-providers"] @clearable_cache def all_selective_core_test_types() -> tuple[str, ...]: return tuple(sorted(e.value for e in SelectiveCoreTestType)) @clearable_cache def providers_test_type() -> tuple[str, ...]: return tuple(sorted(e.value for e in SelectiveProvidersTestType))
TarBallType
python
dagster-io__dagster
python_modules/automation/automation/dagster_docs/public_api_validator.py
{ "start": 825, "end": 1057 }
class ____: """Represents a validation issue found during public API checking.""" issue_type: str # 'missing_rst', 'missing_public', 'missing_export' symbol_name: str module_path: str details: str
ValidationIssue
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_ddl.py
{ "start": 772, "end": 6919 }
class ____(fixtures.TestBase): __sparse_driver_backend__ = True def _simple_fixture(self, schema=None): return Table( "test_table", self.metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("data", String(50)), schema=schema, ) def _underscore_fixture(self): return Table( "_test_table", self.metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("_data", String(50)), ) def _table_index_fixture(self, schema=None): table = self._simple_fixture(schema=schema) idx = Index("test_index", table.c.data) return table, idx def _simple_roundtrip(self, table): with config.db.begin() as conn: conn.execute(table.insert().values((1, "some data"))) result = conn.execute(table.select()) eq_(result.first(), (1, "some data")) @requirements.create_table @util.provide_metadata def test_create_table(self): table = self._simple_fixture() table.create(config.db, checkfirst=False) self._simple_roundtrip(table) @requirements.create_table @requirements.schemas @util.provide_metadata def test_create_table_schema(self): table = self._simple_fixture(schema=config.test_schema) table.create(config.db, checkfirst=False) self._simple_roundtrip(table) @requirements.drop_table @util.provide_metadata def test_drop_table(self): table = self._simple_fixture() table.create(config.db, checkfirst=False) table.drop(config.db, checkfirst=False) @requirements.create_table @util.provide_metadata def test_underscore_names(self): table = self._underscore_fixture() table.create(config.db, checkfirst=False) self._simple_roundtrip(table) @requirements.comment_reflection @util.provide_metadata def test_add_table_comment(self, connection): table = self._simple_fixture() table.create(connection, checkfirst=False) table.comment = "a comment" connection.execute(schema.SetTableComment(table)) eq_( inspect(connection).get_table_comment("test_table"), {"text": "a comment"}, ) @requirements.comment_reflection @util.provide_metadata def test_drop_table_comment(self, connection): table = self._simple_fixture() table.create(connection, checkfirst=False) table.comment = "a comment" connection.execute(schema.SetTableComment(table)) connection.execute(schema.DropTableComment(table)) eq_( inspect(connection).get_table_comment("test_table"), {"text": None} ) @requirements.table_ddl_if_exists @util.provide_metadata def test_create_table_if_not_exists(self, connection): table = self._simple_fixture() connection.execute(schema.CreateTable(table, if_not_exists=True)) is_true(inspect(connection).has_table("test_table")) connection.execute(schema.CreateTable(table, if_not_exists=True)) @requirements.table_ddl_if_exists @util.provide_metadata def test_create_table_if_not_exists_via_create(self, connection): table = self._simple_fixture() table.set_creator_ddl(schema.CreateTable(table, if_not_exists=True)) table.create(connection, checkfirst=False) is_true(inspect(connection).has_table("test_table")) # works! table.create(connection, checkfirst=False) @requirements.index_ddl_if_exists @util.provide_metadata def test_create_index_if_not_exists(self, connection): table, idx = self._table_index_fixture() connection.execute(schema.CreateTable(table, if_not_exists=True)) is_true(inspect(connection).has_table("test_table")) is_false( "test_index" in [ ix["name"] for ix in inspect(connection).get_indexes("test_table") ] ) connection.execute(schema.CreateIndex(idx, if_not_exists=True)) is_true( "test_index" in [ ix["name"] for ix in inspect(connection).get_indexes("test_table") ] ) connection.execute(schema.CreateIndex(idx, if_not_exists=True)) @requirements.table_ddl_if_exists @util.provide_metadata def test_drop_table_if_exists(self, connection): table = self._simple_fixture() table.create(connection) is_true(inspect(connection).has_table("test_table")) connection.execute(schema.DropTable(table, if_exists=True)) is_false(inspect(connection).has_table("test_table")) connection.execute(schema.DropTable(table, if_exists=True)) @requirements.table_ddl_if_exists @util.provide_metadata def test_drop_table_if_exists_via_drop(self, connection): table = self._simple_fixture() table.create(connection) is_true(inspect(connection).has_table("test_table")) table.set_dropper_ddl(schema.DropTable(table, if_exists=True)) table.drop(connection, checkfirst=False) is_false(inspect(connection).has_table("test_table")) # works!! table.drop(connection, checkfirst=False) @requirements.index_ddl_if_exists @util.provide_metadata def test_drop_index_if_exists(self, connection): table, idx = self._table_index_fixture() table.create(connection) is_true( "test_index" in [ ix["name"] for ix in inspect(connection).get_indexes("test_table") ] ) connection.execute(schema.DropIndex(idx, if_exists=True)) is_false( "test_index" in [ ix["name"] for ix in inspect(connection).get_indexes("test_table") ] ) connection.execute(schema.DropIndex(idx, if_exists=True))
TableDDLTest
python
aio-libs__aiohttp
aiohttp/web_request.py
{ "start": 1669, "end": 2769 }
class ____: name: str filename: str file: io.BufferedReader content_type: str headers: CIMultiDictProxy[str] _TCHAR: Final[str] = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-" # '-' at the end to prevent interpretation as range in a char class _TOKEN: Final[str] = rf"[{_TCHAR}]+" _QDTEXT: Final[str] = r"[{}]".format( r"".join(chr(c) for c in (0x09, 0x20, 0x21) + tuple(range(0x23, 0x7F))) ) # qdtext includes 0x5C to escape 0x5D ('\]') # qdtext excludes obs-text (because obsoleted, and encoding not specified) _QUOTED_PAIR: Final[str] = r"\\[\t !-~]" _QUOTED_STRING: Final[str] = rf'"(?:{_QUOTED_PAIR}|{_QDTEXT})*"' _FORWARDED_PAIR: Final[str] = rf"({_TOKEN})=({_TOKEN}|{_QUOTED_STRING})(:\d{{1,4}})?" _QUOTED_PAIR_REPLACE_RE: Final[Pattern[str]] = re.compile(r"\\([\t !-~])") # same pattern as _QUOTED_PAIR but contains a capture group _FORWARDED_PAIR_RE: Final[Pattern[str]] = re.compile(_FORWARDED_PAIR) ############################################################ # HTTP Request ############################################################
FileField
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 972102, "end": 972544 }
class ____(sgqlc.types.Type): """Represents a user or organization who is sponsoring someone in GitHub Sponsors. """ __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("Sponsor", graphql_name="node") """The item at the end of the edge."""
SponsorEdge
python
pennersr__django-allauth
allauth/socialaccount/providers/oauth2/views.py
{ "start": 3785, "end": 3908 }
class ____(OAuth2View, BaseLoginView): def get_provider(self): return self.adapter.get_provider()
OAuth2LoginView
python
celery__celery
t/integration/test_canvas.py
{ "start": 61587, "end": 124964 }
class ____: @flaky def test_simple_chord_with_a_delay_in_group_save(self, manager, monkeypatch): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) if not isinstance(manager.app.backend, BaseKeyValueStoreBackend): raise pytest.skip("The delay may only occur in the cache backend") x = BaseKeyValueStoreBackend._apply_chord_incr def apply_chord_incr_with_sleep(self, *args, **kwargs): sleep(1) x(self, *args, **kwargs) monkeypatch.setattr(BaseKeyValueStoreBackend, '_apply_chord_incr', apply_chord_incr_with_sleep) c = chord(header=[add.si(1, 1), add.si(1, 1)], body=tsum.s()) result = c() assert result.get(timeout=TIMEOUT) == 4 def test_chord_order(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) inputs = [i for i in range(10)] c = chord((identity.si(i) for i in inputs), identity.s()) result = c() assert result.get() == inputs @pytest.mark.xfail(reason="async_results aren't performed in async way") def test_redis_subscribed_channels_leak(self, manager): if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') manager.app.backend.result_consumer.on_after_fork() initial_channels = get_active_redis_channels() initial_channels_count = len(initial_channels) total_chords = 10 async_results = [ chord([add.s(5, 6), add.s(6, 7)])(delayed_sum.s()) for _ in range(total_chords) ] channels_before = get_active_redis_channels() manager.assert_result_tasks_in_progress_or_completed(async_results) channels_before_count = len(channels_before) assert set(channels_before) != set(initial_channels) assert channels_before_count > initial_channels_count # The total number of active Redis channels at this point # is the number of chord header tasks multiplied by the # total chord tasks, plus the initial channels # (existing from previous tests). chord_header_task_count = 2 assert channels_before_count <= \ chord_header_task_count * total_chords + initial_channels_count result_values = [ result.get(timeout=TIMEOUT) for result in async_results ] assert result_values == [24] * total_chords channels_after = get_active_redis_channels() channels_after_count = len(channels_after) assert channels_after_count == initial_channels_count assert set(channels_after) == set(initial_channels) @flaky def test_replaced_nested_chord(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chord([ chord( [add.s(1, 2), add_replaced.s(3, 4)], add_to_all.s(5), ) | tsum.s(), chord( [add_replaced.s(6, 7), add.s(0, 0)], add_to_all.s(8), ) | tsum.s(), ], add_to_all.s(9)) res1 = c1() assert res1.get(timeout=TIMEOUT) == [29, 38] @flaky def test_add_to_chord(self, manager): if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') c = group([add_to_all_to_chord.s([1, 2, 3], 4)]) | identity.s() res = c() assert sorted(res.get()) == [0, 5, 6, 7] @flaky def test_add_chord_to_chord(self, manager): if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') c = group([add_chord_to_chord.s([1, 2, 3], 4)]) | identity.s() res = c() assert sorted(res.get()) == [0, 5 + 6 + 7] @flaky def test_eager_chord_inside_task(self, manager): from .tasks import chord_add prev = chord_add.app.conf.task_always_eager chord_add.app.conf.task_always_eager = True chord_add.apply_async(args=(4, 8), throw=True).get() chord_add.app.conf.task_always_eager = prev def test_group_chain(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = ( add.s(2, 2) | group(add.s(i) for i in range(4)) | add_to_all.s(8) ) res = c() assert res.get(timeout=TIMEOUT) == [12, 13, 14, 15] def test_group_kwargs(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = ( add.s(2, 2) | group(add.s(i) for i in range(4)) | add_to_all.s(8) ) res = c.apply_async(kwargs={"z": 1}) assert res.get(timeout=TIMEOUT) == [13, 14, 15, 16] def test_group_args_and_kwargs(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = ( group(add.s(i) for i in range(4)) | add_to_all.s(8) ) res = c.apply_async(args=(4,), kwargs={"z": 1}) if manager.app.conf.result_backend.startswith('redis'): # for a simple chord like the one above, redis does not guarantee # the ordering of the results as a performance trade off. assert set(res.get(timeout=TIMEOUT)) == {13, 14, 15, 16} else: assert res.get(timeout=TIMEOUT) == [13, 14, 15, 16] def test_nested_group_chain(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = chain( add.si(1, 0), group( add.si(1, 100), chain( add.si(1, 200), group( add.si(1, 1000), add.si(1, 2000), ), ), ), add.si(1, 10), ) res = c() assert res.get(timeout=TIMEOUT) == 11 @flaky def test_single_task_header(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chord([add.s(2, 5)], body=add_to_all.s(9)) res1 = c1() assert res1.get(timeout=TIMEOUT) == [16] c2 = group([add.s(2, 5)]) | add_to_all.s(9) res2 = c2() assert res2.get(timeout=TIMEOUT) == [16] def test_empty_header_chord(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chord([], body=add_to_all.s(9)) res1 = c1() assert res1.get(timeout=TIMEOUT) == [] c2 = group([]) | add_to_all.s(9) res2 = c2() assert res2.get(timeout=TIMEOUT) == [] @flaky def test_nested_chord(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chord([ chord([add.s(1, 2), add.s(3, 4)], add.s([5])), chord([add.s(6, 7)], add.s([10])) ], add_to_all.s(['A'])) res1 = c1() assert res1.get(timeout=TIMEOUT) == [[3, 7, 5, 'A'], [13, 10, 'A']] c2 = group([ group([add.s(1, 2), add.s(3, 4)]) | add.s([5]), group([add.s(6, 7)]) | add.s([10]), ]) | add_to_all.s(['A']) res2 = c2() assert res2.get(timeout=TIMEOUT) == [[3, 7, 5, 'A'], [13, 10, 'A']] c = group([ group([ group([ group([ add.s(1, 2) ]) | add.s([3]) ]) | add.s([4]) ]) | add.s([5]) ]) | add.s([6]) res = c() assert [[[[3, 3], 4], 5], 6] == res.get(timeout=TIMEOUT) @flaky def test_parent_ids(self, manager): if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') root = ids.si(i=1) expected_root_id = root.freeze().id g = chain( root, ids.si(i=2), chord( group(ids.si(i=i) for i in range(3, 50)), chain(collect_ids.s(i=50) | ids.si(i=51)), ), ) self.assert_parentids_chord(g(), expected_root_id) @flaky def test_parent_ids__OR(self, manager): if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') root = ids.si(i=1) expected_root_id = root.freeze().id g = ( root | ids.si(i=2) | group(ids.si(i=i) for i in range(3, 50)) | collect_ids.s(i=50) | ids.si(i=51) ) self.assert_parentids_chord(g(), expected_root_id) def assert_parentids_chord(self, res, expected_root_id): assert isinstance(res, AsyncResult) assert isinstance(res.parent, AsyncResult) assert isinstance(res.parent.parent, GroupResult) assert isinstance(res.parent.parent.parent, AsyncResult) assert isinstance(res.parent.parent.parent.parent, AsyncResult) # first we check the last task assert_ids(res, 51, expected_root_id, res.parent.id) # then the chord callback prev, (root_id, parent_id, value) = res.parent.get(timeout=30) assert value == 50 assert root_id == expected_root_id # started by one of the chord header tasks. assert parent_id in res.parent.parent.results # check what the chord callback recorded for i, p in enumerate(prev): root_id, parent_id, value = p assert root_id == expected_root_id assert parent_id == res.parent.parent.parent.id # ids(i=2) root_id, parent_id, value = res.parent.parent.parent.get(timeout=30) assert value == 2 assert parent_id == res.parent.parent.parent.parent.id assert root_id == expected_root_id # ids(i=1) root_id, parent_id, value = res.parent.parent.parent.parent.get( timeout=30) assert value == 1 assert root_id == expected_root_id assert parent_id is None def test_chord_on_error(self, manager): from celery import states from .tasks import ExpectedException if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') # Run the chord and wait for the error callback to finish. Note that # this only works for old style callbacks since they get dispatched to # run async while new style errbacks are called synchronously so that # they can be passed the request object for the failing task. c1 = chord( header=[add.s(1, 2), add.s(3, 4), fail.s()], body=print_unicode.s('This should not be called').on_error( errback_old_style.s()), ) res = c1() with pytest.raises(ExpectedException): res.get(propagate=True) # Got to wait for children to populate. check = ( lambda: res.children, lambda: res.children[0].children, lambda: res.children[0].children[0].result, ) start = monotonic() while not all(f() for f in check): if monotonic() > start + TIMEOUT: raise TimeoutError("Timed out waiting for children") sleep(0.1) # Extract the results of the successful tasks from the chord. # # We could do this inside the error handler, and probably would in a # real system, but for the purposes of the test it's obnoxious to get # data out of the error handler. # # So for clarity of our test, we instead do it here. # Use the error callback's result to find the failed task. uuid_patt = re.compile( r"[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}" ) callback_chord_exc = AsyncResult( res.children[0].children[0].result ).result failed_task_id = uuid_patt.search(str(callback_chord_exc)) assert (failed_task_id is not None), "No task ID in %r" % callback_chord_exc failed_task_id = failed_task_id.group() # Use new group_id result metadata to get group ID. failed_task_result = AsyncResult(failed_task_id) original_group_id = failed_task_result._get_task_meta()['group_id'] # Use group ID to get preserved group result. backend = fail.app.backend j_key = backend.get_key_for_group(original_group_id, '.j') redis_connection = get_redis_connection() # The redis key is either a list or a zset (a redis sorted set) depending on configuration if manager.app.conf.result_backend_transport_options.get( 'result_chord_ordered', True ): job_results = redis_connection.zrange(j_key, 0, 3) else: job_results = redis_connection.lrange(j_key, 0, 3) chord_results = [backend.decode(t) for t in job_results] # Validate group result assert [cr[3] for cr in chord_results if cr[2] == states.SUCCESS] == \ [3, 7] assert len([cr for cr in chord_results if cr[2] != states.SUCCESS] ) == 1 @flaky @pytest.mark.parametrize('size', [3, 4, 5, 6, 7, 8, 9]) def test_generator(self, manager, size): if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') def assert_generator(file_name): for i in range(size): sleep(1) if i == size - 1: with open(file_name) as file_handle: # ensures chord header generators tasks are processed incrementally #3021 assert file_handle.readline() == '0\n', "Chord header was unrolled too early" yield write_to_file_and_return_int.s(file_name, i) with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file: file_name = tmp_file.name c = chord(assert_generator(file_name), tsum.s()) assert c().get(timeout=TIMEOUT) == size * (size - 1) // 2 @flaky def test_parallel_chords(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chord(group(add.s(1, 2), add.s(3, 4)), tsum.s()) c2 = chord(group(add.s(1, 2), add.s(3, 4)), tsum.s()) g = group(c1, c2) r = g.delay() assert r.get(timeout=TIMEOUT) == [10, 10] @flaky def test_chord_in_chords_with_chains(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = chord( group([ chain( add.si(1, 2), chord( group([add.si(1, 2), add.si(1, 2)]), add.si(1, 2), ), ), chain( add.si(1, 2), chord( group([add.si(1, 2), add.si(1, 2)]), add.si(1, 2), ), ), ]), add.si(2, 2) ) r = c.delay() assert r.get(timeout=TIMEOUT) == 4 @flaky def test_chain_chord_chain_chord(self, manager): # test for #2573 try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = chain( identity.si(1), chord( [ identity.si(2), chain( identity.si(3), chord( [identity.si(4), identity.si(5)], identity.si(6) ) ) ], identity.si(7) ) ) res = c.delay() assert res.get(timeout=TIMEOUT) == 7 @pytest.mark.xfail(reason="Issue #6176") def test_chord_in_chain_with_args(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chain( chord( [identity.s(), identity.s()], identity.s(), ), identity.s(), ) res1 = c1.apply_async(args=(1,)) assert res1.get(timeout=TIMEOUT) == [1, 1] res1 = c1.apply(args=(1,)) assert res1.get(timeout=TIMEOUT) == [1, 1] @pytest.mark.xfail(reason="Issue #6200") def test_chain_in_chain_with_args(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c1 = chain( # NOTE: This chain should have only 1 chain inside it chain( identity.s(), identity.s(), ), ) res1 = c1.apply_async(args=(1,)) assert res1.get(timeout=TIMEOUT) == 1 res1 = c1.apply(args=(1,)) assert res1.get(timeout=TIMEOUT) == 1 @flaky def test_large_header(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = group(identity.si(i) for i in range(1000)) | tsum.s() res = c.delay() assert res.get(timeout=TIMEOUT) == 499500 @flaky def test_chain_to_a_chord_with_large_header(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) c = identity.si(1) | group( identity.s() for _ in range(1000)) | tsum.s() res = c.delay() assert res.get(timeout=TIMEOUT) == 1000 @flaky def test_priority(self, manager): c = chain(return_priority.signature(priority=3))() assert c.get(timeout=TIMEOUT) == "Priority: 3" @flaky def test_priority_chain(self, manager): c = return_priority.signature(priority=3) | return_priority.signature( priority=5) assert c().get(timeout=TIMEOUT) == "Priority: 5" def test_nested_chord_group(self, manager): """ Confirm that groups nested inside chords get unrolled. """ try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) sig = chord( ( group(identity.s(42), identity.s(42)), # [42, 42] ), identity.s() # [42, 42] ) res = sig.delay() assert res.get(timeout=TIMEOUT) == [42, 42] def test_nested_chord_group_chain_group_tail(self, manager): """ Sanity check that a deeply nested group is completed as expected. Groups at the end of chains nested in chords have had issues and this simple test sanity check that such a task structure can be completed. """ try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) sig = chord( group( chain( identity.s(42), # 42 group( identity.s(), # 42 identity.s(), # 42 ), # [42, 42] ), # [42, 42] ), # [[42, 42]] since the chain prevents unrolling identity.s(), # [[42, 42]] ) res = sig.delay() assert res.get(timeout=TIMEOUT) == [[42, 42]] @pytest.mark.xfail(TEST_BACKEND.startswith('redis://'), reason="Issue #6437") def test_error_propagates_from_chord(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) sig = add.s(1, 1) | fail.s() | group(add.s(1), add.s(1)) res = sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) def test_error_propagates_from_chord2(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) sig = add.s(1, 1) | add.s(1) | group(add.s(1), fail.s()) res = sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) def test_error_propagates_to_chord_from_simple(self, manager, subtests): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) child_sig = fail.s() chord_sig = chord((child_sig,), identity.s()) with subtests.test(msg="Error propagates from simple header task"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) chord_sig = chord((identity.si(42),), child_sig) with subtests.test(msg="Error propagates from simple body task"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) def test_immutable_errback_called_by_chord_from_simple( self, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback_msg = str(uuid.uuid4()).encode() redis_key = str(uuid.uuid4()) errback = redis_echo.si(errback_msg, redis_key=redis_key) child_sig = fail.s() chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test(msg="Error propagates from simple header task"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after simple header task fails" ): await_redis_echo({errback_msg, }, redis_key=redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test(msg="Error propagates from simple body task"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after simple body task fails" ): await_redis_echo({errback_msg, }, redis_key=redis_key) redis_connection.delete(redis_key) @pytest.mark.parametrize( "errback_task", [errback_old_style, errback_new_style, ], ) def test_mutable_errback_called_by_chord_from_simple( self, errback_task, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback = errback_task.s() child_sig = fail.s() chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) expected_redis_key = chord_sig.body.freeze().id redis_connection.delete(expected_redis_key) with subtests.test(msg="Error propagates from simple header task"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after simple header task fails" ): await_redis_count(1, redis_key=expected_redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) expected_redis_key = chord_sig.body.freeze().id redis_connection.delete(expected_redis_key) with subtests.test(msg="Error propagates from simple body task"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after simple body task fails" ): await_redis_count(1, redis_key=expected_redis_key) redis_connection.delete(expected_redis_key) def test_error_propagates_to_chord_from_chain(self, manager, subtests): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) child_sig = chain(identity.si(42), fail.s(), identity.si(42)) chord_sig = chord((child_sig,), identity.s()) with subtests.test( msg="Error propagates from header chain which fails before the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) chord_sig = chord((identity.si(42),), child_sig) with subtests.test( msg="Error propagates from body chain which fails before the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) def test_immutable_errback_called_by_chord_from_chain( self, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback_msg = str(uuid.uuid4()).encode() redis_key = str(uuid.uuid4()) errback = redis_echo.si(errback_msg, redis_key=redis_key) child_sig = chain(identity.si(42), fail.s(), identity.si(42)) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test( msg="Error propagates from header chain which fails before the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after header chain which fails before the end" ): await_redis_echo({errback_msg, }, redis_key=redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test( msg="Error propagates from body chain which fails before the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after body chain which fails before the end" ): await_redis_echo({errback_msg, }, redis_key=redis_key) redis_connection.delete(redis_key) @pytest.mark.parametrize( "errback_task", [errback_old_style, errback_new_style, ], ) def test_mutable_errback_called_by_chord_from_chain( self, errback_task, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback = errback_task.s() fail_sig = fail.s() fail_sig_id = fail_sig.freeze().id child_sig = chain(identity.si(42), fail_sig, identity.si(42)) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) expected_redis_key = chord_sig.body.freeze().id redis_connection.delete(expected_redis_key) with subtests.test( msg="Error propagates from header chain which fails before the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after header chain which fails before the end" ): await_redis_count(1, redis_key=expected_redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) expected_redis_key = fail_sig_id redis_connection.delete(expected_redis_key) with subtests.test( msg="Error propagates from body chain which fails before the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after body chain which fails before the end" ): await_redis_count(1, redis_key=expected_redis_key) redis_connection.delete(expected_redis_key) def test_error_propagates_to_chord_from_chain_tail(self, manager, subtests): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) child_sig = chain(identity.si(42), fail.s()) chord_sig = chord((child_sig,), identity.s()) with subtests.test( msg="Error propagates from header chain which fails at the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) chord_sig = chord((identity.si(42),), child_sig) with subtests.test( msg="Error propagates from body chain which fails at the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) def test_immutable_errback_called_by_chord_from_chain_tail( self, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback_msg = str(uuid.uuid4()).encode() redis_key = str(uuid.uuid4()) errback = redis_echo.si(errback_msg, redis_key=redis_key) child_sig = chain(identity.si(42), fail.s()) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test( msg="Error propagates from header chain which fails at the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after header chain which fails at the end" ): await_redis_echo({errback_msg, }, redis_key=redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test( msg="Error propagates from body chain which fails at the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after body chain which fails at the end" ): await_redis_echo({errback_msg, }, redis_key=redis_key) redis_connection.delete(redis_key) @pytest.mark.parametrize( "errback_task", [errback_old_style, errback_new_style, ], ) def test_mutable_errback_called_by_chord_from_chain_tail( self, errback_task, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback = errback_task.s() fail_sig = fail.s() fail_sig_id = fail_sig.freeze().id child_sig = chain(identity.si(42), fail_sig) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) expected_redis_key = chord_sig.body.freeze().id redis_connection.delete(expected_redis_key) with subtests.test( msg="Error propagates from header chain which fails at the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after header chain which fails at the end" ): await_redis_count(1, redis_key=expected_redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) expected_redis_key = fail_sig_id redis_connection.delete(expected_redis_key) with subtests.test( msg="Error propagates from header chain which fails at the end" ): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test( msg="Errback is called after header chain which fails at the end" ): await_redis_count(1, redis_key=expected_redis_key) redis_connection.delete(expected_redis_key) def test_error_propagates_to_chord_from_group(self, manager, subtests): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) child_sig = group(identity.si(42), fail.s()) chord_sig = chord((child_sig,), identity.s()) with subtests.test(msg="Error propagates from header group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) chord_sig = chord((identity.si(42),), child_sig) with subtests.test(msg="Error propagates from body group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) def test_immutable_errback_called_by_chord_from_group( self, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback_msg = str(uuid.uuid4()).encode() redis_key = str(uuid.uuid4()) errback = redis_echo.si(errback_msg, redis_key=redis_key) child_sig = group(identity.si(42), fail.s()) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test(msg="Error propagates from header group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after header group fails"): await_redis_echo({errback_msg, }, redis_key=redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test(msg="Error propagates from body group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after body group fails"): await_redis_echo({errback_msg, }, redis_key=redis_key) redis_connection.delete(redis_key) @flaky @pytest.mark.parametrize( "errback_task", [errback_old_style, errback_new_style, ], ) def test_mutable_errback_called_by_chord_from_group( self, errback_task, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback = errback_task.s() fail_sig = fail.s() fail_sig_id = fail_sig.freeze().id child_sig = group(identity.si(42), fail_sig) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) expected_redis_key = chord_sig.body.freeze().id redis_connection.delete(expected_redis_key) with subtests.test(msg="Error propagates from header group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after header group fails"): await_redis_count(1, redis_key=expected_redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) expected_redis_key = fail_sig_id redis_connection.delete(expected_redis_key) with subtests.test(msg="Error propagates from body group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after body group fails"): await_redis_count(1, redis_key=expected_redis_key) redis_connection.delete(expected_redis_key) def test_immutable_errback_called_by_chord_from_group_fail_multiple( self, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() fail_task_count = 42 redis_key = str(uuid.uuid4()) errback = redis_count.si(redis_key=redis_key) # Include a mix of passing and failing tasks child_sig = group( *(identity.si(42) for _ in range(24)), # arbitrary task count *(fail.s() for _ in range(fail_task_count)), ) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test(msg="Error propagates from header group"): redis_connection.delete(redis_key) res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after header group fails"): # NOTE: Here we only expect the errback to be called once since it # is attached to the chord body which is a single task! await_redis_count(1, redis_key=redis_key) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) redis_connection.delete(redis_key) with subtests.test(msg="Error propagates from body group"): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after body group fails"): # NOTE: Here we expect the errback to be called once per failing # task in the chord body since it is a group await_redis_count(fail_task_count, redis_key=redis_key) redis_connection.delete(redis_key) @pytest.mark.parametrize("errback_task", [errback_old_style, errback_new_style]) def test_mutable_errback_called_by_chord_from_group_fail_multiple_on_header_failure( self, errback_task, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() fail_task_count = 42 # We have to use failing task signatures with unique task IDs to ensure # the chord can complete when they are used as part of its header! fail_sigs = tuple( fail.s() for _ in range(fail_task_count) ) errback = errback_task.s() # Include a mix of passing and failing tasks child_sig = group( *(identity.si(42) for _ in range(8)), # arbitrary task count *fail_sigs, ) chord_sig = chord((child_sig,), identity.s()) chord_sig.link_error(errback) expected_redis_key = chord_sig.body.freeze().id redis_connection.delete(expected_redis_key) with subtests.test(msg="Error propagates from header group"): res = chord_sig.delay() sleep(1) with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after header group fails"): # NOTE: Here we only expect the errback to be called once since it # is attached to the chord body which is a single task! await_redis_count(1, redis_key=expected_redis_key) @pytest.mark.parametrize("errback_task", [errback_old_style, errback_new_style]) def test_mutable_errback_called_by_chord_from_group_fail_multiple_on_body_failure( self, errback_task, manager, subtests ): if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() fail_task_count = 42 # We have to use failing task signatures with unique task IDs to ensure # the chord can complete when they are used as part of its header! fail_sigs = tuple( fail.s() for _ in range(fail_task_count) ) fail_sig_ids = tuple(s.freeze().id for s in fail_sigs) errback = errback_task.s() # Include a mix of passing and failing tasks child_sig = group( *(identity.si(42) for _ in range(8)), # arbitrary task count *fail_sigs, ) chord_sig = chord((identity.si(42),), child_sig) chord_sig.link_error(errback) for fail_sig_id in fail_sig_ids: redis_connection.delete(fail_sig_id) with subtests.test(msg="Error propagates from body group"): res = chord_sig.delay() sleep(1) with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg="Errback is called after body group fails"): # NOTE: Here we expect the errback to be called once per failing # task in the chord body since it is a group, and each task has a # unique task ID for i, fail_sig_id in enumerate(fail_sig_ids): await_redis_count( 1, redis_key=fail_sig_id, # After the first one is seen, check the rest with no # timeout since waiting to confirm that each one doesn't # get over-incremented will take a long time timeout=TIMEOUT if i == 0 else 0, ) for fail_sig_id in fail_sig_ids: redis_connection.delete(fail_sig_id) def test_chord_header_task_replaced_with_chain(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( replace_with_chain.si(42), identity.s(), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42] def test_chord_header_child_replaced_with_chain_first(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( (replace_with_chain.si(42), identity.s(1337),), identity.s(), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42, 1337] def test_chord_header_child_replaced_with_chain_middle(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( (identity.s(42), replace_with_chain.s(1337), identity.s(31337),), identity.s(), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42, 1337, 31337] def test_chord_header_child_replaced_with_chain_last(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( (identity.s(42), replace_with_chain.s(1337),), identity.s(), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42, 1337] def test_chord_body_task_replaced_with_chain(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( identity.s(42), replace_with_chain.s(), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42] def test_chord_body_chain_child_replaced_with_chain_first(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( identity.s(42), chain(replace_with_chain.s(), identity.s(), ), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42] def test_chord_body_chain_child_replaced_with_chain_middle(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( identity.s(42), chain(identity.s(), replace_with_chain.s(), identity.s(), ), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42] def test_chord_body_chain_child_replaced_with_chain_last(self, manager): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) orig_sig = chord( identity.s(42), chain(identity.s(), replace_with_chain.s(), ), ) res_obj = orig_sig.delay() assert res_obj.get(timeout=TIMEOUT) == [42] def test_nested_chord_header_link_error(self, manager, subtests): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) if not manager.app.conf.result_backend.startswith("redis"): raise pytest.skip("Requires redis result backend.") redis_connection = get_redis_connection() errback_msg = "errback called" errback_key = "echo_errback" errback_sig = redis_echo.si(errback_msg, redis_key=errback_key) body_msg = "chord body called" body_key = "echo_body" body_sig = redis_echo.si(body_msg, redis_key=body_key) redis_connection.delete(errback_key, body_key) manager.app.conf.task_allow_error_cb_on_chord_header = False chord_inner = chord( [identity.si("t1"), fail.si()], identity.si("t2 (body)"), ) chord_outer = chord( group( [ identity.si("t3"), chord_inner, ], ), body_sig, ) chord_outer.link_error(errback_sig) chord_outer.delay() with subtests.test(msg="Confirm the body was not executed"): with pytest.raises(TimeoutError): # confirm the chord body was not called await_redis_echo((body_msg,), redis_key=body_key, timeout=10) # Double check assert not redis_connection.exists(body_key), "Chord body was called when it should have not" with subtests.test(msg="Confirm only one errback was called"): await_redis_echo((errback_msg,), redis_key=errback_key, timeout=10) with pytest.raises(TimeoutError): # Double check await_redis_echo((errback_msg,), redis_key=errback_key, timeout=10) # Cleanup redis_connection.delete(errback_key) def test_enabling_flag_allow_error_cb_on_chord_header(self, manager, subtests): """ Test that the flag allow_error_callback_on_chord_header works as expected. To confirm this, we create a chord with a failing header task, and check that the body does not execute when the header task fails. This allows preventing the body from executing when the chord header fails when the flag is turned on. In addition, we make sure the body error callback is also executed when the header fails and the flag is turned on. """ try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') redis_connection = get_redis_connection() manager.app.conf.task_allow_error_cb_on_chord_header = True header_errback_msg = 'header errback called' header_errback_key = 'echo_header_errback' header_errback_sig = redis_echo.si(header_errback_msg, redis_key=header_errback_key) body_errback_msg = 'body errback called' body_errback_key = 'echo_body_errback' body_errback_sig = redis_echo.si(body_errback_msg, redis_key=body_errback_key) body_msg = 'chord body called' body_key = 'echo_body' body_sig = redis_echo.si(body_msg, redis_key=body_key) headers = ( (fail.si(),), (fail.si(), fail.si(), fail.si()), (fail.si(), identity.si(42)), (fail.si(), identity.si(42), identity.si(42)), (fail.si(), identity.si(42), fail.si()), (fail.si(), identity.si(42), fail.si(), identity.si(42)), (fail.si(), identity.si(42), fail.si(), identity.si(42), fail.si()), ) # for some reason using parametrize breaks the test so we do it manually unfortunately for header in headers: chord_sig = chord(header, body_sig) # link error to chord header ONLY [header_task.link_error(header_errback_sig) for header_task in chord_sig.tasks] # link error to chord body ONLY chord_sig.body.link_error(body_errback_sig) redis_connection.delete(header_errback_key, body_errback_key, body_key) with subtests.test(msg='Error propagates from failure in header'): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg='Confirm the body was not executed'): with pytest.raises(TimeoutError): # confirm the chord body was not called await_redis_echo((body_msg,), redis_key=body_key, timeout=10) # Double check assert not redis_connection.exists(body_key), 'Chord body was called when it should have not' with subtests.test(msg='Confirm the errback was called for each failed header task + body'): # confirm the errback was called for each task in the chord header failed_header_tasks_count = len(list(filter(lambda f_sig: f_sig == fail.si(), header))) expected_header_errbacks = tuple(header_errback_msg for _ in range(failed_header_tasks_count)) await_redis_echo(expected_header_errbacks, redis_key=header_errback_key) # confirm the errback was called for the chord body await_redis_echo((body_errback_msg,), redis_key=body_errback_key) redis_connection.delete(header_errback_key, body_errback_key) def test_disabling_flag_allow_error_cb_on_chord_header(self, manager, subtests): """ Confirm that when allow_error_callback_on_chord_header is disabled, the default behavior is kept. """ try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') redis_connection = get_redis_connection() manager.app.conf.task_allow_error_cb_on_chord_header = False errback_msg = 'errback called' errback_key = 'echo_errback' errback_sig = redis_echo.si(errback_msg, redis_key=errback_key) body_msg = 'chord body called' body_key = 'echo_body' body_sig = redis_echo.si(body_msg, redis_key=body_key) headers = ( (fail.si(),), (fail.si(), fail.si(), fail.si()), (fail.si(), identity.si(42)), (fail.si(), identity.si(42), identity.si(42)), (fail.si(), identity.si(42), fail.si()), (fail.si(), identity.si(42), fail.si(), identity.si(42)), (fail.si(), identity.si(42), fail.si(), identity.si(42), fail.si()), ) # for some reason using parametrize breaks the test so we do it manually unfortunately for header in headers: chord_sig = chord(header, body_sig) chord_sig.link_error(errback_sig) redis_connection.delete(errback_key, body_key) with subtests.test(msg='Error propagates from failure in header'): res = chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg='Confirm the body was not executed'): with pytest.raises(TimeoutError): # confirm the chord body was not called await_redis_echo((body_msg,), redis_key=body_key, timeout=10) # Double check assert not redis_connection.exists(body_key), 'Chord body was called when it should have not' with subtests.test(msg='Confirm only one errback was called'): await_redis_echo((errback_msg,), redis_key=errback_key, timeout=10) with pytest.raises(TimeoutError): await_redis_echo((errback_msg,), redis_key=errback_key, timeout=10) # Cleanup redis_connection.delete(errback_key) def test_flag_allow_error_cb_on_chord_header_on_upgraded_chord(self, manager, subtests): """ Confirm that allow_error_callback_on_chord_header flag supports upgraded chords """ try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') redis_connection = get_redis_connection() manager.app.conf.task_allow_error_cb_on_chord_header = True errback_msg = 'errback called' errback_key = 'echo_errback' errback_sig = redis_echo.si(errback_msg, redis_key=errback_key) body_msg = 'chord body called' body_key = 'echo_body' body_sig = redis_echo.si(body_msg, redis_key=body_key) headers = ( # (fail.si(),), <-- this is not supported because it's not a valid chord header (only one task) (fail.si(), fail.si(), fail.si()), (fail.si(), identity.si(42)), (fail.si(), identity.si(42), identity.si(42)), (fail.si(), identity.si(42), fail.si()), (fail.si(), identity.si(42), fail.si(), identity.si(42)), (fail.si(), identity.si(42), fail.si(), identity.si(42), fail.si()), ) # for some reason using parametrize breaks the test so we do it manually unfortunately for header in headers: implicit_chord_sig = chain(group(list(header)), body_sig) implicit_chord_sig.link_error(errback_sig) redis_connection.delete(errback_key, body_key) with subtests.test(msg='Error propagates from failure in header'): res = implicit_chord_sig.delay() with pytest.raises(ExpectedException): res.get(timeout=TIMEOUT) with subtests.test(msg='Confirm the body was not executed'): with pytest.raises(TimeoutError): # confirm the chord body was not called await_redis_echo((body_msg,), redis_key=body_key, timeout=10) # Double check assert not redis_connection.exists(body_key), 'Chord body was called when it should have not' with subtests.test(msg='Confirm the errback was called for each failed header task + body'): # confirm the errback was called for each task in the chord header failed_header_tasks_count = len(list(filter(lambda f_sig: f_sig.name == fail.si().name, header))) expected_errbacks_count = failed_header_tasks_count + 1 # +1 for the body expected_errbacks = tuple(errback_msg for _ in range(expected_errbacks_count)) await_redis_echo(expected_errbacks, redis_key=errback_key) # confirm there are not leftovers assert not redis_connection.exists(errback_key) # Cleanup redis_connection.delete(errback_key) def test_upgraded_chord_link_error_with_header_errback_enabled(self, manager, subtests): try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) if not manager.app.conf.result_backend.startswith('redis'): raise pytest.skip('Requires redis result backend.') redis_connection = get_redis_connection() manager.app.conf.task_allow_error_cb_on_chord_header = True body_msg = 'chord body called' body_key = 'echo_body' body_sig = redis_echo.si(body_msg, redis_key=body_key) errback_msg = 'errback called' errback_key = 'echo_errback' errback_sig = redis_echo.si(errback_msg, redis_key=errback_key) redis_connection.delete(errback_key, body_key) sig = chain( identity.si(42), group( fail.si(), fail.si(), ), body_sig, ).on_error(errback_sig) with subtests.test(msg='Error propagates from failure in header'): with pytest.raises(ExpectedException): sig.apply_async().get(timeout=TIMEOUT) redis_connection.delete(errback_key, body_key) @flaky @pytest.mark.parametrize( "input_body", [ (lambda: add.si(9, 7)), ( lambda: chain( add.si(9, 7), add.si(5, 7), ) ), ( lambda: group( [ add.si(9, 7), add.si(5, 7), ] ) ), ( lambda: chord( group( [ add.si(1, 1), add.si(2, 2), ] ), add.si(10, 10), ) ), ], ids=[ "body is a single_task", "body is a chain", "body is a group", "body is a chord", ], ) def test_chord_error_propagation_with_different_body_types( self, manager, caplog, input_body ) -> None: """Integration test for issue #9773: task_id must not be empty on chain of groups. This test reproduces the exact scenario from GitHub issue #9773 where a chord with a failing group task and a chain body causes a ValueError during error handling. The test verifies that: 1. The chord executes without the "task_id must not be empty" error 2. The failure from the group properly propagates to the chain body 3. Error handling works correctly with proper task IDs Args: input_body (callable): A callable that returns a Celery signature for the body of the chord. """ try: manager.app.backend.ensure_chords_allowed() except NotImplementedError as e: raise pytest.skip(e.args[0]) # Create the failing group header (same for all tests) failing_chord = chain( group( [ add.si(15, 7), # failing task fail.si(), ] ), # dynamic parametrized body input_body(), ) result = failing_chord.apply_async() # The chain should fail due to the failing task in the group with pytest.raises(ExpectedException): result.get(timeout=TIMEOUT) # Verify that error propagation worked correctly without the task_id error # This test passes if no "task_id must not be empty" error was logged # Check if the message appears in the logs (it shouldn't) error_found = check_for_logs(caplog=caplog, message="ValueError: task_id must not be empty") assert not error_found, "The 'task_id must not be empty' error was found in the logs"
test_chord
python
ApeWorX__ape
src/ape/managers/_deploymentscache.py
{ "start": 1026, "end": 6408 }
class ____(BaseManager): """ Manage cached contract deployments. """ def __init__(self): # NOTE: For some reason, deployments are all inside their ecosystem folders, # but they still have the ecosystem key. Hence, the weird structure here. self._deployments: dict[str, Deployments] = {} self._base_path = None @property def _is_live_network(self) -> bool: return bool(self.network_manager.active_provider) and not self.provider.network.is_dev @property def cachefile(self) -> Path: base_path = self._base_path or self.provider.network.ecosystem.data_folder return base_path / "deployments_map.json" @property def _all_deployments(self) -> Deployments: if not self._is_live_network: # No file. if "local" not in self._deployments: self._deployments["local"] = Deployments() return self._deployments["local"] ecosystem_name = self.provider.network.ecosystem.name if ecosystem_name not in self._deployments: self._deployments[ecosystem_name] = Deployments.model_validate_file(self.cachefile) return self._deployments[ecosystem_name] def __getitem__(self, contract_name: str) -> list[Deployment]: return self.get_deployments(contract_name) def __setitem__(self, contract_name, deployments: list[Deployment]): self._set_deployments(contract_name, deployments) def __delitem__(self, contract_name: str): self.remove_deployments(contract_name) def __contains__(self, contract_name: str): return bool(self.get_deployments(contract_name)) def get_deployments( self, contract_name: str, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ) -> list[Deployment]: """ Get the deployments of the given contract on the currently connected network. Args: contract_name (str): The name of the deployed contract. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. Returns: list[Deployment] """ if not self.network_manager.connected and (not ecosystem_key or not network_key): # Allows it to work when not connected (testing?) return [] ecosystem_name = ecosystem_key or self.provider.network.ecosystem.name network_name = network_key or self.provider.network.name.replace("-fork", "") return ( self._all_deployments.ecosystems.get(ecosystem_name, {}) .get(network_name, {}) .get(contract_name, []) ) def cache_deployment( self, address: AddressType, contract_name: str, transaction_hash: Optional[str] = None, ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): """ Update the deployments cache with a new contract. Args: address (AddressType): The address of the contract. contract_name (str): The name of the contract type. transaction_hash (Optional[str]): Optionally, the transaction has associated with the deployment transaction. ecosystem_key (str | None): The ecosystem key. Defaults to the connected ecosystem's name. network_key (str | None): The network key. Defaults to the connected network's name. """ deployments = [ *self.get_deployments(contract_name), Deployment(address=address, transaction_hash=transaction_hash), ] self._set_deployments( contract_name, deployments, ecosystem_key=ecosystem_key, network_key=network_key, ) @contextmanager def use_temporary_cache(self): base_path = self._base_path deployments = self._deployments with create_tempdir() as temp_path: self._base_path = temp_path self._deployments = {} yield self._base_path = base_path self._deployments = deployments def _set_deployments( self, contract_name: str, deployments: list[Deployment], ecosystem_key: Optional[str] = None, network_key: Optional[str] = None, ): ecosystem_name = ecosystem_key or self.provider.network.ecosystem.name network_name = network_key or self.provider.network.name.replace("-fork", "") self._all_deployments.ecosystems.setdefault(ecosystem_name, {}) self._all_deployments.ecosystems[ecosystem_name].setdefault(network_name, {}) self._all_deployments.ecosystems[ecosystem_name][network_name][contract_name] = deployments # For live networks, cache the deployments to a file as well. if self._is_live_network and ecosystem_name in self._deployments: self._deployments[ecosystem_name].model_dump_file() def remove_deployments(self, contract_name: str): self._set_deployments(contract_name, []) def clear_local(self): self._deployments["local"] = Deployments()
DeploymentDiskCache
python
kamyu104__LeetCode-Solutions
Python/length-of-the-longest-valid-substring.py
{ "start": 191, "end": 975 }
class ____(object): def longestValidSubstring(self, word, forbidden): """ :type word: str :type forbidden: List[str] :rtype: int """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() for w in forbidden: reduce(dict.__getitem__, w, trie)["_end"] result = 0 right = len(word)-1 for left in reversed(xrange(len(word))): node = trie for i in xrange(left, right+1): if word[i] not in node: # O(l) times break node = node[word[i]] if "_end" in node: right = i-1 break result = max(result, right-left+1) return result
Solution
python
getsentry__sentry
tests/sentry/workflow_engine/processors/contexts/test_workflow_event_context.py
{ "start": 595, "end": 713 }
class ____: def run(self) -> Detector | None: return WorkflowEventContext.get().detector
MockContextualClass
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/expect_batch_columns_to_be_unique.py
{ "start": 1228, "end": 3431 }
class ____(TableMetricProvider): # </snippet> # This is the id string that will be used to reference your Metric. # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_batch_columns_to_be_unique.py metric_name"> metric_name = "table.columns.unique" # </snippet> # This method implements the core logic for the PandasExecutionEngine # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_batch_columns_to_be_unique.py pandas"> @metric_value(engine=PandasExecutionEngine) def _pandas( cls, execution_engine, metric_domain_kwargs, metric_value_kwargs, metrics, runtime_configuration, ): df, _, _ = execution_engine.get_compute_domain( metric_domain_kwargs, domain_type=MetricDomainTypes.TABLE ) unique_columns = set(df.T.drop_duplicates().T.columns) return unique_columns # </snippet> # @metric_value(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy( # cls, # execution_engine, # metric_domain_kwargs, # metric_value_kwargs, # metrics, # runtime_configuration, # ): # raise NotImplementedError # # @metric_value(engine=SparkDFExecutionEngine) # def _spark( # cls, # execution_engine, # metric_domain_kwargs, # metric_value_kwargs, # metrics, # runtime_configuration, # ): # raise NotImplementedError @classmethod def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[dict] = None, ): return { "table.columns": MetricConfiguration( "table.columns", metric.metric_domain_kwargs ), } # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_batch_columns_to_be_unique.py ExpectBatchColumnsToBeUnique class_def">
BatchColumnsUnique
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 855754, "end": 856496 }
class ____(ValueChannelMixin, core.PositionValueDef): """ Theta2Value schema wrapper. Definition object for a constant value (primitive value or gradient definition) of an encoding channel. Parameters ---------- value : dict, float, :class:`ExprRef`, Literal['height', 'width'] A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient definition <https://vega.github.io/vega-lite/docs/types.html#gradient>`__ for color, values between ``0`` to ``1`` for opacity). """ _class_is_valid_at_instantiation = False _encoding_name = "theta2" def __init__(self, value, **kwds): super().__init__(value=value, **kwds) @with_property_setters
Theta2Value
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1575682, "end": 1584615 }
class ____(VegaLiteSchema): """ ViewBackground schema wrapper. Parameters ---------- cornerRadius : dict, float, :class:`ExprRef` The radius in pixels of rounded rectangles or arcs' corners. **Default value:** ``0`` cursor : :class:`Cursor`, Literal['auto', 'default', 'none', 'context-menu', 'help', 'pointer', 'progress', 'wait', 'cell', 'crosshair', 'text', 'vertical-text', 'alias', 'copy', 'move', 'no-drop', 'not-allowed', 'e-resize', 'n-resize', 'ne-resize', 'nw-resize', 's-resize', 'se-resize', 'sw-resize', 'w-resize', 'ew-resize', 'ns-resize', 'nesw-resize', 'nwse-resize', 'col-resize', 'row-resize', 'all-scroll', 'zoom-in', 'zoom-out', 'grab', 'grabbing'] The mouse cursor used over the view. Any valid `CSS cursor type <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values>`__ can be used. fill : str, dict, :class:`Color`, :class:`ExprRef`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'], None The fill color. **Default value:** ``undefined`` fillOpacity : dict, float, :class:`ExprRef` The fill opacity (value between [0,1]). **Default value:** ``1`` opacity : dict, float, :class:`ExprRef` The overall opacity (value between [0,1]). **Default value:** ``0.7`` for non-aggregate plots with ``point``, ``tick``, ``circle``, or ``square`` marks or layered ``bar`` charts and ``1`` otherwise. stroke : str, dict, :class:`Color`, :class:`ExprRef`, :class:`HexColor`, :class:`ColorName`, Literal['black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua', 'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige', 'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow', 'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen', 'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'whitesmoke', 'yellowgreen', 'rebeccapurple'], None The stroke color. **Default value:** ``"#ddd"`` strokeCap : dict, :class:`ExprRef`, :class:`StrokeCap`, Literal['butt', 'round', 'square'] The stroke cap for line ending style. One of ``"butt"``, ``"round"``, or ``"square"``. **Default value:** ``"butt"`` strokeDash : dict, Sequence[float], :class:`ExprRef` An array of alternating stroke, space lengths for creating dashed or dotted lines. strokeDashOffset : dict, float, :class:`ExprRef` The offset (in pixels) into which to begin drawing with the stroke dash array. strokeJoin : dict, :class:`ExprRef`, :class:`StrokeJoin`, Literal['miter', 'round', 'bevel'] The stroke line join method. One of ``"miter"``, ``"round"`` or ``"bevel"``. **Default value:** ``"miter"`` strokeMiterLimit : dict, float, :class:`ExprRef` The miter limit at which to bevel a line join. strokeOpacity : dict, float, :class:`ExprRef` The stroke opacity (value between [0,1]). **Default value:** ``1`` strokeWidth : dict, float, :class:`ExprRef` The stroke width, in pixels. style : str, Sequence[str] A string or array of strings indicating the name of custom styles to apply to the view background. A style is a named collection of mark property defaults defined within the `style configuration <https://vega.github.io/vega-lite/docs/mark.html#style-config>`__. If style is an array, later styles will override earlier styles. **Default value:** ``"cell"`` **Note:** Any specified view background properties will augment the default style. """ _schema = {"$ref": "#/definitions/ViewBackground"} def __init__( self, cornerRadius: Optional[float | Parameter | SchemaBase | Map] = Undefined, cursor: Optional[SchemaBase | Cursor_T] = Undefined, fill: Optional[ str | Parameter | SchemaBase | Map | ColorName_T | None ] = Undefined, fillOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined, opacity: Optional[float | Parameter | SchemaBase | Map] = Undefined, stroke: Optional[ str | Parameter | SchemaBase | Map | ColorName_T | None ] = Undefined, strokeCap: Optional[Parameter | SchemaBase | Map | StrokeCap_T] = Undefined, strokeDash: Optional[ Parameter | SchemaBase | Sequence[float] | Map ] = Undefined, strokeDashOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeJoin: Optional[Parameter | SchemaBase | Map | StrokeJoin_T] = Undefined, strokeMiterLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined, strokeWidth: Optional[float | Parameter | SchemaBase | Map] = Undefined, style: Optional[str | Sequence[str]] = Undefined, **kwds, ): super().__init__( cornerRadius=cornerRadius, cursor=cursor, fill=fill, fillOpacity=fillOpacity, opacity=opacity, stroke=stroke, strokeCap=strokeCap, strokeDash=strokeDash, strokeDashOffset=strokeDashOffset, strokeJoin=strokeJoin, strokeMiterLimit=strokeMiterLimit, strokeOpacity=strokeOpacity, strokeWidth=strokeWidth, style=style, **kwds, )
ViewBackground
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_pinned_searches.py
{ "start": 425, "end": 5138 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-pinned-searches" method = "put" @cached_property def member(self): user = self.create_user("test@test.com") self.create_member(organization=self.organization, user=user) return user def get_response(self, *args, **params): return super().get_response(*((self.organization.slug,) + args), **params) def test(self) -> None: self.login_as(self.member) query = "test" search_type = SearchType.ISSUE.value sort = SortOptions.DATE self.get_success_response(type=search_type, query=query, sort=sort, status_code=201) assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.member.id, type=search_type, query=query, sort=sort, visibility=Visibility.OWNER_PINNED, ).exists() # Errors out if no default view is found, inherently verifying existence. default_view = GroupSearchView.objects.get( organization=self.organization, name="Default Search", user_id=self.member.id, query=query, query_sort=sort, ) assert GroupSearchViewStarred.objects.filter( organization=self.organization, user_id=self.member.id, group_search_view=default_view, position=0, ).exists() query = "test_2" self.get_success_response(type=search_type, query=query, sort=sort, status_code=201) assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.member.id, type=search_type, query=query, sort=sort, visibility=Visibility.OWNER_PINNED, ).exists() self.get_success_response(type=SearchType.EVENT.value, query=query, status_code=201) assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.member.id, type=search_type, query=query, ).exists() assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.member.id, type=SearchType.EVENT.value, query=query, visibility=Visibility.OWNER_PINNED, ).exists() self.login_as(self.user) self.get_success_response(type=search_type, query=query, status_code=201) assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.member.id, type=search_type, query=query, visibility=Visibility.OWNER_PINNED, ).exists() assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.user.id, type=search_type, query=query, visibility=Visibility.OWNER_PINNED, ).exists() def test_pin_sort_mismatch(self) -> None: saved_search = SavedSearch.objects.create( organization=self.organization, owner_id=self.member.id, type=SearchType.ISSUE.value, sort=SortOptions.FREQ, query="wat", visibility=Visibility.OWNER_PINNED, ) self.login_as(self.user) resp = self.get_success_response( sort=SortOptions.DATE, type=saved_search.type, query=saved_search.query, status_code=201 ) assert resp.data["isPinned"] assert resp.data["id"] != str(saved_search.id) def test_invalid_type(self) -> None: self.login_as(self.member) resp = self.get_response(type=55, query="test", status_code=201) assert resp.status_code == 400 assert "not a valid SearchType" in resp.data["type"][0] def test_empty_query(self) -> None: self.login_as(self.member) query = "" search_type = SearchType.ISSUE.value sort = SortOptions.DATE self.get_success_response(type=search_type, query=query, sort=sort, status_code=201) assert SavedSearch.objects.filter( organization=self.organization, name=PINNED_SEARCH_NAME, owner_id=self.member.id, type=search_type, query=query, sort=sort, visibility=Visibility.OWNER_PINNED, ).exists()
CreateOrganizationPinnedSearchTest
python
huggingface__transformers
src/transformers/models/mllama/modeling_mllama.py
{ "start": 64469, "end": 70975 }
class ____(MllamaPreTrainedModel): _checkpoint_conversion_mapping = { "language_model.model": "language_model", "model.vision_model": "vision_model", } def __init__(self, config: MllamaConfig): super().__init__(config) self.vocab_size = config.text_config.vocab_size self.hidden_size = config.text_config.hidden_size self.max_num_tiles = config.vision_config.max_num_tiles self.vision_output_dim = config.vision_config.vision_output_dim self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1 self.vision_model = MllamaVisionModel._from_config(config.vision_config) self.language_model = MllamaTextModel._from_config(config.text_config) self.multi_modal_projector = nn.Linear( config.vision_config.vision_output_dim, config.text_config.hidden_size, bias=True, ) self.post_init() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): self.language_model.set_input_embeddings(value) @check_model_inputs() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, aspect_ratio_mask: Optional[torch.Tensor] = None, aspect_ratio_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, cross_attention_mask: Optional[torch.Tensor] = None, cross_attention_states: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> BaseModelOutputWithPast: r""" aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*): Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`: - 1 for tiles that are **not masked**, - 0 for tiles that are **masked**. aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*): Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image. These ids correspond to indices in the model's list of supported aspect ratios, offset by 1. For example, if the model supports aspect ratios [[1, 1], [1, 2], [2, 1]]: - An image with aspect ratio [1, 1] would have ID 1 - An image with aspect ratio [1, 2] would have ID 2 - An image with aspect ratio [2, 1] would have ID 3 The id 0 is reserved for padding (i.e., no image). If an image has aspect ratio [1, 2], that means it was split into 2 tiles horizontally, and its `aspect_ratio_id` would be 2. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_num_images, max_num_tiles)`, *optional*): Cross-attention mask to control the interaction between text tokens and image tiles. This 4D tensor defines which image tiles each text token should attend to. For each text token (in seq_length): - 1 indicates the token **should attend** to the corresponding image tile - 0 indicates the token **should not attend** to the corresponding image tile cross_attention_states (`torch.FloatTensor`, *optional*): Output of the vision model, used for cross-attention. This tensor contains the processed image features that the language model will attend to. """ if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if pixel_values is not None and cross_attention_states is not None: raise ValueError("`pixel_values` and `cross_attention_states` cannot be provided simultaneously") if pixel_values is not None: if aspect_ratio_ids is None: raise ValueError("`aspect_ratio_ids` must be provided if `pixel_values` is provided") # get vision tokens from vision model vision_outputs = self.vision_model( pixel_values=pixel_values, aspect_ratio_ids=aspect_ratio_ids, aspect_ratio_mask=aspect_ratio_mask, ) cross_attention_states = vision_outputs.last_hidden_state cross_attention_states = self.multi_modal_projector(cross_attention_states).reshape( -1, cross_attention_states.shape[-2], self.hidden_size ) if cross_attention_mask is not None: cross_attention_mask, full_text_row_masked_out_mask = _prepare_cross_attention_mask( cross_attention_mask, num_vision_tokens=self.vision_model.num_patches, dtype=self.dtype, ) else: full_text_row_masked_out_mask = None if cross_attention_mask is not None and cache_position is not None: cross_attention_mask = cross_attention_mask[:, :, cache_position] full_text_row_masked_out_mask = full_text_row_masked_out_mask[:, :, cache_position] outputs = self.language_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, cross_attention_states=cross_attention_states, cross_attention_mask=cross_attention_mask, full_text_row_masked_out_mask=full_text_row_masked_out_mask, past_key_values=past_key_values, use_cache=use_cache, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs, ) return BaseModelOutputWithPast( last_hidden_state=outputs.last_hidden_state, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring( custom_intro=""" The Mllama model which consists of a vision encoder and a language model. """, )
MllamaModel
python
google__jax
jax/_src/state/types.py
{ "start": 8299, "end": 8746 }
class ____: ref_or_view: Any def __getitem__(self, slc): if not isinstance(slc, tuple): slc = (slc,) indexer = indexing.NDIndexer.from_indices_shape(slc, self.ref_or_view.shape) if isinstance(self.ref_or_view, TransformedRef): view = self.ref_or_view return TransformedRef(view.ref, (*view.transforms, indexer)) return TransformedRef(self.ref_or_view, (indexer,)) @dataclasses.dataclass(frozen=True)
RefIndexer
python
spyder-ide__spyder
spyder/plugins/findinfiles/widgets/main_widget.py
{ "start": 1502, "end": 1893 }
class ____: # Triggers Find = 'find_action' MaxResults = 'max_results_action' # Toggles ToggleCase = 'toggle_case_action' ToggleExcludeCase = 'toggle_exclude_case_action' ToggleExcludeRegex = 'togle_use_regex_on_exlude_action' ToggleMoreOptions = 'toggle_more_options_action' ToggleSearchRegex = 'toggle_use_regex_on_search_action'
FindInFilesWidgetActions
python
scikit-learn__scikit-learn
sklearn/neighbors/_lof.py
{ "start": 507, "end": 20167 }
class ____(KNeighborsMixin, OutlierMixin, NeighborsBase): """Unsupervised Outlier Detection using the Local Outlier Factor (LOF). The anomaly score of each sample is called the Local Outlier Factor. It measures the local deviation of the density of a given sample with respect to its neighbors. It is local in that the anomaly score depends on how isolated the object is with respect to the surrounding neighborhood. More precisely, locality is given by k-nearest neighbors, whose distance is used to estimate the local density. By comparing the local density of a sample to the local densities of its neighbors, one can identify samples that have a substantially lower density than their neighbors. These are considered outliers. .. versionadded:: 0.19 Parameters ---------- n_neighbors : int, default=20 Number of neighbors to use by default for :meth:`kneighbors` queries. If n_neighbors is larger than the number of samples provided, all samples will be used. algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' Algorithm used to compute the nearest neighbors: - 'ball_tree' will use :class:`BallTree` - 'kd_tree' will use :class:`KDTree` - 'brute' will use a brute-force search. - 'auto' will attempt to decide the most appropriate algorithm based on the values passed to :meth:`fit` method. Note: fitting on sparse input will override the setting of this parameter, using brute force. leaf_size : int, default=30 Leaf is size passed to :class:`BallTree` or :class:`KDTree`. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem. metric : str or callable, default='minkowski' Metric to use for distance computation. Default is "minkowski", which results in the standard Euclidean distance when p = 2. See the documentation of `scipy.spatial.distance <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and the metrics listed in :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric values. If metric is "precomputed", X is assumed to be a distance matrix and must be square during fit. X may be a :term:`sparse graph`, in which case only "nonzero" elements may be considered neighbors. If metric is a callable function, it takes two arrays representing 1D vectors as inputs and must return one value indicating the distance between those vectors. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. p : float, default=2 Parameter for the Minkowski metric from :func:`sklearn.metrics.pairwise_distances`. When p = 1, this is equivalent to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. metric_params : dict, default=None Additional keyword arguments for the metric function. contamination : 'auto' or float, default='auto' The amount of contamination of the data set, i.e. the proportion of outliers in the data set. When fitting this is used to define the threshold on the scores of the samples. - if 'auto', the threshold is determined as in the original paper, - if a float, the contamination should be in the range (0, 0.5]. .. versionchanged:: 0.22 The default value of ``contamination`` changed from 0.1 to ``'auto'``. novelty : bool, default=False By default, LocalOutlierFactor is only meant to be used for outlier detection (novelty=False). Set novelty to True if you want to use LocalOutlierFactor for novelty detection. In this case be aware that you should only use predict, decision_function and score_samples on new unseen data and not on the training set; and note that the results obtained this way may differ from the standard LOF results. .. versionadded:: 0.20 n_jobs : int, default=None The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Attributes ---------- negative_outlier_factor_ : ndarray of shape (n_samples,) The opposite LOF of the training samples. The higher, the more normal. Inliers tend to have a LOF score close to 1 (``negative_outlier_factor_`` close to -1), while outliers tend to have a larger LOF score. The local outlier factor (LOF) of a sample captures its supposed 'degree of abnormality'. It is the average of the ratio of the local reachability density of a sample and those of its k-nearest neighbors. n_neighbors_ : int The actual number of neighbors used for :meth:`kneighbors` queries. offset_ : float Offset used to obtain binary labels from the raw scores. Observations having a negative_outlier_factor smaller than `offset_` are detected as abnormal. The offset is set to -1.5 (inliers score around -1), except when a contamination parameter different than "auto" is provided. In that case, the offset is defined in such a way we obtain the expected number of outliers in training. .. versionadded:: 0.20 effective_metric_ : str The effective metric used for the distance computation. effective_metric_params_ : dict The effective additional keyword arguments for the metric function. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 n_samples_fit_ : int It is the number of samples in the fitted data. See Also -------- sklearn.svm.OneClassSVM: Unsupervised Outlier Detection using Support Vector Machine. References ---------- .. [1] Breunig, M. M., Kriegel, H. P., Ng, R. T., & Sander, J. (2000, May). `LOF: identifying density-based local outliers. <https://dl.acm.org/doi/pdf/10.1145/342009.335388>`_ In Proceedings of the 2000 ACM SIGMOD International Conference on Management of Data, pp. 93-104. Examples -------- >>> import numpy as np >>> from sklearn.neighbors import LocalOutlierFactor >>> X = [[-1.1], [0.2], [101.1], [0.3]] >>> clf = LocalOutlierFactor(n_neighbors=2) >>> clf.fit_predict(X) array([ 1, 1, -1, 1]) >>> clf.negative_outlier_factor_ array([ -0.9821, -1.0370, -73.3697, -0.9821]) """ _parameter_constraints: dict = { **NeighborsBase._parameter_constraints, "contamination": [ StrOptions({"auto"}), Interval(Real, 0, 0.5, closed="right"), ], "novelty": ["boolean"], } _parameter_constraints.pop("radius") def __init__( self, n_neighbors=20, *, algorithm="auto", leaf_size=30, metric="minkowski", p=2, metric_params=None, contamination="auto", novelty=False, n_jobs=None, ): super().__init__( n_neighbors=n_neighbors, algorithm=algorithm, leaf_size=leaf_size, metric=metric, p=p, metric_params=metric_params, n_jobs=n_jobs, ) self.contamination = contamination self.novelty = novelty def _check_novelty_fit_predict(self): if self.novelty: msg = ( "fit_predict is not available when novelty=True. Use " "novelty=False if you want to predict on the training set." ) raise AttributeError(msg) return True @available_if(_check_novelty_fit_predict) def fit_predict(self, X, y=None): """Fit the model to the training set X and return the labels. **Not available for novelty detection (when novelty is set to True).** Label is 1 for an inlier and -1 for an outlier according to the LOF score and the contamination parameter. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. y : Ignored Not used, present for API consistency by convention. Returns ------- is_inlier : ndarray of shape (n_samples,) Returns -1 for anomalies/outliers and 1 for inliers. """ # As fit_predict would be different from fit.predict, fit_predict is # only available for outlier detection (novelty=False) return self.fit(X)._predict() @_fit_context( # LocalOutlierFactor.metric is not validated yet prefer_skip_nested_validation=False ) def fit(self, X, y=None): """Fit the local outlier factor detector from the training dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ (n_samples, n_samples) if metric='precomputed' Training data. y : Ignored Not used, present for API consistency by convention. Returns ------- self : LocalOutlierFactor The fitted local outlier factor detector. """ self._fit(X) n_samples = self.n_samples_fit_ if self.n_neighbors > n_samples: warnings.warn( "n_neighbors (%s) is greater than the " "total number of samples (%s). n_neighbors " "will be set to (n_samples - 1) for estimation." % (self.n_neighbors, n_samples) ) self.n_neighbors_ = max(1, min(self.n_neighbors, n_samples - 1)) self._distances_fit_X_, _neighbors_indices_fit_X_ = self.kneighbors( n_neighbors=self.n_neighbors_ ) if self._fit_X.dtype == np.float32: self._distances_fit_X_ = self._distances_fit_X_.astype( self._fit_X.dtype, copy=False, ) self._lrd = self._local_reachability_density( self._distances_fit_X_, _neighbors_indices_fit_X_ ) # Compute lof score over training samples to define offset_: lrd_ratios_array = ( self._lrd[_neighbors_indices_fit_X_] / self._lrd[:, np.newaxis] ) self.negative_outlier_factor_ = -np.mean(lrd_ratios_array, axis=1) if self.contamination == "auto": # inliers score around -1 (the higher, the less abnormal). self.offset_ = -1.5 else: self.offset_ = np.percentile( self.negative_outlier_factor_, 100.0 * self.contamination ) # Verify if negative_outlier_factor_ values are within acceptable range. # Novelty must also be false to detect outliers if np.min(self.negative_outlier_factor_) < -1e7 and not self.novelty: warnings.warn( "Duplicate values are leading to incorrect results. " "Increase the number of neighbors for more accurate results." ) return self def _check_novelty_predict(self): if not self.novelty: msg = ( "predict is not available when novelty=False, use " "fit_predict if you want to predict on training data. Use " "novelty=True if you want to use LOF for novelty detection " "and predict on new unseen data." ) raise AttributeError(msg) return True @available_if(_check_novelty_predict) def predict(self, X=None): """Predict the labels (1 inlier, -1 outlier) of X according to LOF. **Only available for novelty detection (when novelty is set to True).** This method allows to generalize prediction to *new observations* (not in the training set). Note that the result of ``clf.fit(X)`` then ``clf.predict(X)`` with ``novelty=True`` may differ from the result obtained by ``clf.fit_predict(X)`` with ``novelty=False``. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns ------- is_inlier : ndarray of shape (n_samples,) Returns -1 for anomalies/outliers and +1 for inliers. """ return self._predict(X) def _predict(self, X=None): """Predict the labels (1 inlier, -1 outlier) of X according to LOF. If X is None, returns the same as fit_predict(X_train). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. If None, makes prediction on the training data without considering them as their own neighbors. Returns ------- is_inlier : ndarray of shape (n_samples,) Returns -1 for anomalies/outliers and +1 for inliers. """ check_is_fitted(self) if X is not None: shifted_opposite_lof_scores = self.decision_function(X) is_inlier = np.ones(shifted_opposite_lof_scores.shape[0], dtype=int) is_inlier[shifted_opposite_lof_scores < 0] = -1 else: is_inlier = np.ones(self.n_samples_fit_, dtype=int) is_inlier[self.negative_outlier_factor_ < self.offset_] = -1 return is_inlier def _check_novelty_decision_function(self): if not self.novelty: msg = ( "decision_function is not available when novelty=False. " "Use novelty=True if you want to use LOF for novelty " "detection and compute decision_function for new unseen " "data. Note that the opposite LOF of the training samples " "is always available by considering the " "negative_outlier_factor_ attribute." ) raise AttributeError(msg) return True @available_if(_check_novelty_decision_function) def decision_function(self, X): """Shifted opposite of the Local Outlier Factor of X. Bigger is better, i.e. large values correspond to inliers. **Only available for novelty detection (when novelty is set to True).** The shift offset allows a zero threshold for being an outlier. The argument X is supposed to contain *new data*: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns ------- shifted_opposite_lof_scores : ndarray of shape (n_samples,) The shifted opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. Negative scores represent outliers, positive scores represent inliers. """ return self.score_samples(X) - self.offset_ def _check_novelty_score_samples(self): if not self.novelty: msg = ( "score_samples is not available when novelty=False. The " "scores of the training samples are always available " "through the negative_outlier_factor_ attribute. Use " "novelty=True if you want to use LOF for novelty detection " "and compute score_samples for new unseen data." ) raise AttributeError(msg) return True @available_if(_check_novelty_score_samples) def score_samples(self, X): """Opposite of the Local Outlier Factor of X. It is the opposite as bigger is better, i.e. large values correspond to inliers. **Only available for novelty detection (when novelty is set to True).** The argument X is supposed to contain *new data*: if X contains a point from training, it considers the later in its own neighborhood. Also, the samples in X are not considered in the neighborhood of any point. Because of this, the scores obtained via ``score_samples`` may differ from the standard LOF scores. The standard LOF scores for the training data is available via the ``negative_outlier_factor_`` attribute. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The query sample or samples to compute the Local Outlier Factor w.r.t. the training samples. Returns ------- opposite_lof_scores : ndarray of shape (n_samples,) The opposite of the Local Outlier Factor of each input samples. The lower, the more abnormal. """ check_is_fitted(self) X = check_array(X, accept_sparse="csr") distances_X, neighbors_indices_X = self.kneighbors( X, n_neighbors=self.n_neighbors_ ) if X.dtype == np.float32: distances_X = distances_X.astype(X.dtype, copy=False) X_lrd = self._local_reachability_density( distances_X, neighbors_indices_X, ) lrd_ratios_array = self._lrd[neighbors_indices_X] / X_lrd[:, np.newaxis] # as bigger is better: return -np.mean(lrd_ratios_array, axis=1) def _local_reachability_density(self, distances_X, neighbors_indices): """The local reachability density (LRD) The LRD of a sample is the inverse of the average reachability distance of its k-nearest neighbors. Parameters ---------- distances_X : ndarray of shape (n_queries, self.n_neighbors) Distances to the neighbors (in the training samples `self._fit_X`) of each query point to compute the LRD. neighbors_indices : ndarray of shape (n_queries, self.n_neighbors) Neighbors indices (of each query point) among training samples self._fit_X. Returns ------- local_reachability_density : ndarray of shape (n_queries,) The local reachability density of each sample. """ dist_k = self._distances_fit_X_[neighbors_indices, self.n_neighbors_ - 1] reach_dist_array = np.maximum(distances_X, dist_k) # 1e-10 to avoid `nan' when nb of duplicates > n_neighbors_: return 1.0 / (np.mean(reach_dist_array, axis=1) + 1e-10)
LocalOutlierFactor
python
kamyu104__LeetCode-Solutions
Python/design-an-expression-tree-with-evaluate-function.py
{ "start": 1992, "end": 2424 }
class ____(object): def buildTree(self, postfix): """ :type s: List[str] :rtype: int """ stk = [] for c in postfix: if c.isdigit(): stk.append(NodeRecu(c)) else: node = NodeRecu(c) node.right = stk.pop() node.left = stk.pop() stk.append(node) return stk.pop()
TreeBuilder2
python
getsentry__sentry
tests/sentry/api/endpoints/test_user_organizations.py
{ "start": 49, "end": 481 }
class ____(APITestCase): endpoint = "sentry-api-0-user-organizations" def setUp(self) -> None: super().setUp() self.login_as(self.user) def test_simple(self) -> None: organization_id = self.organization.id # force creation response = self.get_success_response("me") assert len(response.data) == 1 assert response.data[0]["id"] == str(organization_id)
UserOrganizationsTest
python
pytorch__pytorch
torch/utils/data/datapipes/iter/grouping.py
{ "start": 662, "end": 2857 }
class ____(IterDataPipe[DataChunk]): r""" Creates mini-batches of data (functional name: ``batch``). An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the last batch if ``drop_last`` is set to ``False``. Args: datapipe: Iterable DataPipe being batched batch_size: The size of each batch drop_last: Option to drop the last batch if it's not full wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding, defaults to ``DataChunk`` Example: >>> # xdoctest: +SKIP >>> from torchdata.datapipes.iter import IterableWrapper >>> dp = IterableWrapper(range(10)) >>> dp = dp.batch(batch_size=3, drop_last=True) >>> list(dp) [[0, 1, 2], [3, 4, 5], [6, 7, 8]] """ datapipe: IterDataPipe batch_size: int drop_last: bool def __init__( self, datapipe: IterDataPipe, batch_size: int, drop_last: bool = False, wrapper_class: type[DataChunk] = DataChunk, ) -> None: if batch_size <= 0: raise AssertionError("Batch size is required to be larger than 0!") super().__init__() self.datapipe = datapipe self.batch_size = batch_size self.drop_last = drop_last self.wrapper_class = wrapper_class def __iter__(self) -> Iterator[DataChunk]: batch: list = [] for x in self.datapipe: batch.append(x) if len(batch) == self.batch_size: yield self.wrapper_class(batch) batch = [] if len(batch) > 0: if not self.drop_last: yield self.wrapper_class(batch) def __len__(self) -> int: if isinstance(self.datapipe, Sized): if self.drop_last: return len(self.datapipe) // self.batch_size else: return (len(self.datapipe) + self.batch_size - 1) // self.batch_size else: raise TypeError(f"{type(self).__name__} instance doesn't have valid length") @functional_datapipe("unbatch")
BatcherIterDataPipe
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-oci-data-science/tests/test_oci_data_science_client.py
{ "start": 17205, "end": 25212 }
class ____: """Unit tests for AsyncClient class.""" def setup_method(self): self.endpoint = "https://example.com/api" self.auth_mock = {"signer": Mock()} self.retries = 2 self.backoff_factor = 0.1 self.timeout = 10 self.client = AsyncClient( endpoint=self.endpoint, auth=self.auth_mock, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) # Mock the internal HTTPX client self.client._client = AsyncMock() self.client._client.is_closed = False def async_iter(self, items): """Helper function to create an async iterator from a list.""" async def generator(): for item in items: yield item return generator() async def test_request_success(self): """Ensures that _request returns JSON response on success.""" payload = {"prompt": "Hello"} response_json = {"choices": [{"text": "Hi"}]} response_mock = AsyncMock() response_mock.status_code = 200 response_mock.json = AsyncMock(return_value=response_json) response_mock.raise_for_status = Mock() self.client._client.post.return_value = response_mock result = await self.client._request(payload) assert await result == response_json async def test_request_http_error(self): """Ensures that _request raises ExtendedRequestException on HTTP error.""" payload = {"prompt": "Hello"} response_mock = MagicMock() response_mock.status_code = 500 response_mock.raise_for_status.side_effect = httpx.HTTPStatusError( "Server error", request=None, response=response_mock ) response_mock.text = "Internal Server Error" self.client._client.post.return_value = response_mock with pytest.raises(ExtendedRequestException) as exc_info: await self.client._request(payload) assert "Request failed" in str(exc_info.value) assert exc_info.value.response_text == "Internal Server Error" async def test_stream_success(self): """Ensures that _stream yields parsed lines on success.""" payload = {"prompt": "Hello"} response_mock = MagicMock() response_mock.status_code = 200 response_mock.raise_for_status = Mock() response_mock.aiter_lines.return_value = self.async_iter( ['data: {"key": "value1"}', 'data: {"key": "value2"}', "[DONE]"] ) # Define an async context manager @asynccontextmanager async def stream_context_manager(*args, **kwargs): yield response_mock # Mock the stream method to return our context manager self.client._client.stream = Mock(side_effect=stream_context_manager) result = [] async for item in self.client._stream(payload): result.append(item) assert result == [{"key": "value1"}, {"key": "value2"}] @patch("asyncio.sleep", return_value=None) async def test_stream_retry_on_exception(self, mock_sleep): """Ensures that _stream retries on exceptions and raises after retries exhausted.""" payload = {"prompt": "Hello"} # Define an async context manager that raises an exception @asynccontextmanager async def stream_context_manager(*args, **kwargs): raise httpx.RequestError("Connection error") yield # This is never reached # Mock the stream method to use our context manager self.client._client.stream = Mock(side_effect=stream_context_manager) with pytest.raises(ExtendedRequestException): async for _ in self.client._stream(payload): pass assert ( self.client._client.stream.call_count == self.retries + 1 ) # initial attempt + retries async def test_generate_stream(self): """Ensures that generate method calls _stream when stream=True.""" response_mock = MagicMock() response_mock.status_code = 200 response_mock.raise_for_status = Mock() response_mock.aiter_lines.return_value = self.async_iter( ['data: {"key": "value"}', "[DONE]"] ) @asynccontextmanager async def stream_context_manager(*args, **kwargs): yield response_mock self.client._client.stream = Mock(side_effect=stream_context_manager) result = [] async for item in await self.client.generate(prompt="Hello", stream=True): result.append(item) assert result == [{"key": "value"}] async def test_generate_request(self): """Ensures that generate method calls _request when stream=False.""" payload = {"prompt": "Hello"} response_json = {"choices": [{"text": "Hi"}]} response_mock = AsyncMock() response_mock.status_code = 200 response_mock.json = AsyncMock(return_value=response_json) response_mock.raise_for_status = Mock() self.client._client.post.return_value = response_mock result = await self.client.generate(prompt="Hello", stream=False) assert await result == response_json async def test_chat_stream(self): """Ensures that chat method calls _stream when stream=True.""" messages = [{"role": "user", "content": "Hello"}] response_mock = MagicMock() response_mock.status_code = 200 response_mock.raise_for_status = Mock() response_mock.aiter_lines.return_value = self.async_iter( ['data: {"key": "value"}', "[DONE]"] ) @asynccontextmanager async def stream_context_manager(*args, **kwargs): yield response_mock self.client._client.stream = Mock(side_effect=stream_context_manager) result = [] async for item in await self.client.chat(messages=messages, stream=True): result.append(item) assert result == [{"key": "value"}] async def test_chat_request(self): """Ensures that chat method calls _request when stream=False.""" messages = [{"role": "user", "content": "Hello"}] response_json = {"choices": [{"message": {"content": "Hi"}}]} response_mock = AsyncMock() response_mock.status_code = 200 response_mock.json = AsyncMock(return_value=response_json) response_mock.raise_for_status = Mock() self.client._client.post.return_value = response_mock result = await self.client.chat(messages=messages, stream=False) assert await result == response_json async def test_close(self): """Ensures that close method closes the client.""" self.client._client.aclose = AsyncMock() await self.client.close() self.client._client.aclose.assert_called_once() async def test_is_closed(self): """Ensures that is_closed returns the client's is_closed status.""" self.client._client.is_closed = False assert not self.client.is_closed() self.client._client.is_closed = True assert self.client.is_closed() async def test_context_manager(self): """Ensures that the client can be used as a context manager.""" self.client.close = AsyncMock() async with self.client as client_instance: assert client_instance == self.client self.client.close.assert_called_once() async def test_del(self): """Ensures that __del__ method closes the client.""" client = AsyncClient( endpoint=self.endpoint, auth=self.auth_mock, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) client.close = AsyncMock() await client.__aexit__(None, None, None) # Manually invoke __aexit__ client.close.assert_called_once()
TestAsyncClient
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_control.py
{ "start": 5276, "end": 5550 }
class ____(RuleBasedStateMachine): @rule() def step(self): assert currently_in_test_context() is True test_currently_in_stateful_test = ContextMachine.TestCase def test_can_convert_non_weakref_types_to_event_strings(): _event_to_string(())
ContextMachine
python
pypa__setuptools
setuptools/tests/test_depends.py
{ "start": 45, "end": 424 }
class ____: def test_basic(self): """ Invoke get_module_constant on a module in the test package. """ mod_name = 'setuptools.tests.mod_with_constant' val = depends.get_module_constant(mod_name, 'value') assert val == 'three, sir!' assert 'setuptools.tests.mod_with_constant' not in sys.modules
TestGetModuleConstant
python
astropy__astropy
astropy/cosmology/_src/traits/curvature.py
{ "start": 357, "end": 2448 }
class ____: """The object has attributes and methods related to the global curvature. This is a trait class; it is not meant to be instantiated directly, but instead to be used as a mixin to other classes. """ @property @abc.abstractmethod def Ok0(self) -> float | np.floating: """Omega curvature; the effective curvature density/critical density at z=0.""" raise NotImplementedError @property @abc.abstractmethod def is_flat(self) -> bool: """Return `bool`; `True` if the cosmology is globally flat.""" raise NotImplementedError def Ok(self, z: Quantity | ArrayLike, /) -> NDArray[np.floating]: """Return the equivalent density parameter for curvature at redshift ``z``. Parameters ---------- z : Quantity-like ['redshift'], array-like Input redshift. .. versionchanged:: 7.0 Passing z as a keyword argument is deprecated. .. versionchanged:: 8.0 z must be a positional argument. Returns ------- Ok : ndarray The equivalent density parameter for curvature at each redshift. .. versionchanged:: 7.2 Always returns a numpy object, never a `float`. Examples -------- >>> import numpy as np >>> from astropy.cosmology import Planck18, units as cu >>> Planck18.Ok(2) array(0.) >>> Planck18.Ok([1, 2]) array([0., 0.]) >>> Planck18.Ok(np.array([2])) array([0.]) >>> Planck18.Ok(2 * cu.redshift) array(0.) >>> cosmo = Planck18.clone(Ode0=0.71, to_nonflat=True) >>> cosmo.Ok0 np.float64(-0.021153694455455927) >>> cosmo.Ok(100) np.float64(-0.0006557825253017665) """ z = aszarr(z) if self.Ok0 == 0: # Common enough to be worth checking explicitly return np.zeros(getattr(z, "shape", ())) return self.Ok0 * (z + 1.0) ** 2 * self.inv_efunc(z) ** 2
CurvatureComponent
python
vyperlang__vyper
vyper/semantics/types/user.py
{ "start": 11069, "end": 15155 }
class ____(_UserType): typeclass = "struct" is_valid_element_type = True def __init__(self, _id, members, ast_def=None): super().__init__(members) self._id = _id self.ast_def = ast_def @cached_property def name(self) -> str: # Alias for API compatibility with codegen return self._id # duplicated code in TupleT def tuple_members(self): return [v for (_k, v) in self.tuple_items()] # duplicated code in TupleT def tuple_keys(self): return [k for (k, _v) in self.tuple_items()] def tuple_items(self): return list(self.members.items()) @cached_property def member_types(self): """ Alias to match TupleT API without shadowing `members` on TupleT """ return self.members @classmethod def from_StructDef(cls, base_node: vy_ast.StructDef) -> "StructT": """ Generate a `StructT` object from a Vyper ast node. Arguments --------- node : StructDef Vyper ast node defining the struct Returns ------- StructT Struct type """ struct_name = base_node.name members: dict[str, VyperType] = {} for node in base_node.body: if not isinstance(node, vy_ast.AnnAssign): raise StructureException( "Struct declarations can only contain variable definitions", node ) if node.value is not None: raise StructureException("Cannot assign a value during struct declaration", node) if not isinstance(node.target, vy_ast.Name): raise StructureException("Invalid syntax for struct member name", node.target) member_name = node.target.id if member_name in members: # TODO: add prev_decl raise NamespaceCollision( f"struct member '{member_name}' has already been declared", node.value ) members[member_name] = type_from_annotation(node.annotation) return cls(struct_name, members, ast_def=base_node) def __str__(self): return f"{self._id}" def __repr__(self): return f"{self._id} {self.members}" def _try_fold(self, node): if len(node.args) != 1: raise UnfoldableNode("wrong number of args", node.args) args = [arg.get_folded_value() for arg in node.args] if not isinstance(args[0], vy_ast.Dict): raise UnfoldableNode("not a dict") # it can't be reduced, but this lets upstream code know it's constant return node def def_source_str(self): ret = f"struct {self._id}:\n" for k, v in self.member_types.items(): ret += f" {k}: {v}\n" return ret @property def size_in_bytes(self): return sum(i.size_in_bytes for i in self.member_types.values()) @property def abi_type(self) -> ABIType: return ABI_Tuple([t.abi_type for t in self.member_types.values()]) def to_abi_arg(self, name: str = "") -> dict: components = [t.to_abi_arg(name=k) for k, t in self.member_types.items()] return {"name": name, "type": "tuple", "components": components} def _ctor_call_return(self, node: vy_ast.Call) -> "StructT": if len(node.args) > 0: raise VariableDeclarationException( "Struct values must be declared as kwargs e.g. Foo(a=1, b=2)", node.args[0] ) if next((i for i in self.member_types.values() if isinstance(i, HashMapT)), False): raise VariableDeclarationException( "Struct contains a mapping and so cannot be declared as a literal", node ) validate_kwargs(node, self.member_types, self.typeclass) return self def _ctor_modifiability_for_call(self, node: vy_ast.Call, modifiability: Modifiability) -> bool: return all(check_modifiability(k.value, modifiability) for k in node.keywords)
StructT
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/widgets/base.py
{ "start": 2738, "end": 2946 }
class ____: "Box drawing characters. (Thin)" HORIZONTAL = "\u2500" VERTICAL = "\u2502" TOP_LEFT = "\u250c" TOP_RIGHT = "\u2510" BOTTOM_LEFT = "\u2514" BOTTOM_RIGHT = "\u2518"
Border
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/from_list_test.py
{ "start": 4999, "end": 7631 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testInvalidIndex(self): dataset = from_list.from_list([1, 2, 3]) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, -1)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, 3)) @combinations.generate(test_base.default_test_combinations()) def testOneDimensionalArray(self): tensor = [1, 2, 3] dataset = from_list.from_list(tensor) for i in range(len(tensor)): results = self.evaluate(random_access.at(dataset, i)) self.assertAllEqual(tensor[i], results) @combinations.generate(test_base.default_test_combinations()) def testTwoDimensionalArray(self): tensor = [[1, 2], [3, 4]] dataset = from_list.from_list(tensor) for i in range(2): results = self.evaluate(random_access.at(dataset, i)) self.assertAllEqual(tensor[i], results) @combinations.generate(test_base.default_test_combinations()) def testMultipleElements(self): dataset = from_list.from_list([[1, 2], [3, 4], [5, 6]]) self.assertEqual(1, self.evaluate(random_access.at(dataset, 0))[0]) self.assertEqual(2, self.evaluate(random_access.at(dataset, 0))[1]) self.assertEqual(3, self.evaluate(random_access.at(dataset, 1))[0]) self.assertEqual(4, self.evaluate(random_access.at(dataset, 1))[1]) @combinations.generate(test_base.default_test_combinations()) def testDictionary(self): dataset = from_list.from_list([{"a": 1, "b": 3}, {"a": 2, "b": 4}]) self.assertEqual({ "a": 1, "b": 3 }, self.evaluate(random_access.at(dataset, 0))) self.assertEqual({ "a": 2, "b": 4 }, self.evaluate(random_access.at(dataset, 1))) @combinations.generate(test_base.default_test_combinations()) def testNumpy(self): elements = [ np.tile(np.array([[0], [1]], dtype=np.uint64), 2), np.tile(np.array([[2], [256]], dtype=np.uint64), 2), np.tile(np.array([[4], [65536]], dtype=np.uint64), 2), np.tile(np.array([[8], [4294967296]], dtype=np.uint64), 2), ] dataset = from_list.from_list(elements) for i in range(len(elements)): result = self.evaluate(random_access.at(dataset, i)) self.assertAllEqual(elements[i], result) @combinations.generate(test_base.default_test_combinations()) def testName(self): dataset = from_list.from_list([42], name="from_list") self.assertDatasetProduces(dataset, [42])
FromListRandomAccessTest