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 | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instigation.py | {
"start": 12545,
"end": 16101
} | class ____(graphene.ObjectType):
timestamp = graphene.Float()
evaluationResult = graphene.Field(lambda: GrapheneTickEvaluation)
class Meta:
name = "DryRunInstigationTick"
def __init__(
self,
selector: Union[ScheduleSelector, SensorSelector],
timestamp: Optional[float],
cursor: Optional[str] = None,
):
self._selector = check.inst_param(selector, "selector", (ScheduleSelector, SensorSelector))
self._cursor = cursor
super().__init__(
timestamp=check.opt_float_param(timestamp, "timestamp"),
)
def resolve_evaluationResult(self, graphene_info: ResolveInfo):
if not graphene_info.context.has_code_location(self._selector.location_name):
raise UserFacingGraphQLError(
GrapheneRepositoryLocationNotFound(location_name=self._selector.location_name)
)
code_location = graphene_info.context.get_code_location(self._selector.location_name)
if isinstance(self._selector, SensorSelector):
sensor = graphene_info.context.get_sensor(self._selector)
if not sensor:
raise UserFacingGraphQLError(
GrapheneSensorNotFoundError(self._selector.sensor_name)
)
sensor_data: Union[SensorExecutionData, SerializableErrorInfo]
try:
sensor_data = code_location.get_sensor_execution_data(
name=self._selector.sensor_name,
instance=graphene_info.context.instance,
repository_handle=sensor.handle.repository_handle,
cursor=self._cursor,
last_tick_completion_time=None,
last_run_key=None,
last_sensor_start_time=None,
log_key=None,
)
except Exception:
sensor_data = serializable_error_info_from_exc_info(sys.exc_info())
return GrapheneTickEvaluation(sensor_data, sensor)
else:
schedule = graphene_info.context.get_schedule(self._selector)
if not schedule:
raise UserFacingGraphQLError(
GrapheneScheduleNotFoundError(self._selector.schedule_name)
)
if not self.timestamp:
raise Exception(
"No tick timestamp provided when attempting to dry-run schedule"
f" {self._selector.schedule_name}."
)
timezone_str = schedule.execution_timezone
if not timezone_str:
timezone_str = "UTC"
next_tick_datetime = next(schedule.execution_time_iterator(self.timestamp))
schedule_data: Union[ScheduleExecutionData, SerializableErrorInfo]
try:
schedule_data = code_location.get_schedule_execution_data(
instance=graphene_info.context.instance,
repository_handle=schedule.handle.repository_handle,
schedule_name=schedule.name,
scheduled_execution_time=TimestampWithTimezone(
next_tick_datetime.timestamp(),
timezone_str,
),
log_key=None,
)
except Exception:
schedule_data = serializable_error_info_from_exc_info(sys.exc_info())
return GrapheneTickEvaluation(schedule_data, schedule)
| GrapheneDryRunInstigationTick |
python | readthedocs__readthedocs.org | readthedocs/builds/managers.py | {
"start": 3155,
"end": 3443
} | class ____(VersionManager):
"""
Version manager that only includes external version.
It will only include pull request/merge request Versions in the queries.
"""
def get_queryset(self):
return super().get_queryset().filter(type=EXTERNAL)
| ExternalVersionManager |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 12830,
"end": 12987
} | class ____(ByteorderValues):
"""Check the byteorder in unicode (size 1009, UCS4 values)"""
ulen = 1009
ucs_value = ucs4_value
| TestByteorder_1009_UCS4 |
python | huggingface__transformers | src/transformers/models/voxtral/modeling_voxtral.py | {
"start": 15240,
"end": 21750
} | class ____(VoxtralPreTrainedModel, GenerationMixin):
_keep_in_fp32_modules_strict = ["embed_positions"]
def __init__(self, config):
super().__init__(config)
self.vocab_size = config.text_config.vocab_size
self.audio_tower = AutoModel.from_config(config.audio_config)
self.language_model = AutoModelForCausalLM.from_config(config.text_config)
self.multi_modal_projector = VoxtralMultiModalProjector(config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value):
self.language_model.set_input_embeddings(value)
def get_output_embeddings(self):
return self.language_model.get_output_embeddings()
def set_output_embeddings(self, new_embeddings):
self.language_model.set_output_embeddings(new_embeddings)
def set_decoder(self, decoder):
self.language_model.set_decoder(decoder)
def get_decoder(self):
return self.language_model.get_decoder()
def get_audio_features(self, input_features: torch.FloatTensor):
"""
This method is used to get the audio embeddings from input features (a log mel spectrogram), meaning inferring the audio encoder and the multi-modal projector.
Args:
input_features (`torch.FloatTensor`):
Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]` or a
`numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
`input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
Returns:
`torch.FloatTensor`:
The audio embeddings.
"""
audio_outputs = self.audio_tower(input_features)
audio_hidden_states = audio_outputs.last_hidden_state
audio_hidden_states = audio_hidden_states.reshape(-1, self.config.audio_config.intermediate_size)
audio_embeds = self.multi_modal_projector(audio_hidden_states)
return audio_embeds
def get_audio_embeds(self, input_features: torch.FloatTensor):
warnings.warn(
"The method `get_audio_embeds` is deprecated. Please use `get_audio_features` instead.", FutureWarning
)
return self.get_audio_features(input_features)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
input_features: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
r"""
Example:
```python
>>> from transformers import VoxtralForConditionalGeneration, AutoProcessor
>>> import torch
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> repo_id = "mistralai/Voxtral-Mini-3B-2507"
>>> processor = AutoProcessor.from_pretrained(repo_id)
>>> model = VoxtralForConditionalGeneration.from_pretrained(repo_id, dtype=torch.bfloat16, device_map=device)
>>> conversation = [
{
"role": "user",
"content": [
{
"type": "audio",
"url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav",
},
{"type": "text", "text": "What can you tell me about this audio?"},
],
}
]
>>> inputs = processor.apply_chat_template(conversation)
>>> inputs = inputs.to(device, dtype=torch.bfloat16)
>>> outputs = model.generate(**inputs, max_new_tokens=30)
>>> processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
["This audio is a humorous conversation between two friends, likely in English, where one of them is trying to figure out what the other's tattoo says."]
```"""
if inputs_embeds is None:
inputs_embeds = self.get_input_embeddings()(input_ids)
if input_features is not None and input_ids is not None:
audio_embeds = self.get_audio_features(input_features)
# replace text-audio token placeholders with audio embeddings
audio_token_mask = (input_ids == self.config.audio_token_id).unsqueeze(-1)
inputs_embeds = inputs_embeds.masked_scatter(
audio_token_mask.to(inputs_embeds.device), audio_embeds.to(inputs_embeds.device)
)
outputs: BaseModelOutputWithPast = self.language_model(
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
labels=labels,
use_cache=use_cache,
cache_position=cache_position,
logits_to_keep=logits_to_keep,
**kwargs,
)
return outputs
def prepare_inputs_for_generation(self, *args, **kwargs):
# Overwritten -- we should not pass input_features when we are in cached decoding stage
input_features = kwargs.pop("input_features", None)
cache_position = kwargs.get("cache_position")
model_inputs = super().prepare_inputs_for_generation(*args, **kwargs)
if cache_position is not None and cache_position[0] == 0:
# input_features should only be passed when we are not in cached decoding stage
model_inputs["input_features"] = input_features
return model_inputs
__all__ = ["VoxtralPreTrainedModel", "VoxtralEncoder", "VoxtralForConditionalGeneration"]
| VoxtralForConditionalGeneration |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/config.py | {
"start": 9133,
"end": 9296
} | class ____:
def __getattr__(self, attr: str) -> Any:
return getattr(_fixture_functions.add_to_marker, attr)
add_to_marker = _AddToMarker()
| _AddToMarker |
python | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_code_mapping.py | {
"start": 1229,
"end": 3280
} | class ____(TestCase):
"""These evaluate which files should be included as part of a repo."""
def test_filter_source_code_files(self) -> None:
source_code_files = filter_source_code_files(SENTRY_FILES)
assert source_code_files.index("bin/__init__.py") == 0
assert source_code_files.index("docs-ui/.eslintrc.js") == 3
with pytest.raises(ValueError):
source_code_files.index("README.md")
def test_filter_source_code_files_not_supported(self) -> None:
source_code_files = filter_source_code_files([])
assert source_code_files == []
source_code_files = filter_source_code_files([".env", "README"])
assert source_code_files == []
def test_should_not_include(self) -> None:
for file in [
"static/app/views/organizationRoot.spec.jsx",
"tests/foo.py",
]:
assert should_include(file) is False
def test_get_extension() -> None:
assert get_extension("") == ""
assert get_extension("f.py") == "py"
assert get_extension("f.xx") == "xx"
assert get_extension("./app/utils/handleXhrErrorResponse.tsx") == "tsx"
assert get_extension("[native code]") == ""
assert get_extension("/foo/bar/baz") == ""
assert get_extension("/gtm.js") == "js"
def test_buckets_logic() -> None:
frames = [
{"filename": "app://foo.js"},
{"filename": "./app/utils/handleXhrErrorResponse.tsx"},
{"filename": "getsentry/billing/tax/manager.py"},
{"filename": "/cronscripts/monitoringsync.php"},
]
helper = CodeMappingTreesHelper({})
buckets = helper._stacktrace_buckets(frames)
assert buckets == {
"/cronscripts/": [create_frame_info({"filename": "/cronscripts/monitoringsync.php"})],
"./app": [create_frame_info({"filename": "./app/utils/handleXhrErrorResponse.tsx"})],
"app:": [create_frame_info({"filename": "app://foo.js"})],
"getsentry": [create_frame_info({"filename": "getsentry/billing/tax/manager.py"})],
}
| TestRepoFiles |
python | kamyu104__LeetCode-Solutions | Python/minimum-xor-sum-of-two-arrays.py | {
"start": 2065,
"end": 2620
} | class ____(object):
def minimumXORSum(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
dp = [(float("inf"), float("inf"))]*(2**len(nums2))
dp[0] = (0, 0)
for mask in xrange(len(dp)):
bit = 1
for i in xrange(len(nums2)):
if (mask&bit) == 0:
dp[mask|bit] = min(dp[mask|bit], (dp[mask][0]+(nums1[dp[mask][1]]^nums2[i]), dp[mask][1]+1))
bit <<= 1
return dp[-1][0]
| Solution2 |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/ghostwriter/test_ghostwriter_cli.py | {
"start": 4344,
"end": 6101
} | class ____:
@staticmethod
def my_staticmethod(seq: Sequence[int]) -> List[int]:
return sorted(seq)
@classmethod
def my_classmethod(cls, seq: Sequence[int]) -> List[int]:
return sorted(seq)
"""
@pytest.mark.parametrize("func", ["my_staticmethod", "my_classmethod"])
def test_can_import_from_class(tmp_path, func):
(tmp_path / "mycode.py").write_text(CLASS_CODE_TO_TEST, encoding="utf-8")
result = run(f"hypothesis write mycode.MyClass.{func}", cwd=tmp_path)
assert result.returncode == 0
assert "Error: " not in result.stderr
@pytest.mark.parametrize(
"classname,thing,kind",
[
("XX", "", "class"),
("MyClass", " and 'MyClass' class", "attribute"),
("my_func", " and 'my_func' attribute", "attribute"),
],
)
def test_error_import_from_class(tmp_path, classname, thing, kind):
(tmp_path / "mycode.py").write_text(CLASS_CODE_TO_TEST, encoding="utf-8")
result = run(f"hypothesis write mycode.{classname}.XX", cwd=tmp_path)
msg = f"Error: Found the 'mycode' module{thing}, but it doesn't have a 'XX' {kind}."
assert result.returncode == 2
assert msg in result.stderr
def test_magic_discovery_from_module(tmp_path):
(tmp_path / "mycode.py").write_text(CLASS_CODE_TO_TEST, encoding="utf-8")
result = run("hypothesis write mycode", cwd=tmp_path)
assert result.returncode == 0
assert "my_func" in result.stdout
assert "MyClass.my_staticmethod" in result.stdout
assert "MyClass.my_classmethod" in result.stdout
ROUNDTRIP_CODE_TO_TEST = """
from typing import Union
import json
def to_json(json: Union[dict,list]) -> str:
return json.dumps(json)
def from_json(json: str) -> Union[dict,list]:
return json.loads(json)
| MyClass |
python | getsentry__sentry | src/sentry/sentry_apps/api/serializers/sentry_app_avatar.py | {
"start": 404,
"end": 849
} | class ____(Serializer):
def serialize(
self, obj: SentryAppAvatar | RpcSentryAppAvatar, attrs, user, **kwargs
) -> SentryAppAvatarSerializerResponse:
return {
"avatarType": obj.get_avatar_type_display(),
"avatarUuid": obj.ident or "",
"avatarUrl": obj.absolute_url(),
"color": obj.color,
"photoType": obj.get_avatar_photo_type(),
}
| SentryAppAvatarSerializer |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 27880,
"end": 28496
} | class ____(nn.Module):
def __init__(self, config: FlavaPossibleConfigs) -> None:
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# Copied from transformers.models.vit.modeling_vit.ViTOutput.forward
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = hidden_states + input_tensor
return hidden_states
| FlavaOutput |
python | kamyu104__LeetCode-Solutions | Python/valid-anagram.py | {
"start": 491,
"end": 732
} | class ____(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return collections.Counter(s) == collections.Counter(t)
# Time: O(nlogn)
# Space: O(n)
| Solution2 |
python | faif__python-patterns | patterns/behavioral/state.py | {
"start": 310,
"end": 624
} | class ____:
"""Base state. This is to share functionality"""
def scan(self) -> None:
"""Scan the dial to the next station"""
self.pos += 1
if self.pos == len(self.stations):
self.pos = 0
print(f"Scanning... Station is {self.stations[self.pos]} {self.name}")
| State |
python | walkccc__LeetCode | solutions/2519. Count the Number of K-Big Indices/2519.py | {
"start": 421,
"end": 1016
} | class ____:
def kBigIndices(self, nums: list[int], k: int) -> int:
n = len(nums)
leftTree = FenwickTree(n)
rightTree = FenwickTree(n)
# left[i] := the number of `nums` < nums[i] with index < i
left = [0] * n
# right[i] := the number of `nums` < nums[i] with index > i
right = [0] * n
for i, num in enumerate(nums):
left[i] = leftTree.get(num - 1)
leftTree.add(num, 1)
for i in range(n - 1, -1, -1):
right[i] = rightTree.get(nums[i] - 1)
rightTree.add(nums[i], 1)
return sum(l >= k and r >= k for l, r in zip(left, right))
| Solution |
python | getsentry__sentry | tests/sentry/issues/test_ingest.py | {
"start": 15757,
"end": 35980
} | class ____(OccurrenceTestMixin, TestCase):
def test_new_group(self) -> None:
occurrence = self.build_occurrence(type=ErrorGroupType.type_id)
event = self.store_event(
data={
"platform": "javascript",
"sdk": {"name": "sentry.javascript.nextjs", "version": "1.2.3"},
},
project_id=self.project.id,
)
with patch("sentry.issues.ingest.metrics.incr") as mock_metrics_incr:
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
assert group_info.is_new
assert not group_info.is_regression
group = group_info.group
assert group.title == occurrence.issue_title
assert group.platform == event.platform
assert group.level == LOG_LEVELS_MAP.get(occurrence.level)
assert group.last_seen == event.datetime
assert group.first_seen == event.datetime
assert group.active_at == event.datetime
assert group.issue_type == occurrence.type
assert group.first_release is None
assert group.title == occurrence.issue_title
assert group.data["metadata"]["value"] == occurrence.subtitle
assert group.culprit == occurrence.culprit
assert group.message == "<unlabeled event> something bad happened it was bad api/123"
assert group.location() == event.location
mock_metrics_incr.assert_any_call(
"group.created",
skip_internal=True,
tags={
"platform": "javascript",
"type": ErrorGroupType.type_id,
"sdk": "sentry.javascript.nextjs",
},
)
def test_new_group_multiple_fingerprint(self) -> None:
fingerprint = ["hi", "bye"]
occurrence = self.build_occurrence(type=ErrorGroupType.type_id, fingerprint=fingerprint)
event = self.store_event(project_id=self.project.id, data={})
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
assert group_info.is_new
assert not group_info.is_regression
group = group_info.group
assert group.title == occurrence.issue_title
grouphashes = set(GroupHash.objects.filter(group=group).values_list("hash", flat=True))
assert set(hash_fingerprint(fingerprint)) == grouphashes
def test_existing_group(self) -> None:
event = self.store_event(data={}, project_id=self.project.id)
occurrence = self.build_occurrence(fingerprint=["some-fingerprint"])
save_issue_from_occurrence(occurrence, event, None)
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(
fingerprint=["some-fingerprint"], subtitle="new subtitle", issue_title="new title"
)
with self.tasks():
updated_group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert updated_group_info is not None
updated_group = updated_group_info.group
updated_group.refresh_from_db()
assert updated_group_info.group.id == updated_group.id
assert not updated_group_info.is_new
assert not updated_group_info.is_regression
assert updated_group.title == new_occurrence.issue_title
assert updated_group.data["metadata"]["value"] == new_occurrence.subtitle
assert updated_group.culprit == new_occurrence.culprit
assert updated_group.location() == event.location
assert updated_group.times_seen == 2
assert updated_group.message == "<unlabeled event> new title new subtitle api/123"
def test_existing_group_multiple_fingerprints(self) -> None:
fingerprint = ["some-fingerprint"]
event = self.store_event(data={}, project_id=self.project.id)
occurrence = self.build_occurrence(fingerprint=fingerprint)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
assert group_info.is_new
grouphashes = set(
GroupHash.objects.filter(group=group_info.group).values_list("hash", flat=True)
)
assert set(hash_fingerprint(fingerprint)) == grouphashes
fingerprint = ["some-fingerprint", "another-fingerprint"]
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(fingerprint=fingerprint)
with self.tasks():
updated_group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert updated_group_info is not None
assert group_info.group.id == updated_group_info.group.id
assert not updated_group_info.is_new
assert not updated_group_info.is_regression
grouphashes = set(
GroupHash.objects.filter(group=group_info.group).values_list("hash", flat=True)
)
assert set(hash_fingerprint(fingerprint)) == grouphashes
def test_existing_group_multiple_fingerprints_overlap(self) -> None:
fingerprint = ["some-fingerprint"]
group_info = save_issue_from_occurrence(
self.build_occurrence(fingerprint=fingerprint),
self.store_event(data={}, project_id=self.project.id),
None,
)
assert group_info is not None
assert group_info.is_new
grouphashes = set(
GroupHash.objects.filter(group=group_info.group).values_list("hash", flat=True)
)
assert set(hash_fingerprint(fingerprint)) == grouphashes
other_fingerprint = ["another-fingerprint"]
other_group_info = save_issue_from_occurrence(
self.build_occurrence(fingerprint=other_fingerprint),
self.store_event(data={}, project_id=self.project.id),
None,
)
assert other_group_info is not None
assert other_group_info.is_new
grouphashes = set(
GroupHash.objects.filter(group=other_group_info.group).values_list("hash", flat=True)
)
assert set(hash_fingerprint(other_fingerprint)) == grouphashes
# Should process the in order, and not join an already used fingerprint
overlapping_fingerprint = ["another-fingerprint", "some-fingerprint"]
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(fingerprint=overlapping_fingerprint)
with self.tasks():
overlapping_group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert overlapping_group_info is not None
assert other_group_info.group.id == overlapping_group_info.group.id
assert not overlapping_group_info.is_new
assert not overlapping_group_info.is_regression
grouphashes = set(
GroupHash.objects.filter(group=group_info.group).values_list("hash", flat=True)
)
assert set(hash_fingerprint(fingerprint)) == grouphashes
other_grouphashes = set(
GroupHash.objects.filter(group=other_group_info.group).values_list("hash", flat=True)
)
assert set(hash_fingerprint(other_fingerprint)) == other_grouphashes
def test_existing_group_different_type(self) -> None:
event = self.store_event(data={}, project_id=self.project.id)
occurrence = self.build_occurrence(fingerprint=["some-fingerprint"])
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(
fingerprint=["some-fingerprint"], type=MonitorIncidentType.type_id
)
with mock.patch("sentry.issues.ingest.logger") as logger:
assert save_issue_from_occurrence(new_occurrence, new_event, None) is None
logger.error.assert_called_once_with(
"save_issue_from_occurrence.type_mismatch",
extra={
"issue_type": group_info.group.issue_type.slug,
"occurrence_type": MonitorIncidentType.slug,
"event_type": "platform",
"group_id": group_info.group.id,
},
)
def test_rate_limited(self) -> None:
MockGranted = namedtuple("MockGranted", ["granted"])
event = self.store_event(data={}, project_id=self.project.id)
occurrence = self.build_occurrence()
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(fingerprint=["another-fingerprint"])
with (
mock.patch("sentry.issues.ingest.metrics") as metrics,
mock.patch(
"sentry.issues.ingest.issue_rate_limiter.check_and_use_quotas",
return_value=[MockGranted(granted=False)],
) as check_and_use_quotas,
):
assert save_issue_from_occurrence(new_occurrence, new_event, None) is None
metrics.incr.assert_called_once_with("issues.issue.dropped.rate_limiting")
assert check_and_use_quotas.call_count == 1
assert check_and_use_quotas.call_args[0][0] == [
RequestedQuota(
f"issue-platform-issues:{self.project.id}:{occurrence.type.slug}",
1,
[occurrence.type.creation_quota],
)
]
def test_noise_reduction(self) -> None:
# Access project before patching registry to ensure it's created with grouptypes registered
project_id = self.project.id
with patch("sentry.issues.grouptype.registry", new=GroupTypeRegistry()):
@dataclass(frozen=True)
class TestGroupType(GroupType):
type_id = 1
slug = "test"
description = "Test"
category = GroupCategory.PROFILE.value
category_v2 = GroupCategory.MOBILE.value
noise_config = NoiseConfig(ignore_limit=2)
event = self.store_event(data={}, project_id=project_id)
occurrence = self.build_occurrence(type=TestGroupType.type_id)
with mock.patch("sentry.issues.ingest.metrics") as metrics:
assert save_issue_from_occurrence(occurrence, event, None) is None
metrics.incr.assert_called_once_with(
"issues.issue.dropped.noise_reduction", tags={"group_type": "test"}
)
new_event = self.store_event(data={}, project_id=project_id)
new_occurrence = self.build_occurrence(type=TestGroupType.type_id)
group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert group_info is not None
def test_frame_mix_metric_logged(self) -> None:
event = self.store_event(
data={
"platform": "javascript",
"sdk": {"name": "sentry.javascript.nextjs", "version": "1.2.3"},
},
project_id=self.project.id,
)
# Normally this is done by `normalize_stacktraces_for_grouping`, but that can't be mocked
# because it's imported inside its calling function to avoid circular imports
event.data.setdefault("metadata", {})
event.data["metadata"]["in_app_frame_mix"] = "in-app-only"
with patch("sentry.issues.ingest.metrics.incr") as mock_metrics_incr:
occurrence = self.build_occurrence()
save_issue_from_occurrence(occurrence, event, None)
mock_metrics_incr.assert_any_call(
"grouping.in_app_frame_mix",
sample_rate=1.0,
tags={
"platform": "javascript",
"frame_mix": "in-app-only",
"sdk": "sentry.javascript.nextjs",
},
)
def test_frame_mix_metric_not_logged(self) -> None:
event = self.store_event(data={}, project_id=self.project.id)
assert event.get_event_metadata().get("in_app_frame_mix") is None
with patch("sentry.issues.ingest.metrics.incr") as mock_metrics_incr:
occurrence = self.build_occurrence()
save_issue_from_occurrence(occurrence, event, None)
metrics_logged = [call.args[0] for call in mock_metrics_incr.mock_calls]
assert "grouping.in_app_frame_mix" not in metrics_logged
def test_new_group_with_default_priority(self) -> None:
occurrence = self.build_occurrence()
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
assert group_info.group.priority == PriorityLevel.LOW
def test_new_group_with_priority(self) -> None:
occurrence = self.build_occurrence(priority=PriorityLevel.HIGH)
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
assert group_info.group.priority == PriorityLevel.HIGH
def test_update_open_period(self) -> None:
fingerprint = ["some-fingerprint"]
occurrence = self.build_occurrence(
initial_issue_priority=PriorityLevel.MEDIUM,
fingerprint=fingerprint,
)
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
group = group_info.group
assert group.priority == PriorityLevel.MEDIUM
open_period = get_latest_open_period(group)
assert open_period is not None
assert open_period.data["highest_seen_priority"] == PriorityLevel.MEDIUM
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(
fingerprint=["some-fingerprint"],
initial_issue_priority=PriorityLevel.HIGH,
)
with self.tasks():
updated_group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert updated_group_info is not None
group.refresh_from_db()
assert group.priority == PriorityLevel.HIGH
open_period.refresh_from_db()
assert open_period.data["highest_seen_priority"] == PriorityLevel.HIGH
def test_group_with_priority_locked(self) -> None:
occurrence = self.build_occurrence(priority=PriorityLevel.HIGH)
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
group = group_info.group
assert group.priority == PriorityLevel.HIGH
assert group.priority_locked_at is None
handle_priority(
priority=PriorityLevel.LOW.to_str(),
group_list=[group],
acting_user=None,
project_lookup={self.project.id: self.project},
)
occurrence = self.build_occurrence(priority=PriorityLevel.HIGH)
event = self.store_event(data={}, project_id=self.project.id)
save_issue_from_occurrence(occurrence, event, None)
group.refresh_from_db()
assert group.priority == PriorityLevel.LOW
assert group.priority_locked_at is not None
def test_create_open_period_activity_entry(self) -> None:
fingerprint = ["some-fingerprint"]
occurrence = self.build_occurrence(
initial_issue_priority=PriorityLevel.MEDIUM,
fingerprint=fingerprint,
type=MetricIssue.type_id,
)
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
group = group_info.group
open_period = get_latest_open_period(group)
assert open_period is not None
activity_updates = GroupOpenPeriodActivity.objects.filter(group_open_period=open_period)
assert len(activity_updates) == 1
assert activity_updates[0].type == OpenPeriodActivityType.OPENED
assert activity_updates[0].value == PriorityLevel.MEDIUM
def test_update_group_priority_open_period_activity_entry(self) -> None:
fingerprint = ["some-fingerprint"]
occurrence = self.build_occurrence(
initial_issue_priority=PriorityLevel.MEDIUM,
fingerprint=fingerprint,
type=MetricIssue.type_id,
)
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
group = group_info.group
assert group.priority == PriorityLevel.MEDIUM
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(
fingerprint=["some-fingerprint"],
type=MetricIssue.type_id,
initial_issue_priority=PriorityLevel.HIGH,
)
with self.tasks():
updated_group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert updated_group_info is not None
group.refresh_from_db()
assert group.priority == PriorityLevel.HIGH
open_period = get_latest_open_period(group)
assert open_period is not None
activity_updates = GroupOpenPeriodActivity.objects.filter(group_open_period=open_period)
assert len(activity_updates) == 2
assert activity_updates[0].type == OpenPeriodActivityType.OPENED
assert activity_updates[0].value == PriorityLevel.MEDIUM
assert activity_updates[1].type == OpenPeriodActivityType.STATUS_CHANGE
assert activity_updates[1].value == PriorityLevel.HIGH
@mock.patch("sentry.issues.ingest._process_existing_aggregate")
def test_update_group_priority_and_unresolve(self, mock_is_regression: mock.MagicMock) -> None:
# set up the group opening entry
fingerprint = ["some-fingerprint"]
occurrence = self.build_occurrence(
initial_issue_priority=PriorityLevel.MEDIUM,
fingerprint=fingerprint,
type=MetricIssue.type_id,
)
event = self.store_event(data={}, project_id=self.project.id)
group_info = save_issue_from_occurrence(occurrence, event, None)
assert group_info is not None
group = group_info.group
open_period = get_latest_open_period(group)
assert open_period is not None
activity_updates = GroupOpenPeriodActivity.objects.filter(group_open_period=open_period)
assert len(activity_updates) == 1
assert activity_updates[0].type == OpenPeriodActivityType.OPENED
assert activity_updates[0].value == PriorityLevel.MEDIUM
mock_is_regression.return_value = True
# mock a regression with priority change
new_event = self.store_event(data={}, project_id=self.project.id)
new_occurrence = self.build_occurrence(
fingerprint=["some-fingerprint"],
type=MetricIssue.type_id,
initial_issue_priority=PriorityLevel.HIGH,
)
with self.tasks():
updated_group_info = save_issue_from_occurrence(new_occurrence, new_event, None)
assert updated_group_info is not None
group.refresh_from_db()
assert group.priority == PriorityLevel.HIGH
mock_is_regression.assert_called()
activity_updates = GroupOpenPeriodActivity.objects.filter(group_open_period=open_period)
assert len(activity_updates) == 1
assert activity_updates[0].type == OpenPeriodActivityType.OPENED
assert activity_updates[0].value == PriorityLevel.HIGH
| SaveIssueFromOccurrenceTest |
python | openai__openai-python | src/openai/types/beta/thread_create_and_run_params.py | {
"start": 14464,
"end": 14875
} | class ____(ThreadCreateAndRunParamsBase):
stream: Required[Literal[True]]
"""
If `true`, returns a stream of events that happen during the Run as server-sent
events, terminating when the Run enters a terminal state with a `data: [DONE]`
message.
"""
ThreadCreateAndRunParams = Union[ThreadCreateAndRunParamsNonStreaming, ThreadCreateAndRunParamsStreaming]
| ThreadCreateAndRunParamsStreaming |
python | openai__openai-python | src/openai/types/realtime/response_text_done_event.py | {
"start": 198,
"end": 737
} | class ____(BaseModel):
content_index: int
"""The index of the content part in the item's content array."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the item."""
output_index: int
"""The index of the output item in the response."""
response_id: str
"""The ID of the response."""
text: str
"""The final text content."""
type: Literal["response.output_text.done"]
"""The event type, must be `response.output_text.done`."""
| ResponseTextDoneEvent |
python | Textualize__textual | src/textual/_xterm_parser.py | {
"start": 1861,
"end": 15630
} | class ____(Parser[Message]):
_re_sgr_mouse = re.compile(r"\x1b\[<(\d+);(-?\d+);(-?\d+)([Mm])")
def __init__(self, debug: bool = False) -> None:
self.last_x = 0.0
self.last_y = 0.0
self.mouse_pixels = False
self.terminal_size: tuple[int, int] | None = None
self.terminal_pixel_size: tuple[int, int] | None = None
self._debug_log_file = open("keys.log", "at") if debug else None
super().__init__()
self.debug_log("---")
def debug_log(self, *args: Any) -> None: # pragma: no cover
if self._debug_log_file is not None:
self._debug_log_file.write(" ".join(args) + "\n")
self._debug_log_file.flush()
def feed(self, data: str) -> Iterable[Message]:
self.debug_log(f"FEED {data!r}")
return super().feed(data)
def parse_mouse_code(self, code: str) -> Message | None:
sgr_match = self._re_sgr_mouse.match(code)
if sgr_match:
_buttons, _x, _y, state = sgr_match.groups()
buttons = int(_buttons)
x = float(int(_x) - 1)
y = float(int(_y) - 1)
if x < 0 or y < 0:
# TODO: Workaround for Ghostty erroneous negative coordinate bug
return None
if (
self.mouse_pixels
and self.terminal_pixel_size is not None
and self.terminal_size is not None
):
pixel_width, pixel_height = self.terminal_pixel_size
width, height = self.terminal_size
x_ratio = pixel_width / width
y_ratio = pixel_height / height
x /= x_ratio
y /= y_ratio
delta_x = int(x) - int(self.last_x)
delta_y = int(y) - int(self.last_y)
self.last_x = x
self.last_y = y
event_class: type[events.MouseEvent]
if buttons & 64:
event_class = [
events.MouseScrollUp,
events.MouseScrollDown,
events.MouseScrollLeft,
events.MouseScrollRight,
][buttons & 3]
button = 0
else:
button = (buttons + 1) & 3
# XTerm events for mouse movement can look like mouse button down events. But if there is no key pressed,
# it's a mouse move event.
if buttons & 32 or button == 0:
event_class = events.MouseMove
else:
event_class = events.MouseDown if state == "M" else events.MouseUp
event = event_class(
None,
x,
y,
delta_x,
delta_y,
button,
bool(buttons & 4),
bool(buttons & 8),
bool(buttons & 16),
screen_x=x,
screen_y=y,
)
return event
return None
def parse(
self, token_callback: TokenCallback
) -> Generator[Read1 | Peek1, str, None]:
ESC = "\x1b"
read1 = self.read1
sequence_to_key_events = self._sequence_to_key_events
paste_buffer: list[str] = []
bracketed_paste = False
def on_token(token: Message) -> None:
"""Hook to log events."""
self.debug_log(str(token))
if isinstance(token, events.Resize):
self.terminal_size = token.size
self.terminal_pixel_size = token.pixel_size
token_callback(token)
def on_key_token(event: events.Key) -> None:
"""Token callback wrapper for handling keys.
Args:
event: The key event to send to the callback.
This wrapper looks for keys that should be ignored, and filters
them out, logging the ignored sequence when it does.
"""
if event.key == Keys.Ignore:
self.debug_log(f"ignored={event.character!r}")
else:
on_token(event)
def reissue_sequence_as_keys(reissue_sequence: str) -> None:
"""Called when an escape sequence hasn't been understood.
Args:
reissue_sequence: Key sequence to report to the app.
"""
if reissue_sequence:
self.debug_log("REISSUE", repr(reissue_sequence))
for character in reissue_sequence:
key_events = sequence_to_key_events(character)
for event in key_events:
if event.key == "escape":
event = events.Key("circumflex_accent", "^")
on_token(event)
while not self.is_eof:
if not bracketed_paste and paste_buffer:
# We're at the end of the bracketed paste.
# The paste buffer has content, but the bracketed paste has finished,
# so we flush the paste buffer. We have to remove the final character
# since if bracketed paste has come to an end, we'll have added the
# ESC from the closing bracket, since at that point we didn't know what
# the full escape code was.
pasted_text = "".join(paste_buffer[:-1])
# Note the removal of NUL characters: https://github.com/Textualize/textual/issues/1661
on_token(events.Paste(pasted_text.replace("\x00", "")))
paste_buffer.clear()
try:
character = yield read1()
except ParseEOF:
return
if bracketed_paste:
paste_buffer.append(character)
self.debug_log(f"character={character!r}")
if character != ESC:
if not bracketed_paste:
for event in sequence_to_key_events(character):
on_key_token(event)
if not character:
return
continue
# # Could be the escape key was pressed OR the start of an escape sequence
sequence: str = ESC
def send_escape() -> None:
"""Send escape key and reissue sequence."""
on_token(events.Key("escape", "\x1b"))
reissue_sequence_as_keys(sequence[1:])
while True:
try:
new_character = yield read1(constants.ESCAPE_DELAY)
except ParseTimeout:
send_escape()
break
except ParseEOF:
send_escape()
return
if new_character == ESC:
send_escape()
sequence = character
continue
else:
sequence += new_character
if len(sequence) > _MAX_SEQUENCE_SEARCH_THRESHOLD:
reissue_sequence_as_keys(sequence)
break
self.debug_log(f"sequence={sequence!r}")
if sequence in SPECIAL_SEQUENCES:
if sequence == FOCUSIN:
on_token(events.AppFocus())
elif sequence == FOCUSOUT:
on_token(events.AppBlur())
elif sequence == BRACKETED_PASTE_START:
bracketed_paste = True
elif sequence == BRACKETED_PASTE_END:
bracketed_paste = False
break
if match := _re_in_band_window_resize.fullmatch(sequence):
height, width, pixel_height, pixel_width = [
group.partition(":")[0] for group in match.groups()
]
resize_event = events.Resize.from_dimensions(
(int(width), int(height)),
(int(pixel_width), int(pixel_height)),
)
self.terminal_size = resize_event.size
self.terminal_pixel_size = resize_event.pixel_size
self.mouse_pixels = True
on_token(resize_event)
break
if not bracketed_paste:
# Check cursor position report
cursor_position_match = _re_cursor_position.match(sequence)
if cursor_position_match is not None:
row, column = map(int, cursor_position_match.groups())
x = int(column) - 1
y = int(row) - 1
on_token(events.CursorPosition(x, y))
break
# Was it a pressed key event that we received?
key_events = list(sequence_to_key_events(sequence))
for key_event in key_events:
on_key_token(key_event)
if key_events:
break
# Or a mouse event?
mouse_match = _re_mouse_event.match(sequence)
if mouse_match is not None:
mouse_code = mouse_match.group(0)
mouse_event = self.parse_mouse_code(mouse_code)
if mouse_event is not None:
on_token(mouse_event)
break
# Or a mode report?
# (i.e. the terminal saying it supports a mode we requested)
mode_report_match = _re_terminal_mode_response.match(sequence)
if mode_report_match is not None:
mode_id = mode_report_match["mode_id"]
setting_parameter = int(mode_report_match["setting_parameter"])
if mode_id == "2026" and setting_parameter > 0:
on_token(messages.TerminalSupportsSynchronizedOutput())
elif (
mode_id == "2048"
and constants.SMOOTH_SCROLL
and not IS_ITERM
):
# TODO: iTerm is buggy in one or more of the protocols required here
in_band_event = (
messages.InBandWindowResize.from_setting_parameter(
setting_parameter
)
)
on_token(in_band_event)
break
if self._debug_log_file is not None:
self._debug_log_file.close()
self._debug_log_file = None
def _sequence_to_key_events(self, sequence: str) -> Iterable[events.Key]:
"""Map a sequence of code points on to a sequence of keys.
Args:
sequence: Sequence of code points.
Returns:
Keys
"""
if (match := _re_extended_key.fullmatch(sequence)) is not None:
number, modifiers, end = match.groups()
number = number or 1
if not (key := FUNCTIONAL_KEYS.get(f"{number}{end}", "")):
try:
key = _character_to_key(chr(int(number)))
except Exception:
key = chr(int(number))
key_tokens: list[str] = []
if modifiers:
modifier_bits = int(modifiers) - 1
# Not convinced of the utility in reporting caps_lock and num_lock
MODIFIERS = ("shift", "alt", "ctrl", "super", "hyper", "meta")
# Ignore caps_lock and num_lock modifiers
for bit, modifier in enumerate(MODIFIERS):
if modifier_bits & (1 << bit):
key_tokens.append(modifier)
key_tokens.sort()
key_tokens.append(key)
yield events.Key(
"+".join(key_tokens), sequence if len(sequence) == 1 else None
)
return
keys = ANSI_SEQUENCES_KEYS.get(sequence)
# If we're being asked to ignore the key...
if keys is IGNORE_SEQUENCE:
# ...build a special ignore key event, which has the ignore
# name as the key (that is, the key this sequence is bound
# to is the ignore key) and the sequence that was ignored as
# the character.
yield events.Key(Keys.Ignore, sequence)
return
if isinstance(keys, tuple):
# If the sequence mapped to a tuple, then it's values from the
# `Keys` enum. Raise key events from what we find in the tuple.
for key in keys:
yield events.Key(key.value, sequence if len(sequence) == 1 else None)
return
# If keys is a string, the intention is that it's a mapping to a
# character, which should really be treated as the sequence for the
# purposes of the next step...
if isinstance(keys, str):
sequence = keys
# If the sequence is a single character, attempt to process it as a
# key.
if len(sequence) == 1:
try:
if not sequence.isalnum():
name = _character_to_key(sequence)
else:
name = sequence
name = KEY_NAME_REPLACEMENTS.get(name, name)
yield events.Key(name, sequence)
except Exception:
yield events.Key(sequence, sequence)
| XTermParser |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable.py | {
"start": 2343,
"end": 3070
} | class ____(Ancestor): # [used-before-assignment]
""" contains another class, which uses an undefined ancestor. """
class MissingAncestor(Ancestor1): # [used-before-assignment]
""" no op """
def test1(self):
""" It should trigger here, because the two classes
have the same scope.
"""
class UsingBeforeDefinition(Empty): # [used-before-assignment]
""" uses Empty before definition """
class Empty:
""" no op """
return UsingBeforeDefinition
def test(self):
""" Ancestor isn't defined yet, but we don't care. """
class MissingAncestor1(Ancestor):
""" no op """
return MissingAncestor1
| TestClass |
python | PyCQA__pylint | tests/functional/m/member/member_checks.py | {
"start": 4021,
"end": 4191
} | class ____:
"""Emit a warning when accessing __name__ from an instance."""
def __init__(self):
self.var = self.__name__ # [no-member]
| NoDunderNameInInstance |
python | numba__numba | numba/tests/test_array_methods.py | {
"start": 68040,
"end": 68744
} | class ____(TestCase):
def test_identity(self):
def check(a, b, expected):
cfunc = njit((typeof(a), typeof(b)))(pyfunc)
self.assertPreciseEqual(cfunc(a, b),
(expected, not expected))
pyfunc = identity_usecase
arr = np.zeros(10, dtype=np.int32).reshape((2, 5))
check(arr, arr, True)
check(arr, arr[:], True)
check(arr, arr.copy(), False)
check(arr, arr.view('uint32'), False)
check(arr, arr.T, False)
check(arr, arr[:-1], False)
# Other comparison operators ('==', etc.) are tested in test_ufuncs
if __name__ == '__main__':
unittest.main()
| TestArrayComparisons |
python | ethereum__web3.py | ens/exceptions.py | {
"start": 257,
"end": 414
} | class ____(ENSException, TypeError):
"""
An ENS exception wrapper for `TypeError`, for better control over
exception handling.
"""
| ENSTypeError |
python | ray-project__ray | python/ray/tune/utils/serialization.py | {
"start": 915,
"end": 1343
} | class ____(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, obj):
if obj.get("_type") == "CLOUDPICKLE_FALLBACK":
return self._from_cloudpickle(obj)
return obj
def _from_cloudpickle(self, obj):
return cloudpickle.loads(hex_to_binary(obj["value"]))
| TuneFunctionDecoder |
python | scipy__scipy | scipy/sparse/_base.py | {
"start": 605,
"end": 658
} | class ____(SparseWarning):
pass
| SparseFormatWarning |
python | dask__dask | dask/dataframe/dask_expr/_indexing.py | {
"start": 7302,
"end": 8029
} | class ____(Blockwise):
_parameters = ["frame", "iindexer", "cindexer"]
operation = staticmethod(methods.loc)
@functools.cached_property
def _meta(self):
if self.cindexer is None:
return self.frame._meta
else:
return self.frame._meta.loc[:, self.cindexer]
@functools.cached_property
def _layer_cache(self):
return convert_legacy_graph(self._layer())
def _task(self, name: Key, index: int) -> Task:
t = self._layer_cache[(self._name, index)]
if isinstance(t, Alias):
return Alias(name, t.target) # type: ignore[return-value]
elif t.key != name:
return Task(name, lambda x: x, t)
return t
| LocBase |
python | Unity-Technologies__ml-agents | conftest.py | {
"start": 773,
"end": 2872
} | class ____:
"""
WARNING: Should only be used within this file.
Handles handing out unique ports to tests that need ports to test.
Shares state between parallel tests on the same node via a text file and lockfile.
Should only be used through the base_port test fixture.
"""
def __init__(self):
self._port_alloc_file_path: Path = (
Path(tempfile.gettempdir()) / "next_mla_test_port.txt"
)
self._port_alloc_lock_path: Path = self._port_alloc_file_path.with_suffix(
".lock"
)
self.lock = FileLock(str(self._port_alloc_lock_path))
def reserve_n_ports(self, n: int) -> int:
with self.lock:
if self._port_alloc_file_path.is_file():
base_port = int(self._port_alloc_file_path.read_text())
else:
base_port = 6005
self._port_alloc_file_path.write_text(str(base_port + n))
return base_port
def setup_once_per_node(self) -> None:
"""
Clean up state files from previous runs, should only be called once per node.
Intended to only be called via xdist hooks.
"""
if self._port_alloc_lock_path.exists():
self._port_alloc_lock_path.unlink(missing_ok=True)
if self._port_alloc_file_path.exists():
self._port_alloc_file_path.unlink(missing_ok=True)
@pytest.fixture
def base_port(n_ports: int) -> int:
"""
Reserve a range of ports for testing (allows parallel testing even with envs).
Usage:
@pytest.mark.parametrize("n_ports", [2])
def test_something(base_port: int) -> None:
do_something(base_port)
do_something(base_port + 1)
:param _port_allocator: The global port allocator (custom pytest fixture).
:param n_ports: The number of ports needed.
:return: The base port number.
"""
return PortAllocator().reserve_n_ports(n_ports)
@pytest.fixture(scope="session", autouse=True)
def setup_plugin_trainers():
_, _ = mlagents.plugins.trainer_type.register_trainer_plugins()
| PortAllocator |
python | huggingface__transformers | examples/pytorch/object-detection/run_object_detection.py | {
"start": 8970,
"end": 10709
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify
them on the command line.
"""
dataset_name: str = field(
default="cppe-5",
metadata={
"help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
},
)
dataset_config_name: Optional[str] = field(
default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
)
train_val_split: Optional[float] = field(
default=0.15, metadata={"help": "Percent to split off of train for validation."}
)
image_square_size: Optional[int] = field(
default=600,
metadata={"help": "Image longest size will be resized to this value, then image will be padded to square."},
)
max_train_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
},
)
max_eval_samples: Optional[int] = field(
default=None,
metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
},
)
use_fast: Optional[bool] = field(
default=True,
metadata={"help": "Use a fast torchvision-base image processor if it is supported for a given model."},
)
@dataclass
| DataTrainingArguments |
python | getsentry__sentry | src/sentry/tagstore/base.py | {
"start": 856,
"end": 947
} | class ____:
ACTIVE = 0
PENDING_DELETION = 1
DELETION_IN_PROGRESS = 2
| TagKeyStatus |
python | django__django | django/core/files/storage/memory.py | {
"start": 2322,
"end": 5634
} | class ____(TimingMixin):
"""
Helper class representing an in-memory directory node.
Handle path navigation of directory trees, creating missing nodes if
needed.
"""
def __init__(self):
self._children = {}
self._initialize_times()
def resolve(self, path, create_if_missing=False, leaf_cls=None, check_exists=True):
"""
Navigate current directory tree, returning node matching path or
creating a new one, if missing.
- path: path of the node to search
- create_if_missing: create nodes if not exist. Defaults to False.
- leaf_cls: expected type of leaf node. Defaults to None.
- check_exists: if True and the leaf node does not exist, raise a
FileNotFoundError. Defaults to True.
"""
path_segments = list(pathlib.Path(path).parts)
current_node = self
while path_segments:
path_segment = path_segments.pop(0)
# If current node is a file node and there are unprocessed
# segments, raise an error.
if isinstance(current_node, InMemoryFileNode):
path_segments = os.path.split(path)
current_path = "/".join(
path_segments[: path_segments.index(path_segment)]
)
raise NotADirectoryError(
errno.ENOTDIR, os.strerror(errno.ENOTDIR), current_path
)
current_node = current_node._resolve_child(
path_segment,
create_if_missing,
leaf_cls if len(path_segments) == 0 else InMemoryDirNode,
)
if current_node is None:
break
if current_node is None and check_exists:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)
# If a leaf_cls is not None, check if leaf node is of right type.
if leaf_cls and not isinstance(current_node, leaf_cls):
error_cls, error_code = (
(NotADirectoryError, errno.ENOTDIR)
if leaf_cls is InMemoryDirNode
else (IsADirectoryError, errno.EISDIR)
)
raise error_cls(error_code, os.strerror(error_code), path)
return current_node
def _resolve_child(self, path_segment, create_if_missing, child_cls):
if create_if_missing:
self._update_accessed_time()
self._update_modified_time()
if child_cls is InMemoryFileNode:
child = child_cls(name=path_segment)
else:
child = child_cls()
return self._children.setdefault(path_segment, child)
return self._children.get(path_segment)
def listdir(self):
directories, files = [], []
for name, entry in self._children.items():
if isinstance(entry, InMemoryDirNode):
directories.append(name)
else:
files.append(name)
return directories, files
def remove_child(self, name):
if name in self._children:
self._update_accessed_time()
self._update_modified_time()
del self._children[name]
@deconstructible(path="django.core.files.storage.InMemoryStorage")
| InMemoryDirNode |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/base.py | {
"start": 806,
"end": 952
} | class ____(NamedTuple):
id: int | None
fetch_type: FetchType
fetch_type_ext: FetchTypeExt | None = None
@dataclass(frozen=True)
| Metadata |
python | getsentry__sentry | src/sentry/analytics/events/ai_autofix_pr_events.py | {
"start": 55,
"end": 244
} | class ____(analytics.Event):
organization_id: int
project_id: int
group_id: int
run_id: int
integration: str
@analytics.eventclass("ai.autofix.pr.closed")
| AiAutofixPrEvent |
python | doocs__leetcode | lcci/04.03.List of Depth/Solution.py | {
"start": 299,
"end": 818
} | class ____:
def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
ans = []
q = deque([tree])
while q:
dummy = cur = ListNode(0)
for _ in range(len(q)):
node = q.popleft()
cur.next = ListNode(node.val)
cur = cur.next
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(dummy.next)
return ans
| Solution |
python | tensorflow__tensorflow | tensorflow/python/summary/writer/writer_test.py | {
"start": 16452,
"end": 19661
} | class ____(FileWriterTestBase, test.TestCase):
@test_util.run_deprecated_v1
def testWriterException_raisedFromFlush(self):
test_dir = self.get_temp_dir()
sw = self._FileWriter(test_dir)
writer_thread = sw.event_writer._worker
with test.mock.patch.object(
writer_thread, "_ev_writer", autospec=True) as mock_writer:
# Coordinate threads to ensure both events are added before the writer
# thread dies, to avoid the second add_event() failing instead of flush().
second_event_added = threading.Event()
def _FakeWriteEvent(event):
del event # unused
second_event_added.wait()
raise FakeWriteError()
mock_writer.WriteEvent.side_effect = _FakeWriteEvent
sw.add_event(event_pb2.Event())
sw.add_event(event_pb2.Event())
second_event_added.set()
with self.assertRaises(FakeWriteError):
sw.flush()
@test_util.run_deprecated_v1
def testWriterException_raisedFromClose(self):
test_dir = self.get_temp_dir()
sw = self._FileWriter(test_dir)
writer_thread = sw.event_writer._worker
with test.mock.patch.object(
writer_thread, "_ev_writer", autospec=True) as mock_writer:
mock_writer.WriteEvent.side_effect = FakeWriteError()
sw.add_event(event_pb2.Event())
with self.assertRaises(FakeWriteError):
sw.close()
@test_util.run_deprecated_v1
def testWriterException_raisedFromAddEvent(self):
test_dir = self.get_temp_dir()
sw = self._FileWriter(test_dir)
writer_thread = sw.event_writer._worker
with test.mock.patch.object(
writer_thread, "_ev_writer", autospec=True) as mock_writer:
mock_writer.WriteEvent.side_effect = FakeWriteError()
sw.add_event(event_pb2.Event())
# Wait for writer thread to exit first, then try to add a new event.
writer_thread.join()
with self.assertRaises(FakeWriteError):
sw.add_event(event_pb2.Event())
@test_util.run_deprecated_v1
def testWriterException_raisedFromPendingAddEvent(self):
test_dir = self.get_temp_dir()
# Set max_queue=1 to allow the third add_event() call to block (first event
# is consumed immediately, the second fills the queue, the third blocks).
sw = self._FileWriter(test_dir, max_queue=1)
writer_thread = sw.event_writer._worker
with test.mock.patch.object(
writer_thread, "_ev_writer", autospec=True) as mock_writer:
# Coordinate threads to ensure the first two events are added and then
# the writer thread sleeps briefly before exiting, to maximize the chance
# that the third add_event() reaches the pending blocked state before the
# queue closes on writer thread exit, since that's what we want to test.
second_event_added = threading.Event()
def _FakeWriteEvent(event):
del event # unused
second_event_added.wait()
time.sleep(0.1)
raise FakeWriteError()
mock_writer.WriteEvent.side_effect = _FakeWriteEvent
sw.add_event(event_pb2.Event())
sw.add_event(event_pb2.Event())
second_event_added.set()
with self.assertRaises(FakeWriteError):
sw.add_event(event_pb2.Event())
| FileWriterTestCase |
python | getsentry__sentry | src/sentry/api/endpoints/organization_recent_searches.py | {
"start": 737,
"end": 962
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["org:read", "org:write", "org:admin"],
"POST": ["org:read", "org:write", "org:admin"],
}
@region_silo_endpoint
| OrganizationRecentSearchPermission |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 147824,
"end": 149400
} | class ____(BaseModel, extra="forbid"):
"""
Params of single vector data storage
"""
size: int = Field(..., description="Size of a vectors used")
distance: "Distance" = Field(..., description="Params of single vector data storage")
hnsw_config: Optional["HnswConfigDiff"] = Field(
default=None,
description="Custom params for HNSW index. If none - values from collection configuration are used.",
)
quantization_config: Optional["QuantizationConfig"] = Field(
default=None,
description="Custom params for quantization. If none - values from collection configuration are used.",
)
on_disk: Optional[bool] = Field(
default=None,
description="If true, vectors are served from disk, improving RAM usage at the cost of latency Default: false",
)
datatype: Optional["Datatype"] = Field(
default=None,
description="Defines which datatype should be used to represent vectors in the storage. Choosing different datatypes allows to optimize memory usage and performance vs accuracy. - For `float32` datatype - vectors are stored as single-precision floating point numbers, 4 bytes. - For `float16` datatype - vectors are stored as half-precision floating point numbers, 2 bytes. - For `uint8` datatype - vectors are stored as unsigned 8-bit integers, 1 byte. It expects vector elements to be in range `[0, 255]`.",
)
multivector_config: Optional["MultiVectorConfig"] = Field(
default=None, description="Params of single vector data storage"
)
| VectorParams |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/basic.py | {
"start": 26513,
"end": 26639
} | class ____(MetaflowCard):
type = "taskspec_card"
def render(self, task):
return "%s" % task.pathspec
| TaskSpecCard |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1484857,
"end": 1485031
} | class ____(sgqlc.types.Type, GitSignature):
"""Represents an S/MIME signature on a Commit or Tag."""
__schema__ = github_schema
__field_names__ = ()
| SmimeSignature |
python | conda__conda | conda/common/configuration.py | {
"start": 8132,
"end": 9098
} | class ____(RawParameter):
source = CMD_LINE_SOURCE
def value(self, parameter_obj):
# note: this assumes ArgParseRawParameter will only have flat configuration of either
# primitive or sequential type
if isiterable(self._raw_value):
children_values = []
for i in range(len(self._raw_value)):
children_values.append(
ArgParseRawParameter(self.source, self.key, self._raw_value[i])
)
return tuple(children_values)
else:
return deepfreeze(self._raw_value)
def keyflag(self):
return None
def valueflags(self, parameter_obj):
return None if isinstance(parameter_obj, PrimitiveLoadedParameter) else ()
@classmethod
def make_raw_parameters(cls, args_from_argparse):
return super().make_raw_parameters(
ArgParseRawParameter.source, args_from_argparse
)
| ArgParseRawParameter |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 4655,
"end": 4832
} | class ____(str, _Action, Enum):
READ = "read_cluster"
@staticmethod
def values() -> List[str]:
return [action.value for action in ClusterAction]
| ClusterAction |
python | arrow-py__arrow | arrow/factory.py | {
"start": 572,
"end": 11375
} | class ____:
"""A factory for generating :class:`Arrow <arrow.arrow.Arrow>` objects.
:param type: (optional) the :class:`Arrow <arrow.arrow.Arrow>`-based class to construct from.
Defaults to :class:`Arrow <arrow.arrow.Arrow>`.
"""
type: Type[Arrow]
def __init__(self, type: Type[Arrow] = Arrow) -> None:
self.type = type
@overload
def get(
self,
*,
locale: str = DEFAULT_LOCALE,
tzinfo: Optional[TZ_EXPR] = None,
normalize_whitespace: bool = False,
) -> Arrow: ... # pragma: no cover
@overload
def get(
self,
__obj: Union[
Arrow,
datetime,
date,
struct_time,
dt_tzinfo,
int,
float,
str,
Tuple[int, int, int],
],
*,
locale: str = DEFAULT_LOCALE,
tzinfo: Optional[TZ_EXPR] = None,
normalize_whitespace: bool = False,
) -> Arrow: ... # pragma: no cover
@overload
def get(
self,
__arg1: Union[datetime, date],
__arg2: TZ_EXPR,
*,
locale: str = DEFAULT_LOCALE,
tzinfo: Optional[TZ_EXPR] = None,
normalize_whitespace: bool = False,
) -> Arrow: ... # pragma: no cover
@overload
def get(
self,
__arg1: str,
__arg2: Union[str, List[str]],
*,
locale: str = DEFAULT_LOCALE,
tzinfo: Optional[TZ_EXPR] = None,
normalize_whitespace: bool = False,
) -> Arrow: ... # pragma: no cover
def get(self, *args: Any, **kwargs: Any) -> Arrow:
"""Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs.
:param locale: (optional) a ``str`` specifying a locale for the parser. Defaults to 'en-us'.
:param tzinfo: (optional) a :ref:`timezone expression <tz-expr>` or tzinfo object.
Replaces the timezone unless using an input form that is explicitly UTC or specifies
the timezone in a positional argument. Defaults to UTC.
:param normalize_whitespace: (optional) a ``bool`` specifying whether or not to normalize
redundant whitespace (spaces, tabs, and newlines) in a datetime string before parsing.
Defaults to false.
Usage::
>>> import arrow
**No inputs** to get current UTC time::
>>> arrow.get()
<Arrow [2013-05-08T05:51:43.316458+00:00]>
**One** :class:`Arrow <arrow.arrow.Arrow>` object, to get a copy.
>>> arw = arrow.utcnow()
>>> arrow.get(arw)
<Arrow [2013-10-23T15:21:54.354846+00:00]>
**One** ``float`` or ``int``, convertible to a floating-point timestamp, to get
that timestamp in UTC::
>>> arrow.get(1367992474.293378)
<Arrow [2013-05-08T05:54:34.293378+00:00]>
>>> arrow.get(1367992474)
<Arrow [2013-05-08T05:54:34+00:00]>
**One** ISO 8601-formatted ``str``, to parse it::
>>> arrow.get('2013-09-29T01:26:43.830580')
<Arrow [2013-09-29T01:26:43.830580+00:00]>
**One** ISO 8601-formatted ``str``, in basic format, to parse it::
>>> arrow.get('20160413T133656.456289')
<Arrow [2016-04-13T13:36:56.456289+00:00]>
**One** ``tzinfo``, to get the current time **converted** to that timezone::
>>> arrow.get(tz.tzlocal())
<Arrow [2013-05-07T22:57:28.484717-07:00]>
**One** naive ``datetime``, to get that datetime in UTC::
>>> arrow.get(datetime(2013, 5, 5))
<Arrow [2013-05-05T00:00:00+00:00]>
**One** aware ``datetime``, to get that datetime::
>>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal()))
<Arrow [2013-05-05T00:00:00-07:00]>
**One** naive ``date``, to get that date in UTC::
>>> arrow.get(date(2013, 5, 5))
<Arrow [2013-05-05T00:00:00+00:00]>
**One** time.struct time::
>>> arrow.get(gmtime(0))
<Arrow [1970-01-01T00:00:00+00:00]>
**One** iso calendar ``tuple``, to get that week date in UTC::
>>> arrow.get((2013, 18, 7))
<Arrow [2013-05-05T00:00:00+00:00]>
**Two** arguments, a naive or aware ``datetime``, and a replacement
:ref:`timezone expression <tz-expr>`::
>>> arrow.get(datetime(2013, 5, 5), 'US/Pacific')
<Arrow [2013-05-05T00:00:00-07:00]>
**Two** arguments, a naive ``date``, and a replacement
:ref:`timezone expression <tz-expr>`::
>>> arrow.get(date(2013, 5, 5), 'US/Pacific')
<Arrow [2013-05-05T00:00:00-07:00]>
**Two** arguments, both ``str``, to parse the first according to the format of the second::
>>> arrow.get('2013-05-05 12:30:45 America/Chicago', 'YYYY-MM-DD HH:mm:ss ZZZ')
<Arrow [2013-05-05T12:30:45-05:00]>
**Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try::
>>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss'])
<Arrow [2013-05-05T12:30:45+00:00]>
**Three or more** arguments, as for the direct constructor of an ``Arrow`` object::
>>> arrow.get(2013, 5, 5, 12, 30, 45)
<Arrow [2013-05-05T12:30:45+00:00]>
"""
arg_count = len(args)
locale = kwargs.pop("locale", DEFAULT_LOCALE)
tz = kwargs.get("tzinfo", None)
normalize_whitespace = kwargs.pop("normalize_whitespace", False)
# if kwargs given, send to constructor unless only tzinfo provided
if len(kwargs) > 1:
arg_count = 3
# tzinfo kwarg is not provided
if len(kwargs) == 1 and tz is None:
arg_count = 3
# () -> now, @ tzinfo or utc
if arg_count == 0:
if isinstance(tz, str):
tz = parser.TzinfoParser.parse(tz)
return self.type.now(tzinfo=tz)
if isinstance(tz, dt_tzinfo):
return self.type.now(tzinfo=tz)
return self.type.utcnow()
if arg_count == 1:
arg = args[0]
if isinstance(arg, Decimal):
arg = float(arg)
# (None) -> raises an exception
if arg is None:
raise TypeError("Cannot parse argument of type None.")
# try (int, float) -> from timestamp @ tzinfo
elif not isinstance(arg, str) and is_timestamp(arg):
if tz is None:
# set to UTC by default
tz = timezone.utc
return self.type.fromtimestamp(arg, tzinfo=tz)
# (Arrow) -> from the object's datetime @ tzinfo
elif isinstance(arg, Arrow):
return self.type.fromdatetime(arg.datetime, tzinfo=tz)
# (datetime) -> from datetime @ tzinfo
elif isinstance(arg, datetime):
return self.type.fromdatetime(arg, tzinfo=tz)
# (date) -> from date @ tzinfo
elif isinstance(arg, date):
return self.type.fromdate(arg, tzinfo=tz)
# (tzinfo) -> now @ tzinfo
elif isinstance(arg, dt_tzinfo):
return self.type.now(tzinfo=arg)
# (str) -> parse @ tzinfo
elif isinstance(arg, str):
dt = parser.DateTimeParser(locale).parse_iso(arg, normalize_whitespace)
return self.type.fromdatetime(dt, tzinfo=tz)
# (struct_time) -> from struct_time
elif isinstance(arg, struct_time):
return self.type.utcfromtimestamp(calendar.timegm(arg))
# (iso calendar) -> convert then from date @ tzinfo
elif isinstance(arg, tuple) and len(arg) == 3:
d = iso_to_gregorian(*arg)
return self.type.fromdate(d, tzinfo=tz)
else:
raise TypeError(f"Cannot parse single argument of type {type(arg)!r}.")
elif arg_count == 2:
arg_1, arg_2 = args[0], args[1]
if isinstance(arg_1, datetime):
# (datetime, tzinfo/str) -> fromdatetime @ tzinfo
if isinstance(arg_2, (dt_tzinfo, str)):
return self.type.fromdatetime(arg_1, tzinfo=arg_2)
else:
raise TypeError(
f"Cannot parse two arguments of types 'datetime', {type(arg_2)!r}."
)
elif isinstance(arg_1, date):
# (date, tzinfo/str) -> fromdate @ tzinfo
if isinstance(arg_2, (dt_tzinfo, str)):
return self.type.fromdate(arg_1, tzinfo=arg_2)
else:
raise TypeError(
f"Cannot parse two arguments of types 'date', {type(arg_2)!r}."
)
# (str, format) -> parse @ tzinfo
elif isinstance(arg_1, str) and isinstance(arg_2, (str, list)):
dt = parser.DateTimeParser(locale).parse(
args[0], args[1], normalize_whitespace
)
return self.type.fromdatetime(dt, tzinfo=tz)
else:
raise TypeError(
f"Cannot parse two arguments of types {type(arg_1)!r} and {type(arg_2)!r}."
)
# 3+ args -> datetime-like via constructor
else:
return self.type(*args, **kwargs)
def utcnow(self) -> Arrow:
"""Returns an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in UTC time.
Usage::
>>> import arrow
>>> arrow.utcnow()
<Arrow [2013-05-08T05:19:07.018993+00:00]>
"""
return self.type.utcnow()
def now(self, tz: Optional[TZ_EXPR] = None) -> Arrow:
"""Returns an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in the given
timezone.
:param tz: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to local time.
Usage::
>>> import arrow
>>> arrow.now()
<Arrow [2013-05-07T22:19:11.363410-07:00]>
>>> arrow.now('US/Pacific')
<Arrow [2013-05-07T22:19:15.251821-07:00]>
>>> arrow.now('+02:00')
<Arrow [2013-05-08T07:19:25.618646+02:00]>
>>> arrow.now('local')
<Arrow [2013-05-07T22:19:39.130059-07:00]>
"""
if tz is None:
tz = datetime.now().astimezone().tzinfo
elif not isinstance(tz, dt_tzinfo):
tz = parser.TzinfoParser.parse(tz)
return self.type.now(tz)
| ArrowFactory |
python | mlflow__mlflow | mlflow/models/evaluation/evaluators/default.py | {
"start": 974,
"end": 8493
} | class ____(BuiltInEvaluator):
"""
The default built-in evaluator for any models that cannot be evaluated
by other built-in evaluators, such as question-answering.
"""
name = "default"
@classmethod
def can_evaluate(cls, *, model_type, evaluator_config, **kwargs):
return model_type in _ModelType.values() or model_type is None
def _evaluate(
self,
model: Optional["mlflow.pyfunc.PyFuncModel"],
extra_metrics: list[EvaluationMetric],
custom_artifacts=None,
**kwargs,
) -> EvaluationResult | None:
compute_latency = False
for extra_metric in extra_metrics:
# If latency metric is specified, we will compute latency for the model
# during prediction, and we will remove the metric from the list of extra
# metrics to be computed after prediction.
if extra_metric.name == _LATENCY_METRIC_NAME:
compute_latency = True
extra_metrics.remove(extra_metric)
self._log_genai_custom_metrics(extra_metrics)
# Generate model predictions and evaluate metrics
y_pred, other_model_outputs, self.predictions = self._generate_model_predictions(
model, input_df=self.X.copy_to_avoid_mutation(), compute_latency=compute_latency
)
y_true = self.dataset.labels_data
metrics = self._builtin_metrics() + extra_metrics
self.evaluate_metrics(
metrics,
prediction=y_pred,
target=self.dataset.labels_data,
other_output_df=other_model_outputs,
)
self.evaluate_and_log_custom_artifacts(custom_artifacts, prediction=y_pred, target=y_true)
# Log metrics and artifacts
self.log_metrics()
self.log_eval_table(y_pred, other_model_outputs)
return EvaluationResult(
metrics=self.aggregate_metrics, artifacts=self.artifacts, run_id=self.run_id
)
def _builtin_metrics(self) -> list[Metric]:
"""
Get a list of builtin metrics for the model type.
"""
if self.model_type is None:
return []
text_metrics = [
token_count(),
toxicity(),
flesch_kincaid_grade_level(),
ari_grade_level(),
]
builtin_metrics = []
# NB: Classifier and Regressor are handled by dedicated built-in evaluators,
if self.model_type == _ModelType.QUESTION_ANSWERING:
builtin_metrics = [*text_metrics, exact_match()]
elif self.model_type == _ModelType.TEXT_SUMMARIZATION:
builtin_metrics = [
*text_metrics,
rouge1(),
rouge2(),
rougeL(),
rougeLsum(),
]
elif self.model_type == _ModelType.TEXT:
builtin_metrics = text_metrics
elif self.model_type == _ModelType.RETRIEVER:
# default k to 3 if not specified
retriever_k = self.evaluator_config.pop("retriever_k", 3)
builtin_metrics = [
precision_at_k(retriever_k),
recall_at_k(retriever_k),
ndcg_at_k(retriever_k),
]
return builtin_metrics
def _generate_model_predictions(
self,
model: Optional["mlflow.pyfunc.PyFuncModel"],
input_df: pd.DataFrame,
compute_latency=False,
):
"""
Helper method for generating model predictions
"""
predict_fn = _extract_predict_fn(model)
def predict_with_latency(X_copy):
y_pred_list = []
pred_latencies = []
if len(X_copy) == 0:
raise ValueError("Empty input data")
is_dataframe = isinstance(X_copy, pd.DataFrame)
for row in X_copy.iterrows() if is_dataframe else enumerate(X_copy):
i, row_data = row
single_input = row_data.to_frame().T if is_dataframe else row_data
start_time = time.time()
y_pred = predict_fn(single_input)
end_time = time.time()
pred_latencies.append(end_time - start_time)
y_pred_list.append(y_pred)
# Update latency metric
self.metrics_values.update({_LATENCY_METRIC_NAME: MetricValue(scores=pred_latencies)})
# Aggregate all predictions into model_predictions
sample_pred = y_pred_list[0]
if isinstance(sample_pred, pd.DataFrame):
return pd.concat(y_pred_list)
elif isinstance(sample_pred, np.ndarray):
return np.concatenate(y_pred_list, axis=0)
elif isinstance(sample_pred, list):
return sum(y_pred_list, [])
elif isinstance(sample_pred, pd.Series):
return pd.concat(y_pred_list, ignore_index=True)
elif isinstance(sample_pred, str):
return y_pred_list
else:
raise MlflowException(
message=f"Unsupported prediction type {type(sample_pred)} for model type "
f"{self.model_type}.",
error_code=INVALID_PARAMETER_VALUE,
)
if model is not None:
_logger.info("Computing model predictions.")
if compute_latency:
model_predictions = predict_with_latency(input_df)
else:
model_predictions = predict_fn(input_df)
else:
if compute_latency:
_logger.warning(
"Setting the latency to 0 for all entries because the model is not provided."
)
self.metrics_values.update(
{_LATENCY_METRIC_NAME: MetricValue(scores=[0.0] * len(input_df))}
)
model_predictions = self.dataset.predictions_data
output_column_name = self.predictions
(
y_pred,
other_output_df,
predictions_column_name,
) = _extract_output_and_other_columns(model_predictions, output_column_name)
return y_pred, other_output_df, predictions_column_name
def _log_genai_custom_metrics(self, extra_metrics: list[EvaluationMetric]):
genai_custom_metrics = [
extra_metric.genai_metric_args
for extra_metric in extra_metrics
# When the field is present, the metric is created from either make_genai_metric
# or make_genai_metric_from_prompt. We will log the metric definition.
if extra_metric.genai_metric_args is not None
]
if len(genai_custom_metrics) == 0:
return
names = []
versions = []
metric_args_list = []
for metric_args in genai_custom_metrics:
names.append(metric_args["name"])
# Custom metrics created from make_genai_metric_from_prompt don't have version
versions.append(metric_args.get("version", ""))
metric_args_list.append(metric_args)
data = {"name": names, "version": versions, "metric_args": metric_args_list}
mlflow.log_table(data, artifact_file=_GENAI_CUSTOM_METRICS_FILE_NAME)
artifact_name = os.path.splitext(_GENAI_CUSTOM_METRICS_FILE_NAME)[0]
self.artifacts[artifact_name] = JsonEvaluationArtifact(
uri=mlflow.get_artifact_uri(_GENAI_CUSTOM_METRICS_FILE_NAME)
)
| DefaultEvaluator |
python | h5py__h5py | h5py/_hl/selections.py | {
"start": 5239,
"end": 7005
} | class ____(Selection):
"""
Represents a point-wise selection. You can supply sequences of
points to the three methods append(), prepend() and set(), or
instantiate it with a single boolean array using from_mask().
"""
def __init__(self, shape, spaceid=None, points=None):
super().__init__(shape, spaceid)
if points is not None:
self._perform_selection(points, h5s.SELECT_SET)
def _perform_selection(self, points, op):
""" Internal method which actually performs the selection """
points = np.atleast_2d(np.asarray(points, order='C', dtype='u8'))
if self._id.get_select_type() != h5s.SEL_POINTS:
op = h5s.SELECT_SET
if len(points) == 0:
self._id.select_none()
else:
self._id.select_elements(points, op)
@classmethod
def from_mask(cls, mask, spaceid=None):
"""Create a point-wise selection from a NumPy boolean array """
if not (isinstance(mask, np.ndarray) and mask.dtype.kind == 'b'):
raise TypeError("PointSelection.from_mask only works with bool arrays")
points = np.transpose(mask.nonzero())
return cls(mask.shape, spaceid, points=points)
def append(self, points):
""" Add the sequence of points to the end of the current selection """
self._perform_selection(points, h5s.SELECT_APPEND)
def prepend(self, points):
""" Add the sequence of points to the beginning of the current selection """
self._perform_selection(points, h5s.SELECT_PREPEND)
def set(self, points):
""" Replace the current selection with the given sequence of points"""
self._perform_selection(points, h5s.SELECT_SET)
| PointSelection |
python | google__jax | jax/experimental/mosaic/gpu/constraints.py | {
"start": 2908,
"end": 10560
} | class ____:
expression: Expression
def __str__(self):
return f"T({self.expression})"
Expression = (
Variable
| Constant
| LeastReplicated
| MostReplicated
| Reduce
| BroadcastInDim
| Reshape
| Transpose
)
def reduce_replicated_expression(
input_expr: LeastReplicated | MostReplicated,
assignments: dict[Variable, Constant],
reducer: Callable[[fa.FragmentedLayout, fa.FragmentedLayout], fa.FragmentedLayout | None]
) -> Expression | Unsatisfiable:
assert input_expr.expressions
new_expressions: list[Expression] = []
# Use a set to eliminate duplicates, but preserve the order.
seen: set[Expression] = set()
for expr in input_expr.expressions:
reduced_expr = reduce_expression(expr, assignments)
if isinstance(reduced_expr, Unsatisfiable):
return Unsatisfiable()
if reduced_expr in seen:
continue
new_expressions.append(reduced_expr)
seen.add(reduced_expr)
if len(new_expressions) == 1:
return new_expressions[0]
consts = []
unknowns = []
for e in new_expressions:
if not isinstance(e, Constant):
unknowns.append(e)
continue
if not isinstance(e, RegisterLayout):
raise ValueError(
f"Reduction of non-register layout constant is not supported: {e}"
)
consts.append(e)
if consts:
const_red, *consts = consts
red = const_red
for cst in consts:
red_value = reducer(red.value, cst.value)
if red_value is None:
# The layouts are not compatible up to replication, this expression
# cannot be simplified.
return Unsatisfiable()
red = RegisterLayout(red_value)
else:
red = None
constructor = type(input_expr)
if red is not None:
if unknowns:
return constructor((red, *unknowns))
return red
return constructor(tuple(unknowns))
def reduce_broadcast_expression(
broadcast: BroadcastInDim, assignments: dict[Variable, Constant]
) -> Expression | Unsatisfiable:
def _check_shape_broadcast(shape: tuple[int, ...]) -> bool:
for axis, s in zip(broadcast.axes, shape, strict=True):
if broadcast.shape[axis] != s:
return False
return True
reduced_expr = reduce_expression(broadcast.expression, assignments)
match reduced_expr:
case Unsatisfiable():
return Unsatisfiable()
case RegisterLayout(value=layout):
match layout:
case fa.WGSplatFragLayout(shape=shape):
if not _check_shape_broadcast(shape):
return Unsatisfiable()
return RegisterLayout(fa.WGSplatFragLayout(shape=broadcast.shape))
case _:
return BroadcastInDim(
expression=reduced_expr,
axes=broadcast.axes,
shape=broadcast.shape,
)
case _:
return BroadcastInDim(
expression=reduced_expr, axes=broadcast.axes, shape=broadcast.shape
)
def reduce_reshape_expression(
reshape: Reshape, assignments: dict[Variable, Constant]
) -> Expression | Unsatisfiable:
reduced_expr = reduce_expression(reshape.expression, assignments)
match reduced_expr:
case Unsatisfiable():
return Unsatisfiable()
case RegisterLayout(value=layout):
match layout:
case fa.WGSplatFragLayout(shape=shape):
assert math.prod(shape) == math.prod(reshape.target_shape)
return RegisterLayout(
fa.WGSplatFragLayout(shape=reshape.target_shape)
)
case fa.WGStridedFragLayout(shape=shape, vec_size=vec_size):
assert math.prod(shape) == math.prod(reshape.target_shape)
return RegisterLayout(
fa.WGStridedFragLayout(
shape=reshape.target_shape, vec_size=vec_size
)
)
case fa.TiledLayout() as tiled_layout:
tile_shape = tiled_layout.base_tile_shape
if len(reshape.target_shape) < len(tile_shape):
return dataclasses.replace(reshape, expression=reduced_expr)
# Even if the new shape is not perfectly tilable, it is possible that
# we may be able to reshape the tiling itself in a way that is
# compatible with the new shape. We do not handle this case at the
# moment.
for ts, s in zip(tile_shape, reshape.source_shape[-len(tile_shape):], strict=True):
if s % ts != 0:
return dataclasses.replace(reshape, expression=reduced_expr)
# If minor tiled dimensions are modified, then reshaping is likely to
# not be a no-op since the strides between tiles will change,
# potentially mapping different elements to lanes and warps. We don't
# attempt to handle this case at the moment.
num_minor_tiled_dims = len(tile_shape) - 1
source_minor_tiled_dims = reshape.source_shape[-num_minor_tiled_dims:]
target_minor_tiled_dims = reshape.target_shape[-num_minor_tiled_dims:]
major_tiled_dim = tile_shape[0]
if (source_minor_tiled_dims != target_minor_tiled_dims or
reshape.target_shape[-len(tile_shape)] % major_tiled_dim != 0):
return dataclasses.replace(reshape, expression=reduced_expr)
# At this point, we now that only non-tiled dimensions and/or the
# majormost tiled dimensions may have changed. We also know that the
# majormost tiled dimension is still tilable in the new shape.
# Therefore, we can return the tiled layout as is.
return RegisterLayout(tiled_layout)
case _:
return dataclasses.replace(reshape, expression=reduced_expr) # pytype: disable=bad-return-type
def reduce_transpose_expression(
transpose: Transpose, assignments: dict[Variable, Constant]
) -> Expression | Unsatisfiable:
reduced_expr = reduce_expression(transpose.expression, assignments)
match reduced_expr:
case Unsatisfiable():
return Unsatisfiable()
case SMEMTiling(value=tile_transform):
if tile_transform is None:
return SMEMTiling(None)
tiling = tile_transform.tiling
if len(tiling) != 2:
raise NotImplementedError(
f"Only 2D tilings are supported, got {len(tiling)}"
)
return SMEMTiling(lc.TileTransform(tiling[::-1]))
case _:
return Transpose(expression=reduced_expr)
def reduce_expression(
expr: Expression, assignments: dict[Variable, Constant]
) -> Expression | Unsatisfiable:
"""Reduces an expression as much as is possible given a set of known variable assignments."""
match expr:
case Constant():
return expr
case Variable():
return assignments.get(expr, expr)
case MostReplicated():
return reduce_replicated_expression(
expr, assignments, layouts_lib.join_layouts
)
case LeastReplicated():
return reduce_replicated_expression(
expr, assignments, layouts_lib.meet_layouts
)
case Reduce(expression=expr, axes=axes):
reduced_expr = reduce_expression(expr, assignments)
match reduced_expr:
case Unsatisfiable():
return Unsatisfiable()
case RegisterLayout(value=layout) if isinstance(layout, fa.TiledLayout):
return RegisterLayout(layout.reduce(axes))
case _:
return Reduce(expression=reduced_expr, axes=axes)
case BroadcastInDim():
return reduce_broadcast_expression(expr, assignments)
case Reshape():
return reduce_reshape_expression(expr, assignments)
case Transpose():
return reduce_transpose_expression(expr, assignments)
case _:
assert_never(expr)
@dataclasses.dataclass(frozen=True)
| Transpose |
python | tiangolo__fastapi | docs_src/extra_models/tutorial003.py | {
"start": 168,
"end": 217
} | class ____(BaseItem):
type: str = "car"
| CarItem |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py | {
"start": 32649,
"end": 35417
} | class ____(OutbrainAmplifyStream, HttpSubStream):
primary_key = None
def __init__(self, authenticator, config, parent: Marketers, **kwargs):
super().__init__(parent=parent, **kwargs)
self.config = config
self._authenticator = authenticator
self._session = requests.sessions.Session()
def request_params(
self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Mapping[str, Any] = None
) -> MutableMapping[str, Any]:
return {}
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return None
def stream_slices(
self, sync_mode: SyncMode.full_refresh, cursor_field: List[str] = None, stream_state: Mapping[str, Any] = None
) -> Iterable[Optional[Mapping[str, Any]]]:
parent_stream_slices = self.parent.stream_slices(
sync_mode=SyncMode.full_refresh, cursor_field=cursor_field, stream_state=stream_state
)
for stream_slice in parent_stream_slices:
parent_records = self.parent.read_records(
sync_mode=SyncMode.full_refresh, cursor_field=cursor_field, stream_slice=stream_slice, stream_state=stream_state
)
for record in parent_records:
yield {"marketer_id": record.get("id")}
def parse_response(
self,
response: requests.Response,
stream_state: Mapping[str, Any],
stream_slice: Mapping[str, Any] = None,
next_page_token: Mapping[str, Any] = None,
) -> Iterable[Mapping]:
if response.json():
for x in response.json().get("results"):
x["marketer_id"] = stream_slice["marketer_id"]
yield x
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
stream_start, stream_end = self._get_time_interval(self.config.get("start_date"), self.config.get("end_date"))
stream_conversion_count = self._get_bool_conversion_count_by_click_date(
self.config.get("conversion_count", DEFAULT_REPORT_CONVERSION_COUNT_BY_CLICK_DATE)
)
return (
f"reports/marketers/{stream_slice['marketer_id']}/platforms?from="
+ str(stream_start.date())
+ "&to="
+ str(stream_end.date())
+ "&limit=500"
+ "&includeVideoStats=true"
+ "&conversionsByClickDate="
+ str(stream_conversion_count)
)
# Retrieve performance statistics for all marketer campaigns by platform.
# A special endpoint for retrieving platforms data by campaign breakdown.
| PerformanceReportMarketersByPlatforms |
python | sympy__sympy | sympy/core/tests/test_expr.py | {
"start": 5255,
"end": 7405
} | class ____:
'''This class represents an object that knows how to implement binary
operations like +, -, etc with Expr but is not a subclass of Basic itself.
The NonExpr subclass below does subclass Basic but not Expr.
For both NonBasic and NonExpr it should be possible for them to override
Expr.__add__ etc because Expr.__add__ should be returning NotImplemented
for non Expr classes. Otherwise Expr.__add__ would create meaningless
objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for
other classes to override these operations when interacting with Expr.
'''
def __add__(self, other):
return SpecialOp('+', self, other)
def __radd__(self, other):
return SpecialOp('+', other, self)
def __sub__(self, other):
return SpecialOp('-', self, other)
def __rsub__(self, other):
return SpecialOp('-', other, self)
def __mul__(self, other):
return SpecialOp('*', self, other)
def __rmul__(self, other):
return SpecialOp('*', other, self)
def __truediv__(self, other):
return SpecialOp('/', self, other)
def __rtruediv__(self, other):
return SpecialOp('/', other, self)
def __floordiv__(self, other):
return SpecialOp('//', self, other)
def __rfloordiv__(self, other):
return SpecialOp('//', other, self)
def __mod__(self, other):
return SpecialOp('%', self, other)
def __rmod__(self, other):
return SpecialOp('%', other, self)
def __divmod__(self, other):
return SpecialOp('divmod', self, other)
def __rdivmod__(self, other):
return SpecialOp('divmod', other, self)
def __pow__(self, other):
return SpecialOp('**', self, other)
def __rpow__(self, other):
return SpecialOp('**', other, self)
def __lt__(self, other):
return SpecialOp('<', self, other)
def __gt__(self, other):
return SpecialOp('>', self, other)
def __le__(self, other):
return SpecialOp('<=', self, other)
def __ge__(self, other):
return SpecialOp('>=', self, other)
| NonBasic |
python | great-expectations__great_expectations | docs/sphinx_api_docs_source/public_api_report.py | {
"start": 8049,
"end": 16599
} | class ____:
"""Parse code for class, method and function definitions."""
def __init__(
self,
file_contents: Set[FileContents],
) -> None:
"""Create a CodeParser.
Args:
file_contents: A set of FileContents objects to parse.
"""
self.file_contents = file_contents
def get_all_class_method_and_function_names(
self,
) -> Set[str]:
"""Get string names of all classes, methods and functions in all FileContents."""
all_usages = set()
for file_contents in self.file_contents:
usages = self._get_all_class_method_and_function_names_from_file_contents(
file_contents=file_contents
)
all_usages |= usages
return all_usages
def _get_all_class_method_and_function_names_from_file_contents(
self, file_contents: FileContents
) -> Set[str]:
"""Get string names of all classes, methods and functions in a single FileContents."""
definitions: Set[Union[ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef]] = (
self._get_all_entity_definitions_from_file_contents(
file_contents=file_contents
)
)
return {definition.name for definition in definitions}
def get_all_class_method_and_function_definitions(
self,
) -> Set[Definition]:
"""Get Definition objects for all class, method and function definitions."""
all_usages: Set[Definition] = set()
for file_contents in self.file_contents:
entity_definitions = self._get_all_entity_definitions_from_file_contents(
file_contents=file_contents
)
all_usages |= self._build_file_usage_definitions(
file_contents=file_contents, entity_definitions=entity_definitions
)
return all_usages
def get_module_level_function_definitions(self) -> Set[Definition]:
"""Get Definition objects only for functions defined at the module level."""
all_usages: Set[Definition] = set()
for file_contents in self.file_contents:
module_level_function_definitions = (
self._get_module_level_function_definitions_from_file_contents(
file_contents=file_contents
)
)
all_usages |= self._build_file_usage_definitions(
file_contents=file_contents,
entity_definitions=module_level_function_definitions,
)
return all_usages
def _build_file_usage_definitions(
self,
file_contents: FileContents,
entity_definitions: Set[
Union[ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef]
],
) -> Set[Definition]:
"""Build Definitions from FileContents."""
file_usages_definitions: List[Definition] = []
for usage in entity_definitions:
candidate_definition = Definition(
name=usage.name,
filepath=file_contents.filepath,
ast_definition=usage,
)
file_usages_definitions.append(candidate_definition)
return set(file_usages_definitions)
def _get_all_entity_definitions_from_file_contents(
self, file_contents: FileContents
) -> Set[Union[ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef]]:
"""Parse FileContents to retrieve entity definitions as ast trees."""
tree = ast.parse(file_contents.contents)
all_defs: List[Union[ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef]] = []
all_defs.extend(self._list_class_definitions(tree=tree))
all_defs.extend(self._list_function_definitions(tree=tree))
return set(all_defs)
def _get_module_level_function_definitions_from_file_contents(
self, file_contents: FileContents
) -> Set[Union[ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef]]:
"""Parse FileContents to retrieve module level function definitions as ast trees."""
tree = ast.parse(file_contents.contents)
defs = self._list_module_level_function_definitions(tree=tree)
return set(defs)
def _list_class_definitions(self, tree: ast.AST) -> List[ast.ClassDef]:
"""List class definitions from an ast tree."""
class_defs = []
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
class_defs.append(node)
return class_defs
def _list_function_definitions(
self, tree: ast.AST
) -> List[Union[ast.FunctionDef, ast.AsyncFunctionDef]]:
"""List function definitions from an ast tree."""
function_definitions = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
function_definitions.append(node)
return function_definitions
def _list_module_level_function_definitions(
self, tree: ast.AST
) -> List[Union[ast.FunctionDef, ast.AsyncFunctionDef]]:
"""List function definitions that appear outside of classes."""
function_definitions = []
for node in ast.iter_child_nodes(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
function_definitions.append(node)
return function_definitions
def parse_docs_contents_for_class_names(file_contents: Set[FileContents]) -> Set[str]:
"""Parse contents of documentation for class names.
Parses based on class names used in yaml examples e.g. Datasource and
SqlAlchemyExecutionEngine in the below example:
name: my_datasource_name
class_name: Something
execution_engine:
class_name: SqlAlchemyExecutionEngine
Args:
file_contents: Contents from .md and .mdx files that may contain yaml examples.
Returns:
Unique class names used in documentation files.
"""
all_usages = set()
pattern = re.compile(r"class_name: (\w+)")
for single_file_contents in file_contents:
matches = re.finditer(pattern, single_file_contents.contents)
yaml_names = {m.group(1) for m in matches}
all_usages |= yaml_names
return all_usages
def get_shortest_dotted_path(
definition: Definition, repo_root_path: pathlib.Path
) -> str:
"""Get the shortest dotted path to a class definition.
e.g. if a class is imported in a parent __init__.py file use that
instead of the file with the class definition.
Args:
definition: Class definition.
repo_root_path: Repository root path to make sure paths are relative.
Returns:
Dotted representation of shortest import path
e.g. great_expectations.core.ExpectationSuite
"""
if definition.filepath.is_absolute():
relative_definition_path = definition.filepath.relative_to(repo_root_path)
else:
relative_definition_path = definition.filepath
# Traverse parent folders from definition.filepath
shortest_path_prefix = str(".".join(relative_definition_path.parts)).replace(
".py", ""
)
shortest_path = f"{shortest_path_prefix}.{definition.name}"
path_parts = list(relative_definition_path.parts)
while path_parts:
# Keep traversing, shortening path if shorter path is found.
path_parts.pop()
# if __init__.py is found, ast parse and check for import of the class
init_path = repo_root_path / pathlib.Path(*path_parts, "__init__.py")
if init_path.is_file():
import_names = []
with open(init_path) as f:
file_contents: str = f.read()
import_names.extend(_get_import_names(file_contents))
# If name is found in imports, shorten path to where __init__.py is found
if definition.name in import_names:
shortest_path_prefix = str(".".join(path_parts))
shortest_path = f"{shortest_path_prefix}.{definition.name}"
return shortest_path
def _get_import_names(code: str) -> List[str]:
"""Get import names from import statements.
Args:
code: Code with imports to parse.
Returns:
Flattened list of names from imports.
"""
tree = ast.parse(code)
import_names = []
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
for alias in node.names:
import_names.append(alias.name)
return import_names
| CodeParser |
python | PyCQA__pylint | tests/functional/p/protected_access_special_methods_on.py | {
"start": 293,
"end": 770
} | class ____:
"""A class"""
def __init__(self):
self._protected = 42
self.public = "A"
self.__private = None # [unused-private-member]
def __eq__(self, other):
self._protected = other._protected # [protected-access]
def _fake_special_(self, other):
a = other.public
self.public = other._protected # [protected-access]
self.__private = other.__private # [protected-access, unused-private-member]
| Protected |
python | python-rapidjson__python-rapidjson | tests/test_refs_count.py | {
"start": 600,
"end": 6279
} | class ____:
def __init__(self, foo):
self.foo = foo
def hook(d):
if 'foo' in d:
return Foo(d['foo'])
return d
def default(obj):
return {'foo': obj.foo}
# Empirical tolerance used to test the refcount growing
THRESHOLD = 7
plain_string = 'plain-string'
bigint = 123456789
pi = 3.1415926
right_now = datetime.datetime.now()
date = right_now.date()
time = right_now.time()
nil = uuid.UUID(int=0)
foo = Foo('foo')
array = [dict(index=j, array=[dict(index=i,
plain_string=plain_string,
bigint=bigint,
pi=pi,
right_now=right_now,
date=date,
time=time,
nil=nil,
foos=[foo, foo, foo, foo, foo])
for i in range(10)])
for j in range(10)]
NO_OPTION = {}
DATETIMES = {'datetime_mode': rj.DM_ISO8601}
UUIDS = {'uuid_mode': rj.UM_CANONICAL}
FOOS_DUMP = {'default': default}
FOOS_LOAD = {'object_hook': hook}
ARRAY_DUMP = {'datetime_mode': rj.DM_ISO8601,
'uuid_mode': rj.UM_CANONICAL,
'default': default}
ARRAY_LOAD = {'datetime_mode': rj.DM_ISO8601,
'uuid_mode': rj.UM_CANONICAL,
'object_hook': hook}
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
@pytest.mark.parametrize('value,dumps_options,loads_options', [
( plain_string, NO_OPTION, NO_OPTION ),
( bigint, NO_OPTION, NO_OPTION ),
( pi, NO_OPTION, NO_OPTION ),
( rj.RawJSON(' "foo" '), NO_OPTION, NO_OPTION),
( right_now, DATETIMES, DATETIMES ),
( date, DATETIMES, DATETIMES ),
( time, DATETIMES, DATETIMES ),
( nil, UUIDS, UUIDS ),
( foo, FOOS_DUMP, FOOS_LOAD ),
( array, ARRAY_DUMP, ARRAY_LOAD ),
])
def test_leaks(value, dumps_options, loads_options):
rc0 = sys.gettotalrefcount()
for _ in range(1000):
asjson = rj.dumps(value, **dumps_options)
aspython = rj.loads(asjson, **loads_options)
del asjson
del aspython
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
rc0 = sys.gettotalrefcount()
for _ in range(1000):
stream = io.BytesIO()
none = rj.dump(value, stream, **dumps_options)
stream.seek(0)
aspython = rj.load(stream, **loads_options)
del none
del aspython
del stream
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
def test_dump_iterator_leaks():
rc0 = sys.gettotalrefcount()
value = iter(range(10000))
asjson = rj.dumps(value)
del asjson
del value
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
def test_decoder_call_leaks():
class MyDecoder(rj.Decoder):
def start_object(self):
return {}
def end_object(self, obj):
return obj
def end_array(self, array):
return array
def string(self, string):
return string
decoder = MyDecoder()
rc0 = sys.gettotalrefcount()
for _ in range(1000):
value = decoder('["foo", {"foo": "bar"}]')
del value
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
@pytest.mark.parametrize('value', ['Foo', rj.RawJSON('Foo')])
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
def test_encoder_call_leaks(value):
class MyEncoder(rj.Encoder):
def __init__(self, value):
self.value = value
def default(self, obj):
return self.value
class Foo:
pass
encoder = MyEncoder(value)
foo = Foo()
rc0 = sys.gettotalrefcount()
for _ in range(1000):
value = encoder(foo)
del value
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
def test_rawjson_constructor():
raw_json = rj.RawJSON('["foo", "bar"]')
rc0 = sys.gettotalrefcount()
for _ in range(1000):
value = '"foobar"'
raw_json.__init__(value)
del value
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
def test_rawjson_new():
rc0 = sys.gettotalrefcount()
for _ in range(1000):
raw_json = rj.RawJSON('["foo", "bar"]')
del raw_json
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
@pytest.mark.skipif(not hasattr(sys, 'gettotalrefcount'), reason='Non-debug Python')
def test_invalid_json_load_leaks():
# See issue #148
value = '{"a":{"b":}}'
rc0 = sys.gettotalrefcount()
for _ in range(1000):
try:
rj.loads(value)
except rj.JSONDecodeError:
pass
del _
rc1 = sys.gettotalrefcount()
assert (rc1 - rc0) < THRESHOLD
def test_endarray_leak():
# See issue #160
value = '{"v": [1, 2]}'
class Decoder1(rj.Decoder):
pass
class Decoder2(rj.Decoder):
def end_array(self, seq):
return list(seq)
j1 = rj.loads(value)
# Uhm, with Py 3.14 the refcount is 2...
assert 2 <= sys.getrefcount(j1['v']) <= 3
j2 = Decoder1()(value)
assert 2 <= sys.getrefcount(j2['v']) <= 3
j3 = Decoder2()(value)
assert 2 <= sys.getrefcount(j3['v']) <= 3
| Foo |
python | kamyu104__LeetCode-Solutions | Python/permutations-iii.py | {
"start": 59,
"end": 636
} | class ____(object):
def permute(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
def backtracking(lookup):
if len(curr) == n:
result.append(curr[:])
return
for i in xrange(1, n+1):
if lookup&(1<<(i-1)) or (curr and curr[-1]%2 == i%2):
continue
curr.append(i)
backtracking(lookup^(1<<(i-1)))
curr.pop()
result, curr = [], []
backtracking(0)
return result
| Solution |
python | walkccc__LeetCode | solutions/882. Reachable Nodes In Subdivided Graph/882.py | {
"start": 0,
"end": 1366
} | class ____:
def reachableNodes(
self,
edges: list[list[int]],
maxMoves: int,
n: int,
) -> int:
graph = [[] for _ in range(n)]
dist = [maxMoves + 1] * n
for u, v, cnt in edges:
graph[u].append((v, cnt))
graph[v].append((u, cnt))
reachableNodes = self._dijkstra(graph, 0, maxMoves, dist)
reachableSubnodes = 0
for u, v, cnt in edges:
# the number of reachable nodes of (u, v) from `u`
a = 0 if dist[u] > maxMoves else min(maxMoves - dist[u], cnt)
# the number of reachable nodes of (u, v) from `v`
b = 0 if dist[v] > maxMoves else min(maxMoves - dist[v], cnt)
reachableSubnodes += min(a + b, cnt)
return reachableNodes + reachableSubnodes
def _dijkstra(
self,
graph: list[list[tuple[int, int]]],
src: int,
maxMoves: int,
dist: list[int],
) -> int:
dist[src] = 0
minHeap = [(dist[src], src)] # (d, u)
while minHeap:
d, u = heapq.heappop(minHeap)
# Already took `maxMoves` to reach `u`, so can't explore anymore.
if dist[u] >= maxMoves:
break
if d > dist[u]:
continue
for v, w in graph[u]:
newDist = d + w + 1
if newDist < dist[v]:
dist[v] = newDist
heapq.heappush(minHeap, (newDist, v))
return sum(d <= maxMoves for d in dist)
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 16228,
"end": 17674
} | class ____(
NamedTuple(
"_PartitionNamesArgs",
[
("repository_origin", RemoteRepositoryOrigin),
# This is here for backcompat. it's expected to always be f"{job_name}_partition_set".
("partition_set_name", str),
# This is introduced in the same release that we're making it possible for an asset job
# to target assets with different PartitionsDefinitions. Prior user code versions can
# (and do) safely ignore this parameter, because, in those versions, the job name on its
# own is enough to specify which PartitionsDefinition to use.
("job_name", Optional[str]),
],
)
):
def __new__(
cls,
repository_origin: RemoteRepositoryOrigin,
partition_set_name: str,
job_name: Optional[str] = None,
):
return super().__new__(
cls,
repository_origin=check.inst_param(
repository_origin, "repository_origin", RemoteRepositoryOrigin
),
job_name=check.opt_str_param(job_name, "job_name"),
partition_set_name=check.str_param(partition_set_name, "partition_set_name"),
)
def get_job_name(self) -> str:
if self.job_name:
return self.job_name
else:
return job_name_for_partition_set_snap_name(self.partition_set_name)
@whitelist_for_serdes
| PartitionNamesArgs |
python | PrefectHQ__prefect | tests/runtime/test_deployment.py | {
"start": 5733,
"end": 6136
} | class ____:
async def test_run_id_is_attribute(self):
assert "flow_run_id" in dir(deployment)
async def test_run_id_is_none_when_not_set(self):
assert deployment.flow_run_id is None
async def test_run_id_uses_env_var_when_set(self, monkeypatch):
monkeypatch.setenv(name="PREFECT__FLOW_RUN_ID", value="foo")
assert deployment.flow_run_id == "foo"
| TestFlowRunId |
python | django__django | tests/gis_tests/gdal_tests/tests.py | {
"start": 101,
"end": 531
} | class ____(unittest.TestCase):
def test_gdal_version(self):
if GDAL_VERSION:
self.assertEqual(gdal_version(), ("%s.%s.%s" % GDAL_VERSION).encode())
else:
self.assertIn(b".", gdal_version())
def test_gdal_full_version(self):
full_version = gdal_full_version()
self.assertIn(gdal_version(), full_version)
self.assertTrue(full_version.startswith(b"GDAL"))
| GDALTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass4.py | {
"start": 1410,
"end": 1712
} | class ____(DC8):
# This should generate an error because it is overriding
# a field with a default value, but it doesn't have a
# default value.
a: int
# This should generate an error because the default
# value for "a" is inherited from the base class.
b: str
@dataclass
| DC9 |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/api/dagster_looker_api_translator.py | {
"start": 3448,
"end": 3561
} | class ____(Enum):
VIEW = "view"
EXPLORE = "explore"
DASHBOARD = "dashboard"
@record
| LookerStructureType |
python | jina-ai__jina | tests/integration/hub_usage/dummyhub_slow/__init__.py | {
"start": 65,
"end": 223
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
time.sleep(15)
foo()
| DummyHubExecutorSlow |
python | doocs__leetcode | solution/2000-2099/2050.Parallel Courses III/Solution.py | {
"start": 0,
"end": 746
} | class ____:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
g = defaultdict(list)
indeg = [0] * n
for a, b in relations:
g[a - 1].append(b - 1)
indeg[b - 1] += 1
q = deque()
f = [0] * n
ans = 0
for i, (v, t) in enumerate(zip(indeg, time)):
if v == 0:
q.append(i)
f[i] = t
ans = max(ans, t)
while q:
i = q.popleft()
for j in g[i]:
f[j] = max(f[j], f[i] + time[j])
ans = max(ans, f[j])
indeg[j] -= 1
if indeg[j] == 0:
q.append(j)
return ans
| Solution |
python | huggingface__transformers | src/transformers/models/moonshine/modeling_moonshine.py | {
"start": 3519,
"end": 10579
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: MoonshineConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[MoonshineConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
dim = int(head_dim * partial_rotary_factor)
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., 0::2]
x2 = x[..., 1::2]
return torch.stack((-x2, x1), dim=-1).flatten(-2)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
# Interleave them instead of usual shape
cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
# Keep half or full tensor for later concatenation
rotary_dim = cos.shape[-1]
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
# Apply rotary embeddings on the first half or full tensor
q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
# Concatenate back to full shape
q_embed = torch.cat([q_embed, q_pass], dim=-1)
k_embed = torch.cat([k_embed, k_pass], dim=-1)
return q_embed, k_embed
| MoonshineRotaryEmbedding |
python | docker__docker-py | docker/errors.py | {
"start": 3394,
"end": 3968
} | class ____(DockerException):
"""
Represents a container that has exited with a non-zero exit code.
"""
def __init__(self, container, exit_status, command, image, stderr):
self.container = container
self.exit_status = exit_status
self.command = command
self.image = image
self.stderr = stderr
err = f": {stderr}" if stderr is not None else ""
super().__init__(
f"Command '{command}' in image '{image}' "
f"returned non-zero exit status {exit_status}{err}"
)
| ContainerError |
python | scipy__scipy | scipy/sparse/_csc.py | {
"start": 8232,
"end": 11162
} | class ____(spmatrix, _csc_base):
"""
Compressed Sparse Column matrix.
This can be instantiated in several ways:
csc_matrix(D)
where D is a 2-D ndarray
csc_matrix(S)
with another sparse array or matrix S (equivalent to S.tocsc())
csc_matrix((M, N), [dtype])
to construct an empty matrix with shape (M, N)
dtype is optional, defaulting to dtype='d'.
csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
where ``data``, ``row_ind`` and ``col_ind`` satisfy the
relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
csc_matrix((data, indices, indptr), [shape=(M, N)])
is the standard CSC representation where the row indices for
column i are stored in ``indices[indptr[i]:indptr[i+1]]``
and their corresponding values are stored in
``data[indptr[i]:indptr[i+1]]``. If the shape parameter is
not supplied, the matrix dimensions are inferred from
the index arrays.
Attributes
----------
dtype : dtype
Data type of the matrix
shape : 2-tuple
Shape of the matrix
ndim : int
Number of dimensions (this is always 2)
nnz
size
data
CSC format data array of the matrix
indices
CSC format index array of the matrix
indptr
CSC format index pointer array of the matrix
has_sorted_indices
has_canonical_format
T
Notes
-----
Sparse matrices can be used in arithmetic operations: they support
addition, subtraction, multiplication, division, and matrix power.
Advantages of the CSC format
- efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
- efficient column slicing
- fast matrix vector products (CSR, BSR may be faster)
Disadvantages of the CSC format
- slow row slicing operations (consider CSR)
- changes to the sparsity structure are expensive (consider LIL or DOK)
Canonical format
- Within each column, indices are sorted by row.
- There are no duplicate entries.
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csc_matrix
>>> csc_matrix((3, 4), dtype=np.int8).toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>> row = np.array([0, 2, 2, 0, 1, 2])
>>> col = np.array([0, 0, 1, 2, 2, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
"""
| csc_matrix |
python | cython__cython | Cython/Compiler/Errors.py | {
"start": 2973,
"end": 3941
} | class ____(CompileError):
# raised when an unexpected exception occurs in a transform
def __init__(self, pos, context, message, cause, stacktrace=None):
if message:
message = '\n' + message
else:
message = '\n'
self.message_only = message
if context:
message = "Compiler crash in %s%s" % (context, message)
if stacktrace:
import traceback
message += (
'\n\nCompiler crash traceback from this point on:\n' +
''.join(traceback.format_tb(stacktrace)))
if cause:
if not stacktrace:
message += '\n'
message += '%s: %s' % (cause.__class__.__name__, cause)
CompileError.__init__(self, pos, message)
# Python Exception subclass pickling is broken,
# see https://bugs.python.org/issue1692335
self.args = (pos, context, message, cause, stacktrace)
| CompilerCrash |
python | encode__django-rest-framework | tests/test_relations_pk.py | {
"start": 2753,
"end": 7924
} | class ____(TestCase):
def setUp(self):
for idx in range(1, 4):
target = ManyToManyTarget(name='target-%d' % idx)
target.save()
source = ManyToManySource(name='source-%d' % idx)
source.save()
for target in ManyToManyTarget.objects.all():
source.targets.add(target)
def test_many_to_many_retrieve(self):
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'source-1', 'targets': [1]},
{'id': 2, 'name': 'source-2', 'targets': [1, 2]},
{'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}
]
with self.assertNumQueries(4):
assert serializer.data == expected
def test_many_to_many_retrieve_prefetch_related(self):
queryset = ManyToManySource.objects.all().prefetch_related('targets')
serializer = ManyToManySourceSerializer(queryset, many=True)
with self.assertNumQueries(2):
serializer.data
def test_reverse_many_to_many_retrieve(self):
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': 'target-2', 'sources': [2, 3]},
{'id': 3, 'name': 'target-3', 'sources': [3]}
]
with self.assertNumQueries(4):
assert serializer.data == expected
def test_many_to_many_update(self):
data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}
instance = ManyToManySource.objects.get(pk=1)
serializer = ManyToManySourceSerializer(instance, data=data)
assert serializer.is_valid()
serializer.save()
assert serializer.data == data
# Ensure source 1 is updated, and everything else is as expected
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]},
{'id': 2, 'name': 'source-2', 'targets': [1, 2]},
{'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}
]
assert serializer.data == expected
def test_reverse_many_to_many_update(self):
data = {'id': 1, 'name': 'target-1', 'sources': [1]}
instance = ManyToManyTarget.objects.get(pk=1)
serializer = ManyToManyTargetSerializer(instance, data=data)
assert serializer.is_valid()
serializer.save()
assert serializer.data == data
# Ensure target 1 is updated, and everything else is as expected
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'target-1', 'sources': [1]},
{'id': 2, 'name': 'target-2', 'sources': [2, 3]},
{'id': 3, 'name': 'target-3', 'sources': [3]}
]
assert serializer.data == expected
def test_many_to_many_create(self):
data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]}
serializer = ManyToManySourceSerializer(data=data)
assert serializer.is_valid()
obj = serializer.save()
assert serializer.data == data
assert obj.name == 'source-4'
# Ensure source 4 is added, and everything else is as expected
queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'source-1', 'targets': [1]},
{'id': 2, 'name': 'source-2', 'targets': [1, 2]},
{'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]},
{'id': 4, 'name': 'source-4', 'targets': [1, 3]},
]
assert serializer.data == expected
def test_many_to_many_unsaved(self):
source = ManyToManySource(name='source-unsaved')
serializer = ManyToManySourceSerializer(source)
expected = {'id': None, 'name': 'source-unsaved', 'targets': []}
# no query if source hasn't been created yet
with self.assertNumQueries(0):
assert serializer.data == expected
def test_reverse_many_to_many_create(self):
data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]}
serializer = ManyToManyTargetSerializer(data=data)
assert serializer.is_valid()
obj = serializer.save()
assert serializer.data == data
assert obj.name == 'target-4'
# Ensure target 4 is added, and everything else is as expected
queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': 'target-2', 'sources': [2, 3]},
{'id': 3, 'name': 'target-3', 'sources': [3]},
{'id': 4, 'name': 'target-4', 'sources': [1, 3]}
]
assert serializer.data == expected
| PKManyToManyTests |
python | huggingface__transformers | src/transformers/processing_utils.py | {
"start": 24084,
"end": 24590
} | class ____(ChatTemplateLoadKwargs, TokenizerChatTemplateKwargs, total=False):
"""
Keyword arguments for processor's `apply_chat_template`.
tokenize (`bool`, *optional*, defaults to `False`):
Whether to tokenize the output or not.
return_dict (`bool`, defaults to `False`):
Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
"""
tokenize: Optional[bool] = False
return_dict: Optional[bool] = False
| ProcessorChatTemplateKwargs |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 22182,
"end": 22486
} | class ____(LapackNotFoundError):
"""
Lapack (http://www.netlib.org/lapack/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [lapack_src]) or by setting
the LAPACK_SRC environment variable."""
| LapackSrcNotFoundError |
python | ansible__ansible | test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py | {
"start": 4246,
"end": 4366
} | class ____:
def __init__(self, thing: AliasedAnsibleModule) -> None:
self.module = thing
| MyOtherAliasedWrapper |
python | keras-team__keras | keras/src/optimizers/adagrad.py | {
"start": 196,
"end": 3722
} | class ____(optimizer.Optimizer):
"""Optimizer that implements the Adagrad algorithm.
Adagrad is an optimizer with parameter-specific learning rates,
which are adapted relative to how frequently a parameter gets
updated during training. The more updates a parameter receives,
the smaller the updates.
Args:
learning_rate: A float, a
`keras.optimizers.schedules.LearningRateSchedule` instance, or
a callable that takes no arguments and returns the actual value to
use. The learning rate. Defaults to `0.001`. Note that `Adagrad`
tends to benefit from higher initial learning rate values compared
to other optimizers. To match the exact form in the original paper,
use `1.0`.
initial_accumulator_value: Floating point value. Starting value for the
accumulators (per-parameter momentum values). Must be non-negative.
epsilon: Small floating point value for maintaining numerical stability.
{{base_optimizer_keyword_args}}
Reference:
- [Duchi et al., 2011](
http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf).
"""
def __init__(
self,
learning_rate=0.001,
initial_accumulator_value=0.1,
epsilon=1e-7,
weight_decay=None,
clipnorm=None,
clipvalue=None,
global_clipnorm=None,
use_ema=False,
ema_momentum=0.99,
ema_overwrite_frequency=None,
loss_scale_factor=None,
gradient_accumulation_steps=None,
name="adagrad",
**kwargs,
):
super().__init__(
learning_rate=learning_rate,
weight_decay=weight_decay,
clipnorm=clipnorm,
clipvalue=clipvalue,
global_clipnorm=global_clipnorm,
use_ema=use_ema,
ema_momentum=ema_momentum,
ema_overwrite_frequency=ema_overwrite_frequency,
loss_scale_factor=loss_scale_factor,
gradient_accumulation_steps=gradient_accumulation_steps,
name=name,
**kwargs,
)
self.initial_accumulator_value = initial_accumulator_value
self.epsilon = epsilon
def build(self, var_list):
if self.built:
return
super().build(var_list)
initializer = initializers.Constant(self.initial_accumulator_value)
self._accumulators = self.add_optimizer_variables(
var_list, "accumulator", initializer=initializer
)
def update_step(self, gradient, variable, learning_rate):
"""Update step given gradient and the associated model variable."""
lr = ops.cast(learning_rate, variable.dtype)
gradient = ops.cast(gradient, variable.dtype)
accumulator = self._accumulators[self._get_variable_index(variable)]
self.assign_add(accumulator, ops.square(gradient))
self.assign_sub(
variable,
ops.divide(
ops.multiply(lr, gradient),
ops.sqrt(ops.add(accumulator, self.epsilon)),
),
)
def get_config(self):
config = super().get_config()
config.update(
{
"initial_accumulator_value": self.initial_accumulator_value,
"epsilon": self.epsilon,
}
)
return config
Adagrad.__doc__ = Adagrad.__doc__.replace(
"{{base_optimizer_keyword_args}}", optimizer.base_optimizer_keyword_args
)
| Adagrad |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_build_signature.py | {
"start": 664,
"end": 1307
} | class ____:
# Emulates the implementation of Pydantic models. See e.g.
# https://github.com/timothycrosley/hypothesis-auto/issues/10
__annotations__ = get_type_hints(use_this_signature)
__signature__ = signature(use_this_signature)
def __init__(self, **kwargs):
# Check that we're being called with the expected arguments
assert set(kwargs) == {"a", "x", "y"}
assert isinstance(kwargs["a"], int)
assert isinstance(kwargs["x"], float)
assert isinstance(kwargs["y"], str)
@given(st.builds(Model))
def test_builds_uses_signature_attribute(val):
assert isinstance(val, Model)
| Model |
python | getsentry__sentry | src/sentry_plugins/pivotal/plugin.py | {
"start": 1227,
"end": 7951
} | class ____(CorePluginMixin, IssuePlugin2):
description = DESCRIPTION
slug = "pivotal"
title = "Pivotal Tracker"
conf_title = title
conf_key = "pivotal"
required_field = "token"
feature_descriptions = [
FeatureDescription(
"""
Create and link Sentry issue groups directly to a Pivotal Tracker ticket in any of your
projects, providing a quick way to jump from a Sentry bug to tracked ticket.
""",
IntegrationFeatures.ISSUE_BASIC,
),
FeatureDescription(
"""
Link Sentry issues to existing Pivotal Tracker tickets.
""",
IntegrationFeatures.ISSUE_BASIC,
),
]
def get_group_urls(self):
return super().get_group_urls() + [
re_path(
r"^autocomplete",
IssueGroupActionEndpoint.as_view(view_method_name="view_autocomplete", plugin=self),
name=f"sentry-api-0-plugins-{self.slug}-autocomplete",
)
]
def is_configured(self, project) -> bool:
return all(self.get_option(k, project) for k in ("token", "project"))
def get_link_existing_issue_fields(self, request: Request, group, event, **kwargs):
return [
{
"name": "issue_id",
"label": "Story",
"default": "",
"type": "select",
"has_autocomplete": True,
"help": "Search Pivotal Stories by name or description.",
},
{
"name": "comment",
"label": "Comment",
"default": group.get_absolute_url(params={"referrer": "pivotal_plugin"}),
"type": "textarea",
"help": ("Leave blank if you don't want to " "add a comment to the Pivotal story."),
"required": False,
},
]
def handle_api_error(self, error: Exception) -> Response:
msg = "Error communicating with Pivotal Tracker"
status = 400 if isinstance(error, PluginError) else 502
return Response({"error_type": "validation", "errors": {"__all__": msg}}, status=status)
def view_autocomplete(self, request: Request, group, **kwargs):
field = request.GET.get("autocomplete_field")
query = request.GET.get("autocomplete_query")
if field != "issue_id" or not query:
return Response({"issue_id": []})
_url = "{}?{}".format(
self.build_api_url(group, "search"), urlencode({"query": query.encode()})
)
try:
req = self.make_api_request(group.project, _url)
body = safe_urlread(req)
except (requests.RequestException, PluginError) as e:
return self.handle_api_error(e)
try:
json_resp = json.loads(body)
except ValueError as e:
return self.handle_api_error(e)
resp = json_resp.get("stories", {})
stories = resp.get("stories", [])
issues = [{"text": "(#{}) {}".format(i["id"], i["name"]), "id": i["id"]} for i in stories]
return Response({field: issues})
def link_issue(self, request: Request, group, form_data, **kwargs):
comment = form_data.get("comment")
if not comment:
return
_url = "{}/{}/comments".format(self.build_api_url(group, "stories"), form_data["issue_id"])
try:
req = self.make_api_request(group.project, _url, json_data={"text": comment})
body = safe_urlread(req)
except requests.RequestException as e:
msg = str(e)
raise PluginError(f"Error communicating with Pivotal: {msg}")
try:
json_resp = json.loads(body)
except ValueError as e:
msg = str(e)
raise PluginError(f"Error communicating with Pivotal: {msg}")
if req.status_code > 399:
raise PluginError(json_resp["error"])
def build_api_url(self, group, pivotal_api=None):
project = self.get_option("project", group.project)
_url = f"https://www.pivotaltracker.com/services/v5/projects/{project}/{pivotal_api}"
return _url
def make_api_request(self, project, _url, json_data=None):
req_headers = {
"X-TrackerToken": str(self.get_option("token", project)),
"Content-Type": "application/json",
}
return safe_urlopen(_url, json=json_data, headers=req_headers, allow_redirects=True)
def create_issue(self, request: Request, group, form_data):
json_data = {
"story_type": "bug",
"name": force_str(form_data["title"], encoding="utf-8", errors="replace"),
"description": force_str(form_data["description"], encoding="utf-8", errors="replace"),
"labels": ["sentry"],
}
try:
_url = self.build_api_url(group, "stories")
req = self.make_api_request(group.project, _url, json_data=json_data)
body = safe_urlread(req)
except requests.RequestException as e:
msg = str(e)
raise PluginError(f"Error communicating with Pivotal: {msg}")
try:
json_resp = json.loads(body)
except ValueError as e:
msg = str(e)
raise PluginError(f"Error communicating with Pivotal: {msg}")
if req.status_code > 399:
raise PluginError(json_resp["error"])
return json_resp["id"]
def get_issue_label(self, group, issue_id: str) -> str:
return "#%s" % issue_id
def get_issue_url(self, group, issue_id: str) -> str:
return "https://www.pivotaltracker.com/story/show/%s" % issue_id
def get_configure_plugin_fields(self, project, **kwargs):
token = self.get_option("token", project)
helptext = (
"Enter your API Token (found on "
'<a href="https://www.pivotaltracker.com/profile"'
">pivotaltracker.com/profile</a>)."
)
secret_field = get_secret_field_config(token, helptext, include_prefix=True)
secret_field.update(
{
"name": "token",
"label": "API Token",
"placeholder": "e.g. a9877d72b6d13b23410a7109b35e88bc",
}
)
return [
secret_field,
{
"name": "project",
"label": "Project ID",
"default": self.get_option("project", project),
"type": "text",
"placeholder": "e.g. 639281",
"help": "Enter your project's numerical ID.",
},
]
| PivotalPlugin |
python | weaviate__weaviate-python-client | weaviate/cluster/sync.py | {
"start": 211,
"end": 401
} | class ____(_ClusterExecutor[ConnectionSync]):
def __init__(self, connection: ConnectionSync):
super().__init__(connection)
self.replications = _Replicate(connection)
| _Cluster |
python | sqlalchemy__sqlalchemy | test/orm/test_core_compilation.py | {
"start": 68512,
"end": 76019
} | class ____(
_poly_fixtures._PolymorphicUnions, AssertsCompiledSQL
):
"""Test a series of mappers with a very awkward with_polymorphic setting,
that tables and columns are rendered using the selectable in the correct
contexts. PolymorphicUnions represent the most awkward and verbose
polymorphic fixtures you can have. expressions need to be maximally
accurate in terms of the mapped selectable in order to produce correct
queries, which also will be really wrong if that mapped selectable is not
in use.
"""
__dialect__ = "default"
def test_select_columns_where_baseclass(self):
Person = self.classes.Person
stmt = (
select(Person.person_id, Person.name)
.where(Person.name == "some name")
.order_by(Person.person_id)
)
sess = fixture_session()
q = (
sess.query(Person.person_id, Person.name)
.filter(Person.name == "some name")
.order_by(Person.person_id)
)
expected = (
"SELECT pjoin.person_id, pjoin.name FROM "
"(SELECT engineers.person_id AS person_id, people.company_id AS "
"company_id, people.name AS name, people.type AS type, "
"engineers.status AS status, engineers.engineer_name AS "
"engineer_name, engineers.primary_language AS primary_language, "
"CAST(NULL AS VARCHAR(50)) AS manager_name FROM people "
"JOIN engineers ON people.person_id = engineers.person_id "
"UNION ALL SELECT managers.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, managers.status AS status, "
"CAST(NULL AS VARCHAR(50)) AS engineer_name, "
"CAST(NULL AS VARCHAR(50)) AS primary_language, "
"managers.manager_name AS manager_name FROM people "
"JOIN managers ON people.person_id = managers.person_id) AS "
"pjoin WHERE pjoin.name = :name_1 ORDER BY pjoin.person_id"
)
self.assert_compile(stmt, expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
expected,
)
def test_select_where_baseclass(self):
Person = self.classes.Person
stmt = (
select(Person)
.where(Person.name == "some name")
.order_by(Person.person_id)
)
sess = fixture_session()
q = (
sess.query(Person)
.filter(Person.name == "some name")
.order_by(Person.person_id)
)
expected = (
"SELECT pjoin.person_id, pjoin.company_id, pjoin.name, "
"pjoin.type, pjoin.status, pjoin.engineer_name, "
"pjoin.primary_language, pjoin.manager_name FROM "
"(SELECT engineers.person_id AS person_id, people.company_id "
"AS company_id, people.name AS name, people.type AS type, "
"engineers.status AS status, engineers.engineer_name AS "
"engineer_name, engineers.primary_language AS primary_language, "
"CAST(NULL AS VARCHAR(50)) AS manager_name FROM people "
"JOIN engineers ON people.person_id = engineers.person_id "
"UNION ALL SELECT managers.person_id AS person_id, "
"people.company_id AS company_id, people.name AS name, "
"people.type AS type, managers.status AS status, "
"CAST(NULL AS VARCHAR(50)) AS engineer_name, "
"CAST(NULL AS VARCHAR(50)) AS primary_language, "
"managers.manager_name AS manager_name FROM people "
"JOIN managers ON people.person_id = managers.person_id) AS "
"pjoin WHERE pjoin.name = :name_1 ORDER BY pjoin.person_id"
)
self.assert_compile(stmt, expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
expected,
)
def test_select_where_subclass(self):
Engineer = self.classes.Engineer
# what will *not* work with Core, that the ORM does for now,
# is that if you do where/orderby Person.column, it will de-adapt
# the Person columns from the polymorphic union
stmt = (
select(Engineer)
.where(Engineer.name == "some name")
.order_by(Engineer.person_id)
)
sess = fixture_session()
q = (
sess.query(Engineer)
.filter(Engineer.name == "some name")
.order_by(Engineer.person_id)
)
plain_expected = ( # noqa
"SELECT engineers.person_id, people.person_id, people.company_id, "
"people.name, "
"people.type, engineers.status, "
"engineers.engineer_name, engineers.primary_language "
"FROM people JOIN engineers "
"ON people.person_id = engineers.person_id "
"WHERE people.name = :name_1 ORDER BY engineers.person_id"
)
# when we have disambiguating labels turned on
disambiguate_expected = ( # noqa
"SELECT engineers.person_id, people.person_id AS person_id_1, "
"people.company_id, "
"people.name, "
"people.type, engineers.status, "
"engineers.engineer_name, engineers.primary_language "
"FROM people JOIN engineers "
"ON people.person_id = engineers.person_id "
"WHERE people.name = :name_1 ORDER BY engineers.person_id"
)
# these change based on how we decide to apply labels
# in context.py
self.assert_compile(stmt, disambiguate_expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
disambiguate_expected,
)
def test_select_where_columns_subclass(self):
Engineer = self.classes.Engineer
# what will *not* work with Core, that the ORM does for now,
# is that if you do where/orderby Person.column, it will de-adapt
# the Person columns from the polymorphic union
# After many attempts to get the JOIN to render, by annotating
# the columns with the "join" that they come from and trying to
# get Select() to render out that join, there's no approach
# that really works without stepping on other assumptions, so
# add select_from(Engineer) explicitly. It's still puzzling why the
# ORM seems to know how to make this decision more effectively
# when the select() has the same amount of information.
stmt = (
select(Engineer.person_id, Engineer.name)
.where(Engineer.name == "some name")
.select_from(Engineer)
.order_by(Engineer.person_id)
)
sess = fixture_session()
q = (
sess.query(Engineer.person_id, Engineer.name)
.filter(Engineer.name == "some name")
.order_by(Engineer.person_id)
)
expected = (
"SELECT engineers.person_id, people.name "
"FROM people JOIN engineers "
"ON people.person_id = engineers.person_id "
"WHERE people.name = :name_1 ORDER BY engineers.person_id"
)
self.assert_compile(stmt, expected)
self.assert_compile(
q._final_statement(legacy_query_style=False),
expected,
)
| ImplicitWithPolymorphicTest |
python | pyinstaller__pyinstaller | PyInstaller/lib/modulegraph/modulegraph.py | {
"start": 23473,
"end": 23780
} | class ____(Node):
def __init__(self, name, filename=None, path=None):
super(BaseModule, self).__init__(name)
self.filename = filename
self.packagepath = path
def infoTuple(self):
return tuple(filter(None, (self.identifier, self.filename, self.packagepath)))
| BaseModule |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 525076,
"end": 528199
} | class ____(Response):
"""
Response of tasks.unarchive_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "unarchive_many"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"failed": {
"items": {
"properties": {
"error": {
"description": "Error info",
"properties": {
"codes": {
"items": {"type": "integer"},
"type": "array",
},
"data": {
"additionalProperties": True,
"type": "object",
},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {
"description": "ID of the failed entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"succeeded": {
"items": {
"properties": {
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
"unarchived": {
"description": "Indicates whether the task was unarchived",
"type": "boolean",
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, succeeded=None, failed=None, **kwargs):
super(UnarchiveManyResponse, self).__init__(**kwargs)
self.succeeded = succeeded
self.failed = failed
@schema_property("succeeded")
def succeeded(self):
return self._property_succeeded
@succeeded.setter
def succeeded(self, value):
if value is None:
self._property_succeeded = None
return
self.assert_isinstance(value, "succeeded", (list, tuple))
self.assert_isinstance(value, "succeeded", (dict,), is_array=True)
self._property_succeeded = value
@schema_property("failed")
def failed(self):
return self._property_failed
@failed.setter
def failed(self, value):
if value is None:
self._property_failed = None
return
self.assert_isinstance(value, "failed", (list, tuple))
self.assert_isinstance(value, "failed", (dict,), is_array=True)
self._property_failed = value
| UnarchiveManyResponse |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 17669,
"end": 19555
} | class ____(HTTPException):
"""416 Range Not Satisfiable
Args:
message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None`
then the HTTP status 'Range Not Satisfiable' will be sent. Defaults to `None`.
content_range (Optional[ContentRange], optional): An object meeting the :class:`.ContentRange` protocol
that has a `total` property. Defaults to `None`.
quiet (Optional[bool], optional): When `True`, the error traceback will be suppressed
from the logs. Defaults to `None`.
context (Optional[Dict[str, Any]], optional): Additional mapping of key/value data that will be
sent to the client upon exception. Defaults to `None`.
extra (Optional[Dict[str, Any]], optional): Additional mapping of key/value data that will NOT be
sent to the client when in PRODUCTION mode. Defaults to `None`.
headers (Optional[Dict[str, Any]], optional): Additional headers that should be sent with the HTTP
response. Defaults to `None`.
""" # noqa: E501
status_code = 416
quiet = True
def __init__(
self,
message: Optional[Union[str, bytes]] = None,
content_range: Optional[Range] = None,
*,
quiet: Optional[bool] = None,
context: Optional[dict[str, Any]] = None,
extra: Optional[dict[str, Any]] = None,
headers: Optional[dict[str, Any]] = None,
):
super().__init__(
message,
quiet=quiet,
context=context,
extra=extra,
headers=headers,
)
if content_range is not None:
self.headers = {
**self.headers,
"Content-Range": f"bytes */{content_range.total}",
}
ContentRangeError = RangeNotSatisfiable
| RangeNotSatisfiable |
python | getsentry__sentry | src/sentry/exceptions.py | {
"start": 566,
"end": 620
} | class ____(PluginError):
pass
| PluginIdentityRequired |
python | keras-team__keras | keras/src/legacy/saving/legacy_h5_format_test.py | {
"start": 20239,
"end": 20911
} | class ____(testing.TestCase):
def test_directory_creation_on_save(self):
"""Test if directory is created on model save."""
model = get_sequential_model(keras)
nested_dirpath = os.path.join(
self.get_temp_dir(), "dir1", "dir2", "dir3"
)
filepath = os.path.join(nested_dirpath, "model.h5")
self.assertFalse(os.path.exists(nested_dirpath))
legacy_h5_format.save_model_to_hdf5(model, filepath)
self.assertTrue(os.path.exists(nested_dirpath))
loaded_model = legacy_h5_format.load_model_from_hdf5(filepath)
self.assertEqual(model.to_json(), loaded_model.to_json())
| DirectoryCreationTest |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0055_alter_versionautomationrule_priority.py | {
"start": 148,
"end": 645
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0054_add_builds_index_for_addons"),
]
operations = [
migrations.AlterField(
model_name="versionautomationrule",
name="priority",
field=models.IntegerField(
default=0,
help_text="A lower number (0) means a higher priority",
verbose_name="Rule priority",
),
),
]
| Migration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass10.py | {
"start": 273,
"end": 361
} | class ____(ABase[int]):
pass
reveal_type(AChild(123), expected_text="AChild")
| AChild |
python | huggingface__transformers | tests/trainer/test_trainer_callback.py | {
"start": 1256,
"end": 1552
} | class ____(TrainerCallback, ExportableState):
def __init__(self, my_test_state="test"):
self.my_test_state = my_test_state
def state(self):
return {
"args": {
"my_test_state": self.my_test_state,
},
}
| MyTestExportableCallback |
python | walkccc__LeetCode | solutions/2659. Make Array Empty/2659.py | {
"start": 0,
"end": 619
} | class ____:
def countOperationsToEmptyArray(self, nums: list[int]) -> int:
n = len(nums)
ans = n
numToIndex = {}
for i, num in enumerate(nums):
numToIndex[num] = i
nums.sort()
for i in range(1, n):
# On the i-th step we've already removed the i - 1 smallest numbers and
# can ignore them. If an element nums[i] has smaller index in origin
# array than nums[i - 1], we should rotate the whole left array n - i
# times to set nums[i] element on the first position.
if numToIndex[nums[i]] < numToIndex[nums[i - 1]]:
ans += n - i
return ans
| Solution |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 13802,
"end": 13948
} | class ____(InventoryConfig, WindowsConfig):
"""Configuration for Windows hosts using inventory."""
@dataclasses.dataclass
| WindowsInventoryConfig |
python | huggingface__transformers | src/transformers/models/llava_onevision/modeling_llava_onevision.py | {
"start": 3396,
"end": 5234
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
video_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
image_hidden_states: Optional[torch.FloatTensor] = None
video_hidden_states: Optional[torch.FloatTensor] = None
@auto_docstring
| LlavaOnevisionCausalLMOutputWithPast |
python | python-jsonschema__jsonschema | jsonschema/tests/test_validators.py | {
"start": 67684,
"end": 68184
} | class ____(TestCase):
"""
These really apply to multiple versions but are easiest to test on one.
"""
def test_ref_resolvers_may_have_boolean_schemas_stored(self):
ref = "someCoolRef"
schema = {"$ref": ref}
resolver = validators._RefResolver("", {}, store={ref: False})
validator = validators._LATEST_VERSION(schema, resolver=resolver)
with self.assertRaises(exceptions.ValidationError):
validator.validate(None)
| TestLatestValidator |
python | kamyu104__LeetCode-Solutions | Python/grumpy-bookstore-owner.py | {
"start": 29,
"end": 593
} | class ____(object):
def maxSatisfied(self, customers, grumpy, X):
"""
:type customers: List[int]
:type grumpy: List[int]
:type X: int
:rtype: int
"""
result, max_extra, extra = 0, 0, 0
for i in xrange(len(customers)):
result += 0 if grumpy[i] else customers[i]
extra += customers[i] if grumpy[i] else 0
if i >= X:
extra -= customers[i-X] if grumpy[i-X] else 0
max_extra = max(max_extra, extra)
return result + max_extra
| Solution |
python | spyder-ide__spyder | spyder/api/widgets/mixins.py | {
"start": 23367,
"end": 24880
} | class ____(
SpyderActionMixin,
SpyderMenuMixin,
SpyderToolbarMixin,
SpyderToolButtonMixin,
SpyderShortcutsMixin,
):
"""
Basic functionality for all Spyder widgets and Qt items.
This provides a simple management of widget options, as well as Qt helpers
for defining the actions a widget provides.
"""
# Plugin name identifier used to store actions, toolbars, toolbuttons
# and menus
PLUGIN_NAME = None
# Context name used to store actions, toolbars, toolbuttons and menus
CONTEXT_NAME = None
def __init__(self, class_parent=None, parent=None):
for attr in ['CONF_SECTION', 'PLUGIN_NAME']:
if getattr(self, attr, None) is None:
if hasattr(class_parent, attr):
# Inherit class_parent CONF_SECTION/PLUGIN_NAME value
setattr(self, attr, getattr(class_parent, attr))
super().__init__()
@staticmethod
def create_icon(name):
"""
Create an icon by name using the spyder Icon manager.
"""
return ima.icon(name)
def update_style(self):
"""
Update stylesheet and style of the widget.
This method will be called recursively on all widgets on theme change.
"""
pass
def update_translation(self):
"""
Update localization of the widget.
This method will be called recursively on all widgets on language
change.
"""
pass
| SpyderWidgetMixin |
python | getsentry__sentry | tests/sentry/api/test_handlers.py | {
"start": 706,
"end": 1079
} | class ____(APITestCase):
endpoint = "sentry-test"
def test_simple(self) -> None:
self.login_as(self.user)
resp = self.get_response()
assert resp.status_code == 429
assert (
resp.data["detail"]
== "Rate limit exceeded. Please try your query with a smaller date range or fewer projects."
)
| TestRateLimited |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 7931,
"end": 8000
} | class ____(Middle):
author = models.CharField(max_length=50)
| Bottom |
python | django__django | tests/admin_filters/tests.py | {
"start": 9150,
"end": 9286
} | class ____(EmployeeAdmin):
list_filter = [DepartmentListFilterLookupWithUnderscoredParameter]
| DepartmentFilterUnderscoredEmployeeAdmin |
python | readthedocs__readthedocs.org | readthedocs/oauth/migrations/0014_remove_remoterepository_project.py | {
"start": 120,
"end": 500
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("oauth", "0013_create_new_table_for_remote_repository_normalization"),
("projects", "0077_remote_repository_data_migration"),
]
operations = [
migrations.RemoveField(
model_name="remoterepository",
name="project",
),
]
| Migration |
python | django__django | tests/fixtures_regress/models.py | {
"start": 1222,
"end": 1456
} | class ____(models.Model):
title = models.CharField(max_length=255)
channels = models.ManyToManyField(Channel)
class Meta:
ordering = ("id",)
# Subclass of a model with a ManyToManyField for test_ticket_20820
| Article |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/tests/check_env_trains.py | {
"start": 532,
"end": 3722
} | class ____(StatsWriter):
"""
Print to stdout so stats can be viewed in pytest
"""
def __init__(self):
self._last_reward_summary: Dict[str, float] = {}
def get_last_rewards(self):
return self._last_reward_summary
def write_stats(
self, category: str, values: Dict[str, StatsSummary], step: int
) -> None:
for val, stats_summary in values.items():
if (
val == "Environment/Cumulative Reward"
or val == "Environment/Group Cumulative Reward"
):
print(step, val, stats_summary.aggregated_value)
self._last_reward_summary[category] = stats_summary.aggregated_value
# The reward processor is passed as an argument to _check_environment_trains.
# It is applied to the list of all final rewards for each brain individually.
# This is so that we can process all final rewards in different ways for different algorithms.
# Custom reward processors should be built within the test function and passed to _check_environment_trains
# Default is average over the last 5 final rewards
def default_reward_processor(rewards, last_n_rewards=5):
rewards_to_use = rewards[-last_n_rewards:]
# For debugging tests
print(f"Last {last_n_rewards} rewards:", rewards_to_use)
return np.array(rewards[-last_n_rewards:], dtype=np.float32).mean()
def check_environment_trains(
env,
trainer_config,
reward_processor=default_reward_processor,
env_parameter_manager=None,
success_threshold=0.9,
env_manager=None,
training_seed=None,
):
if env_parameter_manager is None:
env_parameter_manager = EnvironmentParameterManager()
# Create controller and begin training.
with tempfile.TemporaryDirectory() as dir:
run_id = "id"
seed = 1337 if training_seed is None else training_seed
StatsReporter.writers.clear() # Clear StatsReporters so we don't write to file
debug_writer = DebugWriter()
StatsReporter.add_writer(debug_writer)
if env_manager is None:
env_manager = SimpleEnvManager(env, EnvironmentParametersChannel())
trainer_factory = TrainerFactory(
trainer_config=trainer_config,
output_path=dir,
train_model=True,
load_model=False,
seed=seed,
param_manager=env_parameter_manager,
multi_gpu=False,
)
tc = TrainerController(
trainer_factory=trainer_factory,
output_path=dir,
run_id=run_id,
param_manager=env_parameter_manager,
train=True,
training_seed=seed,
)
# Begin training
tc.start_learning(env_manager)
if (
success_threshold is not None
): # For tests where we are just checking setup and not reward
processed_rewards = [
reward_processor(rewards) for rewards in env.final_rewards.values()
]
assert all(not math.isnan(reward) for reward in processed_rewards)
assert all(reward > success_threshold for reward in processed_rewards)
| DebugWriter |
python | bokeh__bokeh | src/bokeh/core/property/nullable.py | {
"start": 1477,
"end": 3086
} | class ____(SingleParameterizedProperty[T | None]):
""" A property accepting ``None`` or a value of some other type. """
def __init__(self, type_param: TypeOrInst[Property[T]], *, default: Init[T | None] = None, help: str | None = None) -> None:
super().__init__(type_param, default=default, help=help)
def transform(self, value: Any) -> T | None:
return None if value is None else super().transform(value)
def wrap(self, value: Any) -> Any:
return None if value is None else super().wrap(value)
def validate(self, value: Any, detail: bool = True) -> None:
if value is None:
return
try:
super().validate(value, detail=False)
except ValueError:
pass
else:
return
msg = "" if not detail else f"expected either None or a value of type {self.type_param}, got {value!r}"
raise ValueError(msg)
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
@register_type_link(Nullable)
def _sphinx_type_link(obj: SingleParameterizedProperty[Any]) -> str:
return f"{property_link(obj)}({type_link(obj.type_param)})"
| Nullable |
python | keras-team__keras | keras/src/layers/merging/base_merge.py | {
"start": 161,
"end": 10774
} | class ____(Layer):
"""Generic merge layer for elementwise merge functions.
Used to implement `Sum`, `Average`, etc.
Args:
**kwargs: standard layer keyword arguments.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.supports_masking = True
def _merge_function(self, inputs):
raise NotImplementedError
def _apply_merge_op_and_or_mask(self, op_fn, inputs):
"""Merge a set of inputs by applying `op_fn` and ORing the masks.
We use this for `Minimum` and `Maximum` as it handles the fact that
there is no identity element. If applicable, the mask obtained by ORing
all masks is set on the output.
Args:
op_fn: binary operation to apply to tensor pair.
inputs: array of tensors to apply operation on.
"""
output = None
output_mask = None
for x in inputs:
mask = backend.get_keras_mask(x)
if mask is not None:
mask = ops.broadcast_to(ops.expand_dims(mask, -1), ops.shape(x))
if output is None:
output = x
output_mask = mask
continue
if mask is not None:
x = ops.where(mask, x, output)
if output_mask is not None:
output = ops.where(output_mask, output, x)
if mask is not None and output_mask is not None:
output_mask = ops.logical_or(output_mask, mask)
else:
output_mask = None
output = op_fn(output, x)
if output_mask is not None:
output_mask = ops.any(output_mask, axis=-1, keepdims=False)
backend.set_keras_mask(output, output_mask)
return output
def _compute_elemwise_op_output_shape(self, shape1, shape2):
"""Computes the shape of the resultant of an elementwise operation.
Args:
shape1: Tuple or None. Shape of the first tensor
shape2: Tuple or None. Shape of the second tensor
Returns:
Expected output shape when an element-wise operation is
carried out on 2 tensors with shapes shape1 and shape2.
tuple or None.
Raises:
ValueError: If shape1 and shape2 are not compatible for
element-wise operations.
"""
if None in [shape1, shape2]:
return None
elif len(shape1) < len(shape2):
return self._compute_elemwise_op_output_shape(shape2, shape1)
elif not shape2:
return shape1
output_shape = list(shape1[: -len(shape2)])
for i, j in zip(shape1[-len(shape2) :], shape2):
if i is None or j is None:
output_shape.append(None)
elif i == 1:
output_shape.append(j)
elif j == 1:
output_shape.append(i)
else:
if i != j:
raise ValueError(
"Inputs have incompatible shapes. "
f"Received shapes {shape1} and {shape2}"
)
output_shape.append(i)
return tuple(output_shape)
def build(self, input_shape):
# Used purely for shape validation.
if not isinstance(input_shape[0], (tuple, list)):
raise ValueError(
"A merge layer should be called on a list of inputs. "
f"Received: input_shape={input_shape} (not a list of shapes)"
)
if len(input_shape) < 1:
raise ValueError(
"A merge layer should be called "
"on a list of at least 1 input. "
f"Received {len(input_shape)} inputs. "
f"Full input_shape received: {input_shape}"
)
batch_sizes = {s[0] for s in input_shape if s} - {None}
if len(batch_sizes) > 1:
raise ValueError(
"Cannot merge tensors with different batch sizes. "
f"Received tensors with shapes {input_shape}"
)
if input_shape[0] is None:
output_shape = None
else:
output_shape = input_shape[0][1:]
for i in range(1, len(input_shape)):
if input_shape[i] is None:
shape = None
else:
shape = input_shape[i][1:]
output_shape = self._compute_elemwise_op_output_shape(
output_shape, shape
)
# If the inputs have different ranks, we have to reshape them
# to make them broadcastable.
if None not in input_shape and len(set(map(len, input_shape))) == 1:
self._reshape_required = False
else:
self._reshape_required = True
def call(self, inputs):
if not isinstance(inputs, (list, tuple)):
raise ValueError(
"A merge layer should be called on a list of inputs. "
f"Received: inputs={inputs} (not a list of tensors)"
)
if self._reshape_required:
reshaped_inputs = []
input_ndims = list(map(ops.ndim, inputs))
if None not in input_ndims:
# If ranks of all inputs are available,
# we simply expand each of them at axis=1
# until all of them have the same rank.
max_ndim = max(input_ndims)
for x in inputs:
x_ndim = ops.ndim(x)
for _ in range(max_ndim - x_ndim):
x = ops.expand_dims(x, axis=1)
reshaped_inputs.append(x)
return self._merge_function(reshaped_inputs)
else:
# Transpose all inputs so that batch size is the last dimension.
# (batch_size, dim1, dim2, ... ) -> (dim1, dim2, ... ,
# batch_size)
transposed = False
for x in inputs:
x_ndim = ops.ndim(x)
if x_ndim is None:
x_shape = ops.shape(x)
batch_size = x_shape[0]
new_shape = backend.concatenate(
[x_shape[1:], ops.expand_dims(batch_size, axis=-1)]
)
x_transposed = ops.reshape(
x,
ops.stack(
[batch_size, ops.prod(x_shape[1:])],
axis=0,
),
)
x_transposed = ops.transpose(x_transposed, perm=(1, 0))
x_transposed = ops.reshape(x_transposed, new_shape)
reshaped_inputs.append(x_transposed)
transposed = True
elif x_ndim > 1:
dims = list(range(1, x_ndim)) + [0]
reshaped_inputs.append(ops.transpose(x, perm=dims))
print(dims)
transposed = True
else:
# We don't transpose inputs if they are 1D vectors or
# scalars.
reshaped_inputs.append(x)
y = self._merge_function(reshaped_inputs)
y_ndim = ops.ndim(y)
if transposed:
# If inputs have been transposed, we have to transpose the
# output too.
if y_ndim is None:
y_shape = ops.shape(y)
y_ndim = ops.shape(y_shape)[0]
batch_size = y_shape[y_ndim - 1]
new_shape = ops.concatenate(
[
ops.expand_dims(batch_size, axis=-1),
y_shape[: y_ndim - 1],
]
)
y = ops.reshape(y, (-1, batch_size))
y = ops.transpose(y, perm=(1, 0))
y = ops.reshape(y, new_shape)
elif y_ndim > 1:
dims = [y_ndim - 1] + list(range(y_ndim - 1))
y = ops.transpose(y, perm=dims)
return y
else:
return self._merge_function(inputs)
def compute_output_shape(self, input_shape):
if input_shape[0] is None:
output_shape = None
else:
output_shape = input_shape[0][1:]
for i in range(1, len(input_shape)):
if input_shape[i] is None:
shape = None
else:
shape = input_shape[i][1:]
output_shape = self._compute_elemwise_op_output_shape(
output_shape, shape
)
batch_sizes = {s[0] for s in input_shape if s is not None} - {None}
if len(batch_sizes) == 1:
output_shape = (list(batch_sizes)[0],) + output_shape
else:
output_shape = (None,) + output_shape
return output_shape
def compute_output_spec(self, inputs):
output_shape = self.compute_output_shape([x.shape for x in inputs])
output_sparse = all(x.sparse for x in inputs)
return KerasTensor(
output_shape, dtype=self.compute_dtype, sparse=output_sparse
)
def compute_mask(self, inputs, mask=None):
if mask is None:
return None
if not isinstance(mask, (tuple, list)):
raise ValueError(f"`mask` should be a list. Received: mask={mask}")
if not isinstance(inputs, (tuple, list)):
raise ValueError(
f"`inputs` should be a list. Received: inputs={inputs}"
)
if len(mask) != len(inputs):
raise ValueError(
"The lists `inputs` and `mask` should have the same length. "
f"Received: inputs={inputs} of length {len(inputs)}, and "
f"mask={mask} of length {len(mask)}"
)
# Default implementation does an OR between the masks, which works
# for `Add`, `Subtract`, `Average`, `Maximum`, `Minimum`, `Multiply`.
if any(m is None for m in mask):
return None
output_mask = mask[0]
for m in mask[1:]:
output_mask = ops.logical_or(output_mask, m)
return output_mask
def get_config(self):
return super().get_config()
| Merge |
python | ray-project__ray | python/ray/serve/_private/replica.py | {
"start": 45477,
"end": 47962
} | class ____(ReplicaBase):
async def _on_initialized(self):
# Get current rank from replica context during initialization
current_rank = ray.serve.context._get_internal_replica_context().rank
self._set_internal_replica_context(
servable_object=self._user_callable_wrapper.user_callable,
rank=current_rank,
)
# Save the initialization latency if the replica is initializing
# for the first time.
if self._initialization_latency is None:
self._initialization_latency = time.time() - self._initialization_start_time
def _on_request_cancelled(
self, metadata: RequestMetadata, e: asyncio.CancelledError
):
"""Recursively cancels child requests."""
requests_pending_assignment = (
ray.serve.context._get_requests_pending_assignment(
metadata.internal_request_id
)
)
for task in requests_pending_assignment.values():
task.cancel()
# Cancel child requests that have already been assigned.
in_flight_requests = _get_in_flight_requests(metadata.internal_request_id)
for replica_result in in_flight_requests.values():
replica_result.cancel()
def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception):
if ray.util.pdb._is_ray_debugger_post_mortem_enabled():
ray.util.pdb._post_mortem()
@contextmanager
def _wrap_request(
self, request_metadata: RequestMetadata
) -> Generator[StatusCodeCallback, None, None]:
"""Context manager that wraps user method calls.
1) Sets the request context var with appropriate metadata.
2) Records the access log message (if not disabled).
3) Records per-request metrics via the metrics manager.
"""
ray.serve.context._serve_request_context.set(
ray.serve.context._RequestContext(
route=request_metadata.route,
request_id=request_metadata.request_id,
_internal_request_id=request_metadata.internal_request_id,
app_name=self._deployment_id.app_name,
multiplexed_model_id=request_metadata.multiplexed_model_id,
grpc_context=request_metadata.grpc_context,
)
)
with self._handle_errors_and_metrics(request_metadata) as status_code_callback:
yield status_code_callback
| Replica |
python | doocs__leetcode | solution/0100-0199/0127.Word Ladder/Solution.py | {
"start": 0,
"end": 794
} | class ____:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
words = set(wordList)
q = deque([beginWord])
ans = 1
while q:
ans += 1
for _ in range(len(q)):
s = q.popleft()
s = list(s)
for i in range(len(s)):
ch = s[i]
for j in range(26):
s[i] = chr(ord('a') + j)
t = ''.join(s)
if t not in words:
continue
if t == endWord:
return ans
q.append(t)
words.remove(t)
s[i] = ch
return 0
| Solution |
python | weaviate__weaviate-python-client | weaviate/gql/filter.py | {
"start": 1437,
"end": 1747
} | class ____(ABC):
"""A base abstract class for GraphQL commands, such as Get, Aggregate."""
@abstractmethod
def build(self) -> str:
"""Build method to be overloaded by the child classes. It should return the GraphQL query as a str.
Returns:
The query.
"""
| GraphQL |
python | pydata__xarray | asv_bench/benchmarks/repr.py | {
"start": 1534,
"end": 1958
} | class ____:
# display a memory-saving pandas.RangeIndex shouldn't trigger memory
# expensive conversion into a numpy array
def setup(self):
index = xr.indexes.PandasIndex(pd.RangeIndex(1_000_000), "x")
self.ds = xr.Dataset(coords=xr.Coordinates.from_xindex(index))
def time_repr(self):
repr(self.ds.x)
def time_repr_html(self):
self.ds.x._repr_html_()
| ReprPandasRangeIndex |
python | realpython__materials | inheritance-and-composition/choosing/rectangle_square_demo.py | {
"start": 0,
"end": 312
} | class ____:
def __init__(self, length, height):
self._length = length
self._height = height
@property
def area(self):
return self._length * self._height
def resize(self, new_length, new_height):
self._length = new_length
self._height = new_height
| Rectangle |
python | astropy__astropy | astropy/units/tests/test_structured.py | {
"start": 9656,
"end": 10935
} | class ____(StructuredTestBaseWithUnits):
def test_len(self):
assert len(self.pv_unit) == 2
assert len(self.pv_t_unit) == 2
def test_keys(self):
slv = list(self.pv_t_unit.keys())
assert slv == ["pv", "t"]
def test_values(self):
values = self.pv_t_unit.values()
assert values == (self.pv_unit, self.t_unit)
def test_field_names(self):
field_names = self.pv_t_unit.field_names
assert isinstance(field_names, tuple)
assert field_names == (["pv", ("p", "v")], "t")
@pytest.mark.parametrize("iterable", [list, set])
def test_as_iterable(self, iterable):
sl = iterable(self.pv_unit)
assert isinstance(sl, iterable)
assert sl == iterable(["p", "v"])
def test_as_dict(self):
sd = dict(self.pv_t_unit)
assert sd == {"pv": self.pv_unit, "t": self.t_unit}
def test_contains(self):
assert "p" in self.pv_unit
assert "v" in self.pv_unit
assert "t" not in self.pv_unit
def test_setitem_fails(self):
with pytest.raises(TypeError, match="item assignment"):
self.pv_t_unit["t"] = u.Gyr
def test_hashing(self):
assert hash(self.pv_unit) != hash(self.pv_t_unit)
| TestStructuredUnitAsMapping |
python | apache__airflow | airflow-core/tests/unit/utils/test_deprecation_tools.py | {
"start": 10633,
"end": 21283
} | class ____:
"""Tests for the add_deprecated_classes function."""
@pytest.mark.parametrize(
("test_case", "module_imports", "override_classes", "expected_behavior"),
[
(
"basic_class_mapping",
{"old_module": {"OldClass": "new.module.NewClass"}},
None,
"creates_virtual_module",
),
(
"wildcard_pattern",
{"timezone": {"*": "airflow.sdk.timezone"}},
None,
"creates_virtual_module",
),
(
"with_override",
{"old_module": {"OldClass": "new.module.NewClass"}},
{"old_module": {"OldClass": "override.module.OverrideClass"}},
"creates_virtual_module",
),
],
ids=["basic_class_mapping", "wildcard_pattern", "with_override"],
)
def test_virtual_module_creation(self, test_case, module_imports, override_classes, expected_behavior):
"""Test add_deprecated_classes creates virtual modules correctly."""
# Use unique package and module names to avoid conflicts
package_name = get_unique_module_name("test_package")
module_name = f"{package_name}.{next(iter(module_imports.keys()))}"
with temporary_module(module_name):
add_deprecated_classes(module_imports, package_name, override_classes)
# Check that the module was added to sys.modules
assert module_name in sys.modules
assert isinstance(sys.modules[module_name], ModuleType)
assert hasattr(sys.modules[module_name], "__getattr__")
def test_add_deprecated_classes_doesnt_override_existing(self):
"""Test that add_deprecated_classes doesn't override existing modules."""
module_name = get_unique_module_name("existing_module")
full_module_name = f"airflow.test.{module_name}"
# Create an existing module
existing_module = ModuleType(full_module_name)
existing_module.existing_attr = "existing_value"
sys.modules[full_module_name] = existing_module
with temporary_module(full_module_name):
# This should not override the existing module
add_deprecated_classes(
{module_name: {"NewClass": "new.module.NewClass"}},
package="airflow.test",
)
# The existing module should still be there
assert sys.modules[full_module_name] == existing_module
assert sys.modules[full_module_name].existing_attr == "existing_value"
@pytest.mark.parametrize(
(
"test_case",
"module_imports",
"attr_name",
"target_attr",
"expected_target_msg",
"override_classes",
),
[
(
"direct_imports",
{
"get_something": "target.module.get_something",
"another_attr": "target.module.another_attr",
},
"get_something",
"get_something",
"target.module.get_something",
None,
),
(
"with_wildcard",
{"specific_attr": "target.module.specific_attr", "*": "target.module"},
"any_attribute",
"any_attribute",
"target.module.any_attribute",
None,
),
(
"with_override",
{"get_something": "target.module.get_something"},
"get_something",
"get_something",
"override.module.OverrideClass",
{"get_something": "override.module.OverrideClass"},
),
],
ids=["direct_imports", "with_wildcard", "with_override"],
)
def test_current_module_deprecation(
self, test_case, module_imports, attr_name, target_attr, expected_target_msg, override_classes
):
"""Test add_deprecated_classes with current module (__name__ key) functionality."""
module_name = get_unique_module_name(f"{test_case}_module")
full_module_name = f"airflow.test.{module_name}"
# Create a module to modify
test_module = ModuleType(full_module_name)
sys.modules[full_module_name] = test_module
with temporary_module(full_module_name):
# Mock the target module and attribute
mock_target_module = mock.MagicMock()
mock_attribute = mock.MagicMock()
setattr(mock_target_module, target_attr, mock_attribute)
with mock.patch(
"airflow.utils.deprecation_tools.importlib.import_module", return_value=mock_target_module
):
# Prepare override parameter
override_param = {full_module_name: override_classes} if override_classes else None
add_deprecated_classes(
{full_module_name: module_imports},
package=full_module_name,
override_deprecated_classes=override_param,
)
# The module should now have a __getattr__ method
assert hasattr(test_module, "__getattr__")
# Test that accessing the deprecated attribute works
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = getattr(test_module, attr_name)
assert result == mock_attribute
assert len(w) == 1
assert issubclass(w[0].category, DeprecatedImportWarning)
assert f"{full_module_name}.{attr_name}" in str(w[0].message)
assert expected_target_msg in str(w[0].message)
def test_add_deprecated_classes_mixed_current_and_virtual_modules(self):
"""Test add_deprecated_classes with mixed current module and virtual module imports."""
base_module_name = get_unique_module_name("mixed_module")
full_module_name = f"airflow.test.{base_module_name}"
virtual_module_name = f"{base_module_name}_virtual"
full_virtual_module_name = f"{full_module_name}.{virtual_module_name}"
# Create a module to modify
test_module = ModuleType(full_module_name)
sys.modules[full_module_name] = test_module
with temporary_module(full_module_name), temporary_module(full_virtual_module_name):
# Mock the target modules and attributes
mock_current_module = mock.MagicMock()
mock_current_attr = mock.MagicMock()
mock_current_module.current_attr = mock_current_attr
mock_virtual_module = mock.MagicMock()
mock_virtual_attr = mock.MagicMock()
mock_virtual_module.VirtualClass = mock_virtual_attr
def mock_import_module(module_name):
if "current.module" in module_name:
return mock_current_module
if "virtual.module" in module_name:
return mock_virtual_module
raise ImportError(f"Module {module_name} not found")
with mock.patch(
"airflow.utils.deprecation_tools.importlib.import_module", side_effect=mock_import_module
):
add_deprecated_classes(
{
full_module_name: {
"current_attr": "current.module.current_attr",
},
virtual_module_name: {
"VirtualClass": "virtual.module.VirtualClass",
},
},
package=full_module_name,
)
# Test current module access
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = test_module.current_attr
assert result == mock_current_attr
assert len(w) == 1
assert issubclass(w[0].category, DeprecatedImportWarning)
assert f"{full_module_name}.current_attr" in str(w[0].message)
# Test virtual module access
virtual_module = sys.modules[full_virtual_module_name]
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = virtual_module.VirtualClass
assert result == mock_virtual_attr
assert len(w) == 1
assert issubclass(w[0].category, DeprecatedImportWarning)
assert f"{full_virtual_module_name}.VirtualClass" in str(w[0].message)
def test_add_deprecated_classes_current_module_not_in_sys_modules(self):
"""Test add_deprecated_classes raises error when current module not in sys.modules."""
nonexistent_module = "nonexistent.module.name"
with pytest.raises(ValueError, match=f"Module {nonexistent_module} not found in sys.modules"):
add_deprecated_classes(
{nonexistent_module: {"attr": "target.module.attr"}},
package=nonexistent_module,
)
def test_add_deprecated_classes_preserves_existing_module_attributes(self):
"""Test that add_deprecated_classes preserves existing module attributes."""
module_name = get_unique_module_name("preserve_module")
full_module_name = f"airflow.test.{module_name}"
# Create a module with existing attributes
test_module = ModuleType(full_module_name)
test_module.existing_attr = "existing_value"
test_module.existing_function = lambda: "existing_function_result"
sys.modules[full_module_name] = test_module
with temporary_module(full_module_name):
add_deprecated_classes(
{
full_module_name: {
"deprecated_attr": "target.module.deprecated_attr",
}
},
package=full_module_name,
)
# Existing attributes should still be accessible
assert test_module.existing_attr == "existing_value"
assert test_module.existing_function() == "existing_function_result"
# The module should have __getattr__ for deprecated attributes
assert hasattr(test_module, "__getattr__")
| TestAddDeprecatedClasses |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_integration.py | {
"start": 638,
"end": 5029
} | class ____:
"""Test integration with LlamaIndex core components."""
@pytest.fixture
def mock_tool_spec(self):
"""Create a mocked tool spec for integration testing."""
with patch("llama_index.tools.scrapegraph.base.Client") as mock_client_class:
mock_client = Mock()
mock_client_class.from_env.return_value = mock_client
tool_spec = ScrapegraphToolSpec()
tool_spec.client = mock_client
return tool_spec, mock_client
def test_tool_conversion_to_llamaindex_tools(self, mock_tool_spec):
"""Test that tools are properly converted to LlamaIndex format."""
tool_spec, mock_client = mock_tool_spec
tools = tool_spec.to_tool_list()
# Verify all spec functions are converted
assert len(tools) == len(ScrapegraphToolSpec.spec_functions)
# Verify each tool has proper metadata
for tool in tools:
assert hasattr(tool, "metadata")
assert hasattr(tool.metadata, "name")
assert hasattr(tool.metadata, "description")
assert tool.metadata.name in ScrapegraphToolSpec.spec_functions
# Verify tools can be called
for tool in tools:
assert hasattr(tool, "call")
assert callable(tool.call)
def test_tool_metadata_and_descriptions(self, mock_tool_spec):
"""Test that tools have proper metadata and descriptions."""
tool_spec, _ = mock_tool_spec
tools = tool_spec.to_tool_list()
expected_descriptions = {
"scrapegraph_smartscraper": "Perform intelligent web scraping",
"scrapegraph_markdownify": "Convert webpage content to markdown",
"scrapegraph_search": "Perform a search query",
"scrapegraph_scrape": "Perform basic HTML scraping",
"scrapegraph_agentic_scraper": "Perform agentic web scraping",
}
for tool in tools:
tool_name = tool.metadata.name
assert tool_name in expected_descriptions
# Check that description contains expected keywords
description_lower = tool.metadata.description.lower()
expected_keywords = expected_descriptions[tool_name].lower()
assert any(
keyword in description_lower for keyword in expected_keywords.split()
)
@patch.dict(os.environ, {"SGAI_API_KEY": "test-key"})
def test_environment_variable_initialization(self):
"""Test initialization using environment variables."""
with patch("llama_index.tools.scrapegraph.base.Client") as mock_client_class:
mock_client = Mock()
mock_client_class.from_env.return_value = mock_client
# This should not raise an exception
tool_spec = ScrapegraphToolSpec()
# Verify that from_env was called
mock_client_class.from_env.assert_called_once()
def test_error_handling_in_tool_execution(self, mock_tool_spec):
"""Test that tools handle errors gracefully when integrated."""
tool_spec, mock_client = mock_tool_spec
# Mock all client methods to raise exceptions
mock_client.smartscraper.side_effect = Exception("API Error")
mock_client.markdownify.side_effect = Exception("Network Error")
mock_client.search.side_effect = Exception("Search Error")
mock_client.scrape.side_effect = Exception("Scrape Error")
mock_client.agentic_scraper.side_effect = Exception("Navigation Error")
# Test each method handles errors gracefully
response1 = tool_spec.scrapegraph_smartscraper("test", "https://example.com")
assert "error" in response1
assert "SmartScraper failed" in response1["error"]
response2 = tool_spec.scrapegraph_markdownify("https://example.com")
assert "Markdownify failed" in response2
response3 = tool_spec.scrapegraph_search("test query")
assert "Search failed" in response3
response4 = tool_spec.scrapegraph_scrape("https://example.com")
assert "error" in response4
assert "Scrape failed" in response4["error"]
response5 = tool_spec.scrapegraph_agentic_scraper("test", "https://example.com")
assert "error" in response5
assert "Agentic scraper failed" in response5["error"]
| TestLlamaIndexIntegration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.