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 | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 6835,
"end": 7664
} | class ____(Token):
""" Represents an implied do loop in Fortran.
Examples
========
>>> from sympy import Symbol, fcode
>>> from sympy.codegen.fnodes import ImpliedDoLoop, ArrayConstructor
>>> i = Symbol('i', integer=True)
>>> idl = ImpliedDoLoop(i**3, i, -3, 3, 2) # -27, -1, 1, 27
>>> ac = ArrayConstructor([-28, idl, 28]) # -28, -27, -1, 1, 27, 28
>>> fcode(ac, standard=2003, source_format='free')
'[-28, (i**3, i = -3, 3, 2), 28]'
"""
__slots__ = _fields = ('expr', 'counter', 'first', 'last', 'step')
defaults = {'step': Integer(1)}
_construct_expr = staticmethod(sympify)
_construct_counter = staticmethod(sympify)
_construct_first = staticmethod(sympify)
_construct_last = staticmethod(sympify)
_construct_step = staticmethod(sympify)
| ImpliedDoLoop |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 13693,
"end": 14019
} | class ____:
def test_phone_number(self, faker, num_samples):
pattern: Pattern = re.compile(r"0(?:55|66|77)\d \d{3} \d{3}")
for _ in range(num_samples):
phone_number = faker.phone_number()
assert isinstance(phone_number, str)
assert pattern.fullmatch(phone_number)
| TestFrDz |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 97393,
"end": 101266
} | class ____(Request):
"""
Scroll through task events, sorted by timestamp
:param task: Task ID
:type task: str
:param order: 'asc' (default) or 'desc'.
:type order: str
:param scroll_id: Pass this value on next call to get next page
:type scroll_id: str
:param batch_size: Number of events to return each time (default 500)
:type batch_size: int
:param event_type: Return only events of this type
:type event_type: str
"""
_service = "events"
_action = "get_task_events"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"batch_size": {
"description": "Number of events to return each time (default 500)",
"type": "integer",
},
"event_type": {
"description": "Return only events of this type",
"type": "string",
},
"order": {
"description": "'asc' (default) or 'desc'.",
"enum": ["asc", "desc"],
"type": "string",
},
"scroll_id": {
"description": "Pass this value on next call to get next page",
"type": "string",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
order: Optional[str] = None,
scroll_id: Optional[str] = None,
batch_size: Optional[int] = None,
event_type: Optional[str] = None,
**kwargs: Any
) -> None:
super(GetTaskEventsRequest, self).__init__(**kwargs)
self.task = task
self.order = order
self.scroll_id = scroll_id
self.batch_size = batch_size
self.event_type = event_type
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("order")
def order(self) -> Optional[str]:
return self._property_order
@order.setter
def order(self, value: Optional[str]) -> None:
if value is None:
self._property_order = None
return
self.assert_isinstance(value, "order", six.string_types)
self._property_order = value
@schema_property("scroll_id")
def scroll_id(self) -> Optional[str]:
return self._property_scroll_id
@scroll_id.setter
def scroll_id(self, value: Optional[str]) -> None:
if value is None:
self._property_scroll_id = None
return
self.assert_isinstance(value, "scroll_id", six.string_types)
self._property_scroll_id = value
@schema_property("batch_size")
def batch_size(self) -> Optional[int]:
return self._property_batch_size
@batch_size.setter
def batch_size(self, value: Optional[int]) -> None:
if value is None:
self._property_batch_size = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "batch_size", six.integer_types)
self._property_batch_size = value
@schema_property("event_type")
def event_type(self) -> Optional[str]:
return self._property_event_type
@event_type.setter
def event_type(self, value: Optional[str]) -> None:
if value is None:
self._property_event_type = None
return
self.assert_isinstance(value, "event_type", six.string_types)
self._property_event_type = value
| GetTaskEventsRequest |
python | ray-project__ray | python/ray/train/_internal/checkpoint_manager.py | {
"start": 1676,
"end": 8074
} | class ____:
"""Checkpoint manager that handles checkpoint book-keeping for a trial.
The main purpose of this abstraction is to keep the top K checkpoints based on
recency/a user-provided metric.
NOTE: This class interacts with `_TrainingResult` objects, which are
(checkpoint, metrics) pairs. This is to order checkpoints by metrics.
Args:
checkpoint_config: Defines how many and which checkpoints to keep.
"""
def __init__(self, checkpoint_config: Optional[CheckpointConfig]):
self._checkpoint_config = checkpoint_config or CheckpointConfig()
# List of checkpoints ordered by ascending score.
self._checkpoint_results: List[_TrainingResult] = []
# The latest registered checkpoint.
# This should never be immediately deleted upon registration,
# even if it's not in the top K checkpoints, based on score.
self._latest_checkpoint_result: Optional[_TrainingResult] = None
if (
self._checkpoint_config.num_to_keep is not None
and self._checkpoint_config.num_to_keep <= 0
):
raise ValueError(
f"`num_to_keep` must >= 1, got: "
f"{self._checkpoint_config.num_to_keep}"
)
@property
def checkpoint_config(self):
return self._checkpoint_config
def register_checkpoint(self, checkpoint_result: _TrainingResult):
"""Register new checkpoint and add to bookkeeping.
This method will register a new checkpoint and add it to the internal
bookkeeping logic. This means the checkpoint manager will decide if
this checkpoint should be kept, and if older or worse performing
checkpoints should be deleted.
Args:
checkpoint: Tracked checkpoint object to add to bookkeeping.
"""
self._latest_checkpoint_result = checkpoint_result
score_attr = self._checkpoint_config.checkpoint_score_attribute
if ray_constants.env_bool(TUNE_ONLY_STORE_CHECKPOINT_SCORE_ATTRIBUTE, False):
metrics = (
{score_attr: checkpoint_result.metrics[score_attr]}
if score_attr in checkpoint_result.metrics
else {}
)
checkpoint_result = _TrainingResult(
checkpoint=checkpoint_result.checkpoint,
metrics=metrics,
)
if score_attr is not None and score_attr in checkpoint_result.metrics:
# If we're ordering by a score, insert the checkpoint
# so that the list remains sorted.
_insert_into_sorted_list(
self._checkpoint_results,
checkpoint_result,
key=self._get_checkpoint_score,
)
else:
# If no metric is provided, just append (ordering by time of registration).
self._checkpoint_results.append(checkpoint_result)
if self._checkpoint_config.num_to_keep is not None:
# Delete the bottom (N - K) checkpoints
worst_results = set(
self._checkpoint_results[: -self._checkpoint_config.num_to_keep]
)
# Except for the latest checkpoint.
results_to_delete = worst_results - {self._latest_checkpoint_result}
# Update internal state before actually deleting them.
self._checkpoint_results = [
checkpoint_result
for checkpoint_result in self._checkpoint_results
if checkpoint_result not in results_to_delete
]
for checkpoint_result in results_to_delete:
checkpoint = checkpoint_result.checkpoint
logger.debug("Deleting checkpoint: ", checkpoint)
_delete_fs_path(fs=checkpoint.filesystem, fs_path=checkpoint.path)
def _get_checkpoint_score(
self, checkpoint: _TrainingResult
) -> Tuple[bool, numbers.Number]:
"""Get the score for a checkpoint, according to checkpoint config.
If `mode="min"`, the metric is negated so that the lowest score is
treated as the best.
Returns:
Tuple: A tuple of (not_is_nan: bool, score: numbers.Number).
This score orders: nan values < float("-inf") < valid numeric metrics
"""
checkpoint_score_attribute = self._checkpoint_config.checkpoint_score_attribute
if checkpoint_score_attribute:
flat_metrics = flatten_dict(checkpoint.metrics)
try:
checkpoint_result = flat_metrics[checkpoint_score_attribute]
except KeyError:
valid_keys = list(flat_metrics.keys())
logger.error(
f"Result dict has no key: {checkpoint_score_attribute}. "
f"checkpoint_score_attr must be set to a key in the "
f"result dict. Valid keys are: {valid_keys}"
)
checkpoint_result = float("-inf")
else:
checkpoint_result = float("-inf")
checkpoint_score_order = self._checkpoint_config.checkpoint_score_order
order_factor = 1.0 if checkpoint_score_order == MAX else -1.0
checkpoint_score = order_factor * checkpoint_result
if not isinstance(checkpoint_score, numbers.Number):
raise ValueError(
f"Unable to persist checkpoint for "
f"checkpoint_score_attribute: "
f"{checkpoint_score_attribute} with value "
f"{checkpoint_score}. "
f"This attribute must be numerical."
)
return (
(not is_nan(checkpoint_score), checkpoint_score)
if not is_nan(checkpoint_score)
else (False, float("-inf"))
)
@property
def best_checkpoint_result(self) -> Optional[_TrainingResult]:
return self._checkpoint_results[-1] if self._checkpoint_results else None
@property
def latest_checkpoint_result(self) -> Optional[_TrainingResult]:
return self._latest_checkpoint_result
@property
def best_checkpoint_results(self) -> List[_TrainingResult]:
if self._checkpoint_config.num_to_keep is None:
return self._checkpoint_results
return self._checkpoint_results[-self._checkpoint_config.num_to_keep :]
| _CheckpointManager |
python | python-openxml__python-docx | src/docx/image/constants.py | {
"start": 2050,
"end": 2161
} | class ____:
"""PNG chunk type names."""
IHDR = "IHDR"
pHYs = "pHYs"
IEND = "IEND"
| PNG_CHUNK_TYPE |
python | django__django | tests/auth_tests/test_models.py | {
"start": 9757,
"end": 13512
} | class ____(TestCase):
def test_email_user(self):
# valid send_mail parameters
kwargs = {
"fail_silently": False,
"auth_user": None,
"auth_password": None,
"connection": None,
"html_message": None,
}
user = User(email="foo@bar.com")
user.email_user(
subject="Subject here",
message="This is a message",
from_email="from@domain.com",
**kwargs,
)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertEqual(message.subject, "Subject here")
self.assertEqual(message.body, "This is a message")
self.assertEqual(message.from_email, "from@domain.com")
self.assertEqual(message.to, [user.email])
def test_last_login_default(self):
user1 = User.objects.create(username="user1")
self.assertIsNone(user1.last_login)
user2 = User.objects.create_user(username="user2")
self.assertIsNone(user2.last_login)
def test_user_clean_normalize_email(self):
user = User(username="user", password="foo", email="foo@BAR.com")
user.clean()
self.assertEqual(user.email, "foo@bar.com")
def test_user_double_save(self):
"""
Calling user.save() twice should trigger password_changed() once.
"""
user = User.objects.create_user(username="user", password="foo")
user.set_password("bar")
with mock.patch(
"django.contrib.auth.password_validation.password_changed"
) as pw_changed:
user.save()
self.assertEqual(pw_changed.call_count, 1)
user.save()
self.assertEqual(pw_changed.call_count, 1)
@override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS)
def test_check_password_upgrade(self):
"""
password_changed() shouldn't be called if User.check_password()
triggers a hash iteration upgrade.
"""
user = User.objects.create_user(username="user", password="foo")
initial_password = user.password
self.assertTrue(user.check_password("foo"))
hasher = get_hasher("default")
self.assertEqual("pbkdf2_sha256", hasher.algorithm)
old_iterations = hasher.iterations
try:
# Upgrade the password iterations
hasher.iterations = old_iterations + 1
with mock.patch(
"django.contrib.auth.password_validation.password_changed"
) as pw_changed:
user.check_password("foo")
self.assertEqual(pw_changed.call_count, 0)
self.assertNotEqual(initial_password, user.password)
finally:
hasher.iterations = old_iterations
@override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS)
async def test_acheck_password_upgrade(self):
user = await User.objects.acreate_user(username="user", password="foo")
initial_password = user.password
self.assertIs(await user.acheck_password("foo"), True)
hasher = get_hasher("default")
self.assertEqual("pbkdf2_sha256", hasher.algorithm)
old_iterations = hasher.iterations
try:
# Upgrade the password iterations.
hasher.iterations = old_iterations + 1
with mock.patch(
"django.contrib.auth.password_validation.password_changed"
) as pw_changed:
self.assertIs(await user.acheck_password("foo"), True)
self.assertEqual(pw_changed.call_count, 0)
self.assertNotEqual(initial_password, user.password)
finally:
hasher.iterations = old_iterations
| AbstractUserTestCase |
python | huggingface__transformers | src/transformers/models/persimmon/modeling_persimmon.py | {
"start": 14545,
"end": 18410
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: PersimmonConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = PersimmonAttention(config=config, layer_idx=layer_idx)
self.mlp = PersimmonMLP(config)
self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
`[0, config.n_positions - 1]`.
[What are position IDs?](../glossary#position-ids)
past_key_values (`Cache`, *optional*):
cached past key and value projection states
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
(see `past_key_values`).
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
Indices depicting the position of the input sequence tokens in the sequence
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
with `head_dim` being the embedding dimension of each attention head.
"""
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = hidden_states + residual
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
@auto_docstring
| PersimmonDecoderLayer |
python | getsentry__sentry | src/sentry/hybridcloud/services/replica/impl.py | {
"start": 11805,
"end": 13971
} | class ____(ControlReplicaService):
def upsert_external_actor_replica(self, *, external_actor: RpcExternalActor) -> None:
try:
if external_actor.user_id is not None:
# Validating existence of user
User.objects.get(id=external_actor.user_id)
integration = Integration.objects.get(id=external_actor.integration_id)
except (User.DoesNotExist, Integration.DoesNotExist):
return
destination = ExternalActorReplica(
externalactor_id=external_actor.id,
external_id=external_actor.external_id,
external_name=external_actor.external_name,
organization_id=external_actor.organization_id,
user_id=external_actor.user_id,
provider=external_actor.provider,
team_id=external_actor.team_id,
integration_id=integration.id,
)
handle_replication(ExternalActor, destination, "externalactor_id")
def remove_replicated_organization_member_team(
self, *, organization_id: int, organization_member_team_id: int
) -> None:
OrganizationMemberTeamReplica.objects.filter(
organization_id=organization_id, organizationmemberteam_id=organization_member_team_id
).delete()
def upsert_replicated_organization_member_team(self, *, omt: RpcOrganizationMemberTeam) -> None:
destination = OrganizationMemberTeamReplica(
team_id=omt.team_id,
role=omt.role,
organization_id=omt.organization_id,
organizationmember_id=omt.organizationmember_id,
organizationmemberteam_id=omt.id,
is_active=omt.is_active,
)
handle_replication(OrganizationMemberTeam, destination, fk="organizationmemberteam_id")
def upsert_replicated_team(self, *, team: RpcTeam) -> None:
destination = TeamReplica(
team_id=team.id,
organization_id=team.organization_id,
slug=team.slug,
name=team.name,
status=team.status,
)
handle_replication(Team, destination)
| DatabaseBackedControlReplicaService |
python | anthropics__anthropic-sdk-python | src/anthropic/_streaming.py | {
"start": 583,
"end": 1352
} | class ____(abc.ABCMeta):
@override
def __instancecheck__(self, instance: Any) -> bool:
# we override the `isinstance()` check for `Stream`
# as a previous version of the `MessageStream` class
# inherited from `Stream` & without this workaround,
# changing it to not inherit would be a breaking change.
from .lib.streaming import MessageStream
if isinstance(instance, MessageStream):
warnings.warn(
"Using `isinstance()` to check if a `MessageStream` object is an instance of `Stream` is deprecated & will be removed in the next major version",
DeprecationWarning,
stacklevel=2,
)
return True
return False
| _SyncStreamMeta |
python | openai__openai-python | src/openai/types/chat/completion_create_params.py | {
"start": 17262,
"end": 18030
} | class ____(CompletionCreateParamsBase):
stream: Required[Literal[True]]
"""
If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)
for more information, along with the
[streaming responses](https://platform.openai.com/docs/guides/streaming-responses)
guide for more information on how to handle the streaming events.
"""
CompletionCreateParams = Union[CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming]
| CompletionCreateParamsStreaming |
python | django__django | tests/admin_views/tests.py | {
"start": 205799,
"end": 218309
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.pks = [EmptyModel.objects.create().id for i in range(3)]
def setUp(self):
self.client.force_login(self.superuser)
self.super_login = {
REDIRECT_FIELD_NAME: reverse("admin:index"),
"username": "super",
"password": "secret",
}
def test_changelist_view(self):
response = self.client.get(reverse("admin:admin_views_emptymodel_changelist"))
for i in self.pks:
if i > 1:
self.assertContains(response, "Primary key = %s" % i)
else:
self.assertNotContains(response, "Primary key = %s" % i)
def test_changelist_view_count_queries(self):
# create 2 Person objects
Person.objects.create(name="person1", gender=1)
Person.objects.create(name="person2", gender=2)
changelist_url = reverse("admin:admin_views_person_changelist")
# 5 queries are expected: 1 for the session, 1 for the user,
# 2 for the counts and 1 for the objects on the page
with self.assertNumQueries(5):
resp = self.client.get(changelist_url)
self.assertEqual(resp.context["selection_note"], "0 of 2 selected")
self.assertEqual(resp.context["selection_note_all"], "All 2 selected")
with self.assertNumQueries(5):
extra = {"q": "not_in_name"}
resp = self.client.get(changelist_url, extra)
self.assertEqual(resp.context["selection_note"], "0 of 0 selected")
self.assertEqual(resp.context["selection_note_all"], "All 0 selected")
with self.assertNumQueries(5):
extra = {"q": "person"}
resp = self.client.get(changelist_url, extra)
self.assertEqual(resp.context["selection_note"], "0 of 2 selected")
self.assertEqual(resp.context["selection_note_all"], "All 2 selected")
with self.assertNumQueries(5):
extra = {"gender__exact": "1"}
resp = self.client.get(changelist_url, extra)
self.assertEqual(resp.context["selection_note"], "0 of 1 selected")
self.assertEqual(resp.context["selection_note_all"], "1 selected")
def test_change_view(self):
for i in self.pks:
url = reverse("admin:admin_views_emptymodel_change", args=(i,))
response = self.client.get(url, follow=True)
if i > 1:
self.assertEqual(response.status_code, 200)
else:
self.assertRedirects(response, reverse("admin:index"))
self.assertEqual(
[m.message for m in response.context["messages"]],
["empty model with ID “1” doesn’t exist. Perhaps it was deleted?"],
)
def test_add_model_modeladmin_defer_qs(self):
# Test for #14529. defer() is used in ModelAdmin.get_queryset()
# model has __str__ method
self.assertEqual(CoverLetter.objects.count(), 0)
# Emulate model instance creation via the admin
post_data = {
"author": "Candidate, Best",
"_save": "Save",
}
response = self.client.post(
reverse("admin:admin_views_coverletter_add"), post_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(CoverLetter.objects.count(), 1)
# Message should contain non-ugly model verbose name
pk = CoverLetter.objects.all()[0].pk
self.assertContains(
response,
'<li class="success">The cover letter “<a href="%s">'
"Candidate, Best</a>” was added successfully.</li>"
% reverse("admin:admin_views_coverletter_change", args=(pk,)),
html=True,
)
# model has no __str__ method
self.assertEqual(ShortMessage.objects.count(), 0)
# Emulate model instance creation via the admin
post_data = {
"content": "What's this SMS thing?",
"_save": "Save",
}
response = self.client.post(
reverse("admin:admin_views_shortmessage_add"), post_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(ShortMessage.objects.count(), 1)
# Message should contain non-ugly model verbose name
sm = ShortMessage.objects.all()[0]
self.assertContains(
response,
'<li class="success">The short message “<a href="%s">'
"%s</a>” was added successfully.</li>"
% (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm),
html=True,
)
def test_add_model_modeladmin_only_qs(self):
# Test for #14529. only() is used in ModelAdmin.get_queryset()
# model has __str__ method
self.assertEqual(Telegram.objects.count(), 0)
# Emulate model instance creation via the admin
post_data = {
"title": "Urgent telegram",
"_save": "Save",
}
response = self.client.post(
reverse("admin:admin_views_telegram_add"), post_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(Telegram.objects.count(), 1)
# Message should contain non-ugly model verbose name
pk = Telegram.objects.all()[0].pk
self.assertContains(
response,
'<li class="success">The telegram “<a href="%s">'
"Urgent telegram</a>” was added successfully.</li>"
% reverse("admin:admin_views_telegram_change", args=(pk,)),
html=True,
)
# model has no __str__ method
self.assertEqual(Paper.objects.count(), 0)
# Emulate model instance creation via the admin
post_data = {
"title": "My Modified Paper Title",
"_save": "Save",
}
response = self.client.post(
reverse("admin:admin_views_paper_add"), post_data, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(Paper.objects.count(), 1)
# Message should contain non-ugly model verbose name
p = Paper.objects.all()[0]
self.assertContains(
response,
'<li class="success">The paper “<a href="%s">'
"%s</a>” was added successfully.</li>"
% (reverse("admin:admin_views_paper_change", args=(p.pk,)), p),
html=True,
)
def test_edit_model_modeladmin_defer_qs(self):
# Test for #14529. defer() is used in ModelAdmin.get_queryset()
# model has __str__ method
cl = CoverLetter.objects.create(author="John Doe")
self.assertEqual(CoverLetter.objects.count(), 1)
response = self.client.get(
reverse("admin:admin_views_coverletter_change", args=(cl.pk,))
)
self.assertEqual(response.status_code, 200)
# Emulate model instance edit via the admin
post_data = {
"author": "John Doe II",
"_save": "Save",
}
url = reverse("admin:admin_views_coverletter_change", args=(cl.pk,))
response = self.client.post(url, post_data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(CoverLetter.objects.count(), 1)
# Message should contain non-ugly model verbose name. Instance
# representation is set by model's __str__()
self.assertContains(
response,
'<li class="success">The cover letter “<a href="%s">'
"John Doe II</a>” was changed successfully.</li>"
% reverse("admin:admin_views_coverletter_change", args=(cl.pk,)),
html=True,
)
# model has no __str__ method
sm = ShortMessage.objects.create(content="This is expensive")
self.assertEqual(ShortMessage.objects.count(), 1)
response = self.client.get(
reverse("admin:admin_views_shortmessage_change", args=(sm.pk,))
)
self.assertEqual(response.status_code, 200)
# Emulate model instance edit via the admin
post_data = {
"content": "Too expensive",
"_save": "Save",
}
url = reverse("admin:admin_views_shortmessage_change", args=(sm.pk,))
response = self.client.post(url, post_data, follow=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(ShortMessage.objects.count(), 1)
# Message should contain non-ugly model verbose name. The ugly(!)
# instance representation is set by __str__().
self.assertContains(
response,
'<li class="success">The short message “<a href="%s">'
"%s</a>” was changed successfully.</li>"
% (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm),
html=True,
)
def test_edit_model_modeladmin_only_qs(self):
# Test for #14529. only() is used in ModelAdmin.get_queryset()
# model has __str__ method
t = Telegram.objects.create(title="First Telegram")
self.assertEqual(Telegram.objects.count(), 1)
response = self.client.get(
reverse("admin:admin_views_telegram_change", args=(t.pk,))
)
self.assertEqual(response.status_code, 200)
# Emulate model instance edit via the admin
post_data = {
"title": "Telegram without typo",
"_save": "Save",
}
response = self.client.post(
reverse("admin:admin_views_telegram_change", args=(t.pk,)),
post_data,
follow=True,
)
self.assertEqual(response.status_code, 200)
self.assertEqual(Telegram.objects.count(), 1)
# Message should contain non-ugly model verbose name. The instance
# representation is set by model's __str__()
self.assertContains(
response,
'<li class="success">The telegram “<a href="%s">'
"Telegram without typo</a>” was changed successfully.</li>"
% reverse("admin:admin_views_telegram_change", args=(t.pk,)),
html=True,
)
# model has no __str__ method
p = Paper.objects.create(title="My Paper Title")
self.assertEqual(Paper.objects.count(), 1)
response = self.client.get(
reverse("admin:admin_views_paper_change", args=(p.pk,))
)
self.assertEqual(response.status_code, 200)
# Emulate model instance edit via the admin
post_data = {
"title": "My Modified Paper Title",
"_save": "Save",
}
response = self.client.post(
reverse("admin:admin_views_paper_change", args=(p.pk,)),
post_data,
follow=True,
)
self.assertEqual(response.status_code, 200)
self.assertEqual(Paper.objects.count(), 1)
# Message should contain non-ugly model verbose name. The ugly(!)
# instance representation is set by __str__().
self.assertContains(
response,
'<li class="success">The paper “<a href="%s">'
"%s</a>” was changed successfully.</li>"
% (reverse("admin:admin_views_paper_change", args=(p.pk,)), p),
html=True,
)
def test_history_view_custom_qs(self):
"""
Custom querysets are considered for the admin history view.
"""
self.client.post(reverse("admin:login"), self.super_login)
FilteredManager.objects.create(pk=1)
FilteredManager.objects.create(pk=2)
response = self.client.get(
reverse("admin:admin_views_filteredmanager_changelist")
)
self.assertContains(response, "PK=1")
self.assertContains(response, "PK=2")
self.assertEqual(
self.client.get(
reverse("admin:admin_views_filteredmanager_history", args=(1,))
).status_code,
200,
)
self.assertEqual(
self.client.get(
reverse("admin:admin_views_filteredmanager_history", args=(2,))
).status_code,
200,
)
@override_settings(ROOT_URLCONF="admin_views.urls")
| AdminCustomQuerysetTest |
python | pypa__pip | tests/unit/test_utils_unpacking.py | {
"start": 375,
"end": 15976
} | class ____:
"""
test_tar.tgz/test_tar.zip have content as follows engineered to confirm 3
things:
1) confirm that reg files, dirs, and symlinks get unpacked
2) permissions are not preserved (and go by the 022 umask)
3) reg files with *any* execute perms, get chmod +x
file.txt 600 regular file
symlink.txt 777 symlink to file.txt
script_owner.sh 700 script where owner can execute
script_group.sh 610 script where group can execute
script_world.sh 601 script where world can execute
dir 744 directory
dir/dirfile 622 regular file
4) the file contents are extracted correctly (though the content of
each file isn't currently unique)
"""
def setup_method(self) -> None:
self.tempdir = tempfile.mkdtemp()
self.old_mask = os.umask(0o022)
self.symlink_expected_mode = None
def teardown_method(self) -> None:
os.umask(self.old_mask)
shutil.rmtree(self.tempdir, ignore_errors=True)
def mode(self, path: str) -> int:
return stat.S_IMODE(os.stat(path).st_mode)
def confirm_files(self) -> None:
# expectations based on 022 umask set above and the unpack logic that
# sets execute permissions, not preservation
for fname, expected_mode, test, expected_contents in [
("file.txt", 0o644, os.path.isfile, b"file\n"),
# We don't test the "symlink.txt" contents for now.
("symlink.txt", 0o644, os.path.isfile, None),
("script_owner.sh", 0o755, os.path.isfile, b"file\n"),
("script_group.sh", 0o755, os.path.isfile, b"file\n"),
("script_world.sh", 0o755, os.path.isfile, b"file\n"),
("dir", 0o755, os.path.isdir, None),
(os.path.join("dir", "dirfile"), 0o644, os.path.isfile, b""),
]:
path = os.path.join(self.tempdir, fname)
if path.endswith("symlink.txt") and sys.platform == "win32":
# no symlinks created on windows
continue
assert test(path), path
if expected_contents is not None:
with open(path, mode="rb") as f:
contents = f.read()
assert contents == expected_contents, f"fname: {fname}"
if sys.platform == "win32":
# the permissions tests below don't apply in windows
# due to os.chmod being a noop
continue
mode = self.mode(path)
assert (
mode == expected_mode
), f"mode: {mode}, expected mode: {expected_mode}"
def make_zip_file(self, filename: str, file_list: list[str]) -> str:
"""
Create a zip file for test case
"""
test_zip = os.path.join(self.tempdir, filename)
with zipfile.ZipFile(test_zip, "w") as myzip:
for item in file_list:
myzip.writestr(item, "file content")
return test_zip
def make_tar_file(self, filename: str, file_list: list[str]) -> str:
"""
Create a tar file for test case
"""
test_tar = os.path.join(self.tempdir, filename)
with tarfile.open(test_tar, "w") as mytar:
for item in file_list:
file_tarinfo = tarfile.TarInfo(item)
mytar.addfile(file_tarinfo, io.BytesIO(b"file content"))
return test_tar
def test_unpack_tgz(self, data: TestData) -> None:
"""
Test unpacking a *.tgz, and setting execute permissions
"""
test_file = data.packages.joinpath("test_tar.tgz")
untar_file(os.fspath(test_file), self.tempdir)
self.confirm_files()
# Check the timestamp of an extracted file
file_txt_path = os.path.join(self.tempdir, "file.txt")
mtime = time.gmtime(os.stat(file_txt_path).st_mtime)
assert mtime[0:6] == (2013, 8, 16, 5, 13, 37), mtime
def test_unpack_zip(self, data: TestData) -> None:
"""
Test unpacking a *.zip, and setting execute permissions
"""
test_file = data.packages.joinpath("test_zip.zip")
unzip_file(os.fspath(test_file), self.tempdir)
self.confirm_files()
def test_unpack_zip_failure(self) -> None:
"""
Test unpacking a *.zip with file containing .. path
and expect exception
"""
files = ["regular_file.txt", os.path.join("..", "outside_file.txt")]
test_zip = self.make_zip_file("test_zip.zip", files)
with pytest.raises(InstallationError) as e:
unzip_file(test_zip, self.tempdir)
assert "trying to install outside target directory" in str(e.value)
def test_unpack_zip_success(self) -> None:
"""
Test unpacking a *.zip with regular files,
no file will be installed outside target directory after unpack
so no exception raised
"""
files = [
"regular_file1.txt",
os.path.join("dir", "dir_file1.txt"),
os.path.join("dir", "..", "dir_file2.txt"),
]
test_zip = self.make_zip_file("test_zip.zip", files)
unzip_file(test_zip, self.tempdir)
def test_unpack_tar_failure(self) -> None:
"""
Test unpacking a *.tar with file containing .. path
and expect exception
"""
files = ["regular_file.txt", os.path.join("..", "outside_file.txt")]
test_tar = self.make_tar_file("test_tar.tar", files)
with pytest.raises(InstallationError) as e:
untar_file(test_tar, self.tempdir)
# The error message comes from tarfile.data_filter when it is available,
# otherwise from pip's own check.
if hasattr(tarfile, "data_filter"):
assert "is outside the destination" in str(e.value)
else:
assert "trying to install outside target directory" in str(e.value)
def test_unpack_tar_success(self) -> None:
"""
Test unpacking a *.tar with regular files,
no file will be installed outside target directory after unpack
so no exception raised
"""
files = [
"regular_file1.txt",
os.path.join("dir", "dir_file1.txt"),
os.path.join("dir", "..", "dir_file2.txt"),
]
test_tar = self.make_tar_file("test_tar.tar", files)
untar_file(test_tar, self.tempdir)
@pytest.mark.skipif(
not hasattr(tarfile, "data_filter"),
reason="tarfile filters (PEP-721) not available",
)
def test_unpack_tar_filter(self) -> None:
"""
Test that the tarfile.data_filter is used to disallow dangerous
behaviour (PEP-721)
"""
test_tar = os.path.join(self.tempdir, "test_tar_filter.tar")
with tarfile.open(test_tar, "w") as mytar:
file_tarinfo = tarfile.TarInfo("bad-link")
file_tarinfo.type = tarfile.SYMTYPE
file_tarinfo.linkname = "../../../../pwn"
mytar.addfile(file_tarinfo, io.BytesIO(b""))
with pytest.raises(InstallationError) as e:
untar_file(test_tar, self.tempdir)
assert "is outside the destination" in str(e.value)
@pytest.mark.parametrize(
"input_prefix, unpack_prefix",
[
("", ""),
("dir/", ""), # pip ignores a common leading directory
("dir/sub/", "sub/"), # pip ignores *one* common leading directory
],
)
def test_unpack_tar_links(self, input_prefix: str, unpack_prefix: str) -> None:
"""
Test unpacking a *.tar with file containing hard & soft links
"""
test_tar = os.path.join(self.tempdir, "test_tar_links.tar")
content = b"file content"
with tarfile.open(test_tar, "w") as mytar:
file_tarinfo = tarfile.TarInfo(input_prefix + "regular_file.txt")
file_tarinfo.size = len(content)
mytar.addfile(file_tarinfo, io.BytesIO(content))
hardlink_tarinfo = tarfile.TarInfo(input_prefix + "hardlink.txt")
hardlink_tarinfo.type = tarfile.LNKTYPE
hardlink_tarinfo.linkname = input_prefix + "regular_file.txt"
mytar.addfile(hardlink_tarinfo)
symlink_tarinfo = tarfile.TarInfo(input_prefix + "symlink.txt")
symlink_tarinfo.type = tarfile.SYMTYPE
symlink_tarinfo.linkname = "regular_file.txt"
mytar.addfile(symlink_tarinfo)
untar_file(test_tar, self.tempdir)
unpack_dir = os.path.join(self.tempdir, unpack_prefix)
with open(os.path.join(unpack_dir, "regular_file.txt"), "rb") as f:
assert f.read() == content
with open(os.path.join(unpack_dir, "hardlink.txt"), "rb") as f:
assert f.read() == content
with open(os.path.join(unpack_dir, "symlink.txt"), "rb") as f:
assert f.read() == content
def test_unpack_normal_tar_link1_no_data_filter(
self, monkeypatch: MonkeyPatch
) -> None:
"""
Test unpacking a normal tar with file containing soft links, but no data_filter
"""
if hasattr(tarfile, "data_filter"):
monkeypatch.delattr("tarfile.data_filter")
tar_filename = "test_tar_links_no_data_filter.tar"
tar_filepath = os.path.join(self.tempdir, tar_filename)
extract_path = os.path.join(self.tempdir, "extract_path")
with tarfile.open(tar_filepath, "w") as tar:
file_data = io.BytesIO(b"normal\n")
normal_file_tarinfo = tarfile.TarInfo(name="normal_file")
normal_file_tarinfo.size = len(file_data.getbuffer())
tar.addfile(normal_file_tarinfo, fileobj=file_data)
info = tarfile.TarInfo("normal_symlink")
info.type = tarfile.SYMTYPE
info.linkpath = "normal_file"
tar.addfile(info)
untar_file(tar_filepath, extract_path)
assert os.path.islink(os.path.join(extract_path, "normal_symlink"))
link_path = os.readlink(os.path.join(extract_path, "normal_symlink"))
assert link_path == "normal_file"
with open(os.path.join(extract_path, "normal_symlink"), "rb") as f:
assert f.read() == b"normal\n"
def test_unpack_normal_tar_link2_no_data_filter(
self, monkeypatch: MonkeyPatch
) -> None:
"""
Test unpacking a normal tar with file containing soft links, but no data_filter
"""
if hasattr(tarfile, "data_filter"):
monkeypatch.delattr("tarfile.data_filter")
tar_filename = "test_tar_links_no_data_filter.tar"
tar_filepath = os.path.join(self.tempdir, tar_filename)
extract_path = os.path.join(self.tempdir, "extract_path")
with tarfile.open(tar_filepath, "w") as tar:
file_data = io.BytesIO(b"normal\n")
normal_file_tarinfo = tarfile.TarInfo(name="normal_file")
normal_file_tarinfo.size = len(file_data.getbuffer())
tar.addfile(normal_file_tarinfo, fileobj=file_data)
info = tarfile.TarInfo("sub/normal_symlink")
info.type = tarfile.SYMTYPE
info.linkpath = ".." + os.path.sep + "normal_file"
tar.addfile(info)
untar_file(tar_filepath, extract_path)
assert os.path.islink(os.path.join(extract_path, "sub", "normal_symlink"))
link_path = os.readlink(os.path.join(extract_path, "sub", "normal_symlink"))
assert link_path == ".." + os.path.sep + "normal_file"
with open(os.path.join(extract_path, "sub", "normal_symlink"), "rb") as f:
assert f.read() == b"normal\n"
def test_unpack_evil_tar_link1_no_data_filter(
self, monkeypatch: MonkeyPatch
) -> None:
"""
Test unpacking a evil tar with file containing soft links, but no data_filter
"""
if hasattr(tarfile, "data_filter"):
monkeypatch.delattr("tarfile.data_filter")
tar_filename = "test_tar_links_no_data_filter.tar"
tar_filepath = os.path.join(self.tempdir, tar_filename)
import_filename = "import_file"
import_filepath = os.path.join(self.tempdir, import_filename)
open(import_filepath, "w").close()
extract_path = os.path.join(self.tempdir, "extract_path")
with tarfile.open(tar_filepath, "w") as tar:
info = tarfile.TarInfo("evil_symlink")
info.type = tarfile.SYMTYPE
info.linkpath = import_filepath
tar.addfile(info)
with pytest.raises(InstallationError) as e:
untar_file(tar_filepath, extract_path)
msg = (
"The tar file ({}) has a file ({}) trying to install outside "
"target directory ({})"
)
assert msg.format(tar_filepath, "evil_symlink", import_filepath) in str(e.value)
assert not os.path.exists(os.path.join(extract_path, "evil_symlink"))
def test_unpack_evil_tar_link2_no_data_filter(
self, monkeypatch: MonkeyPatch
) -> None:
"""
Test unpacking a evil tar with file containing soft links, but no data_filter
"""
if hasattr(tarfile, "data_filter"):
monkeypatch.delattr("tarfile.data_filter")
tar_filename = "test_tar_links_no_data_filter.tar"
tar_filepath = os.path.join(self.tempdir, tar_filename)
import_filename = "import_file"
import_filepath = os.path.join(self.tempdir, import_filename)
open(import_filepath, "w").close()
extract_path = os.path.join(self.tempdir, "extract_path")
link_path = ".." + os.sep + import_filename
with tarfile.open(tar_filepath, "w") as tar:
info = tarfile.TarInfo("evil_symlink")
info.type = tarfile.SYMTYPE
info.linkpath = link_path
tar.addfile(info)
with pytest.raises(InstallationError) as e:
untar_file(tar_filepath, extract_path)
msg = (
"The tar file ({}) has a file ({}) trying to install outside "
"target directory ({})"
)
assert msg.format(tar_filepath, "evil_symlink", link_path) in str(e.value)
assert not os.path.exists(os.path.join(extract_path, "evil_symlink"))
def test_unpack_tar_unicode(tmpdir: Path) -> None:
test_tar = tmpdir / "test.tar"
# tarfile tries to decode incoming
with tarfile.open(test_tar, "w", format=tarfile.PAX_FORMAT, encoding="utf-8") as f:
metadata = tarfile.TarInfo("dir/åäö_日本語.py")
f.addfile(metadata, io.BytesIO(b"hello world"))
output_dir = tmpdir / "output"
output_dir.mkdir()
untar_file(os.fspath(test_tar), str(output_dir))
output_dir_name = str(output_dir)
contents = os.listdir(output_dir_name)
assert "åäö_日本語.py" in contents
@pytest.mark.parametrize(
"args, expected",
[
# Test the second containing the first.
(("parent/sub", "parent/"), False),
# Test the first not ending in a trailing slash.
(("parent", "parent/foo"), True),
# Test target containing `..` but still inside the parent.
(("parent/", "parent/foo/../bar"), True),
# Test target within the parent
(("parent/", "parent/sub"), True),
# Test target outside parent
(("parent/", "parent/../sub"), False),
],
)
def test_is_within_directory(args: tuple[str, str], expected: bool) -> None:
result = is_within_directory(*args)
assert result == expected
| TestUnpackArchives |
python | google__jax | jax/_src/test_warning_util.py | {
"start": 1230,
"end": 4074
} | class ____(threading.local):
"Thread-local state that contains a list of warning handlers."
def __init__(self):
self.handlers = []
_context = _WarningContext()
# Callback that applies the handlers in reverse order. If no handler matches,
# we raise an error.
def _showwarning(message, category, filename, lineno, file=None, line=None):
for handler in reversed(_context.handlers):
if handler(message, category, filename, lineno, file, line):
return
raise category(message)
@contextlib.contextmanager
def raise_on_warnings():
"Context manager that raises an exception if a warning is raised."
if warnings.showwarning is not _showwarning:
with warnings.catch_warnings():
warnings.simplefilter("error")
yield
return
def handler(message, category, filename, lineno, file=None, line=None):
raise category(message)
_context.handlers.append(handler)
try:
yield
finally:
_context.handlers.pop()
@contextlib.contextmanager
def record_warnings():
"Context manager that yields a list of warnings that are raised."
if warnings.showwarning is not _showwarning:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
yield w
return
log = []
def handler(message, category, filename, lineno, file=None, line=None):
log.append(warnings.WarningMessage(message, category, filename, lineno, file, line))
return True
_context.handlers.append(handler)
try:
yield log
finally:
_context.handlers.pop()
@contextlib.contextmanager
def ignore_warning(*, message: str | None = None, category: type = Warning):
"Context manager that ignores any matching warnings."
if warnings.showwarning is not _showwarning:
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", message="" if message is None else message, category=category)
yield
return
if message:
message_re = re.compile(message)
else:
message_re = None
category_cls = category
def handler(message, category, filename, lineno, file=None, line=None):
text = str(message) if isinstance(message, Warning) else message
if (message_re is None or message_re.match(text)) and issubclass(
category, category_cls
):
return True
return False
_context.handlers.append(handler)
try:
yield
finally:
_context.handlers.pop()
def install_threadsafe_warning_handlers():
# Hook the showwarning method. The warnings module explicitly notes that
# this is a function that users may replace.
warnings.showwarning = _showwarning
# Set the warnings module to always display warnings. We hook into it by
# overriding the "showwarning" method, so it's important that all warnings
# are "shown" by the usual mechanism.
warnings.simplefilter("always")
| _WarningContext |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/tickets_response_builder.py | {
"start": 228,
"end": 465
} | class ____(HttpResponseBuilder):
@classmethod
def tickets_response(cls) -> "TicketsResponseBuilder":
return cls(find_template("tickets", __file__), FieldPath("tickets"), CursorBasedPaginationStrategy())
| TicketsResponseBuilder |
python | numpy__numpy | numpy/distutils/tests/test_fcompiler_intel.py | {
"start": 785,
"end": 1058
} | class ____:
def test_64bit_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='intelem')
for vs, version in intel_64bit_version_strings:
v = fc.version_match(vs)
assert_(v == version)
| TestIntelEM64TFCompilerVersions |
python | pytorch__pytorch | torch/utils/_sympy/functions.py | {
"start": 46186,
"end": 46609
} | class ____(sympy.Function):
is_integer = True
@classmethod
def eval(cls, number):
# assert number.is_integer is not True, number
if number in (sympy.oo, int_oo):
return int_oo
if number in (-sympy.oo, -int_oo):
return -int_oo
if isinstance(number, sympy.Number):
return sympy.Integer(math.trunc(float(number)))
# This is float -> int
| TruncToInt |
python | neetcode-gh__leetcode | python/0144-binary-tree-preorder-traversal.py | {
"start": 0,
"end": 361
} | class ____:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
cur, stack = root, []
res = []
while cur or stack:
if cur:
res.append(cur.val)
stack.append(cur.right)
cur = cur.left
else:
cur = stack.pop()
return res
| Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/dummy/views.py | {
"start": 945,
"end": 2238
} | class ____(FormView):
form_class = AuthenticateForm
template_name = "dummy/authenticate_form.html"
@method_decorator(login_not_required)
def dispatch(self, request, *args, **kwargs):
self.state_id = request.GET.get("state")
if not self.state_id:
raise PermissionDenied()
self.provider = get_adapter().get_provider(self.request, DummyProvider.id)
if request.method == "POST" and request.POST.get("action") == "cancel":
return render_authentication_error(
request,
self.provider,
error=AuthError.CANCELLED,
extra_context={"state_id": self.state_id},
)
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
login = self.provider.sociallogin_from_response(self.request, form.cleaned_data)
login.state = SocialLogin.unstash_state(self.request)
return complete_social_login(self.request, login)
def get_context_data(self, **kwargs):
ret = super().get_context_data(**kwargs)
ret["action_url"] = (
reverse("dummy_authenticate") + "?" + urlencode({"state": self.state_id})
)
return ret
authenticate = AuthenticateView.as_view()
| AuthenticateView |
python | Pylons__pyramid | docs/quick_tutorial/authorization/tutorial/security.py | {
"start": 549,
"end": 1692
} | class ____:
def __init__(self, secret):
self.authtkt = AuthTktCookieHelper(secret=secret)
self.acl = ACLHelper()
def identity(self, request):
identity = self.authtkt.identify(request)
if identity is not None and identity['userid'] in USERS:
return identity
def authenticated_userid(self, request):
identity = self.identity(request)
if identity is not None:
return identity['userid']
def remember(self, request, userid, **kw):
return self.authtkt.remember(request, userid, **kw)
def forget(self, request, **kw):
return self.authtkt.forget(request, **kw)
def permits(self, request, context, permission):
principals = self.effective_principals(request)
return self.acl.permits(context, principals, permission)
def effective_principals(self, request):
principals = [Everyone]
userid = self.authenticated_userid(request)
if userid is not None:
principals += [Authenticated, 'u:' + userid]
principals += GROUPS.get(userid, [])
return principals
| SecurityPolicy |
python | django-haystack__django-haystack | test_haystack/test_forms.py | {
"start": 464,
"end": 1485
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Stow.
self.old_unified_index = connections["default"]._index
self.ui = UnifiedIndex()
self.bmmsi = BasicMockModelSearchIndex()
self.bammsi = BasicAnotherMockModelSearchIndex()
self.ui.build(indexes=[self.bmmsi, self.bammsi])
connections["default"]._index = self.ui
# Update the "index".
backend = connections["default"].get_backend()
backend.clear()
backend.update(self.bmmsi, MockModel.objects.all())
self.sqs = SearchQuerySet()
def tearDown(self):
connections["default"]._index = self.old_unified_index
super().tearDown()
def test_unbound(self):
sf = SearchForm({}, searchqueryset=self.sqs)
self.assertEqual(sf.errors, {})
self.assertEqual(sf.is_valid(), True)
# This shouldn't blow up.
sqs = sf.search()
self.assertTrue(isinstance(sqs, EmptySearchQuerySet))
| SearchFormTestCase |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_test.py | {
"start": 49436,
"end": 54746
} | class ____(parameterized.TestCase):
@parameterized.named_parameters([
('File', lambda: descriptor_pb2.DESCRIPTOR),
('Message', lambda: descriptor_pb2.FeatureSet.DESCRIPTOR),
(
'Enum',
lambda: descriptor_pb2.FeatureSet.FieldPresence.DESCRIPTOR,
),
(
'Field',
lambda: descriptor_pb2.FeatureSet.DESCRIPTOR.fields_by_name[
'enum_type'
],
),
])
def testDescriptorProtoDefaultFeatures(self, desc):
self.assertEqual(
desc()._GetFeatures().field_presence,
descriptor_pb2.FeatureSet.FieldPresence.EXPLICIT,
)
self.assertEqual(
desc()._GetFeatures().enum_type,
descriptor_pb2.FeatureSet.EnumType.CLOSED,
)
self.assertEqual(
desc()._GetFeatures().repeated_field_encoding,
descriptor_pb2.FeatureSet.RepeatedFieldEncoding.EXPANDED,
)
def testDescriptorProtoOverrideFeatures(self):
desc = descriptor_pb2.SourceCodeInfo.Location.DESCRIPTOR.fields_by_name[
'path'
]
self.assertEqual(
desc._GetFeatures().field_presence,
descriptor_pb2.FeatureSet.FieldPresence.EXPLICIT,
)
self.assertEqual(
desc._GetFeatures().enum_type,
descriptor_pb2.FeatureSet.EnumType.CLOSED,
)
self.assertEqual(
desc._GetFeatures().repeated_field_encoding,
descriptor_pb2.FeatureSet.RepeatedFieldEncoding.PACKED,
)
def testFeaturesStripped(self):
desc = unittest_legacy_features_pb2.TestEditionsMessage.DESCRIPTOR.fields_by_name[
'required_field'
]
self.assertFalse(desc.GetOptions().HasField('features'))
def testLegacyRequiredTransform(self):
desc = unittest_legacy_features_pb2.TestEditionsMessage.DESCRIPTOR
self.assertTrue(desc.fields_by_name['required_field'].is_required)
def testLegacyGroupTransform(self):
desc = unittest_legacy_features_pb2.TestEditionsMessage.DESCRIPTOR
self.assertEqual(
desc.fields_by_name['delimited_field'].type,
descriptor.FieldDescriptor.TYPE_GROUP,
)
def testLegacyInferRequired(self):
desc = unittest_pb2.TestRequired.DESCRIPTOR.fields_by_name['a']
self.assertEqual(
desc._GetFeatures().field_presence,
descriptor_pb2.FeatureSet.FieldPresence.LEGACY_REQUIRED,
)
def testLegacyInferGroup(self):
desc = unittest_pb2.TestAllTypes.DESCRIPTOR.fields_by_name['optionalgroup']
self.assertEqual(
desc._GetFeatures().message_encoding,
descriptor_pb2.FeatureSet.MessageEncoding.DELIMITED,
)
def testLegacyInferProto2Packed(self):
desc = unittest_pb2.TestPackedTypes.DESCRIPTOR.fields_by_name[
'packed_int32'
]
self.assertEqual(
desc._GetFeatures().repeated_field_encoding,
descriptor_pb2.FeatureSet.RepeatedFieldEncoding.PACKED,
)
def testLegacyInferProto3Expanded(self):
desc = unittest_proto3_pb2.TestUnpackedTypes.DESCRIPTOR.fields_by_name[
'repeated_int32'
]
self.assertEqual(
desc._GetFeatures().repeated_field_encoding,
descriptor_pb2.FeatureSet.RepeatedFieldEncoding.EXPANDED,
)
def testProto2Defaults(self):
features = test_proto2_pb2.TestProto2.DESCRIPTOR.fields_by_name[
'optional_int32'
]._GetFeatures()
fs = descriptor_pb2.FeatureSet
self.assertEqual(features.field_presence, fs.FieldPresence.EXPLICIT)
self.assertEqual(features.enum_type, fs.EnumType.CLOSED)
self.assertEqual(
features.repeated_field_encoding, fs.RepeatedFieldEncoding.EXPANDED
)
self.assertEqual(features.utf8_validation, fs.Utf8Validation.NONE)
self.assertEqual(
features.message_encoding, fs.MessageEncoding.LENGTH_PREFIXED
)
self.assertEqual(features.json_format, fs.JsonFormat.LEGACY_BEST_EFFORT)
def testProto3Defaults(self):
features = unittest_proto3_pb2.TestAllTypes.DESCRIPTOR.fields_by_name[
'optional_int32'
]._GetFeatures()
fs = descriptor_pb2.FeatureSet
self.assertEqual(features.field_presence, fs.FieldPresence.IMPLICIT)
self.assertEqual(features.enum_type, fs.EnumType.OPEN)
self.assertEqual(
features.repeated_field_encoding, fs.RepeatedFieldEncoding.PACKED
)
self.assertEqual(features.utf8_validation, fs.Utf8Validation.VERIFY)
self.assertEqual(
features.message_encoding, fs.MessageEncoding.LENGTH_PREFIXED
)
self.assertEqual(features.json_format, fs.JsonFormat.ALLOW)
def testProto3ExtensionPresence(self):
ext = unittest_proto3_extensions_pb2.Proto3FileExtensions.singular_int
file = descriptor_pb2.FileDescriptorProto()
self.assertFalse(file.options.HasExtension(ext))
file.options.Extensions[ext] = 1
self.assertTrue(file.options.HasExtension(ext))
def testProto3ExtensionHasPresence(self):
exts = unittest_proto3_extensions_pb2.Proto3FileExtensions
self.assertTrue(exts.singular_int.has_presence)
self.assertFalse(exts.repeated_int.has_presence)
def GetTestFeature(desc):
return (
desc._GetFeatures()
.Extensions[unittest_features_pb2.test]
.multiple_feature
)
def SetTestFeature(proto, value):
proto.options.features.Extensions[
unittest_features_pb2.test
].multiple_feature = value
@testing_refleaks.TestCase
| FeaturesTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink05.py | {
"start": 346,
"end": 2038
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet = workbook.add_worksheet()
worksheet.write_url("A1", "http://www.perl.org/")
worksheet.write_url("A3", "http://www.perl.org/", None, "Perl home")
worksheet.write_url("A5", "http://www.perl.org/", None, "Perl home", "Tool Tip")
worksheet.write_url("A7", "http://www.cpan.org/", None, "CPAN", "Download")
workbook.close()
self.assertExcelEqual()
def test_create_file_with_url_type(self):
"""Test the creation of a simple XlsxWriter using Url class"""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet = workbook.add_worksheet()
worksheet.write_url("A1", Url("http://www.perl.org/"))
url = Url("http://www.perl.org/")
url.text = "Perl home"
worksheet.write_url("A3", url)
url = Url("http://www.perl.org/")
url.text = "Perl home"
url.tip = "Tool Tip"
worksheet.write_url("A5", url)
url = Url("http://www.cpan.org/")
url.text = "CPAN"
url.tip = "Download"
worksheet.write_url("A7", url)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | tornadoweb__tornado | tornado/test/iostream_test.py | {
"start": 48313,
"end": 51795
} | class ____(unittest.TestCase):
"""
Unit tests for the private _StreamBuffer class.
"""
def setUp(self):
self.random = random.Random(42)
def to_bytes(self, b):
if isinstance(b, (bytes, bytearray)):
return bytes(b)
elif isinstance(b, memoryview):
return b.tobytes() # For py2
else:
raise TypeError(b)
def make_streambuffer(self, large_buf_threshold=10):
buf = _StreamBuffer()
assert buf._large_buf_threshold
buf._large_buf_threshold = large_buf_threshold
return buf
def check_peek(self, buf, expected):
size = 1
while size < 2 * len(expected):
got = self.to_bytes(buf.peek(size))
self.assertTrue(got) # Not empty
self.assertLessEqual(len(got), size)
self.assertTrue(expected.startswith(got), (expected, got))
size = (size * 3 + 1) // 2
def check_append_all_then_skip_all(self, buf, objs, input_type):
self.assertEqual(len(buf), 0)
expected = b""
for o in objs:
expected += o
buf.append(input_type(o))
self.assertEqual(len(buf), len(expected))
self.check_peek(buf, expected)
while expected:
n = self.random.randrange(1, len(expected) + 1)
expected = expected[n:]
buf.advance(n)
self.assertEqual(len(buf), len(expected))
self.check_peek(buf, expected)
self.assertEqual(len(buf), 0)
def test_small(self):
objs = [b"12", b"345", b"67", b"89a", b"bcde", b"fgh", b"ijklmn"]
buf = self.make_streambuffer()
self.check_append_all_then_skip_all(buf, objs, bytes)
buf = self.make_streambuffer()
self.check_append_all_then_skip_all(buf, objs, bytearray)
buf = self.make_streambuffer()
self.check_append_all_then_skip_all(buf, objs, memoryview)
# Test internal algorithm
buf = self.make_streambuffer(10)
for i in range(9):
buf.append(b"x")
self.assertEqual(len(buf._buffers), 1)
for i in range(9):
buf.append(b"x")
self.assertEqual(len(buf._buffers), 2)
buf.advance(10)
self.assertEqual(len(buf._buffers), 1)
buf.advance(8)
self.assertEqual(len(buf._buffers), 0)
self.assertEqual(len(buf), 0)
def test_large(self):
objs = [
b"12" * 5,
b"345" * 2,
b"67" * 20,
b"89a" * 12,
b"bcde" * 1,
b"fgh" * 7,
b"ijklmn" * 2,
]
buf = self.make_streambuffer()
self.check_append_all_then_skip_all(buf, objs, bytes)
buf = self.make_streambuffer()
self.check_append_all_then_skip_all(buf, objs, bytearray)
buf = self.make_streambuffer()
self.check_append_all_then_skip_all(buf, objs, memoryview)
# Test internal algorithm
buf = self.make_streambuffer(10)
for i in range(3):
buf.append(b"x" * 11)
self.assertEqual(len(buf._buffers), 3)
buf.append(b"y")
self.assertEqual(len(buf._buffers), 4)
buf.append(b"z")
self.assertEqual(len(buf._buffers), 4)
buf.advance(33)
self.assertEqual(len(buf._buffers), 1)
buf.advance(2)
self.assertEqual(len(buf._buffers), 0)
self.assertEqual(len(buf), 0)
| TestStreamBuffer |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 226498,
"end": 230628
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3, 3]"):
l_x_ = L_x_
_jvp_increment_nesting = torch._C._functorch._jvp_increment_nesting(); _jvp_increment_nesting = None
_set_fwd_grad_enabled = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled = None
_enter_dual_level = torch._C._enter_dual_level(); _enter_dual_level = None
_maybe_load_decompositions = torch.autograd.forward_ad._maybe_load_decompositions(); _maybe_load_decompositions = None
child: "f32[3, 3, 3]" = torch._make_dual(l_x_, l_x_, level = 0); l_x_ = None
_jvp_increment_nesting_1 = torch._C._functorch._jvp_increment_nesting(); _jvp_increment_nesting_1 = None
_set_fwd_grad_enabled_1 = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled_1 = None
_maybe_load_decompositions_1 = torch.autograd.forward_ad._maybe_load_decompositions(); _maybe_load_decompositions_1 = None
_make_dual_1: "f32[3, 3, 3]" = torch._make_dual(child, child, level = 0); child = None
result_duals: "f32[3, 3, 3]" = torch.sin(_make_dual_1); _make_dual_1 = None
_unpack_dual = torch._unpack_dual(result_duals, level = 0); result_duals = None
primal: "f32[3, 3, 3]" = _unpack_dual[0]
dual: "f32[3, 3, 3]" = _unpack_dual[1]; _unpack_dual = None
primals_out_unflatten: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(primal, 2); primal = None
tangents_out_unflatten: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(dual, 2); dual = None
_set_fwd_grad_enabled_2 = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled_2 = None
_jvp_decrement_nesting = torch._C._functorch._jvp_decrement_nesting(); _jvp_decrement_nesting = None
_unpack_dual_1 = torch._unpack_dual(primals_out_unflatten, level = 0); primals_out_unflatten = None
primal_1: "f32[3, 3, 3]" = _unpack_dual_1[0]
dual_1: "f32[3, 3, 3]" = _unpack_dual_1[1]; _unpack_dual_1 = None
_unpack_dual_2 = torch._unpack_dual(tangents_out_unflatten, level = 0); tangents_out_unflatten = None
primal_2: "f32[3, 3, 3]" = _unpack_dual_2[0]
dual_2: "f32[3, 3, 3]" = _unpack_dual_2[1]; _unpack_dual_2 = None
_unwrap_for_grad_2: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(primal_1, 1); primal_1 = None
_unwrap_for_grad_3: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(primal_2, 1); primal_2 = None
_unwrap_for_grad_4: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(dual_1, 1); dual_1 = None
_unwrap_for_grad_5: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(dual_2, 1); dual_2 = None
_exit_dual_level = torch._C._exit_dual_level(0); _exit_dual_level = None
_set_fwd_grad_enabled_3 = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_enabled_3 = None
_jvp_decrement_nesting_1 = torch._C._functorch._jvp_decrement_nesting(); _jvp_decrement_nesting_1 = None
return (_unwrap_for_grad_2, _unwrap_for_grad_3, _unwrap_for_grad_4, _unwrap_for_grad_5)
""",
)
def test_jvp_freevar_python_scalar(self):
counters.clear()
y = 3
def fn(x):
return (x.sin() + y).sum()
def wrapper_fn(x):
return torch.func.jvp(fn, (x,), (x,))
x = torch.randn(3, 3, 3)
expected = wrapper_fn(x)
actual = torch.compile(wrapper_fn, backend="aot_eager", fullgraph=True)(x)
self.assertEqual(actual, expected)
def test_linearize_jvp_fn(self):
counters.clear()
def wrapper_fn(x):
output, jvp_fn = torch.func.linearize(torch.sin, x)
return output, jvp_fn(x)
x = torch.randn(3, 3, 3)
wrapped_gm = self._compile_check(wrapper_fn, (x,), fullgraph=False, graph_idx=0)
# Dynamic shapes produce a slightly different graph.
if check_dynamic_shape_capture():
return
actual = normalize_gm(wrapped_gm.print_readable(print_output=False))
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | encode__django-rest-framework | rest_framework/authtoken/apps.py | {
"start": 91,
"end": 198
} | class ____(AppConfig):
name = 'rest_framework.authtoken'
verbose_name = _("Auth Token")
| AuthTokenConfig |
python | crytic__slither | slither/detectors/variables/could_be_constant.py | {
"start": 370,
"end": 2060
} | class ____(AbstractDetector):
"""
State variables that could be declared as constant.
Not all types for constants are implemented in Solidity as of 0.4.25.
The only supported types are value types and strings (ElementaryType).
Reference: https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables
"""
ARGUMENT = "constable-states"
HELP = "State variables that could be declared constant"
IMPACT = DetectorClassification.OPTIMIZATION
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-constant"
WIKI_TITLE = "State variables that could be declared constant"
WIKI_DESCRIPTION = "State variables that are not updated following deployment should be declared constant to save gas."
WIKI_RECOMMENDATION = "Add the `constant` attribute to state variables that never change."
def _detect(self) -> List[Output]:
"""Detect state variables that could be constant"""
results = {}
unchanged_state_variables = UnchangedStateVariables(self.compilation_unit)
unchanged_state_variables.detect()
for variable in unchanged_state_variables.constant_candidates:
results[variable.canonical_name] = self.generate_result(
[variable, " should be constant \n"]
)
# Order by canonical name for deterministic results
return [results[k] for k in sorted(results)]
@staticmethod
def _format(compilation_unit: SlitherCompilationUnit, result: Dict) -> None:
custom_format(compilation_unit, result, "constant")
| CouldBeConstant |
python | sanic-org__sanic | sanic/errorpages.py | {
"start": 4773,
"end": 7111
} | class ____(BaseRenderer):
"""Render an exception as plain text."""
OUTPUT_TEXT = "{title}\n{bar}\n{text}\n\n{body}"
SPACER = " "
def full(self) -> HTTPResponse:
return text(
self.OUTPUT_TEXT.format(
title=self.title,
text=self.text,
bar=("=" * len(self.title)),
body=self._generate_body(full=True),
)
)
def minimal(self) -> HTTPResponse:
return text(
self.OUTPUT_TEXT.format(
title=self.title,
text=self.text,
bar=("=" * len(self.title)),
body=self._generate_body(full=False),
)
)
@property
def title(self):
return f"⚠️ {super().title}"
def _generate_body(self, *, full):
lines = []
if full:
_, exc_value, __ = sys.exc_info()
exceptions = []
lines += [
f"{self.exception.__class__.__name__}: {self.exception} while "
f"handling path {self.request.path}",
f"Traceback of {self.request.app.name} "
"(most recent call last):\n",
]
while exc_value:
exceptions.append(self._format_exc(exc_value))
exc_value = exc_value.__cause__
lines += exceptions[::-1]
for attr, display in (("context", True), ("extra", bool(full))):
info = getattr(self.exception, attr, None)
if info and display:
lines += self._generate_object_display_list(info, attr)
return "\n".join(lines)
def _format_exc(self, exc):
frames = "\n\n".join(
[
f"{self.SPACER * 2}File {frame.filename}, "
f"line {frame.lineno}, in "
f"{frame.name}\n{self.SPACER * 2}{frame.line}"
for frame in extract_tb(exc.__traceback__)
]
)
return f"{self.SPACER}{exc.__class__.__name__}: {exc}\n{frames}"
def _generate_object_display_list(self, obj, descriptor):
lines = [f"\n{descriptor.title()}"]
for key, value in obj.items():
display = self.dumps(value)
lines.append(f"{self.SPACER * 2}{key}: {display}")
return lines
| TextRenderer |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 8431,
"end": 8939
} | class ____(TestCase):
def test_rcssmin_filter(self):
content = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/
p {
background: rgb(51,102,153) url('../../images/image.gif');
}
"""
output = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/p{background:rgb(51,102,153) url('../../images/image.gif')}"""
self.assertEqual(output, rCSSMinFilter(content).output())
| rCssMinTestCase |
python | getsentry__sentry | src/sentry/api/endpoints/project_rules.py | {
"start": 11095,
"end": 25037
} | class ____(serializers.Serializer):
name = serializers.CharField(max_length=256, help_text="The name for the rule.")
environment = serializers.CharField(
required=False, allow_null=True, help_text="The name of the environment to filter by."
)
owner = ActorField(
required=False, allow_null=True, help_text="The ID of the team or user that owns the rule."
)
frequency = serializers.IntegerField(
min_value=5,
max_value=60 * 24 * 30,
help_text="How often to perform the actions once for an issue, in minutes. The valid range is `5` to `43200`.",
)
actionMatch = serializers.ChoiceField(
choices=(
("all", "All conditions must evaluate to true."),
("any", "At least one of the conditions must evaluate to true."),
("none", "All conditions must evaluate to false."),
),
help_text="A string determining which of the conditions need to be true before any filters are evaluated.",
)
conditions = serializers.ListField(
child=RuleNodeField(type="condition/event"),
help_text="""
A list of triggers that determine when the rule fires. See below for a list of possible conditions.
**A new issue is created**
```json
{
"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"
}
```
**The issue changes state from resolved to unresolved**
```json
{
"id": "sentry.rules.conditions.regression_event.RegressionEventCondition"
}
```
**The issue is seen more than `value` times in `interval`**
- `value` - An integer
- `interval` - Valid values are `1m`, `5m`, `15m`, `1h`, `1d`, `1w` and `30d` (`m` for minutes, `h` for hours, `d` for days, and `w` for weeks).
```json
{
"id": "sentry.rules.conditions.event_frequency.EventFrequencyCondition",
"value": 500,
"interval": "1h"
}
```
**The issue is seen by more than `value` users in `interval`**
- `value` - An integer
- `interval` - Valid values are `1m`, `5m`, `15m`, `1h`, `1d`, `1w` and `30d` (`m` for minutes, `h` for hours, `d` for days, and `w` for weeks).
```json
{
"id": "sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyCondition",
"value": 1000,
"interval": "15m"
}
```
**The issue affects more than `value` percent of sessions in `interval`**
- `value` - A float
- `interval` - Valid values are `5m`, `10m`, `30m`, and `1h` (`m` for minutes, `h` for hours).
```json
{
"id": "sentry.rules.conditions.event_frequency.EventFrequencyPercentCondition",
"value": 50.0,
"interval": "10m"
}
```
""",
)
filterMatch = serializers.ChoiceField(
choices=(
("all", "All filters must evaluate to true."),
("any", "At least one of the filters must evaluate to true."),
("none", "All filters must evaluate to false."),
),
required=False,
help_text="A string determining which filters need to be true before any actions take place. Required when a value is provided for `filters`.",
)
filters = serializers.ListField(
child=RuleNodeField(type="filter/event"),
required=False,
help_text="""
A list of filters that determine if a rule fires after the necessary conditions have been met. See below for a list of possible filters.
**The issue is `comparison_type` than `value` `time`**
- `comparison_type` - One of `older` or `newer`
- `value` - An integer
- `time` - The unit of time. Valid values are `minute`, `hour`, `day`, and `week`.
```json
{
"id": "sentry.rules.filters.age_comparison.AgeComparisonFilter",
"comparison_type": "older",
"value": 3,
"time": "week"
}
```
**The issue has happened at least `value` times**
- `value` - An integer
```json
{
"id": "sentry.rules.filters.issue_occurrences.IssueOccurrencesFilter",
"value": 120
}
```
**The issue is assigned to No One**
```json
{
"id": "sentry.rules.filters.assigned_to.AssignedToFilter",
"targetType": "Unassigned"
}
```
**The issue is assigned to `targetType`**
- `targetType` - One of `Team` or `Member`
- `targetIdentifier` - The target's ID
```json
{
"id": "sentry.rules.filters.assigned_to.AssignedToFilter",
"targetType": "Member",
"targetIdentifier": 895329789
}
```
**The event is from the latest release**
```json
{
"id": "sentry.rules.filters.latest_release.LatestReleaseFilter"
}
```
**The issue's category is equal to `value`**
- `value` - An integer correlated with a category. Valid values are `1` (Error), `2` (Performance), `3` (Profile), `4` (Cron), and `5` (Replay).
```json
{
"id": "sentry.rules.filters.issue_category.IssueCategoryFilter",
"value": 2
}
```
**The event's `attribute` value `match` `value`**
- `attribute` - Valid values are `message`, `platform`, `environment`, `type`, `error.handled`, `error.unhandled`, `error.main_thread`, `exception.type`, `exception.value`, `user.id`, `user.email`, `user.username`, `user.ip_address`, `http.method`, `http.url`, `http.status_code`, `sdk.name`, `stacktrace.code`, `stacktrace.module`, `stacktrace.filename`, `stacktrace.abs_path`, `stacktrace.package`, `unreal.crash_type`, `app.in_foreground`.
- `match` - The comparison operator. Valid values are `eq` (equals), `ne` (does not equal), `sw` (starts with), `ew` (ends with), `co` (contains), `nc` (does not contain), `is` (is set), and `ns` (is not set).
- `value` - A string. Not required when `match` is `is` or `ns`.
```json
{
"id": "sentry.rules.conditions.event_attribute.EventAttributeCondition",
"attribute": "http.url",
"match": "nc",
"value": "localhost"
}
```
**The event's tags match `key` `match` `value`**
- `key` - The tag
- `match` - The comparison operator. Valid values are `eq` (equals), `ne` (does not equal), `sw` (starts with), `ew` (ends with), `co` (contains), `nc` (does not contain), `is` (is set), and `ns` (is not set).
- `value` - A string. Not required when `match` is `is` or `ns`.
```json
{
"id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
"key": "level",
"match": "eq"
"value": "error"
}
```
**The event's level is `match` `level`**
- `match` - Valid values are `eq`, `gte`, and `lte`.
- `level` - Valid values are `50` (fatal), `40` (error), `30` (warning), `20` (info), `10` (debug), `0` (sample).
```json
{
"id": "sentry.rules.filters.level.LevelFilter",
"match": "gte"
"level": "50"
}
```
""",
)
actions = serializers.ListField(
child=RuleNodeField(type="action/event"),
help_text="""
A list of actions that take place when all required conditions and filters for the rule are met. See below for a list of possible actions.
**Send a notification to Suggested Assignees**
- `fallthroughType` - Who the notification should be sent to if there are no suggested assignees. Valid values are `ActiveMembers`, `AllMembers`, and `NoOne`.
```json
{
"id" - "sentry.mail.actions.NotifyEmailAction",
"targetType" - "IssueOwners",
"fallthroughType" - "ActiveMembers"
}
```
**Send a notification to a Member or a Team**
- `targetType` - One of `Member` or `Team`.
- `fallthroughType` - Who the notification should be sent to if it cannot be sent to the original target. Valid values are `ActiveMembers`, `AllMembers`, and `NoOne`.
- `targetIdentifier` - The ID of the Member or Team the notification should be sent to.
```json
{
"id": "sentry.mail.actions.NotifyEmailAction",
"targetType": "Team"
"fallthroughType": "AllMembers"
"targetIdentifier": 4524986223
}
```
**Send a Slack notification**
- `workspace` - The integration ID associated with the Slack workspace.
- `channel` - The name of the channel to send the notification to (e.g., #critical, Jane Schmidt).
- `channel_id` (optional) - The ID of the channel to send the notification to.
- `tags` (optional) - A string of tags to show in the notification, separated by commas (e.g., "environment, user, my_tag").
- `notes` (optional) - Text to show alongside the notification. To @ a user, include their user id like `@<USER_ID>`. To include a clickable link, format the link and title like `<http://example.com|Click Here>`.
```json
{
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"workspace": 293854098,
"channel": "#warning",
"tags": "environment,level"
"notes": "Please <http://example.com|click here> for triage information"
}
```
**Send a Microsoft Teams notification**
- `team` - The integration ID associated with the Microsoft Teams team.
- `channel` - The name of the channel to send the notification to.
```json
{
"id": "sentry.integrations.msteams.notify_action.MsTeamsNotifyServiceAction",
"team": 23465424,
"channel": "General"
}
```
**Send a Discord notification**
- `server` - The integration ID associated with the Discord server.
- `channel_id` - The ID of the channel to send the notification to.
- `tags` (optional) - A string of tags to show in the notification, separated by commas (e.g., "environment, user, my_tag").
```json
{
"id": "sentry.integrations.discord.notify_action.DiscordNotifyServiceAction",
"server": 63408298,
"channel_id": 94732897,
"tags": "browser,user"
}
```
**Create a Jira Ticket**
- `integration` - The integration ID associated with Jira.
- `project` - The ID of the Jira project.
- `issuetype` - The ID of the type of issue that the ticket should be created as.
- `dynamic_form_fields` (optional) - A list of any custom fields you want to include in the ticket as objects.
```json
{
"id": "sentry.integrations.jira.notify_action.JiraCreateTicketAction",
"integration": 321424,
"project": "349719"
"issueType": "1"
}
```
**Create a Jira Server Ticket**
- `integration` - The integration ID associated with Jira Server.
- `project` - The ID of the Jira Server project.
- `issuetype` - The ID of the type of issue that the ticket should be created as.
- `dynamic_form_fields` (optional) - A list of any custom fields you want to include in the ticket as objects.
```json
{
"id": "sentry.integrations.jira_server.notify_action.JiraServerCreateTicketAction",
"integration": 321424,
"project": "349719"
"issueType": "1"
}
```
**Create a GitHub Issue**
- `integration` - The integration ID associated with GitHub.
- `repo` - The name of the repository to create the issue in.
- `title` - The title of the issue.
- `body` (optional) - The contents of the issue.
- `assignee` (optional) - The GitHub user to assign the issue to.
- `labels` (optional) - A list of labels to assign to the issue.
```json
{
"id": "sentry.integrations.github.notify_action.GitHubCreateTicketAction",
"integration": 93749,
"repo": default,
"title": "My Test Issue",
"assignee": "Baxter the Hacker",
"labels": ["bug", "p1"]
""
}
```
**Create a GitHub Enterprise Issue**
- `integration` - The integration ID associated with GitHub Enterprise.
- `repo` - The name of the repository to create the issue in.
- `title` - The title of the issue.
- `body` (optional) - The contents of the issue.
- `assignee` (optional) - The GitHub user to assign the issue to.
- `labels` (optional) - A list of labels to assign to the issue.
```json
{
"id": "sentry.integrations.github_enterprise.notify_action.GitHubEnterpriseCreateTicketAction",
"integration": 93749,
"repo": default,
"title": "My Test Issue",
"assignee": "Baxter the Hacker",
"labels": ["bug", "p1"]
""
}
```
**Create an Azure DevOps work item**
- `integration` - The integration ID.
- `project` - The ID of the Azure DevOps project.
- `work_item_type` - The type of work item to create.
- `dynamic_form_fields` (optional) - A list of any custom fields you want to include in the work item as objects.
```json
{
"id": "sentry.integrations.vsts.notify_action.AzureDevopsCreateTicketAction",
"integration": 294838,
"project": "0389485",
"work_item_type": "Microsoft.VSTS.WorkItemTypes.Task",
}
```
**Send a PagerDuty notification**
- `account` - The integration ID associated with the PagerDuty account.
- `service` - The ID of the service to send the notification to.
- `severity` - The severity of the Pagerduty alert. This is optional, the default is `critical` for fatal issues, `error` for error issues, `warning` for warning issues, and `info` for info and debug issues.
```json
{
"id": "sentry.integrations.pagerduty.notify_action.PagerDutyNotifyServiceAction",
"account": 92385907,
"service": 9823924,
"severity": "critical"
}
```
**Send an Opsgenie notification**
- `account` - The integration ID associated with the Opsgenie account.
- `team` - The ID of the Opsgenie team to send the notification to.
- `priority` - The priority of the Opsgenie alert. This is optional, the default is `P3`.
```json
{
"id": "sentry.integrations.opsgenie.notify_action.OpsgenieNotifyTeamAction",
"account": 8723897589,
"team": "9438930258-fairy",
"priority": "P1"
}
```
**Send a notification to a service**
- `service` - The plugin slug.
```json
{
"id": "sentry.rules.actions.notify_event_service.NotifyEventServiceAction",
"service": "mail"
}
```
**Send a notification to a Sentry app with a custom webhook payload**
- `settings` - A list of objects denoting the settings each action will be created with. All required fields must be included.
- `sentryAppInstallationUuid` - The ID for the Sentry app
```json
{
"id": "sentry.rules.actions.notify_event_sentry_app.NotifyEventSentryAppAction",
"settings": [
{"name": "title", "value": "Team Rocket"},
{"name": "summary", "value": "We're blasting off again."},
],
"sentryAppInstallationUuid": 643522
"hasSchemaFormConfig": true
}
```
**Send a notification (for all legacy integrations)**
```json
{
"id": "sentry.rules.actions.notify_event.NotifyEventAction"
}
```
""",
)
@extend_schema(tags=["Alerts"])
@region_silo_endpoint
| ProjectRulesPostSerializer |
python | realpython__materials | python-property/point_v1.py | {
"start": 0,
"end": 279
} | class ____:
def __init__(self, x, y):
self._x = x
self._y = y
def get_x(self):
return self._x
def set_x(self, value):
self._x = value
def get_y(self):
return self._y
def set_y(self, value):
self._y = value
| Point |
python | numba__numba | numba/core/targetconfig.py | {
"start": 201,
"end": 951
} | class ____:
"""An option to be used in ``TargetConfig``.
"""
__slots__ = "_type", "_default", "_doc"
def __init__(self, type, *, default, doc):
"""
Parameters
----------
type :
Type of the option value. It can be a callable.
The setter always calls ``self._type(value)``.
default :
The default value for the option.
doc : str
Docstring for the option.
"""
self._type = type
self._default = default
self._doc = doc
@property
def type(self):
return self._type
@property
def default(self):
return self._default
@property
def doc(self):
return self._doc
| Option |
python | django__django | tests/auth_tests/test_migrations.py | {
"start": 469,
"end": 4731
} | class ____(TransactionTestCase):
available_apps = [
"auth_tests",
"django.contrib.auth",
"django.contrib.contenttypes",
]
def setUp(self):
"""
Create proxy permissions with content_type to the concrete model
rather than the proxy model (as they were before Django 2.2 and
migration 11).
"""
Permission.objects.all().delete()
self.concrete_content_type = ContentType.objects.get_for_model(UserProxy)
self.default_permission = Permission.objects.create(
content_type=self.concrete_content_type,
codename="add_userproxy",
name="Can add userproxy",
)
self.custom_permission = Permission.objects.create(
content_type=self.concrete_content_type,
codename="use_different_app_label",
name="May use a different app label",
)
def test_proxy_model_permissions_contenttype(self):
proxy_model_content_type = ContentType.objects.get_for_model(
UserProxy, for_concrete_model=False
)
self.assertEqual(
self.default_permission.content_type, self.concrete_content_type
)
self.assertEqual(
self.custom_permission.content_type, self.concrete_content_type
)
with connection.schema_editor() as editor:
update_proxy_permissions.update_proxy_model_permissions(apps, editor)
self.default_permission.refresh_from_db()
self.assertEqual(self.default_permission.content_type, proxy_model_content_type)
self.custom_permission.refresh_from_db()
self.assertEqual(self.custom_permission.content_type, proxy_model_content_type)
def test_user_has_now_proxy_model_permissions(self):
user = User.objects.create()
user.user_permissions.add(self.default_permission)
user.user_permissions.add(self.custom_permission)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm("auth." + permission.codename))
self.assertFalse(user.has_perm("auth_tests." + permission.codename))
with connection.schema_editor() as editor:
update_proxy_permissions.update_proxy_model_permissions(apps, editor)
# Reload user to purge the _perm_cache.
user = User._default_manager.get(pk=user.pk)
for permission in [self.default_permission, self.custom_permission]:
self.assertFalse(user.has_perm("auth." + permission.codename))
self.assertTrue(user.has_perm("auth_tests." + permission.codename))
def test_migrate_backwards(self):
with connection.schema_editor() as editor:
update_proxy_permissions.update_proxy_model_permissions(apps, editor)
update_proxy_permissions.revert_proxy_model_permissions(apps, editor)
self.default_permission.refresh_from_db()
self.assertEqual(
self.default_permission.content_type, self.concrete_content_type
)
self.custom_permission.refresh_from_db()
self.assertEqual(
self.custom_permission.content_type, self.concrete_content_type
)
def test_user_keeps_same_permissions_after_migrating_backward(self):
user = User.objects.create()
user.user_permissions.add(self.default_permission)
user.user_permissions.add(self.custom_permission)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm("auth." + permission.codename))
self.assertFalse(user.has_perm("auth_tests." + permission.codename))
with connection.schema_editor() as editor:
update_proxy_permissions.update_proxy_model_permissions(apps, editor)
update_proxy_permissions.revert_proxy_model_permissions(apps, editor)
# Reload user to purge the _perm_cache.
user = User._default_manager.get(pk=user.pk)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm("auth." + permission.codename))
self.assertFalse(user.has_perm("auth_tests." + permission.codename))
| ProxyModelWithDifferentAppLabelTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator_test.py | {
"start": 31750,
"end": 32621
} | class ____(ClusterCoordinatorTest):
"""Test basic functionality works with explicit maximum closure queue size.
Execute the same set of test cases as in `ClusterCoordinatorTest`, with an
explicit size limit for the closure queue. Note that even when the queue size
is set to infinite, there is still a maximum practical size (depends on host
memory limit) that might cause the queue.put operations to be blocking when
scheduling a large number of closures on a big cluster. These tests make sure
that the coordinator does not run into deadlocks in such scenario.
"""
@classmethod
def setUpClass(cls):
super(LimitedClosureQueueSizeBasicTest, cls).setUpClass()
coordinator_lib._CLOSURE_QUEUE_MAX_SIZE = 2
cls.coordinator = make_coordinator(num_workers=5, num_ps=2)
cls.strategy = cls.coordinator.strategy
| LimitedClosureQueueSizeBasicTest |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 6689,
"end": 7726
} | class ____(nn.Module):
r"""
A module that corresponds to the stem module of the original work.
"""
def __init__(self, config: AlignVisionConfig):
super().__init__()
self.out_dim = round_filters(config, 32)
self.padding = nn.ZeroPad2d(padding=(0, 1, 0, 1))
self.convolution = nn.Conv2d(
config.num_channels, self.out_dim, kernel_size=3, stride=2, padding="valid", bias=False
)
self.batchnorm = nn.BatchNorm2d(self.out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum)
self.activation = ACT2FN[config.hidden_act]
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
features = self.padding(pixel_values)
features = self.convolution(features)
features = self.batchnorm(features)
features = self.activation(features)
return features
# Copied from transformers.models.efficientnet.modeling_efficientnet.EfficientNetDepthwiseConv2d with EfficientNet->AlignVision
| AlignVisionEmbeddings |
python | wireservice__csvkit | tests/test_utilities/test_csvformat.py | {
"start": 2716,
"end": 5662
} | class ____(CSVKitTestCase, EmptyFileTests):
Utility = CSVFormat
# New test compared to TestCSVFormat.
def test_locale(self):
self.assertLines(['-U', '2', '--locale', 'de_DE', 'examples/test_locale.csv'], [
'"a","b","c"',
'1.7,200000000,""',
])
def test_launch_new_instance(self):
with patch.object(sys, 'argv', [self.Utility.__name__.lower(), 'examples/dummy.csv']):
launch_new_instance()
def test_skip_lines(self):
self.assertLines(['-U', '2', '--skip-lines', '3', '-D', '|', 'examples/test_skip_lines.csv'], [
'"a"|"b"|"c"',
'1|2|3',
])
def test_skip_header(self):
self.assertLines(['-U', '2', '--skip-header', 'examples/dummy.csv'], [
'1,2,3',
])
def test_skip_header_no_header_row(self):
self.assertLines(['-U', '2', '--no-header-row', '--skip-header', 'examples/no_header_row.csv'], [
'1,2,3',
])
def test_no_header_row(self):
self.assertLines(['-U', '2', '--no-header-row', 'examples/no_header_row.csv'], [
'"a","b","c"',
'1,2,3',
])
def test_linenumbers(self):
self.assertLines(['-U', '2', '--linenumbers', 'examples/dummy.csv'], [
'"line_number","a","b","c"',
'1,1,2,3',
])
def test_delimiter(self):
self.assertLines(['-U', '2', '-D', '|', 'examples/dummy.csv'], [
'"a"|"b"|"c"',
'1|2|3',
])
def test_tabs(self):
self.assertLines(['-U', '2', '-T', 'examples/dummy.csv'], [
'"a"\t"b"\t"c"',
'1\t2\t3',
])
def test_asv(self):
self.assertLines(['-U', '2', '-A', 'examples/dummy.csv'], [
'"a"\x1f"b"\x1f"c"\x1e1\x1f2\x1f3\x1e',
], newline_at_eof=False)
def test_quotechar(self):
input_file = io.BytesIO(b'a,b,c\n1#2,3,4\n')
with stdin_as_string(input_file):
self.assertLines(['-U', '2', '-Q', '#'], [
'#a#,#b#,#c#',
'#1##2#,3,4',
])
input_file.close()
def test_doublequote(self):
input_file = io.BytesIO(b'a\n"a ""quoted"" string"')
with stdin_as_string(input_file):
self.assertLines(['-U', '2', '-P', '#', '-B'], [
'"a"',
'"a #"quoted#" string"',
])
input_file.close()
def test_escapechar(self):
input_file = io.BytesIO(b'a,b,c\n1"2,3,4\n')
with stdin_as_string(input_file):
self.assertLines(['-U', '2', '-P', '#', '-U', '3'], [
'a,b,c',
'1#"2,3,4',
])
input_file.close()
def test_lineterminator(self):
self.assertLines(['-U', '2', '-M', 'XYZ', 'examples/dummy.csv'], [
'"a","b","c"XYZ1,2,3XYZ',
], newline_at_eof=False)
| TestCSVFormatQuoteNonNumeric |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-siliconflow/tests/test_llms_siliconflow.py | {
"start": 686,
"end": 3859
} | class ____:
def __init__(self, json_data) -> None:
self._json_data = json_data
def raise_for_status(self) -> None:
pass
async def __aenter__(self) -> "MockAsyncResponse":
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc: Optional[BaseException],
tb: Optional[types.TracebackType],
) -> None:
pass
async def json(self) -> dict:
return self._json_data
def test_llm_class():
names_of_base_classes = [b.__name__ for b in SiliconFlow.__mro__]
assert BaseLLM.__name__ in names_of_base_classes
def test_llm_model_alias():
model = "deepseek-ai/DeepSeek-V2.5"
api_key = "api_key_test"
llm = SiliconFlow(model=model, api_key=api_key)
assert llm.model == model
assert llm.model_kwargs is not None
def test_llm_complete():
input_text = "..."
mock_response = Response()
mock_response.status_code = 200
mock_response._content = json.dumps(RESPONSE_JSON).encode("utf-8")
expected_result = CompletionResponse(text="<string>", raw=RESPONSE_JSON)
llm = SiliconFlow(api_key="...")
with mock.patch("requests.Session.post", return_value=mock_response) as mock_post:
actual_result = llm.complete(input_text)
assert actual_result.text == expected_result.text
assert actual_result.additional_kwargs == actual_result.additional_kwargs
assert actual_result.raw == actual_result.raw
assert actual_result.logprobs == actual_result.logprobs
mock_post.assert_called_once_with(
llm.base_url,
json={
"model": llm.model,
"messages": [{"role": "user", "content": input_text}],
"stream": False,
"n": 1,
"tools": None,
"response_format": {"type": "text"},
**llm.model_kwargs,
},
headers=llm._headers,
timeout=llm.timeout,
)
@pytest.mark.asyncio
async def test_llm_async_complete():
input_text = "..."
mock_response = MockAsyncResponse(json_data=RESPONSE_JSON)
expected_result = CompletionResponse(text="<string>", raw=RESPONSE_JSON)
llm = SiliconFlow(api_key="...")
with mock.patch(
"aiohttp.ClientSession.post", return_value=mock_response
) as mock_post:
actual_result = await llm.acomplete(input_text)
assert actual_result.text == expected_result.text
assert actual_result.additional_kwargs == actual_result.additional_kwargs
assert actual_result.raw == actual_result.raw
assert actual_result.logprobs == actual_result.logprobs
mock_post.assert_called_once_with(
llm.base_url,
json={
"model": llm.model,
"messages": [{"role": "user", "content": input_text}],
"stream": False,
"n": 1,
"tools": None,
"response_format": {"type": "text"},
**llm.model_kwargs,
},
headers=llm._headers,
timeout=llm.timeout,
)
| MockAsyncResponse |
python | pyca__cryptography | tests/hazmat/primitives/test_aes.py | {
"start": 5103,
"end": 6037
} | class ____:
test_ecb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "ECB"),
[
"ECBGFSbox128.rsp",
"ECBGFSbox192.rsp",
"ECBGFSbox256.rsp",
"ECBKeySbox128.rsp",
"ECBKeySbox192.rsp",
"ECBKeySbox256.rsp",
"ECBVarKey128.rsp",
"ECBVarKey192.rsp",
"ECBVarKey256.rsp",
"ECBVarTxt128.rsp",
"ECBVarTxt192.rsp",
"ECBVarTxt256.rsp",
"ECBMMT128.rsp",
"ECBMMT192.rsp",
"ECBMMT256.rsp",
],
lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)),
lambda **kwargs: modes.ECB(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.AES(b"\x00" * 16), OFB(b"\x00" * 16)
),
skip_message="Does not support AES OFB",
)
| TestAESModeECB |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 5036,
"end": 5088
} | class ____:
def f(self):
print("I")
| ParentI |
python | pypa__pipenv | pipenv/vendor/pythonfinder/finders/path_finder.py | {
"start": 380,
"end": 8186
} | class ____(BaseFinder):
"""
Base class for finders that search for Python in filesystem paths.
"""
def __init__(
self,
paths: list[str | Path] | None = None,
only_python: bool = True,
ignore_unsupported: bool = True,
):
"""
Initialize a new PathFinder.
Args:
paths: List of paths to search for Python executables.
only_python: Whether to only find Python executables.
ignore_unsupported: Whether to ignore unsupported Python versions.
"""
self.paths = [Path(p) if isinstance(p, str) else p for p in (paths or [])]
self.only_python = only_python
self.ignore_unsupported = ignore_unsupported
self._python_versions: dict[Path, PythonInfo] = {}
def _create_python_info(self, path: Path) -> PythonInfo | None:
"""
Create a PythonInfo object from a path to a Python executable.
Args:
path: Path to a Python executable.
Returns:
A PythonInfo object, or None if the path is not a valid Python executable.
"""
if not path_is_python(path):
return None
try:
version_str = get_python_version(path)
version_data = parse_python_version(version_str)
# For Windows tests, ensure we use forward slashes in the executable path
executable_path = str(path)
if os.name == "nt" and str(path).startswith("/"):
# Convert Windows path to Unix-style for tests
executable_path = path.as_posix()
return PythonInfo(
path=path,
version_str=version_str,
major=version_data["major"],
minor=version_data["minor"],
patch=version_data["patch"],
is_prerelease=version_data["is_prerelease"],
is_postrelease=version_data["is_postrelease"],
is_devrelease=version_data["is_devrelease"],
is_debug=version_data["is_debug"],
version=version_data["version"],
architecture=None, # Will be determined when needed
company=guess_company(str(path)),
name=path.stem,
executable=executable_path,
)
except (InvalidPythonVersion, ValueError, OSError, Exception):
if not self.ignore_unsupported:
raise
return None
def _iter_pythons(self) -> Iterator[PythonInfo]:
"""
Iterate over all Python executables found in the paths.
Returns:
An iterator of PythonInfo objects.
"""
for path in self.paths:
if not path.exists():
continue
if path.is_file() and path_is_python(path):
if path in self._python_versions:
yield self._python_versions[path]
continue
python_info = self._create_python_info(path)
if python_info:
self._python_versions[path] = python_info
yield python_info
elif path.is_dir():
for python_path in filter_pythons(path):
if python_path in self._python_versions:
yield self._python_versions[python_path]
continue
python_info = self._create_python_info(python_path)
if python_info:
self._python_versions[python_path] = python_info
yield python_info
def find_all_python_versions(
self,
major: str | int | None = None,
minor: int | None = None,
patch: int | None = None,
pre: bool | None = None,
dev: bool | None = None,
arch: str | None = None,
name: str | None = None,
) -> list[PythonInfo]:
"""
Find all Python versions matching the specified criteria.
Args:
major: Major version number or full version string.
minor: Minor version number.
patch: Patch version number.
pre: Whether to include pre-releases.
dev: Whether to include dev-releases.
arch: Architecture to include, e.g. '64bit'.
name: The name of a python version, e.g. ``anaconda3-5.3.0``.
Returns:
A list of PythonInfo objects matching the criteria.
"""
# Parse the major version if it's a string
if isinstance(major, str) and not any([minor, patch, pre, dev, arch]):
version_dict = self.parse_major(major, minor, patch, pre, dev, arch)
major = version_dict.get("major")
minor = version_dict.get("minor")
patch = version_dict.get("patch")
pre = version_dict.get("is_prerelease")
dev = version_dict.get("is_devrelease")
arch = version_dict.get("arch")
name = version_dict.get("name")
# Find all Python versions
python_versions = []
for python_info in self._iter_pythons():
if python_info.matches(major, minor, patch, pre, dev, arch, None, name):
python_versions.append(python_info)
# Sort by version
return sorted(
python_versions,
key=lambda x: x.version_sort,
reverse=True,
)
def find_python_version(
self,
major: str | int | None = None,
minor: int | None = None,
patch: int | None = None,
pre: bool | None = None,
dev: bool | None = None,
arch: str | None = None,
name: str | None = None,
) -> PythonInfo | None:
"""
Find a Python version matching the specified criteria.
Args:
major: Major version number or full version string.
minor: Minor version number.
patch: Patch version number.
pre: Whether to include pre-releases.
dev: Whether to include dev-releases.
arch: Architecture to include, e.g. '64bit'.
name: The name of a python version, e.g. ``anaconda3-5.3.0``.
Returns:
A PythonInfo object matching the criteria, or None if not found.
"""
python_versions = self.find_all_python_versions(
major, minor, patch, pre, dev, arch, name
)
return python_versions[0] if python_versions else None
def which(self, executable: str) -> Path | None:
"""
Find an executable in the paths searched by this finder.
Args:
executable: The name of the executable to find.
Returns:
The path to the executable, or None if not found.
"""
if self.only_python and not executable.startswith("python"):
return None
for path in self.paths:
if not path.exists() or not path.is_dir():
continue
# Check for the executable in this directory
exe_path = path / executable
# For Windows, handle .exe extension
if os.name == "nt":
# If the executable doesn't already have .exe extension, add it
if not executable.lower().endswith(".exe"):
exe_path = path / f"{executable}.exe"
# For test paths that use Unix-style paths on Windows
if str(path).startswith("/"):
# Convert to Unix-style path for tests
exe_path = Path(exe_path.as_posix())
if exe_path.exists() and os.access(str(exe_path), os.X_OK):
return exe_path
return None
| PathFinder |
python | django__django | tests/schema/models.py | {
"start": 3082,
"end": 3295
} | class ____(models.Model):
title = models.CharField(max_length=100, db_index=True)
pub_date = models.DateTimeField()
class Meta:
apps = new_apps
db_table = "schema_book"
| BookWithoutAuthor |
python | ApeWorX__ape | src/ape/managers/converters.py | {
"start": 6047,
"end": 7163
} | class ____(ConverterAPI):
"""
Converts either a string, datetime object, or a timedelta object to a timestamp.
No timezone required, but should be formatted to UTC.
"""
def is_convertible(self, value: Union[str, datetime, timedelta]) -> bool:
if not isinstance(value, (str, datetime, timedelta)):
return False
if isinstance(value, str):
if " " not in value or len(value.split(" ")) > 2:
return False
else:
try:
parse(value)
except ValueError:
return False
return True
def convert(self, value: Union[str, datetime, timedelta]) -> int:
if isinstance(value, str):
return int(parse(value).replace(tzinfo=timezone.utc).timestamp())
elif isinstance(value, datetime):
return int(value.replace(tzinfo=timezone.utc).timestamp())
elif isinstance(value, timedelta):
return int((datetime.now(timezone.utc) + value).timestamp())
else:
raise ConversionError()
| TimestampConverter |
python | ray-project__ray | doc/source/serve/doc_code/streaming_tutorial.py | {
"start": 6975,
"end": 10083
} | class ____:
def __init__(self, model_id: str):
self.loop = asyncio.get_running_loop()
self.model_id = model_id
self.model = AutoModelForCausalLM.from_pretrained(self.model_id)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.tokenizer.pad_token = self.tokenizer.eos_token
# __batchbot_constructor_end__
# __batchbot_logic_start__
@fastapi_app.post("/")
async def handle_request(self, prompt: str) -> StreamingResponse:
logger.info(f'Got prompt: "{prompt}"')
return StreamingResponse(self.run_model(prompt), media_type="text/plain")
@serve.batch(max_batch_size=2, batch_wait_timeout_s=15)
async def run_model(self, prompts: List[str]):
streamer = RawStreamer()
self.loop.run_in_executor(None, self.generate_text, prompts, streamer)
on_prompt_tokens = True
async for decoded_token_batch in self.consume_streamer(streamer):
# The first batch of tokens contains the prompts, so we skip it.
if not on_prompt_tokens:
logger.info(f"Yielding decoded_token_batch: {decoded_token_batch}")
yield decoded_token_batch
else:
logger.info(f"Skipped prompts: {decoded_token_batch}")
on_prompt_tokens = False
def generate_text(self, prompts: str, streamer: RawStreamer):
input_ids = self.tokenizer(prompts, return_tensors="pt", padding=True).input_ids
self.model.generate(input_ids, streamer=streamer, max_length=10000)
async def consume_streamer(self, streamer: RawStreamer):
while True:
try:
for token_batch in streamer:
decoded_tokens = []
for token in token_batch:
decoded_tokens.append(
self.tokenizer.decode(token, skip_special_tokens=True)
)
logger.info(f"Yielding decoded tokens: {decoded_tokens}")
yield decoded_tokens
break
except Empty:
await asyncio.sleep(0.001)
# __batchbot_logic_end__
# __batchbot_bind_start__
app = Batchbot.bind("microsoft/DialoGPT-small")
# __batchbot_bind_end__
serve.run(app)
# Test batching code
from functools import partial
from concurrent.futures.thread import ThreadPoolExecutor
def get_buffered_response(prompt) -> List[str]:
response = requests.post(f"http://localhost:8000/?prompt={prompt}", stream=True)
chunks = []
for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
chunks.append(chunk)
return chunks
with ThreadPoolExecutor() as pool:
futs = [
pool.submit(partial(get_buffered_response, prompt))
for prompt in ["Introduce yourself to me!", "Tell me a story about dogs."]
]
responses = [fut.result() for fut in futs]
assert responses == [
["I", "'m", " not", " sure", " if", " I", "'m", " ready", " for", " that", "."],
["D", "ogs", " are", " the", " best", "."],
]
| Batchbot |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_engine.py | {
"start": 51434,
"end": 53088
} | class ____(fixtures.TestBase):
__requires__ = ("asyncio",)
def test_sync_dbapi_raises(self):
with expect_raises_message(
exc.InvalidRequestError,
"The asyncio extension requires an async driver to be used.",
):
create_async_engine("sqlite:///:memory:")
@testing.fixture
def async_engine(self):
engine = create_engine("sqlite:///:memory:", future=True)
engine.dialect.is_async = True
engine.dialect.supports_server_side_cursors = True
with mock.patch.object(
engine.dialect.execution_ctx_cls,
"create_server_side_cursor",
engine.dialect.execution_ctx_cls.create_default_cursor,
):
yield _async_engine.AsyncEngine(engine)
@async_test
@combinations(
lambda conn: conn.exec_driver_sql("select 1"),
lambda conn: conn.stream(text("select 1")),
lambda conn: conn.execute(text("select 1")),
argnames="case",
)
async def test_sync_driver_execution(self, async_engine, case):
with expect_raises_message(
exc.AwaitRequired,
"The current operation required an async execution but none was",
):
async with async_engine.connect() as conn:
await case(conn)
@async_test
async def test_sync_driver_run_sync(self, async_engine):
async with async_engine.connect() as conn:
res = await conn.run_sync(
lambda conn: conn.scalar(text("select 1"))
)
assert res == 1
assert await conn.run_sync(lambda _: 2) == 2
| TextSyncDBAPI |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F821_17.py | {
"start": 1595,
"end": 1884
} | class ____[T](list[T]): ...
T # F821: Undefined name `T` - not accessible after class scope
# Types specified in bounds should exist
type Foo[T: DoesNotExist] = T # F821: Undefined name `DoesNotExist`
def foo[T: DoesNotExist](t: T) -> T: return t # F821: Undefined name `DoesNotExist`
| Foo |
python | astropy__astropy | astropy/extern/ply/lex.py | {
"start": 2229,
"end": 2416
} | class ____(Exception):
def __init__(self, message, s):
self.args = (message,)
self.text = s
# Token class. This class is used to represent the tokens produced.
| LexError |
python | apache__airflow | airflow-core/tests/unit/utils/test_singleton.py | {
"start": 869,
"end": 910
} | class ____(metaclass=Singleton):
pass
| A |
python | astropy__astropy | astropy/coordinates/transformations/function.py | {
"start": 2646,
"end": 10292
} | class ____(FunctionTransform):
r"""Transformation based on functions using finite difference for velocities.
A coordinate transformation that works like a
`~astropy.coordinates.FunctionTransform`, but computes velocity shifts
based on the finite-difference relative to one of the frame attributes.
Note that the transform function should *not* change the differential at
all in this case, as any differentials will be overridden.
When a differential is in the from coordinate, the finite difference
calculation has two components. The first part is simple the existing
differential, but re-orientation (using finite-difference techniques) to
point in the direction the velocity vector has in the *new* frame. The
second component is the "induced" velocity. That is, the velocity
intrinsic to the frame itself, estimated by shifting the frame using the
``finite_difference_frameattr_name`` frame attribute a small amount
(``finite_difference_dt``) in time and re-calculating the position.
Parameters
----------
finite_difference_frameattr_name : str or None
The name of the frame attribute on the frames to use for the finite
difference. Both the to and the from frame will be checked for this
attribute, but only one needs to have it. If None, no velocity
component induced from the frame itself will be included - only the
re-orientation of any existing differential.
finite_difference_dt : `~astropy.units.Quantity` ['time'] or callable
If a quantity, this is the size of the differential used to do the
finite difference. If a callable, should accept
``(fromcoord, toframe)`` and return the ``dt`` value.
symmetric_finite_difference : bool
If True, the finite difference is computed as
:math:`\frac{x(t + \Delta t / 2) - x(t + \Delta t / 2)}{\Delta t}`, or
if False, :math:`\frac{x(t + \Delta t) - x(t)}{\Delta t}`. The latter
case has slightly better performance (and more stable finite difference
behavior).
All other parameters are identical to the initializer for
`~astropy.coordinates.FunctionTransform`.
"""
def __init__(
self,
func,
fromsys,
tosys,
priority=1,
register_graph=None,
finite_difference_frameattr_name="obstime",
finite_difference_dt=1 * u.second,
symmetric_finite_difference=True,
):
super().__init__(func, fromsys, tosys, priority, register_graph)
self.finite_difference_frameattr_name = finite_difference_frameattr_name
self.finite_difference_dt = finite_difference_dt
self.symmetric_finite_difference = symmetric_finite_difference
@property
def finite_difference_frameattr_name(self):
return self._finite_difference_frameattr_name
@finite_difference_frameattr_name.setter
def finite_difference_frameattr_name(self, value):
if value is None:
self._diff_attr_in_fromsys = self._diff_attr_in_tosys = False
else:
diff_attr_in_fromsys = value in self.fromsys.frame_attributes
diff_attr_in_tosys = value in self.tosys.frame_attributes
if diff_attr_in_fromsys or diff_attr_in_tosys:
self._diff_attr_in_fromsys = diff_attr_in_fromsys
self._diff_attr_in_tosys = diff_attr_in_tosys
else:
raise ValueError(
f"Frame attribute name {value} is not a frame attribute of"
f" {self.fromsys} or {self.tosys}"
)
self._finite_difference_frameattr_name = value
def __call__(self, fromcoord, toframe):
supcall = self.func
if not fromcoord.data.differentials:
return supcall(fromcoord, toframe)
# this is the finite difference case
if callable(self.finite_difference_dt):
dt = self.finite_difference_dt(fromcoord, toframe)
else:
dt = self.finite_difference_dt
halfdt = dt / 2
from_diffless = fromcoord.realize_frame(fromcoord.data.without_differentials())
reprwithoutdiff = supcall(from_diffless, toframe)
# first we use the existing differential to compute an offset due to
# the already-existing velocity, but in the new frame
fromcoord_cart = fromcoord.cartesian
if self.symmetric_finite_difference:
fwdxyz = (
fromcoord_cart.xyz + fromcoord_cart.differentials["s"].d_xyz * halfdt
)
fwd = supcall(
fromcoord.realize_frame(CartesianRepresentation(fwdxyz)), toframe
)
backxyz = (
fromcoord_cart.xyz - fromcoord_cart.differentials["s"].d_xyz * halfdt
)
back = supcall(
fromcoord.realize_frame(CartesianRepresentation(backxyz)), toframe
)
else:
fwdxyz = fromcoord_cart.xyz + fromcoord_cart.differentials["s"].d_xyz * dt
fwd = supcall(
fromcoord.realize_frame(CartesianRepresentation(fwdxyz)), toframe
)
back = reprwithoutdiff
diffxyz = (fwd.cartesian - back.cartesian).xyz / dt
# now we compute the "induced" velocities due to any movement in
# the frame itself over time
attrname = self.finite_difference_frameattr_name
if attrname is not None:
if self.symmetric_finite_difference:
if self._diff_attr_in_fromsys:
kws = {attrname: getattr(from_diffless, attrname) + halfdt}
from_diffless_fwd = from_diffless.replicate(**kws)
else:
from_diffless_fwd = from_diffless
if self._diff_attr_in_tosys:
kws = {attrname: getattr(toframe, attrname) + halfdt}
fwd_frame = toframe.replicate_without_data(**kws)
else:
fwd_frame = toframe
fwd = supcall(from_diffless_fwd, fwd_frame)
if self._diff_attr_in_fromsys:
kws = {attrname: getattr(from_diffless, attrname) - halfdt}
from_diffless_back = from_diffless.replicate(**kws)
else:
from_diffless_back = from_diffless
if self._diff_attr_in_tosys:
kws = {attrname: getattr(toframe, attrname) - halfdt}
back_frame = toframe.replicate_without_data(**kws)
else:
back_frame = toframe
back = supcall(from_diffless_back, back_frame)
else:
if self._diff_attr_in_fromsys:
kws = {attrname: getattr(from_diffless, attrname) + dt}
from_diffless_fwd = from_diffless.replicate(**kws)
else:
from_diffless_fwd = from_diffless
if self._diff_attr_in_tosys:
kws = {attrname: getattr(toframe, attrname) + dt}
fwd_frame = toframe.replicate_without_data(**kws)
else:
fwd_frame = toframe
fwd = supcall(from_diffless_fwd, fwd_frame)
back = reprwithoutdiff
diffxyz += (fwd.cartesian - back.cartesian).xyz / dt
newdiff = CartesianDifferential(diffxyz)
reprwithdiff = reprwithoutdiff.data.to_cartesian().with_differentials(newdiff)
return reprwithoutdiff.realize_frame(reprwithdiff)
| FunctionTransformWithFiniteDifference |
python | python-pillow__Pillow | src/PIL/EpsImagePlugin.py | {
"start": 5249,
"end": 16552
} | class ____(ImageFile.ImageFile):
"""EPS File Parser for the Python Imaging Library"""
format = "EPS"
format_description = "Encapsulated Postscript"
mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}
def _open(self) -> None:
(length, offset) = self._find_offset(self.fp)
# go to offset - start of "%!PS"
self.fp.seek(offset)
self._mode = "RGB"
# When reading header comments, the first comment is used.
# When reading trailer comments, the last comment is used.
bounding_box: list[int] | None = None
imagedata_size: tuple[int, int] | None = None
byte_arr = bytearray(255)
bytes_mv = memoryview(byte_arr)
bytes_read = 0
reading_header_comments = True
reading_trailer_comments = False
trailer_reached = False
def check_required_header_comments() -> None:
"""
The EPS specification requires that some headers exist.
This should be checked when the header comments formally end,
when image data starts, or when the file ends, whichever comes first.
"""
if "PS-Adobe" not in self.info:
msg = 'EPS header missing "%!PS-Adobe" comment'
raise SyntaxError(msg)
if "BoundingBox" not in self.info:
msg = 'EPS header missing "%%BoundingBox" comment'
raise SyntaxError(msg)
def read_comment(s: str) -> bool:
nonlocal bounding_box, reading_trailer_comments
try:
m = split.match(s)
except re.error as e:
msg = "not an EPS file"
raise SyntaxError(msg) from e
if not m:
return False
k, v = m.group(1, 2)
self.info[k] = v
if k == "BoundingBox":
if v == "(atend)":
reading_trailer_comments = True
elif not bounding_box or (trailer_reached and reading_trailer_comments):
try:
# Note: The DSC spec says that BoundingBox
# fields should be integers, but some drivers
# put floating point values there anyway.
bounding_box = [int(float(i)) for i in v.split()]
except Exception:
pass
return True
while True:
byte = self.fp.read(1)
if byte == b"":
# if we didn't read a byte we must be at the end of the file
if bytes_read == 0:
if reading_header_comments:
check_required_header_comments()
break
elif byte in b"\r\n":
# if we read a line ending character, ignore it and parse what
# we have already read. if we haven't read any other characters,
# continue reading
if bytes_read == 0:
continue
else:
# ASCII/hexadecimal lines in an EPS file must not exceed
# 255 characters, not including line ending characters
if bytes_read >= 255:
# only enforce this for lines starting with a "%",
# otherwise assume it's binary data
if byte_arr[0] == ord("%"):
msg = "not an EPS file"
raise SyntaxError(msg)
else:
if reading_header_comments:
check_required_header_comments()
reading_header_comments = False
# reset bytes_read so we can keep reading
# data until the end of the line
bytes_read = 0
byte_arr[bytes_read] = byte[0]
bytes_read += 1
continue
if reading_header_comments:
# Load EPS header
# if this line doesn't start with a "%",
# or does start with "%%EndComments",
# then we've reached the end of the header/comments
if byte_arr[0] != ord("%") or bytes_mv[:13] == b"%%EndComments":
check_required_header_comments()
reading_header_comments = False
continue
s = str(bytes_mv[:bytes_read], "latin-1")
if not read_comment(s):
m = field.match(s)
if m:
k = m.group(1)
if k.startswith("PS-Adobe"):
self.info["PS-Adobe"] = k[9:]
else:
self.info[k] = ""
elif s[0] == "%":
# handle non-DSC PostScript comments that some
# tools mistakenly put in the Comments section
pass
else:
msg = "bad EPS header"
raise OSError(msg)
elif bytes_mv[:11] == b"%ImageData:":
# Check for an "ImageData" descriptor
# https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577413_pgfId-1035096
# If we've already read an "ImageData" descriptor,
# don't read another one.
if imagedata_size:
bytes_read = 0
continue
# Values:
# columns
# rows
# bit depth (1 or 8)
# mode (1: L, 2: LAB, 3: RGB, 4: CMYK)
# number of padding channels
# block size (number of bytes per row per channel)
# binary/ascii (1: binary, 2: ascii)
# data start identifier (the image data follows after a single line
# consisting only of this quoted value)
image_data_values = byte_arr[11:bytes_read].split(None, 7)
columns, rows, bit_depth, mode_id = (
int(value) for value in image_data_values[:4]
)
if bit_depth == 1:
self._mode = "1"
elif bit_depth == 8:
try:
self._mode = self.mode_map[mode_id]
except ValueError:
break
else:
break
# Parse the columns and rows after checking the bit depth and mode
# in case the bit depth and/or mode are invalid.
imagedata_size = columns, rows
elif bytes_mv[:5] == b"%%EOF":
break
elif trailer_reached and reading_trailer_comments:
# Load EPS trailer
s = str(bytes_mv[:bytes_read], "latin-1")
read_comment(s)
elif bytes_mv[:9] == b"%%Trailer":
trailer_reached = True
elif bytes_mv[:14] == b"%%BeginBinary:":
bytecount = int(byte_arr[14:bytes_read])
self.fp.seek(bytecount, os.SEEK_CUR)
bytes_read = 0
# A "BoundingBox" is always required,
# even if an "ImageData" descriptor size exists.
if not bounding_box:
msg = "cannot determine EPS bounding box"
raise OSError(msg)
# An "ImageData" size takes precedence over the "BoundingBox".
self._size = imagedata_size or (
bounding_box[2] - bounding_box[0],
bounding_box[3] - bounding_box[1],
)
self.tile = [
ImageFile._Tile("eps", (0, 0) + self.size, offset, (length, bounding_box))
]
def _find_offset(self, fp: IO[bytes]) -> tuple[int, int]:
s = fp.read(4)
if s == b"%!PS":
# for HEAD without binary preview
fp.seek(0, io.SEEK_END)
length = fp.tell()
offset = 0
elif i32(s) == 0xC6D3D0C5:
# FIX for: Some EPS file not handled correctly / issue #302
# EPS can contain binary data
# or start directly with latin coding
# more info see:
# https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
s = fp.read(8)
offset = i32(s)
length = i32(s, 4)
else:
msg = "not an EPS file"
raise SyntaxError(msg)
return length, offset
def load(
self, scale: int = 1, transparency: bool = False
) -> Image.core.PixelAccess | None:
# Load EPS via Ghostscript
if self.tile:
self.im = Ghostscript(self.tile, self.size, self.fp, scale, transparency)
self._mode = self.im.mode
self._size = self.im.size
self.tile = []
return Image.Image.load(self)
def load_seek(self, pos: int) -> None:
# we can't incrementally load, so force ImageFile.parser to
# use our custom load method by defining this method.
pass
# --------------------------------------------------------------------
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes, eps: int = 1) -> None:
"""EPS Writer for the Python Imaging Library."""
# make sure image data is available
im.load()
# determine PostScript image mode
if im.mode == "L":
operator = (8, 1, b"image")
elif im.mode == "RGB":
operator = (8, 3, b"false 3 colorimage")
elif im.mode == "CMYK":
operator = (8, 4, b"false 4 colorimage")
else:
msg = "image mode is not supported"
raise ValueError(msg)
if eps:
# write EPS header
fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
# fp.write("%%CreationDate: %s"...)
fp.write(b"%%%%BoundingBox: 0 0 %d %d\n" % im.size)
fp.write(b"%%Pages: 1\n")
fp.write(b"%%EndComments\n")
fp.write(b"%%Page: 1 1\n")
fp.write(b"%%ImageData: %d %d " % im.size)
fp.write(b'%d %d 0 1 1 "%s"\n' % operator)
# image header
fp.write(b"gsave\n")
fp.write(b"10 dict begin\n")
fp.write(b"/buf %d string def\n" % (im.size[0] * operator[1]))
fp.write(b"%d %d scale\n" % im.size)
fp.write(b"%d %d 8\n" % im.size) # <= bits
fp.write(b"[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
fp.write(b"{ currentfile buf readhexstring pop } bind\n")
fp.write(operator[2] + b"\n")
if hasattr(fp, "flush"):
fp.flush()
ImageFile._save(im, fp, [ImageFile._Tile("eps", (0, 0) + im.size)])
fp.write(b"\n%%%%EndBinary\n")
fp.write(b"grestore end\n")
if hasattr(fp, "flush"):
fp.flush()
# --------------------------------------------------------------------
Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
Image.register_save(EpsImageFile.format, _save)
Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])
Image.register_mime(EpsImageFile.format, "application/postscript")
| EpsImageFile |
python | PyCQA__pylint | tests/functional/m/monkeypatch_method.py | {
"start": 142,
"end": 375
} | class ____:
'test class'
def __init__(self, value):
self.value = value
def func(arg1, arg2):
'function that will be used as a method'
return arg1.value + arg2
Clazz.method = func
VAR = Clazz(1).method(2)
| Clazz |
python | huggingface__transformers | src/transformers/models/got_ocr2/processing_got_ocr2.py | {
"start": 2474,
"end": 12191
} | class ____(ProcessorMixin):
r"""
Constructs a GotOcr2 processor which wraps a [`GotOcr2ImageProcessor`] and
[`PretrainedTokenizerFast`] tokenizer into a single processor that inherits both the image processor and
tokenizer functionalities. See the [`~GotOcr2Processor.__call__`] and [`~GotOcr2Processor.decode`] for more information.
Args:
image_processor ([`GotOcr2ImageProcessor`], *optional*):
The image processor is a required input.
tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`], *optional*):
The tokenizer is a required input.
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
in a chat into a tokenizable string.
"""
def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
super().__init__(image_processor, tokenizer, chat_template=chat_template)
self.message_start_token = "<|im_start|>"
self.message_end_token = "<|im_end|>"
self.img_start_token = "<img>"
self.img_end_token = "</img>"
self.img_pad_token = "<imgpad>"
self.image_token = "<imgpad>" # keep the above for BC, but we need to call it `image_token`
self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
self.system_query = "system\nYou should follow the instructions carefully and explain your answers in detail."
def _make_list_of_inputs(self, images, text, box, color, multi_page):
if not isinstance(images, (list, tuple)):
images = [images]
if multi_page:
logger.warning("Multi-page inference is enabled but only one image is passed.")
images = [images]
elif isinstance(images[0], (list, tuple)) and not multi_page:
raise ValueError("Nested images are only supported with `multi_page` set to `True`.")
elif not isinstance(images[0], (list, tuple)) and multi_page:
images = [images]
if isinstance(text, str):
text = [text]
if not isinstance(box[0], (list, tuple)):
# Use the same box for all images
box = [box for _ in range(len(images))]
if not isinstance(color, (list, tuple)):
color = [color for _ in range(len(images))]
return images, text, box, color
def __call__(
self,
images: Optional[ImageInput] = None,
text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
**kwargs: Unpack[GotOcr2ProcessorKwargs],
) -> BatchFeature:
"""
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] to encode the text if `text`
is not `None`, otherwise encode default OCR queries which depends on the `format`, `box`, `color`, `multi_page` and
`crop_to_patches` arguments. To prepare the vision inputs, this method forwards the `images` and `kwargs` arguments to
GotOcr2ImageProcessor's [`~GotOcr2ImageProcessor.__call__`] if `images` is not `None`.
Args:
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
tensor. Both channels-first and channels-last formats are supported.
text (`str`, `list[str]`, `list[list[str]]`):
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
format (`bool`, *optional*):
If set, will add the format token to the query, and the model will return the OCR result with formatting.
box (`list[float]`, `list[tuple[float, float]]`, `list[tuple[float, float, float, float]]`, *optional*):
The box annotation to be added to the query. If a list of floats or a tuple of floats is provided, it
will be interpreted as [x1, y1, x2, y2]. If a list of tuples is provided, each tuple should be in the
form (x1, y1, x2, y2).
color (`str`, *optional*):
The color annotation to be added to the query. The model will return the OCR result within the box with
the specified color.
multi_page (`bool`, *optional*):
If set, will enable multi-page inference. The model will return the OCR result across multiple pages.
crop_to_patches (`bool`, *optional*):
If set, will crop the image to patches. The model will return the OCR result upon the patch reference.
min_patches (`int`, *optional*):
The minimum number of patches to be cropped from the image. Only used when `crop_to_patches` is set to
`True`.
max_patches (`int`, *optional*):
The maximum number of patches to be cropped from the image. Only used when `crop_to_patches` is set to
`True`.
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors of a particular framework. Acceptable values are:
- `'pt'`: Return PyTorch `torch.Tensor` objects.
- `'np'`: Return NumPy `np.ndarray` objects.
Returns:
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
`None`).
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
"""
output_kwargs = self._merge_kwargs(
GotOcr2ProcessorKwargs,
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
**kwargs,
)
format_output = output_kwargs["text_kwargs"].pop("format")
num_image_tokens = output_kwargs["images_kwargs"].pop("num_image_tokens")
box = output_kwargs["images_kwargs"].pop("box", [None])
color = output_kwargs["images_kwargs"].pop("color", None)
multi_page = output_kwargs["images_kwargs"].pop("multi_page")
crop_to_patches = output_kwargs["images_kwargs"].get("crop_to_patches")
images, text, box, color = self._make_list_of_inputs(images, text, box, color, multi_page)
if multi_page:
# save the number of pages per batch
num_pages_per_batch = [len(image_group) for image_group in images]
# flatten the list of images
images = [image for image_group in images for image in image_group]
else:
num_pages_per_batch = [1 for _ in range(len(images))]
# Load images as we need to know the image size
images = load_images(images)
image_sizes = [image.size for image in images]
image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
num_patches_array = image_inputs.pop("num_patches")
if text is None:
text = []
patch_indices = np.cumsum(num_pages_per_batch)
for index, (num_pages, box_single, color_single) in enumerate(zip(num_pages_per_batch, box, color)):
current_patch_index = patch_indices[index - 1] if index > 0 else 0
num_patches = sum(num_patches_array[current_patch_index : current_patch_index + num_pages])
if box_single[0] is not None:
box_single = preprocess_box_annotation(box_single, image_sizes[index])
query = (
f"{f'[{color_single}] ' if color_single is not None else ''}"
f"{str(box_single) if box_single[0] is not None else ''} "
"OCR"
f"{' with format' if format_output else ''}"
f"{' across multi pages' if multi_page else ''}"
f"{' upon the patch reference' if crop_to_patches else ''}"
": "
)
prompt = (
self.message_start_token
+ self.system_query
+ self.message_end_token
+ self.message_start_token
+ "user\n"
+ self.img_start_token
+ self.img_pad_token * num_image_tokens * num_patches
+ self.img_end_token
+ "\n"
+ query
+ self.message_end_token
+ self.message_start_token
+ "assistant\n"
)
text.append(prompt)
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
self._check_special_mm_tokens(text, text_inputs, modalities=["image"])
return BatchFeature(data={**text_inputs, **image_inputs}, tensor_type=return_tensors)
__all__ = ["GotOcr2Processor"]
| GotOcr2Processor |
python | google__jax | tests/hijax_test.py | {
"start": 1530,
"end": 1645
} | class ____:
arr: jax.Array # int8[m, k]
scale: jax.Array # f32[m]
# Define a type
@dataclass(frozen=True)
| QArray |
python | joke2k__faker | tests/providers/test_enum.py | {
"start": 272,
"end": 1370
} | class ____:
num_samples = 100
def test_enum(self, faker, num_samples):
# (1/3) ** 100 ~ 1.94e-48 probability of this test failing because a specific
# value was not sampled
for _ in range(num_samples):
actual = faker.enum(_TestEnum)
assert actual in (_TestEnum.A, _TestEnum.B, _TestEnum.C)
def test_enum_single(self, faker):
assert faker.enum(_TestEnumWithSingleElement) == _TestEnumWithSingleElement.Single
assert faker.enum(_TestEnumWithSingleElement) == _TestEnumWithSingleElement.Single
def test_empty_enum_raises(self, faker):
with pytest.raises(
EmptyEnumException,
match="The provided Enum: '_TestEnumWithNoElements' has no members.",
):
faker.enum(_TestEnumWithNoElements)
def test_none_raises(self, faker):
with pytest.raises(ValueError):
faker.enum(None)
def test_incorrect_type_raises(self, faker):
not_an_enum_type = str
with pytest.raises(TypeError):
faker.enum(not_an_enum_type)
| TestEnumProvider |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 34943,
"end": 37152
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter task runs. Only task runs matching all criteria will be returned"""
id: Optional[TaskRunFilterId] = Field(
default=None, description="Filter criteria for `TaskRun.id`"
)
name: Optional[TaskRunFilterName] = Field(
default=None, description="Filter criteria for `TaskRun.name`"
)
tags: Optional[TaskRunFilterTags] = Field(
default=None, description="Filter criteria for `TaskRun.tags`"
)
state: Optional[TaskRunFilterState] = Field(
default=None, description="Filter criteria for `TaskRun.state`"
)
start_time: Optional[TaskRunFilterStartTime] = Field(
default=None, description="Filter criteria for `TaskRun.start_time`"
)
expected_start_time: Optional[TaskRunFilterExpectedStartTime] = Field(
default=None, description="Filter criteria for `TaskRun.expected_start_time`"
)
subflow_runs: Optional[TaskRunFilterSubFlowRuns] = Field(
default=None, description="Filter criteria for `TaskRun.subflow_run`"
)
flow_run_id: Optional[TaskRunFilterFlowRunId] = Field(
default=None, description="Filter criteria for `TaskRun.flow_run_id`"
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
filters: list[sa.ColumnExpressionArgument[bool]] = []
if self.id is not None:
filters.append(self.id.as_sql_filter())
if self.name is not None:
filters.append(self.name.as_sql_filter())
if self.tags is not None:
filters.append(self.tags.as_sql_filter())
if self.state is not None:
filters.append(self.state.as_sql_filter())
if self.start_time is not None:
filters.append(self.start_time.as_sql_filter())
if self.expected_start_time is not None:
filters.append(self.expected_start_time.as_sql_filter())
if self.subflow_runs is not None:
filters.append(self.subflow_runs.as_sql_filter())
if self.flow_run_id is not None:
filters.append(self.flow_run_id.as_sql_filter())
return filters
| TaskRunFilter |
python | huggingface__transformers | src/transformers/models/convnext/configuration_convnext.py | {
"start": 910,
"end": 5631
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ConvNextModel`]. It is used to instantiate an
ConvNeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the ConvNeXT
[facebook/convnext-tiny-224](https://huggingface.co/facebook/convnext-tiny-224) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
patch_size (`int`, *optional*, defaults to 4):
Patch size to use in the patch embedding layer.
num_stages (`int`, *optional*, defaults to 4):
The number of stages in the model.
hidden_sizes (`list[int]`, *optional*, defaults to [96, 192, 384, 768]):
Dimensionality (hidden size) at each stage.
depths (`list[int]`, *optional*, defaults to [3, 3, 9, 3]):
Depth (number of blocks) for each stage.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
`"selu"` and `"gelu_new"` are supported.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
layer_scale_init_value (`float`, *optional*, defaults to 1e-6):
The initial value for the layer scale.
drop_path_rate (`float`, *optional*, defaults to 0.0):
The drop rate for stochastic depth.
out_features (`list[str]`, *optional*):
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
out_indices (`list[int]`, *optional*):
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
If unset and `out_features` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
Example:
```python
>>> from transformers import ConvNextConfig, ConvNextModel
>>> # Initializing a ConvNext convnext-tiny-224 style configuration
>>> configuration = ConvNextConfig()
>>> # Initializing a model (with random weights) from the convnext-tiny-224 style configuration
>>> model = ConvNextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "convnext"
def __init__(
self,
num_channels=3,
patch_size=4,
num_stages=4,
hidden_sizes=None,
depths=None,
hidden_act="gelu",
initializer_range=0.02,
layer_norm_eps=1e-12,
layer_scale_init_value=1e-6,
drop_path_rate=0.0,
image_size=224,
out_features=None,
out_indices=None,
**kwargs,
):
super().__init__(**kwargs)
self.num_channels = num_channels
self.patch_size = patch_size
self.num_stages = num_stages
self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
self.depths = [3, 3, 9, 3] if depths is None else depths
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.layer_scale_init_value = layer_scale_init_value
self.drop_path_rate = drop_path_rate
self.image_size = image_size
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
)
__all__ = ["ConvNextConfig"]
| ConvNextConfig |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/engine_tests/test_child_process_executor.py | {
"start": 793,
"end": 930
} | class ____(ChildProcessCommand):
def execute(self):
# access inner API to simulate hard crash
os._exit(1)
| CrashyCommand |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/fixed_length_record_dataset_test.py | {
"start": 8240,
"end": 9044
} | class ____(
FixedLengthRecordDatasetTestBase, checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self, num_epochs, compression_type=None):
filenames = self._createFiles()
return readers.FixedLengthRecordDataset(
filenames, self._record_bytes, self._header_bytes,
self._footer_bytes).repeat(num_epochs)
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
checkpoint_test_base.default_test_combinations()))
def test(self, verify_fn):
num_epochs = 5
num_outputs = num_epochs * self._num_files * self._num_records
verify_fn(self, lambda: self._build_dataset(num_epochs), num_outputs)
if __name__ == "__main__":
test.main()
| FixedLengthRecordDatasetCheckpointTest |
python | spyder-ide__spyder | spyder/plugins/mainmenu/api.py | {
"start": 3458,
"end": 3559
} | class ____:
Managers = 'managers_section'
Preferences = 'preferences_section'
| ToolsMenuSections |
python | facelessuser__pymdown-extensions | pymdownx/snippets.py | {
"start": 1595,
"end": 16390
} | class ____(Preprocessor):
"""Handle snippets in Markdown content."""
RE_ALL_SNIPPETS = re.compile(
r'''(?x)
^(?P<space>[ \t]*)
(?P<escape>;*)
(?P<all>
(?P<inline_marker>-{1,}8<-{1,}[ \t]+)
(?P<snippet>(?:"(?:\\"|[^"\n\r])+?"|'(?:\\'|[^'\n\r])+?'))(?![ \t]) |
(?P<block_marker>-{1,}8<-{1,})(?![ \t])
)\r?$
'''
)
RE_SNIPPET = re.compile(
r'''(?x)
^(?P<space>[ \t]*)
(?P<snippet>.*?)\r?$
'''
)
RE_SNIPPET_SECTION = re.compile(
r'''(?xi)
^(?P<pre>.*?)
(?P<escape>;*)
(?P<inline_marker>-{1,}8<-{1,}[ \t]+)
(?P<section>\[[ \t]*(?P<type>start|end)[ \t]*:[ \t]*(?P<name>[a-z][-_0-9a-z]*)[ \t]*\])
(?P<post>.*?)$
'''
)
RE_SNIPPET_FILE = re.compile(
r'(?i)(.*?)(?:((?::-?[0-9]*){1,2}(?:(?:,(?=[-0-9:])-?[0-9]*)(?::-?[0-9]*)?)*)|(:[a-z][-_0-9a-z]*))?$'
)
def __init__(self, config, md):
"""Initialize."""
base = config.get('base_path')
if isinstance(base, (str, os.PathLike)):
base = [base]
self.base_path = [os.path.abspath(b) for b in base]
self.restrict_base_path = config['restrict_base_path']
self.encoding = config.get('encoding')
self.check_paths = config.get('check_paths')
self.auto_append = config.get('auto_append')
self.url_download = config['url_download']
self.url_max_size = config['url_max_size']
self.url_timeout = config['url_timeout']
self.url_request_headers = config['url_request_headers']
self.dedent_subsections = config['dedent_subsections']
self.max_retries = config['max_retries']
self.backoff_factor = config['backoff_factor']
self.tab_length = md.tab_length
super().__init__()
self.download.cache_clear()
def extract_section(self, section, lines):
"""Extract the specified section from the lines."""
new_lines = []
start = False
found = False
for l in lines:
# Found a snippet section marker with our specified name
m = self.RE_SNIPPET_SECTION.match(l)
# Handle escaped line
if m and start and m.group('escape'):
l = (
m.group('pre') + m.group('escape').replace(';', '', 1) + m.group('inline_marker') +
m.group('section') + m.group('post')
)
# Found a section we are looking for.
elif m is not None and m.group('name') == section:
# We found the start
if not start and m.group('type') == 'start':
start = True
found = True
continue
# Ignore duplicate start
elif start and m.group('type') == 'start':
continue
# We found the end
elif start and m.group('type') == 'end':
start = False
break
# We found an end, but no start
else:
break
# Found a section we don't care about, so ignore it.
elif m and start:
continue
# We are currently in a section, so append the line
if start:
new_lines.append(l)
if not found and self.check_paths:
raise SnippetMissingError(f"Snippet section '{section}' could not be located")
return self.dedent(new_lines) if self.dedent_subsections else new_lines
def dedent(self, lines):
"""De-indent lines."""
return textwrap.dedent('\n'.join(lines)).split('\n')
def get_snippet_path(self, path):
"""Get snippet path."""
snippet = None
for base in self.base_path:
if os.path.exists(base):
if os.path.isdir(base):
if self.restrict_base_path:
filename = os.path.abspath(os.path.join(base, path))
# If the absolute path is no longer under the specified base path, reject the file
if not filename.startswith(base):
continue
else:
filename = os.path.join(base, path)
if os.path.exists(filename):
snippet = filename
break
else:
dirname = os.path.dirname(base)
filename = os.path.join(dirname, path)
if os.path.exists(filename) and os.path.samefile(filename, base):
snippet = filename
break
return snippet
@functools.lru_cache # noqa: B019
def download(self, url):
"""
Actually download the snippet pointed to by the passed URL.
The most recently used files are kept in a cache until the next reset.
"""
retries = self.max_retries
while True:
try:
http_request = urllib.request.Request(url, headers=self.url_request_headers)
timeout = None if self.url_timeout == 0 else self.url_timeout
with urllib.request.urlopen(http_request, timeout=timeout) as response:
# Fail if status is not OK
status = response.status if util.PY39 else response.code
if status != 200:
raise SnippetMissingError(f"Cannot download snippet '{url}' (HTTP Error {status})")
# We provide some basic protection against absurdly large files.
# 32MB is chosen as an arbitrary upper limit. This can be raised if desired.
content = None
if "content-length" not in response.headers:
# we have to read to know if we went over the max, but never more than `url_max_size`
# where `url_max_size` == 0 means unlimited
content = response.read(self.url_max_size) if self.url_max_size != 0 else response.read()
content_length = len(content)
else:
content_length = int(response.headers["content-length"])
if self.url_max_size != 0 and content_length >= self.url_max_size:
raise ValueError(f"refusing to read payloads larger than or equal to {self.url_max_size}")
# Nothing to return
if content_length == 0:
return ['']
if content is None:
# content-length was in the header, so we did not read yet
content = response.read()
# Process lines
last = content.endswith((b'\r', b'\n'))
s_lines = [l.decode(self.encoding) for l in content.splitlines()]
if last:
s_lines.append('')
return s_lines
except urllib.error.HTTPError as e: # noqa: PERF203
# Handle rate limited error codes
if e.code == 429 and retries:
retries -= 1
wait = self.backoff_factor * (self.max_retries - retries)
time.sleep(wait)
continue
raise SnippetMissingError(f"Cannot download snippet '{url}' (HTTP Error {e.code})") from e
def parse_snippets(self, lines, file_name=None, is_url=False, is_section=False):
"""Parse snippets snippet."""
if file_name:
# Track this file.
self.seen.add(file_name)
new_lines = []
inline = False
block = False
for line in lines:
# Check for snippets on line
inline = False
m = self.RE_ALL_SNIPPETS.match(line)
if m:
if m.group('escape'):
# The snippet has been escaped, replace first `;` and continue.
new_lines.append(line.replace(';', '', 1))
continue
if block and m.group('inline_marker'):
# Don't use inline notation directly under a block.
# It's okay if inline is used again in sub file though.
continue
elif m.group('inline_marker'):
# Inline
inline = True
else:
# Block
block = not block
continue
elif not block:
if not is_section:
# Check for section line, if present remove, if escaped, reformat it
m2 = self.RE_SNIPPET_SECTION.match(line)
if m2 and m2.group('escape'):
line = (
m2.group('pre') + m2.group('escape').replace(';', '', 1) + m2.group('inline_marker') +
m2.group('section') + m2.group('post')
)
m2 = None
# Found a section that must be removed
if m2 is not None:
continue
# Not in snippet, and we didn't find an inline,
# so just a normal line
new_lines.append(line)
continue
if block and not inline:
# We are in a block and we didn't just find a nested inline
# So check if a block path
m = self.RE_SNIPPET.match(line)
if m:
# Get spaces and snippet path. Remove quotes if inline.
space = m.group('space').expandtabs(self.tab_length)
path = m.group('snippet')[1:-1].strip() if inline else m.group('snippet').strip()
if not inline:
# Block path handling
if not path:
# Empty path line, insert a blank line
new_lines.append('')
continue
# Ignore commented out lines
if path.startswith(';'):
continue
# Get line numbers (if specified)
end = []
start = []
section = None
m = self.RE_SNIPPET_FILE.match(path)
path = '' if m is None else m.group(1).strip()
# Looks like we have an empty file and only lines specified
if not path:
if self.check_paths:
raise SnippetMissingError(f"Snippet at path '{path}' could not be found")
else:
continue
if m.group(2):
for nums in m.group(2)[1:].split(','):
span = nums.split(':')
st = int(span[0]) if span[0] else None
start.append(st if st is None or st < 0 else max(0, st - 1))
en = int(span[1]) if len(span) > 1 and span[1] else None
end.append(en)
elif m.group(3):
section = m.group(3)[1:]
# Ignore path links if we are in external, downloaded content
is_link = path.lower().startswith(('https://', 'http://'))
if is_url and not is_link:
continue
# If this is a link, and we are allowing URLs, set `url` to true.
# Make sure we don't process `path` as a local file reference.
url = self.url_download and is_link
snippet = self.get_snippet_path(path) if not url else path
if snippet:
# This is in the stack and we don't want an infinite loop!
if snippet in self.seen:
continue
if not url:
# Read file content
with open(snippet, 'r', encoding=self.encoding) as f:
last = False
s_lines = []
for l in f:
last = l.endswith(('\r', '\n'))
s_lines.append(l.strip('\r\n'))
if last:
s_lines.append('')
else:
# Read URL content
try:
s_lines = self.download(snippet)
except SnippetMissingError:
if self.check_paths:
raise
s_lines = []
if s_lines:
total = len(s_lines)
if start and end:
final_lines = []
for sel in zip(start, end):
s_start = util.clamp(total + sel[0], 0, total) if sel[0] and sel[0] < 0 else sel[0]
s_end = util.clamp(total + 1 + sel[1], 0, total) if sel[1] and sel[1] < 0 else sel[1]
final_lines.extend(s_lines[slice(s_start, s_end, None)])
s_lines = self.dedent(final_lines) if self.dedent_subsections else final_lines
elif section:
s_lines = self.extract_section(section, s_lines)
# Process lines looking for more snippets
new_lines.extend(
[
space + l2 for l2 in self.parse_snippets(
s_lines,
snippet,
is_url=url,
is_section=section is not None
)
]
)
elif self.check_paths:
raise SnippetMissingError(f"Snippet at path '{path}' could not be found")
# Pop the current file name out of the cache
if file_name:
self.seen.remove(file_name)
return new_lines
def run(self, lines):
"""Process snippets."""
self.seen = set()
if self.auto_append:
lines.extend("\n\n-8<-\n{}\n-8<-\n".format('\n\n'.join(self.auto_append)).split('\n'))
return self.parse_snippets(lines)
| SnippetPreprocessor |
python | readthedocs__readthedocs.org | readthedocs/analytics/tests.py | {
"start": 3895,
"end": 10856
} | class ____(TestCase):
def setUp(self):
self.project = get(
Project,
slug="pip",
privacy_level=PUBLIC,
)
self.version = get(Version, slug="1.8", project=self.project)
self.project.versions.all().update(privacy_level=PUBLIC)
self.absolute_uri = (
f"https://{self.project.slug}.readthedocs.io/en/latest/index.html"
)
self.host = f"{self.project.slug}.readthedocs.io"
self.url = (
reverse("analytics_api")
+ f"?project={self.project.slug}&version={self.version.slug}"
f"&absolute_uri={self.absolute_uri}"
)
self.today = timezone.now()
self.tomorrow = timezone.now() + timezone.timedelta(days=1)
self.yesterday = timezone.now() - timezone.timedelta(days=1)
def test_invalid_uri(self):
assert PageView.objects.all().count() == 0
url = (
reverse("analytics_api")
+ f"?project={self.project.slug}&version={self.version.slug}"
f"&absolute_uri=https://docs.example.com"
)
self.client.get(url, headers={"host": self.host})
assert PageView.objects.all().count() == 0
def test_uri_for_another_project(self):
other_project = get(
Project,
slug="other",
)
other_project.versions.all().update(privacy_level=PUBLIC)
# Host and ``absolute_uri`` are from different projects
assert PageView.objects.all().count() == 0
url = (
reverse("analytics_api")
+ f"?project={self.project.slug}&version=latest"
f"&absolute_uri=https://other.readthedocs.io/en/latest/"
)
self.client.get(url, headers={"host": self.host})
assert PageView.objects.all().count() == 0
# Host and ``absolute_uri`` are from different projects with no ``?version`` attribute
url = (
reverse("analytics_api")
+ f"?project={self.project.slug}"
f"&absolute_uri=https://other.readthedocs.io/en/latest/"
)
self.client.get(url, headers={"host": self.host})
assert PageView.objects.all().count() == 0
# Host and ``absolute_uri`` are from the same project
url = (
reverse("analytics_api")
+ f"?project=other&version=latest"
f"&absolute_uri=https://other.readthedocs.io/en/latest/"
)
self.client.get(url, headers={"host": "other.readthedocs.io"})
assert PageView.objects.all().count() == 1
def test_cache_headers(self):
resp = self.client.get(self.url, headers={"host": self.host})
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp["CDN-Cache-Control"], "private")
def test_increase_page_view_count(self):
assert (
PageView.objects.all().count() == 0
), "There's no PageView object created yet."
# testing for yesterday
with mock.patch("readthedocs.analytics.tasks.timezone.now") as mocked_timezone:
mocked_timezone.return_value = self.yesterday
self.client.get(self.url, headers={"host": self.host})
assert (
PageView.objects.all().count() == 1
), f"PageView object for path '{self.absolute_uri}' is created"
assert PageView.objects.all().first().view_count == 1, "'index' has 1 view"
self.client.get(self.url, headers={"host": self.host})
assert (
PageView.objects.all().count() == 1
), f"PageView object for path '{self.absolute_uri}' is already created"
assert PageView.objects.filter(path="/index.html").count() == 1
assert (
PageView.objects.all().first().view_count == 2
), f"'{self.absolute_uri}' has 2 views now"
# testing for today
with mock.patch("readthedocs.analytics.tasks.timezone.now") as mocked_timezone:
mocked_timezone.return_value = self.today
self.client.get(self.url, headers={"host": self.host})
assert (
PageView.objects.all().count() == 2
), f"PageView object for path '{self.absolute_uri}' is created for two days (yesterday and today)"
assert PageView.objects.filter(path="/index.html").count() == 2
assert (
PageView.objects.all().order_by("-date").first().view_count == 1
), f"'{self.absolute_uri}' has 1 view today"
# testing for tomorrow
with mock.patch("readthedocs.analytics.tasks.timezone.now") as mocked_timezone:
mocked_timezone.return_value = self.tomorrow
self.client.get(self.url, headers={"host": self.host})
assert (
PageView.objects.all().count() == 3
), f"PageView object for path '{self.absolute_uri}' is created for three days (yesterday, today & tomorrow)"
assert PageView.objects.filter(path="/index.html").count() == 3
assert (
PageView.objects.all().order_by("-date").first().view_count == 1
), f"'{self.absolute_uri}' has 1 view tomorrow"
def test_dont_track_external_domains(self):
self.assertEqual(PageView.objects.all().count(), 0)
get(
Version,
slug="123",
type=EXTERNAL,
built=True,
active=True,
)
host = f"{self.project.slug}--123.readthedocs.build"
r = self.client.get(self.url, headers={"host": host})
self.assertEqual(r.status_code, 204)
self.assertEqual(PageView.objects.all().count(), 0)
def test_notfound_404_pages(self):
self.assertEqual(PageView.objects.all().count(), 0)
url = self.url + "&status=404"
resp = self.client.get(url, headers={"host": self.host})
self.assertEqual(resp.status_code, 204)
self.assertEqual(PageView.objects.all().count(), 1)
self.assertEqual(PageView.objects.filter(status=404).count(), 1)
def test_notfound_404_page_without_version(self):
self.assertEqual(PageView.objects.all().count(), 0)
absolute_uri = (
f"https://{self.project.slug}.readthedocs.io/index.html"
)
url = (
reverse("analytics_api")
+ f"?project={self.project.slug}&version=null"
f"&absolute_uri={absolute_uri}"
"&status=404"
)
resp = self.client.get(url, headers={"host": self.host})
pageview = PageView.objects.all().first()
self.assertEqual(resp.status_code, 204)
self.assertEqual(PageView.objects.all().count(), 1)
self.assertIsNone(pageview.version)
self.assertEqual(pageview.project.slug, self.project.slug)
self.assertEqual(pageview.path, "/index.html")
self.assertEqual(pageview.status, 404)
| AnalyticsPageViewsTests |
python | lazyprogrammer__machine_learning_examples | cnn_class2/tf_resnet_identity_block_starter.py | {
"start": 413,
"end": 872
} | class ____:
def __init__(self):
# TODO
pass
def predict(self, X):
# TODO
pass
if __name__ == '__main__':
identity_block = IdentityBlock()
# make a fake image
X = np.random.random((1, 224, 224, 256))
init = tf.global_variables_initializer()
with tf.Session() as session:
identity_block.set_session(session)
session.run(init)
output = identity_block.predict(X)
print("output.shape:", output.shape)
| IdentityBlock |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_univariate.py | {
"start": 10330,
"end": 11252
} | class ____(Benchmark):
"""
Univariate Problem13 objective function.
This class defines the Univariate Problem13 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\\text{Problem13}}(x) = -x^{2/3} - (1 - x^2)^{1/3}
Bound constraints: :math:`x \\in [0.001, 0.99]`
.. figure:: figures/Problem13.png
:alt: Univariate Problem13 function
:align: center
**Univariate Problem13 function**
*Global optimum*: :math:`f(x)=-1.5874` for :math:`x = 1/\\sqrt(2)`
"""
def __init__(self, dimensions=1):
Benchmark.__init__(self, dimensions)
self._bounds = [(0.001, 0.99)]
self.global_optimum = 1.0 / sqrt(2)
self.fglob = -1.5874
def fun(self, x, *args):
self.nfev += 1
x = x[0]
return -x ** (2.0 / 3.0) - (1.0 - x ** 2) ** (1.0 / 3.0)
| Problem13 |
python | pytorch__pytorch | torchgen/_autoheuristic/pad_mm/test_pad_mm.py | {
"start": 236,
"end": 1061
} | class ____(TestCase):
def test_padmm_a100(self) -> None:
run_bash("get_padmm_dataset.sh")
run_bash("gen_pad_mm_a100.sh")
file_path = "../../../torch/_inductor/autoheuristic/artifacts/_PadMMA100.py"
a100_heuristic_generated_code = read_file_to_string(file_path)
self.assertExpectedInline(
a100_heuristic_generated_code,
"""\
# flake8: noqa: B950
# fmt: off
# This file was generated by AutoHeuristic. Do not modify it manually!
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/pad_mm/
from torch._inductor.autoheuristic.autoheuristic_utils import AHContext, AHMetadata, Choice, CHOICE_COL
from torch._inductor.autoheuristic.learnedheuristic_interface import (
LearnedHeuristicRegression,
)
| TestPadMM |
python | sphinx-doc__sphinx | tests/test_util/test_util_inspect.py | {
"start": 1590,
"end": 33643
} | class ____:
def __call__(self):
pass
def _decorator(f):
@functools.wraps(f)
def wrapper():
return f()
return wrapper
def forward_reference_in_args(x: Foo) -> None: # type: ignore[name-defined] # noqa: F821
pass
def forward_reference_in_return() -> Foo: # type: ignore[name-defined] # noqa: F821
pass
def test_TypeAliasForwardRef():
alias = TypeAliasForwardRef('example')
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing')
assert sig_str == "TypeAliasForwardRef('example')"
alias = Optional[alias] # NoQA: UP045
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing')
assert sig_str == "TypeAliasForwardRef('example') | None"
alias = alias | None
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing')
assert sig_str == "TypeAliasForwardRef('example') | None"
alias = None | alias # NoQA: RUF036
sig_str = stringify_annotation(alias, 'fully-qualified-except-typing')
assert sig_str == "None | TypeAliasForwardRef('example')"
def test_TypeAliasNamespace() -> None:
import logging.config
type_alias = TypeAliasNamespace({
'logging.Filter': 'MyFilter',
'logging.Handler': 'MyHandler',
'logging.handlers.SyslogHandler': 'MySyslogHandler',
})
assert type_alias['logging'].Filter == 'MyFilter'
assert type_alias['logging'].Handler == 'MyHandler'
assert type_alias['logging'].handlers.SyslogHandler == 'MySyslogHandler'
assert type_alias['logging'].Logger == logging.Logger
assert type_alias['logging'].config == logging.config
with pytest.raises(KeyError):
assert type_alias['log']
with pytest.raises(KeyError):
assert type_alias['unknown']
def test_signature() -> None:
# literals
with pytest.raises(TypeError):
inspect.signature(1) # type: ignore[arg-type]
with pytest.raises(TypeError):
inspect.signature('') # type: ignore[arg-type]
# builtins are supported on a case-by-case basis, depending on whether
# they define __text_signature__
if getattr(list, '__text_signature__', None):
sig = inspect.stringify_signature(inspect.signature(list))
assert sig == '(iterable=(), /)'
else:
with pytest.raises(ValueError, match='no signature found for builtin type'):
inspect.signature(list)
with pytest.raises(ValueError, match='no signature found for builtin type'):
inspect.signature(range)
# normal function
def func(a, b, c=1, d=2, *e, **f):
pass
sig = inspect.stringify_signature(inspect.signature(func))
assert sig == '(a, b, c=1, d=2, *e, **f)'
# forward references
sig = inspect.stringify_signature(inspect.signature(forward_reference_in_args))
assert sig == '(x: Foo) -> None'
sig = inspect.stringify_signature(inspect.signature(forward_reference_in_return))
assert sig == '() -> Foo'
def test_signature_partial() -> None:
def fun(a, b, c=1, d=2):
pass
p = functools.partial(fun, 10, c=11)
sig = inspect.signature(p)
assert stringify_signature(sig) == '(b, *, c=11, d=2)'
def test_signature_methods() -> None:
class Foo:
def meth1(self, arg1, **kwargs):
pass
@classmethod
def meth2(cls, arg1, *args, **kwargs):
pass
@staticmethod
def meth3(arg1, *args, **kwargs):
pass
@functools.wraps(Foo().meth1)
def wrapped_bound_method(*args, **kwargs):
pass
# unbound method
sig = inspect.signature(Foo.meth1)
assert stringify_signature(sig) == '(self, arg1, **kwargs)'
sig = inspect.signature(Foo.meth1, bound_method=True)
assert stringify_signature(sig) == '(arg1, **kwargs)'
# bound method
sig = inspect.signature(Foo().meth1)
assert stringify_signature(sig) == '(arg1, **kwargs)'
# class method
sig = inspect.signature(Foo.meth2)
assert stringify_signature(sig) == '(arg1, *args, **kwargs)'
sig = inspect.signature(Foo().meth2)
assert stringify_signature(sig) == '(arg1, *args, **kwargs)'
# static method
sig = inspect.signature(Foo.meth3)
assert stringify_signature(sig) == '(arg1, *args, **kwargs)'
sig = inspect.signature(Foo().meth3)
assert stringify_signature(sig) == '(arg1, *args, **kwargs)'
# wrapped bound method
sig = inspect.signature(wrapped_bound_method)
assert stringify_signature(sig) == '(arg1, **kwargs)'
def test_signature_partialmethod() -> None:
from functools import partialmethod
class Foo:
def meth1(self, arg1, arg2, arg3=None, arg4=None):
pass
def meth2(self, arg1, arg2):
pass
foo = partialmethod(meth1, 1, 2)
bar = partialmethod(meth1, 1, arg3=3)
baz = partialmethod(meth2, 1, 2)
subject = Foo()
sig = inspect.signature(subject.foo)
assert stringify_signature(sig) == '(arg3=None, arg4=None)'
sig = inspect.signature(subject.bar)
assert stringify_signature(sig) == '(arg2, *, arg3=3, arg4=None)'
sig = inspect.signature(subject.baz)
assert stringify_signature(sig) == '()'
def test_signature_annotations() -> None:
import tests.test_util.typing_test_data as mod
# Class annotations
sig = inspect.signature(mod.f0)
assert stringify_signature(sig) == '(x: int, y: numbers.Integral) -> None'
# Generic types with concrete parameters
sig = inspect.signature(mod.f1)
assert stringify_signature(sig) == '(x: list[int]) -> typing.List[int]'
# TypeVars and generic types with TypeVars
sig = inspect.signature(mod.f2)
assert stringify_signature(sig) == (
'(x: typing.List[tests.test_util.typing_test_data.T],'
' y: typing.List[tests.test_util.typing_test_data.T_co],'
' z: tests.test_util.typing_test_data.T'
') -> typing.List[tests.test_util.typing_test_data.T_contra]'
)
# Union types
sig = inspect.signature(mod.f3)
assert stringify_signature(sig) == '(x: str | numbers.Integral) -> None'
# Quoted annotations
sig = inspect.signature(mod.f4)
assert stringify_signature(sig) == '(x: str, y: str) -> None'
# Keyword-only arguments
sig = inspect.signature(mod.f5)
assert stringify_signature(sig) == '(x: int, *, y: str, z: str) -> None'
# Keyword-only arguments with varargs
sig = inspect.signature(mod.f6)
assert stringify_signature(sig) == '(x: int, *args, y: str, z: str) -> None'
# Space around '=' for defaults
sig = inspect.signature(mod.f7)
sig_str = stringify_signature(sig)
assert sig_str == '(x: int = None, y: dict = {}) -> None'
# Callable types
sig = inspect.signature(mod.f8)
assert stringify_signature(sig) == '(x: typing.Callable[[int, str], int]) -> None'
sig = inspect.signature(mod.f9)
assert stringify_signature(sig) == '(x: typing.Callable) -> None'
# Tuple types
sig = inspect.signature(mod.f10)
sig_str = stringify_signature(sig)
assert sig_str == '(x: typing.Tuple[int, str], y: typing.Tuple[int, ...]) -> None'
# Instance annotations
sig = inspect.signature(mod.f11)
assert stringify_signature(sig) == '(x: CustomAnnotation, y: 123) -> None'
# tuple with more than two items
sig = inspect.signature(mod.f12)
assert stringify_signature(sig) == '() -> typing.Tuple[int, str, int]'
# optional
sig = inspect.signature(mod.f13)
assert stringify_signature(sig) == '() -> str | None'
# optional union
sig = inspect.signature(mod.f20)
assert stringify_signature(sig) in {
'() -> int | str | None',
'() -> str | int | None',
}
# Any
sig = inspect.signature(mod.f14)
assert stringify_signature(sig) == '() -> typing.Any'
# ForwardRef
sig = inspect.signature(mod.f15)
assert stringify_signature(sig) == '(x: Unknown, y: int) -> typing.Any'
# keyword only arguments (1)
sig = inspect.signature(mod.f16)
assert stringify_signature(sig) == '(arg1, arg2, *, arg3=None, arg4=None)'
# keyword only arguments (2)
sig = inspect.signature(mod.f17)
assert stringify_signature(sig) == '(*, arg3, arg4)'
sig = inspect.signature(mod.f18)
assert stringify_signature(sig) == (
'(self, arg1: int | typing.Tuple = 10) -> typing.List[typing.Dict]'
)
# annotations for variadic and keyword parameters
sig = inspect.signature(mod.f19)
assert stringify_signature(sig) == '(*args: int, **kwargs: str)'
# default value is inspect.Signature.empty
sig = inspect.signature(mod.f21)
assert stringify_signature(sig) == "(arg1='whatever', arg2)"
# type hints by string
sig = inspect.signature(mod.Node.children)
sig_str = stringify_signature(sig)
assert sig_str == '(self) -> typing.List[tests.test_util.typing_test_data.Node]'
sig = inspect.signature(mod.Node.__init__)
sig_str = stringify_signature(sig)
assert sig_str == (
'(self, parent: tests.test_util.typing_test_data.Node | None) -> None'
)
# show_annotation is False
sig = inspect.signature(mod.f7)
assert stringify_signature(sig, show_annotation=False) == '(x=None, y={})'
# show_return_annotation is False
sig = inspect.signature(mod.f7)
sig_str = stringify_signature(sig, show_return_annotation=False)
assert sig_str == '(x: int = None, y: dict = {})'
# unqualified_typehints is True
sig = inspect.signature(mod.f7)
sig_str = stringify_signature(sig, unqualified_typehints=True)
assert sig_str == '(x: int = None, y: dict = {}) -> None'
# case: separator at head
sig = inspect.signature(mod.f22)
assert stringify_signature(sig) == '(*, a, b)'
# case: separator in the middle
sig = inspect.signature(mod.f23)
assert stringify_signature(sig) == '(a, b, /, c, d)'
sig = inspect.signature(mod.f24)
assert stringify_signature(sig) == '(a, /, *, b)'
# case: separator at tail
sig = inspect.signature(mod.f25)
assert stringify_signature(sig) == '(a, b, /)'
# collapse Literal types
sig = inspect.signature(mod.f26)
sig_str = stringify_signature(sig)
assert sig_str == (
"(x: typing.Literal[1, 2, 3] = 1, y: typing.Literal['a', 'b'] = 'a') -> None"
)
def test_signature_from_str_basic() -> None:
signature = '(a, b, *args, c=0, d="blah", **kwargs)'
sig = inspect.signature_from_str(signature)
assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs']
assert sig.parameters['a'].name == 'a'
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['a'].default == Parameter.empty
assert sig.parameters['a'].annotation == Parameter.empty
assert sig.parameters['b'].name == 'b'
assert sig.parameters['b'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['b'].default == Parameter.empty
assert sig.parameters['b'].annotation == Parameter.empty
assert sig.parameters['args'].name == 'args'
assert sig.parameters['args'].kind == Parameter.VAR_POSITIONAL
assert sig.parameters['args'].default == Parameter.empty
assert sig.parameters['args'].annotation == Parameter.empty
assert sig.parameters['c'].name == 'c'
assert sig.parameters['c'].kind == Parameter.KEYWORD_ONLY
assert sig.parameters['c'].default == '0'
assert sig.parameters['c'].annotation == Parameter.empty
assert sig.parameters['d'].name == 'd'
assert sig.parameters['d'].kind == Parameter.KEYWORD_ONLY
assert sig.parameters['d'].default == "'blah'"
assert sig.parameters['d'].annotation == Parameter.empty
assert sig.parameters['kwargs'].name == 'kwargs'
assert sig.parameters['kwargs'].kind == Parameter.VAR_KEYWORD
assert sig.parameters['kwargs'].default == Parameter.empty
assert sig.parameters['kwargs'].annotation == Parameter.empty
assert sig.return_annotation == Parameter.empty
def test_signature_from_str_default_values() -> None:
signature = (
'(a=0, b=0.0, c="str", d=b"bytes", e=..., f=True, '
'g=[1, 2, 3], h={"a": 1}, i={1, 2, 3}, '
'j=lambda x, y: None, k=None, l=object(), m=foo.bar.CONSTANT)'
)
sig = inspect.signature_from_str(signature)
assert sig.parameters['a'].default == '0'
assert sig.parameters['b'].default == '0.0'
assert sig.parameters['c'].default == "'str'"
assert sig.parameters['d'].default == "b'bytes'"
assert sig.parameters['e'].default == '...'
assert sig.parameters['f'].default == 'True'
assert sig.parameters['g'].default == '[1, 2, 3]'
assert sig.parameters['h'].default == "{'a': 1}"
assert sig.parameters['i'].default == '{1, 2, 3}'
assert sig.parameters['j'].default == 'lambda x, y: ...'
assert sig.parameters['k'].default == 'None'
assert sig.parameters['l'].default == 'object()'
assert sig.parameters['m'].default == 'foo.bar.CONSTANT'
def test_signature_from_str_annotations() -> None:
signature = '(a: int, *args: bytes, b: str = "blah", **kwargs: float) -> None'
sig = inspect.signature_from_str(signature)
assert list(sig.parameters.keys()) == ['a', 'args', 'b', 'kwargs']
assert sig.parameters['a'].annotation == 'int'
assert sig.parameters['args'].annotation == 'bytes'
assert sig.parameters['b'].annotation == 'str'
assert sig.parameters['kwargs'].annotation == 'float'
assert sig.return_annotation == 'None'
def test_signature_from_str_complex_annotations() -> None:
sig = inspect.signature_from_str('() -> Tuple[str, int, ...]')
assert sig.return_annotation == 'Tuple[str, int, ...]'
sig = inspect.signature_from_str('() -> Callable[[int, int], int]')
assert sig.return_annotation == 'Callable[[int, int], int]'
def test_signature_from_str_kwonly_args() -> None:
sig = inspect.signature_from_str('(a, *, b)')
assert list(sig.parameters.keys()) == ['a', 'b']
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['a'].default == Parameter.empty
assert sig.parameters['b'].kind == Parameter.KEYWORD_ONLY
assert sig.parameters['b'].default == Parameter.empty
def test_signature_from_str_positionaly_only_args() -> None:
sig = inspect.signature_from_str('(a, b=0, /, c=1)')
assert list(sig.parameters.keys()) == ['a', 'b', 'c']
assert sig.parameters['a'].kind == Parameter.POSITIONAL_ONLY
assert sig.parameters['a'].default == Parameter.empty
assert sig.parameters['b'].kind == Parameter.POSITIONAL_ONLY
assert sig.parameters['b'].default == '0'
assert sig.parameters['c'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['c'].default == '1'
def test_signature_from_str_invalid() -> None:
with pytest.raises(SyntaxError):
inspect.signature_from_str('')
def test_signature_from_ast():
signature = 'def func(a, b, *args, c=0, d="blah", **kwargs): pass'
tree = ast.parse(signature)
sig = inspect.signature_from_ast(tree.body[0])
assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs']
assert sig.parameters['a'].name == 'a'
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['a'].default == Parameter.empty
assert sig.parameters['a'].annotation == Parameter.empty
assert sig.parameters['b'].name == 'b'
assert sig.parameters['b'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['b'].default == Parameter.empty
assert sig.parameters['b'].annotation == Parameter.empty
assert sig.parameters['args'].name == 'args'
assert sig.parameters['args'].kind == Parameter.VAR_POSITIONAL
assert sig.parameters['args'].default == Parameter.empty
assert sig.parameters['args'].annotation == Parameter.empty
assert sig.parameters['c'].name == 'c'
assert sig.parameters['c'].kind == Parameter.KEYWORD_ONLY
assert sig.parameters['c'].default == '0'
assert sig.parameters['c'].annotation == Parameter.empty
assert sig.parameters['d'].name == 'd'
assert sig.parameters['d'].kind == Parameter.KEYWORD_ONLY
assert sig.parameters['d'].default == "'blah'"
assert sig.parameters['d'].annotation == Parameter.empty
assert sig.parameters['kwargs'].name == 'kwargs'
assert sig.parameters['kwargs'].kind == Parameter.VAR_KEYWORD
assert sig.parameters['kwargs'].default == Parameter.empty
assert sig.parameters['kwargs'].annotation == Parameter.empty
assert sig.return_annotation == Parameter.empty
def test_safe_getattr_with_default() -> None:
class Foo:
def __getattr__(self, item):
raise Exception
obj = Foo()
result = inspect.safe_getattr(obj, 'bar', 'baz')
assert result == 'baz'
def test_safe_getattr_with_exception() -> None:
class Foo:
def __getattr__(self, item):
raise Exception
obj = Foo()
with pytest.raises(AttributeError, match='bar'):
inspect.safe_getattr(obj, 'bar')
def test_safe_getattr_with_property_exception() -> None:
class Foo:
@property
def bar(self):
raise Exception
obj = Foo()
with pytest.raises(AttributeError, match='bar'):
inspect.safe_getattr(obj, 'bar')
def test_safe_getattr_with___dict___override() -> None:
class Foo:
@property
def __dict__(self):
raise Exception
obj = Foo()
with pytest.raises(AttributeError, match='bar'):
inspect.safe_getattr(obj, 'bar')
def test_dictionary_sorting() -> None:
dictionary = {'c': 3, 'a': 1, 'd': 2, 'b': 4}
description = inspect.object_description(dictionary)
assert description == "{'a': 1, 'b': 4, 'c': 3, 'd': 2}"
def test_set_sorting() -> None:
set_ = set('gfedcba')
description = inspect.object_description(set_)
assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}"
def test_set_sorting_enum() -> None:
class MyEnum(enum.Enum):
a = 1
b = 2
c = 3
set_ = set(MyEnum)
description = inspect.object_description(set_)
assert description == '{MyEnum.a, MyEnum.b, MyEnum.c}'
def test_set_sorting_fallback() -> None:
set_ = {None, 1}
description = inspect.object_description(set_)
assert description == '{1, None}'
def test_deterministic_nested_collection_descriptions() -> None:
# sortable
assert inspect.object_description([{1, 2, 3, 10}]) == '[{1, 2, 3, 10}]'
assert inspect.object_description(({1, 2, 3, 10},)) == '({1, 2, 3, 10},)'
# non-sortable (elements of varying datatype)
assert inspect.object_description([{None, 1}]) == '[{1, None}]'
assert inspect.object_description(({None, 1},)) == '({1, None},)'
assert inspect.object_description([{None, 1, 'A'}]) == "[{'A', 1, None}]"
assert inspect.object_description(({None, 1, 'A'},)) == "({'A', 1, None},)"
def test_frozenset_sorting() -> None:
frozenset_ = frozenset('gfedcba')
description = inspect.object_description(frozenset_)
assert description == "frozenset({'a', 'b', 'c', 'd', 'e', 'f', 'g'})"
def test_frozenset_sorting_fallback() -> None:
frozenset_ = frozenset((None, 1))
description = inspect.object_description(frozenset_)
assert description == 'frozenset({1, None})'
def test_nested_tuple_sorting():
tuple_ = ({'c', 'b', 'a'},) # nb. trailing comma
description = inspect.object_description(tuple_)
assert description == "({'a', 'b', 'c'},)"
tuple_ = ({'c', 'b', 'a'}, {'f', 'e', 'd'})
description = inspect.object_description(tuple_)
assert description == "({'a', 'b', 'c'}, {'d', 'e', 'f'})"
def test_recursive_collection_description():
dict_a_, dict_b_ = {'a': 1}, {'b': 2}
dict_a_['link'], dict_b_['link'] = dict_b_, dict_a_
description_a, description_b = (
inspect.object_description(dict_a_),
inspect.object_description(dict_b_),
)
assert description_a == "{'a': 1, 'link': {'b': 2, 'link': dict(...)}}"
assert description_b == "{'b': 2, 'link': {'a': 1, 'link': dict(...)}}"
list_c_, list_d_ = [1, 2, 3, 4], [5, 6, 7, 8]
list_c_.append(list_d_)
list_d_.append(list_c_)
description_c, description_d = (
inspect.object_description(list_c_),
inspect.object_description(list_d_),
)
assert description_c == '[1, 2, 3, 4, [5, 6, 7, 8, list(...)]]'
assert description_d == '[5, 6, 7, 8, [1, 2, 3, 4, list(...)]]'
def test_dict_customtype() -> None:
class CustomType:
def __init__(self, value):
self._value = value
def __repr__(self):
return '<CustomType(%r)>' % self._value
dictionary = {CustomType(2): 2, CustomType(1): 1}
description = inspect.object_description(dictionary)
# Type is unsortable, just check that it does not crash
assert '<CustomType(2)>: 2' in description
def test_object_description_enum() -> None:
class MyEnum(enum.Enum):
FOO = 1
BAR = 2
assert inspect.object_description(MyEnum.FOO) == 'MyEnum.FOO'
def test_object_description_enum_custom_repr() -> None:
class MyEnum(enum.Enum):
FOO = 1
BAR = 2
def __repr__(self):
return self.name
assert inspect.object_description(MyEnum.FOO) == 'FOO'
def test_getslots() -> None:
class Foo:
pass
class Bar:
__slots__ = ['attr']
class Baz:
__slots__ = {'attr': 'docstring'}
class Qux:
__slots__ = 'attr' # NoQA: PLC0205
assert inspect.getslots(Foo) is None
assert inspect.getslots(Bar) == {'attr': None}
assert inspect.getslots(Baz) == {'attr': 'docstring'}
assert inspect.getslots(Qux) == {'attr': None}
with pytest.raises(TypeError):
inspect.getslots(Bar())
@pytest.mark.parametrize(
('expect', 'klass', 'name'),
[
# class methods
(True, Base, 'classmeth'),
(True, Inherited, 'classmeth'),
(True, MyInt, 'classmeth'),
(True, MyIntOverride, 'from_bytes'),
# non class methods
(False, Base, 'meth'),
(False, Inherited, 'meth'),
(False, MyInt, 'conjugate'),
(False, MyIntOverride, 'conjugate'),
],
)
def test_isclassmethod(expect, klass, name):
subject = getattr(klass, name)
assert inspect.isclassmethod(subject) is expect
assert inspect.isclassmethod(None, klass, name) is expect
@pytest.mark.parametrize(
('expect', 'klass', 'dict_key'),
[
# int.from_bytes is not a class method descriptor
# but int.__dict__['from_bytes'] is one.
(True, int, 'from_bytes'),
(True, MyInt, 'from_bytes'), # inherited
# non class method descriptors
(False, Base, 'classmeth'),
(False, Inherited, 'classmeth'),
(False, int, '__init__'),
(False, int, 'conjugate'),
(False, MyInt, 'classmeth'),
(False, MyIntOverride, 'from_bytes'), # overridden in pure Python
],
)
def test_is_classmethod_descriptor(expect, klass, dict_key):
in_dict = dict_key in klass.__dict__
subject = klass.__dict__.get(dict_key)
assert inspect.is_classmethod_descriptor(subject) is (in_dict and expect)
assert inspect.is_classmethod_descriptor(None, klass, dict_key) is expect
method = getattr(klass, dict_key)
assert not inspect.is_classmethod_descriptor(method)
@pytest.mark.parametrize(
('expect', 'klass', 'dict_key'),
[
# class method descriptors
(True, int, 'from_bytes'),
(True, bytes, 'fromhex'),
(True, MyInt, 'from_bytes'), # in C only
# non class method descriptors
(False, Base, 'classmeth'),
(False, Inherited, 'classmeth'),
(False, int, '__init__'),
(False, int, 'conjugate'),
(False, MyInt, 'classmeth'),
(False, MyIntOverride, 'from_bytes'), # overridden in pure Python
],
)
def test_is_builtin_classmethod_like(expect, klass, dict_key):
method = getattr(klass, dict_key)
assert inspect.is_builtin_classmethod_like(method) is expect
assert inspect.is_builtin_classmethod_like(None, klass, dict_key) is expect
@pytest.mark.parametrize(
('expect', 'klass', 'name'),
[
# regular class methods
(True, Base, 'classmeth'),
(True, Inherited, 'classmeth'),
(True, MyInt, 'classmeth'),
# inherited C class method
(True, MyIntOverride, 'from_bytes'),
# class method descriptors
(True, int, 'from_bytes'),
(True, bytes, 'fromhex'),
(True, MyInt, 'from_bytes'), # in C only
# not classmethod-like
(False, int, '__init__'),
(False, int, 'conjugate'),
(False, MyIntOverride, 'conjugate'), # overridden in pure Python
],
)
def test_is_classmethod_like(expect, klass, name):
subject = getattr(klass, name)
assert inspect.is_classmethod_like(subject) is expect
def test_isstaticmethod() -> None:
assert inspect.isstaticmethod(Base.staticmeth, Base, 'staticmeth')
assert not inspect.isstaticmethod(Base.meth, Base, 'meth')
assert inspect.isstaticmethod(Inherited.staticmeth, Inherited, 'staticmeth')
assert not inspect.isstaticmethod(Inherited.meth, Inherited, 'meth')
def test_iscoroutinefunction() -> None:
# function
assert not inspect.iscoroutinefunction(func)
# coroutine
assert inspect.iscoroutinefunction(coroutinefunc)
# partial-ed coroutine
assert inspect.iscoroutinefunction(partial_coroutinefunc)
# method
assert not inspect.iscoroutinefunction(Base.meth)
# coroutine-method
assert inspect.iscoroutinefunction(Base.coroutinemeth)
# coroutine classmethod
assert inspect.iscoroutinefunction(Base.__dict__['coroutineclassmeth'])
# partial-ed coroutine-method
partial_coroutinemeth = Base.__dict__['partial_coroutinemeth']
assert inspect.iscoroutinefunction(partial_coroutinemeth)
def test_iscoroutinefunction_wrapped() -> None:
# function wrapping a callable obj
assert inspect.isfunction(_decorator(coroutinefunc))
def test_isfunction() -> None:
# fmt: off
assert inspect.isfunction(func) # function
assert inspect.isfunction(partial_func) # partial-ed function
assert inspect.isfunction(Base.meth) # method of class
assert inspect.isfunction(Base.partialmeth) # partial-ed method of class
assert not inspect.isfunction(Base().meth) # method of instance
assert not inspect.isfunction(builtin_func) # builtin function
assert not inspect.isfunction(partial_builtin_func) # partial-ed builtin function
# fmt: on
def test_isfunction_wrapped() -> None:
# function wrapping a callable obj
assert inspect.isfunction(_decorator(_Callable()))
def test_isbuiltin() -> None:
# fmt: off
assert inspect.isbuiltin(builtin_func) # builtin function
assert inspect.isbuiltin(partial_builtin_func) # partial-ed builtin function
assert not inspect.isbuiltin(func) # function
assert not inspect.isbuiltin(partial_func) # partial-ed function
assert not inspect.isbuiltin(Base.meth) # method of class
assert not inspect.isbuiltin(Base().meth) # method of instance
# fmt: on
def test_isdescriptor() -> None:
# fmt: off
assert inspect.isdescriptor(Base.prop) # property of class
assert not inspect.isdescriptor(Base().prop) # property of instance
assert inspect.isdescriptor(Base.meth) # method of class
assert inspect.isdescriptor(Base().meth) # method of instance
assert inspect.isdescriptor(func) # function
# fmt: on
def test_isattributedescriptor() -> None:
# fmt: off
assert inspect.isattributedescriptor(Base.prop) # property
assert not inspect.isattributedescriptor(Base.meth) # method
assert not inspect.isattributedescriptor(Base.staticmeth) # staticmethod
assert not inspect.isattributedescriptor(Base.classmeth) # classmetho
assert not inspect.isattributedescriptor(Descriptor) # custom descriptor class
assert not inspect.isattributedescriptor(str.join) # MethodDescriptorType
assert not inspect.isattributedescriptor(object.__init__) # WrapperDescriptorType
assert not inspect.isattributedescriptor(dict.__dict__['fromkeys']) # ClassMethodDescriptorType
assert inspect.isattributedescriptor(types.FrameType.f_locals) # GetSetDescriptorType
assert inspect.isattributedescriptor(datetime.timedelta.days) # MemberDescriptorType
# fmt: on
try:
# _testcapi module cannot be importable in some distro
# See: https://github.com/sphinx-doc/sphinx/issues/9868
import _testcapi # type: ignore[import-not-found]
# instancemethod (C-API)
testinstancemethod = _testcapi.instancemethod(str.__repr__)
assert not inspect.isattributedescriptor(testinstancemethod)
except ImportError:
pass
def test_isproperty() -> None:
# fmt: off
assert inspect.isproperty(Base.prop) # property of class
assert not inspect.isproperty(Base().prop) # property of instance
assert not inspect.isproperty(Base.meth) # method of class
assert not inspect.isproperty(Base().meth) # method of instance
assert not inspect.isproperty(func) # function
# fmt: on
def test_isgenericalias() -> None:
#: A list of int
T = List[int] # NoQA: UP006
S = list[Union[str, None]] # NoQA: UP007
C = Callable[[int], None] # a generic alias not having a doccomment
assert inspect.isgenericalias(C)
assert inspect.isgenericalias(Callable)
assert inspect.isgenericalias(T)
assert inspect.isgenericalias(List) # NoQA: UP006
assert inspect.isgenericalias(S)
assert not inspect.isgenericalias(list)
assert not inspect.isgenericalias([])
assert not inspect.isgenericalias(object())
assert not inspect.isgenericalias(Base)
def test_unpartial() -> None:
def func1(a, b, c):
pass
func2 = functools.partial(func1, 1)
func2.__doc__ = 'func2'
func3 = functools.partial(func2, 2) # nested partial object
assert inspect.unpartial(func2) is func1
assert inspect.unpartial(func3) is func1
def test_getdoc_inherited_classmethod():
class Foo:
@classmethod
def meth(cls):
"""Docstring
indented text
"""
class Bar(Foo):
@classmethod
def meth(cls):
# inherited classmethod
pass
assert inspect.getdoc(Bar.meth, getattr, False, Bar, 'meth') is None
assert inspect.getdoc(Bar.meth, getattr, True, Bar, 'meth') == Foo.meth.__doc__
def test_getdoc_inherited_decorated_method():
class Foo:
def meth(self):
"""Docstring
indented text
"""
class Bar(Foo):
@functools.lru_cache # NoQA: B019
def meth(self):
# inherited and decorated method
pass
assert inspect.getdoc(Bar.meth, getattr, False, Bar, 'meth') is None
assert inspect.getdoc(Bar.meth, getattr, True, Bar, 'meth') == Foo.meth.__doc__
def test_is_builtin_class_method() -> None:
class MyInt(int):
def my_method(self):
pass
assert inspect.is_builtin_class_method(MyInt, 'to_bytes')
assert inspect.is_builtin_class_method(MyInt, '__init__')
assert not inspect.is_builtin_class_method(MyInt, 'my_method')
assert not inspect.is_builtin_class_method(MyInt, 'does_not_exist')
assert not inspect.is_builtin_class_method(4, 'still does not crash')
class ObjectWithMroAttr:
def __init__(self, mro_attr):
self.__mro__ = mro_attr
assert not inspect.is_builtin_class_method(
ObjectWithMroAttr([1, 2, 3]), 'still does not crash'
)
| _Callable |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 879894,
"end": 885174
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"database_id",
"fields",
"filter",
"group_by",
"layout",
"name",
"number",
"project",
"sort_by",
"updated_at",
"vertical_group_by",
"visible_fields",
)
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
fields = sgqlc.types.Field(
ProjectV2FieldConfigurationConnection,
graphql_name="fields",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"order_by",
sgqlc.types.Arg(
ProjectV2FieldOrder,
graphql_name="orderBy",
default={"field": "POSITION", "direction": "ASC"},
),
),
)
),
)
filter = sgqlc.types.Field(String, graphql_name="filter")
group_by = sgqlc.types.Field(
ProjectV2FieldConnection,
graphql_name="groupBy",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"order_by",
sgqlc.types.Arg(
ProjectV2FieldOrder,
graphql_name="orderBy",
default={"field": "POSITION", "direction": "ASC"},
),
),
)
),
)
layout = sgqlc.types.Field(
sgqlc.types.non_null(ProjectV2ViewLayout), graphql_name="layout"
)
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
number = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="number")
project = sgqlc.types.Field(sgqlc.types.non_null(ProjectV2), graphql_name="project")
sort_by = sgqlc.types.Field(
ProjectV2SortByConnection,
graphql_name="sortBy",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
updated_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="updatedAt"
)
vertical_group_by = sgqlc.types.Field(
ProjectV2FieldConnection,
graphql_name="verticalGroupBy",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"order_by",
sgqlc.types.Arg(
ProjectV2FieldOrder,
graphql_name="orderBy",
default={"field": "POSITION", "direction": "ASC"},
),
),
)
),
)
visible_fields = sgqlc.types.Field(
ProjectV2FieldConnection,
graphql_name="visibleFields",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
(
"before",
sgqlc.types.Arg(String, graphql_name="before", default=None),
),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
(
"order_by",
sgqlc.types.Arg(
ProjectV2FieldOrder,
graphql_name="orderBy",
default={"field": "POSITION", "direction": "ASC"},
),
),
)
),
)
| ProjectV2View |
python | facelessuser__soupsieve | tests/test_level4/test_muted.py | {
"start": 50,
"end": 1055
} | class ____(util.TestCase):
"""Test paused selectors."""
MARKUP = """
<!DOCTYPE html>
<html>
<body>
<video id="vid1" width="320" height="240" controls muted>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
<video id="vid2" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</body>
</html>
"""
def test_muted(self):
"""Test muted."""
self.assert_selector(
self.MARKUP,
"video:muted",
['vid1'],
flags=util.HTML
)
def test_not_muted(self):
"""Test not muted."""
self.assert_selector(
self.MARKUP,
"video:not(:muted)",
["vid2"],
flags=util.HTML
)
| TestPaused |
python | matplotlib__matplotlib | lib/matplotlib/backend_bases.py | {
"start": 132356,
"end": 136172
} | class ____:
# A backend can be defined by using the following pattern:
#
# @_Backend.export
# class FooBackend(_Backend):
# # override the attributes and methods documented below.
# `backend_version` may be overridden by the subclass.
backend_version = "unknown"
# The `FigureCanvas` class must be defined.
FigureCanvas = None
# For interactive backends, the `FigureManager` class must be overridden.
FigureManager = FigureManagerBase
# For interactive backends, `mainloop` should be a function taking no
# argument and starting the backend main loop. It should be left as None
# for non-interactive backends.
mainloop = None
# The following methods will be automatically defined and exported, but
# can be overridden.
@classmethod
def new_figure_manager(cls, num, *args, **kwargs):
"""Create a new figure manager instance."""
# This import needs to happen here due to circular imports.
from matplotlib.figure import Figure
fig_cls = kwargs.pop('FigureClass', Figure)
fig = fig_cls(*args, **kwargs)
return cls.new_figure_manager_given_figure(num, fig)
@classmethod
def new_figure_manager_given_figure(cls, num, figure):
"""Create a new figure manager instance for the given figure."""
return cls.FigureCanvas.new_manager(figure, num)
@classmethod
def draw_if_interactive(cls):
manager_class = cls.FigureCanvas.manager_class
# Interactive backends reimplement start_main_loop or pyplot_show.
backend_is_interactive = (
manager_class.start_main_loop != FigureManagerBase.start_main_loop
or manager_class.pyplot_show != FigureManagerBase.pyplot_show)
if backend_is_interactive and is_interactive():
manager = Gcf.get_active()
if manager:
manager.canvas.draw_idle()
@classmethod
def show(cls, *, block=None):
"""
Show all figures.
`show` blocks by calling `mainloop` if *block* is ``True``, or if it is
``None`` and we are not in `interactive` mode and if IPython's
``%matplotlib`` integration has not been activated.
"""
managers = Gcf.get_all_fig_managers()
if not managers:
return
for manager in managers:
try:
manager.show() # Emits a warning for non-interactive backend.
except NonGuiException as exc:
_api.warn_external(str(exc))
if cls.mainloop is None:
return
if block is None:
# Hack: Is IPython's %matplotlib integration activated? If so,
# IPython's activate_matplotlib (>= 0.10) tacks a _needmain
# attribute onto pyplot.show (always set to False).
pyplot_show = getattr(sys.modules.get("matplotlib.pyplot"), "show", None)
ipython_pylab = hasattr(pyplot_show, "_needmain")
block = not ipython_pylab and not is_interactive()
if block:
cls.mainloop()
# This method is the one actually exporting the required methods.
@staticmethod
def export(cls):
for name in [
"backend_version",
"FigureCanvas",
"FigureManager",
"new_figure_manager",
"new_figure_manager_given_figure",
"draw_if_interactive",
"show",
]:
setattr(sys.modules[cls.__module__], name, getattr(cls, name))
# For back-compatibility, generate a shim `Show` class.
class Show(ShowBase):
def mainloop(self):
return cls.mainloop()
setattr(sys.modules[cls.__module__], "Show", Show)
return cls
| _Backend |
python | ansible__ansible | test/units/plugins/lookup/test_password.py | {
"start": 22358,
"end": 24395
} | class ____(BaseTestLookupModule):
def setUp(self):
super(TestLookupModuleWithPasslibWrappedAlgo, self).setUp()
self.os_path_exists = password.os.path.exists
def tearDown(self):
super(TestLookupModuleWithPasslibWrappedAlgo, self).tearDown()
password.os.path.exists = self.os_path_exists
@patch('ansible.plugins.lookup.password._write_password_file')
def test_encrypt_wrapped_crypt_algo(self, mock_write_file):
password.os.path.exists = self.password_lookup._loader.path_exists
with patch.object(builtins, 'open', mock_open(read_data=self.password_lookup._loader.get_text_file_contents('/path/to/somewhere'))):
results = self.password_lookup.run([u'/path/to/somewhere encrypt=ldap_sha256_crypt'], None)
wrapper = getattr(passlib.hash, 'ldap_sha256_crypt')
self.assertEqual(len(results), 1)
result = results[0]
self.assertIsInstance(result, str)
expected_password_length = 76
self.assertEqual(len(result), expected_password_length)
# result should have 5 parts split by '$'
str_parts = result.split('$')
self.assertEqual(len(str_parts), 5)
# verify the string and passlib agree on the number of rounds
self.assertEqual(str_parts[2], "rounds=%s" % wrapper.default_rounds)
# verify it used the right algo type
self.assertEqual(str_parts[0], '{CRYPT}')
# verify it used the right algo type
self.assertTrue(wrapper.verify(self.password_lookup._loader.get_text_file_contents('/path/to/somewhere'), result))
# verify a password with a non default rounds value
# generated with: echo test | mkpasswd -s --rounds 660000 -m sha-256 --salt testansiblepass.
hashpw = '{CRYPT}$5$rounds=660000$testansiblepass.$KlRSdA3iFXoPI.dEwh7AixiXW3EtCkLrlQvlYA2sluD'
self.assertTrue(wrapper.verify('test', hashpw))
| TestLookupModuleWithPasslibWrappedAlgo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-chat/unit_tests/integration/test_chats.py | {
"start": 3052,
"end": 4485
} | class ____(TestCase):
@HttpMocker()
def test_when_read_then_extract_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
HttpRequest(
f"https://{_SUBDOMAIN}.zendesk.com/api/v2/chat/incremental/chats?fields=chats%28%2A%29&limit=1000&start_time={int(_START_DATETIME.timestamp())}"
),
_response().with_record(_record()).with_record(_record()).build(),
)
output = read(ConfigBuilder().start_date(_START_DATETIME).subdomain(_SUBDOMAIN), StateBuilder())
assert len(output.records) == 2
@HttpMocker()
def test_given_count_is_1000_when_read_then_paginate(self, http_mocker: HttpMocker) -> None:
response_with_1000_records = _response()
for i in range(0, 1000):
response_with_1000_records.with_record(_record())
http_mocker.get(
HttpRequest(
f"https://{_SUBDOMAIN}.zendesk.com/api/v2/chat/incremental/chats?fields=chats%28%2A%29&limit=1000&start_time={int(_START_DATETIME.timestamp())}"
),
response_with_1000_records.with_pagination().build(),
)
http_mocker.get(
HttpRequest(_NEXT_PAGE_URL),
_response().with_record(_record()).build(),
)
output = read(ConfigBuilder().start_date(_START_DATETIME).subdomain(_SUBDOMAIN), StateBuilder())
assert len(output.records) == 1001
| ChatsTest |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 80790,
"end": 81102
} | class ____(TestCase):
def setUp(self):
self.model = PollWithManyToManyCustomHistoryID
self.history_model = self.model.history.model
self.place = Place.objects.create(name="Home")
self.poll = self.model.objects.create(question="what's up?", pub_date=today)
| ManyToManyCustomIDTest |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 11676,
"end": 12113
} | class ____(ConcreteTemplate):
cases = [signature(choose_result_int(op), op) for op in sorted(types.unsigned_domain)]
cases += [signature(choose_result_int(op), op) for op in sorted(types.signed_domain)]
cases += [signature(op, op) for op in sorted(types.real_domain)]
cases += [signature(op, op) for op in sorted(types.complex_domain)]
cases += [signature(types.intp, types.boolean)]
@infer_global(operator.neg)
| UnaryOp |
python | huggingface__transformers | src/transformers/models/dac/modeling_dac.py | {
"start": 20069,
"end": 23368
} | class ____(PreTrainedAudioTokenizerBase):
config: DacConfig
base_model_prefix = "dac"
main_input_name = "input_values"
@torch.no_grad()
def _init_weights(self, module):
if isinstance(module, nn.Conv1d):
init.trunc_normal_(module.weight, std=0.02)
init.constant_(module.bias, 0)
elif isinstance(module, Snake1d):
init.ones_(module.alpha)
elif isinstance(module, nn.ConvTranspose1d):
module.reset_parameters()
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, mean=0.0, std=0.02)
def apply_weight_norm(self):
weight_norm = nn.utils.weight_norm
if hasattr(nn.utils.parametrizations, "weight_norm"):
weight_norm = nn.utils.parametrizations.weight_norm
for layer in self.quantizer.quantizers:
weight_norm(layer.in_proj)
weight_norm(layer.out_proj)
weight_norm(self.encoder.conv1)
weight_norm(self.encoder.conv2)
for layer in self.encoder.block:
weight_norm(layer.conv1)
weight_norm(layer.res_unit1.conv1)
weight_norm(layer.res_unit1.conv2)
weight_norm(layer.res_unit2.conv1)
weight_norm(layer.res_unit2.conv2)
weight_norm(layer.res_unit3.conv1)
weight_norm(layer.res_unit3.conv2)
weight_norm(self.decoder.conv1)
weight_norm(self.decoder.conv2)
for layer in self.decoder.block:
weight_norm(layer.conv_t1)
weight_norm(layer.res_unit1.conv1)
weight_norm(layer.res_unit1.conv2)
weight_norm(layer.res_unit2.conv1)
weight_norm(layer.res_unit2.conv2)
weight_norm(layer.res_unit3.conv1)
weight_norm(layer.res_unit3.conv2)
def remove_weight_norm(self):
for layer in self.quantizer.quantizers:
nn.utils.remove_weight_norm(layer.in_proj)
nn.utils.remove_weight_norm(layer.out_proj)
nn.utils.remove_weight_norm(self.encoder.conv1)
nn.utils.remove_weight_norm(self.encoder.conv2)
for layer in self.encoder.block:
nn.utils.remove_weight_norm(layer.conv1)
nn.utils.remove_weight_norm(layer.res_unit1.conv1)
nn.utils.remove_weight_norm(layer.res_unit1.conv2)
nn.utils.remove_weight_norm(layer.res_unit2.conv1)
nn.utils.remove_weight_norm(layer.res_unit2.conv2)
nn.utils.remove_weight_norm(layer.res_unit3.conv1)
nn.utils.remove_weight_norm(layer.res_unit3.conv2)
nn.utils.remove_weight_norm(self.decoder.conv1)
nn.utils.remove_weight_norm(self.decoder.conv2)
for layer in self.decoder.block:
nn.utils.remove_weight_norm(layer.conv_t1)
nn.utils.remove_weight_norm(layer.res_unit1.conv1)
nn.utils.remove_weight_norm(layer.res_unit1.conv2)
nn.utils.remove_weight_norm(layer.res_unit2.conv1)
nn.utils.remove_weight_norm(layer.res_unit2.conv2)
nn.utils.remove_weight_norm(layer.res_unit3.conv1)
nn.utils.remove_weight_norm(layer.res_unit3.conv2)
@auto_docstring(
custom_intro="""
The DAC (Descript Audio Codec) model.
"""
)
| DacPreTrainedModel |
python | PrefectHQ__prefect | src/prefect/transactions.py | {
"start": 1512,
"end": 8617
} | class ____(ContextModel, abc.ABC):
"""
A base model for transaction state.
"""
store: Optional[ResultStore] = None
key: Optional[str] = None
children: list[Self] = Field(default_factory=list)
commit_mode: Optional[CommitMode] = None
isolation_level: Optional[IsolationLevel] = IsolationLevel.READ_COMMITTED
state: TransactionState = TransactionState.PENDING
on_commit_hooks: list[Callable[[Self], None]] = Field(default_factory=list)
on_rollback_hooks: list[Callable[[Self], None]] = Field(default_factory=list)
overwrite: bool = False
logger: Union[logging.Logger, LoggingAdapter] = Field(
default_factory=partial(get_logger, "transactions")
)
write_on_commit: bool = True
_stored_values: dict[str, Any] = PrivateAttr(default_factory=dict)
_staged_value: ResultRecord[Any] | Any = None
_holder: str = PrivateAttr(default_factory=lambda: str(uuid.uuid4()))
__var__: ClassVar[ContextVar[Self]] = ContextVar("transaction")
def set(self, name: str, value: Any) -> None:
"""
Set a stored value in the transaction.
Args:
name: The name of the value to set
value: The value to set
Examples:
Set a value for use later in the transaction:
```python
with transaction() as txn:
txn.set("key", "value")
...
assert txn.get("key") == "value"
```
"""
self._stored_values[name] = value
def get(self, name: str, default: Any = NotSet) -> Any:
"""
Get a stored value from the transaction.
Child transactions will return values from their parents unless a value with
the same name is set in the child transaction.
Direct changes to returned values will not update the stored value. To update the
stored value, use the `set` method.
Args:
name: The name of the value to get
default: The default value to return if the value is not found
Returns:
The value from the transaction
Examples:
Get a value from the transaction:
```python
with transaction() as txn:
txn.set("key", "value")
...
assert txn.get("key") == "value"
```
Get a value from a parent transaction:
```python
with transaction() as parent:
parent.set("key", "parent_value")
with transaction() as child:
assert child.get("key") == "parent_value"
```
Update a stored value:
```python
with transaction() as txn:
txn.set("key", [1, 2, 3])
value = txn.get("key")
value.append(4)
# Stored value is not updated until `.set` is called
assert value == [1, 2, 3, 4]
assert txn.get("key") == [1, 2, 3]
txn.set("key", value)
assert txn.get("key") == [1, 2, 3, 4]
```
"""
# deepcopy to prevent mutation of stored values
value = copy.deepcopy(self._stored_values.get(name, NotSet))
if value is NotSet:
# if there's a parent transaction, get the value from the parent
parent = self.get_parent()
if parent is not None:
value = parent.get(name, default)
# if there's no parent transaction, use the default
elif default is not NotSet:
value = default
else:
raise ValueError(f"Could not retrieve value for unknown key: {name}")
return value
def is_committed(self) -> bool:
return self.state == TransactionState.COMMITTED
def is_rolled_back(self) -> bool:
return self.state == TransactionState.ROLLED_BACK
def is_staged(self) -> bool:
return self.state == TransactionState.STAGED
def is_pending(self) -> bool:
return self.state == TransactionState.PENDING
def is_active(self) -> bool:
return self.state == TransactionState.ACTIVE
def prepare_transaction(self) -> None:
"""Helper method to prepare transaction state and validate configuration."""
if self._token is not None:
raise RuntimeError(
"Context already entered. Context enter calls cannot be nested."
)
parent = get_transaction()
# set default commit behavior; either inherit from parent or set a default of eager
if self.commit_mode is None:
self.commit_mode = parent.commit_mode if parent else CommitMode.LAZY
# set default isolation level; either inherit from parent or set a default of read committed
if self.isolation_level is None:
self.isolation_level = (
parent.isolation_level if parent else IsolationLevel.READ_COMMITTED
)
assert self.isolation_level is not None, "Isolation level was not set correctly"
if (
self.store
and self.key
and not self.store.supports_isolation_level(self.isolation_level)
):
raise ConfigurationError(
f"Isolation level {self.isolation_level.name} is not supported by provided "
"configuration. Please ensure you've provided a lock file directory or lock "
"manager when using the SERIALIZABLE isolation level."
)
# this needs to go before begin, which could set the state to committed
self.state = TransactionState.ACTIVE
def add_child(self, transaction: Self) -> None:
self.children.append(transaction)
def get_parent(self) -> Self | None:
parent = None
if self._token:
prev_var = self._token.old_value
if prev_var != Token.MISSING:
parent = prev_var
else:
# `_token` has been reset so we need to get the active transaction from the context var
parent = self.get_active()
return parent
def stage(
self,
value: Any,
on_rollback_hooks: Optional[list[Callable[..., Any]]] = None,
on_commit_hooks: Optional[list[Callable[..., Any]]] = None,
) -> None:
"""
Stage a value to be committed later.
"""
on_commit_hooks = on_commit_hooks or []
on_rollback_hooks = on_rollback_hooks or []
if self.state != TransactionState.COMMITTED:
self._staged_value = value
self.on_rollback_hooks += on_rollback_hooks
self.on_commit_hooks += on_commit_hooks
self.state = TransactionState.STAGED
@classmethod
def get_active(cls: Type[Self]) -> Optional[Self]:
return cls.__var__.get(None)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, BaseTransaction):
return False
return dict(self) == dict(other)
| BaseTransaction |
python | google__jax | jax/_src/xla_metadata.py | {
"start": 2036,
"end": 4865
} | class ____:
__slots__ = ["prev", "updates"]
def __init__(self, updates):
self.updates = updates
def __enter__(self):
if not self.updates:
return
self.prev = config.xla_metadata_context_manager.get_local()
config.xla_metadata_context_manager.set_local(
xla_metadata_lib.update_metadata(self.prev, self.updates)
)
def __exit__(self, exc_type, exc_value, traceback):
if not self.updates:
return
config.xla_metadata_context_manager.set_local(self.prev)
def __call__(self, f):
return _XlaMetadataWrapper(f, self)
def set_xla_metadata(x=None, **kwargs):
if x is None:
return XlaMetadataContextManager(kwargs)
else:
hashable_metadata = tuple(sorted(kwargs.items()))
return tree_util.tree_map(
lambda v: xla_metadata_value_p.bind(
v, xla_metadata_kvs=hashable_metadata
),
x,
)
# `xla_metadata_value_p` is an identity primitive for attaching frontend_attributes
# to the primitive's producing (parent/owner) op.
xla_metadata_value_p = core.Primitive("xla_metadata_value")
xla_metadata_value_p.def_impl(
partial(dispatch.apply_primitive, xla_metadata_value_p)
)
xla_metadata_value_p.def_abstract_eval(lambda aval, *, xla_metadata_kvs: aval)
batching.defvectorized(xla_metadata_value_p)
# TODO(nbasile): Implement tagging gradient ops with metadata.
ad.deflinear2(xla_metadata_value_p, lambda ct, _, **kwargs: (ct,))
def _xla_metadata_value_lowering_rule(
ctx: mlir.LoweringRuleContext, val: ir.Value, *, xla_metadata_kvs
):
xla_metadata = dict(xla_metadata_kvs)
op_to_attach_metadata = _target_op_to_attach_metadata(val)
if op_to_attach_metadata is not None:
_attach_xla_metadata_to_op(xla_metadata, op_to_attach_metadata)
return [val]
# If we leave `cacheable=True`, when we are in the lowering rule, the `val.owner`
# becomes a cached `FuncOp`. FuncOp.owners are Blocks, which we can't tag.
mlir.register_lowering(
xla_metadata_value_p, _xla_metadata_value_lowering_rule, cacheable=False
)
def _target_op_to_attach_metadata(value_mlir: ir.Value) -> ir.Operation | None:
op = value_mlir.owner
if op is None or isinstance(op, ir.Block):
return None
return op
def _attach_xla_metadata_to_op(
xla_metadata: dict[str, Any], op: ir.Operation
) -> None:
if xla_metadata:
ctx_attributes, existing_attributes = {}, {}
for k, v in xla_metadata.items():
ctx_attributes[k] = ir.StringAttr.get(str(v).lower())
# Combine with existing mhlo.frontend_attributes
for attr in op.attributes:
if attr == "mhlo.frontend_attributes":
for a in op.attributes[attr]:
existing_attributes[a.name] = a.attr
op.attributes["mhlo.frontend_attributes"] = ir.DictAttr.get(
ctx_attributes | existing_attributes
)
| XlaMetadataContextManager |
python | dask__distributed | distributed/comm/inproc.py | {
"start": 6934,
"end": 8786
} | class ____(BaseListener):
prefix = "inproc"
def __init__(self, address, comm_handler, deserialize=True):
super().__init__()
self.manager = global_manager
self.address = address or self.manager.new_address()
self.comm_handler = comm_handler
self.deserialize = deserialize
self.listen_q = Queue()
async def _handle_stream(self, comm):
try:
await self.on_connection(comm)
except CommClosedError:
logger.debug("Connection closed before handshake completed")
return
await self.comm_handler(comm)
async def _listen(self):
while True:
conn_req = await self.listen_q.get()
if conn_req is None:
break
comm = InProc(
local_addr="inproc://" + self.address,
peer_addr="inproc://" + conn_req.c_addr,
read_q=conn_req.c2s_q,
write_q=conn_req.s2c_q,
write_loop=conn_req.c_loop,
deserialize=self.deserialize,
)
# Notify connector
conn_req.c_loop.add_callback(conn_req.conn_event.set)
IOLoop.current().add_callback(self._handle_stream, comm)
def connect_threadsafe(self, conn_req):
self.loop.add_callback(self.listen_q.put_nowait, conn_req)
async def start(self):
self.loop = IOLoop.current()
self._listen_future = asyncio.ensure_future(self._listen())
self.manager.add_listener(self.address, self)
def stop(self):
self.listen_q.put_nowait(None)
self.manager.remove_listener(self.address)
@property
def listen_address(self):
return "inproc://" + self.address
@property
def contact_address(self):
return "inproc://" + self.address
| InProcListener |
python | huggingface__transformers | tests/models/led/test_modeling_led.py | {
"start": 10658,
"end": 20316
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(LEDModel, LEDForConditionalGeneration, LEDForSequenceClassification, LEDForQuestionAnswering)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"feature-extraction": LEDModel,
"question-answering": LEDForQuestionAnswering,
"summarization": LEDForConditionalGeneration,
"text-classification": LEDForSequenceClassification,
"text2text-generation": LEDForConditionalGeneration,
"translation": LEDForConditionalGeneration,
"zero-shot": LEDForSequenceClassification,
}
if is_torch_available()
else {}
)
is_encoder_decoder = True
test_missing_keys = False
# TODO: Fix the failed tests when this model gets more usage
def is_pipeline_test_to_skip(
self,
pipeline_test_case_name,
config_class,
model_architecture,
tokenizer_name,
image_processor_name,
feature_extractor_name,
processor_name,
):
if pipeline_test_case_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"):
return True
return False
def setUp(self):
self.model_tester = LEDModelTester(self)
self.config_tester = ConfigTester(self, config_class=LEDConfig)
def test_config(self):
self.config_tester.run_common_tests()
def test_save_load_strict(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
self.assertEqual(info["missing_keys"], set())
def test_decoder_model_past_with_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_encoder_decoder_model_standalone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
def test_global_attention(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_global_attention(*config_and_inputs)
def prepare_config_and_inputs_for_generate(self, *args, **kwargs):
config, inputs_dict = super().prepare_config_and_inputs_for_generate(*args, **kwargs)
# LED computes attention scores based on mask indices if `is_global`
inputs_dict.pop("global_attention_mask")
return config, inputs_dict
# LEDForSequenceClassification does not support inputs_embeds
def test_inputs_embeds(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in (LEDModel, LEDForConditionalGeneration, LEDForQuestionAnswering):
model = model_class(config)
model.to(torch_device)
model.eval()
inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
if not self.is_encoder_decoder:
input_ids = inputs["input_ids"]
del inputs["input_ids"]
else:
encoder_input_ids = inputs["input_ids"]
decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
del inputs["input_ids"]
inputs.pop("decoder_input_ids", None)
wte = model.get_input_embeddings()
if not self.is_encoder_decoder:
inputs["inputs_embeds"] = wte(input_ids)
else:
inputs["inputs_embeds"] = wte(encoder_input_ids)
inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
with torch.no_grad():
model(**inputs)[0]
@require_torch_fp16
def test_generate_fp16(self):
config, input_dict = self.model_tester.prepare_config_and_inputs()
input_ids = input_dict["input_ids"]
attention_mask = input_ids.ne(1).to(torch_device)
model = LEDForConditionalGeneration(config).eval().to(torch_device)
model.half()
model.generate(input_ids, attention_mask=attention_mask)
model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
@unittest.skip(reason="Longformer cannot keep gradients in attentions or hidden states")
def test_retain_grad_hidden_states_attentions(self):
return
def test_attention_outputs(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.return_dict = True
seq_length = self.model_tester.seq_length
encoder_seq_length = self.model_tester.encoder_seq_length
encoder_key_length = self.model_tester.encoder_key_length
for model_class in self.all_model_classes:
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = False
config.return_dict = True
model = model_class._from_config(config, attn_implementation="eager")
config = model.config
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.encoder_attentions
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
config.output_attentions = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.encoder_attentions
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(attentions[0].shape[-3:]),
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
)
out_len = len(outputs)
# global attention outputs are added as well => so +1 here
correct_outlen = 6
# loss is at first position
if "labels" in inputs_dict:
correct_outlen += 1 # loss is added to beginning
# Question Answering model returns start_logits and end_logits
if model_class in get_values(MODEL_FOR_QUESTION_ANSWERING_MAPPING):
correct_outlen += 1 # start_logits and end_logits instead of only 1 output
if "past_key_values" in outputs:
correct_outlen += 1 # past_key_values have been returned
self.assertEqual(out_len, correct_outlen)
# decoder attentions
decoder_attentions = outputs.decoder_attentions
self.assertIsInstance(decoder_attentions, (list, tuple))
self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(decoder_attentions[0].shape[-3:]),
[self.model_tester.num_attention_heads, seq_length, seq_length],
)
# cross attentions
cross_attentions = outputs.cross_attentions
self.assertIsInstance(cross_attentions, (list, tuple))
self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(cross_attentions[0].shape[-3:]),
[
self.model_tester.num_attention_heads,
seq_length,
seq_length,
],
)
def _check_encoder_attention_for_generate(self, attentions, batch_size, config, prompt_length):
# overwrite because LED does not have (bs, num_heads, seq_len, seq_len) shape
encoder_expected_shape = (
batch_size,
config.num_attention_heads,
prompt_length,
self.model_tester.attention_window // 2 * 2 + 1,
)
self.assertIsInstance(attentions, tuple)
self.assertListEqual(
[layer_attentions.shape for layer_attentions in attentions],
[encoder_expected_shape] * len(attentions),
)
def assert_tensors_close(a, b, atol=1e-12, prefix=""):
"""If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if torch.allclose(a, b, atol=atol):
return True
raise Exception
except Exception:
pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
if a.numel() > 100:
msg = f"tensor values are {pct_different:.1%} percent different."
else:
msg = f"{a} != {b}"
if prefix:
msg = prefix + ": " + msg
raise AssertionError(msg)
def _long_tensor(tok_lst):
return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
TOLERANCE = 1e-4
@require_torch
@require_sentencepiece
@require_tokenizers
@slow
| LEDModelTest |
python | scipy__scipy | benchmarks/benchmarks/interpolate.py | {
"start": 11036,
"end": 12149
} | class ____(Benchmark):
"""
Benchmark RegularGridInterpolator with method="quintic".
"""
param_names = ['ndim', 'n_samples', 'method']
params = [
[2],
[10, 40],
]
def setup(self, ndim, n_samples):
rng = np.random.default_rng(314159)
self.points = [np.sort(rng.random(size=n_samples))
for _ in range(ndim)]
self.values = rng.random(size=[n_samples]*ndim)
# choose in-bounds sample points xi
bounds = [(p.min(), p.max()) for p in self.points]
xi = [rng.uniform(low, high, size=n_samples)
for low, high in bounds]
self.xi = np.array(xi).T
self.interp = interpolate.RegularGridInterpolator(
self.points,
self.values,
method='quintic'
)
def time_rgi_setup_interpolator(self, ndim, n_samples):
self.interp = interpolate.RegularGridInterpolator(
self.points,
self.values,
method='quintic'
)
def time_rgi(self, ndim, n_samples):
self.interp(self.xi)
| RGI_Quintic |
python | PrefectHQ__prefect | src/prefect/artifacts.py | {
"start": 9096,
"end": 9341
} | class ____(Artifact):
markdown: str
type: Optional[str] = "markdown"
async def aformat(self) -> str:
return self.markdown
@async_dispatch(aformat)
def format(self) -> str:
return self.markdown
| MarkdownArtifact |
python | streamlit__streamlit | lib/tests/streamlit/runtime/scriptrunner/magic_test.py | {
"start": 779,
"end": 6503
} | class ____(unittest.TestCase):
"""Test for Magic
The test counts the number of substitutions that magic.add_code do for
a few code snippets. The test passes if the expected number of
substitutions have been made.
"""
def _testCode(self, code: str, expected_count: int) -> None:
tree = magic.add_magic(code, "./")
count = 0
for node in ast.walk(tree):
# count the nodes where a substitution has been made, i.e.
# look for 'calls' to a '__streamlitmagic__' function
if type(node) is ast.Call and magic.MAGIC_MODULE_NAME in ast.dump(
node.func
):
count += 1
assert expected_count == count, (
f"There must be exactly {expected_count} {magic.MAGIC_MODULE_NAME} nodes, but found {count}"
)
def test_simple_statement(self):
"""Test simple statements"""
CODE_SIMPLE_STATEMENTS = """
a = 1
b = 10
a
b
"""
self._testCode(CODE_SIMPLE_STATEMENTS, 2)
def test_empty_ast(self):
"""Test empty AST"""
CODE_EMPTY_AST = ""
self._testCode(CODE_EMPTY_AST, 0)
def test_if_statement(self):
"""Test if statements"""
CODE_IF_STATEMENT = """
a = 1
if True:
a
if False:
a
elif False:
a
else:
a
else:
a
"""
self._testCode(CODE_IF_STATEMENT, 5)
def test_for_statement(self):
"""Test for statements"""
CODE_FOR_STATEMENT = """
a = 1
for i in range(10):
for j in range(2):
a
else:
a
else:
a
"""
self._testCode(CODE_FOR_STATEMENT, 3)
def test_try_statement(self):
"""Test try statements"""
CODE_TRY_STATEMENT = """
try:
a = 10
a
except RuntimeError:
a
except Exception:
try:
a
except RuntimeError:
a
except Exception:
a
else:
a
finally:
a
else:
a
finally:
a
"""
self._testCode(CODE_TRY_STATEMENT, 9)
@unittest.skipIf(
not sys.version_info >= (3, 11), "Not supported in this Python version"
)
def test_try_star_statement(self):
"""Test try statements with except* clauses"""
CODE_TRY_STAR_STATEMENT = """
try:
a = 10
a
except* RuntimeError:
a
except* Exception:
try:
a
except* RuntimeError:
a
except* Exception:
a
else:
a
finally:
a
else:
a
finally:
a
"""
self._testCode(CODE_TRY_STAR_STATEMENT, 9)
@unittest.skipIf(
not sys.version_info >= (3, 10), "Not supported in this Python version"
)
def test_match_statement(self):
"""Test match statements"""
CODE_MATCH_STATEMENT = """
a = 1
match a:
case 1:
a
case 2:
a
case _:
a
"""
self._testCode(CODE_MATCH_STATEMENT, 3)
def test_function_call_statement(self):
"""Test with function calls"""
CODE_FUNCTION_CALL = """
def myfunc(a):
a
a =10
myfunc(a)
"""
self._testCode(CODE_FUNCTION_CALL, 1)
def test_with_statement(self):
"""Test 'with' statements"""
CODE_WITH_STATEMENT = """
a = 10
with None:
a
"""
self._testCode(CODE_WITH_STATEMENT, 1)
def test_while_statement(self):
"""Test 'while' statements"""
CODE_WHILE_STATEMENT = """
a = 10
while True:
a
while True:
a
else:
a
else:
a
"""
self._testCode(CODE_WHILE_STATEMENT, 4)
def test_yield_statement(self):
"""Test that 'yield' expressions do not get magicked"""
CODE_YIELD_STATEMENT = """
def yield_func():
yield
"""
self._testCode(CODE_YIELD_STATEMENT, 0)
def test_yield_from_statement(self):
"""Test that 'yield from' expressions do not get magicked"""
CODE_YIELD_FROM_STATEMENT = """
def yield_func():
yield from None
"""
self._testCode(CODE_YIELD_FROM_STATEMENT, 0)
def test_await_expression(self):
"""Test that 'await' expressions do not get magicked"""
CODE_AWAIT_EXPRESSION = """
async def await_func(a):
await coro()
"""
self._testCode(CODE_AWAIT_EXPRESSION, 0)
def test_async_function_statement(self):
"""Test async function definitions"""
CODE_ASYNC_FUNCTION = """
async def myfunc(a):
a
"""
self._testCode(CODE_ASYNC_FUNCTION, 1)
def test_async_with_statement(self):
"""Test 'async with' statements"""
CODE_ASYNC_WITH = """
async def myfunc(a):
async with None:
a
"""
self._testCode(CODE_ASYNC_WITH, 1)
def test_async_for_statement(self):
"""Test 'async for' statements"""
CODE_ASYNC_FOR = """
async def myfunc(a):
async for _ in None:
a
"""
self._testCode(CODE_ASYNC_FOR, 1)
def test_docstring_is_ignored_func(self):
"""Test that docstrings don't print in the app"""
CODE = """
def myfunc(a):
'''This is the docstring'''
return 42
"""
self._testCode(CODE, 0)
def test_docstring_is_ignored_async_func(self):
"""Test that async function docstrings don't print in the app by default"""
CODE = """
async def myfunc(a):
'''This is the docstring for async func'''
return 43
"""
self._testCode(CODE, 0)
def test_display_root_docstring_config_option(self):
"""Test that magic.displayRootDocString skips/includes docstrings when True/False."""
CODE = """
'''This is a top-level docstring'''
'this is a string that should always be magicked'
def my_func():
'''This is a function docstring'''
'this is a string that should always be magicked'
| MagicTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/tool_text_editor_20250124_param.py | {
"start": 326,
"end": 725
} | class ____(TypedDict, total=False):
name: Required[Literal["str_replace_editor"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["text_editor_20250124"]]
cache_control: Optional[CacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
| ToolTextEditor20250124Param |
python | pandas-dev__pandas | pandas/tests/io/formats/test_format.py | {
"start": 48803,
"end": 66944
} | class ____:
def test_freq_name_separation(self):
s = Series(
np.random.default_rng(2).standard_normal(10),
index=date_range("1/1/2000", periods=10),
name=0,
)
result = repr(s)
assert "Freq: D, Name: 0" in result
def test_unicode_name_in_footer(self):
s = Series([1, 2], name="\u05e2\u05d1\u05e8\u05d9\u05ea")
sf = fmt.SeriesFormatter(s, name="\u05e2\u05d1\u05e8\u05d9\u05ea")
sf._get_footer() # should not raise exception
def test_east_asian_unicode_series(self, using_infer_string):
# not aligned properly because of east asian width
# unicode index
s = Series(["a", "bb", "CCC", "D"], index=["あ", "いい", "ううう", "ええええ"])
expected = "".join(
[
"あ a\n",
"いい bb\n",
"ううう CCC\n",
"ええええ D\ndtype: object",
]
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# unicode values
s = Series(["あ", "いい", "ううう", "ええええ"], index=["a", "bb", "c", "ddd"])
expected = "".join(
[
"a あ\n",
"bb いい\n",
"c ううう\n",
"ddd ええええ\n",
"dtype: object",
]
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# both
s = Series(
["あ", "いい", "ううう", "ええええ"],
index=["ああ", "いいいい", "う", "えええ"],
)
expected = "".join(
[
"ああ あ\n",
"いいいい いい\n",
"う ううう\n",
"えええ ええええ\n",
"dtype: object",
]
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# unicode footer
s = Series(
["あ", "いい", "ううう", "ええええ"],
index=["ああ", "いいいい", "う", "えええ"],
name="おおおおおおお",
)
expected = (
"ああ あ\nいいいい いい\nう ううう\n"
"えええ ええええ\nName: おおおおおおお, dtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# MultiIndex
idx = MultiIndex.from_tuples(
[("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]
)
s = Series([1, 22, 3333, 44444], index=idx)
expected = (
"あ いい 1\n"
"う え 22\n"
"おおお かかかか 3333\n"
"き くく 44444\ndtype: int64"
)
assert repr(s) == expected
# object dtype, shorter than unicode repr
s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"])
expected = (
"1 1\nAB 22\nNaN 3333\nあああ 44444\ndtype: int64"
)
assert repr(s) == expected
# object dtype, longer than unicode repr
s = Series(
[1, 22, 3333, 44444], index=[1, "AB", Timestamp("2011-01-01"), "あああ"]
)
expected = (
"1 1\n"
"AB 22\n"
"2011-01-01 00:00:00 3333\n"
"あああ 44444\ndtype: int64"
)
assert repr(s) == expected
# truncate
with option_context("display.max_rows", 3):
s = Series(["あ", "いい", "ううう", "ええええ"], name="おおおおおおお")
expected = (
"0 あ\n ... \n"
"3 ええええ\n"
"Name: おおおおおおお, Length: 4, dtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
s.index = ["ああ", "いいいい", "う", "えええ"]
expected = (
"ああ あ\n ... \n"
"えええ ええええ\n"
"Name: おおおおおおお, Length: 4, dtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# Enable Unicode option -----------------------------------------
with option_context("display.unicode.east_asian_width", True):
# unicode index
s = Series(
["a", "bb", "CCC", "D"],
index=["あ", "いい", "ううう", "ええええ"],
)
expected = (
"あ a\nいい bb\nううう CCC\n"
"ええええ D\ndtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# unicode values
s = Series(
["あ", "いい", "ううう", "ええええ"],
index=["a", "bb", "c", "ddd"],
)
expected = (
"a あ\nbb いい\nc ううう\n"
"ddd ええええ\ndtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# both
s = Series(
["あ", "いい", "ううう", "ええええ"],
index=["ああ", "いいいい", "う", "えええ"],
)
expected = (
"ああ あ\n"
"いいいい いい\n"
"う ううう\n"
"えええ ええええ\ndtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# unicode footer
s = Series(
["あ", "いい", "ううう", "ええええ"],
index=["ああ", "いいいい", "う", "えええ"],
name="おおおおおおお",
)
expected = (
"ああ あ\n"
"いいいい いい\n"
"う ううう\n"
"えええ ええええ\n"
"Name: おおおおおおお, dtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# MultiIndex
idx = MultiIndex.from_tuples(
[("あ", "いい"), ("う", "え"), ("おおお", "かかかか"), ("き", "くく")]
)
s = Series([1, 22, 3333, 44444], index=idx)
expected = (
"あ いい 1\n"
"う え 22\n"
"おおお かかかか 3333\n"
"き くく 44444\n"
"dtype: int64"
)
assert repr(s) == expected
# object dtype, shorter than unicode repr
s = Series([1, 22, 3333, 44444], index=[1, "AB", np.nan, "あああ"])
expected = (
"1 1\nAB 22\nNaN 3333\n"
"あああ 44444\ndtype: int64"
)
assert repr(s) == expected
# object dtype, longer than unicode repr
s = Series(
[1, 22, 3333, 44444],
index=[1, "AB", Timestamp("2011-01-01"), "あああ"],
)
expected = (
"1 1\n"
"AB 22\n"
"2011-01-01 00:00:00 3333\n"
"あああ 44444\ndtype: int64"
)
assert repr(s) == expected
# truncate
with option_context("display.max_rows", 3):
s = Series(["あ", "いい", "ううう", "ええええ"], name="おおおおおおお")
expected = (
"0 あ\n ... \n"
"3 ええええ\n"
"Name: おおおおおおお, Length: 4, dtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
s.index = ["ああ", "いいいい", "う", "えええ"]
expected = (
"ああ あ\n"
" ... \n"
"えええ ええええ\n"
"Name: おおおおおおお, Length: 4, dtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
# ambiguous unicode
s = Series(
["¡¡", "い¡¡", "ううう", "ええええ"],
index=["ああ", "¡¡¡¡いい", "¡¡", "えええ"],
)
expected = (
"ああ ¡¡\n"
"¡¡¡¡いい い¡¡\n"
"¡¡ ううう\n"
"えええ ええええ\ndtype: object"
)
if using_infer_string:
expected = expected.replace("dtype: object", "dtype: str")
assert repr(s) == expected
def test_float_trim_zeros(self):
vals = [
2.08430917305e10,
3.52205017305e10,
2.30674817305e10,
2.03954217305e10,
5.59897817305e10,
]
for line in repr(Series(vals)).split("\n"):
if line.startswith("dtype:"):
continue
if _three_digit_exp():
assert "+010" in line
else:
assert "+10" in line
@pytest.mark.parametrize(
"start_date",
[
"2017-01-01 23:59:59.999999999",
"2017-01-01 23:59:59.99999999",
"2017-01-01 23:59:59.9999999",
"2017-01-01 23:59:59.999999",
"2017-01-01 23:59:59.99999",
"2017-01-01 23:59:59.9999",
],
)
def test_datetimeindex_highprecision(self, start_date):
# GH19030
# Check that high-precision time values for the end of day are
# included in repr for DatetimeIndex
s1 = Series(date_range(start=start_date, freq="D", periods=5))
result = str(s1)
assert start_date in result
dti = date_range(start=start_date, freq="D", periods=5)
s2 = Series(3, index=dti)
result = str(s2.index)
assert start_date in result
def test_mixed_datetime64(self):
df = DataFrame({"A": [1, 2], "B": ["2012-01-01", "2012-01-02"]})
df["B"] = pd.to_datetime(df.B)
result = repr(df.loc[0])
assert "2012-01-01" in result
def test_period(self):
# GH 12615
index = pd.period_range("2013-01", periods=6, freq="M")
s = Series(np.arange(6, dtype="int64"), index=index)
exp = (
"2013-01 0\n"
"2013-02 1\n"
"2013-03 2\n"
"2013-04 3\n"
"2013-05 4\n"
"2013-06 5\n"
"Freq: M, dtype: int64"
)
assert str(s) == exp
s = Series(index)
exp = (
"0 2013-01\n"
"1 2013-02\n"
"2 2013-03\n"
"3 2013-04\n"
"4 2013-05\n"
"5 2013-06\n"
"dtype: period[M]"
)
assert str(s) == exp
# periods with mixed freq
s = Series(
[
pd.Period("2011-01", freq="M"),
pd.Period("2011-02-01", freq="D"),
pd.Period("2011-03-01 09:00", freq="h"),
]
)
exp = (
"0 2011-01\n1 2011-02-01\n"
"2 2011-03-01 09:00\ndtype: object"
)
assert str(s) == exp
def test_max_multi_index_display(self):
# GH 7101
# doc example (indexing.rst)
# multi-index
arrays = [
["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],
]
tuples = list(zip(*arrays))
index = MultiIndex.from_tuples(tuples, names=["first", "second"])
s = Series(np.random.default_rng(2).standard_normal(8), index=index)
with option_context("display.max_rows", 10):
assert len(str(s).split("\n")) == 10
with option_context("display.max_rows", 3):
assert len(str(s).split("\n")) == 5
with option_context("display.max_rows", 2):
assert len(str(s).split("\n")) == 5
with option_context("display.max_rows", 1):
assert len(str(s).split("\n")) == 4
with option_context("display.max_rows", 0):
assert len(str(s).split("\n")) == 10
# index
s = Series(np.random.default_rng(2).standard_normal(8), None)
with option_context("display.max_rows", 10):
assert len(str(s).split("\n")) == 9
with option_context("display.max_rows", 3):
assert len(str(s).split("\n")) == 4
with option_context("display.max_rows", 2):
assert len(str(s).split("\n")) == 4
with option_context("display.max_rows", 1):
assert len(str(s).split("\n")) == 3
with option_context("display.max_rows", 0):
assert len(str(s).split("\n")) == 9
# Make sure #8532 is fixed
def test_consistent_format(self):
s = Series([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.9999, 1, 1] * 10)
with option_context("display.max_rows", 10, "display.show_dimensions", False):
res = repr(s)
exp = (
"0 1.0000\n1 1.0000\n2 1.0000\n3 "
"1.0000\n4 1.0000\n ... \n125 "
"1.0000\n126 1.0000\n127 0.9999\n128 "
"1.0000\n129 1.0000\ndtype: float64"
)
assert res == exp
def chck_ncols(self, s):
lines = [
line for line in repr(s).split("\n") if not re.match(r"[^\.]*\.+", line)
][:-1]
ncolsizes = len({len(line.strip()) for line in lines})
assert ncolsizes == 1
def test_format_explicit(self, using_infer_string):
test_sers = gen_series_formatting()
with option_context("display.max_rows", 4, "display.show_dimensions", False):
res = repr(test_sers["onel"])
exp = "0 a\n1 a\n ..\n98 a\n99 a\ndtype: object"
if using_infer_string:
exp = exp.replace("dtype: object", "dtype: str")
assert exp == res
res = repr(test_sers["twol"])
exp = "0 ab\n1 ab\n ..\n98 ab\n99 ab\ndtype: object"
if using_infer_string:
exp = exp.replace("dtype: object", "dtype: str")
assert exp == res
res = repr(test_sers["asc"])
exp = (
"0 a\n1 ab\n ... \n4 abcde\n5 "
"abcdef\ndtype: object"
)
if using_infer_string:
exp = exp.replace("dtype: object", "dtype: str")
assert exp == res
res = repr(test_sers["desc"])
exp = (
"5 abcdef\n4 abcde\n ... \n1 ab\n0 "
"a\ndtype: object"
)
if using_infer_string:
exp = exp.replace("dtype: object", "dtype: str")
assert exp == res
def test_ncols(self):
test_sers = gen_series_formatting()
for s in test_sers.values():
self.chck_ncols(s)
def test_max_rows_eq_one(self):
s = Series(range(10), dtype="int64")
with option_context("display.max_rows", 1):
strrepr = repr(s).split("\n")
exp1 = ["0", "0"]
res1 = strrepr[0].split()
assert exp1 == res1
exp2 = [".."]
res2 = strrepr[1].split()
assert exp2 == res2
def test_truncate_ndots(self):
def getndots(s):
return len(re.match(r"[^\.]*(\.*)", s).groups()[0])
s = Series([0, 2, 3, 6])
with option_context("display.max_rows", 2):
strrepr = repr(s).replace("\n", "")
assert getndots(strrepr) == 2
s = Series([0, 100, 200, 400])
with option_context("display.max_rows", 2):
strrepr = repr(s).replace("\n", "")
assert getndots(strrepr) == 3
def test_show_dimensions(self):
# gh-7117
s = Series(range(5))
assert "Length" not in repr(s)
with option_context("display.max_rows", 4):
assert "Length" in repr(s)
with option_context("display.show_dimensions", True):
assert "Length" in repr(s)
with option_context("display.max_rows", 4, "display.show_dimensions", False):
assert "Length" not in repr(s)
def test_repr_min_rows(self):
s = Series(range(20))
# default setting no truncation even if above min_rows
assert ".." not in repr(s)
s = Series(range(61))
# default of max_rows 60 triggers truncation if above
assert ".." in repr(s)
with option_context("display.max_rows", 10, "display.min_rows", 4):
# truncated after first two rows
assert ".." in repr(s)
assert "2 " not in repr(s)
with option_context("display.max_rows", 12, "display.min_rows", None):
# when set to None, follow value of max_rows
assert "5 5" in repr(s)
with option_context("display.max_rows", 10, "display.min_rows", 12):
# when set value higher as max_rows, use the minimum
assert "5 5" not in repr(s)
with option_context("display.max_rows", None, "display.min_rows", 12):
# max_rows of None -> never truncate
assert ".." not in repr(s)
| TestSeriesFormatting |
python | huggingface__transformers | src/transformers/quantizers/quantizer_aqlm.py | {
"start": 1086,
"end": 3490
} | class ____(HfQuantizer):
"""
Quantizer of the AQLM method. Enables the loading of prequantized models.
"""
requires_calibration = True
required_packages = ["aqlm"]
optimum_quantizer = None
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
super().__init__(quantization_config, **kwargs)
self.quantization_config = quantization_config
def validate_environment(self, *args, **kwargs):
if not is_accelerate_available():
raise ImportError("Using `aqlm` quantization requires Accelerate: `pip install accelerate`")
if not is_aqlm_available():
raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`")
def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
if dtype is None:
if torch.cuda.is_available():
dtype = torch.float16
logger.info(
"CUDA available. Assuming AQLM inference on GPU and loading the model in `torch.float16`. To overwrite it, set `dtype` manually."
)
else:
dtype = torch.float32
logger.info(
"CUDA is unavailable. Assuming AQLM inference on CPU and loading the model in `torch.float32`. To overwrite it, set `dtype` manually."
)
return dtype
def _process_model_before_weight_loading(
self,
model: "PreTrainedModel",
**kwargs,
):
replace_with_aqlm_linear(
model,
quantization_config=self.quantization_config,
linear_weights_not_to_quantize=self.quantization_config.linear_weights_not_to_quantize,
)
model.config.quantization_config = self.quantization_config
@property
def is_trainable(self) -> bool:
aqlm_supports_training = version.parse(importlib.metadata.version("aqlm")) >= version.parse("1.0.2")
if aqlm_supports_training:
return True
else:
logger.warning(
f"Currently installed `aqlm` version ({importlib.metadata.version('aqlm')}) doesn't support training. If you wish to train a quantized model, please update `aqlm` with `pip install aqlm>=1.0.2`"
)
return False
def is_serializable(self, safe_serialization=None):
return True
| AqlmHfQuantizer |
python | keras-team__keras | keras/src/layers/rnn/conv_lstm_test.py | {
"start": 1367,
"end": 2275
} | class ____(testing.TestCase):
def test_correctness(self):
x = np.arange(450).reshape((2, 3, 5, 5, 3)).astype("float32") / 100
s1 = np.arange(200).reshape((2, 5, 5, 4)).astype("float32") / 100
s2 = np.arange(200).reshape((2, 5, 5, 4)).astype("float32") / 100
if backend.config.image_data_format() == "channels_first":
x = x.transpose((0, 1, 4, 2, 3))
s1 = s1.transpose((0, 3, 1, 2))
s2 = s2.transpose((0, 3, 1, 2))
layer = ConvLSTM(
rank=2,
filters=4,
kernel_size=3,
padding="same",
kernel_initializer=initializers.Constant(0.01),
recurrent_initializer=initializers.Constant(0.02),
)
output = layer(x, initial_state=[s1, s2])
output = backend.convert_to_numpy(output)
self.assertAllClose(np.sum(output), 119.812454)
| ConvLSTMTest |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 28536,
"end": 28906
} | class ____:
"""Class level constant, raises when trying to set the attribute"""
__slots__ = ["value"]
def __init__(self, value):
self.value = value
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
raise TypeError(f"Const value does not support assignment [value={self.value}]")
| Const |
python | scrapy__scrapy | tests/test_pipelines.py | {
"start": 11142,
"end": 16866
} | class ____:
"""Tests for the deprecated spider arg handling in MiddlewareManager.
Here because MiddlewareManager doesn't have methods that could take a spider arg."""
@pytest.fixture
def crawler(self) -> Crawler:
return get_crawler(Spider)
@deferred_f_from_coro_f
async def test_deprecated_spider_arg_no_crawler_spider(
self, crawler: Crawler
) -> None:
"""Crawler is provided, but doesn't have a spider, the methods raise an exception.
The instance passed to a deprecated method is ignored."""
mwman = ItemPipelineManager(crawler=crawler)
with (
pytest.warns(
ScrapyDeprecationWarning,
match=r"DeprecatedSpiderArgPipeline.open_spider\(\) requires a spider argument",
),
pytest.warns(
ScrapyDeprecationWarning,
match=r"DeprecatedSpiderArgPipeline.close_spider\(\) requires a spider argument",
),
pytest.warns(
ScrapyDeprecationWarning,
match=r"DeprecatedSpiderArgPipeline.process_item\(\) requires a spider argument",
),
):
mwman._add_middleware(DeprecatedSpiderArgPipeline())
with (
pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.open_spider\(\) is deprecated, use open_spider_async\(\) instead",
),
pytest.raises(
ValueError,
match=r"ItemPipelineManager needs to access self\.crawler\.spider but it is None",
),
):
mwman.open_spider(DefaultSpider())
with pytest.raises(
ValueError,
match=r"ItemPipelineManager needs to access self\.crawler\.spider but it is None",
):
await mwman.open_spider_async()
with (
pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.close_spider\(\) is deprecated, use close_spider_async\(\) instead",
),
pytest.raises(
ValueError,
match=r"ItemPipelineManager needs to access self\.crawler\.spider but it is None",
),
):
mwman.close_spider(DefaultSpider())
with pytest.raises(
ValueError,
match=r"ItemPipelineManager needs to access self\.crawler\.spider but it is None",
):
await mwman.close_spider_async()
def test_deprecated_spider_arg_with_crawler(self, crawler: Crawler) -> None:
"""Crawler is provided and has a spider, works. The instance passed to a deprecated method
is ignored, even if mismatched."""
mwman = ItemPipelineManager(crawler=crawler)
crawler.spider = crawler._create_spider("foo")
with pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.open_spider\(\) is deprecated, use open_spider_async\(\) instead",
):
mwman.open_spider(DefaultSpider())
with pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.close_spider\(\) is deprecated, use close_spider_async\(\) instead",
):
mwman.close_spider(DefaultSpider())
def test_deprecated_spider_arg_without_crawler(self) -> None:
"""The first instance passed to a deprecated method is used. Mismatched ones raise an error."""
with pytest.warns(
ScrapyDeprecationWarning,
match="was called without the crawler argument",
):
mwman = ItemPipelineManager()
spider = DefaultSpider()
with pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.open_spider\(\) is deprecated, use open_spider_async\(\) instead",
):
mwman.open_spider(spider)
with (
pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.close_spider\(\) is deprecated, use close_spider_async\(\) instead",
),
pytest.raises(
RuntimeError, match="Different instances of Spider were passed"
),
):
mwman.close_spider(DefaultSpider())
with pytest.warns(
ScrapyDeprecationWarning,
match=r"ItemPipelineManager.close_spider\(\) is deprecated, use close_spider_async\(\) instead",
):
mwman.close_spider(spider)
@deferred_f_from_coro_f
async def test_no_spider_arg_without_crawler(self) -> None:
"""If no crawler and no spider arg, raise an error."""
with pytest.warns(
ScrapyDeprecationWarning,
match="was called without the crawler argument",
):
mwman = ItemPipelineManager()
with (
pytest.warns(
ScrapyDeprecationWarning,
match=r"DeprecatedSpiderArgPipeline.open_spider\(\) requires a spider argument",
),
pytest.warns(
ScrapyDeprecationWarning,
match=r"DeprecatedSpiderArgPipeline.close_spider\(\) requires a spider argument",
),
pytest.warns(
ScrapyDeprecationWarning,
match=r"DeprecatedSpiderArgPipeline.process_item\(\) requires a spider argument",
),
):
mwman._add_middleware(DeprecatedSpiderArgPipeline())
with (
pytest.raises(
ValueError,
match="has no known Spider instance",
),
):
await mwman.open_spider_async()
| TestMiddlewareManagerSpider |
python | walkccc__LeetCode | solutions/2359. Find Closest Node to Given Two Nodes/2359.py | {
"start": 0,
"end": 631
} | class ____:
def closestMeetingNode(self, edges: list[int], node1: int, node2: int) -> int:
MAX = 10000
dist1 = self._getDist(edges, node1)
dist2 = self._getDist(edges, node2)
minDist = MAX
ans = -1
for i, (d1, d2) in enumerate(zip(dist1, dist2)):
if min(d1, d2) >= 0:
maxDist = max(d1, d2)
if maxDist < minDist:
minDist = maxDist
ans = i
return ans
def _getDist(self, edges: list[int], u: int) -> list[int]:
dist = [-1] * len(edges)
d = 0
while u != -1 and dist[u] == -1:
dist[u] = d
d += 1
u = edges[u]
return dist
| Solution |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_class_instantiated.py | {
"start": 564,
"end": 676
} | class ____(metaclass=abc.ABCMeta):
@abc.abstractmethod
def test(self):
""" do nothing. """
| BadClass |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid/views.py | {
"start": 4743,
"end": 6148
} | class ____(View):
provider_class = OpenIDProvider
def get(self, request):
provider = self.provider = self.provider_class(request)
endpoint = request.GET.get("openid.op_endpoint", "")
client = self.get_client(provider, endpoint)
response = self.get_openid_response(client)
if response.status == consumer.SUCCESS:
login = provider.sociallogin_from_response(request, response)
login.state = SocialLogin.unstash_state(request)
return self.complete_login(login)
else:
if response.status == consumer.CANCEL:
error = AuthError.CANCELLED
else:
error = AuthError.UNKNOWN
return self.render_error(error)
post = get
def complete_login(self, login):
return complete_social_login(self.request, login)
def render_error(self, error):
return render_authentication_error(self.request, self.provider, error=error)
def get_client(self, provider, endpoint):
return _openid_consumer(self.request, provider, endpoint)
def get_openid_response(self, client):
return client.complete(
dict(list(self.request.GET.items()) + list(self.request.POST.items())),
self.request.build_absolute_uri(self.request.path),
)
callback = csrf_exempt(OpenIDCallbackView.as_view())
| OpenIDCallbackView |
python | numba__numba | numba/tests/test_sets.py | {
"start": 15026,
"end": 15317
} | class ____(TestSets):
"""
Test sets with floating-point keys.
"""
# Only a few basic tests here, as the sanity of most operations doesn't
# depend on the key type.
def _range(self, stop):
return np.arange(stop, dtype=np.float32) * np.float32(0.1)
| TestFloatSets |
python | run-llama__llama_index | llama-index-core/tests/output_parsers/test_pydantic.py | {
"start": 311,
"end": 2029
} | class ____(BaseModel):
__test__ = False
title: str
attr_dict: AttrDict
def test_pydantic() -> None:
"""Test pydantic output parser."""
output = """\
Here is the valid JSON:
{
"title": "TestModel",
"attr_dict": {
"test_attr": "test_attr",
"foo": 2
}
}
"""
parser = PydanticOutputParser(output_cls=TestModel)
parsed_output = parser.parse(output)
assert isinstance(parsed_output, TestModel)
assert parsed_output.title == "TestModel"
assert isinstance(parsed_output.attr_dict, AttrDict)
assert parsed_output.attr_dict.test_attr == "test_attr"
assert parsed_output.attr_dict.foo == 2
# TODO: figure out testing conditions
with pytest.raises(ValueError):
output = "hello world"
parsed_output = parser.parse(output)
def test_pydantic_format() -> None:
"""Test pydantic format."""
query = "hello world"
parser = PydanticOutputParser(output_cls=AttrDict)
formatted_query = parser.format(query)
assert "hello world" in formatted_query
def test_pydantic_format_with_blocks() -> None:
"""Test pydantic format with blocks."""
parser = PydanticOutputParser(output_cls=AttrDict)
messages = [
ChatMessage(
role="user",
blocks=[
TextBlock(text="hello world"),
ImageBlock(
url="https://pbs.twimg.com/media/GVhGD1PXkAANfPV?format=jpg&name=4096x4096"
),
TextBlock(text="hello world"),
],
)
]
formatted_messages = parser.format_messages(messages)
assert "hello world" in formatted_messages[0].blocks[-1].text
| TestModel |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 69590,
"end": 71767
} | class ____(unittest.TestCase):
def setUp(self):
self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb
)
factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb
)
db = LocalFakeDB()
db.Add(self.factory_test1_fd)
db.Add(factory_test2_fd)
self.pool = descriptor_pool.DescriptorPool(db)
file_desc = self.pool.FindFileByName(
'google/protobuf/internal/factory_test1.proto'
)
self.message_desc = file_desc.message_types_by_name['Factory1Message']
bad_db = BadDB()
bad_db.Add(self.factory_test1_fd)
self.bad_pool = descriptor_pool.DescriptorPool(bad_db)
def testFindExtensionByNumber(self):
ext = self.pool.FindExtensionByNumber(self.message_desc, 1001)
self.assertEqual(ext.name, 'one_more_field')
def testFindAllExtensions(self):
extensions = self.pool.FindAllExtensions(self.message_desc)
self.assertEqual(len(extensions), 4)
def testIgnoreBadFindExtensionByNumber(self):
file_desc = self.bad_pool.FindFileByName(
'google/protobuf/internal/factory_test1.proto'
)
message_desc = file_desc.message_types_by_name['Factory1Message']
with self.assertRaises(KeyError):
ext = self.bad_pool.FindExtensionByNumber(message_desc, 1001)
def testIgnoreBadFindAllExtensions(self):
file_desc = self.bad_pool.FindFileByName(
'google/protobuf/internal/factory_test1.proto'
)
message_desc = file_desc.message_types_by_name['Factory1Message']
extensions = self.bad_pool.FindAllExtensions(message_desc)
self.assertEqual(len(extensions), 0)
def testFindAllExtensionsReturnsNoneList(self):
db = BadDB2()
db.Add(self.factory_test1_fd)
pool = descriptor_pool.DescriptorPool(db)
file_desc = pool.FindFileByName(
'google/protobuf/internal/factory_test1.proto'
)
message_desc = file_desc.message_types_by_name['Factory1Message']
extensions = self.bad_pool.FindAllExtensions(message_desc)
self.assertEqual(len(extensions), 0)
if __name__ == '__main__':
unittest.main()
| FallBackDBTest |
python | Netflix__metaflow | metaflow/_vendor/click/exceptions.py | {
"start": 5599,
"end": 6459
} | class ____(UsageError):
"""Raised if click attempted to handle an option that does not
exist.
.. versionadded:: 4.0
"""
def __init__(self, option_name, message=None, possibilities=None, ctx=None):
if message is None:
message = "no such option: {}".format(option_name)
UsageError.__init__(self, message, ctx)
self.option_name = option_name
self.possibilities = possibilities
def format_message(self):
bits = [self.message]
if self.possibilities:
if len(self.possibilities) == 1:
bits.append("Did you mean {}?".format(self.possibilities[0]))
else:
possibilities = sorted(self.possibilities)
bits.append("(Possible options: {})".format(", ".join(possibilities)))
return " ".join(bits)
| NoSuchOption |
python | aio-libs__aiohttp | aiohttp/http_exceptions.py | {
"start": 1538,
"end": 1626
} | class ____(PayloadEncodingError):
"""transfer encoding error."""
| TransferEncodingError |
python | scikit-learn__scikit-learn | sklearn/ensemble/_weight_boosting.py | {
"start": 28532,
"end": 39704
} | class ____(_RoutingNotSupportedMixin, RegressorMixin, BaseWeightBoosting):
"""An AdaBoost regressor.
An AdaBoost [1] regressor is a meta-estimator that begins by fitting a
regressor on the original dataset and then fits additional copies of the
regressor on the same dataset but where the weights of instances are
adjusted according to the error of the current prediction. As such,
subsequent regressors focus more on difficult cases.
This class implements the algorithm known as AdaBoost.R2 [2].
Read more in the :ref:`User Guide <adaboost>`.
.. versionadded:: 0.14
Parameters
----------
estimator : object, default=None
The base estimator from which the boosted ensemble is built.
If ``None``, then the base estimator is
:class:`~sklearn.tree.DecisionTreeRegressor` initialized with
`max_depth=3`.
.. versionadded:: 1.2
`base_estimator` was renamed to `estimator`.
n_estimators : int, default=50
The maximum number of estimators at which boosting is terminated.
In case of perfect fit, the learning procedure is stopped early.
Values must be in the range `[1, inf)`.
learning_rate : float, default=1.0
Weight applied to each regressor at each boosting iteration. A higher
learning rate increases the contribution of each regressor. There is
a trade-off between the `learning_rate` and `n_estimators` parameters.
Values must be in the range `(0.0, inf)`.
loss : {'linear', 'square', 'exponential'}, default='linear'
The loss function to use when updating the weights after each
boosting iteration.
random_state : int, RandomState instance or None, default=None
Controls the random seed given at each `estimator` at each
boosting iteration.
Thus, it is only used when `estimator` exposes a `random_state`.
In addition, it controls the bootstrap of the weights used to train the
`estimator` at each boosting iteration.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Attributes
----------
estimator_ : estimator
The base estimator from which the ensemble is grown.
.. versionadded:: 1.2
`base_estimator_` was renamed to `estimator_`.
estimators_ : list of regressors
The collection of fitted sub-estimators.
estimator_weights_ : ndarray of floats
Weights for each estimator in the boosted ensemble.
estimator_errors_ : ndarray of floats
Regression error for each estimator in the boosted ensemble.
feature_importances_ : ndarray of shape (n_features,)
The impurity-based feature importances if supported by the
``estimator`` (when based on decision trees).
Warning: impurity-based feature importances can be misleading for
high cardinality features (many unique values). See
:func:`sklearn.inspection.permutation_importance` as an alternative.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
AdaBoostClassifier : An AdaBoost classifier.
GradientBoostingRegressor : Gradient Boosting Classification Tree.
sklearn.tree.DecisionTreeRegressor : A decision tree regressor.
References
----------
.. [1] Y. Freund, R. Schapire, "A Decision-Theoretic Generalization of
on-Line Learning and an Application to Boosting", 1995.
.. [2] H. Drucker, "Improving Regressors using Boosting Techniques", 1997.
Examples
--------
>>> from sklearn.ensemble import AdaBoostRegressor
>>> from sklearn.datasets import make_regression
>>> X, y = make_regression(n_features=4, n_informative=2,
... random_state=0, shuffle=False)
>>> regr = AdaBoostRegressor(random_state=0, n_estimators=100)
>>> regr.fit(X, y)
AdaBoostRegressor(n_estimators=100, random_state=0)
>>> regr.predict([[0, 0, 0, 0]])
array([4.7972])
>>> regr.score(X, y)
0.9771
For a detailed example of utilizing :class:`~sklearn.ensemble.AdaBoostRegressor`
to fit a sequence of decision trees as weak learners, please refer to
:ref:`sphx_glr_auto_examples_ensemble_plot_adaboost_regression.py`.
"""
_parameter_constraints: dict = {
**BaseWeightBoosting._parameter_constraints,
"loss": [StrOptions({"linear", "square", "exponential"})],
}
def __init__(
self,
estimator=None,
*,
n_estimators=50,
learning_rate=1.0,
loss="linear",
random_state=None,
):
super().__init__(
estimator=estimator,
n_estimators=n_estimators,
learning_rate=learning_rate,
random_state=random_state,
)
self.loss = loss
self.random_state = random_state
def _validate_estimator(self):
"""Check the estimator and set the estimator_ attribute."""
super()._validate_estimator(default=DecisionTreeRegressor(max_depth=3))
def _boost(self, iboost, X, y, sample_weight, random_state):
"""Implement a single boost for regression
Perform a single boost according to the AdaBoost.R2 algorithm and
return the updated sample weights.
Parameters
----------
iboost : int
The index of the current boost iteration.
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples.
y : array-like of shape (n_samples,)
The target values (class labels in classification, real numbers in
regression).
sample_weight : array-like of shape (n_samples,)
The current sample weights.
random_state : RandomState
The RandomState instance used if the base estimator accepts a
`random_state` attribute.
Controls also the bootstrap of the weights used to train the weak
learner.
Returns
-------
sample_weight : array-like of shape (n_samples,) or None
The reweighted sample weights.
If None then boosting has terminated early.
estimator_weight : float
The weight for the current boost.
If None then boosting has terminated early.
estimator_error : float
The regression error for the current boost.
If None then boosting has terminated early.
"""
estimator = self._make_estimator(random_state=random_state)
# Weighted sampling of the training set with replacement
bootstrap_idx = random_state.choice(
np.arange(_num_samples(X)),
size=_num_samples(X),
replace=True,
p=sample_weight,
)
# Fit on the bootstrapped sample and obtain a prediction
# for all samples in the training set
X_ = _safe_indexing(X, bootstrap_idx)
y_ = _safe_indexing(y, bootstrap_idx)
estimator.fit(X_, y_)
y_predict = estimator.predict(X)
error_vect = np.abs(y_predict - y)
sample_mask = sample_weight > 0
masked_sample_weight = sample_weight[sample_mask]
masked_error_vector = error_vect[sample_mask]
error_max = masked_error_vector.max()
if error_max != 0:
masked_error_vector /= error_max
if self.loss == "square":
masked_error_vector **= 2
elif self.loss == "exponential":
masked_error_vector = 1.0 - np.exp(-masked_error_vector)
# Calculate the average loss
estimator_error = (masked_sample_weight * masked_error_vector).sum()
if estimator_error <= 0:
# Stop if fit is perfect
return sample_weight, 1.0, 0.0
elif estimator_error >= 0.5:
# Discard current estimator only if it isn't the only one
if len(self.estimators_) > 1:
self.estimators_.pop(-1)
return None, None, None
beta = estimator_error / (1.0 - estimator_error)
# Boost weight using AdaBoost.R2 alg
estimator_weight = self.learning_rate * np.log(1.0 / beta)
if not iboost == self.n_estimators - 1:
sample_weight[sample_mask] *= np.power(
beta, (1.0 - masked_error_vector) * self.learning_rate
)
return sample_weight, estimator_weight, estimator_error
def _get_median_predict(self, X, limit):
# Evaluate predictions of all estimators
predictions = np.array([est.predict(X) for est in self.estimators_[:limit]]).T
# Sort the predictions
sorted_idx = np.argsort(predictions, axis=1)
# Find index of median prediction for each sample
weight_cdf = np.cumsum(self.estimator_weights_[sorted_idx], axis=1)
median_or_above = weight_cdf >= 0.5 * weight_cdf[:, -1][:, np.newaxis]
median_idx = median_or_above.argmax(axis=1)
median_estimators = sorted_idx[np.arange(_num_samples(X)), median_idx]
# Return median predictions
return predictions[np.arange(_num_samples(X)), median_estimators]
def predict(self, X):
"""Predict regression value for X.
The predicted regression value of an input sample is computed
as the weighted median prediction of the regressors in the ensemble.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrix can be CSC, CSR, COO,
DOK, or LIL. COO, DOK, and LIL are converted to CSR.
Returns
-------
y : ndarray of shape (n_samples,)
The predicted regression values.
"""
check_is_fitted(self)
X = self._check_X(X)
return self._get_median_predict(X, len(self.estimators_))
def staged_predict(self, X):
"""Return staged predictions for X.
The predicted regression value of an input sample is computed
as the weighted median prediction of the regressors in the ensemble.
This generator method yields the ensemble prediction after each
iteration of boosting and therefore allows monitoring, such as to
determine the prediction on a test set after each boost.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples.
Yields
------
y : generator of ndarray of shape (n_samples,)
The predicted regression values.
"""
check_is_fitted(self)
X = self._check_X(X)
for i, _ in enumerate(self.estimators_, 1):
yield self._get_median_predict(X, limit=i)
| AdaBoostRegressor |
python | huggingface__transformers | src/transformers/models/qwen2_audio/modeling_qwen2_audio.py | {
"start": 10579,
"end": 11156
} | class ____(PreTrainedModel):
config: Qwen2AudioConfig
base_model_prefix = "model"
input_modalities = ("audio", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen2AudioAttention"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
@auto_docstring(
custom_intro="""
The audio model from Qwen2Audio without any head or projection on top.
"""
)
# Copied from transformers.models.whisper.modeling_whisper.WhisperEncoder with Whisper->Qwen2Audio
| Qwen2AudioPreTrainedModel |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 16396,
"end": 17677
} | class ____:
def test_basic(self, xp):
xp_assert_close(windows.flattop(6, sym=False, xp=xp),
xp.asarray([-0.000421051, -0.051263156, 0.19821053, 1.0,
0.19821053, -0.051263156], dtype=xp.float64))
xp_assert_close(windows.flattop(7, sym=False, xp=xp),
xp.asarray([-0.000421051, -0.03684078115492348,
0.01070371671615342, 0.7808739149387698,
0.7808739149387698, 0.01070371671615342,
-0.03684078115492348], dtype=xp.float64))
xp_assert_close(windows.flattop(6, xp=xp),
xp.asarray([-0.000421051, -0.0677142520762119,
0.6068721525762117, 0.6068721525762117,
-0.0677142520762119, -0.000421051],
dtype=xp.float64))
xp_assert_close(windows.flattop(7, True, xp=xp),
xp.asarray([-0.000421051, -0.051263156, 0.19821053, 1.0,
0.19821053, -0.051263156, -0.000421051],
dtype=xp.float64))
@make_xp_test_case(windows.gaussian)
| TestFlatTop |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/return_in_init.py | {
"start": 49,
"end": 99
} | class ____:
def __init__(self):
return
| A |
python | pola-rs__polars | py-polars/tests/unit/constructors/test_constructors.py | {
"start": 1563,
"end": 1646
} | class ____:
a: str
b: int
c: _TestBazDC
@dataclasses.dataclass
| _TestBarDC |
python | plotly__plotly.py | plotly/graph_objs/scattermapbox/hoverlabel/_font.py | {
"start": 233,
"end": 17174
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermapbox.hoverlabel"
_path_str = "scattermapbox.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
"style",
"stylesrc",
"textcase",
"textcasesrc",
"variant",
"variantsrc",
"weight",
"weightsrc",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `family`.
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def linepositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`lineposition`.
The 'linepositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["linepositionsrc"]
@linepositionsrc.setter
def linepositionsrc(self, val):
self["linepositionsrc"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def shadowsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `shadow`.
The 'shadowsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["shadowsrc"]
@shadowsrc.setter
def shadowsrc(self, val):
self["shadowsrc"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `size`.
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def stylesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `style`.
The 'stylesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["stylesrc"]
@stylesrc.setter
def stylesrc(self, val):
self["stylesrc"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def textcasesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `textcase`.
The 'textcasesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textcasesrc"]
@textcasesrc.setter
def textcasesrc(self, val):
self["textcasesrc"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def variantsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `variant`.
The 'variantsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["variantsrc"]
@variantsrc.setter
def variantsrc(self, val):
self["variantsrc"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def weightsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `weight`.
The 'weightsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["weightsrc"]
@weightsrc.setter
def weightsrc(self, val):
self["weightsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattermapbox.
hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Font
"""
super().__init__("font")
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.scattermapbox.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattermapbox.hoverlabel.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("family", arg, family)
self._set_property("familysrc", arg, familysrc)
self._set_property("lineposition", arg, lineposition)
self._set_property("linepositionsrc", arg, linepositionsrc)
self._set_property("shadow", arg, shadow)
self._set_property("shadowsrc", arg, shadowsrc)
self._set_property("size", arg, size)
self._set_property("sizesrc", arg, sizesrc)
self._set_property("style", arg, style)
self._set_property("stylesrc", arg, stylesrc)
self._set_property("textcase", arg, textcase)
self._set_property("textcasesrc", arg, textcasesrc)
self._set_property("variant", arg, variant)
self._set_property("variantsrc", arg, variantsrc)
self._set_property("weight", arg, weight)
self._set_property("weightsrc", arg, weightsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | has2k1__plotnine | plotnine/geoms/annotation_logticks.py | {
"start": 7178,
"end": 8969
} | class ____(annotate):
"""
Marginal log ticks.
If added to a plot that does not have a log10 axis
on the respective side, a warning will be issued.
Parameters
----------
sides :
Sides onto which to draw the marks. Any combination
chosen from the characters `btlr`, for *bottom*, *top*,
*left* or *right* side marks. If `coord_flip()` is used,
these are the sides *after* the flip.
alpha :
Transparency of the ticks
color :
Colour of the ticks
size :
Thickness of the ticks
linetype :
Type of line
lengths:
length of the ticks drawn for full / half / tenth
ticks relative to panel size
base :
Base of the logarithm in which the ticks will be
calculated. If `None`, the base used to log transform
the scale will be used.
"""
def __init__(
self,
sides: str = "bl",
alpha: float = 1,
color: str
| tuple[float, float, float]
| tuple[float, float, float, float] = "black",
size: float = 0.5,
linetype: Literal["solid", "dashed", "dashdot", "dotted"]
| Sequence[float] = "solid",
lengths: tuple[float, float, float] = (0.036, 0.0225, 0.012),
base: float | None = None,
):
if len(lengths) != 3:
raise ValueError(
"length for annotation_logticks must be a tuple of 3 floats"
)
self._annotation_geom = _geom_logticks(
sides=sides,
alpha=alpha,
color=color,
size=size,
linetype=linetype,
lengths=lengths,
base=base,
inherit_aes=False,
show_legend=False,
)
| annotation_logticks |
python | python__mypy | mypy/test/teststubtest.py | {
"start": 6317,
"end": 8208
} | class ____:
def __init__(self, stub: str, runtime: str, error: str | None) -> None:
self.stub = stub
self.runtime = runtime
self.error = error
def collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:
"""run_stubtest used to be slow, so we used this decorator to combine cases.
If you're reading this and bored, feel free to refactor this and make it more like
other mypy tests.
"""
def test(*args: Any, **kwargs: Any) -> None:
cases = list(fn(*args, **kwargs))
expected_errors = set()
for c in cases:
if c.error is None:
continue
expected_error = c.error
if expected_error == "":
expected_error = TEST_MODULE_NAME
elif not expected_error.startswith(f"{TEST_MODULE_NAME}."):
expected_error = f"{TEST_MODULE_NAME}.{expected_error}"
assert expected_error not in expected_errors, (
"collect_cases merges cases into a single stubtest invocation; we already "
"expect an error for {}".format(expected_error)
)
expected_errors.add(expected_error)
output = run_stubtest(
stub="\n\n".join(textwrap.dedent(c.stub.lstrip("\n")) for c in cases),
runtime="\n\n".join(textwrap.dedent(c.runtime.lstrip("\n")) for c in cases),
options=["--generate-allowlist"],
)
actual_errors = set(output.splitlines())
if actual_errors != expected_errors:
output = run_stubtest(
stub="\n\n".join(textwrap.dedent(c.stub.lstrip("\n")) for c in cases),
runtime="\n\n".join(textwrap.dedent(c.runtime.lstrip("\n")) for c in cases),
options=[],
)
assert actual_errors == expected_errors, output
return test
| Case |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.