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
astropy__astropy
astropy/visualization/stretch.py
{ "start": 18017, "end": 19156 }
class ____(BaseStretch): r""" Inverse transformation for `~astropy.visualization.LogStretch`. The stretch is given by: .. math:: y = \frac{e^{x \log{a + 1}} - 1}{a} = \frac{(a + 1)^x - 1}{a} Parameters ---------- a : float, optional The ``a`` parameter used in the above formula. The stretch becomes more linear for small ``a`` values and more exponential for large ``a`` values. ``a`` must be greater than 0. Default is 1000. """ def __init__(self, a): super().__init__() if a <= 0: # singularity raise ValueError("a must be > 0") self.a = a def __call__(self, values, clip=True, out=None): values = _prepare(values, clip=clip, out=out) np.multiply(values, np.log(self.a + 1.0), out=values) np.exp(values, out=values) np.subtract(values, 1.0, out=values) np.true_divide(values, self.a, out=values) return values @property def inverse(self): """A stretch object that performs the inverse operation.""" return LogStretch(self.a)
InvertedLogStretch
python
jazzband__django-waffle
waffle/tests/test_testutils.py
{ "start": 6134, "end": 6283 }
class ____(OverrideFlagTestsMixin, TransactionTestCase): """ Run tests with Django TransactionTestCase """
OverrideFlagsTransactionTestCase
python
huggingface__transformers
src/transformers/models/idefics2/modeling_idefics2.py
{ "start": 43438, "end": 52500 }
class ____(Idefics2PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.text_model.embed_tokens.weight"} def __init__(self, config): super().__init__(config) self.model = Idefics2Model(config) self.image_token_id = self.config.image_token_id self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) self.vocab_size = config.text_config.vocab_size # Initialize weights and apply final processing self.post_init() def enable_input_require_grads(self): """ Enables the gradients for the input embeddings. This is useful for fine-tuning adapter weights while keeping the model weights fixed. """ def make_inputs_require_grads(module, input, output): output.requires_grad_(True) self._text_require_grads_hook = self.get_input_embeddings().register_forward_hook(make_inputs_require_grads) self._vision_require_grads_hook = self.model.vision_model.get_input_embeddings().register_forward_hook( make_inputs_require_grads ) def disable_input_require_grads(self): self._text_require_grads_hook.remove() self._vision_require_grads_hook.remove() def get_input_embeddings(self): return self.model.text_model.get_input_embeddings() def set_input_embeddings(self, value): self.model.text_model.set_input_embeddings(value) def get_image_features( self, pixel_values: torch.FloatTensor, pixel_attention_mask: Optional[torch.LongTensor] = None ): return self.model.get_image_features(pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask) @can_return_tuple @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, pixel_values: Optional[torch.FloatTensor] = None, pixel_attention_mask: Optional[torch.BoolTensor] = None, image_hidden_states: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Idefics2CausalLMOutputWithPast]: r""" pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The hidden states of the image encoder after modality projection and perceiver resampling. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or `model.image_token_id` (where `model` is your instance of `Idefics2ForConditionalGeneration`). Tokens with indices set to `model.image_token_id` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> import requests >>> import torch >>> from PIL import Image >>> from io import BytesIO >>> from transformers import AutoProcessor, AutoModelForImageTextToText >>> from transformers.image_utils import load_image >>> # Note that passing the image urls (instead of the actual pil images) to the processor is also possible >>> image1 = load_image("https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg") >>> image2 = load_image("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg") >>> image3 = load_image("https://cdn.britannica.com/68/170868-050-8DDE8263/Golden-Gate-Bridge-San-Francisco.jpg") >>> processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-base") >>> model = AutoModelForImageTextToText.from_pretrained("HuggingFaceM4/idefics2-8b-base", device_map="auto") >>> BAD_WORDS_IDS = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids >>> EOS_WORDS_IDS = [processor.tokenizer.eos_token_id] >>> # Create inputs >>> prompts = [ ... "<image>In this image, we can see the city of New York, and more specifically the Statue of Liberty.<image>In this image,", ... "In which city is that bridge located?<image>", ... ] >>> images = [[image1, image2], [image3]] >>> inputs = processor(images=images, text=prompts, padding=True, return_tensors="pt").to("cuda") >>> # Generate >>> generated_ids = model.generate(**inputs, bad_words_ids=BAD_WORDS_IDS, max_new_tokens=20) >>> generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True) >>> print(generated_texts) ['In this image, we can see the city of New York, and more specifically the Statue of Liberty. In this image, we can see the city of New York, and more specifically the Statue of Liberty.\n\n', 'In which city is that bridge located?\n\nThe bridge is located in the city of Pittsburgh, Pennsylvania.\n\n\nThe bridge is'] ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask, image_hidden_states=image_hidden_states, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, return_dict=True, **kwargs, ) hidden_states = outputs[0] # 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.text_config.vocab_size, **kwargs ) return Idefics2CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_hidden_states=outputs.image_hidden_states, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, pixel_values=None, pixel_attention_mask=None, image_hidden_states=None, logits_to_keep=None, **kwargs, ): # Overwritten -- there are mutually exclusive inputs (if the logic to make `image_hidden_states` take # precedence is moved to the model, we can remove this fn) model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, pixel_values=pixel_values, pixel_attention_mask=pixel_attention_mask, image_hidden_states=image_hidden_states, logits_to_keep=logits_to_keep, **kwargs, ) if image_hidden_states is not None or cache_position[0] != 0: model_inputs["pixel_values"] = None model_inputs["pixel_attention_mask"] = None return model_inputs __all__ = ["Idefics2ForConditionalGeneration", "Idefics2PreTrainedModel", "Idefics2Model"]
Idefics2ForConditionalGeneration
python
getsentry__sentry
tests/acceptance/test_organization_alert_rule_details.py
{ "start": 402, "end": 1378 }
class ____(AcceptanceTestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.login_as(self.user) self.project = self.create_project(fire_project_created=True) self.rule = Rule.objects.get(project=self.project) self.path = f"/organizations/{self.organization.slug}/issues/alerts/rules/{self.project.slug}/{self.rule.id}/details/" def test_empty_alert_rule_details(self) -> None: self.browser.get(self.path) self.browser.wait_until_not('[data-test-id="loading-indicator"]') def test_alert_rule_with_issues(self) -> None: group = self.create_group() RuleFireHistory.objects.create( project=self.project, rule=self.rule, group=group, date_added=timezone.now() - timedelta(days=1), ) self.browser.get(self.path) self.browser.wait_until_not('[data-test-id="loading-indicator"]')
OrganizationAlertRuleDetailsTest
python
run-llama__llama_index
llama-index-core/llama_index/core/readers/base.py
{ "start": 415, "end": 1798 }
class ____(ABC): # pragma: no cover """Utilities for loading data from a directory.""" def lazy_load_data(self, *args: Any, **load_kwargs: Any) -> Iterable[Document]: """Load data from the input directory lazily.""" raise NotImplementedError( f"{self.__class__.__name__} does not provide lazy_load_data method currently" ) async def alazy_load_data( self, *args: Any, **load_kwargs: Any ) -> Iterable[Document]: """Load data from the input directory lazily.""" # Threaded async - just calls the sync method with to_thread. Override in subclasses for real async implementations. return await asyncio.to_thread(self.lazy_load_data, *args, **load_kwargs) def load_data(self, *args: Any, **load_kwargs: Any) -> List[Document]: """Load data from the input directory.""" return list(self.lazy_load_data(*args, **load_kwargs)) async def aload_data(self, *args: Any, **load_kwargs: Any) -> List[Document]: """Load data from the input directory.""" return await asyncio.to_thread(self.load_data, *args, **load_kwargs) def load_langchain_documents(self, **load_kwargs: Any) -> List["LCDocument"]: """Load data in LangChain document format.""" docs = self.load_data(**load_kwargs) return [d.to_langchain_format() for d in docs]
BaseReader
python
realpython__materials
python-maze-solver/source_code_final/src/maze_solver/view/primitives.py
{ "start": 935, "end": 1129 }
class ____(tuple[Point, ...]): def draw(self, **attributes) -> str: points = " ".join(point.draw() for point in self) return tag("polygon", points=points, **attributes)
Polygon
python
ray-project__ray
python/ray/train/_internal/state/schema.py
{ "start": 2156, "end": 2285 }
class ____(BaseModel): # This gpu usage stats from a process pid: int gpuMemoryUsage: int @DeveloperAPI
ProcessGPUUsage
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_message.py
{ "start": 532, "end": 4055 }
class ____(BaseModel): id: str """Unique object identifier. The format and length of IDs may change over time. """ container: Optional[BetaContainer] = None """ Information about the container used in the request (for the code execution tool) """ content: List[BetaContentBlock] """Content generated by the model. This is an array of content blocks, each of which has a `type` that determines its shape. Example: ```json [{ "type": "text", "text": "Hi, I'm Claude." }] ``` If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output. For example, if the input `messages` were: ```json [ { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" }, { "role": "assistant", "content": "The best answer is (" } ] ``` Then the response `content` might be: ```json [{ "type": "text", "text": "B)" }] ``` """ context_management: Optional[BetaContextManagementResponse] = None """Context management response. Information about context management strategies applied during the request. """ model: Model """ The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options. """ role: Literal["assistant"] """Conversational role of the generated message. This will always be `"assistant"`. """ stop_reason: Optional[BetaStopReason] = None """The reason that we stopped. This may be one the following values: - `"end_turn"`: the model reached a natural stopping point - `"max_tokens"`: we exceeded the requested `max_tokens` or the model's maximum - `"stop_sequence"`: one of your provided custom `stop_sequences` was generated - `"tool_use"`: the model invoked one or more tools - `"pause_turn"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue. - `"refusal"`: when streaming classifiers intervene to handle potential policy violations In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise. """ stop_sequence: Optional[str] = None """Which custom stop sequence was generated, if any. This value will be a non-null string if one of your custom stop sequences was generated. """ type: Literal["message"] """Object type. For Messages, this is always `"message"`. """ usage: BetaUsage """Billing and rate-limit usage. Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems. Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response. For example, `output_tokens` will be non-zero, even for an empty string response from Claude. Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. """
BetaMessage
python
getsentry__sentry
tests/snuba/rules/conditions/test_event_frequency.py
{ "start": 19755, "end": 21956 }
class ____( EventFrequencyQueryTestBase, BaseEventFrequencyPercentTest ): rule_cls = EventFrequencyPercentCondition @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1) def test_batch_query_percent(self) -> None: self._make_sessions(60, self.environment2.name) self._make_sessions(60, self.environment.name) batch_query = self.condition_inst.batch_query_hook( group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id], start=self.start, end=self.end, environment_id=self.environment.id, ) percent_of_sessions = 20 assert batch_query == { self.event.group_id: percent_of_sessions, self.event2.group_id: percent_of_sessions, self.perf_event.group_id: 0, } batch_query = self.condition_inst2.batch_query_hook( group_ids=[self.event3.group_id], start=self.start, end=self.end, environment_id=self.environment2.id, ) assert batch_query == {self.event3.group_id: percent_of_sessions} @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 100) def test_batch_query_percent_no_avg_sessions_in_interval(self) -> None: self._make_sessions(60, self.environment2.name) self._make_sessions(60, self.environment.name) batch_query = self.condition_inst.batch_query_hook( group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id], start=self.start, end=self.end, environment_id=self.environment.id, ) percent = 0 assert batch_query == { self.event.group_id: percent, self.event2.group_id: percent, self.perf_event.group_id: percent, } batch_query = self.condition_inst2.batch_query_hook( group_ids=[self.event3.group_id], start=self.start, end=self.end, environment_id=self.environment2.id, ) assert batch_query == {self.event3.group_id: percent}
EventFrequencyPercentConditionQueryTest
python
getsentry__sentry
tests/sentry/integrations/test_notification_utilities.py
{ "start": 694, "end": 3245 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.notification = DummyNotification(self.organization) self.external_user_id_1 = "UXXXXXXX1" self.integration = self.create_slack_integration(self.notification.organization) self.api_integration = serialize_integration(self.integration) self.user_2 = self.create_user() self.external_team_id_2 = "TXXXXXXX2" self.integration2 = self.create_slack_integration( self.notification.organization, external_id=self.external_team_id_2, user=self.user_2, identity_external_id=self.external_team_id_2, ) self.api_integration2 = serialize_integration(self.integration2) def _assert_integrations_are( self, actual: Mapping[Actor, Mapping[str, RpcIntegration | Integration]], expected: Mapping[User, Mapping[str, RpcIntegration | Integration]], ) -> None: assert actual == {Actor.from_orm_user(k): v for (k, v) in expected.items()} def test_simple(self) -> None: integrations_by_channel_by_recipient = get_integrations_by_channel_by_recipient( self.notification.organization, [Actor.from_object(self.user)], ExternalProviders.SLACK, ) self._assert_integrations_are( integrations_by_channel_by_recipient, {self.user: {self.external_user_id_1: self.api_integration}}, ) def test_matching_idp_and_identity_external_id(self) -> None: """ Test that rows where identity.external_id is equal to idp.external_id are excluded. """ integrations_by_channel_by_recipient = get_integrations_by_channel_by_recipient( self.notification.organization, [Actor.from_object(self.user_2)], ExternalProviders.SLACK, ) self._assert_integrations_are(integrations_by_channel_by_recipient, {self.user_2: {}}) def test_multiple(self) -> None: integrations_by_channel_by_recipient = get_integrations_by_channel_by_recipient( self.notification.organization, [Actor.from_object(self.user), Actor.from_object(self.user_2)], ExternalProviders.SLACK, ) self._assert_integrations_are( integrations_by_channel_by_recipient, { self.user: {self.external_user_id_1: self.api_integration}, self.user_2: {}, }, )
TestNotificationUtilities
python
mamba-org__mamba
version_scheme.py
{ "start": 455, "end": 2984 }
class ____: major = "" minor = "" patch = "" pre_release = "" name = "" def __init__(self, version: str): if not isinstance(version, str): raise ValueError(f"'{version}' is not a valid version name : must be a string") if "-" in version: raise ValueError( f"'{version}' is not a valid version name : `-` is reserved for another usage in conda packages version names" ) VALID_VERSION_PRERELEASE_TYPES = ("alpha", "beta", "rc", "dev") version_fields = version.split(".") version_fields_count = len(version_fields) if version_fields_count < 3: raise ValueError( f"'{version}' is not a valid version name : valid version scheme contains 3 or more dots-separated fields, the pre-release name starting with the 4th field (valid examples: 1.2.3, 0.1.2.alpha3, 0.1.2.alpha.3)" ) self.major = version_fields[0] self.minor = version_fields[1] self.patch = version_fields[2] self.pre_release = "" if version_fields_count > 3: # we assume here that all the additional dot-separated values are part of the pre-release name self.pre_release = ".".join(version_fields[3:]) version_errors = [] if not self.major.isdigit(): version_errors.append(f"'{self.major}' is not a valid major version number") if not self.minor.isdigit(): version_errors.append(f"'{self.minor}' is not a valid minor version number") if not self.patch.isdigit(): version_errors.append(f"'{self.patch}' is not a valid patch version number") if self.pre_release != "" and not self.pre_release.startswith( VALID_VERSION_PRERELEASE_TYPES ): version_errors.append( f"'{self.pre_release}' is not a valid pre-release name, pre-release names must start with either : {VALID_VERSION_PRERELEASE_TYPES} " ) if len(version_errors) > 0: error_message = f"'{version}' is not a valid version name:" for error in version_errors: error_message += f"\n - {error}" hint = ( "examples of valid versions: 1.2.3, 0.1.2, 1.2.3.alpha0, 1.2.3.beta1, 3.4.5.beta.2" ) error_message += f"\n{hint}" raise ValueError(error_message) self.name = version def __str__(self): return self.name
version_info
python
kamyu104__LeetCode-Solutions
Python/the-knights-tour.py
{ "start": 1439, "end": 2331 }
class ____(object): def tourOfKnight(self, m, n, r, c): """ :type m: int :type n: int :type r: int :type c: int :rtype: List[List[int]] """ DIRECTIONS = ((1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1)) def backtracking(r, c, i): if i == m*n: return True for dr, dc in DIRECTIONS: nr, nc = r+dr, c+dc if not (0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1): continue result[nr][nc] = i if backtracking(nr, nc, i+1): return True result[nr][nc] = -1 return False result = [[-1]*n for _ in xrange(m)] result[r][c] = 0 backtracking(r, c, 1) return result
Solution2
python
walkccc__LeetCode
solutions/333. Largest BST Subtree/333.py
{ "start": 202, "end": 767 }
class ____: def largestBSTSubtree(self, root: TreeNode | None) -> int: def dfs(root: TreeNode | None) -> T: if not root: return T(math.inf, -math.inf, 0) l = dfs(root.left) r = dfs(root.right) if l.mx < root.val < r.mn: return T(min(l.mn, root.val), max(r.mx, root.val), 1 + l.size + r.size) # Mark one as invalid, but still record the size of children. # Return (-inf, inf) because no node will be > inf or < -inf. return T(-math.inf, math.inf, max(l.size, r.size)) return dfs(root).size
Solution
python
tiangolo__fastapi
tests/test_pydantic_v1_v2_noneable.py
{ "start": 620, "end": 28584 }
class ____(NewBaseModel): new_title: str new_size: int new_description: Union[str, None] = None new_sub: NewSubItem new_multi: List[NewSubItem] = [] app = FastAPI() @app.post("/v1-to-v2/") def handle_v1_item_to_v2(data: Item) -> Union[NewItem, None]: if data.size < 0: return None return NewItem( new_title=data.title, new_size=data.size, new_description=data.description, new_sub=NewSubItem(new_sub_name=data.sub.name), new_multi=[NewSubItem(new_sub_name=s.name) for s in data.multi], ) @app.post("/v1-to-v2/item-filter", response_model=Union[NewItem, None]) def handle_v1_item_to_v2_filter(data: Item) -> Any: if data.size < 0: return None result = { "new_title": data.title, "new_size": data.size, "new_description": data.description, "new_sub": {"new_sub_name": data.sub.name, "new_sub_secret": "sub_hidden"}, "new_multi": [ {"new_sub_name": s.name, "new_sub_secret": "sub_hidden"} for s in data.multi ], "secret": "hidden_v1_to_v2", } return result @app.post("/v2-to-v1/item") def handle_v2_item_to_v1(data: NewItem) -> Union[Item, None]: if data.new_size < 0: return None return Item( title=data.new_title, size=data.new_size, description=data.new_description, sub=SubItem(name=data.new_sub.new_sub_name), multi=[SubItem(name=s.new_sub_name) for s in data.new_multi], ) @app.post("/v2-to-v1/item-filter", response_model=Union[Item, None]) def handle_v2_item_to_v1_filter(data: NewItem) -> Any: if data.new_size < 0: return None result = { "title": data.new_title, "size": data.new_size, "description": data.new_description, "sub": {"name": data.new_sub.new_sub_name, "sub_secret": "sub_hidden"}, "multi": [ {"name": s.new_sub_name, "sub_secret": "sub_hidden"} for s in data.new_multi ], "secret": "hidden_v2_to_v1", } return result client = TestClient(app) def test_v1_to_v2_item_success(): response = client.post( "/v1-to-v2/", json={ "title": "Old Item", "size": 100, "description": "V1 description", "sub": {"name": "V1 Sub"}, "multi": [{"name": "M1"}, {"name": "M2"}], }, ) assert response.status_code == 200, response.text assert response.json() == { "new_title": "Old Item", "new_size": 100, "new_description": "V1 description", "new_sub": {"new_sub_name": "V1 Sub"}, "new_multi": [{"new_sub_name": "M1"}, {"new_sub_name": "M2"}], } def test_v1_to_v2_item_returns_none(): response = client.post( "/v1-to-v2/", json={"title": "Invalid Item", "size": -10, "sub": {"name": "Sub"}}, ) assert response.status_code == 200, response.text assert response.json() is None def test_v1_to_v2_item_minimal(): response = client.post( "/v1-to-v2/", json={"title": "Minimal", "size": 50, "sub": {"name": "MinSub"}} ) assert response.status_code == 200, response.text assert response.json() == { "new_title": "Minimal", "new_size": 50, "new_description": None, "new_sub": {"new_sub_name": "MinSub"}, "new_multi": [], } def test_v1_to_v2_item_filter_success(): response = client.post( "/v1-to-v2/item-filter", json={ "title": "Filtered Item", "size": 50, "sub": {"name": "Sub"}, "multi": [{"name": "Multi1"}], }, ) assert response.status_code == 200, response.text result = response.json() assert result["new_title"] == "Filtered Item" assert result["new_size"] == 50 assert result["new_sub"]["new_sub_name"] == "Sub" assert result["new_multi"][0]["new_sub_name"] == "Multi1" # Verify secret fields are filtered out assert "secret" not in result assert "new_sub_secret" not in result["new_sub"] assert "new_sub_secret" not in result["new_multi"][0] def test_v1_to_v2_item_filter_returns_none(): response = client.post( "/v1-to-v2/item-filter", json={"title": "Invalid", "size": -1, "sub": {"name": "Sub"}}, ) assert response.status_code == 200, response.text assert response.json() is None def test_v2_to_v1_item_success(): response = client.post( "/v2-to-v1/item", json={ "new_title": "New Item", "new_size": 200, "new_description": "V2 description", "new_sub": {"new_sub_name": "V2 Sub"}, "new_multi": [{"new_sub_name": "N1"}, {"new_sub_name": "N2"}], }, ) assert response.status_code == 200, response.text assert response.json() == { "title": "New Item", "size": 200, "description": "V2 description", "sub": {"name": "V2 Sub"}, "multi": [{"name": "N1"}, {"name": "N2"}], } def test_v2_to_v1_item_returns_none(): response = client.post( "/v2-to-v1/item", json={ "new_title": "Invalid New", "new_size": -5, "new_sub": {"new_sub_name": "NewSub"}, }, ) assert response.status_code == 200, response.text assert response.json() is None def test_v2_to_v1_item_minimal(): response = client.post( "/v2-to-v1/item", json={ "new_title": "MinimalNew", "new_size": 75, "new_sub": {"new_sub_name": "MinNewSub"}, }, ) assert response.status_code == 200, response.text assert response.json() == { "title": "MinimalNew", "size": 75, "description": None, "sub": {"name": "MinNewSub"}, "multi": [], } def test_v2_to_v1_item_filter_success(): response = client.post( "/v2-to-v1/item-filter", json={ "new_title": "Filtered New", "new_size": 75, "new_sub": {"new_sub_name": "NewSub"}, "new_multi": [], }, ) assert response.status_code == 200, response.text result = response.json() assert result["title"] == "Filtered New" assert result["size"] == 75 assert result["sub"]["name"] == "NewSub" # Verify secret fields are filtered out assert "secret" not in result assert "sub_secret" not in result["sub"] def test_v2_to_v1_item_filter_returns_none(): response = client.post( "/v2-to-v1/item-filter", json={ "new_title": "Invalid Filtered", "new_size": -100, "new_sub": {"new_sub_name": "Sub"}, }, ) assert response.status_code == 200, response.text assert response.json() is None def test_v1_to_v2_validation_error(): response = client.post("/v1-to-v2/", json={"title": "Missing fields"}) assert response.status_code == 422, response.text assert response.json() == snapshot( { "detail": [ { "loc": ["body", "size"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "sub"], "msg": "field required", "type": "value_error.missing", }, ] } ) def test_v1_to_v2_nested_validation_error(): response = client.post( "/v1-to-v2/", json={"title": "Bad sub", "size": 100, "sub": {"wrong_field": "value"}}, ) assert response.status_code == 422, response.text error_detail = response.json()["detail"] assert len(error_detail) == 1 assert error_detail[0]["loc"] == ["body", "sub", "name"] def test_v1_to_v2_type_validation_error(): response = client.post( "/v1-to-v2/", json={"title": "Bad type", "size": "not_a_number", "sub": {"name": "Sub"}}, ) assert response.status_code == 422, response.text error_detail = response.json()["detail"] assert len(error_detail) == 1 assert error_detail[0]["loc"] == ["body", "size"] def test_v2_to_v1_validation_error(): response = client.post("/v2-to-v1/item", json={"new_title": "Missing fields"}) assert response.status_code == 422, response.text assert response.json() == snapshot( { "detail": pydantic_snapshot( v2=snapshot( [ { "type": "missing", "loc": ["body", "new_size"], "msg": "Field required", "input": {"new_title": "Missing fields"}, }, { "type": "missing", "loc": ["body", "new_sub"], "msg": "Field required", "input": {"new_title": "Missing fields"}, }, ] ), v1=snapshot( [ { "loc": ["body", "new_size"], "msg": "field required", "type": "value_error.missing", }, { "loc": ["body", "new_sub"], "msg": "field required", "type": "value_error.missing", }, ] ), ) } ) def test_v2_to_v1_nested_validation_error(): response = client.post( "/v2-to-v1/item", json={ "new_title": "Bad sub", "new_size": 200, "new_sub": {"wrong_field": "value"}, }, ) assert response.status_code == 422, response.text assert response.json() == snapshot( { "detail": [ pydantic_snapshot( v2=snapshot( { "type": "missing", "loc": ["body", "new_sub", "new_sub_name"], "msg": "Field required", "input": {"wrong_field": "value"}, } ), v1=snapshot( { "loc": ["body", "new_sub", "new_sub_name"], "msg": "field required", "type": "value_error.missing", } ), ) ] } ) def test_v2_to_v1_type_validation_error(): response = client.post( "/v2-to-v1/item", json={ "new_title": "Bad type", "new_size": "not_a_number", "new_sub": {"new_sub_name": "Sub"}, }, ) assert response.status_code == 422, response.text assert response.json() == snapshot( { "detail": [ pydantic_snapshot( v2=snapshot( { "type": "int_parsing", "loc": ["body", "new_size"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "not_a_number", } ), v1=snapshot( { "loc": ["body", "new_size"], "msg": "value is not a valid integer", "type": "type_error.integer", } ), ) ] } ) def test_v1_to_v2_with_multi_items(): response = client.post( "/v1-to-v2/", json={ "title": "Complex Item", "size": 300, "description": "Item with multiple sub-items", "sub": {"name": "Main Sub"}, "multi": [{"name": "Sub1"}, {"name": "Sub2"}, {"name": "Sub3"}], }, ) assert response.status_code == 200, response.text assert response.json() == snapshot( { "new_title": "Complex Item", "new_size": 300, "new_description": "Item with multiple sub-items", "new_sub": {"new_sub_name": "Main Sub"}, "new_multi": [ {"new_sub_name": "Sub1"}, {"new_sub_name": "Sub2"}, {"new_sub_name": "Sub3"}, ], } ) def test_v2_to_v1_with_multi_items(): response = client.post( "/v2-to-v1/item", json={ "new_title": "Complex New Item", "new_size": 400, "new_description": "New item with multiple sub-items", "new_sub": {"new_sub_name": "Main New Sub"}, "new_multi": [{"new_sub_name": "NewSub1"}, {"new_sub_name": "NewSub2"}], }, ) assert response.status_code == 200, response.text assert response.json() == snapshot( { "title": "Complex New Item", "size": 400, "description": "New item with multiple sub-items", "sub": {"name": "Main New Sub"}, "multi": [{"name": "NewSub1"}, {"name": "NewSub2"}], } ) def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/v1-to-v2/": { "post": { "summary": "Handle V1 Item To V2", "operationId": "handle_v1_item_to_v2_v1_to_v2__post", "requestBody": { "content": { "application/json": { "schema": pydantic_snapshot( v2=snapshot( { "allOf": [ { "$ref": "#/components/schemas/Item" } ], "title": "Data", } ), v1=snapshot( {"$ref": "#/components/schemas/Item"} ), ) } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": pydantic_snapshot( v2=snapshot( { "anyOf": [ { "$ref": "#/components/schemas/NewItem" }, {"type": "null"}, ], "title": "Response Handle V1 Item To V2 V1 To V2 Post", } ), v1=snapshot( {"$ref": "#/components/schemas/NewItem"} ), ) } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/v1-to-v2/item-filter": { "post": { "summary": "Handle V1 Item To V2 Filter", "operationId": "handle_v1_item_to_v2_filter_v1_to_v2_item_filter_post", "requestBody": { "content": { "application/json": { "schema": pydantic_snapshot( v2=snapshot( { "allOf": [ { "$ref": "#/components/schemas/Item" } ], "title": "Data", } ), v1=snapshot( {"$ref": "#/components/schemas/Item"} ), ) } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": pydantic_snapshot( v2=snapshot( { "anyOf": [ { "$ref": "#/components/schemas/NewItem" }, {"type": "null"}, ], "title": "Response Handle V1 Item To V2 Filter V1 To V2 Item Filter Post", } ), v1=snapshot( {"$ref": "#/components/schemas/NewItem"} ), ) } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/v2-to-v1/item": { "post": { "summary": "Handle V2 Item To V1", "operationId": "handle_v2_item_to_v1_v2_to_v1_item_post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/NewItem"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/v2-to-v1/item-filter": { "post": { "summary": "Handle V2 Item To V1 Filter", "operationId": "handle_v2_item_to_v1_filter_v2_to_v1_item_filter_post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/NewItem"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item": { "properties": { "title": {"type": "string", "title": "Title"}, "size": {"type": "integer", "title": "Size"}, "description": {"type": "string", "title": "Description"}, "sub": {"$ref": "#/components/schemas/SubItem"}, "multi": { "items": {"$ref": "#/components/schemas/SubItem"}, "type": "array", "title": "Multi", "default": [], }, }, "type": "object", "required": ["title", "size", "sub"], "title": "Item", }, "NewItem": { "properties": { "new_title": {"type": "string", "title": "New Title"}, "new_size": {"type": "integer", "title": "New Size"}, "new_description": pydantic_snapshot( v2=snapshot( { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "New Description", } ), v1=snapshot( {"type": "string", "title": "New Description"} ), ), "new_sub": {"$ref": "#/components/schemas/NewSubItem"}, "new_multi": { "items": {"$ref": "#/components/schemas/NewSubItem"}, "type": "array", "title": "New Multi", "default": [], }, }, "type": "object", "required": ["new_title", "new_size", "new_sub"], "title": "NewItem", }, "NewSubItem": { "properties": { "new_sub_name": {"type": "string", "title": "New Sub Name"} }, "type": "object", "required": ["new_sub_name"], "title": "NewSubItem", }, "SubItem": { "properties": {"name": {"type": "string", "title": "Name"}}, "type": "object", "required": ["name"], "title": "SubItem", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, } )
NewItem
python
huggingface__transformers
tests/models/mask2former/test_modeling_mask2former.py
{ "start": 7649, "end": 15739 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (Mask2FormerModel, Mask2FormerForUniversalSegmentation) if is_torch_available() else () pipeline_model_mapping = {"image-feature-extraction": Mask2FormerModel} if is_torch_available() else {} is_encoder_decoder = False test_missing_keys = False test_torch_exportable = True def setUp(self): self.model_tester = Mask2FormerModelTester(self) self.config_tester = ConfigTester(self, config_class=Mask2FormerConfig, has_text_modality=False) def test_config(self): self.config_tester.run_common_tests() def test_mask2former_model(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_mask2former_model(config, **inputs, output_hidden_states=False) def test_mask2former_instance_segmentation_head_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mask2former_instance_segmentation_head_model(*config_and_inputs) @unittest.skip(reason="Mask2Former does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="Mask2Former is not a generative model") def test_generate_without_input_ids(self): pass @unittest.skip(reason="Mask2Former does not use token embeddings") def test_resize_tokens_embeddings(self): pass @require_torch_multi_gpu @unittest.skip( reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def test_multi_gpu_data_parallel_forward(self): pass @slow def test_model_from_pretrained(self): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: model = Mask2FormerModel.from_pretrained(model_name) self.assertIsNotNone(model) def test_model_with_labels(self): size = (self.model_tester.min_size,) * 2 inputs = { "pixel_values": torch.randn((2, 3, *size), device=torch_device), "mask_labels": torch.randn((2, 10, *size), device=torch_device), "class_labels": torch.zeros(2, 10, device=torch_device).long(), } config = self.model_tester.get_config() model = Mask2FormerForUniversalSegmentation(config).to(torch_device) outputs = model(**inputs) self.assertTrue(outputs.loss is not None) def test_hidden_states_output(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_mask2former_model(config, **inputs, output_hidden_states=True) def test_attention_outputs(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config).to(torch_device) outputs = model(**inputs, output_attentions=True) self.assertTrue(outputs.attentions is not None) def test_training(self): if not self.model_tester.is_training: self.skipTest(reason="model_tester.is_training is set to False") model_class = self.all_model_classes[1] config, pixel_values, pixel_mask, mask_labels, class_labels = self.model_tester.prepare_config_and_inputs() model = model_class(config) model.to(torch_device) model.train() loss = model(pixel_values, mask_labels=mask_labels, class_labels=class_labels).loss loss.backward() def test_retain_grad_hidden_states_attentions(self): model_class = self.all_model_classes[1] config, pixel_values, pixel_mask, mask_labels, class_labels = self.model_tester.prepare_config_and_inputs() config.output_hidden_states = True config.output_attentions = True model = model_class(config).to(torch_device) model.train() outputs = model(pixel_values, mask_labels=mask_labels, class_labels=class_labels) encoder_hidden_states = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() pixel_decoder_hidden_states = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() transformer_decoder_hidden_states = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() attentions = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=True) self.assertIsNotNone(encoder_hidden_states.grad) self.assertIsNotNone(pixel_decoder_hidden_states.grad) self.assertIsNotNone(transformer_decoder_hidden_states.grad) self.assertIsNotNone(attentions.grad) @require_timm def test_backbone_selection(self): config, inputs = self.model_tester.prepare_config_and_inputs_for_common() config.backbone_config = None config.backbone_kwargs = {"out_indices": [1, 2, 3]} config.use_pretrained_backbone = True # Load a timm backbone # We can't load transformer checkpoint with timm backbone, as we can't specify features_only and out_indices config.backbone = "resnet18" config.use_timm_backbone = True for model_class in self.all_model_classes: model = model_class(config).to(torch_device).eval() if model.__class__.__name__ == "Mask2FormerModel": self.assertEqual(model.pixel_level_module.encoder.out_indices, [1, 2, 3]) elif model.__class__.__name__ == "Mask2FormerForUniversalSegmentation": self.assertEqual(model.model.pixel_level_module.encoder.out_indices, [1, 2, 3]) # Load a HF backbone config.backbone = "microsoft/resnet-18" config.use_timm_backbone = False for model_class in self.all_model_classes: model = model_class(config).to(torch_device).eval() if model.__class__.__name__ == "Mask2FormerModel": self.assertEqual(model.pixel_level_module.encoder.out_indices, [1, 2, 3]) elif model.__class__.__name__ == "Mask2FormerForUniversalSegmentation": self.assertEqual(model.model.pixel_level_module.encoder.out_indices, [1, 2, 3]) def test_initialization_pretrained_backbone(self): backbone_name = "microsoft/resnet-18" # load Mask2Former config with a pretrained backbone config = Mask2FormerConfig( backbone=backbone_name, use_pretrained_backbone=True, ) # load pretrained backbone backbone_model = AutoModelForImageClassification.from_pretrained(backbone_name, device_map=torch_device) def params_match(params1, params2): return all((p1 == p2).all() for p1, p2 in zip(params1, params2)) for model_class in self.all_model_classes: model = model_class(config).to(torch_device).eval() if model.__class__.__name__ == "Mask2FormerModel": self.assertTrue( params_match( backbone_model.base_model.encoder.parameters(), model.pixel_level_module.encoder.encoder.parameters(), ) ) elif model.__class__.__name__ == "Mask2FormerForUniversalSegmentation": self.assertTrue( params_match( backbone_model.base_model.encoder.parameters(), model.model.pixel_level_module.encoder.encoder.parameters(), ) ) TOLERANCE = 2e-4 # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_vision @slow
Mask2FormerModelTest
python
django__django
tests/postgres_tests/test_aggregates.py
{ "start": 25714, "end": 26962 }
class ____(PostgreSQLTestCase): @classmethod def setUpTestData(cls): AggregateTestModel.objects.create(char_field="Foo") AggregateTestModel.objects.create(char_field="Foo") AggregateTestModel.objects.create(char_field="Bar") def test_array_agg_distinct_false(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("char_field", distinct=False) ) self.assertEqual(sorted(values["arrayagg"]), ["Bar", "Foo", "Foo"]) def test_array_agg_distinct_true(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("char_field", distinct=True) ) self.assertEqual(sorted(values["arrayagg"]), ["Bar", "Foo"]) def test_jsonb_agg_distinct_false(self): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("char_field", distinct=False), ) self.assertEqual(sorted(values["jsonbagg"]), ["Bar", "Foo", "Foo"]) def test_jsonb_agg_distinct_true(self): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("char_field", distinct=True), ) self.assertEqual(sorted(values["jsonbagg"]), ["Bar", "Foo"])
TestAggregateDistinct
python
redis__redis-py
redis/client.py
{ "start": 1673, "end": 2384 }
class ____(dict): "Case insensitive dict implementation. Assumes string keys only." def __init__(self, data: Dict[str, str]) -> None: for k, v in data.items(): self[k.upper()] = v def __contains__(self, k): return super().__contains__(k.upper()) def __delitem__(self, k): super().__delitem__(k.upper()) def __getitem__(self, k): return super().__getitem__(k.upper()) def get(self, k, default=None): return super().get(k.upper(), default) def __setitem__(self, k, v): super().__setitem__(k.upper(), v) def update(self, data): data = CaseInsensitiveDict(data) super().update(data)
CaseInsensitiveDict
python
django__django
tests/syndication_tests/feeds.py
{ "start": 3004, "end": 3144 }
class ____(views.Feed): title = "Test feed" link = "/feed/" def items(self): return Entry.objects.all()
TestNoPubdateFeed
python
pydantic__pydantic
tests/mypy/modules/plugin_fail.py
{ "start": 721, "end": 832 }
class ____(BaseModel): model_config = ConfigDict(extra=Extra.forbid) ForbidExtraModel(x=1)
ForbidExtraModel
python
python__mypy
mypy/test/visitors.py
{ "start": 1945, "end": 2089 }
class ____(TransformVisitor): def type(self, type: Type) -> Type: assert type is not None return type
TypeAssertTransformVisitor
python
davidhalter__jedi
jedi/plugins/django.py
{ "start": 9685, "end": 9972 }
class ____(AbstractSignature): def __init__(self, value, field_names): super().__init__(value) self._field_names = field_names def get_param_names(self, resolve_stars=False): return [DjangoParamName(name) for name in self._field_names]
DjangoModelSignature
python
catalyst-team__catalyst
catalyst/data/loader.py
{ "start": 6407, "end": 9744 }
class ____(ILoaderWrapper): """Loader wrapper. Prefetches specified number of batches on the GPU. Base usage: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst.data import BatchPrefetchLoaderWrapper num_samples, num_features = int(1e4), int(1e1) X, y = torch.rand(num_samples, num_features), torch.rand(num_samples) dataset = TensorDataset(X, y) loader = DataLoader(dataset, batch_size=32, num_workers=1) loader = BatchPrefetchLoaderWrapper(loader) Minimal working example: .. code-block:: python import os import torch from torch.nn import functional as F from torch.utils.data import DataLoader from catalyst import dl, metrics from catalyst.data.cv import ToTensor from catalyst.contrib.datasets import MNIST from catalyst.data import BatchPrefetchLoaderWrapper class CustomRunner(dl.Runner): def handle_batch(self, batch): # model train/valid step x, y = batch y_hat = self.model(x.view(x.size(0), -1)) loss = F.cross_entropy(y_hat, y) accuracy01 = metrics.accuracy(y_hat, y, topk=(1, )) self.batch_metrics.update( {"loss": loss, "accuracy01": accuracy01} ) if self.is_train_loader: self.engine.backward(loss) self.optimizer.step() self.optimizer.zero_grad() model = torch.nn.Linear(28 * 28, 10) optimizer = torch.optim.Adam(model.parameters(), lr=0.02) batch_size=32 loaders = { "train": DataLoader( MNIST( os.getcwd(), train=True, download=True, transform=ToTensor() ), batch_size=batch_size), "valid": DataLoader( MNIST( os.getcwd(), train=False, download=True, transform=ToTensor() ), batch_size=batch_size), } loaders = { k: BatchPrefetchLoaderWrapper(v) for k, v in loaders.items() } runner = CustomRunner() # model training runner.train( model=model, optimizer=optimizer, loaders=loaders, logdir="./logs", num_epochs=5, verbose=True, load_best_on_end=True, ) """ def __init__(self, loader: DataLoader, num_prefetches: int = None): """Loader wrapper. Prefetches specified number of batches on the GPU. Args: loader: torch dataloader. num_prefetches: number of batches to prefetch on the GPU. """ super().__init__(loader) self.num_prefetches = num_prefetches or 1 def __iter__(self): """Iterator. Returns: iterator object """ return _prefetch_loader(self.origin, self.num_prefetches) __all__ = ["ILoaderWrapper", "BatchLimitLoaderWrapper", "BatchPrefetchLoaderWrapper"]
BatchPrefetchLoaderWrapper
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/decorators/hook_decorator.py
{ "start": 1310, "end": 9508 }
class ____: def __init__( self, name: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, decorated_fn: Optional[Callable[..., Any]] = None, ): self.name = check.opt_str_param(name, "name") self.required_resource_keys = check.opt_set_param( required_resource_keys, "required_resource_keys" ) self.decorated_fn = check.opt_callable_param(decorated_fn, "decorated_fn") def __call__(self, fn) -> HookDefinition: check.callable_param(fn, "fn") if not self.name: self.name = fn.__name__ expected_positionals = ["context", "event_list"] _validate_hook_fn_params(fn, expected_positionals) hook_def = HookDefinition( name=self.name or "", hook_fn=fn, required_resource_keys=self.required_resource_keys, decorated_fn=self.decorated_fn or fn, ) update_wrapper(cast("Callable[..., Any]", hook_def), fn) return hook_def @overload def event_list_hook( hook_fn: Callable[..., Any], ) -> HookDefinition: pass @overload def event_list_hook( *, name: Optional[str] = ..., required_resource_keys: Optional[AbstractSet[str]] = ..., decorated_fn: Optional[Callable[..., Any]] = ..., ) -> _Hook: pass def event_list_hook( hook_fn: Optional[Callable] = None, *, name: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, decorated_fn: Optional[Callable[..., Any]] = None, ) -> Union[HookDefinition, _Hook]: """Create a generic hook with the specified parameters from the decorated function. This decorator is currently used internally by Dagster machinery to support success_hook and failure_hook. The user-defined hook function requires two parameters: - A `context` object is passed as the first parameter. The context is an instance of :py:class:`context <HookContext>`, and provides access to system information, such as loggers (context.log), resources (context.resources), the op (context.op) and its execution step (context.step) which triggers this hook. - An `event_list` object is passed as the second parameter. It provides the full event list of the associated execution step. Args: name (Optional[str]): The name of this hook. required_resource_keys (Optional[AbstractSet[str]]): Keys for the resources required by the hook. Examples: .. code-block:: python @event_list_hook(required_resource_keys={'slack'}) def slack_on_materializations(context, event_list): for event in event_list: if event.event_type == DagsterEventType.ASSET_MATERIALIZATION: message = f'{context.op_name} has materialized an asset {event.asset_key}.' # send a slack message every time a materialization event occurs context.resources.slack.send_message(message) """ # This case is for when decorator is used bare, without arguments. # e.g. @event_list_hook versus @event_list_hook() if hook_fn is not None: check.invariant(required_resource_keys is None) return _Hook()(hook_fn) return _Hook( name=name, required_resource_keys=required_resource_keys, decorated_fn=decorated_fn ) SuccessOrFailureHookFn = Callable[["HookContext"], Any] @overload def success_hook(hook_fn: SuccessOrFailureHookFn) -> HookDefinition: ... @overload def success_hook( *, name: Optional[str] = ..., required_resource_keys: Optional[AbstractSet[str]] = ..., ) -> Callable[[SuccessOrFailureHookFn], HookDefinition]: ... @public def success_hook( hook_fn: Optional[SuccessOrFailureHookFn] = None, *, name: Optional[str] = None, required_resource_keys: Optional[AbstractSet[str]] = None, ) -> Union[HookDefinition, Callable[[SuccessOrFailureHookFn], HookDefinition]]: """Create a hook on step success events with the specified parameters from the decorated function. Args: name (Optional[str]): The name of this hook. required_resource_keys (Optional[AbstractSet[str]]): Keys for the resources required by the hook. Examples: .. code-block:: python @success_hook(required_resource_keys={'slack'}) def slack_message_on_success(context): message = 'op {} succeeded'.format(context.op.name) context.resources.slack.send_message(message) @success_hook def do_something_on_success(context): do_something() """ def wrapper(fn: SuccessOrFailureHookFn) -> HookDefinition: check.callable_param(fn, "fn") expected_positionals = ["context"] _validate_hook_fn_params(fn, expected_positionals) if name is None or callable(name): _name = fn.__name__ else: _name = name @event_list_hook(name=_name, required_resource_keys=required_resource_keys, decorated_fn=fn) def _success_hook( context: "HookContext", event_list: Sequence["DagsterEvent"] ) -> HookExecutionResult: for event in event_list: if event.is_step_success: fn(context) return HookExecutionResult(hook_name=_name, is_skipped=False) # hook is skipped when fn didn't run return HookExecutionResult(hook_name=_name, is_skipped=True) return _success_hook # This case is for when decorator is used bare, without arguments, i.e. @success_hook if hook_fn is not None: check.invariant(required_resource_keys is None) return wrapper(hook_fn) return wrapper @overload def failure_hook(name: SuccessOrFailureHookFn) -> HookDefinition: ... @overload def failure_hook( name: Optional[str] = ..., required_resource_keys: Optional[AbstractSet[str]] = ..., ) -> Callable[[SuccessOrFailureHookFn], HookDefinition]: ... @public def failure_hook( name: Optional[Union[SuccessOrFailureHookFn, str]] = None, required_resource_keys: Optional[AbstractSet[str]] = None, ) -> Union[HookDefinition, Callable[[SuccessOrFailureHookFn], HookDefinition]]: """Create a hook on step failure events with the specified parameters from the decorated function. Args: name (Optional[str]): The name of this hook. required_resource_keys (Optional[AbstractSet[str]]): Keys for the resources required by the hook. Examples: .. code-block:: python @failure_hook(required_resource_keys={'slack'}) def slack_message_on_failure(context): message = 'op {} failed'.format(context.op.name) context.resources.slack.send_message(message) @failure_hook def do_something_on_failure(context): do_something() """ def wrapper(fn: Callable[["HookContext"], Any]) -> HookDefinition: check.callable_param(fn, "fn") expected_positionals = ["context"] _validate_hook_fn_params(fn, expected_positionals) if name is None or callable(name): _name = fn.__name__ else: _name = name @event_list_hook(name=_name, required_resource_keys=required_resource_keys, decorated_fn=fn) def _failure_hook( context: "HookContext", event_list: Sequence["DagsterEvent"] ) -> HookExecutionResult: for event in event_list: if event.is_step_failure: fn(context) return HookExecutionResult(hook_name=_name, is_skipped=False) # hook is skipped when fn didn't run return HookExecutionResult(hook_name=_name, is_skipped=True) return _failure_hook # This case is for when decorator is used bare, without arguments, i.e. @failure_hook if callable(name): check.invariant(required_resource_keys is None) return wrapper(name) return wrapper
_Hook
python
plotly__plotly.py
plotly/graph_objs/streamtube/colorbar/_title.py
{ "start": 233, "end": 3992 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "streamtube.colorbar" _path_str = "streamtube.colorbar.title" _valid_props = {"font", "side", "text"} @property def font(self): """ Sets this color bar's title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.streamtube.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.streamtube.colorbar.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def side(self): """ Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"] @side.setter def side(self, val): self["side"] = val @property def text(self): """ Sets the title of the color bar. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. """ def __init__(self, arg=None, font=None, side=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.streamtube.colorbar.Title` font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. Returns ------- Title """ super().__init__("title") 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.streamtube.colorbar.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.streamtube.colorbar.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("side", arg, side) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
keras-team__keras
keras/src/initializers/random_initializers.py
{ "start": 15939, "end": 17358 }
class ____(VarianceScaling): """Lecun uniform initializer. Draws samples from a uniform distribution within `[-limit, limit]`, where `limit = sqrt(3 / fan_in)` (`fan_in` is the number of input units in the weight tensor). Examples: >>> # Standalone usage: >>> initializer = LecunUniform() >>> values = initializer(shape=(2, 2)) >>> # Usage in a Keras layer: >>> initializer = LecunUniform() >>> layer = Dense(3, kernel_initializer=initializer) Args: seed: A Python integer or instance of `keras.backend.SeedGenerator`. Used to make the behavior of the initializer deterministic. Note that an initializer seeded with an integer or `None` (unseeded) will produce the same random values across multiple calls. To get different random values across multiple calls, use as seed an instance of `keras.backend.SeedGenerator`. Reference: - [Klambauer et al., 2017](https://arxiv.org/abs/1706.02515) """ def __init__(self, seed=None): super().__init__( scale=1.0, mode="fan_in", distribution="uniform", seed=seed ) def get_config(self): return { "seed": serialization_lib.serialize_keras_object(self._init_seed) } @keras_export(["keras.initializers.HeNormal", "keras.initializers.he_normal"])
LecunUniform
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 113517, "end": 119459 }
class ____(SendrecvmsgBase): # Tests for recvmsg() which can also be emulated using # recvmsg_into(), and can use any socket type. def testRecvmsg(self): # Receive a simple message with recvmsg[_into](). msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) def _testRecvmsg(self): self.sendToServer(MSG) def testRecvmsgExplicitDefaults(self): # Test recvmsg[_into]() with default arguments provided explicitly. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG), 0, 0) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) def _testRecvmsgExplicitDefaults(self): self.sendToServer(MSG) def testRecvmsgShorter(self): # Receive a message smaller than buffer. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG) + 42) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) def _testRecvmsgShorter(self): self.sendToServer(MSG) def testRecvmsgTrunc(self): # Receive part of message, check for truncation indicators. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG) - 3) self.assertEqual(msg, MSG[:-3]) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=False) def _testRecvmsgTrunc(self): self.sendToServer(MSG) def testRecvmsgShortAncillaryBuf(self): # Test ancillary data buffer too small to hold any ancillary data. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG), 1) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) def _testRecvmsgShortAncillaryBuf(self): self.sendToServer(MSG) def testRecvmsgLongAncillaryBuf(self): # Test large ancillary data buffer. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG), 10240) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) def _testRecvmsgLongAncillaryBuf(self): self.sendToServer(MSG) def testRecvmsgAfterClose(self): # Check that recvmsg[_into]() fails on a closed socket. self.serv_sock.close() self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024) def _testRecvmsgAfterClose(self): pass def testRecvmsgTimeout(self): # Check that timeout works. try: self.serv_sock.settimeout(0.03) self.assertRaises(TimeoutError, self.doRecvmsg, self.serv_sock, len(MSG)) finally: self.misc_event.set() def _testRecvmsgTimeout(self): self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) @requireAttrs(socket, "MSG_PEEK") def testRecvmsgPeek(self): # Check that MSG_PEEK in flags enables examination of pending # data without consuming it. # Receive part of data with MSG_PEEK. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG) - 3, 0, socket.MSG_PEEK) self.assertEqual(msg, MSG[:-3]) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) # Ignoring MSG_TRUNC here (so this test is the same for stream # and datagram sockets). Some wording in POSIX seems to # suggest that it needn't be set when peeking, but that may # just be a slip. self.checkFlags(flags, eor=False, ignore=getattr(socket, "MSG_TRUNC", 0)) # Receive all data with MSG_PEEK. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG), 0, socket.MSG_PEEK) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) # Check that the same data can still be received normally. msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) @testRecvmsgPeek.client_skip def _testRecvmsgPeek(self): self.sendToServer(MSG) @requireAttrs(socket.socket, "sendmsg") def testRecvmsgFromSendmsg(self): # Test receiving with recvmsg[_into]() when message is sent # using sendmsg(). self.serv_sock.settimeout(self.fail_timeout) msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) self.assertEqual(msg, MSG) self.checkRecvmsgAddress(addr, self.cli_addr) self.assertEqual(ancdata, []) self.checkFlags(flags, eor=True) @testRecvmsgFromSendmsg.client_skip def _testRecvmsgFromSendmsg(self): self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
RecvmsgGenericTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 491005, "end": 492354 }
class ____(sgqlc.types.Type): """A single check step.""" __schema__ = github_schema __field_names__ = ("completed_at", "conclusion", "external_id", "name", "number", "seconds_to_completion", "started_at", "status") completed_at = sgqlc.types.Field(DateTime, graphql_name="completedAt") """Identifies the date and time when the check step was completed.""" conclusion = sgqlc.types.Field(CheckConclusionState, graphql_name="conclusion") """The conclusion of the check step.""" external_id = sgqlc.types.Field(String, graphql_name="externalId") """A reference for the check step on the integrator's system.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The step's name.""" number = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="number") """The index of the step in the list of steps of the parent check run. """ seconds_to_completion = sgqlc.types.Field(Int, graphql_name="secondsToCompletion") """Number of seconds to completion.""" started_at = sgqlc.types.Field(DateTime, graphql_name="startedAt") """Identifies the date and time when the check step was started.""" status = sgqlc.types.Field(sgqlc.types.non_null(CheckStatusState), graphql_name="status") """The current status of the check step."""
CheckStep
python
astropy__astropy
astropy/table/tests/test_table.py
{ "start": 19865, "end": 21109 }
class ____(SetupData): def test_from_table_cols(self, table_types): """Ensure that using cols from an existing table gives a clean copy. """ self._setup(table_types) t = self.t cols = t.columns # Construct Table with cols via Table._new_from_cols t2a = table_types.Table([cols["a"], cols["b"], self.c]) # Construct with add_column t2b = table_types.Table() t2b.add_column(cols["a"]) t2b.add_column(cols["b"]) t2b.add_column(self.c) t["a"][1] = 20 t["b"][1] = 21 for t2 in [t2a, t2b]: t2["a"][2] = 10 t2["b"][2] = 11 t2["c"][2] = 12 t2.columns["a"].meta["aa"][3] = 10 assert np.all(t["a"] == np.array([1, 20, 3])) assert np.all(t["b"] == np.array([4, 21, 6])) assert np.all(t2["a"] == np.array([1, 2, 10])) assert np.all(t2["b"] == np.array([4, 5, 11])) assert np.all(t2["c"] == np.array([7, 8, 12])) assert t2["a"].name == "a" assert t2.columns["a"].meta["aa"][3] == 10 assert t.columns["a"].meta["aa"][3] == 3 @pytest.mark.usefixtures("table_types")
TestInitFromTable
python
tensorflow__tensorflow
tensorflow/compiler/tests/matrix_diag_ops_test.py
{ "start": 25949, "end": 29551 }
class ____(xla_test.XLATestCase): def _assertOpOutputMatchesExpected(self, params, solution, high_level=True, rtol=1e-3, atol=1e-5): """Verifies that matrix_diag_part produces `solution` when fed `params`. Args: params: dictionary containing input parameters to matrix_diag_part. solution: numpy array representing the expected output. high_level: call high_level matrix_set_diag rtol: relative tolerance for equality test. atol: absolute tolerance for equality test. """ input = params["input"] # pylint: disable=redefined-builtin with self.session() as session: for dtype in self.numeric_types - {np.int8, np.uint8}: expected = solution.astype(dtype) with self.test_scope(): params["input"] = array_ops.placeholder( dtype, input.shape, name="input") if high_level: # wraps gen_array_ops.matrix_diag_part_v3 output = array_ops.matrix_diag_part(**params) else: # TODO(b/201086188): Remove this case once MatrixDiag V1 is removed. output = gen_array_ops.matrix_diag_part(**params) output = array_ops.matrix_diag_part(**params) result = session.run(output, { params["input"]: input.astype(dtype), }) self.assertEqual(output.dtype, expected.dtype) self.assertAllCloseAccordingToType( expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03) # Generic tests applicable to both v1 and v2 ops. # Originally from unary_ops_tests.py. def _testV1Level(self, high_level): matrices = np.arange(3 * 2 * 4).reshape([3, 2, 4]) solution = np.array([[0, 5], [8, 13], [16, 21]]) self._assertOpOutputMatchesExpected({"input": matrices}, solution, high_level) def testV1(self): self._testV1Level(True) def testV1LowLevel(self): self._testV1Level(False) # From here onwards are v2-only tests. def testSingleMatrix(self): for align in alignment_list: test_list = [square_cases(align), tall_cases(align), fat_cases(align)] for mat, tests in test_list: for diag_index, (solution, _) in tests.items(): self._assertOpOutputMatchesExpected( { "input": mat[0], "k": diag_index, "align": align }, solution[0]) def testBatch(self): for align in alignment_list: for mat, tests in all_tests(align): for diag_index, (solution, _) in tests.items(): self._assertOpOutputMatchesExpected( { "input": mat, "k": diag_index, "align": align }, solution) def testPadding(self): for padding_value, align in zip_to_first_list_length([555, -11], alignment_list): for mat, tests in all_tests(align): for diag_index, (solution, _) in tests.items(): mask = (solution == 0) solution = solution + (mask * padding_value) self._assertOpOutputMatchesExpected( { "input": mat, "k": diag_index, "padding_value": padding_value, "align": align }, solution) if __name__ == "__main__": googletest.main()
MatrixDiagPartTest
python
ray-project__ray
rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py
{ "start": 526, "end": 6858 }
class ____(ConnectorV2): """Adds an artificial timestep to all incoming episodes at the end. In detail: The last observations, infos, actions, and all `extra_model_outputs` will be duplicated and appended to each episode's data. An extra 0.0 reward will be appended to the episode's rewards. The episode's timestep will be increased by 1. Also, adds the truncated=True flag to each episode if the episode is not already done (terminated or truncated). Useful for value function bootstrapping, where it is required to compute a forward pass for the very last timestep within the episode, i.e. using the following input dict: { obs=[final obs], state=[final state output], prev. reward=[final reward], etc.. } .. testcode:: from ray.rllib.connectors.learner import AddOneTsToEpisodesAndTruncate from ray.rllib.env.single_agent_episode import SingleAgentEpisode from ray.rllib.utils.test_utils import check # Create 2 episodes (both to be extended by one timestep). episode1 = SingleAgentEpisode( observations=[0, 1, 2], actions=[0, 1], rewards=[0.0, 1.0], terminated=False, truncated=False, len_lookback_buffer=0, ).to_numpy() check(len(episode1), 2) check(episode1.is_truncated, False) episode2 = SingleAgentEpisode( observations=[0, 1, 2, 3, 4, 5], actions=[0, 1, 2, 3, 4], rewards=[0.0, 1.0, 2.0, 3.0, 4.0], terminated=True, # a terminated episode truncated=False, len_lookback_buffer=0, ).to_numpy() check(len(episode2), 5) check(episode2.is_truncated, False) check(episode2.is_terminated, True) # Create an instance of this class. connector = AddOneTsToEpisodesAndTruncate() # Call the connector. shared_data = {} _ = connector( rl_module=None, # Connector used here does not require RLModule. batch={}, episodes=[episode1, episode2], shared_data=shared_data, ) # Check on the episodes. Both of them should now be 1 timestep longer. check(len(episode1), 3) check(episode1.is_truncated, True) check(len(episode2), 6) check(episode2.is_truncated, False) check(episode2.is_terminated, True) """ @override(ConnectorV2) def __call__( self, *, rl_module: RLModule, batch: Dict[str, Any], episodes: List[EpisodeType], explore: Optional[bool] = None, shared_data: Optional[dict] = None, **kwargs, ) -> Any: # Build the loss mask to make sure the extra added timesteps do not influence # the final loss and fix the terminateds and truncateds in the batch. # For proper v-trace execution, the rules must be as follows: # Legend: # T: terminal=True # R: truncated=True # B0: bootstrap with value 0 (also: terminal=True) # Bx: bootstrap with some vf-computed value (also: terminal=True) # batch: - - - - - - - T B0- - - - - R Bx- - - - R Bx # mask : t t t t t t t t f t t t t t t f t t t t t f # TODO (sven): Same situation as in TODO below, but for multi-agent episode. # Maybe add a dedicated connector piece for this task? # We extend the MultiAgentEpisode's ID by a running number here to make sure # we treat each MAEpisode chunk as separate (for potentially upcoming v-trace # and LSTM zero-padding) and don't mix data from different chunks. if isinstance(episodes[0], MultiAgentEpisode): for i, ma_episode in enumerate(episodes): ma_episode.id_ += "_" + str(i) # Also change the underlying single-agent episode's # `multi_agent_episode_id` properties. for sa_episode in ma_episode.agent_episodes.values(): sa_episode.multi_agent_episode_id = ma_episode.id_ for i, sa_episode in enumerate( self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False) ): # TODO (sven): This is a little bit of a hack: By extending the Episode's # ID, we make sure that each episode chunk in `episodes` is treated as a # separate episode in the `self.add_n_batch_items` below. Some algos (e.g. # APPO) may have >1 episode chunks from the same episode (same ID) in the # training data, thus leading to a malformatted batch in case of # RNN-triggered zero-padding of the train batch. # For example, if e1 (id=a len=4) and e2 (id=a len=5) are two chunks of the # same episode in `episodes`, the resulting batch would have an additional # timestep in the middle of the episode's "row": # { "obs": { # ("a", <- eps ID): [0, 1, 2, 3 <- len=4, [additional 1 ts (bad)], # 0, 1, 2, 3, 4 <- len=5, [additional 1 ts]] # }} sa_episode.id_ += "_" + str(i) len_ = len(sa_episode) # Extend all episodes by one ts. add_one_ts_to_episodes_and_truncate([sa_episode]) loss_mask = [True for _ in range(len_)] + [False] self.add_n_batch_items( batch, Columns.LOSS_MASK, loss_mask, len_ + 1, sa_episode, ) terminateds = ( [False for _ in range(len_ - 1)] + [bool(sa_episode.is_terminated)] + [True] # extra timestep ) self.add_n_batch_items( batch, Columns.TERMINATEDS, terminateds, len_ + 1, sa_episode, ) # Signal to following connector pieces that the loss-mask which masks out # invalid episode ts (for the extra added ts at the end) has already been # added to `data`. shared_data["_added_loss_mask_for_valid_episode_ts"] = True return batch
AddOneTsToEpisodesAndTruncate
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor17.py
{ "start": 404, "end": 548 }
class ____(Generic[T]): def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) def __init__(self): ...
C
python
ethereum__web3.py
web3/types.py
{ "start": 5984, "end": 6063 }
class ____(SubscriptionResponse): result: LogReceipt
LogsSubscriptionResponse
python
numba__numba
numba/cuda/simulator/kernel.py
{ "start": 7922, "end": 10668 }
class ____(object): ''' Manages the execution of a thread block. When run() is called, all threads are started. Each thread executes until it hits syncthreads(), at which point it sets its own syncthreads_blocked to True so that the BlockManager knows it is blocked. It then waits on its syncthreads_event. The BlockManager polls threads to determine if they are blocked in syncthreads(). If it finds a blocked thread, it adds it to the set of blocked threads. When all threads are blocked, it unblocks all the threads. The thread are unblocked by setting their syncthreads_blocked back to False and setting their syncthreads_event. The polling continues until no threads are alive, when execution is complete. ''' def __init__(self, f, grid_dim, block_dim, debug): self._grid_dim = grid_dim self._block_dim = block_dim self._f = f self._debug = debug self.block_state = np.zeros(block_dim, dtype=np.bool_) def run(self, grid_point, *args): # Create all threads threads = set() livethreads = set() blockedthreads = set() for block_point in np.ndindex(*self._block_dim): def target(): self._f(*args) t = BlockThread(target, self, grid_point, block_point, self._debug) t.start() threads.add(t) livethreads.add(t) # Potential optimisations: # 1. Continue the while loop immediately after finding a blocked thread # 2. Don't poll already-blocked threads while livethreads: for t in livethreads: if t.syncthreads_blocked: blockedthreads.add(t) elif t.exception: # Abort all other simulator threads on exception, # do *not* join immediately to facilitate debugging. for t_other in threads: t_other.abort = True t_other.syncthreads_blocked = False t_other.syncthreads_event.set() raise t.exception[0].with_traceback(t.exception[1]) if livethreads == blockedthreads: for t in blockedthreads: t.syncthreads_blocked = False t.syncthreads_event.set() blockedthreads = set() livethreads = set([ t for t in livethreads if t.is_alive() ]) # Final check for exceptions in case any were set prior to thread # finishing, before we could check it for t in threads: if t.exception: raise t.exception[0].with_traceback(t.exception[1])
BlockManager
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 37213, "end": 37466 }
class ____(WebTestCase): def get_handlers(self): return [("/empty_flush", EmptyFlushCallbackHandler)] def test_empty_flush(self): response = self.fetch("/empty_flush") self.assertEqual(response.body, b"ok")
NonWSGIWebTests
python
ray-project__ray
python/ray/train/v2/_internal/execution/controller/state.py
{ "start": 4119, "end": 4403 }
class ____(TrainControllerState): # TODO: Split into multiple more granular states, or add more fields. # For example, we may want to indicate if any health checks failed. def __init__(self): super().__init__(state_type=TrainControllerStateType.RUNNING)
RunningState
python
tensorflow__tensorflow
tensorflow/python/training/saver.py
{ "start": 3849, "end": 24159 }
class ____: """Base class for Savers. Can be extended to create different Ops. """ SaveSpec = saveable_object.SaveSpec SaveableObject = saveable_object.SaveableObject # Aliases for code which was moved but still has lots of users. VariableSaveable = saveable_object_util.ReferenceVariableSaveable ResourceVariableSaveable = saveable_object_util.ResourceVariableSaveable def __init__(self, write_version=saver_pb2.SaverDef.V2): self._write_version = write_version def save_op(self, filename_tensor, saveables): """Create an Op to save 'saveables'. This is intended to be overridden by subclasses that want to generate different Ops. Args: filename_tensor: String Tensor. saveables: A list of BaseSaverBuilder.SaveableObject objects. Returns: An Operation that save the variables. Raises: RuntimeError: (implementation detail) if "self._write_version" is an unexpected value. """ # pylint: disable=protected-access tensor_names = [] tensors = [] tensor_slices = [] for saveable in saveables: for spec in saveable.specs: tensor_names.append(spec.name) tensors.append(spec.tensor) tensor_slices.append(spec.slice_spec) if self._write_version == saver_pb2.SaverDef.V1: return io_ops._save( filename=filename_tensor, tensor_names=tensor_names, tensors=tensors, tensor_slices=tensor_slices) elif self._write_version == saver_pb2.SaverDef.V2: # "filename_tensor" is interpreted *NOT AS A FILENAME*, but as a prefix # of a V2 checkpoint: e.g. "/fs/train/ckpt-<step>/tmp/worker<i>-<step>". return io_ops.save_v2(filename_tensor, tensor_names, tensor_slices, tensors) else: raise RuntimeError("Unexpected write_version: " + self._write_version) def bulk_restore(self, filename_tensor, saveables, preferred_shard, restore_sequentially): """Restore all tensors contained in saveables. By default, this issues separate calls to `restore_op` for each saveable. Subclasses may override to load multiple saveables in a single call. Args: filename_tensor: String Tensor. saveables: List of BaseSaverBuilder.SaveableObject objects. preferred_shard: Int. Shard to open first when loading a sharded file. restore_sequentially: Unused. Bool. If true, each restore is sequential. Returns: A list of Tensors resulting from reading 'saveable' from 'filename'. """ del restore_sequentially all_tensors = [] for saveable in saveables: if saveable.device: device = saveable_object_util.set_cpu0(saveable.device) else: device = None with ops.device(device): all_tensors.extend( self.restore_op(filename_tensor, saveable, preferred_shard)) return all_tensors # pylint: disable=unused-argument def restore_op(self, filename_tensor, saveable, preferred_shard): """Create ops to restore 'saveable'. This is intended to be overridden by subclasses that want to generate different Ops. Args: filename_tensor: String Tensor. saveable: A BaseSaverBuilder.SaveableObject object. preferred_shard: Int. Shard to open first when loading a sharded file. Returns: A list of Tensors resulting from reading 'saveable' from 'filename'. """ # pylint: disable=protected-access tensors = [] for spec in saveable.specs: tensors.append( io_ops.restore_v2(filename_tensor, [spec.name], [spec.slice_spec], [spec.dtype])[0]) return tensors # pylint: enable=unused-argument def sharded_filename(self, filename_tensor, shard, num_shards): """Append sharding information to a filename. Args: filename_tensor: A string tensor. shard: Integer. The shard for the filename. num_shards: An int Tensor for the number of shards. Returns: A string tensor. """ return gen_io_ops.sharded_filename(filename_tensor, shard, num_shards) def _AddSaveOps(self, filename_tensor, saveables): """Add ops to save variables that are on the same shard. Args: filename_tensor: String Tensor. saveables: A list of SaveableObject objects. Returns: A tensor with the filename used to save. """ save = self.save_op(filename_tensor, saveables) return control_flow_ops.with_dependencies([save], filename_tensor) def _AddShardedSaveOpsForV2(self, checkpoint_prefix, per_device): """Add ops to save the params per shard, for the V2 format. Note that the sharded save procedure for the V2 format is different from V1: there is a special "merge" step that merges the small metadata produced from each device. Args: checkpoint_prefix: scalar String Tensor. Interpreted *NOT AS A FILENAME*, but as a prefix of a V2 checkpoint; per_device: A list of (device, BaseSaverBuilder.VarToSave) pairs, as returned by _GroupByDevices(). Returns: An op to save the variables, which, when evaluated, returns the prefix "<user-fed prefix>" only and does not include the sharded spec suffix. """ # IMPLEMENTATION DETAILS: most clients should skip. # # Suffix for any well-formed "checkpoint_prefix", when sharded. # Transformations: # * Users pass in "save_path" in save() and restore(). Say "myckpt". # * checkpoint_prefix gets fed <save_path><_SHARDED_SUFFIX>. # * If checkpoint_prefix is a S3 bucket path ".part" is appended to it # * Otherwise _temp/part is appended which is normalized relative to the OS # Example: # During runtime, a temporary directory is first created, which contains # files # # <train dir>/myckpt_temp/ # part-?????-of-?????{.index, .data-00000-of-00001} # # Before .save() finishes, they will be (hopefully, atomically) renamed to # # <train dir>/ # myckpt{.index, .data-?????-of-?????} # # Filesystems with eventual consistency (such as S3), don't need a # temporary location. Using a temporary directory in those cases might # cause situations where files are not available during copy. # # Users only need to interact with the user-specified prefix, which is # "<train dir>/myckpt" in this case. Save() and Restore() work with the # prefix directly, instead of any physical pathname. (On failure and # subsequent restore, an outdated and orphaned temporary directory can be # safely removed.) with ops.device("CPU"): _SHARDED_SUFFIX = array_ops.where( string_ops.regex_full_match(checkpoint_prefix, "^s3://.*"), constant_op.constant(".part"), constant_op.constant(os.path.normpath("_temp/part"))) tmp_checkpoint_prefix = string_ops.string_join( [checkpoint_prefix, _SHARDED_SUFFIX]) num_shards = len(per_device) sharded_saves = [] sharded_prefixes = [] num_shards_tensor = constant_op.constant(num_shards, name="num_shards") last_device = None for shard, (device, saveables) in enumerate(per_device): last_device = device with ops.device(saveable_object_util.set_cpu0(device)): sharded_filename = self.sharded_filename(tmp_checkpoint_prefix, shard, num_shards_tensor) sharded_prefixes.append(sharded_filename) sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) with ops.control_dependencies([x.op for x in sharded_saves]): # Co-locates the merge step with the last device. with ops.device(saveable_object_util.set_cpu0(last_device)): # V2 format write path consists of a metadata merge step. Once merged, # attempts to delete the temporary directory, "<user-fed prefix>_temp". merge_step = gen_io_ops.merge_v2_checkpoints( sharded_prefixes, checkpoint_prefix, delete_old_dirs=True) with ops.control_dependencies([merge_step]): # Returns the prefix "<user-fed prefix>" only. DOES NOT include the # sharded spec suffix. return array_ops.identity(checkpoint_prefix) def _AddShardedSaveOps(self, filename_tensor, per_device): """Add ops to save the params per shard. Args: filename_tensor: a scalar String Tensor. per_device: A list of (device, BaseSaverBuilder.SaveableObject) pairs, as returned by _GroupByDevices(). Returns: An op to save the variables. """ if self._write_version == saver_pb2.SaverDef.V2: return self._AddShardedSaveOpsForV2(filename_tensor, per_device) num_shards = len(per_device) sharded_saves = [] num_shards_tensor = constant_op.constant(num_shards, name="num_shards") for shard, (device, saveables) in enumerate(per_device): with ops.device(device): sharded_filename = self.sharded_filename(filename_tensor, shard, num_shards_tensor) sharded_saves.append(self._AddSaveOps(sharded_filename, saveables)) # Return the sharded name for the save path. with ops.control_dependencies([x.op for x in sharded_saves]): return gen_io_ops.sharded_filespec(filename_tensor, num_shards_tensor) def _AddRestoreOps(self, filename_tensor, saveables, restore_sequentially, reshape, preferred_shard=-1, name="restore_all"): """Add operations to restore saveables. Args: filename_tensor: Tensor for the path of the file to load. saveables: A list of SaveableObject objects. restore_sequentially: True if we want to restore variables sequentially within a shard. reshape: True if we want to reshape loaded tensors to the shape of the corresponding variable. preferred_shard: Shard to open first when loading a sharded file. name: Name for the returned op. Returns: An Operation that restores the variables. """ all_tensors = self.bulk_restore(filename_tensor, saveables, preferred_shard, restore_sequentially) assign_ops = [] idx = 0 # Load and optionally reshape on the CPU, as string tensors are not # available on the GPU. # TODO(touts): Re-enable restore on GPU when we can support annotating # string tensors as "HostMemory" inputs. for saveable in saveables: shapes = None if reshape: # Compute the shapes, let the restore op decide if and how to do # the reshape. shapes = [] for spec in saveable.specs: v = spec.tensor shape = v.get_shape() if not shape.is_fully_defined(): shape = array_ops.shape(v) shapes.append(shape) saveable_tensors = all_tensors[idx:idx + len(saveable.specs)] idx += len(saveable.specs) assign_ops.append(saveable.restore(saveable_tensors, shapes)) # Create a Noop that has control dependencies from all the updates. return control_flow_ops.group(*assign_ops, name=name) def _AddShardedRestoreOps(self, filename_tensor, per_device, restore_sequentially, reshape): """Add Ops to restore variables from multiple devices. Args: filename_tensor: Tensor for the path of the file to load. per_device: A list of (device, SaveableObject) pairs, as returned by _GroupByDevices(). restore_sequentially: True if we want to restore variables sequentially within a shard. reshape: True if we want to reshape loaded tensors to the shape of the corresponding variable. Returns: An Operation that restores the variables. """ sharded_restores = [] for shard, (device, saveables) in enumerate(per_device): with ops.device(device): sharded_restores.append( self._AddRestoreOps( filename_tensor, saveables, restore_sequentially, reshape, preferred_shard=shard, name="restore_shard")) return control_flow_ops.group(*sharded_restores, name="restore_all") def _GroupByDevices(self, saveables): """Group Variable tensor slices per device. TODO(touts): Make sure that all the devices found are on different job/replica/task/cpu|gpu. It would be bad if 2 were on the same device. It can happen if the devices are unspecified. Args: saveables: A list of BaseSaverBuilder.SaveableObject objects. Returns: A list of tuples: (device_name, BaseSaverBuilder.SaveableObject) tuples. The list is sorted by ascending device_name. Raises: ValueError: If the tensors of a saveable are on different devices. """ per_device = collections.defaultdict(lambda: []) for saveable in saveables: canonical_device = set( pydev.canonical_name(spec.device) for spec in saveable.specs) if len(canonical_device) != 1: raise ValueError("All tensors of a saveable object must be " "on the same device: %s" % saveable.name) per_device[canonical_device.pop()].append(saveable) return sorted(per_device.items(), key=lambda t: t[0]) def build(self, names_to_saveables, reshape=False, sharded=False, max_to_keep=5, keep_checkpoint_every_n_hours=10000.0, name=None, restore_sequentially=False, filename="model"): """Builds save/restore graph nodes or runs save/restore in eager mode. Args: names_to_saveables: A dictionary mapping name to a Variable or SaveableObject. Each name will be associated with the corresponding variable in the checkpoint. reshape: If True, allow restoring parameters from a checkpoint that where the parameters have a different shape. This is only needed when you try to restore from a Dist-Belief checkpoint, and only some times. sharded: If True, shard the checkpoints, one per device that has Variable nodes. max_to_keep: Maximum number of checkpoints to keep. As new checkpoints are created, old ones are deleted. If None or 0, no checkpoints are deleted from the filesystem but only the last one is kept in the `checkpoint` file. Presently the number is only roughly enforced. For example in case of restarts more than max_to_keep checkpoints may be kept. keep_checkpoint_every_n_hours: How often checkpoints should be kept. Defaults to 10,000 hours. name: String. Optional name to use as a prefix when adding operations. restore_sequentially: A Bool, which if true, causes restore of different variables to happen sequentially within each device. filename: If known at graph construction time, filename used for variable loading/saving. If None, then the default name "model" will be used. Returns: A SaverDef proto. Raises: TypeError: If 'names_to_saveables' is not a dictionary mapping string keys to variable Tensors. ValueError: If any of the keys or values in 'names_to_saveables' is not unique. """ return self._build_internal( names_to_saveables=names_to_saveables, reshape=reshape, sharded=sharded, max_to_keep=max_to_keep, keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, name=name, restore_sequentially=restore_sequentially, filename=filename) def _build_internal(self, names_to_saveables, reshape=False, sharded=False, max_to_keep=5, keep_checkpoint_every_n_hours=10000.0, name=None, restore_sequentially=False, filename="model", build_save=True, build_restore=True): """build() with option to only perform save and restore.""" if not context.executing_eagerly() and (not build_save or not build_restore): raise ValueError("save and restore operations need to be built together " " when eager execution is not enabled.") if not isinstance(names_to_saveables, dict): names_to_saveables = saveable_object_util.op_list_to_dict( names_to_saveables) saveables = saveable_object_util.validate_and_slice_inputs( names_to_saveables) if max_to_keep is None: max_to_keep = 0 with ops.name_scope(name, "save", [saveable.op for saveable in saveables]) as name: # Add a placeholder string tensor for the filename. filename_tensor = array_ops.placeholder_with_default( filename or "model", shape=(), name="filename") # Keep the name "Const" for backwards compatibility. filename_tensor = array_ops.placeholder_with_default( filename_tensor, shape=(), name="Const") # Add the save ops. if sharded: per_device = self._GroupByDevices(saveables) if build_save: save_tensor = self._AddShardedSaveOps(filename_tensor, per_device) if build_restore: restore_op = self._AddShardedRestoreOps(filename_tensor, per_device, restore_sequentially, reshape) else: if build_save: save_tensor = self._AddSaveOps(filename_tensor, saveables) if build_restore: restore_op = self._AddRestoreOps(filename_tensor, saveables, restore_sequentially, reshape) # In the following use case, it's possible to have restore_ops be called # something else: # - Build inference graph and export a meta_graph. # - Import the inference meta_graph # - Extend the inference graph to a train graph. # - Export a new meta_graph. # Now the second restore_op will be called "restore_all_1". # As such, comment out the assert for now until we know whether supporting # such usage model makes sense. # # assert restore_op.name.endswith("restore_all"), restore_op.name if context.executing_eagerly(): # Store the tensor values to the tensor_names. save_tensor_name = save_tensor.numpy() if build_save else "" return saver_pb2.SaverDef( filename_tensor_name=filename_tensor.numpy(), save_tensor_name=save_tensor_name, restore_op_name="", max_to_keep=max_to_keep, sharded=sharded, keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, version=self._write_version) else: graph = ops.get_default_graph() # Do some sanity checking on collections containing # PartitionedVariables. If a saved collection has a PartitionedVariable, # the GraphDef needs to include concat ops to get the value (or there'll # be a lookup error on load). check_collection_list = graph.get_all_collection_keys() for collection_type in check_collection_list: for element in graph.get_collection(collection_type): if isinstance(element, variables.PartitionedVariable): try: graph.get_operation_by_name(element.name) except KeyError: # Create a concat op for this PartitionedVariable. The user may # not need it, but we'll try looking it up on MetaGraph restore # since it's in a collection. element.as_tensor() return saver_pb2.SaverDef( filename_tensor_name=filename_tensor.name, save_tensor_name=save_tensor.name, restore_op_name=restore_op.name, max_to_keep=max_to_keep, sharded=sharded, keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours, version=self._write_version)
BaseSaverBuilder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE796.py
{ "start": 44, "end": 120 }
class ____(enum.Enum): A = "A" B = "B" C = "B" # PIE796
FakeEnum1
python
doocs__leetcode
solution/0400-0499/0434.Number of Segments in a String/Solution2.py
{ "start": 0, "end": 211 }
class ____: def countSegments(self, s: str) -> int: ans = 0 for i, c in enumerate(s): if c != ' ' and (i == 0 or s[i - 1] == ' '): ans += 1 return ans
Solution
python
walkccc__LeetCode
solutions/1385. Find the Distance Value Between Two Arrays/1385.py
{ "start": 0, "end": 346 }
class ____: def findTheDistanceValue( self, arr1: list[int], arr2: list[int], d: int, ) -> int: ans = 0 arr2.sort() for a in arr1: i = bisect.bisect_left(arr2, a) if ((i == len(arr2) or arr2[i] - a > d) and (i == 0 or a - arr2[i - 1] > d)): ans += 1 return ans
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/types/python_dict.py
{ "start": 4681, "end": 4927 }
class ____: def __getitem__(self, *args): check.param_invariant(len(args[0]) == 2, "args", "Must be two parameters") return create_typed_runtime_dict(args[0][0], args[0][1]) Dict: DagsterDictApi = DagsterDictApi()
DagsterDictApi
python
scipy__scipy
scipy/optimize/tests/test_nonlin.py
{ "start": 8669, "end": 11551 }
class ____: """Check that some Jacobian approximations satisfy the secant condition""" xs = [np.array([1., 2., 3., 4., 5.]), np.array([2., 3., 4., 5., 1.]), np.array([3., 4., 5., 1., 2.]), np.array([4., 5., 1., 2., 3.]), np.array([9., 1., 9., 1., 3.]), np.array([0., 1., 9., 1., 3.]), np.array([5., 5., 7., 1., 1.]), np.array([1., 2., 7., 5., 1.]),] fs = [x**2 - 1 for x in xs] def _check_secant(self, jac_cls, npoints=1, **kw): """ Check that the given Jacobian approximation satisfies secant conditions for last `npoints` points. """ jac = jac_cls(**kw) jac.setup(self.xs[0], self.fs[0], None) for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): jac.update(x, f) for k in range(min(npoints, j+1)): dx = self.xs[j-k+1] - self.xs[j-k] df = self.fs[j-k+1] - self.fs[j-k] assert_(np.allclose(dx, jac.solve(df))) # Check that the `npoints` secant bound is strict if j >= npoints: dx = self.xs[j-npoints+1] - self.xs[j-npoints] df = self.fs[j-npoints+1] - self.fs[j-npoints] assert_(not np.allclose(dx, jac.solve(df))) def test_broyden1(self): self._check_secant(nonlin.BroydenFirst) def test_broyden2(self): self._check_secant(nonlin.BroydenSecond) def test_broyden1_update(self): # Check that BroydenFirst update works as for a dense matrix jac = nonlin.BroydenFirst(alpha=0.1) jac.setup(self.xs[0], self.fs[0], None) B = np.identity(5) * (-1/0.1) for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): df = f - self.fs[last_j] dx = x - self.xs[last_j] B += (df - dot(B, dx))[:, None] * dx[None, :] / dot(dx, dx) jac.update(x, f) assert_(np.allclose(jac.todense(), B, rtol=1e-10, atol=1e-13)) def test_broyden2_update(self): # Check that BroydenSecond update works as for a dense matrix jac = nonlin.BroydenSecond(alpha=0.1) jac.setup(self.xs[0], self.fs[0], None) H = np.identity(5) * (-0.1) for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): df = f - self.fs[last_j] dx = x - self.xs[last_j] H += (dx - dot(H, df))[:, None] * df[None, :] / dot(df, df) jac.update(x, f) assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13)) def test_anderson(self): # Anderson mixing (with w0=0) satisfies secant conditions # for the last M iterates, see [Ey]_ # # .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3)
TestSecant
python
huggingface__transformers
tests/models/blip_2/test_modeling_blip_2.py
{ "start": 5019, "end": 7788 }
class ____(ModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as BLIP-2's vision encoder does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (Blip2VisionModel,) if is_torch_available() else () test_resize_embeddings = False def setUp(self): self.model_tester = Blip2VisionModelTester(self) self.config_tester = ConfigTester( self, config_class=Blip2VisionConfig, has_text_modality=False, hidden_size=37 ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="BLIP-2's vision encoder does not use inputs_embeds") def test_inputs_embeds(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) def test_forward_signature(self): for model_class in self.all_model_classes: config, _ = self.model_tester.prepare_config_and_inputs_for_common() model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = ["pixel_values"] self.assertListEqual(arg_names[:1], expected_arg_names) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @unittest.skip def test_training(self): pass @unittest.skip def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass @slow def test_model_from_pretrained(self): model_name = "Salesforce/blip2-opt-2.7b" model = Blip2VisionModel.from_pretrained(model_name) self.assertIsNotNone(model)
Blip2VisionModelTest
python
altair-viz__altair
altair/vegalite/v6/api.py
{ "start": 32407, "end": 39966 }
class ____(ConditionLike, t.Generic[_C]): """ Utility class for ``when-then-otherwise`` conditions. Represents the state after calling :func:`.when().then()`. This state is a valid condition on its own. It can be further specified, via multiple chained `when-then` calls, or finalized with :meth:`Then.otherwise()`. References ---------- `polars.when <https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html>`__ """ def __init__(self, conditions: _Conditional[_C], /) -> None: self.condition: _C = conditions["condition"] @overload def otherwise(self, statement: _TSchemaBase, /, **kwds: Any) -> _TSchemaBase: ... @overload def otherwise(self, statement: str, /, **kwds: Any) -> _Conditional[_Condition]: ... @overload def otherwise( self, statement: _Value, /, **kwds: Any ) -> _Conditional[_Conditions]: ... @overload def otherwise( self, statement: dict[str, Any], /, **kwds: Any ) -> _Conditional[Any]: ... def otherwise( self, statement: _StatementType, /, **kwds: Any ) -> SchemaBase | _Conditional[Any]: """ Finalize the condition with a default value. Parameters ---------- statement A spec or value to use when no predicates were met. .. note:: Roughly equivalent to an ``else`` clause. .. note:: ``str`` will be encoded as `shorthand`_. **kwds Additional keyword args are added to the resulting ``dict``. .. _shorthand: https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands Examples -------- Points outside of ``brush`` will not appear highlighted:: import altair as alt from altair.datasets import data source = data.cars() brush = alt.selection_interval() color = alt.when(brush).then("Origin:N").otherwise(alt.value("grey")) alt.Chart(source).mark_point().encode( x="Horsepower:Q", y="Miles_per_Gallon:Q", color=color, ).add_params(brush) """ conditions: _Conditional[Any] is_extra = functools.partial(_is_condition_extra, kwds=kwds) if is_extra(self.condition, statement): current = self.condition if isinstance(current, list) and len(current) == 1: # This case is guaranteed to have come from `When` and not `ChainedWhen` # The `list` isn't needed if we complete the condition here conditions = _Conditional(condition=current[0]) # pyright: ignore[reportArgumentType] elif isinstance(current, dict): if not is_extra(statement): conditions = self.to_dict() else: cond = _reveal_parsed_shorthand(current) msg = ( f"Only one field may be used within a condition.\n" f"Shorthand {statement!r} would conflict with {cond!r}\n\n" f"Use `alt.value({statement!r})` if this is not a shorthand string." ) raise TypeError(msg) else: # Generic message to cover less trivial cases msg = ( f"Chained conditions cannot be mixed with field conditions.\n" f"{self!r}\n\n{statement!r}" ) raise TypeError(msg) else: conditions = self.to_dict() return _parse_otherwise(statement, conditions, kwds) def when( self, predicate: Optional[_PredicateType] = Undefined, *more_predicates: _ComposablePredicateType, empty: Optional[bool] = Undefined, **constraints: _FieldEqualType, ) -> ChainedWhen: """ Attach another predicate to the condition. The resulting predicate is an ``&`` reduction over ``predicate`` and optional ``*``, ``**``, arguments. Parameters ---------- predicate A selection or test predicate. ``str`` input will be treated as a test operand. .. note:: Accepts the same range of inputs as in :func:`.condition()`. *more_predicates Additional predicates, restricted to types supporting ``&``. empty For selection parameters, the predicate of empty selections returns ``True`` by default. Override this behavior, with ``empty=False``. .. note:: When ``predicate`` is a ``Parameter`` that is used more than once, ``alt.when().then().when(..., empty=...)`` provides granular control for each occurrence. **constraints Specify `Field Equal Predicate`_'s. Shortcut for ``alt.datum.field_name == value``, see examples for usage. Returns ------- :class:`ChainedWhen` A partial state which requires calling :meth:`ChainedWhen.then()` to finish the condition. .. _Field Equal Predicate: https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate Examples -------- Chain calls to express precise queries:: import altair as alt from altair.datasets import data source = data.cars() color = ( alt.when(alt.datum.Miles_per_Gallon >= 30, Origin="Europe") .then(alt.value("crimson")) .when(alt.datum.Horsepower > 150) .then(alt.value("goldenrod")) .otherwise(alt.value("grey")) ) alt.Chart(source).mark_point().encode(x="Horsepower", y="Miles_per_Gallon", color=color) """ condition = _parse_when(predicate, *more_predicates, empty=empty, **constraints) conditions = self.to_dict() current = conditions["condition"] if isinstance(current, list): conditions = t.cast("_Conditional[_Conditions]", conditions) return ChainedWhen(condition, conditions) elif isinstance(current, dict): cond = _reveal_parsed_shorthand(current) msg = ( f"Chained conditions cannot be mixed with field conditions.\n" f"Additional conditions would conflict with {cond!r}\n\n" f"Must finalize by calling `.otherwise()`." ) raise TypeError(msg) else: msg = ( f"The internal structure has been modified.\n" f"{type(current).__name__!r} found, but only `dict | list` are valid." ) raise NotImplementedError(msg) def to_dict(self, *args: Any, **kwds: Any) -> _Conditional[_C]: return _Conditional(condition=self.condition.copy()) def __deepcopy__(self, memo: Any) -> Self: return type(self)(_Conditional(condition=_deepcopy(self.condition, memo))) def __repr__(self) -> str: name = type(self).__name__ COND = "condition: " LB, RB = "{", "}" if len(self.condition) == 1: args = f"{COND}{self.condition!r}".replace("\n", "\n ") else: conds = "\n ".join(f"{c!r}" for c in self.condition) args = f"{COND}[\n {conds}\n ]" return f"{name}({LB}\n {args}\n{RB})"
Then
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/records/articles_records_builder.py
{ "start": 196, "end": 493 }
class ____(ZendeskSupportRecordBuilder): @classmethod def record(cls) -> "ArticlesRecordBuilder": record_template = cls.extract_record("articles", __file__, NestedPath(["articles", 0])) return cls(record_template, FieldPath("id"), FieldPath("updated_at"))
ArticlesRecordBuilder
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/eks.py
{ "start": 3633, "end": 25819 }
class ____(AwsBaseHook): """ Interact with Amazon Elastic Kubernetes Service (EKS). Provide thin wrapper around :external+boto3:py:class:`boto3.client("eks") <EKS.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` """ client_type = "eks" def __init__(self, *args, **kwargs) -> None: kwargs["client_type"] = self.client_type super().__init__(*args, **kwargs) def create_cluster( self, name: str, roleArn: str, resourcesVpcConfig: dict, **kwargs, ) -> dict: """ Create an Amazon EKS control plane. .. seealso:: - :external+boto3:py:meth:`EKS.Client.create_cluster` :param name: The unique name to give to your Amazon EKS Cluster. :param roleArn: The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. :param resourcesVpcConfig: The VPC configuration used by the cluster control plane. :return: Returns descriptive information about the created EKS Cluster. """ eks_client = self.conn response = eks_client.create_cluster( name=name, roleArn=roleArn, resourcesVpcConfig=resourcesVpcConfig, **kwargs ) self.log.info("Created Amazon EKS cluster with the name %s.", response.get("cluster").get("name")) return response def create_nodegroup( self, clusterName: str, nodegroupName: str, subnets: list[str], nodeRole: str | None, *, tags: dict | None = None, **kwargs, ) -> dict: """ Create an Amazon EKS managed node group for an Amazon EKS Cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.create_nodegroup` :param clusterName: The name of the Amazon EKS cluster to create the EKS Managed Nodegroup in. :param nodegroupName: The unique name to give your managed nodegroup. :param subnets: The subnets to use for the Auto Scaling group that is created for your nodegroup. :param nodeRole: The Amazon Resource Name (ARN) of the IAM role to associate with your nodegroup. :param tags: Optional tags to apply to your nodegroup. :return: Returns descriptive information about the created EKS Managed Nodegroup. """ eks_client = self.conn # The below tag is mandatory and must have a value of either 'owned' or 'shared' # A value of 'owned' denotes that the subnets are exclusive to the nodegroup. # The 'shared' value allows more than one resource to use the subnet. cluster_tag_key = f"kubernetes.io/cluster/{clusterName}" resolved_tags = tags or {} if cluster_tag_key not in resolved_tags: resolved_tags[cluster_tag_key] = "owned" response = eks_client.create_nodegroup( clusterName=clusterName, nodegroupName=nodegroupName, subnets=subnets, nodeRole=nodeRole, tags=resolved_tags, **kwargs, ) self.log.info( "Created an Amazon EKS managed node group named %s in Amazon EKS cluster %s", response.get("nodegroup").get("nodegroupName"), response.get("nodegroup").get("clusterName"), ) return response def create_fargate_profile( self, clusterName: str, fargateProfileName: str | None, podExecutionRoleArn: str | None, selectors: list, **kwargs, ) -> dict: """ Create an AWS Fargate profile for an Amazon EKS cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.create_fargate_profile` :param clusterName: The name of the Amazon EKS cluster to apply the Fargate profile to. :param fargateProfileName: The name of the Fargate profile. :param podExecutionRoleArn: The Amazon Resource Name (ARN) of the pod execution role to use for pods that match the selectors in the Fargate profile. :param selectors: The selectors to match for pods to use this Fargate profile. :return: Returns descriptive information about the created Fargate profile. """ eks_client = self.conn response = eks_client.create_fargate_profile( clusterName=clusterName, fargateProfileName=fargateProfileName, podExecutionRoleArn=podExecutionRoleArn, selectors=selectors, **kwargs, ) self.log.info( "Created AWS Fargate profile with the name %s for Amazon EKS cluster %s.", response.get("fargateProfile").get("fargateProfileName"), response.get("fargateProfile").get("clusterName"), ) return response def delete_cluster(self, name: str) -> dict: """ Delete the Amazon EKS Cluster control plane. .. seealso:: - :external+boto3:py:meth:`EKS.Client.delete_cluster` :param name: The name of the cluster to delete. :return: Returns descriptive information about the deleted EKS Cluster. """ eks_client = self.conn response = eks_client.delete_cluster(name=name) self.log.info("Deleted Amazon EKS cluster with the name %s.", response.get("cluster").get("name")) return response def delete_nodegroup(self, clusterName: str, nodegroupName: str) -> dict: """ Delete an Amazon EKS managed node group from a specified cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.delete_nodegroup` :param clusterName: The name of the Amazon EKS Cluster that is associated with your nodegroup. :param nodegroupName: The name of the nodegroup to delete. :return: Returns descriptive information about the deleted EKS Managed Nodegroup. """ eks_client = self.conn response = eks_client.delete_nodegroup(clusterName=clusterName, nodegroupName=nodegroupName) self.log.info( "Deleted Amazon EKS managed node group named %s from Amazon EKS cluster %s.", response.get("nodegroup").get("nodegroupName"), response.get("nodegroup").get("clusterName"), ) return response def delete_fargate_profile(self, clusterName: str, fargateProfileName: str) -> dict: """ Delete an AWS Fargate profile from a specified Amazon EKS cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.delete_fargate_profile` :param clusterName: The name of the Amazon EKS cluster associated with the Fargate profile to delete. :param fargateProfileName: The name of the Fargate profile to delete. :return: Returns descriptive information about the deleted Fargate profile. """ eks_client = self.conn response = eks_client.delete_fargate_profile( clusterName=clusterName, fargateProfileName=fargateProfileName ) self.log.info( "Deleted AWS Fargate profile with the name %s from Amazon EKS cluster %s.", response.get("fargateProfile").get("fargateProfileName"), response.get("fargateProfile").get("clusterName"), ) return response def describe_cluster(self, name: str, verbose: bool = False) -> dict: """ Return descriptive information about an Amazon EKS Cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_cluster` :param name: The name of the cluster to describe. :param verbose: Provides additional logging if set to True. Defaults to False. :return: Returns descriptive information about a specific EKS Cluster. """ eks_client = self.conn response = eks_client.describe_cluster(name=name) self.log.info( "Retrieved details for Amazon EKS cluster named %s.", response.get("cluster").get("name") ) if verbose: cluster_data = response.get("cluster") self.log.info("Amazon EKS cluster details: %s", json.dumps(cluster_data, default=repr)) return response def describe_nodegroup(self, clusterName: str, nodegroupName: str, verbose: bool = False) -> dict: """ Return descriptive information about an Amazon EKS managed node group. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_nodegroup` :param clusterName: The name of the Amazon EKS Cluster associated with the nodegroup. :param nodegroupName: The name of the nodegroup to describe. :param verbose: Provides additional logging if set to True. Defaults to False. :return: Returns descriptive information about a specific EKS Nodegroup. """ eks_client = self.conn response = eks_client.describe_nodegroup(clusterName=clusterName, nodegroupName=nodegroupName) self.log.info( "Retrieved details for Amazon EKS managed node group named %s in Amazon EKS cluster %s.", response.get("nodegroup").get("nodegroupName"), response.get("nodegroup").get("clusterName"), ) if verbose: nodegroup_data = response.get("nodegroup") self.log.info( "Amazon EKS managed node group details: %s", json.dumps(nodegroup_data, default=repr), ) return response def describe_fargate_profile( self, clusterName: str, fargateProfileName: str, verbose: bool = False ) -> dict: """ Return descriptive information about an AWS Fargate profile. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_fargate_profile` :param clusterName: The name of the Amazon EKS Cluster associated with the Fargate profile. :param fargateProfileName: The name of the Fargate profile to describe. :param verbose: Provides additional logging if set to True. Defaults to False. :return: Returns descriptive information about an AWS Fargate profile. """ eks_client = self.conn response = eks_client.describe_fargate_profile( clusterName=clusterName, fargateProfileName=fargateProfileName ) self.log.info( "Retrieved details for AWS Fargate profile named %s in Amazon EKS cluster %s.", response.get("fargateProfile").get("fargateProfileName"), response.get("fargateProfile").get("clusterName"), ) if verbose: fargate_profile_data = response.get("fargateProfile") self.log.info("AWS Fargate profile details: %s", json.dumps(fargate_profile_data, default=repr)) return response def get_cluster_state(self, clusterName: str) -> ClusterStates: """ Return the current status of a given Amazon EKS Cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_cluster` :param clusterName: The name of the cluster to check. :return: Returns the current status of a given Amazon EKS Cluster. """ eks_client = self.conn try: return ClusterStates(eks_client.describe_cluster(name=clusterName).get("cluster").get("status")) except ClientError as ex: if ex.response.get("Error").get("Code") == "ResourceNotFoundException": return ClusterStates.NONEXISTENT raise def get_fargate_profile_state(self, clusterName: str, fargateProfileName: str) -> FargateProfileStates: """ Return the current status of a given AWS Fargate profile. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_fargate_profile` :param clusterName: The name of the Amazon EKS Cluster associated with the Fargate profile. :param fargateProfileName: The name of the Fargate profile to check. :return: Returns the current status of a given AWS Fargate profile. """ eks_client = self.conn try: return FargateProfileStates( eks_client.describe_fargate_profile( clusterName=clusterName, fargateProfileName=fargateProfileName ) .get("fargateProfile") .get("status") ) except ClientError as ex: if ex.response.get("Error").get("Code") == "ResourceNotFoundException": return FargateProfileStates.NONEXISTENT raise def get_nodegroup_state(self, clusterName: str, nodegroupName: str) -> NodegroupStates: """ Return the current status of a given Amazon EKS managed node group. .. seealso:: - :external+boto3:py:meth:`EKS.Client.describe_nodegroup` :param clusterName: The name of the Amazon EKS Cluster associated with the nodegroup. :param nodegroupName: The name of the nodegroup to check. :return: Returns the current status of a given Amazon EKS Nodegroup. """ eks_client = self.conn try: return NodegroupStates( eks_client.describe_nodegroup(clusterName=clusterName, nodegroupName=nodegroupName) .get("nodegroup") .get("status") ) except ClientError as ex: if ex.response.get("Error").get("Code") == "ResourceNotFoundException": return NodegroupStates.NONEXISTENT raise def list_clusters( self, verbose: bool = False, ) -> list: """ List all Amazon EKS Clusters in your AWS account. .. seealso:: - :external+boto3:py:meth:`EKS.Client.list_clusters` :param verbose: Provides additional logging if set to True. Defaults to False. :return: A List containing the cluster names. """ eks_client = self.conn list_cluster_call = partial(eks_client.list_clusters) return self._list_all(api_call=list_cluster_call, response_key="clusters", verbose=verbose) def list_nodegroups( self, clusterName: str, verbose: bool = False, ) -> list: """ List all Amazon EKS managed node groups associated with the specified cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.list_nodegroups` :param clusterName: The name of the Amazon EKS Cluster containing nodegroups to list. :param verbose: Provides additional logging if set to True. Defaults to False. :return: A List of nodegroup names within the given cluster. """ eks_client = self.conn list_nodegroups_call = partial(eks_client.list_nodegroups, clusterName=clusterName) return self._list_all(api_call=list_nodegroups_call, response_key="nodegroups", verbose=verbose) def list_fargate_profiles( self, clusterName: str, verbose: bool = False, ) -> list: """ List all AWS Fargate profiles associated with the specified cluster. .. seealso:: - :external+boto3:py:meth:`EKS.Client.list_fargate_profiles` :param clusterName: The name of the Amazon EKS Cluster containing Fargate profiles to list. :param verbose: Provides additional logging if set to True. Defaults to False. :return: A list of Fargate profile names within a given cluster. """ eks_client = self.conn list_fargate_profiles_call = partial(eks_client.list_fargate_profiles, clusterName=clusterName) return self._list_all( api_call=list_fargate_profiles_call, response_key="fargateProfileNames", verbose=verbose ) def _list_all(self, api_call: Callable, response_key: str, verbose: bool) -> list: """ Repeatedly call a provided boto3 API Callable and collates the responses into a List. :param api_call: The api command to execute. :param response_key: Which dict key to collect into the final list. :param verbose: Provides additional logging if set to True. Defaults to False. :return: A List of the combined results of the provided API call. """ name_collection: list = [] token: str | None = DEFAULT_PAGINATION_TOKEN while token is not None: response = api_call(nextToken=token) # If response list is not empty, append it to the running list. name_collection += filter(None, response.get(response_key)) token = response.get("nextToken") self.log.info("Retrieved list of %s %s.", len(name_collection), response_key) if verbose: self.log.info("%s found: %s", response_key.title(), name_collection) return name_collection @contextlib.contextmanager def _secure_credential_context( self, access_key: str, secret_key: str, session_token: str | None ) -> Generator[str, None, None]: """ Context manager for secure temporary credential file. Creates a temporary file with restrictive permissions (0600) containing AWS credentials. The file is automatically cleaned up when the context manager exits. :param access_key: AWS access key ID :param secret_key: AWS secret access key :param session_token: AWS session token (optional) :return: Path to the temporary credential file """ fd = None temp_path = None try: # Create secure temporary file fd, temp_path = tempfile.mkstemp( suffix=".aws_creds", prefix="airflow_eks_", ) # Set restrictive permissions (0600) - owner read/write only os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR) # Write credentials to secure file with os.fdopen(fd, "w") as f: f.write(f"export AWS_ACCESS_KEY_ID='{access_key}'\n") f.write(f"export AWS_SECRET_ACCESS_KEY='{secret_key}'\n") if session_token: f.write(f"export AWS_SESSION_TOKEN='{session_token}'\n") fd = None # File handle closed by fdopen yield temp_path finally: # Cleanup if fd is not None: os.close(fd) if temp_path and os.path.exists(temp_path): try: os.unlink(temp_path) except OSError: pass # Best effort cleanup @contextmanager def generate_config_file( self, eks_cluster_name: str, pod_namespace: str | None, credentials_file, ) -> Generator[str, None, None]: """ Write the kubeconfig file given an EKS Cluster. :param eks_cluster_name: The name of the cluster to generate kubeconfig file for. :param pod_namespace: The namespace to run within kubernetes. """ args = "" if self.region_name is not None: args = args + f" --region-name {self.region_name}" # We need to determine which python executable the host is running in order to correctly # call the eks_get_token.py script. python_executable = f"python{sys.version_info[0]}.{sys.version_info[1]}" # Set up the client eks_client = self.conn session = self.get_session() # Get cluster details cluster = eks_client.describe_cluster(name=eks_cluster_name) cluster_cert = cluster["cluster"]["certificateAuthority"]["data"] cluster_ep = cluster["cluster"]["endpoint"] os.environ["AWS_STS_REGIONAL_ENDPOINTS"] = "regional" try: sts_url = f"{StsHook(region_name=session.region_name).conn_client_meta.endpoint_url}/?Action=GetCallerIdentity&Version=2011-06-15" finally: del os.environ["AWS_STS_REGIONAL_ENDPOINTS"] cluster_config = { "apiVersion": "v1", "kind": "Config", "clusters": [ { "cluster": {"server": cluster_ep, "certificate-authority-data": cluster_cert}, "name": eks_cluster_name, } ], "contexts": [ { "context": { "cluster": eks_cluster_name, "namespace": pod_namespace, "user": _POD_USERNAME, }, "name": _CONTEXT_NAME, } ], "current-context": _CONTEXT_NAME, "preferences": {}, "users": [ { "name": _POD_USERNAME, "user": { "exec": { "apiVersion": AUTHENTICATION_API_VERSION, "command": "sh", "args": [ "-c", COMMAND.format( credentials_file=credentials_file, sts_url=sts_url, python_executable=python_executable, eks_cluster_name=eks_cluster_name, args=args, ), ], "interactiveMode": "Never", } }, } ], } config_text = yaml.dump(cluster_config, default_flow_style=False) with tempfile.NamedTemporaryFile(mode="w") as config_file: config_file.write(config_text) config_file.flush() yield config_file.name
EksHook
python
huggingface__transformers
src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py
{ "start": 18236, "end": 18284 }
class ____(Qwen3VLModel): pass
Qwen3VLMoeModel
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 47040, "end": 47468 }
class ____(FieldValues): """ Valid and invalid values for `DateField` with a custom input format. """ valid_inputs = { '1 Jan 2001': datetime.date(2001, 1, 1), } invalid_inputs = { '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY.'] } outputs = {} field = serializers.DateField(input_formats=['%d %b %Y'])
TestCustomInputFormatDateField
python
kamyu104__LeetCode-Solutions
Python/perfect-number.py
{ "start": 35, "end": 421 }
class ____(object): def checkPerfectNumber(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False sqrt_num = int(num ** 0.5) total = sum(i+num//i for i in xrange(1, sqrt_num+1) if num%i == 0) if sqrt_num ** 2 == num: total -= sqrt_num return total - num == num
Solution
python
numpy__numpy
numpy/lib/tests/test_twodim_base.py
{ "start": 17141, "end": 17414 }
class ____: def test_exceptions(self): assert_raises(ValueError, tril_indices_from, np.ones((2,))) assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2))) # assert_raises(ValueError, tril_indices_from, np.ones((2, 3)))
TestTrilIndicesFrom
python
readthedocs__readthedocs.org
readthedocs/vcs_support/base.py
{ "start": 350, "end": 1004 }
class ____: """ Represents a Version (tag or branch) in a VCS. This class should only be instantiated in BaseVCS subclasses. It can act as a context manager to temporarily switch to this tag (eg to build docs for this tag). """ def __init__(self, repository, identifier, verbose_name): self.repository = repository self.identifier = identifier self.verbose_name = verbose_name def __repr__(self): return "<VCSVersion: {}:{}".format( self.repository.repo_url, self.verbose_name, ) # TODO: merge this class with Git VCS class to simplify the code.
VCSVersion
python
pypa__setuptools
setuptools/command/install_egg_info.py
{ "start": 182, "end": 2075 }
class ____(namespaces.Installer, Command): """Install an .egg-info directory for the package""" description = "Install an .egg-info directory for the package" user_options = [ ('install-dir=', 'd', "directory to install to"), ] def initialize_options(self): self.install_dir = None def finalize_options(self) -> None: self.set_undefined_options('install_lib', ('install_dir', 'install_dir')) ei_cmd = self.get_finalized_command("egg_info") basename = f"{ei_cmd._get_egg_basename()}.egg-info" self.source = ei_cmd.egg_info self.target = os.path.join(self.install_dir, basename) self.outputs: list[str] = [] def run(self) -> None: self.run_command('egg_info') if os.path.isdir(self.target) and not os.path.islink(self.target): dir_util.remove_tree(self.target, dry_run=self.dry_run) elif os.path.exists(self.target): self.execute(os.unlink, (self.target,), "Removing " + self.target) if not self.dry_run: ensure_directory(self.target) self.execute(self.copytree, (), f"Copying {self.source} to {self.target}") self.install_namespaces() def get_outputs(self): return self.outputs def copytree(self) -> None: # Copy the .egg-info tree to site-packages def skimmer(src, dst): # filter out source-control directories; note that 'src' is always # a '/'-separated path, regardless of platform. 'dst' is a # platform-specific path. for skip in '.svn/', 'CVS/': if src.startswith(skip) or '/' + skip in src: return None self.outputs.append(dst) log.debug("Copying %s to %s", src, dst) return dst unpack_archive(self.source, self.target, skimmer)
install_egg_info
python
viewflow__viewflow
viewflow/jsonstore.py
{ "start": 7127, "end": 7459 }
class ____(JSONFieldMixin, fields.TimeField): def to_json(self, value): if value: if not timezone.is_aware(value): value = timezone.make_aware(value) return value.isoformat() def from_json(self, value): if value: return dateparse.parse_time(value)
TimeField
python
marshmallow-code__marshmallow
src/marshmallow/fields.py
{ "start": 15976, "end": 23479 }
class ____(Field): """Allows you to nest a :class:`Schema <marshmallow.Schema>` inside a field. Examples: :: class ChildSchema(Schema): id = fields.Str() name = fields.Str() # Use lambda functions when you need two-way nesting or self-nesting parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) siblings = fields.List( fields.Nested(lambda: ChildSchema(only=("id", "name"))) ) class ParentSchema(Schema): id = fields.Str() children = fields.List( fields.Nested(ChildSchema(only=("id", "parent", "siblings"))) ) spouse = fields.Nested(lambda: ParentSchema(only=("id",))) When passing a `Schema <marshmallow.Schema>` instance as the first argument, the instance's ``exclude``, ``only``, and ``many`` attributes will be respected. Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`, you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument. :: # Yes author = fields.Nested(UserSchema, only=("id", "name")) # No author = fields.Nested(UserSchema(), only=("id", "name")) :param nested: `Schema <marshmallow.Schema>` instance, class, class name (string), dictionary, or callable that returns a `Schema <marshmallow.Schema>` or dictionary. Dictionaries are converted with `Schema.from_dict <marshmallow.Schema.from_dict>`. :param exclude: A list or tuple of fields to exclude. :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled. This parameter takes precedence over ``exclude``. :param many: Whether the field is a collection of objects. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. :param kwargs: The same keyword arguments that :class:`Field` receives. """ #: Default error messages. default_error_messages = {"type": "Invalid type."} def __init__( self, nested: ( Schema | SchemaMeta | str | dict[str, Field] | typing.Callable[[], Schema | SchemaMeta | dict[str, Field]] ), *, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, unknown: types.UnknownOption | None = None, **kwargs: Unpack[_BaseFieldKwargs], ): # Raise error if only or exclude is passed as string, not list of strings if only is not None and not utils.is_sequence_but_not_string(only): raise StringNotCollectionError('"only" should be a collection of strings.') if not utils.is_sequence_but_not_string(exclude): raise StringNotCollectionError( '"exclude" should be a collection of strings.' ) self.nested = nested self.only = only self.exclude = exclude self.many = many self.unknown = unknown self._schema: Schema | None = None # Cached Schema instance super().__init__(**kwargs) @property def schema(self) -> Schema: """The nested Schema object.""" if not self._schema: if callable(self.nested) and not isinstance(self.nested, type): nested = self.nested() else: nested = typing.cast("Schema", self.nested) # defer the import of `marshmallow.schema` to avoid circular imports from marshmallow.schema import Schema # noqa: PLC0415 if isinstance(nested, dict): nested = Schema.from_dict(nested) if isinstance(nested, Schema): self._schema = copy.copy(nested) # Respect only and exclude passed from parent and re-initialize fields set_class = typing.cast("type[set]", self._schema.set_class) if self.only is not None: if self._schema.only is not None: original = self._schema.only else: # only=None -> all fields original = self._schema.fields.keys() self._schema.only = set_class(self.only) & set_class(original) if self.exclude: original = self._schema.exclude self._schema.exclude = set_class(self.exclude) | set_class(original) self._schema._init_fields() else: if isinstance(nested, type) and issubclass(nested, Schema): schema_class: type[Schema] = nested elif not isinstance(nested, (str, bytes)): raise ValueError( "`Nested` fields must be passed a " f"`Schema`, not {nested.__class__}." ) else: schema_class = class_registry.get_class(nested, all=False) # type: ignore[unreachable] self._schema = schema_class( many=self.many, only=self.only, exclude=self.exclude, load_only=self._nested_normalized_option("load_only"), dump_only=self._nested_normalized_option("dump_only"), ) return self._schema def _nested_normalized_option(self, option_name: str) -> list[str]: nested_field = f"{self.name}." return [ field.split(nested_field, 1)[1] for field in getattr(self.root, option_name, set()) if field.startswith(nested_field) ] def _serialize(self, nested_obj, attr, obj, **kwargs): # Load up the schema first. This allows a RegistryError to be raised # if an invalid schema name was passed schema = self.schema if nested_obj is None: return None many = schema.many or self.many return schema.dump(nested_obj, many=many) def _test_collection(self, value: typing.Any) -> None: many = self.schema.many or self.many if many and not utils.is_collection(value): raise self.make_error("type", input=value, type=value.__class__.__name__) def _load( self, value: typing.Any, partial: bool | types.StrSequenceOrSet | None = None, # noqa: FBT001 ): try: valid_data = self.schema.load(value, unknown=self.unknown, partial=partial) except ValidationError as error: raise ValidationError( error.messages, valid_data=error.valid_data ) from error return valid_data def _deserialize( self, value: typing.Any, attr: str | None, data: typing.Mapping[str, typing.Any] | None, partial: bool | types.StrSequenceOrSet | None = None, # noqa: FBT001 **kwargs, ): """Same as :meth:`Field._deserialize` with additional ``partial`` argument. :param partial: For nested schemas, the ``partial`` parameter passed to `marshmallow.Schema.load`. .. versionchanged:: 3.0.0 Add ``partial`` parameter. """ self._test_collection(value) return self._load(value, partial=partial)
Nested
python
google__jax
tests/ode_test.py
{ "start": 859, "end": 8746 }
class ____(jtu.JaxTestCase): def check_against_scipy(self, fun, y0, tspace, *args, tol=1e-1): y0, tspace = np.array(y0), np.array(tspace) np_fun = partial(fun, np) scipy_result = jnp.asarray(osp_integrate.odeint(np_fun, y0, tspace, args)) y0, tspace = jnp.array(y0), jnp.array(tspace) jax_fun = partial(fun, jnp) jax_result = odeint(jax_fun, y0, tspace, *args) self.assertAllClose(jax_result, scipy_result, check_dtypes=False, atol=tol, rtol=tol) @jtu.skip_on_devices("tpu") def test_pend_grads(self): def pend(_np, y, _, m, g): theta, omega = y return [omega, -m * omega - g * _np.sin(theta)] y0 = [np.pi - 0.1, 0.0] ts = np.linspace(0., 1., 11) args = (0.25, 9.8) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 self.check_against_scipy(pend, y0, ts, *args, tol=tol) integrate = partial(odeint, partial(pend, jnp)) jtu.check_grads(integrate, (y0, ts, *args), modes=["rev"], order=2, atol=tol, rtol=tol) @jtu.skip_on_devices("tpu", "gpu") def test_pytree_state(self): """Test calling odeint with y(t) values that are pytrees.""" def dynamics(y, _t): return jax.tree.map(jnp.negative, y) y0 = (np.array(-0.1), np.array([[[0.1]]])) ts = np.linspace(0., 1., 11) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 integrate = partial(odeint, dynamics) jtu.check_grads(integrate, (y0, ts), modes=["rev"], order=2, atol=tol, rtol=tol) @jtu.skip_on_devices("tpu") def test_weird_time_pendulum_grads(self): """Test that gradients are correct when the dynamics depend on t.""" def dynamics(_np, y, t): return _np.array([y[1] * -t, -1 * y[1] - 9.8 * _np.sin(y[0])]) y0 = [np.pi - 0.1, 0.0] ts = np.linspace(0., 1., 11) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 self.check_against_scipy(dynamics, y0, ts, tol=tol) integrate = partial(odeint, partial(dynamics, jnp)) jtu.check_grads(integrate, (y0, ts), modes=["rev"], order=2, rtol=tol, atol=tol) @jtu.skip_on_devices("tpu", "gpu") def test_decay(self): def decay(_np, y, t, arg1, arg2): return -_np.sqrt(t) - y + arg1 - _np.mean((y + arg2)**2) rng = self.rng() args = (rng.randn(3), rng.randn(3)) y0 = rng.randn(3) ts = np.linspace(0.1, 0.2, 4) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 self.check_against_scipy(decay, y0, ts, *args, tol=tol) integrate = partial(odeint, partial(decay, jnp)) jtu.check_grads(integrate, (y0, ts, *args), modes=["rev"], order=2, rtol=tol, atol=tol) @jtu.skip_on_devices("tpu", "gpu") def test_swoop(self): def swoop(_np, y, t, arg1, arg2): return _np.array(y - _np.sin(t) - _np.cos(t) * arg1 + arg2) ts = np.array([0.1, 0.2]) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 y0 = np.linspace(0.1, 0.9, 10) args = (0.1, 0.2) self.check_against_scipy(swoop, y0, ts, *args, tol=tol) integrate = partial(odeint, partial(swoop, jnp)) jtu.check_grads(integrate, (y0, ts, *args), modes=["rev"], order=2, rtol=tol, atol=tol) @jtu.skip_on_devices("tpu", "gpu") def test_swoop_bigger(self): def swoop(_np, y, t, arg1, arg2): return _np.array(y - _np.sin(t) - _np.cos(t) * arg1 + arg2) ts = np.array([0.1, 0.2]) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 big_y0 = np.linspace(1.1, 10.9, 10) args = (0.1, 0.3) self.check_against_scipy(swoop, big_y0, ts, *args, tol=tol) integrate = partial(odeint, partial(swoop, jnp)) jtu.check_grads(integrate, (big_y0, ts, *args), modes=["rev"], order=2, rtol=tol, atol=tol) @jtu.skip_on_devices("tpu", "gpu") def test_odeint_vmap_grad(self): # https://github.com/jax-ml/jax/issues/2531 def dx_dt(x, *args): return 0.1 * x def f(x, y): y0 = jnp.array([x, y]) t = jnp.array([0., 5.]) y = odeint(dx_dt, y0, t) return y[-1].sum() def g(x): # Two initial values for the ODE y0_arr = jnp.array([[x, 0.1], [x, 0.2]]) # Run ODE twice t = jnp.array([0., 5.]) y = jax.vmap(lambda y0: odeint(dx_dt, y0, t))(y0_arr) return y[:,-1].sum() ans = jax.grad(g)(2.) # don't crash expected = jax.grad(f, 0)(2., 0.1) + jax.grad(f, 0)(2., 0.2) atol = {jnp.float32: 1e-5, jnp.float64: 5e-15} rtol = {jnp.float32: 1e-5, jnp.float64: 2e-15} self.assertAllClose(ans, expected, check_dtypes=False, atol=atol, rtol=rtol) @jtu.skip_on_devices("tpu", "gpu") def test_disable_jit_odeint_with_vmap(self): # https://github.com/jax-ml/jax/issues/2598 with jax.disable_jit(): t = jnp.array([0.0, 1.0]) x0_eval = jnp.zeros((5, 2)) f = lambda x0: odeint(lambda x, _t: x, x0, t) jax.vmap(f)(x0_eval) # doesn't crash @jtu.skip_on_devices("tpu", "gpu") def test_grad_closure(self): # simplification of https://github.com/jax-ml/jax/issues/2718 def experiment(x): def model(y, t): return -x * y history = odeint(model, 1., np.arange(0, 10, 0.1)) return history[-1] jtu.check_grads(experiment, (0.01,), modes=["rev"], order=1) @jtu.skip_on_devices("tpu", "gpu") def test_grad_closure_with_vmap(self): # https://github.com/jax-ml/jax/issues/2718 @jax.jit def experiment(x): def model(y, t): return -x * y history = odeint(model, 1., np.arange(0, 10, 0.1)) return history[-1] gradfun = jax.value_and_grad(experiment) t = np.arange(0., 1., 0.01) h, g = jax.vmap(gradfun)(t) # doesn't crash ans = h[11], g[11] expected_h = experiment(t[11]) expected_g = (experiment(t[11] + 5e-6) - experiment(t[11] - 5e-6)) / 1e-5 expected = expected_h, expected_g self.assertAllClose(ans, expected, check_dtypes=False, atol=1e-2, rtol=1e-2) @jtu.skip_on_devices("tpu", "gpu") def test_forward_mode_error(self): # https://github.com/jax-ml/jax/issues/3558 def f(k): return odeint(lambda x, t: k*x, 1., jnp.linspace(0, 1., 50)).sum() with self.assertRaisesRegex(TypeError, "can't apply forward-mode.*"): jax.jacfwd(f)(3.) @jtu.skip_on_devices("tpu", "gpu") def test_closure_nondiff(self): # https://github.com/jax-ml/jax/issues/3584 def dz_dt(z, t): return jnp.stack([z[0], z[1]]) def f(z): y = odeint(dz_dt, z, jnp.arange(10.)) return jnp.sum(y) jax.grad(f)(jnp.ones(2)) # doesn't crash @jtu.skip_on_devices("tpu", "gpu") def test_complex_odeint(self): # https://github.com/jax-ml/jax/issues/3986 # https://github.com/jax-ml/jax/issues/8757 def dy_dt(y, t, alpha): return alpha * y * jnp.exp(-t).astype(y.dtype) def f(y0, ts, alpha): return odeint(dy_dt, y0, ts, alpha).real alpha = 3 + 4j y0 = 1 + 2j ts = jnp.linspace(0., 1., 11) tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3 # During the backward pass, this ravels all parameters into a single array # such that dtype promotion is unavoidable. with jax.numpy_dtype_promotion('standard'): jtu.check_grads(f, (y0, ts, alpha), modes=["rev"], order=2, atol=tol, rtol=tol) @jtu.skip_on_devices("tpu", "gpu") def test_hmax(self): """Test max step size control.""" def rhs(y, t): return jnp.piecewise( t, [t <= 2., (t >= 5.) & (t <= 7.)], [lambda s: jnp.array(1.), lambda s: jnp.array(-1.), lambda s: jnp.array(0.)] ) ys = odeint(func=rhs, y0=jnp.array(0.), t=jnp.array([0., 5., 10.]), hmax=1.) self.assertTrue(jnp.abs(ys[1] - 2.) < 1e-4) self.assertTrue(jnp.abs(ys[2]) < 1e-4) if __name__ == '__main__': absltest.main(testLoader=jtu.JaxTestLoader())
ODETest
python
getsentry__sentry
src/sentry/issue_detection/detectors/disable_detectors.py
{ "start": 108, "end": 1686 }
class ____(TypedDict): detector_project_option: str languages_to_disable: set[str] SETTINGS_PROJECT_OPTION_KEY = "sentry:performance_issue_settings" # `project_performance_issue_settings.py` has the project option keys for each detector. DEFAULT_DETECTOR_DISABLING_CONFIGS: list[DetectorDisablingConfig] = [ { "detector_project_option": "consecutive_db_queries_detection_enabled", "languages_to_disable": {"ruby"}, }, { "detector_project_option": "consecutive_http_spans_detection_enabled", "languages_to_disable": {"python", "ruby", "other"}, }, ] def set_default_disabled_detectors(project: Project) -> None: performance_issue_settings_default = projectoptions.get_well_known_default( SETTINGS_PROJECT_OPTION_KEY, project=project, ) performance_issue_settings = project.get_option( SETTINGS_PROJECT_OPTION_KEY, default=performance_issue_settings_default ) disabled_by_config_keys = set() for disable_config in DEFAULT_DETECTOR_DISABLING_CONFIGS: if project.platform in disable_config["languages_to_disable"]: disabled_by_config_keys.add(disable_config["detector_project_option"]) disabled_by_config = {k: False for k in disabled_by_config_keys} if disabled_by_config: project.update_option( SETTINGS_PROJECT_OPTION_KEY, { **performance_issue_settings_default, **performance_issue_settings, **disabled_by_config, }, )
DetectorDisablingConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/final2.py
{ "start": 114, "end": 1501 }
class ____: def func1(self): pass @classmethod def func2(cls): pass @final def func3(self): pass @final @classmethod def func4(cls): pass @final def _func5(self): pass @final def __func6(self): pass @overload def func7(self, x: int) -> int: ... @overload def func7(self, x: str) -> str: ... @final def func7(self, x: int | str) -> int | str: ... # This should generate an error because the implementation # of func8 is marked as not final but this overload is. @overload @final def func8(self, x: int) -> int: ... @overload def func8(self, x: str) -> str: ... def func8(self, x: int | str) -> int | str: ... @final @property def prop1(self) -> int: ... @property @final def prop2(self) -> int: ... @property def prop3(self) -> int: ... @prop3.setter @final def prop3(self, value: int) -> None: ... # This should generate an error because func3 is final. ClassA.func3 = lambda self: None # This should generate an error because func4 is final. ClassA.func4 = lambda cls: None # This should generate an error because _func5 is final. ClassA._func5 = lambda self: None # This should generate an error because func7 is final. ClassA.func7 = cast(Any, lambda self, x: "")
ClassA
python
pytorch__pytorch
test/higher_order_ops/test_invoke_quant.py
{ "start": 3914, "end": 7103 }
class ____(TestInvokeQuant): backend = "inductor" def test_pattern_matching(self): counter = 0 test_pass = PatternMatcherPass() def my_pass(g): return test_pass.apply(g) def gn(x, y): return torch.mul(x, y) + y def fn(x, y, z): return invoke_quant_tracer(gn, x, y, scheme="nf4") @ z def fn_no_match(x, y, z): return invoke_quant_tracer(gn, x, y) @ z x = torch.randn(64, 64, requires_grad=False) y = torch.randn(64, 64, requires_grad=False) z = torch.randn(64, 64, requires_grad=False) @register_graph_pattern( CallFunction( torch.ops.aten.mm, CallFunction( torch.ops.higher_order.invoke_quant, Ignored(), Ignored(), Ignored(), scheme="nf4", ), Arg(), ), pass_dict=test_pass, ) def quant_matching(match: Match, *args, **kwargs): nonlocal counter counter += 1 with unittest.mock.patch( "torch._inductor.config.post_grad_custom_pre_pass", my_pass ): torch.compile(fn)(x, y, z) self.assertTrue(counter == 1) torch.compile(fn_no_match)(x, y, z) self.assertTrue(counter == 1) @skipIfXpu( msg="MM Triton template fusion for XPU not work because the fusion" " can not speedup, unskip until #146568 fixed." ) @requires_gpu() @config.patch(prologue_fusion=True) def test_prologue(self): if not is_big_gpu(): raise unittest.SkipTest("requires large gpu to max-autotune") def gn(x, y): return torch.mul(x, y) + (y - 1) def fn(x, y, z): return ( invoke_quant_tracer( gn, x, y, scheme="nf4", quant_options=invoke_quant_tracer ) @ z ) x = torch.randn( 64, 64, requires_grad=False, device=GPU_TYPE, dtype=torch.float16 ) # make this a no-op to ensure equivalent numerics y = torch.randn( 64, 64, requires_grad=False, device=GPU_TYPE, dtype=torch.float16 ).fill_(1.0) z = torch.randn( 64, 64, requires_grad=False, device=GPU_TYPE, dtype=torch.float16 ) ref = gn(x, y) @ z x_clone = x.clone().detach().requires_grad_(False) y_clone = y.clone().detach().requires_grad_(False) z_clone = z.clone().detach().requires_grad_(False) torch._dynamo.reset() with torch.no_grad(), config.patch(max_autotune_gemm_backends="TRITON"): fn_c = torch.compile(fn, mode="max-autotune-no-cudagraphs") res, code = run_and_get_code(fn_c, x_clone, y_clone, z_clone) FileCheck().check("k_idx in range").check_not("tl.float32").check( "tl.dot" ).run(code[0]) self.assertEqual(ref, res) del TestInvokeQuant if __name__ == "__main__": run_tests()
TestInvokeQuantInductor
python
facebook__pyre-check
client/commands/expression_level_coverage.py
{ "start": 3386, "end": 12230 }
class ____: module_paths: Iterable[Path] argument_paths: Iterable[Path] @staticmethod def from_raw_path_arguments( raw_paths: Iterable[str], configuration: frontend_configuration.Base, ) -> "CoveragePaths": working_directory = Path.cwd() explicit_paths: List[Path] = [] argument_paths: List[Path] = [] for raw_path in raw_paths: if raw_path[0] == "@": argument_paths.append(working_directory / Path(raw_path[1:])) else: explicit_paths.append(working_directory / Path(raw_path)) if len(explicit_paths) == 0 and len(argument_paths) > 0: # Do not typecheck everything in the project if the user passed # at least one argument file. module_paths: List[Path] = [] elif len(explicit_paths) == 0: module_paths = coverage_data.find_module_paths( paths=[ configuration.get_local_root() or configuration.get_global_root() ], excludes=configuration.get_excludes(), ) else: module_paths = coverage_data.find_module_paths( paths=explicit_paths, excludes=configuration.get_excludes(), ) return CoveragePaths( module_paths=module_paths, argument_paths=argument_paths, ) def get_paths_for_backend(self) -> List[str]: return [ *(str(path) for path in self.module_paths), *("@" + str(path) for path in self.argument_paths), ] def _calculate_percent_covered( uncovered_expressions: int, total_expressions: int ) -> float: if total_expressions == 0: return 100.0 return round( (total_expressions - uncovered_expressions) / total_expressions * 100, 2 ) def _get_total_and_uncovered_expressions( coverage: CoverageAtPath, ) -> Tuple[int, int]: return coverage.total_expressions, len(coverage.coverage_gaps) def get_percent_covered_per_path(path_response: CoverageAtPathResponse) -> float: total_expressions, uncovered_expressions = _get_total_and_uncovered_expressions( path_response.CoverageAtPath ) return _calculate_percent_covered(uncovered_expressions, total_expressions) def summary_expression_level(response: object) -> str: percent_output = "" overall_total_expressions = 0 overall_uncovered_expressions = 0 for path_response in _make_expression_level_coverage_response(response).response: if isinstance(path_response, ErrorAtPathResponse): continue expression_level_coverage = path_response.CoverageAtPath total_expressions, uncovered_expressions = _get_total_and_uncovered_expressions( expression_level_coverage ) overall_total_expressions += total_expressions overall_uncovered_expressions += uncovered_expressions percent_covered = get_percent_covered_per_path(path_response) percent_output += f"{expression_level_coverage.path}: {percent_covered}% expressions are covered\n" percent_covered = _calculate_percent_covered( overall_uncovered_expressions, overall_total_expressions ) percent_output += f"Overall: {percent_covered}% expressions are covered" return percent_output def location_to_range(location: Location) -> lsp.LspRange: return lsp.LspRange( start=lsp.LspPosition( line=location.start.line - 1, character=location.start.column ), end=lsp.LspPosition( line=location.stop.line - 1, character=location.stop.column ), ) def make_diagnostic_for_coverage_gap(coverage_gap: CoverageGap) -> lsp.Diagnostic: range = location_to_range(coverage_gap.location) return lsp.Diagnostic(range=range, message=coverage_gap.reason[0]) def get_uncovered_expression_diagnostics( expression_level_coverage: ExpressionLevelCoverageResponse, ) -> List[lsp.Diagnostic]: if not isinstance(expression_level_coverage.response[0], CoverageAtPathResponse): return [] # pyre-ignore[16]: Pyre doesn't understand Union of dataclasses_json within dataclasses_json coverage_gaps = expression_level_coverage.response[0].CoverageAtPath.coverage_gaps return [ make_diagnostic_for_coverage_gap(coverage_gap) for coverage_gap in coverage_gaps ] def _log_expression_level_coverage_to_remote( configuration: frontend_configuration.Base, response: object, ) -> None: logger = configuration.get_remote_logger() if logger is None: return run_id = str(time.time_ns()) for path_response in _make_expression_level_coverage_response(response).response: if isinstance(path_response, ErrorAtPathResponse): continue expression_level_coverage = path_response.CoverageAtPath _log_number_expression_level_coverage( configuration, logger, run_id, expression_level_coverage ) unannotated_functions = {} for coverage_gap in expression_level_coverage.coverage_gaps: function_name = coverage_gap.function_name if function_name is None: continue if function_name not in unannotated_functions: unannotated_functions[function_name] = 0 unannotated_functions[function_name] += 1 _log_unannotated_functions( configuration, logger, run_id, expression_level_coverage, unannotated_functions, ) def _log_number_expression_level_coverage( configuration: frontend_configuration.Base, logger: str, run_id: str, expression_level_coverage: CoverageAtPath, ) -> None: total_expressions = expression_level_coverage.total_expressions covered_expressions = total_expressions - len( expression_level_coverage.coverage_gaps ) remote_logger.log( category=remote_logger.LoggerCategory.EXPRESSION_LEVEL_COVERAGE, logger=logger, integers={ "total_expressions": total_expressions, "covered_expressions": covered_expressions, }, normals={ "run_id": run_id, "project_root": str(configuration.get_global_root()), "root": configuration.get_relative_local_root(), "path": expression_level_coverage.path, "binary": configuration.get_binary_version(), }, ) def _log_unannotated_functions( configuration: frontend_configuration.Base, logger: str, run_id: str, expression_level_coverage: CoverageAtPath, unannotated_functions: Dict[str, int], ) -> None: for function_name, count in unannotated_functions.items(): remote_logger.log( category=remote_logger.LoggerCategory.UNANNOTATED_FUNCTIONS, logger=logger, integers={ "count": count, }, normals={ "function_name": function_name, "run_id": run_id, "project_root": str(configuration.get_global_root()), "root": configuration.get_relative_local_root(), "path": expression_level_coverage.path, "binary": configuration.get_binary_version(), }, ) def run_query( configuration: frontend_configuration.Base, query_text: str, print_summary: bool = False, ) -> commands.ExitCode: socket_path = daemon_socket.get_socket_path( configuration.get_project_identifier(), flavor=identifiers.PyreFlavor.CLASSIC, ) try: response = daemon_query.execute_query(socket_path, query_text) _log_expression_level_coverage_to_remote(configuration, response.payload) if not print_summary: log.stdout.write(json.dumps(response.payload)) else: LOG.warning(summary_expression_level(response.payload)) return commands.ExitCode.SUCCESS except connections.ConnectionFailure: LOG.warning( "A running Pyre server is required for queries to be responded. " "Please run `pyre` first to set up a server." ) return commands.ExitCode.SERVER_NOT_FOUND def run( configuration: frontend_configuration.Base, paths: Iterable[str], print_summary: bool = False, ) -> commands.ExitCode: path_list = CoveragePaths.from_raw_path_arguments( raw_paths=paths, configuration=configuration, ).get_paths_for_backend() paths_string = ",".join([f"'{path}'" for path in path_list]) query_text = f"expression_level_coverage({paths_string})" return run_query( configuration, query_text, print_summary, )
CoveragePaths
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 158476, "end": 164236 }
class ____(SkewKurtosisTest): def stat_fun(self, x): return stats.kurtosis(x) @pytest.mark.filterwarnings("ignore:invalid value encountered in scalar divide") def test_kurtosis(self, xp): # Scalar test case y = stats.kurtosis(xp.asarray(self.scalar_testcase)) assert xp.isnan(y) # sum((testcase-mean(testcase,axis=0))**4,axis=0) # / ((sqrt(var(testcase)*3/4))**4) # / 4 # # sum((test2-mean(testmathworks,axis=0))**4,axis=0) # / ((sqrt(var(testmathworks)*4/5))**4) # / 5 # # Set flags for axis = 0 and # fisher=0 (Pearson's defn of kurtosis for compatibility with Matlab) y = stats.kurtosis(xp.asarray(self.testmathworks), 0, fisher=0, bias=1) xp_assert_close(y, xp.asarray(2.1658856802973)) # Note that MATLAB has confusing docs for the following case # kurtosis(x,0) gives an unbiased estimate of Pearson's skewness # kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3) # The MATLAB docs imply that both should give Fisher's y = stats.kurtosis(xp.asarray(self.testmathworks), fisher=0, bias=0) xp_assert_close(y, xp.asarray(3.663542721189047)) y = stats.kurtosis(xp.asarray(self.testcase), 0, 0) xp_assert_close(y, xp.asarray(1.64)) x = xp.arange(10.) x = xp.where(x == 8, xp.nan, x) xp_assert_equal(stats.kurtosis(x), xp.asarray(xp.nan)) def test_kurtosis_nan_policy(self): # nan_policy only for NumPy right now x = np.arange(10.) x[9] = np.nan assert_almost_equal(stats.kurtosis(x, nan_policy='omit'), -1.230000) assert_raises(ValueError, stats.kurtosis, x, nan_policy='raise') assert_raises(ValueError, stats.kurtosis, x, nan_policy='foobar') def test_kurtosis_array_scalar(self): # "array scalars" do not exist in other backends assert_equal(type(stats.kurtosis([1, 2, 3])), np.float64) def test_kurtosis_propagate_nan(self): # nan_policy only for NumPy right now # Check that the shape of the result is the same for inputs # with and without nans, cf gh-5817 a = np.arange(8).reshape(2, -1).astype(float) a[1, 0] = np.nan k = stats.kurtosis(a, axis=1, nan_policy="propagate") np.testing.assert_allclose(k, [-1.36, np.nan], atol=1e-15) def test_kurtosis_constant_value(self, xp): # Kurtosis of a constant input should be NaN (gh-16061) a = xp.asarray([-0.27829495]*10) with eager_warns(RuntimeWarning, match="Precision loss occurred", xp=xp): assert xp.isnan(stats.kurtosis(a, fisher=False)) assert xp.isnan(stats.kurtosis(a * float(2**50), fisher=False)) assert xp.isnan(stats.kurtosis(a / float(2**50), fisher=False)) assert xp.isnan(stats.kurtosis(a, fisher=False, bias=False)) @pytest.mark.parametrize('axis', [-1, 0, 2, None]) @pytest.mark.parametrize('bias', [False, True]) @pytest.mark.parametrize('fisher', [False, True]) def test_vectorization(self, xp, axis, bias, fisher): # Behavior with array input is not tested above. Compare # against naive implementation. rng = np.random.default_rng(1283413549926) x = xp.asarray(rng.random((4, 5, 6))) def kurtosis(a, axis, bias, fisher): # Simple implementation of kurtosis if axis is None: a = xp.reshape(a, (-1,)) axis = 0 mean = xp.mean(a, axis=axis, keepdims=True) mu4 = xp.mean((a - mean)**4, axis=axis) mu2 = xp.var(a, axis=axis, correction=0) if bias: res = mu4 / mu2**2 - 3 else: n = a.shape[axis] # https://en.wikipedia.org/wiki/Kurtosis#Standard_unbiased_estimator res = (n-1) / ((n-2) * (n-3)) * ((n + 1) * mu4/mu2**2 - 3*(n-1)) # I know it looks strange to subtract then add 3, # but it is simpler than the alternatives return res if fisher else res + 3 res = stats.kurtosis(x, axis=axis, bias=bias, fisher=fisher) ref = kurtosis(x, axis=axis, bias=bias, fisher=fisher) xp_assert_close(res, ref) @hypothesis.strategies.composite def ttest_data_axis_strategy(draw): # draw an array under shape and value constraints elements = dict(allow_nan=False, allow_infinity=False) shape = npst.array_shapes(min_dims=1, min_side=2) # The test that uses this, `test_pvalue_ci`, uses `float64` to test # extreme `alpha`. It could be adjusted to test a dtype-dependent # range of `alpha` if this strategy is needed to generate other floats. data = draw(npst.arrays(dtype=np.float64, elements=elements, shape=shape)) # determine axes over which nonzero variance can be computed accurately ok_axes = [] # Locally, I don't need catch_warnings or simplefilter, and I can just # suppress RuntimeWarning. I include all that in hope of getting the same # behavior on CI. with warnings.catch_warnings(): warnings.simplefilter("error") for axis in range(len(data.shape)): with contextlib.suppress(Exception): var = stats.moment(data, order=2, axis=axis) if np.all(var > 0) and np.all(np.isfinite(var)): ok_axes.append(axis) # if there are no valid axes, tell hypothesis to try a different example hypothesis.assume(ok_axes) # draw one of the valid axes axis = draw(hypothesis.strategies.sampled_from(ok_axes)) return data, axis @make_xp_test_case(stats.ttest_1samp)
TestKurtosis
python
python-pillow__Pillow
src/PIL/ImagePalette.py
{ "start": 638, "end": 9009 }
class ____: """ Color palette for palette mapped images :param mode: The mode to use for the palette. See: :ref:`concept-modes`. Defaults to "RGB" :param palette: An optional palette. If given, it must be a bytearray, an array or a list of ints between 0-255. The list must consist of all channels for one color followed by the next color (e.g. RGBRGBRGB). Defaults to an empty palette. """ def __init__( self, mode: str = "RGB", palette: Sequence[int] | bytes | bytearray | None = None, ) -> None: self.mode = mode self.rawmode: str | None = None # if set, palette contains raw data self.palette = palette or bytearray() self.dirty: int | None = None @property def palette(self) -> Sequence[int] | bytes | bytearray: return self._palette @palette.setter def palette(self, palette: Sequence[int] | bytes | bytearray) -> None: self._colors: dict[tuple[int, ...], int] | None = None self._palette = palette @property def colors(self) -> dict[tuple[int, ...], int]: if self._colors is None: mode_len = len(self.mode) self._colors = {} for i in range(0, len(self.palette), mode_len): color = tuple(self.palette[i : i + mode_len]) if color in self._colors: continue self._colors[color] = i // mode_len return self._colors @colors.setter def colors(self, colors: dict[tuple[int, ...], int]) -> None: self._colors = colors def copy(self) -> ImagePalette: new = ImagePalette() new.mode = self.mode new.rawmode = self.rawmode if self.palette is not None: new.palette = self.palette[:] new.dirty = self.dirty return new def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]: """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes() def tobytes(self) -> bytes: """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(self.palette, bytes): return self.palette arr = array.array("B", self.palette) return arr.tobytes() # Declare tostring as an alias for tobytes tostring = tobytes def _new_color_index( self, image: Image.Image | None = None, e: Exception | None = None ) -> int: if not isinstance(self.palette, bytearray): self._palette = bytearray(self.palette) index = len(self.palette) // 3 special_colors: tuple[int | tuple[int, ...] | None, ...] = () if image: special_colors = ( image.info.get("background"), image.info.get("transparency"), ) while index in special_colors: index += 1 if index >= 256: if image: # Search for an unused index for i, count in reversed(list(enumerate(image.histogram()))): if count == 0 and i not in special_colors: index = i break if index >= 256: msg = "cannot allocate more than 256 colors" raise ValueError(msg) from e return index def getcolor( self, color: tuple[int, ...], image: Image.Image | None = None, ) -> int: """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(color, tuple): if self.mode == "RGB": if len(color) == 4: if color[3] != 255: msg = "cannot add non-opaque RGBA color to RGB palette" raise ValueError(msg) color = color[:3] elif self.mode == "RGBA": if len(color) == 3: color += (255,) try: return self.colors[color] except KeyError as e: # allocate new color slot index = self._new_color_index(image, e) assert isinstance(self._palette, bytearray) self.colors[color] = index if index * 3 < len(self.palette): self._palette = ( self._palette[: index * 3] + bytes(color) + self._palette[index * 3 + 3 :] ) else: self._palette += bytes(color) self.dirty = 1 return index else: msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable] raise ValueError(msg) def save(self, fp: str | IO[str]) -> None: """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: msg = "palette contains raw palette data" raise ValueError(msg) if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.write(f"# Mode: {self.mode}\n") for i in range(256): fp.write(f"{i}") for j in range(i * len(self.mode), (i + 1) * len(self.mode)): try: fp.write(f" {self.palette[j]}") except IndexError: fp.write(" 0") fp.write("\n") fp.close() # -------------------------------------------------------------------- # Internal def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette: palette = ImagePalette() palette.rawmode = rawmode palette.palette = data palette.dirty = 1 return palette # -------------------------------------------------------------------- # Factories def make_linear_lut(black: int, white: float) -> list[int]: if black == 0: return [int(white * i // 255) for i in range(256)] msg = "unavailable when black is non-zero" raise NotImplementedError(msg) # FIXME def make_gamma_lut(exp: float) -> list[int]: return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)] def negative(mode: str = "RGB") -> ImagePalette: palette = list(range(256 * len(mode))) palette.reverse() return ImagePalette(mode, [i // len(mode) for i in palette]) def random(mode: str = "RGB") -> ImagePalette: from random import randint palette = [randint(0, 255) for _ in range(256 * len(mode))] return ImagePalette(mode, palette) def sepia(white: str = "#fff0c0") -> ImagePalette: bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)] return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)]) def wedge(mode: str = "RGB") -> ImagePalette: palette = list(range(256 * len(mode))) return ImagePalette(mode, [i // len(mode) for i in palette]) def load(filename: str) -> tuple[bytes, str]: # FIXME: supports GIMP gradients only with open(filename, "rb") as fp: paletteHandlers: list[ type[ GimpPaletteFile.GimpPaletteFile | GimpGradientFile.GimpGradientFile | PaletteFile.PaletteFile ] ] = [ GimpPaletteFile.GimpPaletteFile, GimpGradientFile.GimpGradientFile, PaletteFile.PaletteFile, ] for paletteHandler in paletteHandlers: try: fp.seek(0) lut = paletteHandler(fp).getpalette() if lut: break except (SyntaxError, ValueError): pass else: msg = "cannot load palette" raise OSError(msg) return lut # data, rawmode
ImagePalette
python
Netflix__metaflow
metaflow/plugins/kubernetes/kubernetes_job.py
{ "start": 16313, "end": 32277 }
class ____(object): # State Machine implementation for the lifecycle behavior documented in # https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/ # # This object encapsulates *both* V1Job and V1Pod. It simplifies the status # to "running" and "done" (failed/succeeded) state. Note that V1Job and V1Pod # status fields are not guaranteed to be always in sync due to the way job # controller works. # To ascertain the status of V1Job, we peer into the lifecycle status of # the pod it is responsible for executing. Unfortunately, the `phase` # attributes (pending, running, succeeded, failed etc.) only provide # partial answers and the official API conventions guide suggests that # it may soon be deprecated (however, not anytime soon - see # https://github.com/kubernetes/kubernetes/issues/7856). `conditions` otoh # provide a deeper understanding about the state of the pod; however # conditions are not state machines and can be oscillating - from the # official API conventions guide: # In general, condition values may change back and forth, but some # condition transitions may be monotonic, depending on the resource and # condition type. However, conditions are observations and not, # themselves, state machines, nor do we define comprehensive state # machines for objects, nor behaviors associated with state # transitions. The system is level-based rather than edge-triggered, # and should assume an Open World. # As a follow-up, we can synthesize our notion of "phase" state # machine from `conditions`, since Kubernetes won't do it for us (for # many good reasons). # # `conditions` can be of the following types - # 1. (kubelet) Initialized (always True since we don't rely on init # containers) # 2. (kubelet) ContainersReady # 3. (kubelet) Ready (same as ContainersReady since we don't use # ReadinessGates - # https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/status/generate.go) # 4. (kube-scheduler) PodScheduled # (https://github.com/kubernetes/kubernetes/blob/master/pkg/scheduler/scheduler.go) def __init__(self, client, name, uid, namespace): self._client = client self._name = name self._pod_name = None self._id = uid self._namespace = namespace self._job = self._fetch_job() self._pod = self._fetch_pod() import atexit def best_effort_kill(): try: self.kill() except Exception: pass atexit.register(best_effort_kill) def __repr__(self): return "{}('{}/{}')".format( self.__class__.__name__, self._namespace, self._name ) @k8s_retry() def _fetch_job(self): client = self._client.get() try: return ( client.BatchV1Api() .read_namespaced_job(name=self._name, namespace=self._namespace) .to_dict() ) except client.rest.ApiException as e: if e.status == 404: raise KubernetesJobException( "Unable to locate Kubernetes batch/v1 job %s" % self._name ) raise @k8s_retry() def _fetch_pod(self): # Fetch pod metadata. client = self._client.get() pods = ( client.CoreV1Api() .list_namespaced_pod( namespace=self._namespace, label_selector="job-name={}".format(self._name), ) .to_dict()["items"] ) if pods: return pods[0] return {} def kill(self): # Terminating a Kubernetes job is a bit tricky. Issuing a # `BatchV1Api.delete_namespaced_job` will also remove all traces of the # job object from the Kubernetes API server which may not be desirable. # This forces us to be a bit creative in terms of how we handle kill: # # 1. If the container is alive and kicking inside the pod, we simply # attach ourselves to the container and issue a kill signal. The # way we have initialized the Job ensures that the job will cleanly # terminate. # 2. In scenarios where either the pod (unschedulable etc.) or the # container (ImagePullError etc.) hasn't come up yet, we become a # bit creative by patching the job parallelism to 0. This ensures # that the underlying node's resources are made available to # kube-scheduler again. The downside is that the Job wouldn't mark # itself as done and the pod metadata disappears from the API # server. There is an open issue in the Kubernetes GH to provide # better support for job terminations - # https://github.com/kubernetes/enhancements/issues/2232 # 3. If the pod object hasn't shown up yet, we set the parallelism to 0 # to preempt it. client = self._client.get() if not self.is_done: if self.is_running: # Case 1. from kubernetes.stream import stream api_instance = client.CoreV1Api try: # TODO: stream opens a web-socket connection. It may # not be desirable to open multiple web-socket # connections frivolously (think killing a # workflow during a for-each step). stream( api_instance().connect_get_namespaced_pod_exec, name=self._pod["metadata"]["name"], namespace=self._namespace, command=[ "/bin/sh", "-c", "/sbin/killall5", ], stderr=True, stdin=False, stdout=True, tty=False, ) except: # Best effort. It's likely that this API call could be # blocked for the user. # -------------------------------------------------------- # We try patching Job parallelism anyway. Stopping any runaway # jobs (and their pods) is secondary to correctly showing # "Killed" status on the Kubernetes pod. # # This has the effect of pausing the job. try: client.BatchV1Api().patch_namespaced_job( name=self._name, namespace=self._namespace, field_manager="metaflow", body={"spec": {"parallelism": 0}}, ) except: # Best effort. pass # raise else: # Case 2. # This has the effect of pausing the job. try: client.BatchV1Api().patch_namespaced_job( name=self._name, namespace=self._namespace, field_manager="metaflow", body={"spec": {"parallelism": 0}}, ) except: # Best effort. pass # raise return self @property def id(self): if self._pod_name: return "pod %s" % self._pod_name if self._pod: self._pod_name = self._pod["metadata"]["name"] return self.id return "job %s" % self._name @property def is_done(self): # Check if the container is done. As a side effect, also refreshes self._job and # self._pod with the latest state def done(): # Either the container succeeds or fails naturally or else we may have # forced the pod termination causing the job to still be in an # active state but for all intents and purposes dead to us. return ( bool(self._job["status"].get("succeeded")) or bool(self._job["status"].get("failed")) or self._are_pod_containers_done or (self._job["spec"]["parallelism"] == 0) ) if not done(): # If not done, fetch newer status self._job = self._fetch_job() self._pod = self._fetch_pod() return done() @property def status(self): if not self.is_done: if bool(self._job["status"].get("active")): if self._pod: msg = ( "Pod is %s" % self._pod.get("status", {}) .get("phase", "uninitialized") .lower() ) # TODO (savin): parse Pod conditions container_status = ( self._pod["status"].get("container_statuses") or [None] )[0] if container_status: # We have a single container inside the pod status = {"status": "waiting"} for k, v in container_status["state"].items(): if v is not None: status["status"] = k status.update(v) msg += ", Container is %s" % status["status"].lower() reason = "" if status.get("reason"): pass reason = status["reason"] if status.get("message"): reason += " - %s" % status["message"] if reason: msg += " - %s" % reason return msg return "Job is active" return "Job status is unknown" return "Job is done" @property def has_succeeded(self): # The tasks container is in a terminal state and the status is marked as succeeded return self.is_done and self._have_containers_succeeded @property def has_failed(self): # Either the container is marked as failed or the Job is not allowed to # any more pods retval = self.is_done and ( bool(self._job["status"].get("failed")) or self._has_any_container_failed or (self._job["spec"]["parallelism"] == 0) ) return retval @property def _have_containers_succeeded(self): container_statuses = self._pod.get("status", {}).get("container_statuses", []) if not container_statuses: return False for cstatus in container_statuses: # If the terminated field is not set, the pod is still running. terminated = cstatus.get("state", {}).get("terminated", {}) if not terminated: return False # If the terminated field is set but the `finished_at` field is not set, # the pod is still considered as running. if not terminated.get("finished_at"): return False # If finished_at is set AND reason is Completed if terminated.get("reason", "").lower() != "completed": return False return True @property def _has_any_container_failed(self): container_statuses = self._pod.get("status", {}).get("container_statuses", []) if not container_statuses: return False for cstatus in container_statuses: # If the terminated field is not set, the pod is still running. Too early # to determine if any container failed. terminated = cstatus.get("state", {}).get("terminated", {}) if not terminated: return False # If the terminated field is set but the `finished_at` field is not set, # the pod is still considered as running. Too early to determine if any # container failed. if not terminated.get("finished_at"): return False # If finished_at is set AND reason is Error, it means that the # container failed. if terminated.get("reason", "").lower() == "error": return True # If none of the containers are marked as failed, the pod is not # considered failed. return False @property def _are_pod_containers_done(self): # All containers in the pod have a containerStatus that has a # finishedAt set. container_statuses = self._pod.get("status", {}).get("container_statuses", []) if not container_statuses: return False for cstatus in container_statuses: # If the terminated field is not set, the pod is still running. Too early # to determine if any container failed. terminated = cstatus.get("state", {}).get("terminated", {}) if not terminated: return False # If the terminated field is set but the `finished_at` field is not set, # the pod is still considered as running. if not terminated.get("finished_at"): return False # If we got until here, the containers were marked terminated and their # finishedAt was set. return True @property def is_running(self): # Returns true if the container is running. if self.is_done: return False return not self._are_pod_containers_done @property def is_waiting(self): return not self.is_done and not self.is_running @property def reason(self): if self.is_done: if self.has_succeeded: return 0, None # Best effort since Pod object can disappear on us at anytime else: if self._pod.get("status", {}).get("phase") not in ( "Succeeded", "Failed", ): # If pod status is dirty, check for newer status self._pod = self._fetch_pod() if self._pod: if self._pod.get("status", {}).get("container_statuses") is None: # We're done, but no container_statuses is set # This can happen when the pod is evicted return None, ": ".join( filter( None, [ self._pod.get("status", {}).get("reason"), self._pod.get("status", {}).get("message"), ], ) ) for k, v in ( self._pod.get("status", {}) .get("container_statuses", [{}])[0] .get("state", {}) .items() ): if v is not None: return v.get("exit_code"), ": ".join( filter( None, [v.get("reason"), v.get("message")], ) ) return None, None
RunningJob
python
ray-project__ray
python/ray/llm/tests/common/cloud/test_pyarrow_filesystem.py
{ "start": 278, "end": 7225 }
class ____: """Tests for the PyArrowFileSystem class.""" @patch("pyarrow.fs.S3FileSystem") def test_get_file(self, mock_s3fs): """Test getting a file from cloud storage.""" # Setup mock filesystem and file mock_fs = MagicMock() mock_s3fs.return_value = mock_fs # Mock file content and info mock_file = MagicMock() mock_file.read.return_value = b"test file content" mock_fs.open_input_file.return_value.__enter__.return_value = mock_file mock_fs.get_file_info.return_value.type = pa_fs.FileType.File # Test getting file as string (default) content = PyArrowFileSystem.get_file("s3://bucket/test.txt") assert content == "test file content" # Test getting file as bytes content_bytes = PyArrowFileSystem.get_file( "s3://bucket/test.txt", decode_as_utf_8=False ) assert content_bytes == b"test file content" # Test non-existent file mock_fs.get_file_info.return_value.type = pa_fs.FileType.NotFound assert PyArrowFileSystem.get_file("s3://bucket/nonexistent.txt") is None @patch("pyarrow.fs.GcsFileSystem") def test_list_subfolders(self, mock_gcsfs): """Test listing subfolders in cloud storage.""" # Setup mock filesystem mock_fs = MagicMock() mock_gcsfs.return_value = mock_fs # Create mock file infos for directory listing dir1 = MagicMock() dir1.type = pa_fs.FileType.Directory dir1.path = "bucket/parent/dir1" dir2 = MagicMock() dir2.type = pa_fs.FileType.Directory dir2.path = "bucket/parent/dir2" file1 = MagicMock() file1.type = pa_fs.FileType.File file1.path = "bucket/parent/file.txt" mock_fs.get_file_info.return_value = [dir1, dir2, file1] # Test listing subfolders folders = PyArrowFileSystem.list_subfolders("gs://bucket/parent") assert sorted(folders) == ["dir1", "dir2"] @patch.object(PyArrowFileSystem, "get_fs_and_path") def test_list_subfolders_exception_handling(self, mock_get_fs_and_path): """Test that list_subfolders returns empty list when get_fs_and_path raises exception.""" # Make get_fs_and_path raise an exception mock_get_fs_and_path.side_effect = ValueError("Example exception") # Test that list_subfolders handles the exception gracefully folders = PyArrowFileSystem.list_subfolders("gs://bucket/parent") assert folders == [] # Verify get_fs_and_path was called mock_get_fs_and_path.assert_called_once_with("gs://bucket/parent/") @patch("pyarrow.fs.copy_files") @patch("pyarrow.fs.S3FileSystem") def test_download_files_no_filters(self, mock_s3fs, mock_copy_files): """Test downloading files from cloud storage without filters.""" # Setup mock filesystem mock_fs = MagicMock() mock_s3fs.return_value = mock_fs # Create temp directory for testing with tempfile.TemporaryDirectory() as tempdir: # Test downloading files without filters PyArrowFileSystem.download_files(tempdir, "s3://bucket/dir") # Verify copy_files was called with correct arguments mock_copy_files.assert_called_once_with( source="bucket/dir", destination=tempdir, source_filesystem=mock_fs, destination_filesystem=ANY, use_threads=True, chunk_size=64 * 1024 * 1024, ) @patch("pyarrow.fs.copy_files") @patch("pyarrow.fs.S3FileSystem") def test_download_files_with_filters(self, mock_s3fs, mock_copy_files): """Test downloading files from cloud storage with filters.""" # Setup mock filesystem mock_fs = MagicMock() mock_s3fs.return_value = mock_fs # Create mock file infos for listing file_info1 = MagicMock() file_info1.type = pa_fs.FileType.File file_info1.path = "bucket/dir/file1.txt" file_info2 = MagicMock() file_info2.type = pa_fs.FileType.File file_info2.path = "bucket/dir/subdir/file2.json" file_info3 = MagicMock() file_info3.type = pa_fs.FileType.File file_info3.path = "bucket/dir/file3.tmp" dir_info = MagicMock() dir_info.type = pa_fs.FileType.Directory dir_info.path = "bucket/dir/subdir" mock_fs.get_file_info.return_value = [ file_info1, file_info2, file_info3, dir_info, ] # Create temp directory for testing with tempfile.TemporaryDirectory() as tempdir: # Test downloading files with filters PyArrowFileSystem.download_files( tempdir, "s3://bucket/dir", substrings_to_include=["file1", "file2"], suffixes_to_exclude=[".tmp"], ) # Verify copy_files was called for each filtered file assert mock_copy_files.call_count == 2 # Get all calls to copy_files calls = mock_copy_files.call_args_list # Verify the calls (order may vary due to threading) expected_sources = {"bucket/dir/file1.txt", "bucket/dir/subdir/file2.json"} expected_dests = { os.path.join(tempdir, "file1.txt"), os.path.join(tempdir, "subdir", "file2.json"), } actual_sources = {call.kwargs["source"] for call in calls} actual_dests = {call.kwargs["destination"] for call in calls} assert actual_sources == expected_sources assert actual_dests == expected_dests # Verify all calls have correct filesystem and options for call in calls: assert call.kwargs["source_filesystem"] == mock_fs assert call.kwargs["destination_filesystem"] is not None assert call.kwargs["use_threads"] is True assert call.kwargs["chunk_size"] == 64 * 1024 * 1024 @patch("pyarrow.fs.copy_files") @patch("pyarrow.fs.S3FileSystem") def test_upload_files(self, mock_s3fs, mock_copy_files): """Test uploading files to cloud storage.""" # Setup mock filesystem mock_fs = MagicMock() mock_s3fs.return_value = mock_fs # Create temp directory for testing with tempfile.TemporaryDirectory() as tempdir: # Test uploading files PyArrowFileSystem.upload_files(tempdir, "s3://bucket/dir") # Check that the files are copied mock_copy_files.assert_called_once_with( source=tempdir, destination="bucket/dir", source_filesystem=ANY, destination_filesystem=ANY, )
TestPyArrowFileSystem
python
sympy__sympy
sympy/physics/quantum/sho1d.py
{ "start": 9159, "end": 12882 }
class ____(SHOOp): """The Number Operator is simply a^dagger*a It is often useful to write a^dagger*a as simply the Number Operator because the Number Operator commutes with the Hamiltonian. And can be expressed using the Number Operator. Also the Number Operator can be applied to states. We can represent the Number Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Number Operator and rewrite it in terms of the ladder operators, position and momentum operators, and Hamiltonian: >>> from sympy.physics.quantum.sho1d import NumberOp >>> N = NumberOp('N') >>> N.rewrite('a').doit() RaisingOp(a)*a >>> N.rewrite('xp').doit() -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega) >>> N.rewrite('H').doit() -1/2 + H/(hbar*omega) Take the Commutator of the Number Operator with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> N = NumberOp('N') >>> H = Hamiltonian('H') >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> Commutator(N,H).doit() 0 >>> Commutator(N,ad).doit() RaisingOp(a) >>> Commutator(N,a).doit() -a Apply the Number Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet >>> N = NumberOp('N') >>> k = SHOKet('k') >>> qapply(N*k) k*|k> Matrix Representation >>> from sympy.physics.quantum.sho1d import NumberOp >>> from sympy.physics.quantum.represent import represent >>> N = NumberOp('N') >>> represent(N, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]) """ def _eval_rewrite_as_a(self, *args, **kwargs): return ad*a def _eval_rewrite_as_xp(self, *args, **kwargs): return (S.One/(Integer(2)*m*hbar*omega))*(Px**2 + ( m*omega*X)**2) - S.Half def _eval_rewrite_as_H(self, *args, **kwargs): return H/(hbar*omega) - S.Half def _apply_operator_SHOKet(self, ket, **options): return ket.n*ket def _eval_commutator_Hamiltonian(self, other): return S.Zero def _eval_commutator_RaisingOp(self, other): return other def _eval_commutator_LoweringOp(self, other): return S.NegativeOne*other def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix
NumberOp
python
apache__airflow
providers/databricks/tests/unit/databricks/hooks/test_databricks.py
{ "start": 75192, "end": 76903 }
class ____: """ Tests for DatabricksHook using async methods when auth is done with AAD token for SP as user inside workspace. """ @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id=DEFAULT_CONN_ID, conn_type="databricks", host=HOST, login="9ff815a6-4404-4ab8-85cb-cd0e6f879c1d", password="secret", extra=json.dumps( { "azure_tenant_id": "3ff810a6-5504-4ab8-85cb-cd0e6f879c1d", } ), ) ) self.hook = DatabricksHook(retry_args=DEFAULT_RETRY_ARGS) @pytest.mark.asyncio @mock.patch("airflow.providers.databricks.hooks.databricks_base.aiohttp.ClientSession.get") @mock.patch("azure.identity.aio.ClientSecretCredential.get_token") async def test_get_run_state(self, mock_azure_identity, mock_get): mock_get.return_value.__aenter__.return_value.json = AsyncMock(return_value=GET_RUN_RESPONSE) mock_azure_identity.return_value = create_aad_token_for_resource() async with self.hook: run_state = await self.hook.a_get_run_state(RUN_ID) assert run_state == RunState(LIFE_CYCLE_STATE, RESULT_STATE, STATE_MESSAGE) mock_get.assert_called_once_with( get_run_endpoint(HOST), json={"run_id": RUN_ID}, auth=BearerAuth(TOKEN), headers=self.hook.user_agent_header, timeout=self.hook.timeout_seconds, ) @pytest.mark.db_test
TestDatabricksHookAsyncAadToken
python
doocs__leetcode
solution/2500-2599/2574.Left and Right Sum Differences/Solution.py
{ "start": 0, "end": 262 }
class ____: def leftRigthDifference(self, nums: List[int]) -> List[int]: left, right = 0, sum(nums) ans = [] for x in nums: right -= x ans.append(abs(left - right)) left += x return ans
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/cli/__init__.py
{ "start": 5229, "end": 7129 }
class ____: empty_workspace: bool = False workspace: Optional[Sequence[str]] = None # Like PythonPointerParams but multiple files/modules/packages are allowed python_file: Optional[Sequence[str]] = None module_name: Optional[Sequence[str]] = None package_name: Optional[Sequence[str]] = None working_directory: Optional[str] = None attribute: Optional[str] = None autoload_defs_module_name: Optional[str] = None # For gRPC server grpc_port: Optional[int] = None grpc_socket: Optional[str] = None grpc_host: Optional[str] = None use_ssl: bool = False @classmethod def extract_from_cli_options(cls, cli_options: dict[str, Any]) -> Self: # This is expected to always be called from a click entry point, so all options should be # present in the dictionary. We rely on `@record` for type-checking. return cls( empty_workspace=cli_options.pop("empty_workspace", False), workspace=cli_options.pop("workspace", None), python_file=cli_options.pop("python_file", None), module_name=cli_options.pop("module_name", None), package_name=cli_options.pop("package_name", None), working_directory=cli_options.pop("working_directory", None), attribute=cli_options.pop("attribute", None), autoload_defs_module_name=cli_options.pop("autoload_defs_module_name", None), grpc_port=cli_options.pop("grpc_port", None), grpc_socket=cli_options.pop("grpc_socket", None), grpc_host=cli_options.pop("grpc_host", None), use_ssl=cli_options.pop("use_ssl", False), ) def specifies_target(self) -> bool: set_args = [ k for k, v in as_dict(self).items() if v and (k not in {"empty_workspace", "use_ssl"}) ] return bool(set_args) @record
WorkspaceOpts
python
rapidsai__cudf
python/cudf/cudf/core/mixins/getitem.py
{ "start": 141, "end": 2030 }
class ____: """This mixin changes `__getattr__` to attempt a `__getitem__` call. Classes that include this mixin gain enhanced functionality for the behavior of attribute access like `obj.foo`: if `foo` is not an attribute of `obj`, obj['foo'] will be attempted, and the result returned. To make this behavior safe, classes that include this mixin must define a class attribute `_PROTECTED_KEYS` that defines the attributes that are accessed within `__getitem__`. For example, if `__getitem__` is defined as `return self._data[key]`, we must define `_PROTECTED_KEYS={'_data'}`. """ # Tracking of protected keys by each subclass is necessary to make the # `__getattr__`->`__getitem__` call safe. See # https://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html # for an explanation. In brief, defining the `_PROTECTED_KEYS` allows this # class to avoid calling `__getitem__` inside `__getattr__` when # `__getitem__` will internally again call `__getattr__`, resulting in an # infinite recursion. # This problem only arises when the copy protocol is invoked (e.g. by # `copy.copy` or `pickle.dumps`), and could also be avoided by redefining # methods involved with the copy protocol such as `__reduce__` or # `__setstate__`, but this class may be used in complex multiple # inheritance hierarchies that might also override serialization. The # solution here is a minimally invasive change that avoids such conflicts. _PROTECTED_KEYS: frozenset[str] | set[str] = frozenset() def __getattr__(self, key): if key in self._PROTECTED_KEYS: raise AttributeError try: return self[key] except KeyError: raise AttributeError( f"{type(self).__name__} object has no attribute {key}" )
GetAttrGetItemMixin
python
coleifer__peewee
playhouse/sqlite_udf.py
{ "start": 6999, "end": 7248 }
class ____(object): def __init__(self): self.heap = [] self.ct = 0 def process(self, value): return value def step(self, value): self.ct += 1 heapq.heappush(self.heap, self.process(value))
_heap_agg
python
tornadoweb__tornado
tornado/template.py
{ "start": 18119, "end": 18871 }
class ____(BaseLoader): """A template loader that loads from a dictionary.""" def __init__(self, dict: Dict[str, str], **kwargs: Any) -> None: super().__init__(**kwargs) self.dict = dict def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str: if ( parent_path and not parent_path.startswith("<") and not parent_path.startswith("/") and not name.startswith("/") ): file_dir = posixpath.dirname(parent_path) name = posixpath.normpath(posixpath.join(file_dir, name)) return name def _create_template(self, name: str) -> Template: return Template(self.dict[name], name=name, loader=self)
DictLoader
python
pytorch__pytorch
torch/_inductor/codegen/cpp.py
{ "start": 225765, "end": 229420 }
class ____: var: Optional[sympy.Expr] = None size: Optional[sympy.Expr] = None offset: sympy.Expr = sympy.S.Zero # Note [tiled_size] # We may do loop-tiling at this loop level. # When var is in [offset, tiled_size), we will perform the vectorization kernel. # When var is in [tiled_size, size), we will perform the scalar or masked vectorization kernel. # for (var = offset; var < size; var += steps) { # if (var >= offset && var < tiled_size) vec_loop_body(); # if (var >= tiled_size && var < size) scalar_or_maskvec_loop_body(); # } tiled_size: sympy.Expr = sympy.S.Zero steps: sympy.Expr = sympy.S.One parallel: int = 0 simd_omp: bool = False simd_vec: bool = False collapsed: bool = False is_reduction: bool = False def __post_init__(self): # Regarding the C++/OpenMP backend, `cpu_vec_isa.pick_vec_isa()` to check # vectorization ISA is a time-consuming and one-shot operation. It leads # to taking a longer time to import `codegen.cpp` package because the # `LoopLevel` of the package is decorated by `@dataclasses.dataclass` while # the decorator will invoke `cpu_vec_isa.pick_vec_isa()` to initialize the # `simd_nelements` of the `LoopLevel`. It might introduce additional compilation # overhead to the Triton backend. Therefore, we moved the `simd_nelements` to # `__post_init__` picked_vec_isa: cpu_vec_isa.VecISA = cpu_vec_isa.pick_vec_isa() self.simd_nelements: int = picked_vec_isa.nelements() if picked_vec_isa else 0 def tile(self, factor): sympy_factor = sympy.Integer(factor) loop = LoopLevel(self.var, self.size) loop.steps = sympy_factor loop.simd_vec = True loop.tiled_size = FloorDiv(loop.size, sympy_factor) * sympy_factor loop.parallel = self.parallel loop.collapsed = False loop.is_reduction = self.is_reduction return loop def lines(self): offset_expr = cexpr_index(self.offset) size_expr = cexpr_index(self.size) if config.cpp.no_redundant_loops and offset_expr == size_expr: return None simd = ( f"simd simdlen({self.simd_nelements}) " if self.simd_omp and self.simd_nelements > 1 else "" ) if self.parallel: # TODO(jansel): look into chunk size and other schedules line1 = "#pragma omp for" if self.parallel > 1: line1 += f" collapse({self.parallel})" if self.simd_omp: line1 = line1.replace(" for ", f" for {simd}") elif self.simd_vec: line1 = "" elif self.simd_omp: line1 = f"#pragma omp {simd}" elif not self.is_reduction and cpp_builder.is_gcc(): line1 = "#pragma GCC ivdep" else: line1 = "" offset_str = f"{INDEX_TYPE} {self.var}={offset_expr}" size_str = f"{self.var}<{size_expr}" if self.steps.is_number: steps_str = f"{self.var}+={cexpr_index(self.steps)}" else: # If the step size is 0, change it to 1 because a step size of 0 # will cause floating point exception (core dump) during parallelization. steps_str = ( f"{self.var}+=({cexpr_index(self.steps)} == 0 ? " f"1 : {cexpr_index(self.steps)})" ) line2 = f"for({offset_str}; {size_str}; {steps_str})" if self.collapsed or not line1: return [line2] return [line1, line2] @dataclasses.dataclass
LoopLevel
python
huggingface__transformers
src/transformers/models/data2vec/modular_data2vec_audio.py
{ "start": 8940, "end": 9036 }
class ____(Wav2Vec2ForAudioFrameClassification): pass
Data2VecAudioForAudioFrameClassification
python
kamyu104__LeetCode-Solutions
Python/serialize-and-deserialize-n-ary-tree.py
{ "start": 146, "end": 1514 }
class ____(object): def serialize(self, root): """Encodes a tree to a single string. :type root: Node :rtype: str """ def dfs(node, vals): if not node: return vals.append(str(node.val)) for child in node.children: dfs(child, vals) vals.append("#") vals = [] dfs(root, vals) return " ".join(vals) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: Node """ def isplit(source, sep): sepsize = len(sep) start = 0 while True: idx = source.find(sep, start) if idx == -1: yield source[start:] return yield source[start:idx] start = idx + sepsize def dfs(vals): val = next(vals) if val == "#": return None root = Node(int(val), []) child = dfs(vals) while child: root.children.append(child) child = dfs(vals) return root if not data: return None return dfs(iter(isplit(data, ' ')))
Codec
python
doocs__leetcode
solution/0900-0999/0926.Flip String to Monotone Increasing/Solution.py
{ "start": 0, "end": 253 }
class ____: def minFlipsMonoIncr(self, s: str) -> int: tot = s.count("0") ans, cur = tot, 0 for i, c in enumerate(s, 1): cur += int(c == "0") ans = min(ans, i - cur + tot - cur) return ans
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-genesys/source_genesys/source.py
{ "start": 5684, "end": 5885 }
class ____(GenesysStream): """ API Docs: https://developer.genesys.cloud/useragentman/users/ """ primary_key = "id" def path(self, **kwargs) -> str: return "users"
UserUsers
python
pytorch__pytorch
torch/distributed/fsdp/_fully_shard/_fsdp_api.py
{ "start": 2492, "end": 3761 }
class ____(ABC): """ Interface for communication primitives. A primitive primarily needs to handle 3 tasks, namely: 1. How to allocate memory for communication Depending on the goal, an implementation can choose to: a. associate each call to a temporary buffer (best for flexibility and simplicity) b. reuse an persistent buffer for efficiency reasons 2. Where to allocate memory (e.g. NCCL mem pool or regular cuda caching allocator) 3. What to do/call upon the comm is called (see `AllGather` interface as an example) """ @abstractmethod def allocate( self, size: Sequence[Union[int, torch.SymInt]], *, dtype: torch.dtype, device: torch.device, ) -> torch.Tensor: """ This handles the "how to allocate memory" part. A default implementation could be simply: .. code-block:: python with self.mem_pool: torch.empty(...) Args: size (Sequence[Union[int, torch.SymInt]]): size of the tensor buffer dtype (torch.dtype): dtype of the tensor buffer device (torch.device): which device to allocate the tensor onto """ ...
Comm
python
doocs__leetcode
lcci/01.03.String to URL/Solution.py
{ "start": 0, "end": 119 }
class ____: def replaceSpaces(self, S: str, length: int) -> str: return S[:length].replace(' ', '%20')
Solution
python
ipython__ipython
IPython/terminal/shortcuts/__init__.py
{ "start": 1177, "end": 1247 }
class ____(BaseBinding): filter: Condition @dataclass
RuntimeBinding
python
walkccc__LeetCode
solutions/3541. Find Most Frequent Vowel and Consonant/3541.py
{ "start": 0, "end": 298 }
class ____: def maxFreqSum(self, s: str) -> int: VOWELS = 'aeiou' count = collections.Counter(s) maxVowel = max((count[c] for c in VOWELS if c in count), default=0) maxConsonant = max((count[c] for c in count if c not in VOWELS), default=0) return maxVowel + maxConsonant
Solution
python
facebook__pyre-check
tools/upgrade/commands/strict_default.py
{ "start": 1518, "end": 6341 }
class ____(ErrorSuppressingCommand): def __init__( self, command_arguments: CommandArguments, *, repository: Repository, local_configuration: Path, remove_strict_headers: bool, fixme_threshold: int, remove_unsafe_headers: bool, remove_strict_flag: bool, paths: List[str] | None, ) -> None: super().__init__(command_arguments, repository) self._local_configuration: Path = local_configuration self._remove_strict_headers: bool = remove_strict_headers self._fixme_threshold: int = fixme_threshold self._remove_unsafe_headers: bool = remove_unsafe_headers self._remove_strict_flag: bool = remove_strict_flag self._paths: List[str] | None = paths @staticmethod def from_arguments( arguments: argparse.Namespace, repository: Repository ) -> "StrictDefault": command_arguments = CommandArguments.from_arguments(arguments) return StrictDefault( command_arguments, repository=repository, local_configuration=arguments.local_configuration, remove_strict_headers=arguments.remove_strict_headers, fixme_threshold=arguments.fixme_threshold, remove_unsafe_headers=arguments.remove_unsafe_headers, remove_strict_flag=arguments.remove_strict_flag, paths=arguments.paths, ) @classmethod def add_arguments(cls, parser: argparse.ArgumentParser) -> None: super(StrictDefault, cls).add_arguments(parser) parser.set_defaults(command=cls.from_arguments) parser.add_argument( "-l", "--local-configuration", type=path_exists, help="Path to project root with local configuration", ) parser.add_argument( "--remove-strict-headers", action="store_true", help="Delete unnecessary `# pyre-strict` headers.", ) parser.add_argument( "--fixme-threshold", type=int, default=None, help="Mark file as unsafe if fixme count exceeds threshold.", ) parser.add_argument( "--remove-unsafe-headers", action="store_true", help="Remove `# pyre-unsafe` headers and replace with `# pyre-fixmes` if the number of new suppressions is under the given fixme threshold", ) parser.add_argument( "--remove-strict-flag", action="store_true", help="Remove the strict flag completely. Useful for repositories where configurations are strict by default.", ) parser.add_argument( "--paths", default=None, nargs="+", help="Paths to convert to strict default. Defaults to all paths in the current directory.", ) def _commit_changes(self) -> None: title = f"Convert {self._local_configuration} to use strict default" summary = ( "Turning on strict default; files with more than " + f"{self._fixme_threshold} errors opted-out of strict." ) self._repository.commit_changes( commit=(not self._no_commit), title=title, summary=summary, set_dependencies=False, ) @override def run(self) -> None: configuration_path = _get_configuration_path(self._local_configuration) if configuration_path is None: raise UserError("Cannot find a path to configuration") configuration = Configuration(configuration_path) LOG.info("Processing %s", configuration.get_directory()) if self._remove_strict_flag: configuration.use_strict_default() else: configuration.add_strict() configuration.write() argument_paths = self._paths if argument_paths is None or len(argument_paths) == 0: source_paths = configuration.get_source_paths() else: LOG.info("Running on specific paths: %s", ", ".join(argument_paths)) source_paths = (Path(path) for path in argument_paths) modes = [ *([LocalMode.STRICT] if self._remove_strict_headers else []), *([LocalMode.UNSAFE] if self._remove_unsafe_headers else []), ] if self._remove_strict_headers or self._remove_unsafe_headers: for path in source_paths: remove_local_mode(path, modes) self._get_and_suppress_errors( configuration, error_source=ErrorSource.GENERATE, fixme_threshold=self._fixme_threshold, fixme_threshold_fallback_mode=LocalMode.UNSAFE, ) self._commit_changes()
StrictDefault
python
walkccc__LeetCode
solutions/1717. Maximum Score From Removing Substrings/1717.py
{ "start": 0, "end": 1207 }
class ____: def maximumGain(self, s: str, x: int, y: int) -> int: # The assumption that gain('ab') > gain('ba') while removing 'ba' first is # optimal is contradicted. Only 'b(ab)a' satisfies the condition of # preventing two 'ba' removals, but after removing 'ab', we can still # remove one 'ba', resulting in a higher gain. Thus, removing 'ba' first is # not optimal. return (self._gain(s, 'ab', x, 'ba', y) if x > y else self._gain(s, 'ba', y, 'ab', x)) # Returns the points gained by first removing sub1 ('ab' | 'ba') from s with # point1, then removing sub2 ('ab' | 'ba') from s with point2. def _gain(self, s: str, sub1: str, point1: int, sub2: str, point2: int) -> int: points = 0 stack1 = [] stack2 = [] # Remove 'sub1' from s with point1 gain. for c in s: if stack1 and stack1[-1] == sub1[0] and c == sub1[1]: stack1.pop() points += point1 else: stack1.append(c) # Remove 'sub2' from s with point2 gain. for c in stack1: if stack2 and stack2[-1] == sub2[0] and c == sub2[1]: stack2.pop() points += point2 else: stack2.append(c) return points
Solution
python
getsentry__sentry
src/sentry/workflow_engine/handlers/detector/base.py
{ "start": 2643, "end": 2971 }
class ____: result: dict[DetectorGroupKey, DetectorEvaluationResult] tainted: bool # TODO - @saponifi3d - Change this class to be a pure ABC and remove the `__init__` method. # TODO - @saponifi3d - Once the change is made, we should introduce a `BaseDetector` class to evaluate simple cases
GroupedDetectorEvaluationResult
python
django__django
tests/utils_tests/test_regex_helper.py
{ "start": 1620, "end": 2004 }
class ____(SimpleTestCase): def test_flags_with_pre_compiled_regex(self): test_pattern = re.compile("test") lazy_test_pattern = regex_helper._lazy_re_compile(test_pattern, re.I) msg = "flags must be empty if regex is passed pre-compiled" with self.assertRaisesMessage(AssertionError, msg): lazy_test_pattern.match("TEST")
LazyReCompileTests
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint_management_test.py
{ "start": 10892, "end": 13441 }
class ____(test.TestCase): def setUp(self): self._base_dir = os.path.join(self.get_temp_dir(), "saver_utils_test") gfile.MakeDirs(self._base_dir) def tearDown(self): gfile.DeleteRecursively(self._base_dir) @test_util.run_deprecated_v1 def testCheckpointExists(self): for sharded in (False, True): for version in (saver_pb2.SaverDef.V2, saver_pb2.SaverDef.V1): with self.session(graph=ops_lib.Graph()) as sess: unused_v = variables.Variable(1.0, name="v") self.evaluate(variables.global_variables_initializer()) saver = saver_module.Saver(sharded=sharded, write_version=version) path = os.path.join(self._base_dir, "%s-%s" % (sharded, version)) self.assertFalse( checkpoint_management.checkpoint_exists(path)) # Not saved yet. ckpt_prefix = saver.save(sess, path) self.assertTrue(checkpoint_management.checkpoint_exists(ckpt_prefix)) ckpt_prefix = checkpoint_management.latest_checkpoint(self._base_dir) self.assertTrue(checkpoint_management.checkpoint_exists(ckpt_prefix)) @test_util.run_deprecated_v1 def testGetCheckpointMtimes(self): prefixes = [] for version in (saver_pb2.SaverDef.V2, saver_pb2.SaverDef.V1): with self.session(graph=ops_lib.Graph()) as sess: unused_v = variables.Variable(1.0, name="v") self.evaluate(variables.global_variables_initializer()) saver = saver_module.Saver(write_version=version) prefixes.append( saver.save(sess, os.path.join(self._base_dir, str(version)))) mtimes = checkpoint_management.get_checkpoint_mtimes(prefixes) self.assertEqual(2, len(mtimes)) self.assertTrue(mtimes[1] >= mtimes[0]) @test_util.run_deprecated_v1 def testRemoveCheckpoint(self): for sharded in (False, True): for version in (saver_pb2.SaverDef.V2, saver_pb2.SaverDef.V1): with self.session(graph=ops_lib.Graph()) as sess: unused_v = variables.Variable(1.0, name="v") self.evaluate(variables.global_variables_initializer()) saver = saver_module.Saver(sharded=sharded, write_version=version) path = os.path.join(self._base_dir, "%s-%s" % (sharded, version)) ckpt_prefix = saver.save(sess, path) self.assertTrue(checkpoint_management.checkpoint_exists(ckpt_prefix)) checkpoint_management.remove_checkpoint(ckpt_prefix, version) self.assertFalse(checkpoint_management.checkpoint_exists(ckpt_prefix))
SaverUtilsTest
python
google__pytype
pytype/pytd/pytd.py
{ "start": 11512, "end": 11832 }
class ____(TypeParameter): """ParamSpec is a specific case of TypeParameter.""" def Get(self, attr): if attr == 'args': return ParamSpecArgs(self.name) elif attr == 'kwargs': return ParamSpecKwargs(self.name) else: # TODO(b/217789659): This should be an error return None
ParamSpec
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 152493, "end": 156390 }
class ____(Response): """ Response of models.update_for_task endpoint. :param id: ID of the model :type id: str :param created: Was the model created :type created: bool :param updated: Number of models updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "models" _action = "update_for_task" _version = "2.23" _schema = { "definitions": {}, "properties": { "created": { "description": "Was the model created", "type": ["boolean", "null"], }, "fields": { "additionalProperties": True, "description": "Updated fields names and values", "type": ["object", "null"], }, "id": {"description": "ID of the model", "type": ["string", "null"]}, "updated": { "description": "Number of models updated (0 or 1)", "type": ["integer", "null"], }, }, "type": "object", } def __init__( self, id: Optional[str] = None, created: Optional[bool] = None, updated: Optional[int] = None, fields: Optional[dict] = None, **kwargs: Any ) -> None: super(UpdateForTaskResponse, self).__init__(**kwargs) self.id = id self.created = created self.updated = updated self.fields = fields @schema_property("id") def id(self) -> Optional[str]: return self._property_id @id.setter def id(self, value: Optional[str]) -> None: if value is None: self._property_id = None return self.assert_isinstance(value, "id", six.string_types) self._property_id = value @schema_property("created") def created(self) -> Optional[bool]: return self._property_created @created.setter def created(self, value: Optional[bool]) -> None: if value is None: self._property_created = None return self.assert_isinstance(value, "created", (bool,)) self._property_created = value @schema_property("updated") def updated(self) -> Optional[int]: return self._property_updated @updated.setter def updated(self, value: Optional[int]) -> None: if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value @schema_property("fields") def fields(self) -> Optional[dict]: return self._property_fields @fields.setter def fields(self, value: Optional[dict]) -> None: if value is None: self._property_fields = None return self.assert_isinstance(value, "fields", (dict,)) self._property_fields = value response_mapping = { GetByIdRequest: GetByIdResponse, GetByTaskIdRequest: GetByTaskIdResponse, GetAllRequest: GetAllResponse, GetFrameworksRequest: GetFrameworksResponse, UpdateForTaskRequest: UpdateForTaskResponse, CreateRequest: CreateResponse, EditRequest: EditResponse, UpdateRequest: UpdateResponse, PublishManyRequest: PublishManyResponse, SetReadyRequest: SetReadyResponse, ArchiveManyRequest: ArchiveManyResponse, UnarchiveManyRequest: UnarchiveManyResponse, DeleteManyRequest: DeleteManyResponse, DeleteRequest: DeleteResponse, MakePublicRequest: MakePublicResponse, MakePrivateRequest: MakePrivateResponse, MoveRequest: MoveResponse, AddOrUpdateMetadataRequest: AddOrUpdateMetadataResponse, DeleteMetadataRequest: DeleteMetadataResponse, }
UpdateForTaskResponse
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 168537, "end": 168748 }
class ____(RecvmsgIntoMixin, RFC3542AncillaryTest, SendrecvmsgUDPLITE6TestBase): pass
RecvmsgIntoRFC3542AncillaryUDPLITE6Test
python
google__jax
jax/_src/pallas/utils.py
{ "start": 14471, "end": 14991 }
class ____: mesh_shape: tuple[int, ...] axis_names: tuple[str, ...] mesh_strides: tuple[int, ...] @staticmethod def from_mesh(mesh: Any) -> MeshInfo: # We need mesh <-> logical translation tables. Since the logical IDs are # just linearized versions of the mesh IDs, we create those tables. mesh_strides = strides_from_shape(tuple( mesh.shape[a] for a in mesh.axis_names )) mesh_shape = tuple(mesh.shape.values()) return MeshInfo(mesh_shape, mesh.axis_names, mesh_strides)
MeshInfo
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_type_annotation.py
{ "start": 937, "end": 1103 }
class ____: ... def test5_taint_1(x) -> Test5_T1: pass def test5_taint_2(x) -> Test5_T2: pass def test5_no_taint_1(x) -> Test5_Foo: pass
Test5_Foo
python
huggingface__transformers
src/transformers/pipelines/zero_shot_classification.py
{ "start": 254, "end": 1570 }
class ____(ArgumentHandler): """ Handles arguments for zero-shot for text classification by turning each possible label into an NLI premise/hypothesis pair. """ def _parse_labels(self, labels): if isinstance(labels, str): labels = [label.strip() for label in labels.split(",") if label.strip()] return labels def __call__(self, sequences, labels, hypothesis_template): if len(labels) == 0 or len(sequences) == 0: raise ValueError("You must include at least one label and at least one sequence.") if hypothesis_template.format(labels[0]) == hypothesis_template: raise ValueError( f'The provided hypothesis_template "{hypothesis_template}" was not able to be formatted with the target labels. ' "Make sure the passed template includes formatting syntax such as {} where the label should go." ) if isinstance(sequences, str): sequences = [sequences] sequence_pairs = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels]) return sequence_pairs, sequences @add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
ZeroShotClassificationArgumentHandler
python
Pylons__pyramid
src/pyramid/exceptions.py
{ "start": 3844, "end": 4352 }
class ____(Exception): """The exception raised when the Pyramid topological sorter detects a cyclic dependency.""" def __init__(self, cycles): self.cycles = cycles def __str__(self): L = [] cycles = self.cycles for cycle in cycles: dependent = cycle dependees = cycles[cycle] L.append(f'{dependent!r} sorts before {dependees!r}') msg = 'Implicit ordering cycle:' + '; '.join(L) return msg
CyclicDependencyError
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 357617, "end": 358204 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("IssueEdge"), graphql_name="edges") nodes = sgqlc.types.Field(sgqlc.types.list_of("Issue"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
IssueConnection
python
kamyu104__LeetCode-Solutions
Python/baseball-game.py
{ "start": 29, "end": 505 }
class ____(object): def calPoints(self, ops): """ :type ops: List[str] :rtype: int """ history = [] for op in ops: if op == '+': history.append(history[-1] + history[-2]) elif op == 'D': history.append(history[-1] * 2) elif op == 'C': history.pop() else: history.append(int(op)) return sum(history)
Solution
python
huggingface__transformers
tests/quantization/autoawq/test_awq.py
{ "start": 11772, "end": 22450 }
class ____(unittest.TestCase): model_name = "TheBloke/Mistral-7B-OpenOrca-AWQ" model_revision = "7048b2af77d0dd1c81b000b19d73f9cc8950b510" custom_mapping_model_id = "TheBloke/Mistral-7B-v0.1-AWQ" custom_model_revision = "f186bcfa9edbe2a4334262ec1e67f23e53ed1ae7" mixtral_model_name = "casperhansen/mixtral-instruct-awq" mixtral_model_revision = "87dd4ec502dde74fb3a624835c776b000d190c3b" multi_modal_model_name = "ybelkada/llava-1.5-7b-hf-awq" multi_modal_model_code_revision = "ad108a50f5b9e681bdd7378409f57b7fa59a7442" awq_rope_model_name = "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4" awq_rope_model_revision = "db1f81ad4b8c7e39777509fac66c652eb0a52f91" prompt = ( "You're standing on the surface of the Earth. " "You walk one mile south, one mile west and one mile north. " "You end up exactly where you started. Where are you?" ) EXPECTED_GENERATION = prompt + "\n\nYou're at the center of a square." EXPECTED_GENERATION_CUSTOM_MODEL = "Hello,\n\nI have a problem with my 20" EXPECTED_GENERATION_MIXTRAL = prompt + " You're on the North Pole.\n\nThe" EXPECTED_GENERATION_AWQ_ROPE = prompt + " [Note: You can't be in a city, and" def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def _check_fused_modules(self, model): has_fused_modules = False fused_modules_name = ["QuantAttentionFused", "QuantFusedMLP", "FasterTransformerRMSNorm"] for _, module in model.named_modules(): if module.__class__.__name__ in fused_modules_name: has_fused_modules = True break self.assertTrue(has_fused_modules, "Modules fusing not performed correctly!") def test_raise_save_pretrained(self): """ Test that `save_pretrained` is effectively blocked for fused models """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.model_name, quantization_config=quantization_config, revision=self.model_revision, ).to(torch_device) self._check_fused_modules(model) with self.assertRaises(ValueError), tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) def test_fused_modules_to_not_convert(self): """ Test if fused + modules to_not_convert work as expected """ model_id = "hf-internal-testing/Mixtral-tiny-AWQ" quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( model_id, quantization_config=quantization_config, ).to(torch_device) # Check if model has been correctly fused self._check_fused_modules(model) # Checks if the modules_to_not_convert (here gate layer) is a Linear self.assertTrue(isinstance(model.model.layers[0].block_sparse_moe.gate, torch.nn.Linear)) @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 8, "Skipping because RuntimeError: FlashAttention only supports Ampere GPUs or newer, so not supported on GPU with capability < 8.0", ) @require_flash_attn @require_torch_gpu @pytest.mark.flash_attn_test def test_generation_fused(self): """ Test generation quality for fused models - single batch case """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.model_name, quantization_config=quantization_config, revision=self.model_revision, ).to(torch_device) self._check_fused_modules(model) tokenizer = AutoTokenizer.from_pretrained(self.model_name, revision=self.model_revision) inputs = tokenizer(self.prompt, return_tensors="pt").to(torch_device) outputs = model.generate(**inputs, max_new_tokens=12) self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION) @pytest.mark.flash_attn_test @require_flash_attn @require_torch_gpu @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 8, "Skipping because RuntimeError: FlashAttention only supports Ampere GPUs or newer, so not supported on GPU with capability < 8.0", ) def test_generation_fused_batched(self): """ Test generation quality for fused models - multi batch case """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.model_name, quantization_config=quantization_config, revision=self.model_revision, ).to(torch_device) self._check_fused_modules(model) tokenizer = AutoTokenizer.from_pretrained(self.model_name, revision=self.model_revision) tokenizer.pad_token_id = tokenizer.eos_token_id inputs = tokenizer([self.prompt, self.prompt], return_tensors="pt", padding=True).to(torch_device) outputs = model.generate(**inputs, max_new_tokens=12) self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION) def test_generation_llava_fused(self): from transformers import pipeline quantization_config = AwqConfig(do_fuse=True, fuse_max_seq_len=2048) pipe = pipeline( "image-to-text", model=self.multi_modal_model_name, device=0, model_kwargs={ "quantization_config": quantization_config, }, revision=self.multi_modal_model_code_revision, ) url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png" prompt = "USER: <image>\nCan you please describe this image?\nASSISTANT:" outputs = pipe(url, prompt=prompt, generate_kwargs={"max_new_tokens": 100}) EXPECTED_OUTPUT = "USER: \nCan you please describe this image?\nASSISTANT: The image features a brown and white cat sitting on a green surface, possibly a carpet or a grassy area. The cat is holding a red ball in its paws, seemingly playing with it. The cat appears to be focused on the ball, possibly preparing to play or just enjoying the toy." self.assertEqual(outputs[0]["generated_text"], EXPECTED_OUTPUT) @pytest.mark.flash_attn_test @require_flash_attn @require_torch_multi_gpu @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 8, "Skipping because RuntimeError: FlashAttention only supports Ampere GPUs or newer, so not supported on GPU with capability < 8.0", ) def test_generation_custom_model(self): """ Test generation quality for fused models using custom fused map. """ quantization_config = AwqConfig( bits=4, fuse_max_seq_len=512, modules_to_fuse={ "attention": ["q_proj", "k_proj", "v_proj", "o_proj"], "mlp": ["gate_proj", "up_proj", "down_proj"], "layernorm": ["input_layernorm", "post_attention_layernorm", "norm"], "use_alibi": False, "hidden_size": 4096, "num_attention_heads": 32, "num_key_value_heads": 8, }, ) model = AutoModelForCausalLM.from_pretrained( self.custom_mapping_model_id, quantization_config=quantization_config, device_map="balanced", revision=self.custom_model_revision, ) self._check_fused_modules(model) tokenizer = AutoTokenizer.from_pretrained(self.custom_mapping_model_id, revision=self.custom_model_revision) prompt = "Hello" inputs = tokenizer(prompt, return_tensors="pt").to(torch_device) outputs = model.generate(**inputs, max_new_tokens=12) self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION_CUSTOM_MODEL) @pytest.mark.flash_attn_test @require_flash_attn @require_torch_multi_gpu @unittest.skip(reason="Not enough GPU memory on CI runners") def test_generation_mixtral_fused(self): """ Text generation test for Mixtral + AWQ + fused """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=1024, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.mixtral_model_name, quantization_config=quantization_config, device_map="auto", revision=self.mixtral_model_revision, ) tokenizer = AutoTokenizer.from_pretrained(self.mixtral_model_name) tokenizer.pad_token = tokenizer.eos_token inputs = tokenizer([self.prompt, self.prompt], return_tensors="pt", padding=True).to(torch_device) outputs = model.generate(**inputs, max_new_tokens=12) self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION_MIXTRAL) @pytest.mark.flash_attn_test @require_flash_attn @require_torch_multi_gpu @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 8, "Skipping because RuntimeError: FlashAttention only supports Ampere GPUs or newer, so not supported on GPU with capability < 8.0", ) def test_generation_awq_rope_fused(self): """ Text generation test for AWQ model with special RoPE implementation (e.g. LLaMA3) + fused """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=1024, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.awq_rope_model_name, quantization_config=quantization_config, device_map="auto", revision=self.awq_rope_model_revision, ) tokenizer = AutoTokenizer.from_pretrained(self.awq_rope_model_name) tokenizer.pad_token = tokenizer.eos_token inputs = tokenizer([self.prompt, self.prompt], return_tensors="pt", padding=True).to(torch_device) outputs = model.generate(**inputs, max_new_tokens=12, do_sample=False) self.assertEqual(tokenizer.decode(outputs[0], skip_special_tokens=True), self.EXPECTED_GENERATION_AWQ_ROPE) @slow @require_torch_accelerator @require_auto_awq @require_accelerate
AwqFusedTest
python
has2k1__plotnine
plotnine/stats/stat_bin.py
{ "start": 332, "end": 4623 }
class ____(stat): """ Count cases in each interval {usage} Parameters ---------- {common_parameters} binwidth : float, default=None The width of the bins. The default is to use bins bins that cover the range of the data. You should always override this value, exploring multiple widths to find the best to illustrate the stories in your data. bins : int, default=None Number of bins. Overridden by binwidth. If `None`{.py}, a number is computed using the freedman-diaconis method. breaks : array_like, default=None Bin boundaries. This supersedes the `binwidth`, `bins`, `center` and `boundary`. center : float, default=None The center of one of the bins. Note that if center is above or below the range of the data, things will be shifted by an appropriate number of widths. To center on integers, for example, use `width=1`{.py} and `center=0`{.py}, even if 0 i s outside the range of the data. At most one of center and boundary may be specified. boundary : float, default=None A boundary between two bins. As with center, things are shifted when boundary is outside the range of the data. For example, to center on integers, use `width=1`{.py} and `boundary=0.5`{.py}, even if 1 is outside the range of the data. At most one of center and boundary may be specified. closed : Literal["left", "right"], default="right" Which edge of the bins is included. pad : bool, default=False If `True`{.py}, adds empty bins at either side of x. This ensures that frequency polygons touch 0. See Also -------- plotnine.histogram : The default `geom` for this `stat`. """ _aesthetics_doc = """ {aesthetics_table} **Options for computed aesthetics** ```python "count" # number of points in bin "density" # density of points in bin, scaled to integrate to 1 "ncount" # count, scaled to maximum of 1 "ndensity" # density, scaled to maximum of 1 "ngroup" # number of points in group ``` """ REQUIRED_AES = {"x"} DEFAULT_PARAMS = { "geom": "histogram", "position": "stack", "na_rm": False, "binwidth": None, "bins": None, "breaks": None, "center": None, "boundary": None, "closed": "right", "pad": False, } DEFAULT_AES = {"y": after_stat("count"), "weight": None} CREATES = {"width", "count", "density", "ncount", "ndensity", "ngroup"} def setup_params(self, data): params = self.params if "y" in data or "y" in params: msg = "stat_bin() must not be used with a y aesthetic." raise PlotnineError(msg) if params["closed"] not in ("right", "left"): raise PlotnineError("`closed` should either 'right' or 'left'") if ( params["breaks"] is None and params["binwidth"] is None and params["bins"] is None ): params["bins"] = freedman_diaconis_bins(data["x"]) msg = ( "'stat_bin()' using 'bins = {}'. " "Pick better value with 'binwidth'." ) warn(msg.format(params["bins"]), PlotnineWarning) def compute_group(self, data, scales): params = self.params if params["breaks"] is not None: breaks = np.asarray(params["breaks"]) if hasattr(scales.x, "transform"): breaks = scales.x.transform(breaks) elif params["binwidth"] is not None: breaks = breaks_from_binwidth( scales.x.dimension(), params["binwidth"], params["center"], params["boundary"], ) else: breaks = breaks_from_bins( scales.x.dimension(), params["bins"], params["center"], params["boundary"], ) new_data = assign_bins( data["x"], breaks, data.get("weight"), params["pad"], params["closed"], ) return new_data
stat_bin
python
huggingface__transformers
src/transformers/models/glpn/modeling_glpn.py
{ "start": 21885, "end": 22845 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config channels = config.decoder_hidden_size self.head = nn.Sequential( nn.Conv2d(channels, channels, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=False), nn.Conv2d(channels, 1, kernel_size=3, stride=1, padding=1), ) def forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor: # use last features of the decoder hidden_states = hidden_states[self.config.head_in_index] hidden_states = self.head(hidden_states) predicted_depth = torch.sigmoid(hidden_states) * self.config.max_depth predicted_depth = predicted_depth.squeeze(dim=1) return predicted_depth @auto_docstring( custom_intro=""" GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2. """ )
GLPNDepthEstimationHead
python
scrapy__scrapy
tests/test_item.py
{ "start": 7159, "end": 7908 }
class ____: def test_new_method_propagates_classcell(self): new_mock = mock.Mock(side_effect=ABCMeta.__new__) base = ItemMeta.__bases__[0] with mock.patch.object(base, "__new__", new_mock): class MyItem(Item): def f(self): # For rationale of this see: # https://github.com/python/cpython/blob/ee1a81b77444c6715cbe610e951c655b6adab88b/Lib/test/test_super.py#L222 return __class__ MyItem() (first_call, second_call) = new_mock.call_args_list[-2:] *_, attrs = first_call[0] assert "__classcell__" not in attrs *_, attrs = second_call[0] assert "__classcell__" in attrs
TestItemMeta
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassSlots1.py
{ "start": 651, "end": 748 }
class ____: __slots__ = ("y", "x") x: int y: str D(1, "bar") @dataclass(slots=True)
D
python
plotly__plotly.py
plotly/graph_objs/surface/_legendgrouptitle.py
{ "start": 233, "end": 2939 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "surface" _path_str = "surface.legendgrouptitle" _valid_props = {"font", "text"} @property def font(self): """ Sets this legend group's title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.surface.legendgrouptitle.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.surface.legendgrouptitle.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def text(self): """ Sets the title of the legend group. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this legend group's title font. text Sets the title of the legend group. """ def __init__(self, arg=None, font=None, text=None, **kwargs): """ Construct a new Legendgrouptitle object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.surface.Legendgrouptitle` font Sets this legend group's title font. text Sets the title of the legend group. Returns ------- Legendgrouptitle """ super().__init__("legendgrouptitle") 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.surface.Legendgrouptitle constructor must be a dict or an instance of :class:`plotly.graph_objs.surface.Legendgrouptitle`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Legendgrouptitle
python
google__jax
jax/_src/ad_util.py
{ "start": 2934, "end": 4589 }
class ____: def __init__(self, aval: core.AbstractValue) -> None: self.aval = aval def __repr__(self) -> str: return self.__class__.__name__ # TODO(mattjj,frostig): this forwards attr lookup to self.aval delegate; # should dedup with core.Tracer.__getattr__ which does the same thing def __getattr__(self, name): # if the aval property raises an AttributeError, gets caught here try: attr = getattr(self.aval, name) except KeyError as err: raise AttributeError( f"{self.__class__.__name__} has no attribute {name}" ) from err else: t = type(attr) if t is core.aval_property: return attr.fget(self) elif t is core.aval_method: return types.MethodType(attr.fun, self) else: return attr @staticmethod def from_primal_value(val: Any) -> SymbolicZero: return SymbolicZero(get_aval(val).to_tangent_aval()) def zero_from_primal(val, symbolic_zeros=False): def f(x): tangent_aval = get_aval(x).to_tangent_aval() if symbolic_zeros: return SymbolicZero(tangent_aval) else: return zeros_like_aval(tangent_aval) return tree_map(f, val) JaxTypeOrTracer = Any def replace_internal_symbolic_zeros( x: JaxTypeOrTracer | Zero) -> JaxTypeOrTracer | SymbolicZero: return SymbolicZero(x.aval) if type(x) is Zero else x def replace_rule_output_symbolic_zeros( x: JaxTypeOrTracer | SymbolicZero) -> JaxTypeOrTracer | Zero: return Zero(x.aval) if type(x) is SymbolicZero else x # TODO(mattjj): remove these after fixing downstream users relying on them zeros_like_p: Primitive = Primitive('zeros_like')
SymbolicZero
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints-frameworks-v2/quickstart/main.py
{ "start": 1013, "end": 1423 }
class ____(messages.Message): """Collection of Greetings.""" items = messages.MessageField(Greeting, 1, repeated=True) STORED_GREETINGS = GreetingCollection( items=[ Greeting(message="hello world!"), Greeting(message="goodbye world!"), ] ) # [END endpoints_greeting_api_messages] # [START endpoints_greeting_api] @endpoints.api(name="greeting", version="v1")
GreetingCollection