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 | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 467111,
"end": 470791
} | class ____(Response):
"""
Response of tasks.publish_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "publish_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": {
"committed_versions_results": {
"description": "Committed versions results",
"items": {"additionalProperties": True, "type": "object"},
"type": "array",
},
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": "object",
},
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": "integer",
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, succeeded=None, failed=None, **kwargs):
super(PublishManyResponse, 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
| PublishManyResponse |
python | astropy__astropy | astropy/utils/data_info.py | {
"start": 6371,
"end": 8091
} | class ____(type):
def __new__(cls, name, bases, dct):
# Ensure that we do not gain a __dict__, which would mean
# arbitrary attributes could be set.
dct.setdefault("__slots__", [])
return super().__new__(cls, name, bases, dct)
def __init__(cls, name, bases, dct):
super().__init__(name, bases, dct)
# Define default getters/setters for attributes, if needed.
for attr in cls.attr_names:
if attr not in dct:
# If not defined explicitly for this class, did any of
# its superclasses define it, and, if so, was this an
# automatically defined look-up-on-parent attribute?
cls_attr = getattr(cls, attr, None)
if attr in cls.attrs_from_parent:
# If the attribute is supposed to be stored on the parent,
# and that is stated by this class yet it was not the case
# on the superclass, override it.
if "attrs_from_parent" in dct and not isinstance(
cls_attr, ParentAttribute
):
setattr(cls, attr, ParentAttribute(attr))
elif not cls_attr or isinstance(cls_attr, ParentAttribute):
# If the attribute is not meant to be stored on the parent,
# and if it was not defined already or was previously defined
# as an attribute on the parent, define a regular
# look-up-on-info attribute
setattr(
cls, attr, InfoAttribute(attr, cls._attr_defaults.get(attr))
)
| DataInfoMeta |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 95166,
"end": 96645
} | class ____(TestCase):
@cached_property
def alert_rule(self):
return self.create_alert_rule()
def test(self) -> None:
label = "hello"
alert_threshold = 1000
trigger = create_alert_rule_trigger(self.alert_rule, label, alert_threshold)
assert trigger.label == label
assert trigger.alert_threshold == alert_threshold
def test_existing_label(self) -> None:
name = "uh oh"
create_alert_rule_trigger(self.alert_rule, name, 100)
with pytest.raises(AlertRuleTriggerLabelAlreadyUsedError):
create_alert_rule_trigger(self.alert_rule, name, 100)
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.store_data.seer_anomaly_detection_connection_pool.urlopen"
)
def test_invalid_threshold_dynamic_alert(self, mock_seer_request: MagicMock) -> None:
seer_return_value: StoreDataResponse = {"success": True}
mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
rule = self.create_alert_rule(
time_window=15,
sensitivity=AlertRuleSensitivity.HIGH,
seasonality=AlertRuleSeasonality.AUTO,
detection_type=AlertRuleDetectionType.DYNAMIC,
)
create_alert_rule_trigger(rule, "yay", 0)
with pytest.raises(ValidationError):
create_alert_rule_trigger(rule, "no", 10)
| CreateAlertRuleTriggerTest |
python | chroma-core__chroma | chromadb/test/test_config.py | {
"start": 308,
"end": 646
} | class ____(Component):
def __init__(self, system: System):
data.inits += "A"
super().__init__(system)
self.require(ComponentB)
self.require(ComponentC)
@overrides
def start(self) -> None:
data.starts += "A"
@overrides
def stop(self) -> None:
data.stops += "A"
| ComponentA |
python | django__django | django/db/models/fields/__init__.py | {
"start": 87900,
"end": 92009
} | class ____(DateTimeCheckMixin, Field):
empty_strings_allowed = False
default_error_messages = {
"invalid": _(
"“%(value)s” value has an invalid format. It must be in "
"HH:MM[:ss[.uuuuuu]] format."
),
"invalid_time": _(
"“%(value)s” value has the correct format "
"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
),
}
description = _("Time")
def __init__(
self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
):
self.auto_now, self.auto_now_add = auto_now, auto_now_add
if auto_now or auto_now_add:
kwargs["editable"] = False
kwargs["blank"] = True
super().__init__(verbose_name, name, **kwargs)
def _check_fix_default_value(self):
"""
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
"""
if not self.has_default():
return []
value = self.default
if isinstance(value, datetime.datetime):
now = None
elif isinstance(value, datetime.time):
now = _get_naive_now()
# This will not use the right date in the race condition where now
# is just before the date change and value is just past 0:00.
value = datetime.datetime.combine(now.date(), value)
else:
# No explicit time / datetime value -- no checks necessary
return []
# At this point, value is a datetime object.
return self._check_if_value_fixed(value, now=now)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
if self.auto_now is not False:
kwargs["auto_now"] = self.auto_now
if self.auto_now_add is not False:
kwargs["auto_now_add"] = self.auto_now_add
if self.auto_now or self.auto_now_add:
del kwargs["blank"]
del kwargs["editable"]
return name, path, args, kwargs
def get_internal_type(self):
return "TimeField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, datetime.time):
return value
if isinstance(value, datetime.datetime):
# Not usually a good idea to pass in a datetime here (it loses
# information), but this can be a side-effect of interacting with a
# database backend (e.g. Oracle), so we'll be accommodating.
return value.time()
try:
parsed = parse_time(value)
if parsed is not None:
return parsed
except ValueError:
raise exceptions.ValidationError(
self.error_messages["invalid_time"],
code="invalid_time",
params={"value": value},
)
raise exceptions.ValidationError(
self.error_messages["invalid"],
code="invalid",
params={"value": value},
)
def pre_save(self, model_instance, add):
if self.auto_now or (self.auto_now_add and add):
value = datetime.datetime.now().time()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
def get_prep_value(self, value):
value = super().get_prep_value(value)
return self.to_python(value)
def get_db_prep_value(self, value, connection, prepared=False):
# Casts times into the format expected by the backend
if not prepared:
value = self.get_prep_value(value)
return connection.ops.adapt_timefield_value(value)
def value_to_string(self, obj):
val = self.value_from_object(obj)
return "" if val is None else val.isoformat()
def formfield(self, **kwargs):
return super().formfield(
**{
"form_class": forms.TimeField,
**kwargs,
}
)
| TimeField |
python | pypa__warehouse | warehouse/email/ses/models.py | {
"start": 7031,
"end": 7766
} | class ____(db.Model):
__tablename__ = "ses_events"
created: Mapped[datetime_now]
email_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey(
"ses_emails.id", deferrable=True, initially="DEFERRED", ondelete="CASCADE"
),
index=True,
)
email: Mapped[EmailMessage] = orm.relationship(
back_populates="events",
lazy=False,
)
event_id: Mapped[str] = mapped_column(unique=True, index=True)
event_type: Mapped[Enum] = mapped_column(
Enum(EventTypes, values_callable=lambda x: [e.value for e in x])
)
data: Mapped[dict] = mapped_column(
MutableDict.as_mutable(JSONB()), server_default=sql.text("'{}'")
)
| Event |
python | falconry__falcon | falcon/errors.py | {
"start": 39965,
"end": 40300
} | class ____(HTTPContentTooLarge):
"""Compatibility alias of :class:`falcon.HTTPContentTooLarge`."""
@deprecation.deprecated(
'HTTPPayloadTooLarge is deprecated; use HTTPContentTooLarge instead.'
)
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| HTTPPayloadTooLarge |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 46535,
"end": 47107
} | class ____(PrefectFilterBaseModel):
"""Filter by `Log.name`."""
any_: Optional[list[str]] = Field(
default=None,
description="A list of log names to include",
examples=[["prefect.logger.flow_runs", "prefect.logger.task_runs"]],
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
filters: list[sa.ColumnExpressionArgument[bool]] = []
if self.any_ is not None:
filters.append(db.Log.name.in_(self.any_))
return filters
| LogFilterName |
python | doocs__leetcode | solution/2300-2399/2305.Fair Distribution of Cookies/Solution.py | {
"start": 0,
"end": 571
} | class ____:
def distributeCookies(self, cookies: List[int], k: int) -> int:
def dfs(i):
if i >= len(cookies):
nonlocal ans
ans = max(cnt)
return
for j in range(k):
if cnt[j] + cookies[i] >= ans or (j and cnt[j] == cnt[j - 1]):
continue
cnt[j] += cookies[i]
dfs(i + 1)
cnt[j] -= cookies[i]
ans = inf
cnt = [0] * k
cookies.sort(reverse=True)
dfs(0)
return ans
| Solution |
python | doocs__leetcode | solution/0100-0199/0149.Max Points on a Line/Solution.py | {
"start": 0,
"end": 530
} | class ____:
def maxPoints(self, points: List[List[int]]) -> int:
n = len(points)
ans = 1
for i in range(n):
x1, y1 = points[i]
for j in range(i + 1, n):
x2, y2 = points[j]
cnt = 2
for k in range(j + 1, n):
x3, y3 = points[k]
a = (y2 - y1) * (x3 - x1)
b = (y3 - y1) * (x2 - x1)
cnt += a == b
ans = max(ans, cnt)
return ans
| Solution |
python | pypa__setuptools | setuptools/build_meta.py | {
"start": 5125,
"end": 9899
} | class ____:
"""Translate ``config_settings`` into distutils-style command arguments.
Only a limited number of options is currently supported.
"""
# See pypa/setuptools#1928 pypa/setuptools#2491
def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
"""
Get the value of a specific key in ``config_settings`` as a list of strings.
>>> fn = _ConfigSettingsTranslator()._get_config
>>> fn("--global-option", None)
[]
>>> fn("--global-option", {})
[]
>>> fn("--global-option", {'--global-option': 'foo'})
['foo']
>>> fn("--global-option", {'--global-option': ['foo']})
['foo']
>>> fn("--global-option", {'--global-option': 'foo'})
['foo']
>>> fn("--global-option", {'--global-option': 'foo bar'})
['foo', 'bar']
"""
cfg = config_settings or {}
opts = cfg.get(key) or []
return shlex.split(opts) if isinstance(opts, str) else opts
def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
"""
Let the user specify ``verbose`` or ``quiet`` + escape hatch via
``--global-option``.
Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,
so we just have to cover the basic scenario ``-v``.
>>> fn = _ConfigSettingsTranslator()._global_args
>>> list(fn(None))
[]
>>> list(fn({"verbose": "False"}))
['-q']
>>> list(fn({"verbose": "1"}))
['-v']
>>> list(fn({"--verbose": None}))
['-v']
>>> list(fn({"verbose": "true", "--global-option": "-q --no-user-cfg"}))
['-v', '-q', '--no-user-cfg']
>>> list(fn({"--quiet": None}))
['-q']
"""
cfg = config_settings or {}
falsey = {"false", "no", "0", "off"}
if "verbose" in cfg or "--verbose" in cfg:
level = str(cfg.get("verbose") or cfg.get("--verbose") or "1")
yield ("-q" if level.lower() in falsey else "-v")
if "quiet" in cfg or "--quiet" in cfg:
level = str(cfg.get("quiet") or cfg.get("--quiet") or "1")
yield ("-v" if level.lower() in falsey else "-q")
yield from self._get_config("--global-option", config_settings)
def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
"""
The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.
.. warning::
We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``
commands run in ``build_sdist`` and ``build_wheel`` to reuse the egg-info
directory created in ``prepare_metadata_for_build_wheel``.
>>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args
>>> list(fn(None))
[]
>>> list(fn({"tag-date": "False"}))
['--no-date']
>>> list(fn({"tag-date": None}))
['--no-date']
>>> list(fn({"tag-date": "true", "tag-build": ".a"}))
['--tag-date', '--tag-build', '.a']
"""
cfg = config_settings or {}
if "tag-date" in cfg:
val = strtobool(str(cfg["tag-date"] or "false"))
yield ("--tag-date" if val else "--no-date")
if "tag-build" in cfg:
yield from ["--tag-build", str(cfg["tag-build"])]
def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
"""
The ``editable_wheel`` command accepts ``editable-mode=strict``.
>>> fn = _ConfigSettingsTranslator()._editable_args
>>> list(fn(None))
[]
>>> list(fn({"editable-mode": "strict"}))
['--mode', 'strict']
"""
cfg = config_settings or {}
mode = cfg.get("editable-mode") or cfg.get("editable_mode")
if not mode:
return
yield from ["--mode", str(mode)]
def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:
"""
Users may expect to pass arbitrary lists of arguments to a command
via "--global-option" (example provided in PEP 517 of a "escape hatch").
>>> fn = _ConfigSettingsTranslator()._arbitrary_args
>>> list(fn(None))
[]
>>> list(fn({}))
[]
>>> list(fn({'--build-option': 'foo'}))
['foo']
>>> list(fn({'--build-option': ['foo']}))
['foo']
>>> list(fn({'--build-option': 'foo'}))
['foo']
>>> list(fn({'--build-option': 'foo bar'}))
['foo', 'bar']
>>> list(fn({'--global-option': 'foo'}))
[]
"""
yield from self._get_config("--build-option", config_settings)
| _ConfigSettingsTranslator |
python | wandb__wandb | wandb/errors/warnings.py | {
"start": 0,
"end": 57
} | class ____(Warning):
"""Base W&B Warning."""
| WandbWarning |
python | sympy__sympy | sympy/stats/drv.py | {
"start": 9520,
"end": 9675
} | class ____(ProductDomain, DiscreteDomain):
def as_boolean(self):
return And(*[domain.as_boolean for domain in self.domains])
| ProductDiscreteDomain |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_organization_release_details.py | {
"start": 45139,
"end": 49701
} | class ____(APITestCase):
def test_simple(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
release_file = ReleaseFile.objects.create(
organization_id=project.organization_id,
release_id=release.id,
file=File.objects.create(name="application.js", type="release.file"),
name="http://example.com/application.js",
)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.delete(url)
assert response.status_code == 204, response.content
assert not Release.objects.filter(id=release.id).exists()
assert not ReleaseFile.objects.filter(id=release_file.id).exists()
def test_existing_group(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[team], organization=org)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_group(first_release=release)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.delete(url)
assert response.status_code == 400, response.content
assert Release.objects.filter(id=release.id).exists()
def test_bad_repo_name(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.create_organization()
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(name="foo", organization=org, teams=[team])
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
data={
"version": "1.2.1",
"projects": [project.slug],
"refs": [{"repository": "not_a_repo", "commit": "a" * 40}],
},
)
assert response.status_code == 400
assert response.data == {"refs": ["Invalid repository names: not_a_repo"]}
def test_bad_commit_list(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.create_organization()
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(name="foo", organization=org, teams=[team])
Repository.objects.create(organization_id=org.id, name="a_repo")
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
release.add_project(project)
self.create_member(teams=[team], user=user, organization=org)
self.login_as(user=user)
url = reverse(
"sentry-api-0-organization-release-details",
kwargs={"organization_id_or_slug": org.slug, "version": release.version},
)
response = self.client.put(
url,
data={
"version": "1.2.1",
"projects": [project.slug],
"commits": [{"repository": "a_repo"}],
},
)
assert response.status_code == 400
assert response.json() == {"commits": {"id": ["This field is required."]}}
| ReleaseDeleteTest |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 28856,
"end": 30172
} | class ____(TestCase):
def test_warning_many_to_many(self):
"""Tests that using a PrimaryKeyRelatedField for a ManyToMany field breaks with default=None."""
class ManyToManySourceSerializer(serializers.ModelSerializer):
targets = serializers.PrimaryKeyRelatedField(
many=True,
queryset=ManyToManyTarget.objects.all(),
default=None
)
class Meta:
model = ManyToManySource
fields = '__all__'
# Instantiates serializer without 'value' field to force using the default=None for the ManyToMany relation
serializer = ManyToManySourceSerializer(data={
"name": "Invalid Example",
})
error_msg = "The field 'targets' on serializer 'ManyToManySourceSerializer' is a ManyToMany field and cannot have a default value of None."
# Calls to get_fields() should raise a ValueError
with pytest.raises(ValueError) as exc_info:
serializer.get_fields()
assert str(exc_info.value) == error_msg
# Calls to is_valid() should behave the same
with pytest.raises(ValueError) as exc_info:
serializer.is_valid(raise_exception=True)
assert str(exc_info.value) == error_msg
| TestWarningManyToMany |
python | streamlit__streamlit | lib/tests/streamlit/runtime/scriptrunner/code_exec_test.py | {
"start": 1357,
"end": 4377
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.ctx = ScriptRunContext(
session_id="test session id",
_enqueue=ForwardMsgQueue().enqueue,
query_string="",
session_state=SafeSessionState(SessionState(), lambda: None),
uploaded_file_mgr=MemoryUploadedFileManager(""),
main_script_path="",
user_info={"email": "something@else.com"},
fragment_storage=MemoryFragmentStorage(),
pages_manager=PagesManager(""),
)
return super().setUp()
def test_func_succeeds(self):
def test_func():
"""Test function that does nothing and, thus, succeeds."""
return 42
(
result,
run_without_errors,
rerun_exception_data,
premature_stop,
uncaught_exception,
) = exec_func_with_error_handling(test_func, self.ctx)
assert result == 42
assert run_without_errors is True
assert rerun_exception_data is None
assert premature_stop is False
assert uncaught_exception is None
def test_func_throws_rerun_exception(self):
rerun_data = RerunData(query_string="foo")
def test_func():
"""Test function that raises a RerunException."""
raise RerunException(rerun_data)
(
_,
run_without_errors,
rerun_exception_data,
premature_stop,
uncaught_exception,
) = exec_func_with_error_handling(test_func, self.ctx)
assert run_without_errors is True
assert rerun_exception_data == rerun_data
assert premature_stop is False
assert uncaught_exception is None
def test_func_throws_stop_exception(self):
def test_func():
"""Test function that raises a StopException."""
raise StopException()
(
_,
run_without_errors,
rerun_exception_data,
premature_stop,
uncaught_exception,
) = exec_func_with_error_handling(test_func, self.ctx)
assert run_without_errors is True
assert rerun_exception_data is None
assert premature_stop is True
assert uncaught_exception is None
@parameterized.expand([(ValueError), (TypeError), (RuntimeError), (Exception)])
def test_func_throws_generic_exception(self, exception_type: type):
def test_func():
"""Test function that raises a generic Exception."""
raise exception_type()
(
_,
run_without_errors,
rerun_exception_data,
premature_stop,
uncaught_exception,
) = exec_func_with_error_handling(test_func, self.ctx)
assert run_without_errors is False
assert rerun_exception_data is None
assert premature_stop is True
assert isinstance(uncaught_exception, exception_type)
| TestWrapInTryAndExec |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigtable.py | {
"start": 20700,
"end": 24051
} | class ____(GoogleCloudBaseOperator, BigtableValidationMixin):
"""
Deletes the Cloud Bigtable table.
For more details about deleting table have a look at the reference:
https://googleapis.github.io/google-cloud-python/latest/bigtable/table.html#google.cloud.bigtable.table.Table.delete
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigtableDeleteTableOperator`
:param instance_id: The ID of the Cloud Bigtable instance.
:param table_id: The ID of the table to be deleted.
:param project_id: Optional, the ID of the Google Cloud project. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:param app_profile_id: Application profile.
:param gcp_conn_id: The connection ID to use to connect to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
REQUIRED_ATTRIBUTES = ("instance_id", "table_id") # type: Iterable[str]
template_fields: Sequence[str] = (
"project_id",
"instance_id",
"table_id",
"impersonation_chain",
)
def __init__(
self,
*,
instance_id: str,
table_id: str,
project_id: str = PROVIDE_PROJECT_ID,
app_profile_id: str | None = None,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
self.project_id = project_id
self.instance_id = instance_id
self.table_id = table_id
self.app_profile_id = app_profile_id
self._validate_inputs()
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
super().__init__(**kwargs)
def execute(self, context: Context) -> None:
hook = BigtableHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
instance = hook.get_instance(project_id=self.project_id, instance_id=self.instance_id)
if not instance:
raise AirflowException(f"Dependency: instance '{self.instance_id}' does not exist.")
try:
hook.delete_table(
project_id=self.project_id,
instance_id=self.instance_id,
table_id=self.table_id,
)
except google.api_core.exceptions.NotFound:
# It's OK if table doesn't exists.
self.log.info("The table '%s' no longer exists. Consider it as deleted", self.table_id)
except google.api_core.exceptions.GoogleAPICallError as e:
self.log.error("An error occurred. Exiting.")
raise e
| BigtableDeleteTableOperator |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/orc_asset.py | {
"start": 1393,
"end": 1982
} | class ____(DirectoryDataAsset, ORCAssetBase):
type: Literal["directory_orc"] = "directory_orc"
@classmethod
@override
def _get_reader_method(cls) -> str:
return "orc"
@override
def _get_reader_options_include(self) -> set[str]:
"""These options are available as of spark v3.4.0
See https://spark.apache.org/docs/latest/sql-data-sources-orc.html for more info.
"""
return (
super()._get_reader_options_include()
| super(DirectoryDataAsset, self)._get_reader_options_include()
)
| DirectoryORCAsset |
python | huggingface__transformers | src/transformers/pipelines/text_generation.py | {
"start": 393,
"end": 541
} | class ____(enum.Enum):
TENSORS = 0
NEW_TEXT = 1
FULL_TEXT = 2
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
| ReturnType |
python | Netflix__metaflow | metaflow/plugins/env_escape/override_decorators.py | {
"start": 585,
"end": 627
} | class ____(Override):
pass
| LocalOverride |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 20677,
"end": 24078
} | class ____(unittest.TestCase):
def readpipe_interrupted(self, interrupt):
"""Perform a read during which a signal will arrive. Return True if the
read is interrupted by the signal and raises an exception. Return False
if it returns normally.
"""
# use a subprocess to have only one thread, to have a timeout on the
# blocking read and to not touch signal handling in this process
code = """if 1:
import errno
import os
import signal
import sys
interrupt = %r
r, w = os.pipe()
def handler(signum, frame):
1 / 0
signal.signal(signal.SIGALRM, handler)
if interrupt is not None:
signal.siginterrupt(signal.SIGALRM, interrupt)
print("ready")
sys.stdout.flush()
# run the test twice
try:
for loop in range(2):
# send a SIGALRM in a second (during the read)
signal.alarm(1)
try:
# blocking call: read from a pipe without data
os.read(r, 1)
except ZeroDivisionError:
pass
else:
sys.exit(2)
sys.exit(3)
finally:
os.close(r)
os.close(w)
""" % (interrupt,)
with spawn_python('-c', code) as process:
try:
# wait until the child process is loaded and has started
first_line = process.stdout.readline()
stdout, stderr = process.communicate(timeout=support.SHORT_TIMEOUT)
except subprocess.TimeoutExpired:
process.kill()
return False
else:
stdout = first_line + stdout
exitcode = process.wait()
if exitcode not in (2, 3):
raise Exception("Child error (exit code %s): %r"
% (exitcode, stdout))
return (exitcode == 3)
def test_without_siginterrupt(self):
# If a signal handler is installed and siginterrupt is not called
# at all, when that signal arrives, it interrupts a syscall that's in
# progress.
interrupted = self.readpipe_interrupted(None)
self.assertTrue(interrupted)
def test_siginterrupt_on(self):
# If a signal handler is installed and siginterrupt is called with
# a true value for the second argument, when that signal arrives, it
# interrupts a syscall that's in progress.
interrupted = self.readpipe_interrupted(True)
self.assertTrue(interrupted)
def test_siginterrupt_off(self):
# If a signal handler is installed and siginterrupt is called with
# a false value for the second argument, when that signal arrives, it
# does not interrupt a syscall that's in progress.
interrupted = self.readpipe_interrupted(False)
self.assertFalse(interrupted)
@unittest.skipIf(sys.platform == "win32", "Not valid on Windows")
@unittest.skipUnless(hasattr(signal, 'getitimer') and hasattr(signal, 'setitimer'),
"needs signal.getitimer() and signal.setitimer()")
| SiginterruptTest |
python | pytorch__pytorch | test/nn/test_lazy_modules.py | {
"start": 394,
"end": 479
} | class ____(torch.nn.modules.lazy.LazyModuleMixin, torch.nn.Module):
pass
| LazyModule |
python | pytorch__pytorch | torch/distributed/checkpoint/_consolidate_hf_safetensors.py | {
"start": 612,
"end": 1178
} | class ____:
"""
Dataclass to store information about a tensor (identified by its fully qualified name).
Attributes:
offset_in_file: Byte offset where this tensor's data begins in the output file
shape_in_file: Shape of the tensor in the output file
dtype_size: Size of the tensor's data type in bytes
dtype_str: String representation of the tensor's data type
"""
offset_in_file: int = 0
shape_in_file: list[int] = field(default_factory=list)
dtype_size: int = 0
dtype_str: str = ""
@dataclass
| _FqnData |
python | allegroai__clearml | clearml/utilities/version.py | {
"start": 1603,
"end": 11303
} | class ____(_BaseVersion):
VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]?
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\.]?
(?P<pre_n>[0-9]+)?
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+))
|
(?:
[-_\.]?
(?P<post_l>post|rev|r)
[-_\.]?
(?P<post_n2>[0-9]+)?
)
)?
(?P<dev> # dev release
[-_\.]?
(?P<dev_l>dev)
[-_\.]?
(?P<dev_n>[0-9]+)?
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
_regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)
_local_version_separators = re.compile(r"[\._-]")
def __init__(self, version: str) -> None:
# Validate the version and parse it into pieces
match = self._regex.search(version)
if not match:
raise InvalidVersion("Invalid version: '{0}'".format(version))
# Store the parsed out pieces of the version
self._version = _Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=self._parse_letter_version(match.group("pre_l"), match.group("pre_n")),
post=self._parse_letter_version(
match.group("post_l") or "",
match.group("post_n1") or match.group("post_n2") or "",
),
dev=self._parse_letter_version(match.group("dev_l") or "", match.group("dev_n") or ""),
local=self._parse_local_version(match.group("local") or ""),
)
# Generate a key which will be used for sorting
key = self._cmpkey(
self._version.epoch,
self._version.release,
self._version.pre,
self._version.post,
self._version.dev,
self._version.local,
)
super(Version, self).__init__(key)
def __repr__(self) -> str:
return "<Version({0})>".format(repr(str(self)))
def __str__(self) -> str:
parts = []
# Epoch
if self.epoch != 0:
parts.append("{0}!".format(self.epoch))
# Release segment
parts.append(".".join(str(x) for x in self.release))
# Pre-release
if self.pre is not None:
parts.append("".join(str(x) for x in self.pre))
# Post-release
if self.post is not None:
parts.append(".post{0}".format(self.post))
# Development release
if self.dev is not None:
parts.append(".dev{0}".format(self.dev))
# Local version segment
if self.local is not None:
parts.append("+{0}".format(self.local))
return "".join(parts)
def get_next_version(self) -> "Version":
def increment(part: Union[int, List[Union[int, str]]]) -> Union[int, List[Union[int, str]]]:
if isinstance(part, int):
return part + 1
type_ = type(part)
part = list(part)
if isinstance(part[-1], int):
part[-1] += 1
return type_(part)
next_version = deepcopy(self)
if next_version._version.dev:
next_version._version.dev = increment(next_version._version.dev)
elif next_version._version.post:
next_version._version.post = increment(next_version._version.post)
elif next_version._version.pre:
next_version._version.pre = increment(next_version._version.pre)
elif next_version._version.release:
next_version._version.release = increment(next_version._version.release)
elif next_version._version.epoch:
next_version._version.epoch = increment(next_version._version.epoch)
return next_version
@property
def epoch(self) -> int:
return self._version.epoch
@property
def release(self) -> Tuple[int]:
return self._version.release
@property
def pre(self) -> Optional[Tuple[str, int]]:
return self._version.pre
@property
def post(self) -> Optional[int]:
return self._version.post[1] if self._version.post else None
@property
def dev(self) -> Optional[int]:
return self._version.dev[1] if self._version.dev else None
@property
def local(self) -> Optional[str]:
if self._version.local:
return ".".join(str(x) for x in self._version.local)
else:
return None
@property
def public(self) -> str:
return str(self).split("+", 1)[0]
@property
def base_version(self) -> str:
parts = []
# Epoch
if self.epoch != 0:
parts.append("{0}!".format(self.epoch))
# Release segment
parts.append(".".join(str(x) for x in self.release))
return "".join(parts)
@property
def is_prerelease(self) -> bool:
return self.dev is not None or self.pre is not None
@property
def is_postrelease(self) -> bool:
return self.post is not None
@property
def is_devrelease(self) -> bool:
return self.dev is not None
@staticmethod
def _parse_letter_version(letter: str, number: str) -> Optional[Tuple[str, int]]:
if not letter and not number:
return None
if letter:
# We consider there to be an implicit 0 in a pre-release if there is
# not a numeral associated with it.
if number is None:
number = 0
# We normalize any letters to their lower case form
letter = letter.lower()
# We consider some words to be alternate spellings of other words and
# in those cases we want to normalize the spellings to our preferred
# spelling.
if letter == "alpha":
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
letter = "rc"
elif letter in ["rev", "r"]:
letter = "post"
return letter, int(number)
if not letter and number:
# We assume if we are given a number, but we are not given a letter
# then this is using the implicit post release syntax (e.g. 1.0-1)
letter = "post"
return letter, int(number)
@classmethod
def is_valid_version_string(cls, version_string: str) -> bool:
if not version_string:
return False
match = cls._regex.search(version_string)
return bool(match)
@classmethod
def _parse_local_version(cls, local: str) -> Optional[Tuple[Union[str, int]]]:
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
local = tuple(
part.lower() if not part.isdigit() else int(part) for part in cls._local_version_separators.split(local)
)
if not local or not local[0]:
return None
return local
return None
@staticmethod
def _cmpkey(
epoch: int,
release: Tuple[int],
pre: Optional[Tuple[str, int]],
post: Optional[Tuple[str, int]],
dev: Optional[Tuple[str, int]],
local: Optional[Tuple[Union[str, int]]],
) -> Tuple[int, Tuple[int], float, float, float, Union[float, Tuple[Union[str, int]]]]:
# When we compare a release version, we want to compare it with all of the
# trailing zeros removed. So we'll use a reverse the list, drop all the now
# leading zeros until we come to something non zero, then take the rest
# re-reverse it back into the correct order and make it a tuple and use
# that for our sorting key.
# release = tuple(
# reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
# )
# Versions without a pre-release (except as noted above) should sort after
# those with one.
if not pre:
pre = inf
elif pre:
pre = pre[1]
# Versions without a post segment should sort before those with one.
if not post:
post = -inf
else:
post = post[1]
# Versions without a development segment should sort after those with one.
if not dev:
dev = inf
else:
dev = dev[1]
if not local:
# Versions without a local segment should sort before those with one.
local = inf
else:
# Versions with a local segment need that segment parsed to implement
# the sorting rules in PEP440.
# - Alpha numeric segments sort before numeric segments
# - Alpha numeric segments sort lexicographically
# - Numeric segments sort numerically
# - Shorter versions sort before longer versions when the prefixes
# match exactly
local = local[1]
return epoch, release, pre, post, dev, local
| Version |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 2379,
"end": 2413
} | class ____(TypedDict):
id: ID
| Ref |
python | coleifer__peewee | tests/regressions.py | {
"start": 38699,
"end": 39267
} | class ____(ModelTestCase):
requires = [BoolModel]
def test_boolean_compare(self):
b1 = BoolModel.create(key='b1', active=True)
b2 = BoolModel.create(key='b2', active=False)
expr2key = (
((BoolModel.active == True), 'b1'),
((BoolModel.active == False), 'b2'),
((BoolModel.active != True), 'b2'),
((BoolModel.active != False), 'b1'))
for expr, key in expr2key:
q = BoolModel.select().where(expr)
self.assertEqual([b.key for b in q], [key])
| TestBooleanCompare |
python | python__mypy | mypy/nodes.py | {
"start": 79544,
"end": 79916
} | class ____(Expression):
"""TypeForm(type) expression."""
__slots__ = ("type",)
__match_args__ = ("type",)
type: mypy.types.Type
def __init__(self, typ: mypy.types.Type) -> None:
super().__init__()
self.type = typ
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visitor.visit_type_form_expr(self)
| TypeFormExpr |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 20952,
"end": 21427
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
error_code: Optional[str] = Field(
None, description="Error code", examples=["INTERNAL_ERROR"]
)
message: Optional[str] = Field(
None,
description=(
"Human-readable error message that describes the cause of the error."
),
examples=["Unexpected error."],
)
| Error |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/equalization_test.py | {
"start": 199,
"end": 4962
} | class ____(testing.TestCase):
def assertAllInRange(self, array, min_val, max_val):
self.assertTrue(np.all(array >= min_val))
self.assertTrue(np.all(array <= max_val))
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.Equalization,
init_kwargs={
"value_range": (0, 255),
"data_format": "channels_last",
},
input_shape=(1, 2, 2, 3),
supports_masking=False,
expected_output_shape=(1, 2, 2, 3),
)
self.run_layer_test(
layers.Equalization,
init_kwargs={
"value_range": (0, 255),
"data_format": "channels_first",
},
input_shape=(1, 3, 2, 2),
supports_masking=False,
expected_output_shape=(1, 3, 2, 2),
)
def test_equalizes_to_all_bins(self):
xs = np.random.uniform(size=(2, 512, 512, 3), low=0, high=255).astype(
np.float32
)
layer = layers.Equalization(value_range=(0, 255))
xs = layer(xs)
for i in range(0, 256):
self.assertTrue(np.any(ops.convert_to_numpy(xs) == i))
@parameterized.named_parameters(
("float32", np.float32), ("int32", np.int32), ("int64", np.int64)
)
def test_input_dtypes(self, dtype):
xs = np.random.uniform(size=(2, 512, 512, 3), low=0, high=255).astype(
dtype
)
layer = layers.Equalization(value_range=(0, 255))
xs = ops.convert_to_numpy(layer(xs))
for i in range(0, 256):
self.assertTrue(np.any(xs == i))
self.assertAllInRange(xs, 0, 255)
@parameterized.named_parameters(("0_255", 0, 255), ("0_1", 0, 1))
def test_output_range(self, lower, upper):
xs = np.random.uniform(
size=(2, 512, 512, 3), low=lower, high=upper
).astype(np.float32)
layer = layers.Equalization(value_range=(lower, upper))
xs = ops.convert_to_numpy(layer(xs))
self.assertAllInRange(xs, lower, upper)
def test_constant_regions(self):
xs = np.zeros((1, 64, 64, 3), dtype=np.float32)
xs[:, :21, :, :] = 50
xs[:, 21:42, :, :] = 100
xs[:, 42:, :, :] = 200
layer = layers.Equalization(value_range=(0, 255))
equalized = ops.convert_to_numpy(layer(xs))
self.assertTrue(len(np.unique(equalized)) >= 3)
self.assertAllInRange(equalized, 0, 255)
def test_grayscale_images(self):
xs_last = np.random.uniform(0, 255, size=(2, 64, 64, 1)).astype(
np.float32
)
layer_last = layers.Equalization(
value_range=(0, 255), data_format="channels_last"
)
equalized_last = ops.convert_to_numpy(layer_last(xs_last))
self.assertEqual(equalized_last.shape[-1], 1)
self.assertAllInRange(equalized_last, 0, 255)
xs_first = np.random.uniform(0, 255, size=(2, 1, 64, 64)).astype(
np.float32
)
layer_first = layers.Equalization(
value_range=(0, 255), data_format="channels_first"
)
equalized_first = ops.convert_to_numpy(layer_first(xs_first))
self.assertEqual(equalized_first.shape[1], 1)
self.assertAllInRange(equalized_first, 0, 255)
def test_single_color_image(self):
xs_last = np.full((1, 64, 64, 3), 128, dtype=np.float32)
layer_last = layers.Equalization(
value_range=(0, 255), data_format="channels_last"
)
equalized_last = ops.convert_to_numpy(layer_last(xs_last))
self.assertAllClose(equalized_last, 128.0)
xs_first = np.full((1, 3, 64, 64), 128, dtype=np.float32)
layer_first = layers.Equalization(
value_range=(0, 255), data_format="channels_first"
)
equalized_first = ops.convert_to_numpy(layer_first(xs_first))
self.assertAllClose(equalized_first, 128.0)
def test_different_bin_sizes(self):
xs = np.random.uniform(0, 255, size=(1, 64, 64, 3)).astype(np.float32)
bin_sizes = [16, 64, 128, 256]
for bins in bin_sizes:
layer = layers.Equalization(value_range=(0, 255), bins=bins)
equalized = ops.convert_to_numpy(layer(xs))
self.assertAllInRange(equalized, 0, 255)
def test_tf_data_compatibility(self):
layer = layers.Equalization(value_range=(0, 255))
input_data = np.random.random((2, 8, 8, 3)) * 255
ds = tf_data.Dataset.from_tensor_slices(input_data).batch(2).map(layer)
for output in ds.take(1):
output_array = output.numpy()
self.assertAllInRange(output_array, 0, 255)
| EqualizationTest |
python | getsentry__sentry | src/sentry/search/events/datasets/spans_indexed.py | {
"start": 22504,
"end": 49635
} | class ____(SpansIndexedDatasetConfig):
"""Eventually should just write the eap dataset from scratch, but inheriting for now to move fast"""
sampling_weight = Column("sampling_weight")
def __init__(self, builder: BaseQueryBuilder):
super().__init__(builder)
self._cached_count_and_weighted: tuple[float, float] | None = None
def _resolve_span_duration(self, alias: str) -> SelectType:
# In ClickHouse, duration is an UInt32 whereas self time is a Float64.
# This creates a situation where a sub-millisecond duration is truncated
# to but the self time is not.
#
# To remedy this, we take the greater of the duration and self time as
# this is the only situation where the self time can be greater than
# the duration.
#
# Also avoids strange situations on the frontend where duration is less
# than the self time.
duration = Column("duration_ms")
self_time = self.builder.column("span.self_time")
return Function(
"if",
[
Function("greater", [self_time, duration]),
self_time,
duration,
],
alias,
)
def _resolve_aggregate_if(
self, aggregate: str
) -> Callable[[Mapping[str, str | SelectType | int | float], str | None], SelectType]:
def resolve_aggregate_if(
args: Mapping[str, str | SelectType | int | float],
alias: str | None = None,
) -> SelectType:
attr = extract_attr(args["column"])
# If we're not aggregating on an attr column,
# we can directly aggregate on the column
if attr is None:
return Function(
f"{aggregate}",
[args["column"]],
alias,
)
# When aggregating on an attr column, we have to make sure that we skip rows
# where the attr does not exist.
attr_col, attr_name = attr
function = (
aggregate.replace("quantile", "quantileTDigestIf")
if aggregate.startswith("quantile(")
else f"{aggregate}If"
)
return Function(
function,
[
args["column"],
Function("mapContains", [attr_col, attr_name]),
],
alias,
)
return resolve_aggregate_if
@property
def function_converter(self) -> dict[str, SnQLFunction]:
function_converter = {
function.name: function
for function in [
SnQLFunction(
"eps",
snql_aggregate=lambda args, alias: function_aliases.resolve_eps(
args, alias, self.builder
),
optional_args=[IntervalDefault("interval", 1, None)],
default_result_type="rate",
),
SnQLFunction(
"epm",
snql_aggregate=lambda args, alias: function_aliases.resolve_epm(
args, alias, self.builder
),
optional_args=[IntervalDefault("interval", 1, None)],
default_result_type="rate",
),
SnQLFunction(
"count_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("count"),
default_result_type="integer",
),
SnQLFunction(
"count_unique",
required_args=[ColumnTagArg("column")],
snql_aggregate=self._resolve_aggregate_if("uniq"),
default_result_type="integer",
),
SnQLFunction(
"sum_sample",
required_args=[NumericColumn("column", spans=True)],
snql_aggregate=self._resolve_aggregate_if("sum"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
),
SnQLFunction(
"avg_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("avg"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p50_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("quantile(0.5)"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p75_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("quantile(0.75)"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p90_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("quantile(0.90)"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p95_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("quantile(0.95)"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p99_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("quantile(0.99)"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p100_sample",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("max"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"min",
required_args=[NumericColumn("column", spans=True)],
snql_aggregate=self._resolve_aggregate_if("min"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"max",
required_args=[NumericColumn("column", spans=True)],
snql_aggregate=self._resolve_aggregate_if("max"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"count",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_count_weighted,
default_result_type="integer",
),
SnQLFunction(
"sum",
required_args=[NumericColumn("column", spans=True)],
result_type_fn=self.reflective_result_type(),
snql_aggregate=lambda args, alias: self._resolve_sum_weighted(args, alias),
default_result_type="duration",
),
SnQLFunction(
"avg",
required_args=[NumericColumn("column", spans=True)],
result_type_fn=self.reflective_result_type(),
snql_aggregate=lambda args, alias: Function(
"divide",
[
self._resolve_sum_weighted(args),
self._resolve_count_weighted(args),
],
alias,
),
default_result_type="duration",
),
SnQLFunction(
"percentile",
required_args=[
NumericColumn("column", spans=True),
NumberRange("percentile", 0, 1),
],
snql_aggregate=self._resolve_percentile_weighted,
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p50",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=lambda args, alias: self._resolve_percentile_weighted(
args, alias, 0.5
),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p75",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=lambda args, alias: self._resolve_percentile_weighted(
args, alias, 0.75
),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p90",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=lambda args, alias: self._resolve_percentile_weighted(
args, alias, 0.90
),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p95",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=lambda args, alias: self._resolve_percentile_weighted(
args, alias, 0.95
),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p99",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=lambda args, alias: self._resolve_percentile_weighted(
args, alias, 0.99
),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"p100",
optional_args=[
with_default("span.duration", NumericColumn("column", spans=True)),
],
snql_aggregate=self._resolve_aggregate_if("max"),
result_type_fn=self.reflective_result_type(),
default_result_type="duration",
redundant_grouping=True,
),
SnQLFunction(
"margin_of_error",
optional_args=[with_default("fpc", SnQLStringArg("fpc"))],
snql_aggregate=self._resolve_margin_of_error,
default_result_type="number",
),
SnQLFunction(
"lower_count_limit",
optional_args=[with_default("fpc", SnQLStringArg("fpc"))],
snql_aggregate=self._resolve_lower_limit,
default_result_type="number",
),
SnQLFunction(
"upper_count_limit",
optional_args=[with_default("fpc", SnQLStringArg("fpc"))],
snql_aggregate=self._resolve_upper_limit,
default_result_type="number",
),
SnQLFunction(
"first_seen",
snql_aggregate=lambda args, alias: Function(
"toUnixTimestamp64Milli",
[Function("min", [Column("start_timestamp")])],
alias,
),
default_result_type="duration",
private=True,
),
SnQLFunction(
"last_seen",
snql_aggregate=lambda args, alias: Function(
"toUnixTimestamp64Milli",
[Function("max", [Column("end_timestamp")])],
alias,
),
default_result_type="duration",
private=True,
),
]
}
for alias, name in constants.SPAN_FUNCTION_ALIASES.items():
if name in function_converter:
function_converter[alias] = function_converter[name].alias_as(alias)
return function_converter
@property
def field_alias_converter(self) -> Mapping[str, Callable[[str], SelectType]]:
existing_field_aliases: dict[str, Callable[[str], SelectType]] = {
**super().field_alias_converter
}
field_alias_converter: Mapping[str, Callable[[str], SelectType]] = {
constants.PRECISE_START_TS: lambda alias: Function(
"divide",
[
Function("toUnixTimestamp64Milli", [Column("start_timestamp")]),
1000,
],
alias,
),
constants.PRECISE_FINISH_TS: lambda alias: Function(
"divide",
[
Function("toUnixTimestamp64Milli", [Column("end_timestamp")]),
1000,
],
alias,
),
}
existing_field_aliases.update(field_alias_converter)
return existing_field_aliases
@property
def search_filter_converter(
self,
) -> dict[str, Callable[[SearchFilter], WhereType | None]]:
existing_search_filters = super().search_filter_converter
del existing_search_filters[constants.SPAN_STATUS]
return existing_search_filters
def _resolve_sum_weighted(
self,
args: Mapping[str, str | SelectType | int | float],
alias: str | None = None,
) -> SelectType:
attr = extract_attr(args["column"])
# If we're not aggregating on an attr column,
# we can directly aggregate on the column
if attr is None:
return Function(
"sum",
[
Function(
"multiply",
[
Column("sign"),
Function("multiply", [args["column"], self.sampling_weight]),
],
)
],
alias,
)
# When aggregating on an attr column, we have to make sure that we skip rows
# where the attr does not exist.
attr_col, attr_name = attr
return Function(
"sumIf",
[
Function(
"multiply",
[
Column("sign"),
Function("multiply", [args["column"], self.sampling_weight]),
],
),
Function("mapContains", [attr_col, attr_name]),
],
alias,
)
def _resolve_count_weighted(
self,
args: Mapping[str, str | SelectType | int | float],
alias: str | None = None,
) -> SelectType:
attr = extract_attr(args["column"])
# If we're not aggregating on an attr column,
# we can directly aggregate on the column
if attr is None:
return Function(
"round",
[
Function(
"sum",
[Function("multiply", [Column("sign"), self.sampling_weight])],
)
],
alias,
)
# When aggregating on an attr column, we have to make sure that we skip rows
# where the attr does not exist.
attr_col, attr_name = attr
return Function(
"round",
[
Function(
"sumIf",
[
Function("multiply", [Column("sign"), self.sampling_weight]),
Function("mapContains", [attr_col, attr_name]),
],
)
],
alias,
)
def _resolve_percentile_weighted(
self,
args: Mapping[str, str | SelectType | int | float],
alias: str,
fixed_percentile: float | None = None,
) -> SelectType:
attr = extract_attr(args["column"])
# If we're not aggregating on an attr column,
# we can directly aggregate on the column
if attr is None:
return Function(
f'quantileTDigestWeighted({fixed_percentile if fixed_percentile is not None else args["percentile"]})',
# Only convert to UInt64 when we have to since we lose rounding accuracy
[args["column"], Function("toUInt64", [self.sampling_weight])],
alias,
)
# When aggregating on an attr column, we have to make sure that we skip rows
# where the attr does not exist.
attr_col, attr_name = attr
return Function(
f'quantileTDigestWeightedIf({fixed_percentile if fixed_percentile is not None else args["percentile"]})',
# Only convert to UInt64 when we have to since we lose rounding accuracy
[
args["column"],
Function("toUInt64", [self.sampling_weight]),
Function("mapContains", [attr_col, attr_name]),
],
alias,
)
def _query_total_counts(self) -> tuple[float, float]:
if self._cached_count_and_weighted is None:
total_query = spans_indexed.SpansEAPQueryBuilder(
dataset=self.builder.dataset,
params={},
snuba_params=self.builder.params,
selected_columns=["count_sample()", "count()"],
)
total_results = total_query.run_query(Referrer.API_SPANS_TOTAL_COUNT_FIELD.value)
results = total_query.process_results(total_results)
if len(results["data"]) != 1:
raise Exception("Could not query population size")
self._cached_count_and_weighted = (
results["data"][0]["count_sample"],
results["data"][0]["count"],
)
return self._cached_count_and_weighted
@cached_property
def _zscore(self) -> float | int:
"""Defaults to 1.96, based on a z score for a confidence level of 95%"""
return options.get("performance.extrapolation.confidence.z-score")
def _resolve_margin_of_error(
self,
args: Mapping[str, str | SelectType | int | float],
alias: str | None = None,
) -> SelectType:
"""Calculates the Margin of error for a given value, but unfortunately basis the total count based on
extrapolated data
Z * Margin Of Error * Finite Population Correction
"""
# both of these need to be aggregated without a query
total_samples, population_size = self._query_total_counts()
sampled_group = Function("count", [])
return Function(
"multiply",
[
self._zscore,
Function(
"multiply",
[
# Unadjusted Margin of Error
self._resolve_unadjusted_margin(sampled_group, total_samples),
# Finite Population Correction
self._resolve_finite_population_correction(
args, total_samples, population_size
),
],
),
],
alias,
)
def _resolve_unadjusted_margin(
self, sampled_group: SelectType, total_samples: SelectType
) -> SelectType:
"""sqrt((p(1 - p)) / (total_samples))"""
# Naming this p to match the formula
p = Function("divide", [sampled_group, total_samples])
return Function(
"sqrt",
[
Function(
"divide", [Function("multiply", [p, Function("minus", [1, p])]), total_samples]
)
],
)
def _resolve_finite_population_correction(
self,
args: Mapping[str, str | SelectType | int | float],
total_samples: SelectType,
population_size: int | float,
) -> SelectType:
"""sqrt((population_size - total_samples) / (population_size - 1))"""
return (
Function(
"sqrt",
[
Function(
"divide",
[
Function("minus", [population_size, total_samples]),
Function("minus", [population_size, 1]),
],
)
],
)
# if the arg is anything but `fpc` just return 1 so we're not correcting for a finite population
if args["fpc"] == "fpc"
else 1
)
def _resolve_lower_limit(
self,
args: Mapping[str, str | SelectType | int | float],
alias: str,
) -> SelectType:
"""round(max(0, proportion_by_sample - margin_of_error) * total_population)"""
_, total_population = self._query_total_counts()
sampled_group = Function("count", [])
proportion_by_sample = Function(
"divide",
[
sampled_group,
Function(
"multiply", [total_population, Function("avg", [Column("sampling_factor")])]
),
],
"proportion_by_sample",
)
return Function(
"round",
[
Function(
"multiply",
[
Function(
"arrayMax",
[
[
0,
Function(
"minus",
[
proportion_by_sample,
self._resolve_margin_of_error(args, "margin_of_error"),
],
),
]
],
),
total_population,
],
)
],
alias,
)
def _resolve_upper_limit(
self,
args: Mapping[str, str | SelectType | int | float],
alias: str,
) -> SelectType:
"""round(max(0, proportion_by_sample + margin_of_error) * total_population)"""
_, total_population = self._query_total_counts()
sampled_group = Function("count", [])
proportion_by_sample = Function(
"divide",
[
sampled_group,
Function(
"multiply", [total_population, Function("avg", [Column("sampling_factor")])]
),
],
"proportion_by_sample",
)
return Function(
"round",
[
Function(
"multiply",
[
Function(
"plus",
[
proportion_by_sample,
self._resolve_margin_of_error(args, "margin_of_error"),
],
),
total_population,
],
)
],
alias,
)
def extract_attr(
column: str | SelectType | int | float,
) -> tuple[Column, str] | None:
if isinstance(column, Column) and column.subscriptable in {"attr_str", "attr_num"}:
return Column(column.subscriptable), column.key
return None
| SpansEAPDatasetConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink49.py | {
"start": 315,
"end": 975
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink49.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.write_url("A1", "https://github.com/jmcnamara")
worksheet.insert_image(
"E9", self.image_dir + "red.png", {"url": "https://github.com/jmcnamara"}
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2.py | {
"start": 102744,
"end": 114905
} | class ____(
DenseColumn,
SequenceDenseColumn,
fc_old._DenseColumn, # pylint: disable=protected-access
fc_old._SequenceDenseColumn, # pylint: disable=protected-access
collections.namedtuple(
'EmbeddingColumn',
('categorical_column', 'dimension', 'combiner', 'initializer',
'ckpt_to_load_from', 'tensor_name_in_ckpt', 'max_norm', 'trainable',
'use_safe_embedding_lookup'))):
"""See `embedding_column`."""
def __new__(cls,
categorical_column,
dimension,
combiner,
initializer,
ckpt_to_load_from,
tensor_name_in_ckpt,
max_norm,
trainable,
use_safe_embedding_lookup=True):
return super(EmbeddingColumn, cls).__new__(
cls,
categorical_column=categorical_column,
dimension=dimension,
combiner=combiner,
initializer=initializer,
ckpt_to_load_from=ckpt_to_load_from,
tensor_name_in_ckpt=tensor_name_in_ckpt,
max_norm=max_norm,
trainable=trainable,
use_safe_embedding_lookup=use_safe_embedding_lookup)
@property
def _is_v2_column(self):
return (
isinstance(self.categorical_column, fc_types.FeatureColumn)
and self.categorical_column._is_v2_column
) # pylint: disable=protected-access
@property
def name(self):
"""See `FeatureColumn` base class."""
return '{}_embedding'.format(self.categorical_column.name)
@property
def parse_example_spec(self):
"""See `FeatureColumn` base class."""
return self.categorical_column.parse_example_spec
@property
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _parse_example_spec(self):
return self.categorical_column._parse_example_spec # pylint: disable=protected-access
def transform_feature(self, transformation_cache, state_manager):
"""Transforms underlying `categorical_column`."""
return transformation_cache.get(self.categorical_column, state_manager)
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _transform_feature(self, inputs):
return inputs.get(self.categorical_column)
@property
def variable_shape(self):
"""See `DenseColumn` base class."""
return tensor_shape.TensorShape([self.dimension])
@property
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _variable_shape(self):
return self.variable_shape
def create_state(self, state_manager):
"""Creates the embedding lookup variable."""
default_num_buckets = (
self.categorical_column.num_buckets
if self._is_v2_column else self.categorical_column._num_buckets) # pylint: disable=protected-access
num_buckets = getattr(self.categorical_column, 'num_buckets',
default_num_buckets)
embedding_shape = (num_buckets, self.dimension)
state_manager.create_variable(
self,
name='embedding_weights',
shape=embedding_shape,
dtype=dtypes.float32,
trainable=self.trainable,
use_resource=True,
initializer=self.initializer)
def _get_dense_tensor_internal_helper(self, sparse_tensors,
embedding_weights):
sparse_ids = sparse_tensors.id_tensor
sparse_weights = sparse_tensors.weight_tensor
if self.ckpt_to_load_from is not None:
to_restore = embedding_weights
if isinstance(to_restore, variables.PartitionedVariable):
to_restore = to_restore._get_variable_list() # pylint: disable=protected-access
checkpoint_utils.init_from_checkpoint(
self.ckpt_to_load_from, {self.tensor_name_in_ckpt: to_restore})
sparse_id_rank = tensor_shape.dimension_value(
sparse_ids.dense_shape.get_shape()[0])
embedding_lookup_sparse = embedding_ops.safe_embedding_lookup_sparse
if (not self.use_safe_embedding_lookup and sparse_id_rank is not None and
sparse_id_rank <= 2):
embedding_lookup_sparse = embedding_ops.embedding_lookup_sparse_v2
# Return embedding lookup result.
return embedding_lookup_sparse(
embedding_weights,
sparse_ids,
sparse_weights,
combiner=self.combiner,
name='%s_weights' % self.name,
max_norm=self.max_norm)
def _get_dense_tensor_internal(self, sparse_tensors, state_manager):
"""Private method that follows the signature of get_dense_tensor."""
embedding_weights = state_manager.get_variable(
self, name='embedding_weights')
return self._get_dense_tensor_internal_helper(sparse_tensors,
embedding_weights)
def _old_get_dense_tensor_internal(self, sparse_tensors, weight_collections,
trainable):
"""Private method that follows the signature of _get_dense_tensor."""
embedding_shape = (self.categorical_column._num_buckets, self.dimension) # pylint: disable=protected-access
if (weight_collections and
ops.GraphKeys.GLOBAL_VARIABLES not in weight_collections):
weight_collections.append(ops.GraphKeys.GLOBAL_VARIABLES)
embedding_weights = variable_scope.get_variable(
name='embedding_weights',
shape=embedding_shape,
dtype=dtypes.float32,
initializer=self.initializer,
trainable=self.trainable and trainable,
collections=weight_collections)
return self._get_dense_tensor_internal_helper(sparse_tensors,
embedding_weights)
def get_dense_tensor(self, transformation_cache, state_manager):
"""Returns tensor after doing the embedding lookup.
Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.
Returns:
Embedding lookup tensor.
Raises:
ValueError: `categorical_column` is SequenceCategoricalColumn.
"""
if isinstance(self.categorical_column, SequenceCategoricalColumn):
raise ValueError(
'In embedding_column: {}. '
'categorical_column must not be of type SequenceCategoricalColumn. '
'Suggested fix A: If you wish to use DenseFeatures, use a '
'non-sequence categorical_column_with_*. '
'Suggested fix B: If you wish to create sequence input, use '
'SequenceFeatures instead of DenseFeatures. '
'Given (type {}): {}'.format(self.name, type(self.categorical_column),
self.categorical_column))
# Get sparse IDs and weights.
sparse_tensors = self.categorical_column.get_sparse_tensors(
transformation_cache, state_manager)
return self._get_dense_tensor_internal(sparse_tensors, state_manager)
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None):
if isinstance(
self.categorical_column,
(SequenceCategoricalColumn, fc_old._SequenceCategoricalColumn)): # pylint: disable=protected-access
raise ValueError(
'In embedding_column: {}. '
'categorical_column must not be of type _SequenceCategoricalColumn. '
'Suggested fix A: If you wish to use DenseFeatures, use a '
'non-sequence categorical_column_with_*. '
'Suggested fix B: If you wish to create sequence input, use '
'SequenceFeatures instead of DenseFeatures. '
'Given (type {}): {}'.format(self.name, type(self.categorical_column),
self.categorical_column))
sparse_tensors = self.categorical_column._get_sparse_tensors( # pylint: disable=protected-access
inputs, weight_collections, trainable)
return self._old_get_dense_tensor_internal(sparse_tensors,
weight_collections, trainable)
def get_sequence_dense_tensor(self, transformation_cache, state_manager):
"""See `SequenceDenseColumn` base class."""
if not isinstance(self.categorical_column, SequenceCategoricalColumn):
raise ValueError(
'In embedding_column: {}. '
'categorical_column must be of type SequenceCategoricalColumn '
'to use SequenceFeatures. '
'Suggested fix: Use one of sequence_categorical_column_with_*. '
'Given (type {}): {}'.format(self.name, type(self.categorical_column),
self.categorical_column))
sparse_tensors = self.categorical_column.get_sparse_tensors(
transformation_cache, state_manager)
dense_tensor = self._get_dense_tensor_internal(sparse_tensors,
state_manager)
sequence_length = fc_utils.sequence_length_from_sparse_tensor(
sparse_tensors.id_tensor)
return SequenceDenseColumn.TensorSequenceLengthPair(
dense_tensor=dense_tensor, sequence_length=sequence_length)
@deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE,
_FEATURE_COLUMN_DEPRECATION)
def _get_sequence_dense_tensor(self,
inputs,
weight_collections=None,
trainable=None):
if not isinstance(
self.categorical_column,
(SequenceCategoricalColumn, fc_old._SequenceCategoricalColumn)): # pylint: disable=protected-access
raise ValueError(
'In embedding_column: {}. '
'categorical_column must be of type SequenceCategoricalColumn '
'to use SequenceFeatures. '
'Suggested fix: Use one of sequence_categorical_column_with_*. '
'Given (type {}): {}'.format(self.name, type(self.categorical_column),
self.categorical_column))
sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access
dense_tensor = self._old_get_dense_tensor_internal(
sparse_tensors,
weight_collections=weight_collections,
trainable=trainable)
sequence_length = fc_utils.sequence_length_from_sparse_tensor(
sparse_tensors.id_tensor)
return SequenceDenseColumn.TensorSequenceLengthPair(
dense_tensor=dense_tensor, sequence_length=sequence_length)
@property
def parents(self):
"""See 'FeatureColumn` base class."""
return [self.categorical_column]
def get_config(self):
"""See 'FeatureColumn` base class."""
config = dict(zip(self._fields, self))
config['categorical_column'] = serialization.serialize_feature_column(
self.categorical_column)
config['initializer'] = serialization._serialize_keras_object( # pylint: disable=protected-access
self.initializer)
return config
@classmethod
def from_config(cls, config, custom_objects=None, columns_by_name=None):
"""See 'FeatureColumn` base class."""
if 'use_safe_embedding_lookup' not in config:
config['use_safe_embedding_lookup'] = True
_check_config_keys(config, cls._fields)
kwargs = _standardize_and_copy_config(config)
kwargs['categorical_column'] = serialization.deserialize_feature_column(
config['categorical_column'], custom_objects, columns_by_name)
all_initializers = dict(tf_inspect.getmembers(init_ops, tf_inspect.isclass))
kwargs['initializer'] = serialization._deserialize_keras_object( # pylint: disable=protected-access
config['initializer'],
module_objects=all_initializers,
custom_objects=custom_objects)
return cls(**kwargs)
def _raise_shared_embedding_column_error():
raise ValueError('SharedEmbeddingColumns are not supported in '
'`linear_model` or `input_layer`. Please use '
'`DenseFeatures` or `LinearModel` instead.')
| EmbeddingColumn |
python | milvus-io__pymilvus | pymilvus/bulk_writer/stage_manager.py | {
"start": 183,
"end": 1464
} | class ____:
def __init__(self, cloud_endpoint: str, api_key: str):
"""
private preview feature. Please submit a request and contact us if you need it.
Args:
cloud_endpoint (str): The fixed cloud endpoint URL.
- For international regions: https://api.cloud.zilliz.com
- For regions in China: https://api.cloud.zilliz.com.cn
api_key (str): The API key associated with your organization or cluster.
"""
self.cloud_endpoint = cloud_endpoint
self.api_key = api_key
def create_stage(self, project_id: str, region_id: str, stage_name: str):
"""
Create a stage under the specified project and regionId.
"""
create_stage(self.cloud_endpoint, self.api_key, project_id, region_id, stage_name)
def delete_stage(self, stage_name: str):
"""
Delete a stage.
"""
delete_stage(self.cloud_endpoint, self.api_key, stage_name)
def list_stages(self, project_id: str, current_page: int = 1, page_size: int = 10):
"""
Paginated query of the stage list under a specified projectId.
"""
return list_stages(self.cloud_endpoint, self.api_key, project_id, current_page, page_size)
| StageManager |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 26192,
"end": 43732
} | class ____(GoogleCloudBaseOperator):
"""
Create a new cluster on Google Cloud Dataproc.
The operator will wait until the creation is successful or an error occurs
in the creation process.
If the cluster already exists and ``use_if_exists`` is True, then the operator will:
- if cluster state is ERROR then delete it if specified and raise error
- if cluster state is CREATING wait for it and then check for ERROR state
- if cluster state is DELETING wait for it and then create new cluster
Please refer to
https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.clusters
for a detailed explanation on the different parameters. Most of the configuration
parameters detailed in the link are available as a parameter to this operator.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataprocCreateClusterOperator`
:param project_id: The ID of the Google cloud project in which
to create the cluster. (templated)
:param cluster_name: Name of the cluster to create
:param labels: Labels that will be assigned to created cluster. Please, notice that
adding labels to ClusterConfig object in cluster_config parameter will not lead
to adding labels to the cluster. Labels for the clusters could be only set by passing
values to parameter of DataprocCreateCluster operator.
:param cluster_config: Required. The cluster config to create.
If a dict is provided, it must be of the same form as the protobuf message
:class:`~google.cloud.dataproc_v1.types.ClusterConfig`
:param virtual_cluster_config: Optional. The virtual cluster config, used when creating a Dataproc
cluster that does not directly control the underlying compute resources, for example, when creating a
`Dataproc-on-GKE cluster
<https://cloud.google.com/dataproc/docs/concepts/jobs/dataproc-gke#create-a-dataproc-on-gke-cluster>`
:param region: The specified region where the dataproc cluster is created.
:param delete_on_error: If true the cluster will be deleted if created with ERROR state. Default
value is true.
:param use_if_exists: If true use existing cluster
:param num_retries_if_resource_is_not_ready: Optional. The number of retry for cluster creation request
when resource is not ready error appears.
:param request_id: Optional. A unique id used to identify the request. If the server receives two
``DeleteClusterRequest`` requests with the same id, then the second request will be ignored and the
first ``google.longrunning.Operation`` created and stored in the backend is returned.
:param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
``retry`` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:param deferrable: Run operator in the deferrable mode.
:param polling_interval_seconds: Time (seconds) to wait between calls to check the run status.
"""
template_fields: Sequence[str] = (
"project_id",
"region",
"cluster_config",
"virtual_cluster_config",
"cluster_name",
"labels",
"gcp_conn_id",
"impersonation_chain",
)
template_fields_renderers = {"cluster_config": "json", "virtual_cluster_config": "json"}
operator_extra_links = (DataprocClusterLink(),)
def __init__(
self,
*,
cluster_name: str,
region: str,
project_id: str = PROVIDE_PROJECT_ID,
cluster_config: dict | Cluster | None = None,
virtual_cluster_config: dict | None = None,
labels: dict | None = None,
request_id: str | None = None,
delete_on_error: bool = True,
use_if_exists: bool = True,
num_retries_if_resource_is_not_ready: int = 0,
retry: AsyncRetry | _MethodDefault | Retry = DEFAULT,
timeout: float = 1 * 60 * 60,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
polling_interval_seconds: int = 10,
**kwargs,
) -> None:
# TODO: remove one day
if cluster_config is None and virtual_cluster_config is None:
warnings.warn(
f"Passing cluster parameters by keywords to `{type(self).__name__}` will be deprecated. "
"Please provide cluster_config object using `cluster_config` parameter. "
"You can use `airflow.dataproc.ClusterGenerator.generate_cluster` "
"method to obtain cluster object.",
AirflowProviderDeprecationWarning,
stacklevel=2,
)
# Remove result of apply defaults
if "params" in kwargs:
del kwargs["params"]
# Create cluster object from kwargs
if project_id is None:
raise AirflowException(
"project_id argument is required when building cluster from keywords parameters"
)
kwargs["project_id"] = project_id
cluster_config = ClusterGenerator(**kwargs).make()
# Remove from kwargs cluster params passed for backward compatibility
cluster_params = inspect.signature(ClusterGenerator.__init__).parameters
for arg in cluster_params:
if arg in kwargs:
del kwargs[arg]
super().__init__(**kwargs)
if deferrable and polling_interval_seconds <= 0:
raise ValueError("Invalid value for polling_interval_seconds. Expected value greater than 0")
self.cluster_config = cluster_config
self.cluster_name = cluster_name
self.labels = labels
self.project_id = project_id
self.region = region
self.request_id = request_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.delete_on_error = delete_on_error
self.use_if_exists = use_if_exists
self.impersonation_chain = impersonation_chain
self.virtual_cluster_config = virtual_cluster_config
self.deferrable = deferrable
self.polling_interval_seconds = polling_interval_seconds
self.num_retries_if_resource_is_not_ready = num_retries_if_resource_is_not_ready
def _create_cluster(self, hook: DataprocHook):
return hook.create_cluster(
project_id=self.project_id,
region=self.region,
cluster_name=self.cluster_name,
labels=self.labels,
cluster_config=self.cluster_config,
virtual_cluster_config=self.virtual_cluster_config,
request_id=self.request_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
def _delete_cluster(self, hook):
self.log.info("Deleting the cluster")
hook.delete_cluster(region=self.region, cluster_name=self.cluster_name, project_id=self.project_id)
def _get_cluster(self, hook: DataprocHook) -> Cluster:
return hook.get_cluster(
project_id=self.project_id,
region=self.region,
cluster_name=self.cluster_name,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
def _handle_error_state(self, hook: DataprocHook, cluster: Cluster) -> None:
if cluster.status.state != cluster.status.State.ERROR:
return
self.log.info("Cluster is in ERROR state")
self.log.info("Gathering diagnostic information.")
try:
operation = hook.diagnose_cluster(
region=self.region, cluster_name=self.cluster_name, project_id=self.project_id
)
operation.result()
gcs_uri = str(operation.operation.response.value)
self.log.info(
"Diagnostic information for cluster %s available at: %s", self.cluster_name, gcs_uri
)
except Exception as diagnose_error:
self.log.info("Some error occurred when trying to diagnose cluster.")
self.log.exception(diagnose_error)
finally:
if self.delete_on_error:
self._delete_cluster(hook)
# The delete op is asynchronous and can cause further failure if the cluster finishes
# deleting between catching AlreadyExists and checking state
self._wait_for_cluster_in_deleting_state(hook)
raise AirflowException("Cluster was created in an ERROR state then deleted.")
raise AirflowException("Cluster was created but is in ERROR state")
def _wait_for_cluster_in_deleting_state(self, hook: DataprocHook) -> None:
time_left = self.timeout
for time_to_sleep in exponential_sleep_generator(initial=10, maximum=120):
if time_left < 0:
raise AirflowException(f"Cluster {self.cluster_name} is still DELETING state, aborting")
time.sleep(time_to_sleep)
time_left -= time_to_sleep
try:
self._get_cluster(hook)
except NotFound:
break
def _wait_for_cluster_in_creating_state(self, hook: DataprocHook) -> Cluster:
time_left = self.timeout
cluster = self._get_cluster(hook)
for time_to_sleep in exponential_sleep_generator(initial=10, maximum=120):
if cluster.status.state != cluster.status.State.CREATING:
break
if time_left < 0:
raise AirflowException(f"Cluster {self.cluster_name} is still CREATING state, aborting")
time.sleep(time_to_sleep)
time_left -= time_to_sleep
cluster = self._get_cluster(hook)
return cluster
def _start_cluster(self, hook: DataprocHook):
op: operation.Operation = hook.start_cluster(
region=self.region,
project_id=self.project_id,
cluster_name=self.cluster_name,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
return hook.wait_for_operation(timeout=self.timeout, result_retry=self.retry, operation=op)
def _retry_cluster_creation(self, hook: DataprocHook):
self.log.info("Retrying creation process for Cluster %s", self.cluster_name)
self._delete_cluster(hook)
self._wait_for_cluster_in_deleting_state(hook)
self.log.info("Starting a new creation for Cluster %s", self.cluster_name)
operation = self._create_cluster(hook)
cluster = hook.wait_for_operation(timeout=self.timeout, result_retry=self.retry, operation=operation)
self.log.info("Cluster created.")
return Cluster.to_dict(cluster)
def execute(self, context: Context) -> dict:
self.log.info("Creating cluster: %s", self.cluster_name)
hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain)
# Save data required to display extra link no matter what the cluster status will be
project_id = self.project_id or hook.project_id
if project_id:
DataprocClusterLink.persist(
context=context,
cluster_id=self.cluster_name,
project_id=project_id,
region=self.region,
)
try:
# First try to create a new cluster
operation = self._create_cluster(hook)
if not self.deferrable and type(operation) is not str:
cluster = hook.wait_for_operation(
timeout=self.timeout, result_retry=self.retry, operation=operation
)
self.log.info("Cluster created.")
return Cluster.to_dict(cluster)
cluster = hook.get_cluster(
project_id=self.project_id, region=self.region, cluster_name=self.cluster_name
)
if cluster.status.state == cluster.status.State.RUNNING:
self.log.info("Cluster created.")
return Cluster.to_dict(cluster)
self.defer(
trigger=DataprocClusterTrigger(
cluster_name=self.cluster_name,
project_id=self.project_id,
region=self.region,
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
polling_interval_seconds=self.polling_interval_seconds,
delete_on_error=self.delete_on_error,
),
method_name="execute_complete",
)
except AlreadyExists:
if not self.use_if_exists:
raise
self.log.info("Cluster already exists.")
cluster = self._get_cluster(hook)
except DataprocResourceIsNotReadyError as resource_not_ready_error:
if self.num_retries_if_resource_is_not_ready:
attempt = self.num_retries_if_resource_is_not_ready
while attempt > 0:
attempt -= 1
try:
cluster = self._retry_cluster_creation(hook)
except DataprocResourceIsNotReadyError:
continue
else:
return cluster
self.log.info(
"Retrying Cluster %s creation because of resource not ready was unsuccessful.",
self.cluster_name,
)
if self.delete_on_error:
self._delete_cluster(hook)
self._wait_for_cluster_in_deleting_state(hook)
raise resource_not_ready_error
except AirflowException as ae:
# There still could be a cluster created here in an ERROR state which
# should be deleted immediately rather than consuming another retry attempt
# (assuming delete_on_error is true (default))
# This reduces overall the number of task attempts from 3 to 2 to successful cluster creation
# assuming the underlying GCE issues have resolved within that window. Users can configure
# a higher number of retry attempts in powers of two with 30s-60s wait interval
try:
cluster = self._get_cluster(hook)
self._handle_error_state(hook, cluster)
except AirflowException as ae_inner:
# We could get any number of failures here, including cluster not found and we
# can just ignore to ensure we surface the original cluster create failure
self.log.exception(ae_inner)
finally:
raise ae
# Check if cluster is not in ERROR state
self._handle_error_state(hook, cluster)
if cluster.status.state == cluster.status.State.CREATING:
# Wait for cluster to be created
cluster = self._wait_for_cluster_in_creating_state(hook)
self._handle_error_state(hook, cluster)
elif cluster.status.state == cluster.status.State.DELETING:
# Wait for cluster to be deleted
self._wait_for_cluster_in_deleting_state(hook)
# Create new cluster
cluster = self._create_cluster(hook)
self._handle_error_state(hook, cluster)
elif cluster.status.state == cluster.status.State.STOPPED:
# if the cluster exists and already stopped, then start the cluster
self._start_cluster(hook)
return Cluster.to_dict(cluster)
def execute_complete(self, context: Context, event: dict[str, Any]) -> Any:
"""
Act as a callback for when the trigger fires - returns immediately.
Relies on trigger to throw an exception, otherwise it assumes execution was successful.
"""
cluster_state = event["cluster_state"]
cluster_name = event["cluster_name"]
if cluster_state == ClusterStatus.State(ClusterStatus.State.DELETING).name:
raise AirflowException(f"Cluster is in ERROR state:\n{cluster_name}")
self.log.info("%s completed successfully.", self.task_id)
return event["cluster"]
| DataprocCreateClusterOperator |
python | tensorflow__tensorflow | tensorflow/python/data/ops/options.py | {
"start": 5612,
"end": 6891
} | class ____(enum.Enum):
"""Represents how to handle external state during serialization.
See the `tf.data.Options.experimental_external_state_policy` documentation
for more information.
"""
WARN = 0
IGNORE = 1
FAIL = 2
@classmethod
def _to_proto(cls, obj):
"""Convert enum to proto."""
if obj == cls.IGNORE:
return dataset_options_pb2.ExternalStatePolicy.POLICY_IGNORE
if obj == cls.FAIL:
return dataset_options_pb2.ExternalStatePolicy.POLICY_FAIL
if obj == cls.WARN:
return dataset_options_pb2.ExternalStatePolicy.POLICY_WARN
raise ValueError(
f"Invalid `obj.` Supported values include `POLICY_IGNORE`,"
f"`POLICY_FAIL`, `POLICY_WARN`. Got {obj.name}.")
@classmethod
def _from_proto(cls, pb):
"""Convert proto to enum."""
if pb == dataset_options_pb2.ExternalStatePolicy.POLICY_IGNORE:
return cls.IGNORE
if pb == dataset_options_pb2.ExternalStatePolicy.POLICY_FAIL:
return cls.FAIL
if pb == dataset_options_pb2.ExternalStatePolicy.POLICY_WARN:
return cls.WARN
raise ValueError(
f"Invalid `pb.` Supported values include `POLICY_IGNORE`,"
f"`POLICY_FAIL`, `POLICY_WARN`. Got {pb}.")
@tf_export("data.experimental.AutotuneOptions")
| ExternalStatePolicy |
python | huggingface__transformers | src/transformers/models/hiera/configuration_hiera.py | {
"start": 882,
"end": 9319
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`HieraModel`]. It is used to instantiate a Hiera
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the Hiera
[facebook/hiera-base-224](https://huggingface.co/facebook/hiera-base-224) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
embed_dim (`int`, *optional*, defaults to 96):
Dimensionality of patch embedding.
image_size (`list(int)`, *optional*, defaults to `[224, 224]`):
The size (resolution) of input in the format (height, width) for images
and (frames, height, width) for videos.
patch_size (`list(int)`, *optional*, defaults to `[7, 7]`):
The size (resolution) of each patch.
patch_stride (`list(int)`, *optional*, defaults to `[4, 4]`):
The stride of the patch.
patch_padding (`list(int)`, *optional*, defaults to `[3, 3]`):
The padding of the patch.
mlp_ratio (`float`, *optional*, defaults to 4.0):
The ratio of mlp hidden dim to embedding dim.
depths (`list(int)`, *optional*, defaults to `[2, 3, 16, 3]`):
Depth of each layer in the Transformer encoder.
num_heads (`list(int)`, *optional*, defaults to `[1, 2, 4, 8]`):
Number of attention heads in each layer of the Transformer encoder.
embed_dim_multiplier (`float`, *optional*, defaults to 2.0):
The multiplier to the dimensionality of patch embedding in each layer of the Transformer encoder.
num_query_pool (`int`, *optional*, defaults to 3):
The number of query pool stages.
query_stride (`list(int)`, *optional*, defaults to `[2, 2]`):
The stride of the query pool.
masked_unit_size (`list(int)`, *optional*, defaults to `[8, 8]`):
The size of the masked unit.
masked_unit_attention (`list(bool)`, *optional*, defaults to `[True, True, False, False]`):
Whether to use masked unit attention in each layer of the Transformer encoder.
drop_path_rate (`float`, *optional*, defaults to 0.0):
The drop path rate.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
hidden_act (`str`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
`"selu"` and `"gelu_new"` are supported.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices and
the zero_initializer for initializing all bias vectors.
layer_norm_init (`float`, *optional*, defaults to 1.0):
The initial weight value for layer normalization layers.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
decoder_hidden_size (`int`, *optional*):
Dimensionality of decoder embeddings for MAE pretraining.
decoder_depth (`int`, *optional*):
Depth of the decoder for MAE pretraining.
decoder_num_heads (`int`, *optional*):
Number of attention heads in each layer of the decoder for MAE pretraining.
normalize_pixel_loss (`bool`, *optional*, defaults to `True`):
Whether to normalize the pixel loss by the number of pixels.
mask_ratio (`float`, *optional*, defaults to 0.6):
The ratio of masked tokens in the input.
out_features (`list[str]`, *optional*):
If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
(depending on how many stages the model has). If unset and `out_indices` is set, will default to the
corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
out_indices (`list[int]`, *optional*):
If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
If unset and `out_features` is unset, will default to the last stage. Must be in the
same order as defined in the `stage_names` attribute.
Example:
```python
>>> from transformers import HieraConfig, HieraModel
>>> # Initializing a Hiera hiera-base-patch16-224 style configuration
>>> configuration = HieraConfig()
>>> # Initializing a model (with random weights) from the hiera-base-patch16-224 style configuration
>>> model = HieraModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "hiera"
attribute_map = {"num_hidden_layers": "num_layers"}
def __init__(
self,
embed_dim=96,
image_size=[224, 224],
patch_size=[7, 7],
patch_stride=[4, 4],
patch_padding=[3, 3],
mlp_ratio=4.0,
depths=[2, 3, 16, 3],
num_heads=[1, 2, 4, 8],
embed_dim_multiplier=2.0,
num_query_pool=3,
query_stride=[2, 2],
masked_unit_size=[8, 8],
masked_unit_attention=[True, True, False, False],
drop_path_rate=0.0,
num_channels=3,
hidden_act="gelu",
initializer_range=0.02,
layer_norm_init=1.0,
layer_norm_eps=1e-6,
decoder_hidden_size=None,
decoder_depth=None,
decoder_num_heads=None,
normalize_pixel_loss=True,
mask_ratio=0.6,
out_features=None,
out_indices=None,
**kwargs,
):
super().__init__(**kwargs)
if masked_unit_size[0] % query_stride[0] ** (len(depths) - 1) != 0:
raise ValueError(
f"masked_unit_size[0] ({masked_unit_size[0]}) must be divisible by query_stride[0] ({query_stride[0]}) "
f"raised to the power of the number of layers ({len(depths) - 1})"
)
if num_query_pool >= len(depths):
raise ValueError(
f"num_query_pool ({num_query_pool}) must be less than the number of layers ({len(depths)})"
)
self.embed_dim = embed_dim
self.image_size = image_size
self.patch_size = patch_size
self.patch_stride = patch_stride
self.patch_padding = patch_padding
self.mlp_ratio = mlp_ratio
self.depths = depths
self.num_heads = num_heads
self.num_layers = len(depths)
self.embed_dim_multiplier = embed_dim_multiplier
self.num_query_pool = num_query_pool
self.query_stride = query_stride
self.masked_unit_size = masked_unit_size
self.masked_unit_attention = masked_unit_attention
self.drop_path_rate = drop_path_rate
self.num_channels = num_channels
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.layer_norm_init = layer_norm_init
self.layer_norm_eps = layer_norm_eps
self.decoder_hidden_size = decoder_hidden_size
self.decoder_depth = decoder_depth
self.decoder_num_heads = decoder_num_heads
self.normalize_pixel_loss = normalize_pixel_loss
self.mask_ratio = mask_ratio
# we set the hidden_size attribute in order to make Hiera work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
self.hidden_size = int(embed_dim * embed_dim_multiplier ** (len(depths) - 1))
self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
self._out_features, self._out_indices = get_aligned_output_features_output_indices(
out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
)
__all__ = ["HieraConfig"]
| HieraConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-onedrive/source_microsoft_onedrive/spec.py | {
"start": 1376,
"end": 2574
} | class ____(BaseModel):
"""
ServiceCredentials class for service key authentication.
This class is structured similarly to OAuthCredentials but for a different authentication method.
"""
class Config:
title = "Service Key Authentication"
# Fields for the Service authentication, similar to OAuthCredentials
auth_type: Literal["Service"] = Field("Service", const=True)
tenant_id: str = Field(title="Tenant ID", description="Tenant ID of the Microsoft OneDrive user", airbyte_secret=True)
user_principal_name: str = Field(
title="User Principal Name",
description="Special characters such as a period, comma, space, and the at sign (@) are converted to underscores (_). More details: https://learn.microsoft.com/en-us/sharepoint/list-onedrive-urls",
airbyte_secret=True,
)
client_id: str = Field(
title="Client ID",
description="Client ID of your Microsoft developer application",
airbyte_secret=True,
)
client_secret: str = Field(
title="Client Secret",
description="Client Secret of your Microsoft developer application",
airbyte_secret=True,
)
| ServiceCredentials |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/req/req_file.py | {
"start": 2688,
"end": 9673
} | class ____:
def __init__(
self,
filename: str,
lineno: int,
args: str,
opts: Values,
constraint: bool,
) -> None:
self.filename = filename
self.lineno = lineno
self.opts = opts
self.constraint = constraint
if args:
self.is_requirement = True
self.is_editable = False
self.requirement = args
elif opts.editables:
self.is_requirement = True
self.is_editable = True
# We don't support multiple -e on one line
self.requirement = opts.editables[0]
else:
self.is_requirement = False
def parse_requirements(
filename: str,
session: "PipSession",
finder: Optional["PackageFinder"] = None,
options: Optional[optparse.Values] = None,
constraint: bool = False,
) -> Generator[ParsedRequirement, None, None]:
"""Parse a requirements file and yield ParsedRequirement instances.
:param filename: Path or url of requirements file.
:param session: PipSession instance.
:param finder: Instance of pip.index.PackageFinder.
:param options: cli options.
:param constraint: If true, parsing a constraint file rather than
requirements file.
"""
line_parser = get_line_parser(finder)
parser = RequirementsFileParser(session, line_parser)
for parsed_line in parser.parse(filename, constraint):
parsed_req = handle_line(
parsed_line, options=options, finder=finder, session=session
)
if parsed_req is not None:
yield parsed_req
def preprocess(content: str) -> ReqFileLines:
"""Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
"""
lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comments(lines_enum)
lines_enum = expand_env_variables(lines_enum)
return lines_enum
def handle_requirement_line(
line: ParsedLine,
options: Optional[optparse.Values] = None,
) -> ParsedRequirement:
# preserve for the nested code path
line_comes_from = "{} {} (line {})".format(
"-c" if line.constraint else "-r",
line.filename,
line.lineno,
)
assert line.is_requirement
# get the options that apply to requirements
if line.is_editable:
supported_dest = SUPPORTED_OPTIONS_EDITABLE_REQ_DEST
else:
supported_dest = SUPPORTED_OPTIONS_REQ_DEST
req_options = {}
for dest in supported_dest:
if dest in line.opts.__dict__ and line.opts.__dict__[dest]:
req_options[dest] = line.opts.__dict__[dest]
line_source = f"line {line.lineno} of {line.filename}"
return ParsedRequirement(
requirement=line.requirement,
is_editable=line.is_editable,
comes_from=line_comes_from,
constraint=line.constraint,
options=req_options,
line_source=line_source,
)
def handle_option_line(
opts: Values,
filename: str,
lineno: int,
finder: Optional["PackageFinder"] = None,
options: Optional[optparse.Values] = None,
session: Optional["PipSession"] = None,
) -> None:
if opts.hashes:
logger.warning(
"%s line %s has --hash but no requirement, and will be ignored.",
filename,
lineno,
)
if options:
# percolate options upward
if opts.require_hashes:
options.require_hashes = opts.require_hashes
if opts.features_enabled:
options.features_enabled.extend(
f for f in opts.features_enabled if f not in options.features_enabled
)
# set finder options
if finder:
find_links = finder.find_links
index_urls = finder.index_urls
no_index = finder.search_scope.no_index
if opts.no_index is True:
no_index = True
index_urls = []
if opts.index_url and not no_index:
index_urls = [opts.index_url]
if opts.extra_index_urls and not no_index:
index_urls.extend(opts.extra_index_urls)
if opts.find_links:
# FIXME: it would be nice to keep track of the source
# of the find_links: support a find-links local path
# relative to a requirements file.
value = opts.find_links[0]
req_dir = os.path.dirname(os.path.abspath(filename))
relative_to_reqs_file = os.path.join(req_dir, value)
if os.path.exists(relative_to_reqs_file):
value = relative_to_reqs_file
find_links.append(value)
if session:
# We need to update the auth urls in session
session.update_index_urls(index_urls)
search_scope = SearchScope(
find_links=find_links,
index_urls=index_urls,
no_index=no_index,
)
finder.search_scope = search_scope
if opts.pre:
finder.set_allow_all_prereleases()
if opts.prefer_binary:
finder.set_prefer_binary()
if session:
for host in opts.trusted_hosts or []:
source = f"line {lineno} of {filename}"
session.add_trusted_host(host, source=source)
def handle_line(
line: ParsedLine,
options: Optional[optparse.Values] = None,
finder: Optional["PackageFinder"] = None,
session: Optional["PipSession"] = None,
) -> Optional[ParsedRequirement]:
"""Handle a single parsed requirements line; This can result in
creating/yielding requirements, or updating the finder.
:param line: The parsed line to be processed.
:param options: CLI options.
:param finder: The finder - updated by non-requirement lines.
:param session: The session - updated by non-requirement lines.
Returns a ParsedRequirement object if the line is a requirement line,
otherwise returns None.
For lines that contain requirements, the only options that have an effect
are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
requirement. Other options from SUPPORTED_OPTIONS may be present, but are
ignored.
For lines that do not contain requirements, the only options that have an
effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
be present, but are ignored. These lines may contain multiple options
(although our docs imply only one is supported), and all our parsed and
affect the finder.
"""
if line.is_requirement:
parsed_req = handle_requirement_line(line, options)
return parsed_req
else:
handle_option_line(
line.opts,
line.filename,
line.lineno,
finder,
options,
session,
)
return None
| ParsedLine |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 129894,
"end": 145068
} | class ____(CppPythonBindingsCodeCache):
cache: dict[str, Callable[[], ModuleType | CDLL]] = {}
cache_clear = staticmethod(cache.clear)
_standalone_runtime_path: str | None = None
prefix = textwrap.dedent(
"""
#include "{halideruntime_h}"
#include "{headerfile}"
#include <stdexcept>
#include <cmath>
namespace c10 {{
inline long div_floor_integer(long a, long b) {{
if ((a<0) != (b<0)) {{
const auto quot = a / b;
const auto rem = a % b;
return rem ? quot - 1 : quot;
}}
return a / b;
}}
}}
"""
)
glue_template_cpp = prefix + textwrap.dedent(
"""
void kernel({argdefs}) {{
{buffers}
int err = halide_kernel({buffer_names});
if(err != 0) throw std::runtime_error("halide_kernel failed");
}}
"""
)
glue_template_cuda = prefix + textwrap.dedent(
"""
#include <cuda.h>
static const halide_device_interface_t* cuda_interface = halide_cuda_device_interface();
void kernel({argdefs}, uintptr_t stream) {{
{buffers}
int err = halide_kernel(reinterpret_cast<void*>(stream), {buffer_names});
if(err != 0) throw std::runtime_error("halide_kernel failed");
}}
"""
)
standalone_runtime_cuda_init = textwrap.dedent(
"""
#include "{}"
#include <cuda.h>
static int acquire_context(void* user_context,
void** cuda_context_out,
bool create) {{
return cuCtxGetCurrent(reinterpret_cast<CUcontext*>(cuda_context_out));
}}
static int release_context(void* user_context) {{
return 0;
}}
static int get_stream(void* user_context,
void* cuda_context,
void** stream_out) {{
*stream_out = user_context;
return 0;
}}
static int register_halide_hooks() {{
halide_set_cuda_acquire_context(&acquire_context);
halide_set_cuda_release_context(&release_context);
halide_set_cuda_get_stream(&get_stream);
return 0;
}}
int inductor_register_halide_hooks_result = register_halide_hooks();
"""
)
@classmethod
def _codegen_buffer(cls, name: str, arg: HalideInputSpec, cuda: bool) -> list[str]:
assert arg.shape is not None
assert arg.stride is not None and len(arg.shape) == len(arg.stride)
assert arg.offset is not None
data_ptr = f"{arg.alias_of or arg.name} + {arg.offset}"
if cuda:
device = f"reinterpret_cast<uint64_t>({data_ptr})"
device_interface = "cuda_interface"
host = "nullptr"
flags = "halide_buffer_flag_device_dirty"
else:
device = "0"
device_interface = "nullptr"
host = f"reinterpret_cast<uint8_t*>({data_ptr})"
flags = "halide_buffer_flag_host_dirty"
dims = []
for size, stride in zip(arg.shape, arg.stride):
dims.append(f"halide_dimension_t(0, {size}, {stride})")
return [
f"halide_buffer_t {name};",
f"halide_dimension_t {name}_dims[] = {{{', '.join(dims)}}};"
if len(dims) > 0
else f"halide_dimension_t * {name}_dims = nullptr;",
f"{name}.device = {device};",
f"{name}.device_interface = {device_interface};",
f"{name}.host = {host};",
f"{name}.flags = {flags};",
f"{name}.type = {arg.halide_type()};",
f"{name}.dimensions = {len(dims)};",
f"{name}.dim = {name}_dims;",
f"{name}.padding = nullptr;",
]
@classmethod
def _codegen_glue(cls, meta: HalideMeta, headerfile: object) -> str:
is_cuda = meta.is_cuda()
assert is_cuda is ("user_context" in meta.target)
assert "no_runtime" in meta.target
buffers = []
buffer_names = []
for i, arg in enumerate(meta.argtypes):
if arg.is_buffer():
# pyrefly: ignore [bad-argument-type]
buffer_names.append(f"&hl_buf_{i}")
buffers.extend(cls._codegen_buffer(f"hl_buf_{i}", arg, is_cuda))
else:
assert "*" not in arg.ctype
# pyrefly: ignore [bad-argument-type]
buffer_names.append(arg.name)
buffers = "\n".join([f" {line}" for line in buffers]).lstrip()
glue_template = cls.glue_template_cuda if is_cuda else cls.glue_template_cpp
glue_code = glue_template.format(
halideruntime_h=cls.find_header(
"HalideRuntimeCuda.h" if is_cuda else "HalideRuntime.h"
),
headerfile=headerfile,
argdefs=", ".join(
f"{a.bindings_type()} {a.name}"
for a in meta.argtypes
if a.alias_of is None
),
buffers=buffers,
buffer_names=", ".join(buffer_names),
)
return glue_code
@classmethod
@functools.cache
def config_hash(cls) -> str:
command_gen = CppBuilder(
name="O",
sources="I",
BuildOption=CppOptions(),
)
command_line = command_gen.get_command_line()
return sha256_hash(
"\n".join(
[
cls.glue_template_cpp,
cls.glue_template_cuda,
cls.standalone_runtime_cuda_init,
command_line,
]
).encode("utf-8")
)
@staticmethod
def _search_for_file(suffix: str, errmsg: str) -> str:
spec = importlib.machinery.PathFinder.find_spec("halide")
if spec is None or not spec.submodule_search_locations:
raise RuntimeError("halide python bindings not installed")
try:
search = spec.submodule_search_locations[0]
for file in os.listdir(search):
if file.endswith(".so"):
try:
out = subprocess.check_output(
["ldd", os.path.join(search, file)]
)
except subprocess.SubprocessError:
continue
m = re.search(r"(/.*)/libHalide.so", out.decode("utf-8"))
if m:
path = os.path.join(os.path.abspath(m.group(1)), suffix)
if os.path.exists(path):
return os.path.abspath(path)
except Exception as e:
raise RuntimeError(errmsg) from e
raise RuntimeError(errmsg)
@staticmethod
@functools.cache
def find_libautoschedule(name: str) -> str:
sofile = f"libautoschedule_{name.lower()}.so"
if "HALIDE_LIB" in os.environ:
path = os.path.join(os.environ["HALIDE_LIB"], sofile)
if os.path.exists(path):
return path
errmsg = (
f"Can't find {sofile}, set env HALIDE_LIB to the directory containing it"
)
return HalideCodeCache._search_for_file(sofile, errmsg)
@staticmethod
@functools.cache
def find_header(name: str) -> str:
if "HALIDE_INCLUDE" in os.environ:
path = os.path.join(os.environ["HALIDE_INCLUDE"], name)
if os.path.exists(path):
return path
if "HALIDE_LIB" in os.environ:
path = os.path.abspath(
os.path.join(os.environ["HALIDE_LIB"], f"../include/{name}")
)
if os.path.exists(path):
return path
errmsg = (
f"Can't find {name}, set env HALIDE_INCLUDE to the directory containing it"
)
return HalideCodeCache._search_for_file(f"../include/{name}", errmsg)
@classmethod
def generate_halide_async(
cls, meta: HalideMeta, source_code: str, submit_fn: Any = None
) -> Callable[[], Any]:
dirpath = Path(
get_path(
code_hash(
source_code,
extra=repr((cls.config_hash(), meta)),
),
"halide",
)[2]
)
os.makedirs(dirpath, exist_ok=True)
wait_for_compile = None
genfile = str(dirpath / "generate_kernel.py")
libfile = str(dirpath / "halide_kernel.a")
headerfile = str(dirpath / "halide_kernel.h")
donefile = str(dirpath / "done")
lockfile = str(dirpath / "lock")
need_compile = not os.path.exists(donefile)
jobs: list[Any] = []
if need_compile:
write_atomic(genfile, source_code)
cmd = [
sys.executable,
genfile,
"-g",
"kernel",
"-o",
f"{dirpath}",
"-f",
"halide_kernel",
"-e",
"static_library,h,schedule",
]
if meta.scheduler:
cmd.extend(["-p", cls.find_libautoschedule(meta.scheduler)])
cmd.extend(meta.args())
jobs.append(functools.partial(subprocess.check_call, cmd))
binding_types = [
arg.bindings_type() for arg in meta.argtypes if arg.alias_of is None
]
if meta.is_cuda():
binding_types.append("uintptr_t") # stream
bindings_future = cls.load_pybinding_async(
binding_types,
cls._codegen_glue(meta, headerfile),
extra_flags=(libfile, cls.build_standalone_runtime()),
submit_fn=jobs.append if need_compile else None,
device_type="cuda" if meta.is_cuda() else "cpu",
)
if need_compile:
jobs.append(functools.partial(touch, donefile))
task = functools.partial(_worker_task_halide, lockfile, jobs)
if submit_fn:
wait_for_compile = submit_fn(task).result
else:
task()
def load() -> Callable[[], Any]:
if wait_for_compile:
wait_for_compile()
return bindings_future()
return load
@classmethod
def generate_halide(cls, *args: Any, **kwargs: Any) -> Callable[[], Any]:
return cls.generate_halide_async(*args, **kwargs)()
@classmethod
def build_standalone_runtime(cls) -> str:
if cls._standalone_runtime_path and os.path.exists(
cls._standalone_runtime_path
):
return cls._standalone_runtime_path
device_type = "cuda" if torch.cuda.is_available() else "cpu"
libname = "libStandaloneHalideRuntime.so"
target = "host-cuda" if device_type == "cuda" else "host"
if cls._standalone_runtime_path:
assert not os.path.exists(cls._standalone_runtime_path)
# We hit this case in unittests when we run with fresh_cache()
# Generating a fresh runtime over and over causes errors because we initialize
# cuda hundreds of times in the same process and run out of file descriptors.
# Workaround by jail breaking the current fresh_cache().
base = default_cache_dir()
else:
base = cache_dir()
dirpath = Path(base) / f"halide-runtime-{target}-{cls.config_hash()}"
os.makedirs(dirpath, exist_ok=True)
done_file = str(dirpath / "done")
lock_file = str(dirpath / "lock")
hook_file = str(dirpath / "hooks.cpp")
a_file = str(dirpath / "standalone_halide_runtime.a")
so_file = str(dirpath / libname)
if not os.path.exists(done_file):
import halide as hl # type: ignore[import-untyped,import-not-found]
from torch.utils._filelock import FileLock
with FileLock(lock_file, LOCK_TIMEOUT):
if not os.path.exists(done_file):
with open(hook_file, "w") as f:
if device_type == "cuda":
f.write(
cls.standalone_runtime_cuda_init.format(
cls.find_header("HalideRuntimeCuda.h")
)
)
hl.compile_standalone_runtime(a_file, hl.Target(target))
name, output_dir = get_name_and_dir_from_output_file_path(so_file)
halide_cmd_gen = CppBuilder(
name=name,
sources=[hook_file, a_file],
output_dir=output_dir,
BuildOption=CppTorchDeviceOptions(
device_type=device_type,
),
)
subprocess.check_call(
shlex.split(halide_cmd_gen.get_command_line())
)
touch(done_file)
assert os.path.exists(so_file)
cls._standalone_runtime_path = so_file
return so_file
@classmethod
def _get_uncompiled_header(cls, device: str) -> str | None:
"""Header precompiling is currently disabled for halide."""
return None
def _worker_task_halide(lockfile: str, jobs: list[partial[Any]]) -> None:
from torch.utils._filelock import FileLock
try:
with FileLock(lockfile, LOCK_TIMEOUT):
for job in jobs:
job()
except subprocess.SubprocessError as e:
if os.environ.get("HALIDE_REPRO") == "1":
cmd: list[Any]
python, script, *cmd = getattr(e, "cmd", ("", "", ""))
if os.path.basename(python).startswith("python"):
code = Path(script).read_text()
main = " hl.main()"
assert code.count(main) == 1
class Out:
def __repr__(self) -> str:
return "out"
ci = cmd.index("-o")
assert isinstance(ci, int)
# pyrefly: ignore [unsupported-operation]
cmd[ci + 1] = Out()
repl = textwrap.indent(
textwrap.dedent(
f"""\
import sys, tempfile
with tempfile.TemporaryDirectory() as out:
sys.argv = {["repro.py", *cmd]!r}
hl.main()
"""
),
" ",
)
code = code.replace(main, repl)
with open("repro.py", "w") as fd:
fd.write(code.lstrip())
raise RuntimeError(f"wrote repro.py: {e}") from e
raise
def touch(filename: str) -> None:
open(filename, "a").close()
@clear_on_fresh_cache
| HalideCodeCache |
python | Netflix__metaflow | metaflow/plugins/aws/step_functions/schedule_decorator.py | {
"start": 120,
"end": 1940
} | class ____(FlowDecorator):
"""
Specifies the times when the flow should be run when running on a
production scheduler.
Parameters
----------
hourly : bool, default False
Run the workflow hourly.
daily : bool, default True
Run the workflow daily.
weekly : bool, default False
Run the workflow weekly.
cron : str, optional, default None
Run the workflow at [a custom Cron schedule](https://docs.aws.amazon.com/eventbridge/latest/userguide/scheduled-events.html#cron-expressions)
specified by this expression.
timezone : str, optional, default None
Timezone on which the schedule runs (default: None). Currently supported only for Argo workflows,
which accepts timezones in [IANA format](https://nodatime.org/TimeZones).
"""
name = "schedule"
defaults = {
"cron": None,
"weekly": False,
"daily": True,
"hourly": False,
"timezone": None,
}
def flow_init(
self, flow, graph, environment, flow_datastore, metadata, logger, echo, options
):
# Currently supports quartz cron expressions in UTC as defined in
# https://docs.aws.amazon.com/eventbridge/latest/userguide/scheduled-events.html#cron-expressions
if self.attributes["cron"]:
self.schedule = self.attributes["cron"]
elif self.attributes["weekly"]:
self.schedule = "0 0 ? * SUN *"
elif self.attributes["hourly"]:
self.schedule = "0 * * * ? *"
elif self.attributes["daily"]:
self.schedule = "0 0 * * ? *"
else:
self.schedule = None
# Argo Workflows supports the IANA timezone standard, e.g. America/Los_Angeles
self.timezone = self.attributes["timezone"]
| ScheduleDecorator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 67549,
"end": 68476
} | class ____(FromClauseAlias, LateralFromClause):
"""Represent a LATERAL subquery.
This object is constructed from the :func:`_expression.lateral` module
level function as well as the :meth:`_expression.FromClause.lateral`
method available
on all :class:`_expression.FromClause` subclasses.
While LATERAL is part of the SQL standard, currently only more recent
PostgreSQL versions provide support for this keyword.
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
"""
__visit_name__ = "lateral"
_is_lateral = True
inherit_cache = True
@classmethod
def _factory(
cls,
selectable: Union[SelectBase, _FromClauseArgument],
name: Optional[str] = None,
) -> LateralFromClause:
return coercions.expect(
roles.FromClauseRole, selectable, explicit_subquery=True
).lateral(name=name)
| Lateral |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 477,
"end": 729
} | class ____(TestCase):
def setUp(self):
self.widget = widgets.Widget()
def test_clean(self):
self.assertEqual("a", self.widget.clean("a"))
def test_render(self):
self.assertEqual("1", self.widget.render(1))
| WidgetTest |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/_etcd_stub.py | {
"start": 1475,
"end": 1555
} | class ____:
def __init__(self) -> None:
raise EtcdStubError
| EtcdResult |
python | scrapy__scrapy | tests/test_signals.py | {
"start": 625,
"end": 983
} | class ____:
@deferred_f_from_coro_f
async def test_scheduler_empty(self):
crawler = get_crawler()
calls = []
def track_call():
calls.append(object())
crawler.signals.connect(track_call, signals.scheduler_empty)
await maybe_deferred_to_future(crawler.crawl())
assert len(calls) >= 1
| TestMain |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 128989,
"end": 131200
} | class ____(Response):
"""
Response of projects.get_task_tags endpoint.
:param tags: The list of unique tag values
:type tags: Sequence[str]
:param system_tags: The list of unique system tag values. Returned only if 'include_system' is set to 'true'
in the request
:type system_tags: Sequence[str]
"""
_service = "projects"
_action = "get_task_tags"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"system_tags": {
"description": "The list of unique system tag values. Returned only if 'include_system' is set to 'true' in the request",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "The list of unique tag values",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(
self, tags: Optional[List[str]] = None, system_tags: Optional[List[str]] = None, **kwargs: Any
) -> None:
super(GetTaskTagsResponse, self).__init__(**kwargs)
self.tags = tags
self.system_tags = system_tags
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
| GetTaskTagsResponse |
python | kamyu104__LeetCode-Solutions | Python/partition-array-into-two-arrays-to-minimize-sum-difference.py | {
"start": 70,
"end": 843
} | class ____(object):
def minimumDifference(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = nums[:len(nums)//2], nums[len(nums)//2:]
total1, total2 = sum(left), sum(right)
result = float("inf")
for k in xrange(len(left)+1):
sums = sorted(2*sum(comb)-total1 for comb in itertools.combinations(left, k))
for comb in itertools.combinations(right, len(left)-k):
diff = 2*sum(comb)-total2
i = bisect.bisect_left(sums, -diff)
if i < len(sums):
result = min(result, abs(sums[i]+diff))
if i > 0:
result = min(result, abs(sums[i-1]+diff))
return result
| Solution |
python | openai__openai-python | src/openai/types/chat/chat_completion_token_logprob.py | {
"start": 213,
"end": 867
} | class ____(BaseModel):
token: str
"""The token."""
bytes: Optional[List[int]] = None
"""A list of integers representing the UTF-8 bytes representation of the token.
Useful in instances where characters are represented by multiple tokens and
their byte representations must be combined to generate the correct text
representation. Can be `null` if there is no bytes representation for the token.
"""
logprob: float
"""The log probability of this token, if it is within the top 20 most likely
tokens.
Otherwise, the value `-9999.0` is used to signify that the token is very
unlikely.
"""
| TopLogprob |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial004_py310.py | {
"start": 78,
"end": 638
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: set[str] = set()
@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):
"""
Create an item with all the information:
- **name**: each item must have a name
- **description**: a long description
- **price**: required
- **tax**: if the item doesn't have tax, you can omit this
- **tags**: a set of unique tag strings for this item
"""
return item
| Item |
python | keras-team__keras | guides/custom_train_step_in_jax.py | {
"start": 8945,
"end": 10713
} | class ____(keras.Model):
def test_step(self, state, data):
# Unpack the data.
x, y = data
(
trainable_variables,
non_trainable_variables,
metrics_variables,
) = state
# Compute predictions and loss.
y_pred, non_trainable_variables = self.stateless_call(
trainable_variables,
non_trainable_variables,
x,
training=False,
)
loss = self.compute_loss(x, y, y_pred)
# Update metrics.
new_metrics_vars, logs = [], []
for metric in self.metrics:
this_metric_vars = metrics_variables[
len(new_metrics_vars) : len(new_metrics_vars)
+ len(metric.variables)
]
if metric.name == "loss":
this_metric_vars = metric.stateless_update_state(
this_metric_vars, loss
)
else:
this_metric_vars = metric.stateless_update_state(
this_metric_vars, y, y_pred
)
logs = metric.stateless_result(this_metric_vars)
new_metrics_vars += this_metric_vars
# Return metric logs and updated state variables.
state = (
trainable_variables,
non_trainable_variables,
new_metrics_vars,
)
return logs, state
# Construct an instance of CustomModel
inputs = keras.Input(shape=(32,))
outputs = keras.layers.Dense(1)(inputs)
model = CustomModel(inputs, outputs)
model.compile(loss="mse", metrics=["mae"])
# Evaluate with our custom test_step
x = np.random.random((1000, 32))
y = np.random.random((1000, 1))
model.evaluate(x, y)
"""
That's it!
"""
| CustomModel |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker_tests/api/test_component.py | {
"start": 3107,
"end": 4712
} | class ____(TestTranslation):
"""Test translation of asset attributes for Looker components."""
def test_translation(
self,
looker_api_mocks,
attributes: Mapping[str, Any],
assertion: Callable[[AssetSpec], bool],
key_modifier: Optional[Callable[[AssetKey], AssetKey]],
) -> None:
body = copy.deepcopy(BASIC_LOOKER_COMPONENT_BODY)
body["attributes"]["translation"] = attributes
body["attributes"]["defs_state"] = {"management_type": "LOCAL_FILESYSTEM"}
with create_defs_folder_sandbox() as sandbox:
defs_path = sandbox.scaffold_component(
component_cls=LookerComponent,
defs_yaml_contents=body,
)
# First load and populate state
with (
scoped_definitions_load_context(),
sandbox.load_component_and_build_defs(defs_path=defs_path) as (component, defs),
):
assert isinstance(component, LookerComponent)
asyncio.run(component.refresh_state(sandbox.project_root))
# Second load with populated state
with (
scoped_definitions_load_context(),
sandbox.load_component_and_build_defs(defs_path=defs_path) as (component, defs),
):
key = AssetKey(["my_model::my_explore"])
if key_modifier:
key = key_modifier(key)
assets_def = defs.resolve_assets_def(key)
assert assertion(assets_def.get_asset_spec(key))
| TestLookerTranslation |
python | django__django | tests/model_inheritance/models.py | {
"start": 4451,
"end": 4612
} | class ____(CommonAncestor):
first_ancestor = models.OneToOneField(
CommonAncestor, models.CASCADE, primary_key=True, parent_link=True
)
| FirstParent |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 11712,
"end": 12227
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=111, name="INTEGRATION_EDIT", api_name="integration.edit")
def render(self, audit_log_entry: AuditLogEntry) -> str:
if audit_log_entry.data.get("provider"):
return "edited the {name} for the {provider} integration".format(**audit_log_entry.data)
return "edited integration {integration} for project {project}".format(
**audit_log_entry.data
)
| IntegrationEditAuditLogEvent |
python | kamyu104__LeetCode-Solutions | Python/delete-the-middle-node-of-a-linked-list.py | {
"start": 182,
"end": 575
} | class ____(object):
def deleteMiddle(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummy = ListNode()
dummy.next = head
slow = fast = dummy
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
slow.next = slow.next.next
return dummy.next
| Solution |
python | coleifer__peewee | peewee.py | {
"start": 163747,
"end": 164870
} | class ____(Field):
field_type = 'BLOB'
def _db_hook(self, database):
if database is None:
self._constructor = bytearray
else:
self._constructor = database.get_binary_type()
def bind(self, model, name, set_attribute=True):
self._constructor = bytearray
if model._meta.database:
if isinstance(model._meta.database, Proxy):
model._meta.database.attach_callback(self._db_hook)
else:
self._db_hook(model._meta.database)
# Attach a hook to the model metadata; in the event the database is
# changed or set at run-time, we will be sure to apply our callback and
# use the proper data-type for our database driver.
model._meta._db_hooks.append(self._db_hook)
return super(BlobField, self).bind(model, name, set_attribute)
def db_value(self, value):
if isinstance(value, text_type):
value = value.encode('raw_unicode_escape')
if isinstance(value, bytes_type):
return self._constructor(value)
return value
| BlobField |
python | celery__celery | celery/exceptions.py | {
"start": 6967,
"end": 7064
} | class ____(TaskError):
"""The task is already registered."""
# XXX Unused
| AlreadyRegistered |
python | ray-project__ray | python/ray/serve/_private/request_router/pow_2_router.py | {
"start": 495,
"end": 3129
} | class ____(
FIFOMixin, LocalityMixin, MultiplexMixin, RequestRouter
):
"""Chooses a replica for each request using the "power of two choices" procedure.
Requests are routed in FIFO order.
When a request comes in, two candidate replicas are chosen randomly. Each replica
is sent a control message to fetch its queue length.
The replica responds with two items: (queue_len, accepted). Only replicas that
accept the request are considered; between those, the one with the lower queue
length is chosen.
In the case when neither replica accepts the request (e.g., their queues are full),
the procedure is repeated with backoff. This backoff repeats indefinitely until a
replica is chosen, so the caller should use timeouts and cancellation to avoid
hangs.
Each request being routed may spawn an independent task that runs the routing
procedure concurrently. This task will not necessarily satisfy the request that
started it (in order to maintain the FIFO order). The total number of tasks is
capped at (2 * num_replicas).
"""
async def choose_replicas(
self,
candidate_replicas: List[RunningReplica],
pending_request: Optional[PendingRequest] = None,
) -> List[List[RunningReplica]]:
"""One iteration of the power of two choices procedure that chooses
(at most) two random available replicas.
For multiplexing, this will first attempt to choose replicas that have the
requested model ID for a configured timeout. If no replicas with the matching
model ID are available after that timeout, it will fall back to the regular
procedure.
"""
if (
pending_request is not None
and pending_request.metadata.multiplexed_model_id
):
# Get candidates for multiplexed model ID.
candidate_replica_ids = self.apply_multiplex_routing(
pending_request=pending_request,
)
else:
# Get candidates for locality preference.
candidate_replica_ids = self.apply_locality_routing(
pending_request=pending_request,
)
if not candidate_replica_ids:
return []
chosen_ids = random.sample(
list(candidate_replica_ids),
k=min(2, len(candidate_replica_ids)),
)
replica_id_to_replica_map = {
replica.replica_id: replica for replica in candidate_replicas
}
return [[replica_id_to_replica_map[chosen_id] for chosen_id in chosen_ids]]
| PowerOfTwoChoicesRequestRouter |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_list_tuple.py | {
"start": 8005,
"end": 8086
} | class ____:
def __iter__(self):
return iter([1, 2, 5])
| ImplicitContains |
python | sphinx-doc__sphinx | sphinx/search/no.py | {
"start": 197,
"end": 610
} | class ____(SearchLanguage):
lang = 'no'
language_name = 'Norwegian'
js_stemmer_rawcode = 'norwegian-stemmer.js'
stopwords = NORWEGIAN_STOPWORDS
def __init__(self, options: dict[str, str]) -> None:
super().__init__(options)
self.stemmer = snowballstemmer.stemmer('norwegian')
def stem(self, word: str) -> str:
return self.stemmer.stemWord(word.lower())
| SearchNorwegian |
python | mwaskom__seaborn | seaborn/_stats/aggregation.py | {
"start": 1252,
"end": 3587
} | class ____(Stat):
"""
Calculate a point estimate and error bar interval.
For more information about the various `errorbar` choices, see the
:doc:`errorbar tutorial </tutorial/error_bars>`.
Additional variables:
- **weight**: When passed to a layer that uses this stat, a weighted estimate
will be computed. Note that use of weights currently limits the choice of
function and error bar method to `"mean"` and `"ci"`, respectively.
Parameters
----------
func : str or callable
Name of a :class:`numpy.ndarray` method or a vector -> scalar function.
errorbar : str, (str, float) tuple, or callable
Name of errorbar method (one of "ci", "pi", "se" or "sd"), or a tuple
with a method name and a level parameter, or a function that maps from a
vector to a (min, max) interval.
n_boot : int
Number of bootstrap samples to draw for "ci" errorbars.
seed : int
Seed for the PRNG used to draw bootstrap samples.
Examples
--------
.. include:: ../docstrings/objects.Est.rst
"""
func: str | Callable[[Vector], float] = "mean"
errorbar: str | tuple[str, float] = ("ci", 95)
n_boot: int = 1000
seed: int | None = None
group_by_orient: ClassVar[bool] = True
def _process(
self, data: DataFrame, var: str, estimator: EstimateAggregator
) -> DataFrame:
# Needed because GroupBy.apply assumes func is DataFrame -> DataFrame
# which we could probably make more general to allow Series return
res = estimator(data, var)
return pd.DataFrame([res])
def __call__(
self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale],
) -> DataFrame:
boot_kws = {"n_boot": self.n_boot, "seed": self.seed}
if "weight" in data:
engine = WeightedAggregator(self.func, self.errorbar, **boot_kws)
else:
engine = EstimateAggregator(self.func, self.errorbar, **boot_kws)
var = {"x": "y", "y": "x"}[orient]
res = (
groupby
.apply(data, self._process, var, engine)
.dropna(subset=[var])
.reset_index(drop=True)
)
res = res.fillna({f"{var}min": res[var], f"{var}max": res[var]})
return res
@dataclass
| Est |
python | crytic__slither | slither/slithir/operations/send.py | {
"start": 660,
"end": 1683
} | class ____(Call, OperationWithLValue):
def __init__(
self,
destination: Union[LocalVariable, LocalIRVariable],
value: Constant,
result: Union[TemporaryVariable, TemporaryVariableSSA],
) -> None:
assert is_valid_lvalue(result)
assert isinstance(destination, (Variable, SolidityVariable))
super().__init__()
self._destination = destination
self._lvalue = result
self._call_value = value
def can_send_eth(self) -> bool:
return True
@property
def call_value(self) -> Constant:
return self._call_value
@property
def read(self) -> List[Union[Constant, LocalIRVariable, LocalVariable]]:
return [self.destination, self.call_value]
@property
def destination(self) -> Union[LocalVariable, LocalIRVariable]:
return self._destination
def __str__(self):
value = f"value:{self.call_value}"
return str(self.lvalue) + f" = SEND dest:{self.destination} {value}"
#
| Send |
python | getsentry__sentry | src/sentry/seer/endpoints/organization_trace_summary.py | {
"start": 908,
"end": 3031
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ML_AI
enforce_rate_limit = True
# Keeping same rate limits as GroupAISummary endpoint for now
rate_limits = RateLimitConfig(
limit_overrides={
"POST": {
RateLimitCategory.IP: RateLimit(limit=10, window=60),
RateLimitCategory.USER: RateLimit(limit=10, window=60),
RateLimitCategory.ORGANIZATION: RateLimit(limit=30, window=60),
}
}
)
permission_classes = (OrganizationTraceSummaryPermission,)
def post(self, request: Request, organization: Organization) -> Response:
if not features.has(
"organizations:single-trace-summary", organization, actor=request.user
) and not features.has(
"organizations:trace-spans-format", organization, actor=request.user
):
return Response({"detail": "Feature flag not enabled"}, status=400)
data: dict = orjson.loads(request.body) if request.body else {}
trace_id = data.get("traceSlug", None)
only_transaction = data.get("onlyTransaction", False)
if not trace_id:
return Response({"detail": "Missing traceSlug parameter"}, status=400)
# Get the trace tree
try:
trace_endpoint = OrganizationTraceEndpoint()
snuba_params = trace_endpoint.get_snuba_params(request, organization)
trace_tree = trace_endpoint.query_trace_data(snuba_params, trace_id)
except Exception:
return Response({"detail": "Error fetching trace"}, status=400)
if not trace_tree:
return Response({"detail": "Missing trace_tree data"}, status=400)
summary_data, status_code = get_trace_summary(
traceSlug=trace_id,
traceTree=trace_tree,
organization=organization,
user=request.user,
onlyTransaction=only_transaction,
)
return Response(summary_data, status=status_code)
| OrganizationTraceSummaryEndpoint |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 20458,
"end": 20819
} | class ____(NamedValue, _ConstOpMixin, _HasMetadata):
"""
A global value.
"""
name_prefix = '@'
deduplicate_name = False
def __init__(self, *args, **kwargs):
super(GlobalValue, self).__init__(*args, **kwargs)
self.linkage = ''
self.storage_class = ''
self.section = ''
self.metadata = {}
| GlobalValue |
python | langchain-ai__langchain | libs/standard-tests/tests/unit_tests/test_basic_tool.py | {
"start": 917,
"end": 1671
} | class ____(ToolsUnitTests):
@property
def tool_constructor(self) -> type[ParrotMultiplyTool]:
return ParrotMultiplyTool
@property
def tool_constructor_params(self) -> dict:
# if your tool constructor instead required initialization arguments like
# `def __init__(self, some_arg: int):`, you would return those here
# as a dictionary, e.g.: `return {'some_arg': 42}`
return {}
@property
def tool_invoke_params_example(self) -> dict:
"""Returns a dictionary representing the "args" of an example tool call.
This should NOT be a ToolCall dict - i.e. it should not
have {"name", "id", "args"} keys.
"""
return {"a": 2, "b": 3}
| TestParrotMultiplyToolUnit |
python | kamyu104__LeetCode-Solutions | Python/shortest-path-in-a-hidden-grid.py | {
"start": 216,
"end": 2100
} | class ____(object):
def findShortestPath(self, master):
"""
:type master: GridMaster
:rtype: int
"""
directions = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}
rollback = {'L': 'R', 'R': 'L', 'U': 'D', 'D': 'U'}
def dfs(pos, target, master, lookup, adj):
if target[0] is None and master.isTarget():
target[0] = pos
lookup.add(pos)
for d, (di, dj) in directions.iteritems():
if not master.canMove(d):
continue
nei = (pos[0]+di, pos[1]+dj)
adj[pos].add(nei)
adj[nei].add(pos)
if nei in lookup:
continue
master.move(d)
dfs(nei, target, master, lookup, adj)
master.move(rollback[d])
def bi_bfs(adj, start, target):
left, right = {start}, {target}
lookup = set()
steps = 0
while left:
for pos in left:
lookup.add(pos)
new_left = set()
for pos in left:
if pos in right:
return steps
for nei in adj[pos]:
if nei in lookup:
continue
new_left.add(nei)
left = new_left
steps += 1
if len(left) > len(right):
left, right = right, left
return -1
start = (0, 0)
target = [None]
adj = collections.defaultdict(set)
dfs(start, target, master, set(), adj)
if not target[0]:
return -1
return bi_bfs(adj, start, target[0])
# Time: O(m * n)
# Space: O(m * n)
| Solution |
python | huggingface__transformers | tests/models/kyutai_speech_to_text/test_modeling_kyutai_speech_to_text.py | {
"start": 24831,
"end": 31805
} | class ____(unittest.TestCase):
_dataset = None
def setUp(self):
self.model_checkpoint = "kyutai/stt-2.6b-en-trfs"
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@classmethod
def _load_dataset(cls):
# Lazy loading of the dataset. Because it is a class method, it will only be loaded once per pytest process.
if cls._dataset is None:
cls._dataset = datasets.load_dataset(
"hf-internal-testing/librispeech_asr_dummy", "clean", split="validation"
)
# using 24000 here for simplicity, should rather be processor.feature_extractor.sampling_rate
cls._dataset = cls._dataset.cast_column("audio", datasets.Audio(sampling_rate=24000))
def _load_datasamples(self, num_samples):
self._load_dataset()
ds = self._dataset
speech_samples = ds.sort("id")[:num_samples]["audio"]
return [x["array"] for x in speech_samples]
@slow
@require_torch_accelerator
def test_generation(self):
"""
reproduce test expected outputs using original codebase: https://gist.github.com/eustlb/7a9aa6139d11e0103c6b65bac103da52
DISCLAIMER: we are testing for pretty short inputs. Indeed, reproducing correct expected outputs for longer is not possible
as implementation choices (qkv matrix in one linear for original code vs three for hf) create growing divergence with context length,
ultimately giving different outputs.
"""
processor = KyutaiSpeechToTextProcessor.from_pretrained(self.model_checkpoint)
model = KyutaiSpeechToTextForConditionalGeneration.from_pretrained(
self.model_checkpoint, device_map=torch_device
)
samples = self._load_datasamples(1)
inputs = processor(
samples,
).to(torch_device)
out = model.generate(**inputs)
# fmt: off
EXPECTED_TOKENS = torch.tensor([
[48000, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1519, 263, 3, 3, 0, 3635, 428, 641, 0, 277, 3, 0, 265, 0, 267, 1162, 261, 274, 410, 0, 272, 3, 0, 265, 0, 260, 1621, 0, 1174, 371, 262, 3, 3, 3, 0, 269, 0, 281, 0, 304, 0, 2433, 3, 0, 266, 3, 0, 281, 1661, 3, 0, 376, 3, 3, 0, 350, 261, 401, 516, 263, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]],
)
# fmt: on
torch.testing.assert_close(out.cpu(), EXPECTED_TOKENS)
@slow
@require_torch_accelerator
def test_generation_batched(self):
"""
reproduce test expected outputs using original codebase: https://gist.github.com/eustlb/b58c217c75124d405ec1c13877c7ece8
DISCLAIMER: we are testing for pretty short inputs. Indeed, reproducing correct expected outputs for longer is not possible
as implementation choices (qkv matrix in one linear for original code vs three for hf) create growing divergence with context length,
ultimately giving different outputs.
"""
processor = KyutaiSpeechToTextProcessor.from_pretrained(self.model_checkpoint)
model = KyutaiSpeechToTextForConditionalGeneration.from_pretrained(
self.model_checkpoint, device_map=torch_device
)
samples = self._load_datasamples(4)
inputs = processor(
samples,
).to(torch_device)
out = model.generate(**inputs)
# fmt: off
EXPECTED_TOKENS = torch.tensor([
[48000, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1519, 263, 3, 3, 0, 3635, 428, 641, 0, 277, 3, 0, 265, 0, 267, 1162, 261, 274, 410, 0, 272, 3, 0, 265, 0, 260, 1621, 0, 1174, 371, 262, 3, 3, 3, 0, 269, 0, 281, 0, 304, 0, 2433, 3, 0, 266, 3, 0, 281, 1661, 3, 0, 376, 3, 3, 0, 350, 261, 401, 516, 263, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[48000, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 500, 334, 0, 277, 3, 0, 1519, 263, 3, 3, 0, 3635, 428, 641, 264, 261, 0, 511, 1109, 3, 0, 1138, 3, 3, 3, 0, 508, 827, 3, 3, 3, 3, 0, 468, 3, 3, 0, 376, 3, 3, 3, 0, 260, 978, 263, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[48000, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 414, 0, 527, 261, 3, 0, 409, 3, 3, 3, 0, 271, 3, 0, 309, 3, 0, 285, 3, 0, 521, 371, 609, 3, 3, 0, 260, 959, 3, 3, 3, 0, 272, 3, 0, 265, 0, 546, 262, 3, 3, 3, 3, 3, 3, 0, 291, 3, 0, 975, 2203, 3, 3, 3, 3, 0, 269, 3, 0, 260, 489, 651, 274, 279, 1870, 3, 0, 1084, 873, 273, 3, 0, 260, 531, 3, 3, 0, 409, 262, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1502, 1005, 836, 3, 3, 0, 1666, 306, 3, 0, 340, 3, 0, 260, 3232, 3, 0, 269, 3, 3, 0, 275, 261, 0, 260, 1379, 261, 0, 3324, 3, 3, 3, 3, 0, 549, 3, 3, 0, 693, 405, 323, 3, 0, 266, 3, 3, 0, 265, 0, 699, 263, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[48000, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 414, 0, 392, 3, 3, 0, 1269, 314, 0, 2607, 261, 3, 3, 3, 0, 1098, 295, 3, 3, 3, 0, 446, 625, 3, 0, 496, 280, 1205, 485, 1071, 1627, 449, 264, 261, 3, 0, 400, 0, 277, 3, 3, 3, 0, 260, 342, 3, 0, 618, 280, 1866, 3, 3, 0, 554, 3, 3, 3, 3, 0, 317, 262, 3, 3, 3, 3, 3, 3, 3, 3, 0, 269, 0, 303, 3, 0, 573, 2615, 3, 3, 0, 276, 3, 0, 275, 0, 305, 3, 0, 260, 415, 3, 3, 0, 272, 3, 3, 3, 3, 0, 1631, 327, 3, 3, 0, 333, 739, 841, 263, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
])
# fmt: on
# See https://github.com/huggingface/transformers/pull/39416
EXPECTED_TOKENS_2 = torch.clone(EXPECTED_TOKENS)
EXPECTED_TOKENS_2[2, 159:162] = torch.tensor([3, 0, 269])
try:
torch.testing.assert_close(out.cpu(), EXPECTED_TOKENS)
except AssertionError:
torch.testing.assert_close(out.cpu(), EXPECTED_TOKENS_2)
| KyutaiSpeechToTextForConditionalGenerationIntegrationTests |
python | apache__avro | lang/py/avro/io.py | {
"start": 14558,
"end": 21728
} | class ____:
"""Write leaf values."""
_writer: IO[bytes]
def __init__(self, writer: IO[bytes]) -> None:
"""
writer is a Python object on which we can call write.
"""
self._writer = writer
@property
def writer(self) -> IO[bytes]:
return self._writer
def write(self, datum: bytes) -> None:
"""Write an arbitrary datum."""
self.writer.write(datum)
def write_null(self, datum: None) -> None:
"""
null is written as zero bytes
"""
def write_boolean(self, datum: bool) -> None:
"""
a boolean is written as a single byte
whose value is either 0 (false) or 1 (true).
"""
self.write(bytearray([bool(datum)]))
def write_int(self, datum: int) -> None:
"""
int and long values are written using variable-length, zig-zag coding.
"""
self.write_long(datum)
def write_long(self, datum: int) -> None:
"""
int and long values are written using variable-length, zig-zag coding.
"""
datum = (datum << 1) ^ (datum >> 63)
while (datum & ~0x7F) != 0:
self.write(bytearray([(datum & 0x7F) | 0x80]))
datum >>= 7
self.write(bytearray([datum]))
def write_float(self, datum: float) -> None:
"""
A float is written as 4 bytes.
The float is converted into a 32-bit integer using a method equivalent to
Java's floatToRawIntBits and then encoded in little-endian format.
"""
self.write(STRUCT_FLOAT.pack(datum))
def write_double(self, datum: float) -> None:
"""
A double is written as 8 bytes.
The double is converted into a 64-bit integer using a method equivalent to
Java's doubleToRawLongBits and then encoded in little-endian format.
"""
self.write(STRUCT_DOUBLE.pack(datum))
def write_decimal_bytes(self, datum: decimal.Decimal, scale: int) -> None:
"""
Decimal in bytes are encoded as long. Since size of packed value in bytes for
signed long is 8, 8 bytes are written.
"""
sign, digits, exp = datum.as_tuple()
if (-1 * int(exp)) > scale:
raise avro.errors.AvroOutOfScaleException(scale, datum, exp)
unscaled_datum = 0
for digit in digits:
unscaled_datum = (unscaled_datum * 10) + digit
bits_req = unscaled_datum.bit_length() + 1
if sign:
unscaled_datum = (1 << bits_req) - unscaled_datum
bytes_req = bits_req // 8
padding_bits = ~((1 << bits_req) - 1) if sign else 0
packed_bits = padding_bits | unscaled_datum
bytes_req += 1 if (bytes_req << 3) < bits_req else 0
self.write_long(bytes_req)
for index in range(bytes_req - 1, -1, -1):
bits_to_write = packed_bits >> (8 * index)
self.write(bytearray([bits_to_write & 0xFF]))
def write_decimal_fixed(self, datum: decimal.Decimal, scale: int, size: int) -> None:
"""
Decimal in fixed are encoded as size of fixed bytes.
"""
sign, digits, exp = datum.as_tuple()
if (-1 * int(exp)) > scale:
raise avro.errors.AvroOutOfScaleException(scale, datum, exp)
unscaled_datum = 0
for digit in digits:
unscaled_datum = (unscaled_datum * 10) + digit
bits_req = unscaled_datum.bit_length() + 1
size_in_bits = size * 8
offset_bits = size_in_bits - bits_req
mask = 2**size_in_bits - 1
bit = 1
for i in range(bits_req):
mask ^= bit
bit <<= 1
if bits_req < 8:
bytes_req = 1
else:
bytes_req = bits_req // 8
if bits_req % 8 != 0:
bytes_req += 1
if sign:
unscaled_datum = (1 << bits_req) - unscaled_datum
unscaled_datum = mask | unscaled_datum
for index in range(size - 1, -1, -1):
bits_to_write = unscaled_datum >> (8 * index)
self.write(bytearray([bits_to_write & 0xFF]))
else:
for i in range(offset_bits // 8):
self.write(b"\x00")
for index in range(bytes_req - 1, -1, -1):
bits_to_write = unscaled_datum >> (8 * index)
self.write(bytearray([bits_to_write & 0xFF]))
def write_bytes(self, datum: bytes) -> None:
"""
Bytes are encoded as a long followed by that many bytes of data.
"""
self.write_long(len(datum))
self.write(struct.pack(f"{len(datum)}s", datum))
def write_utf8(self, datum: str) -> None:
"""
A string is encoded as a long followed by
that many bytes of UTF-8 encoded character data.
"""
self.write_bytes(datum.encode("utf-8"))
def write_date_int(self, datum: datetime.date) -> None:
"""
Encode python date object as int.
It stores the number of days from
the unix epoch, 1 January 1970 (ISO calendar).
"""
delta_date = datum - datetime.date(1970, 1, 1)
self.write_int(delta_date.days)
def write_time_millis_int(self, datum: datetime.time) -> None:
"""
Encode python time object as int.
It stores the number of milliseconds from midnight, 00:00:00.000
"""
milliseconds = datum.hour * 3600000 + datum.minute * 60000 + datum.second * 1000 + datum.microsecond // 1000
self.write_int(milliseconds)
def write_time_micros_long(self, datum: datetime.time) -> None:
"""
Encode python time object as long.
It stores the number of microseconds from midnight, 00:00:00.000000
"""
microseconds = datum.hour * 3600000000 + datum.minute * 60000000 + datum.second * 1000000 + datum.microsecond
self.write_long(microseconds)
def _timedelta_total_microseconds(self, timedelta_: datetime.timedelta) -> int:
return timedelta_.microseconds + (timedelta_.seconds + timedelta_.days * 24 * 3600) * 10**6
def write_timestamp_millis_long(self, datum: datetime.datetime) -> None:
"""
Encode python datetime object as long.
It stores the number of milliseconds from midnight of unix epoch, 1 January 1970.
"""
datum = datum.astimezone(tz=avro.timezones.utc)
timedelta = datum - datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=avro.timezones.utc)
milliseconds = self._timedelta_total_microseconds(timedelta) // 1000
self.write_long(milliseconds)
def write_timestamp_micros_long(self, datum: datetime.datetime) -> None:
"""
Encode python datetime object as long.
It stores the number of microseconds from midnight of unix epoch, 1 January 1970.
"""
datum = datum.astimezone(tz=avro.timezones.utc)
timedelta = datum - datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=avro.timezones.utc)
microseconds = self._timedelta_total_microseconds(timedelta)
self.write_long(microseconds)
#
# DatumReader/Writer
#
| BinaryEncoder |
python | PrefectHQ__prefect | src/prefect/events/schemas/automations.py | {
"start": 755,
"end": 2783
} | class ____(PrefectBaseModel, abc.ABC, extra="ignore"): # type: ignore[call-arg]
"""
Base class describing a set of criteria that must be satisfied in order to trigger
an automation.
"""
type: str
@abc.abstractmethod
def describe_for_cli(self, indent: int = 0) -> str:
"""Return a human-readable description of this trigger for the CLI"""
# The following allows the regular Trigger class to be used when serving or
# deploying flows, analogous to how the Deployment*Trigger classes work
_deployment_id: Optional[UUID] = PrivateAttr(default=None)
def set_deployment_id(self, deployment_id: UUID) -> None:
self._deployment_id = deployment_id
def owner_resource(self) -> Optional[str]:
return f"prefect.deployment.{self._deployment_id}"
def actions(self) -> List[ActionTypes]:
assert self._deployment_id
return [
RunDeployment(
source="selected",
deployment_id=self._deployment_id,
parameters=getattr(self, "parameters", None),
job_variables=getattr(self, "job_variables", None),
schedule_after=getattr(self, "schedule_after", timedelta(0)),
)
]
def as_automation(self) -> "AutomationCore":
assert self._deployment_id
trigger: TriggerTypes = cast(TriggerTypes, self)
# This is one of the Deployment*Trigger classes, so translate it over to a
# plain Trigger
if hasattr(self, "trigger_type"):
trigger = self.trigger_type(**self.model_dump())
return AutomationCore(
name=(
getattr(self, "name", None)
or f"Automation for deployment {self._deployment_id}"
),
description=getattr(self, "description", ""),
enabled=getattr(self, "enabled", True),
trigger=trigger,
actions=self.actions(),
owner_resource=self.owner_resource(),
)
| Trigger |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 622,
"end": 870
} | class ____(Message):
message = 'redefinition of unused %r from line %r'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
| RedefinedWhileUnused |
python | spack__spack | lib/spack/spack/cmd/common/arguments.py | {
"start": 1469,
"end": 2996
} | class ____(argparse.Action):
"""Constructs a list of specs based on constraints from the command line
An instance of this class is supposed to be used as an argument action
in a parser. It will read a constraint and will attach a function to the
arguments that accepts optional keyword arguments.
To obtain the specs from a command the function must be called.
"""
def __call__(self, parser, namespace, values, option_string=None):
# Query specs from command line
self.constraint = namespace.constraint = values
self.constraint_specs = namespace.constraint_specs = []
namespace.specs = self._specs
def _specs(self, **kwargs):
# store parsed specs in spec.constraint after a call to specs()
self.constraint_specs[:] = spack.cmd.parse_specs(self.constraint)
# If an environment is provided, we'll restrict the search to
# only its installed packages.
env = ev.active_environment()
if env:
kwargs["hashes"] = set(env.all_hashes())
# return everything for an empty query.
if not self.constraint_specs:
return spack.store.STORE.db.query(**kwargs)
# Return only matching stuff otherwise.
specs = {}
for spec in self.constraint_specs:
for s in spack.store.STORE.db.query(spec, **kwargs):
# This is fast for already-concrete specs
specs[s.dag_hash()] = s
return sorted(specs.values())
| ConstraintAction |
python | falconry__falcon | tests/test_cmd_inspect_app.py | {
"start": 4423,
"end": 6179
} | class ____:
def check(self, actual, expect):
if _WIN32:
# windows randomly returns the driver name as lowercase
assert actual.casefold() == expect.casefold()
else:
assert actual == expect
def test_routes_only(self, verbose, internal, monkeypatch):
args = ['some-file.py', '{}:{}'.format(_MODULE, '_APP'), '-r']
if verbose:
args.append('-v')
if internal:
args.append('-i')
monkeypatch.setattr('sys.argv', args)
output = io.StringIO()
with contextlib.redirect_stdout(output):
inspect_app.main()
routes = inspect.inspect_routes(_APP)
sv = inspect.StringVisitor(verbose, internal)
expect = '\n'.join([sv.process(r) for r in routes])
self.check(output.getvalue().strip(), expect)
def test_inspect(self, verbose, internal, monkeypatch):
args = ['some-file.py', '{}:{}'.format(_MODULE, '_APP')]
if verbose:
args.append('-v')
if internal:
args.append('-i')
monkeypatch.setattr('sys.argv', args)
output = io.StringIO()
with contextlib.redirect_stdout(output):
inspect_app.main()
ins = inspect.inspect_app(_APP)
self.check(output.getvalue().strip(), ins.to_string(verbose, internal))
def test_route_main(monkeypatch):
called = False
def mock():
nonlocal called
called = True
monkeypatch.setattr(inspect_app, 'main', mock)
output = io.StringIO()
with contextlib.redirect_stderr(output):
with pytest.raises(SystemExit):
inspect_app.route_main()
assert 'no longer supported' in output.getvalue()
assert not called
| TestMain |
python | joke2k__faker | tests/providers/test_internet.py | {
"start": 33282,
"end": 34547
} | class ____:
"""Test ru_RU internet provider methods"""
def test_free_email_domain(self, faker):
assert faker.free_email_domain() in RuRuInternetProvider.free_email_domains
def test_tld(self, faker):
assert faker.tld() in RuRuInternetProvider.tlds
@patch(
"faker.providers.internet.Provider.user_name",
lambda x: "ИванИванов",
)
def test_ascii_safe_email(self, faker):
email = faker.ascii_safe_email()
validate_email(email)
assert email.split("@")[0] == "ivanivanov"
@patch(
"faker.providers.internet.Provider.user_name",
lambda x: "АлександрСмирнов",
)
def test_ascii_free_email(self, faker):
email = faker.ascii_free_email()
validate_email(email)
assert email.split("@")[0] == "aleksandrsmirnov"
@patch(
"faker.providers.internet.Provider.user_name",
lambda x: "СергейКузнецов",
)
def test_ascii_company_email(self, faker):
email = faker.ascii_company_email()
validate_email(email)
assert email.split("@")[0] == "sergekuznetsov"
def test_slug(self, faker):
num_of_samples = 100
for _ in range(num_of_samples):
assert faker.slug() != ""
| TestRuRu |
python | scikit-learn__scikit-learn | sklearn/metrics/tests/test_score_objects.py | {
"start": 5163,
"end": 5358
} | class ____(BaseEstimator):
"""Dummy estimator to test scoring validators"""
def fit(self, X, y):
return self
def score(self, X, y):
return 1.0
| EstimatorWithFitAndScore |
python | getsentry__sentry | src/sentry/api/paginator.py | {
"start": 8213,
"end": 8493
} | class ____(BasePaginator):
def get_item_key(self, item, for_prev=False):
value = getattr(item, self.key)
return int(math.floor(value) if self._is_asc(for_prev) else math.ceil(value))
def value_from_cursor(self, cursor):
return cursor.value
| Paginator |
python | ZoranPandovski__al-go-rithms | data_structures/Arrays/Python/running_sum_of_1D_array.py | {
"start": 640,
"end": 993
} | class ____:
def runningSum(self, nums: List[int]) -> List[int]:
# In this algorithm we keep replacing the i th element with the running sum.
# This allows us to achieve O(1) space and O(n) time complexity
sum = 0
for i in range(len(nums)):
sum += nums[i]
nums[i] = sum
return nums | Solution |
python | django__django | django/core/management/commands/sqlsequencereset.py | {
"start": 105,
"end": 1101
} | class ____(AppCommand):
help = (
"Prints the SQL statements for resetting sequences for the given app name(s)."
)
output_transaction = True
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--database",
default=DEFAULT_DB_ALIAS,
choices=tuple(connections),
help=(
'Nominates a database to print the SQL for. Defaults to the "default" '
"database."
),
)
def handle_app_config(self, app_config, **options):
if app_config.models_module is None:
return
connection = connections[options["database"]]
models = app_config.get_models(include_auto_created=True)
statements = connection.ops.sequence_reset_sql(self.style, models)
if not statements and options["verbosity"] >= 1:
self.stderr.write("No sequences found.")
return "\n".join(statements)
| Command |
python | pytorch__pytorch | torch/nn/utils/_expanded_weights/embedding_expanded_weights.py | {
"start": 289,
"end": 3073
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(
ctx: Any, kwarg_names: list[str], _: Any, *expanded_args_and_kwargs: Any
) -> torch.Tensor:
expanded_args, expanded_kwargs = standard_kwargs(
kwarg_names, expanded_args_and_kwargs
)
if len(expanded_args[0].shape) == 1:
raise RuntimeError(
f"Expanded Weights needs an input with a batch size, got a 1D tensor, {expanded_args[0]}"
)
output = forward_helper(F.embedding, expanded_args, expanded_kwargs)
ctx.input, ctx.weight = expanded_args
ctx.padding_idx, ctx.scale_grad_by_freq = (
expanded_kwargs["padding_idx"],
expanded_kwargs["scale_grad_by_freq"],
)
ctx.sparse = expanded_kwargs["sparse"]
return output
@staticmethod
# pyrefly: ignore [bad-override]
def backward(
ctx: Any, grad_output: torch.Tensor
) -> tuple[torch.Tensor | None, ...]:
input, weight = ctx.input, ctx.weight
padding_idx, scale_grad_by_freq, sparse = (
ctx.padding_idx,
ctx.scale_grad_by_freq,
ctx.sparse,
)
def weight_per_sample_grad(weight: torch.Tensor) -> torch.Tensor:
batch_size = input.shape[0]
embedding_dim = weight.shape[1]
index = (
input.unsqueeze(-1)
.expand(*input.shape, embedding_dim)
.reshape(batch_size, -1, embedding_dim)
)
grad_sample = torch.zeros( # type: ignore[attr-defined]
batch_size, *weight.shape, device=weight.device, dtype=grad_output.dtype
)
return grad_sample.scatter_add_(
1, index, grad_output.reshape(batch_size, -1, embedding_dim)
)
results: list[torch.Tensor | None] = []
results.append(None) # for kwarg names
results.append(None) # for op reference
if input.requires_grad:
bw_fn = torch.ops.aten.embedding_backward
results.append(
bw_fn(
grad_output,
input,
weight.shape[0],
padding_idx,
scale_grad_by_freq,
sparse,
)
)
else:
results.append(None)
# weight doesn't compute batched gradients; no other arguments are differentiable (2 not saved from forward)
results = results + [None] * 6
# set grad_sample field for weight with per sample gradients
set_grad_sample_if_exists(weight, weight_per_sample_grad)
return tuple(results)
| EmbeddingPerSampleGrad |
python | Textualize__textual | docs/examples/styles/border_title_align.py | {
"start": 64,
"end": 583
} | class ____(App):
CSS_PATH = "border_title_align.tcss"
def compose(self):
lbl = Label("My title is on the left.", id="label1")
lbl.border_title = "< Left"
yield lbl
lbl = Label("My title is centered", id="label2")
lbl.border_title = "Centered!"
yield lbl
lbl = Label("My title is on the right", id="label3")
lbl.border_title = "Right >"
yield lbl
if __name__ == "__main__":
app = BorderTitleAlignApp()
app.run()
| BorderTitleAlignApp |
python | readthedocs__readthedocs.org | readthedocs/config/tests/test_validation.py | {
"start": 1400,
"end": 2219
} | class ____:
def test_it_accepts_list_types(self):
result = validate_list(["choice", "another_choice"])
assert result == ["choice", "another_choice"]
result = validate_list(("choice", "another_choice"))
assert result == ["choice", "another_choice"]
def iterator():
yield "choice"
result = validate_list(iterator())
assert result == ["choice"]
with raises(ConfigValidationError) as excinfo:
validate_choice("c", "abc")
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
def test_it_rejects_string_types(self):
with raises(ConfigValidationError) as excinfo:
validate_list("choice")
assert excinfo.value.message_id == ConfigValidationError.INVALID_LIST
| TestValidateList |
python | realpython__materials | hashtable/01_hashtable_prototype/10_make_the_hash_table_iterable/hashtable.py | {
"start": 107,
"end": 1501
} | class ____:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("Capacity must be a positive number")
self._slots = capacity * [None]
def __len__(self):
return len(self.pairs)
def __iter__(self):
yield from self.keys
def __delitem__(self, key):
if key in self:
self._slots[self._index(key)] = None
else:
raise KeyError(key)
def __setitem__(self, key, value):
self._slots[self._index(key)] = Pair(key, value)
def __getitem__(self, key):
pair = self._slots[self._index(key)]
if pair is None:
raise KeyError(key)
return pair.value
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
@property
def pairs(self):
return {pair for pair in self._slots if pair}
@property
def values(self):
return [pair.value for pair in self.pairs]
@property
def keys(self):
return {pair.key for pair in self.pairs}
@property
def capacity(self):
return len(self._slots)
def _index(self, key):
return hash(key) % self.capacity
| HashTable |
python | apache__airflow | airflow-core/src/airflow/utils/db_cleanup.py | {
"start": 11660,
"end": 23303
} | class ____(Executable, ClauseElement):
"""Custom sqlalchemy clause element for CTAS operations."""
inherit_cache = False
def __init__(self, name, query):
self.name = name
self.query = query
@compiles(CreateTableAs)
def _compile_create_table_as__other(element, compiler, **kw):
return f"CREATE TABLE {element.name} AS {compiler.process(element.query)}"
def _build_query(
*,
orm_model,
recency_column,
keep_last,
keep_last_filters,
keep_last_group_by,
clean_before_timestamp: DateTime,
session: Session,
**kwargs,
) -> Query:
base_table_alias = "base"
base_table = aliased(orm_model, name=base_table_alias)
query = session.query(base_table).with_entities(text(f"{base_table_alias}.*"))
base_table_recency_col = base_table.c[recency_column.name]
conditions = [base_table_recency_col < clean_before_timestamp]
if keep_last:
max_date_col_name = "max_date_per_group"
group_by_columns: list[Any] = [column(x) for x in keep_last_group_by]
subquery = _subquery_keep_last(
recency_column=recency_column,
keep_last_filters=keep_last_filters,
group_by_columns=group_by_columns,
max_date_colname=max_date_col_name,
session=session,
)
query = query.select_from(base_table).outerjoin(
subquery,
and_(
*[base_table.c[x] == subquery.c[x] for x in keep_last_group_by], # type: ignore[attr-defined]
base_table_recency_col == column(max_date_col_name),
),
)
conditions.append(column(max_date_col_name).is_(None))
query = query.filter(and_(*conditions))
return query
def _cleanup_table(
*,
orm_model,
recency_column,
keep_last,
keep_last_filters,
keep_last_group_by,
clean_before_timestamp: DateTime,
dry_run: bool = True,
verbose: bool = False,
skip_archive: bool = False,
session: Session,
batch_size: int | None = None,
**kwargs,
) -> None:
print()
if dry_run:
print(f"Performing dry run for table {orm_model.name}")
query = _build_query(
orm_model=orm_model,
recency_column=recency_column,
keep_last=keep_last,
keep_last_filters=keep_last_filters,
keep_last_group_by=keep_last_group_by,
clean_before_timestamp=clean_before_timestamp,
session=session,
)
logger.debug("old rows query:\n%s", query.selectable.compile())
print(f"Checking table {orm_model.name}")
num_rows = _check_for_rows(query=query, print_rows=False)
if num_rows and not dry_run:
_do_delete(
query=query,
orm_model=orm_model,
skip_archive=skip_archive,
session=session,
batch_size=batch_size,
)
session.commit()
def _confirm_delete(*, date: DateTime, tables: list[str]) -> None:
for_tables = f" for tables {tables!r}" if tables else ""
question = (
f"You have requested that we purge all data prior to {date}{for_tables}.\n"
f"This is irreversible. Consider backing up the tables first and / or doing a dry run "
f"with option --dry-run.\n"
f"Enter 'delete rows' (without quotes) to proceed."
)
print(question)
answer = input().strip()
if answer != "delete rows":
raise SystemExit("User did not confirm; exiting.")
def _confirm_drop_archives(*, tables: list[str]) -> None:
# if length of tables is greater than 3, show the total count
if len(tables) > 3:
text_ = f"{len(tables)} archived tables prefixed with {ARCHIVE_TABLE_PREFIX}"
else:
text_ = f"the following archived tables: {', '.join(tables)}"
question = (
f"You have requested that we drop {text_}.\n"
f"This is irreversible. Consider backing up the tables first.\n"
)
print(question)
if len(tables) > 3:
show_tables = ask_yesno("Show tables that will be dropped? (y/n): ")
if show_tables:
for table in tables:
print(f" {table}")
print("\n")
answer = input("Enter 'drop archived tables' (without quotes) to proceed.\n").strip()
if answer != "drop archived tables":
raise SystemExit("User did not confirm; exiting.")
def _print_config(*, configs: dict[str, _TableConfig]) -> None:
data = [x.readable_config for x in configs.values()]
AirflowConsole().print_as_table(data=data)
@contextmanager
def _suppress_with_logging(table: str, session: Session):
"""Suppresses errors but logs them."""
try:
yield
except (OperationalError, ProgrammingError):
logger.warning("Encountered error when attempting to clean table '%s'. ", table)
logger.debug("Traceback for table '%s'", table, exc_info=True)
if session.is_active:
logger.debug("Rolling back transaction")
session.rollback()
def _effective_table_names(*, table_names: list[str] | None) -> tuple[list[str], dict[str, _TableConfig]]:
desired_table_names = set(table_names or config_dict)
outliers = desired_table_names - set(config_dict.keys())
if outliers:
logger.warning(
"The following table(s) are not valid choices and will be skipped: %s",
sorted(outliers),
)
desired_table_names = desired_table_names - outliers
visited: set[str] = set()
effective_table_names: list[str] = []
def collect_deps(table: str):
if table in visited:
return
visited.add(table)
config = config_dict[table]
for dep in config.dependent_tables or []:
collect_deps(dep)
effective_table_names.append(table)
for table_name in desired_table_names:
collect_deps(table_name)
effective_config_dict = {n: config_dict[n] for n in effective_table_names}
if not effective_config_dict:
raise SystemExit("No tables selected for db cleanup. Please choose valid table names.")
return effective_table_names, effective_config_dict
def _get_archived_table_names(table_names: list[str] | None, session: Session) -> list[str]:
inspector = inspect(session.bind)
db_table_names = [
x
for x in (inspector.get_table_names() if inspector else [])
if x.startswith(ARCHIVE_TABLE_PREFIX) or x in ARCHIVED_TABLES_FROM_DB_MIGRATIONS
]
effective_table_names, _ = _effective_table_names(table_names=table_names)
# Filter out tables that don't start with the archive prefix
archived_table_names = [
table_name
for table_name in db_table_names
if (
any("__" + x + "__" in table_name for x in effective_table_names)
or table_name in ARCHIVED_TABLES_FROM_DB_MIGRATIONS
)
]
return archived_table_names
@provide_session
def run_cleanup(
*,
clean_before_timestamp: DateTime,
table_names: list[str] | None = None,
dry_run: bool = False,
verbose: bool = False,
confirm: bool = True,
skip_archive: bool = False,
session: Session = NEW_SESSION,
batch_size: int | None = None,
) -> None:
"""
Purges old records in airflow metadata database.
The last non-externally-triggered dag run will always be kept in order to ensure
continuity of scheduled dag runs.
Where there are foreign key relationships, deletes will cascade, so that for
example if you clean up old dag runs, the associated task instances will
be deleted.
:param clean_before_timestamp: The timestamp before which data should be purged
:param table_names: Optional. List of table names to perform maintenance on. If list not provided,
will perform maintenance on all tables.
:param dry_run: If true, print rows meeting deletion criteria
:param verbose: If true, may provide more detailed output.
:param confirm: Require user input to confirm before processing deletions.
:param skip_archive: Set to True if you don't want the purged rows preserved in an archive table.
:param session: Session representing connection to the metadata database.
:param batch_size: Maximum number of rows to delete or archive in a single transaction.
"""
clean_before_timestamp = timezone.coerce_datetime(clean_before_timestamp)
# Get all tables to clean (root + dependents)
effective_table_names, effective_config_dict = _effective_table_names(table_names=table_names)
if dry_run:
print("Performing dry run for db cleanup.")
print(
f"Data prior to {clean_before_timestamp} would be purged "
f"from tables {effective_table_names} with the following config:\n"
)
_print_config(configs=effective_config_dict)
if not dry_run and confirm:
_confirm_delete(date=clean_before_timestamp, tables=sorted(effective_table_names))
existing_tables = reflect_tables(tables=None, session=session).tables
for table_name, table_config in effective_config_dict.items():
if table_name in existing_tables:
with _suppress_with_logging(table_name, session):
_cleanup_table(
clean_before_timestamp=clean_before_timestamp,
dry_run=dry_run,
verbose=verbose,
**table_config.__dict__,
skip_archive=skip_archive,
session=session,
batch_size=batch_size,
)
session.commit()
else:
logger.warning("Table %s not found. Skipping.", table_name)
@provide_session
def export_archived_records(
export_format: str,
output_path: str,
table_names: list[str] | None = None,
drop_archives: bool = False,
needs_confirm: bool = True,
session: Session = NEW_SESSION,
) -> None:
"""Export archived data to the given output path in the given format."""
archived_table_names = _get_archived_table_names(table_names, session)
# If user chose to drop archives, check there are archive tables that exists
# before asking for confirmation
if drop_archives and archived_table_names and needs_confirm:
_confirm_drop_archives(tables=sorted(archived_table_names))
export_count = 0
dropped_count = 0
for table_name in archived_table_names:
logger.info("Exporting table %s", table_name)
_dump_table_to_file(
target_table=table_name,
file_path=os.path.join(output_path, f"{table_name}.{export_format}"),
export_format=export_format,
session=session,
)
export_count += 1
if drop_archives:
logger.info("Dropping archived table %s", table_name)
session.execute(text(f"DROP TABLE {table_name}"))
dropped_count += 1
logger.info("Total exported tables: %s, Total dropped tables: %s", export_count, dropped_count)
@provide_session
def drop_archived_tables(
table_names: list[str] | None, needs_confirm: bool, session: Session = NEW_SESSION
) -> None:
"""Drop archived tables."""
archived_table_names = _get_archived_table_names(table_names, session)
if needs_confirm and archived_table_names:
_confirm_drop_archives(tables=sorted(archived_table_names))
dropped_count = 0
for table_name in archived_table_names:
logger.info("Dropping archived table %s", table_name)
session.execute(text(f"DROP TABLE {table_name}"))
dropped_count += 1
logger.info("Total dropped tables: %s", dropped_count)
| CreateTableAs |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/codegen/tiled/tiled_kernel_test.py | {
"start": 1020,
"end": 2650
} | class ____:
def __init__(self, shape: tuple[int, ...]):
"""Initializes the InputSpec.
Args:
shape: The shape of the input array.
"""
self.shape = shape
def get_random_array(shape: tuple[int, ...], dtype: np.dtype) -> np.ndarray:
rng = np.random.default_rng()
return rng.uniform(low=-5, high=5, size=shape).astype(dtype)
def compare_kernel(
ir: str,
kernel_name: str,
num_workgroups: int,
input_specs: Iterable[InputSpec],
output_shape: tuple[int, ...],
dtype,
expected_output: Callable[[np.ndarray, ...], np.ndarray],
maxulp: Optional[int] = None,
) -> None:
mlir_emitter = cpu_testlib.MlirTestKernelEmitter(
ir, kernel_name, (num_workgroups, 1, 1)
)
kernel_definition = mlir_emitter.emit_kernel_definition()
runner = cpu_testlib.KernelRunner.create(
kernel_definition,
cpu_testlib.JitCompiler(base_testlib.HloModuleConfig()),
)
def get_input(spec: InputSpec):
return np.arange(np.prod(spec.shape), dtype=dtype).reshape(spec.shape)
inputs = [get_input(spec) for spec in input_specs]
input_tensors = [create_literal(input) for input in inputs]
# Use a random array as the output to ensure all values are written to.
output_tensor = create_literal(get_random_array(output_shape, dtype))
runner.call(input_tensors + [output_tensor])
output_np = np.asarray(output_tensor)
expected_output_np = expected_output(*inputs)
if maxulp is None:
np.testing.assert_array_equal(output_np, expected_output_np)
else:
np.testing.assert_array_max_ulp(
output_np, expected_output_np, maxulp=maxulp
)
| InputSpec |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-oci-genai/llama_index/embeddings/oci_genai/base.py | {
"start": 534,
"end": 761
} | class ____(Enum):
"""OCI authentication types as enumerator."""
API_KEY = 1
SECURITY_TOKEN = 2
INSTANCE_PRINCIPAL = 3
RESOURCE_PRINCIPAL = 4
CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint"
| OCIAuthType |
python | Textualize__rich | examples/top_lite_simulator.py | {
"start": 275,
"end": 2063
} | class ____:
pid: int
command: str
cpu_percent: float
memory: int
start_time: datetime.datetime
thread_count: int
state: Literal["running", "sleeping"]
@property
def memory_str(self) -> str:
if self.memory > 1e6:
return f"{int(self.memory/1e6)}M"
if self.memory > 1e3:
return f"{int(self.memory/1e3)}K"
return str(self.memory)
@property
def time_str(self) -> str:
return str(datetime.datetime.now() - self.start_time)
def generate_process(pid: int) -> Process:
return Process(
pid=pid,
command=f"Process {pid}",
cpu_percent=random.random() * 20,
memory=random.randint(10, 200) ** 3,
start_time=datetime.datetime.now()
- datetime.timedelta(seconds=random.randint(0, 500) ** 2),
thread_count=random.randint(1, 32),
state="running" if random.randint(0, 10) < 8 else "sleeping",
)
def create_process_table(height: int) -> Table:
processes = sorted(
[generate_process(pid) for pid in range(height)],
key=lambda p: p.cpu_percent,
reverse=True,
)
table = Table(
"PID", "Command", "CPU %", "Memory", "Time", "Thread #", "State", box=box.SIMPLE
)
for process in processes:
table.add_row(
str(process.pid),
process.command,
f"{process.cpu_percent:.1f}",
process.memory_str,
process.time_str,
str(process.thread_count),
process.state,
)
return table
console = Console()
with Live(console=console, screen=True, auto_refresh=False) as live:
while True:
live.update(create_process_table(console.size.height - 4), refresh=True)
time.sleep(1)
| Process |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/methods/test_to_julian_date.py | {
"start": 31,
"end": 810
} | class ____:
def test_compare_1700(self):
ts = Timestamp("1700-06-23")
res = ts.to_julian_date()
assert res == 2_342_145.5
def test_compare_2000(self):
ts = Timestamp("2000-04-12")
res = ts.to_julian_date()
assert res == 2_451_646.5
def test_compare_2100(self):
ts = Timestamp("2100-08-12")
res = ts.to_julian_date()
assert res == 2_488_292.5
def test_compare_hour01(self):
ts = Timestamp("2000-08-12T01:00:00")
res = ts.to_julian_date()
assert res == 2_451_768.5416666666666666
def test_compare_hour13(self):
ts = Timestamp("2000-08-12T13:00:00")
res = ts.to_julian_date()
assert res == 2_451_769.0416666666666666
| TestTimestampToJulianDate |
python | scikit-learn__scikit-learn | sklearn/tests/metadata_routing_common.py | {
"start": 11019,
"end": 11436
} | class ____(ConsumingClassifier):
"""ConsumingClassifier without a predict_proba method, but with predict_log_proba.
Used to mimic dynamic method selection such as in the `_parallel_predict_proba()`
function called by `BaggingClassifier`.
"""
@property
def predict_proba(self):
raise AttributeError("This estimator does not support predict_proba")
| ConsumingClassifierWithoutPredictProba |
python | pytorch__pytorch | setup.py | {
"start": 47478,
"end": 48872
} | class ____:
"""Merge LICENSE and LICENSES_BUNDLED.txt as a context manager
LICENSE is the main PyTorch license, LICENSES_BUNDLED.txt is auto-generated
from all the licenses found in ./third_party/. We concatenate them so there
is a single license file in the sdist and wheels with all of the necessary
licensing info.
"""
def __init__(self, include_files: bool = False) -> None:
self.f1 = CWD / "LICENSE"
self.f2 = THIRD_PARTY_DIR / "LICENSES_BUNDLED.txt"
self.include_files = include_files
self.bsd_text = ""
def __enter__(self) -> None:
"""Concatenate files"""
old_path = sys.path
sys.path.append(str(THIRD_PARTY_DIR))
try:
from build_bundled import create_bundled # type: ignore[import-not-found]
finally:
sys.path = old_path
self.bsd_text = self.f1.read_text(encoding="utf-8")
with self.f1.open(mode="a", encoding="utf-8") as f1:
f1.write("\n\n")
create_bundled(
str(THIRD_PARTY_DIR.resolve()),
f1,
include_files=self.include_files,
)
def __exit__(self, *exc_info: object) -> None:
"""Restore content of f1"""
self.f1.write_text(self.bsd_text, encoding="utf-8")
# Need to create the proper LICENSE.txt for the wheel
| concat_license_files |
python | apache__airflow | airflow-core/tests/unit/utils/log/test_stream_accumulator.py | {
"start": 1239,
"end": 6381
} | class ____:
"""Test cases for the LogStreamAccumulator class."""
@pytest.fixture
def structured_logs(self):
"""Create a stream of mock structured log messages."""
def generate_logs():
yield from (
StructuredLogMessage(
event=f"test_event_{i + 1}",
timestamp=LOG_START_DATETIME.add(seconds=i),
level="INFO",
message=f"Test log message {i + 1}",
)
for i in range(LOG_COUNT)
)
return generate_logs()
def validate_log_stream(self, log_stream: LogHandlerOutputStream):
"""Validate the log stream by checking the number of lines."""
count = 0
for i, log in enumerate(log_stream):
assert log.event == f"test_event_{i + 1}"
assert log.timestamp == LOG_START_DATETIME.add(seconds=i)
count += 1
assert count == 20
def test__capture(self, structured_logs):
"""Test that temporary file is properly cleaned up during get_stream, not when exiting context."""
accumulator = LogStreamAccumulator(structured_logs, 5)
with (
mock.patch.object(accumulator, "_capture") as mock_setup,
):
with accumulator:
mock_setup.assert_called_once()
def test__flush_buffer_to_disk(self, structured_logs):
"""Test flush-to-disk behavior with a small threshold."""
threshold = 6
# Mock the temporary file to verify it's being written to
with (
mock.patch("tempfile.NamedTemporaryFile") as mock_tmpfile,
):
mock_file = mock.MagicMock()
mock_tmpfile.return_value = mock_file
with LogStreamAccumulator(structured_logs, threshold) as accumulator:
mock_tmpfile.assert_called_once_with(
delete=False,
mode="w+",
encoding="utf-8",
)
# Verify _flush_buffer_to_disk was called multiple times
# (20 logs / 6 threshold = 3 flushes + 2 remaining logs in buffer)
assert accumulator._disk_lines == 18
assert mock_file.writelines.call_count == 3
assert len(accumulator._buffer) == 2
@pytest.mark.parametrize(
"threshold",
[
pytest.param(30, id="buffer_only"),
pytest.param(5, id="flush_to_disk"),
],
)
def test_get_stream(self, structured_logs, threshold):
"""Test that stream property returns all logs regardless of whether they were flushed to disk."""
tmpfile_name = None
with LogStreamAccumulator(structured_logs, threshold) as accumulator:
out_stream = accumulator.stream
# Check if the temporary file was created
if threshold < LOG_COUNT:
tmpfile_name = accumulator._tmpfile.name
assert os.path.exists(tmpfile_name)
else:
assert accumulator._tmpfile is None
# Validate the log stream
self.validate_log_stream(out_stream)
# Verify temp file was created and cleaned up
if threshold < LOG_COUNT:
assert accumulator._tmpfile is None
assert not os.path.exists(tmpfile_name) if tmpfile_name else True
@pytest.mark.parametrize(
("threshold", "expected_buffer_size", "expected_disk_lines"),
[
pytest.param(30, 20, 0, id="no_flush_needed"),
pytest.param(10, 0, 20, id="single_flush_needed"),
pytest.param(3, 2, 18, id="multiple_flushes_needed"),
],
)
def test_total_lines(self, structured_logs, threshold, expected_buffer_size, expected_disk_lines):
"""Test that LogStreamAccumulator correctly counts lines across buffer and disk."""
with LogStreamAccumulator(structured_logs, threshold) as accumulator:
# Check buffer and disk line counts
assert len(accumulator._buffer) == expected_buffer_size
assert accumulator._disk_lines == expected_disk_lines
# Validate the log stream and line counts
self.validate_log_stream(accumulator.stream)
def test__cleanup(self, structured_logs):
"""Test that cleanup happens when stream property is fully consumed, not on context exit."""
accumulator = LogStreamAccumulator(structured_logs, 5)
with mock.patch.object(accumulator, "_cleanup") as mock_cleanup:
with accumulator:
# _cleanup should not be called yet
mock_cleanup.assert_not_called()
# Get the stream but don't iterate through it yet
stream = accumulator.stream
mock_cleanup.assert_not_called()
# Now iterate through the stream
for _ in stream:
pass
# After fully consuming the stream, cleanup should be called
mock_cleanup.assert_called_once()
| TestLogStreamAccumulator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/app/test_initialisation.py | {
"start": 289,
"end": 792
} | class ____(unittest.TestCase):
"""
Test initialisation of the App class and call a method.
"""
def setUp(self):
self.fh = StringIO()
self.app = App()
self.app._set_filehandle(self.fh)
def test_xml_declaration(self):
"""Test App xml_declaration()"""
self.app._xml_declaration()
exp = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n"""
got = self.fh.getvalue()
self.assertEqual(exp, got)
| TestInitialisation |
python | aio-libs__aiohttp | aiohttp/streams.py | {
"start": 2367,
"end": 16716
} | class ____(AsyncStreamReaderMixin):
"""An enhancement of asyncio.StreamReader.
Supports asynchronous iteration by line, chunk or as available::
async for line in reader:
...
async for chunk in reader.iter_chunked(1024):
...
async for slice in reader.iter_any():
...
"""
__slots__ = (
"_protocol",
"_low_water",
"_high_water",
"_loop",
"_size",
"_cursor",
"_http_chunk_splits",
"_buffer",
"_buffer_offset",
"_eof",
"_waiter",
"_eof_waiter",
"_exception",
"_timer",
"_eof_callbacks",
"_eof_counter",
"total_bytes",
"total_compressed_bytes",
)
def __init__(
self,
protocol: BaseProtocol,
limit: int,
*,
timer: BaseTimerContext | None = None,
loop: asyncio.AbstractEventLoop,
) -> None:
self._protocol = protocol
self._low_water = limit
self._high_water = limit * 2
self._loop = loop
self._size = 0
self._cursor = 0
self._http_chunk_splits: list[int] | None = None
self._buffer: collections.deque[bytes] = collections.deque()
self._buffer_offset = 0
self._eof = False
self._waiter: asyncio.Future[None] | None = None
self._eof_waiter: asyncio.Future[None] | None = None
self._exception: type[BaseException] | BaseException | None = None
self._timer = TimerNoop() if timer is None else timer
self._eof_callbacks: list[Callable[[], None]] = []
self._eof_counter = 0
self.total_bytes = 0
self.total_compressed_bytes: int | None = None
def __repr__(self) -> str:
info = [self.__class__.__name__]
if self._size:
info.append("%d bytes" % self._size)
if self._eof:
info.append("eof")
if self._low_water != 2**16: # default limit
info.append("low=%d high=%d" % (self._low_water, self._high_water))
if self._waiter:
info.append("w=%r" % self._waiter)
if self._exception:
info.append("e=%r" % self._exception)
return "<%s>" % " ".join(info)
def get_read_buffer_limits(self) -> tuple[int, int]:
return (self._low_water, self._high_water)
def exception(self) -> type[BaseException] | BaseException | None:
return self._exception
def set_exception(
self,
exc: type[BaseException] | BaseException,
exc_cause: BaseException = _EXC_SENTINEL,
) -> None:
self._exception = exc
self._eof_callbacks.clear()
waiter = self._waiter
if waiter is not None:
self._waiter = None
set_exception(waiter, exc, exc_cause)
waiter = self._eof_waiter
if waiter is not None:
self._eof_waiter = None
set_exception(waiter, exc, exc_cause)
def on_eof(self, callback: Callable[[], None]) -> None:
if self._eof:
try:
callback()
except Exception:
internal_logger.exception("Exception in eof callback")
else:
self._eof_callbacks.append(callback)
def feed_eof(self) -> None:
self._eof = True
waiter = self._waiter
if waiter is not None:
self._waiter = None
set_result(waiter, None)
waiter = self._eof_waiter
if waiter is not None:
self._eof_waiter = None
set_result(waiter, None)
if self._protocol._reading_paused:
self._protocol.resume_reading()
for cb in self._eof_callbacks:
try:
cb()
except Exception:
internal_logger.exception("Exception in eof callback")
self._eof_callbacks.clear()
def is_eof(self) -> bool:
"""Return True if 'feed_eof' was called."""
return self._eof
def at_eof(self) -> bool:
"""Return True if the buffer is empty and 'feed_eof' was called."""
return self._eof and not self._buffer
async def wait_eof(self) -> None:
if self._eof:
return
assert self._eof_waiter is None
self._eof_waiter = self._loop.create_future()
try:
await self._eof_waiter
finally:
self._eof_waiter = None
@property
def total_raw_bytes(self) -> int:
if self.total_compressed_bytes is None:
return self.total_bytes
return self.total_compressed_bytes
def unread_data(self, data: bytes) -> None:
"""rollback reading some data from stream, inserting it to buffer head."""
warnings.warn(
"unread_data() is deprecated "
"and will be removed in future releases (#3260)",
DeprecationWarning,
stacklevel=2,
)
if not data:
return
if self._buffer_offset:
self._buffer[0] = self._buffer[0][self._buffer_offset :]
self._buffer_offset = 0
self._size += len(data)
self._cursor -= len(data)
self._buffer.appendleft(data)
self._eof_counter = 0
def feed_data(self, data: bytes) -> None:
assert not self._eof, "feed_data after feed_eof"
if not data:
return
data_len = len(data)
self._size += data_len
self._buffer.append(data)
self.total_bytes += data_len
waiter = self._waiter
if waiter is not None:
self._waiter = None
set_result(waiter, None)
if self._size > self._high_water and not self._protocol._reading_paused:
self._protocol.pause_reading()
def begin_http_chunk_receiving(self) -> None:
if self._http_chunk_splits is None:
if self.total_bytes:
raise RuntimeError(
"Called begin_http_chunk_receiving when some data was already fed"
)
self._http_chunk_splits = []
def end_http_chunk_receiving(self) -> None:
if self._http_chunk_splits is None:
raise RuntimeError(
"Called end_chunk_receiving without calling "
"begin_chunk_receiving first"
)
# self._http_chunk_splits contains logical byte offsets from start of
# the body transfer. Each offset is the offset of the end of a chunk.
# "Logical" means bytes, accessible for a user.
# If no chunks containing logical data were received, current position
# is difinitely zero.
pos = self._http_chunk_splits[-1] if self._http_chunk_splits else 0
if self.total_bytes == pos:
# We should not add empty chunks here. So we check for that.
# Note, when chunked + gzip is used, we can receive a chunk
# of compressed data, but that data may not be enough for gzip FSM
# to yield any uncompressed data. That's why current position may
# not change after receiving a chunk.
return
self._http_chunk_splits.append(self.total_bytes)
# wake up readchunk when end of http chunk received
waiter = self._waiter
if waiter is not None:
self._waiter = None
set_result(waiter, None)
async def _wait(self, func_name: str) -> None:
if not self._protocol.connected:
raise RuntimeError("Connection closed.")
# StreamReader uses a future to link the protocol feed_data() method
# to a read coroutine. Running two read coroutines at the same time
# would have an unexpected behaviour. It would not possible to know
# which coroutine would get the next data.
if self._waiter is not None:
raise RuntimeError(
"%s() called while another coroutine is "
"already waiting for incoming data" % func_name
)
waiter = self._waiter = self._loop.create_future()
try:
with self._timer:
await waiter
finally:
self._waiter = None
async def readline(self) -> bytes:
return await self.readuntil()
async def readuntil(self, separator: bytes = b"\n") -> bytes:
seplen = len(separator)
if seplen == 0:
raise ValueError("Separator should be at least one-byte string")
if self._exception is not None:
raise self._exception
chunk = b""
chunk_size = 0
not_enough = True
while not_enough:
while self._buffer and not_enough:
offset = self._buffer_offset
ichar = self._buffer[0].find(separator, offset) + 1
# Read from current offset to found separator or to the end.
data = self._read_nowait_chunk(
ichar - offset + seplen - 1 if ichar else -1
)
chunk += data
chunk_size += len(data)
if ichar:
not_enough = False
if chunk_size > self._high_water:
raise ValueError("Chunk too big")
if self._eof:
break
if not_enough:
await self._wait("readuntil")
return chunk
async def read(self, n: int = -1) -> bytes:
if self._exception is not None:
raise self._exception
if not n:
return b""
if n < 0:
# This used to just loop creating a new waiter hoping to
# collect everything in self._buffer, but that would
# deadlock if the subprocess sends more than self.limit
# bytes. So just call self.readany() until EOF.
blocks = []
while True:
block = await self.readany()
if not block:
break
blocks.append(block)
return b"".join(blocks)
# TODO: should be `if` instead of `while`
# because waiter maybe triggered on chunk end,
# without feeding any data
while not self._buffer and not self._eof:
await self._wait("read")
return self._read_nowait(n)
async def readany(self) -> bytes:
if self._exception is not None:
raise self._exception
# TODO: should be `if` instead of `while`
# because waiter maybe triggered on chunk end,
# without feeding any data
while not self._buffer and not self._eof:
await self._wait("readany")
return self._read_nowait(-1)
async def readchunk(self) -> tuple[bytes, bool]:
"""Returns a tuple of (data, end_of_http_chunk).
When chunked transfer
encoding is used, end_of_http_chunk is a boolean indicating if the end
of the data corresponds to the end of a HTTP chunk , otherwise it is
always False.
"""
while True:
if self._exception is not None:
raise self._exception
while self._http_chunk_splits:
pos = self._http_chunk_splits.pop(0)
if pos == self._cursor:
return (b"", True)
if pos > self._cursor:
return (self._read_nowait(pos - self._cursor), True)
internal_logger.warning(
"Skipping HTTP chunk end due to data "
"consumption beyond chunk boundary"
)
if self._buffer:
return (self._read_nowait_chunk(-1), False)
# return (self._read_nowait(-1), False)
if self._eof:
# Special case for signifying EOF.
# (b'', True) is not a final return value actually.
return (b"", False)
await self._wait("readchunk")
async def readexactly(self, n: int) -> bytes:
if self._exception is not None:
raise self._exception
blocks: list[bytes] = []
while n > 0:
block = await self.read(n)
if not block:
partial = b"".join(blocks)
raise asyncio.IncompleteReadError(partial, len(partial) + n)
blocks.append(block)
n -= len(block)
return b"".join(blocks)
def read_nowait(self, n: int = -1) -> bytes:
# default was changed to be consistent with .read(-1)
#
# I believe the most users don't know about the method and
# they are not affected.
if self._exception is not None:
raise self._exception
if self._waiter and not self._waiter.done():
raise RuntimeError(
"Called while some coroutine is waiting for incoming data."
)
return self._read_nowait(n)
def _read_nowait_chunk(self, n: int) -> bytes:
first_buffer = self._buffer[0]
offset = self._buffer_offset
if n != -1 and len(first_buffer) - offset > n:
data = first_buffer[offset : offset + n]
self._buffer_offset += n
elif offset:
self._buffer.popleft()
data = first_buffer[offset:]
self._buffer_offset = 0
else:
data = self._buffer.popleft()
data_len = len(data)
self._size -= data_len
self._cursor += data_len
chunk_splits = self._http_chunk_splits
# Prevent memory leak: drop useless chunk splits
while chunk_splits and chunk_splits[0] < self._cursor:
chunk_splits.pop(0)
if self._size < self._low_water and self._protocol._reading_paused:
self._protocol.resume_reading()
return data
def _read_nowait(self, n: int) -> bytes:
"""Read not more than n bytes, or whole buffer if n == -1"""
self._timer.assert_timeout()
chunks = []
while self._buffer:
chunk = self._read_nowait_chunk(n)
chunks.append(chunk)
if n != -1:
n -= len(chunk)
if n == 0:
break
return b"".join(chunks) if chunks else b""
| StreamReader |
python | dask__distributed | distributed/utils.py | {
"start": 9476,
"end": 12969
} | class ____:
"""
A mixin for adding an `asynchronous` attribute and `sync` method to a class.
Subclasses must define a `loop` attribute for an associated
`tornado.IOLoop`, and may also add a `_asynchronous` attribute indicating
whether the class should default to asynchronous behavior.
"""
@property
def asynchronous(self):
"""Are we running in the event loop?"""
try:
return in_async_call(
self.loop, default=getattr(self, "_asynchronous", False)
)
except RuntimeError:
return False
def sync(self, func, *args, asynchronous=None, callback_timeout=None, **kwargs):
"""Call `func` with `args` synchronously or asynchronously depending on
the calling context"""
callback_timeout = _parse_timedelta(callback_timeout)
if asynchronous is None:
asynchronous = self.asynchronous
if asynchronous:
future = func(*args, **kwargs)
if callback_timeout is not None:
future = wait_for(future, callback_timeout)
return future
else:
return sync(
self.loop, func, *args, callback_timeout=callback_timeout, **kwargs
)
def in_async_call(loop, default=False):
"""Whether this call is currently within an async call"""
try:
return loop.asyncio_loop is asyncio.get_running_loop()
except RuntimeError:
# No *running* loop in thread. If the event loop isn't running, it
# _could_ be started later in this thread though. Return the default.
if not loop.asyncio_loop.is_running():
return default
return False
def sync(
loop: IOLoop,
func: Callable[..., Awaitable[T]],
*args: AnyType,
callback_timeout: str | float | timedelta | None = None,
**kwargs: AnyType,
) -> T:
"""
Run coroutine in loop running in separate thread.
"""
timeout = _parse_timedelta(callback_timeout, "s")
if loop.asyncio_loop.is_closed(): # type: ignore[attr-defined]
raise RuntimeError("IOLoop is closed")
e = threading.Event()
main_tid = threading.get_ident()
# set up non-locals
result: T
error: BaseException | None = None
future: asyncio.Future[T]
@gen.coroutine
def f() -> Generator[AnyType, AnyType, None]:
nonlocal result, error, future
try:
if main_tid == threading.get_ident():
raise RuntimeError("sync() called from thread of running loop")
yield gen.moment
awaitable = func(*args, **kwargs)
if timeout is not None:
awaitable = wait_for(awaitable, timeout)
future = asyncio.ensure_future(awaitable)
result = yield future
except Exception as exception:
error = exception
finally:
e.set()
def cancel() -> None:
if future is not None:
future.cancel()
def wait(timeout: float | None) -> bool:
try:
return e.wait(timeout)
except KeyboardInterrupt:
loop.add_callback(cancel)
raise
loop.add_callback(f)
if timeout is not None:
if not wait(timeout):
raise TimeoutError(f"timed out after {timeout} s.")
else:
while not e.is_set():
wait(10)
if error is not None:
raise error
else:
return result
| SyncMethodMixin |
python | getsentry__sentry | src/sentry/uptime/endpoints/project_uptime_alert_checks_index.py | {
"start": 1744,
"end": 8374
} | class ____(ProjectUptimeAlertEndpoint):
owner = ApiOwner.CRONS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(
self,
request: Request,
project: Project,
uptime_detector: Detector,
) -> Response:
uptime_subscription = get_uptime_subscription(uptime_detector)
if uptime_subscription.subscription_id is None:
return Response([])
start, end = get_date_range_from_params(request.GET)
def data_fn(offset: int, limit: int) -> Any:
try:
return self._make_eap_request(
project,
uptime_subscription,
offset,
limit,
start,
end,
)
except Exception:
logger.exception("Error making EAP RPC request for uptime alert checks")
return []
with handle_query_errors():
return self.paginate(
request,
paginator=GenericOffsetPaginator(data_fn=data_fn),
default_per_page=10,
max_per_page=100,
)
def _make_eap_request(
self,
project: Project,
uptime_subscription: UptimeSubscription,
offset: int,
limit: int,
start: datetime,
end: datetime,
) -> list[EapCheckEntrySerializerResponse]:
start_timestamp = Timestamp()
start_timestamp.FromDatetime(start)
end_timestamp = Timestamp()
end_timestamp.FromDatetime(end)
subscription_id = uuid.UUID(uptime_subscription.subscription_id).hex
subscription_filter = TraceItemFilter(
comparison_filter=ComparisonFilter(
key=AttributeKey(
name="subscription_id",
type=AttributeKey.Type.TYPE_STRING,
),
op=ComparisonFilter.OP_EQUALS,
value=AttributeValue(val_str=subscription_id),
)
)
request_sequence_filter = TraceItemFilter(
comparison_filter=ComparisonFilter(
key=AttributeKey(
name="request_sequence",
type=AttributeKey.Type.TYPE_INT,
),
op=ComparisonFilter.OP_EQUALS,
value=AttributeValue(val_int=0),
)
)
query_filter = TraceItemFilter(
and_filter=AndFilter(filters=[subscription_filter, request_sequence_filter])
)
rpc_request = TraceItemTableRequest(
meta=RequestMeta(
referrer="uptime_alert_checks_index",
organization_id=project.organization.id,
project_ids=[project.id],
trace_item_type=TraceItemType.TRACE_ITEM_TYPE_UPTIME_RESULT,
start_timestamp=start_timestamp,
end_timestamp=end_timestamp,
downsampled_storage_config=DownsampledStorageConfig(
mode=DownsampledStorageConfig.MODE_HIGHEST_ACCURACY
),
),
filter=query_filter,
columns=get_columns_for_uptime_result(),
order_by=[
TraceItemTableRequest.OrderBy(
column=Column(
label="sentry.timestamp",
key=AttributeKey(
name="sentry.timestamp",
type=AttributeKey.Type.TYPE_DOUBLE,
),
),
descending=True,
)
],
limit=limit,
page_token=PageToken(offset=offset),
)
return self._serialize_response(snuba_rpc.table_rpc([rpc_request])[0])
def _serialize_response(
self, rpc_response: TraceItemTableResponse
) -> list[EapCheckEntrySerializerResponse]:
"""
Serialize the response from the EAP into a list of items per each uptime check.
"""
column_values = rpc_response.column_values
if not column_values:
return []
column_names = [cv.attribute_name for cv in column_values]
entries: list[EapCheckEntry] = [
self._transform_row(row_idx, column_values, column_names)
for row_idx in range(len(column_values[0].results))
]
return serialize(entries)
def _transform_row(
self,
row_idx: int,
column_values: Any,
column_names: list[str],
) -> EapCheckEntry:
row_dict: dict[str, AttributeValue] = {
col_name: column_values[col_idx].results[row_idx]
for col_idx, col_name in enumerate(column_names)
}
uptime_check_id = row_dict["check_id"].val_str
scheduled_check_time = datetime.fromtimestamp(
row_dict["scheduled_check_time_us"].val_int / 1_000_000
)
duration_val = row_dict.get("check_duration_us")
duration_ms = (
(duration_val.val_int // 1000) if duration_val and not duration_val.is_null else 0
)
trace_id = row_dict["sentry.trace_id"].val_str
return EapCheckEntry(
uptime_check_id=uptime_check_id,
timestamp=datetime.fromtimestamp(row_dict["sentry.timestamp"].val_double),
scheduled_check_time=scheduled_check_time,
check_status=cast(CheckStatus, row_dict["check_status"].val_str),
check_status_reason=self._extract_check_status_reason(
row_dict.get("check_status_reason")
),
http_status_code=(
None
if row_dict["http_status_code"].is_null
else row_dict["http_status_code"].val_int
),
duration_ms=duration_ms,
trace_id=trace_id,
incident_status=IncidentStatus(row_dict["incident_status"].val_int),
environment=row_dict.get("environment", AttributeValue(val_str="")).val_str,
region=row_dict["region"].val_str,
)
def _extract_check_status_reason(
self, check_status_reason_val: AttributeValue | None
) -> CheckStatusReasonType | None:
"""Extract check status reason from attribute value, handling null/empty cases."""
if not check_status_reason_val or check_status_reason_val.is_null:
return None
val_str = check_status_reason_val.val_str
return cast(CheckStatusReasonType, val_str) if val_str != "" else None
| ProjectUptimeAlertCheckIndexEndpoint |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 3863,
"end": 4763
} | class ____(Node):
""" Represents a subroutine in Fortran.
Examples
========
>>> from sympy import fcode, symbols
>>> from sympy.codegen.ast import Print
>>> from sympy.codegen.fnodes import Subroutine
>>> x, y = symbols('x y', real=True)
>>> sub = Subroutine('mysub', [x, y], [Print([x**2 + y**2, x*y])])
>>> print(fcode(sub, source_format='free', standard=2003))
subroutine mysub(x, y)
real*8 :: x
real*8 :: y
print *, x**2 + y**2, x*y
end subroutine
"""
__slots__ = ('name', 'parameters', 'body')
_fields = __slots__ + Node._fields
_construct_name = String
_construct_parameters = staticmethod(lambda params: Tuple(*map(Variable.deduced, params)))
@classmethod
def _construct_body(cls, itr):
if isinstance(itr, CodeBlock):
return itr
else:
return CodeBlock(*itr)
| Subroutine |
python | django__django | tests/admin_inlines/admin.py | {
"start": 1960,
"end": 2512
} | class ____:
model = Photo
extra = 2
fieldsets = [
(None, {"fields": ["image", "title"], "description": "First group"}),
(
"Details",
{
"fields": ["description", "creation_date"],
"classes": ["collapse"],
"description": "Second group",
},
),
(
"Details", # Fieldset name intentionally duplicated
{"fields": ["update_date", "updated_by"], "description": "Third group"},
),
]
| PhotoInlineMixin |
python | MongoEngine__mongoengine | tests/fields/test_enum_field.py | {
"start": 293,
"end": 339
} | class ____(Enum):
RED = 1
BLUE = 2
| Color |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1595428,
"end": 1597270
} | class ____(sgqlc.types.Union):
"""An item in a pull request timeline"""
__schema__ = github_schema
__types__ = (
AddedToMergeQueueEvent,
AddedToProjectEvent,
AssignedEvent,
AutoMergeDisabledEvent,
AutoMergeEnabledEvent,
AutoRebaseEnabledEvent,
AutoSquashEnabledEvent,
AutomaticBaseChangeFailedEvent,
AutomaticBaseChangeSucceededEvent,
BaseRefChangedEvent,
BaseRefDeletedEvent,
BaseRefForcePushedEvent,
ClosedEvent,
CommentDeletedEvent,
ConnectedEvent,
ConvertToDraftEvent,
ConvertedNoteToIssueEvent,
ConvertedToDiscussionEvent,
CrossReferencedEvent,
DemilestonedEvent,
DeployedEvent,
DeploymentEnvironmentChangedEvent,
DisconnectedEvent,
HeadRefDeletedEvent,
HeadRefForcePushedEvent,
HeadRefRestoredEvent,
IssueComment,
LabeledEvent,
LockedEvent,
MarkedAsDuplicateEvent,
MentionedEvent,
MergedEvent,
MilestonedEvent,
MovedColumnsInProjectEvent,
PinnedEvent,
PullRequestCommit,
PullRequestCommitCommentThread,
PullRequestReview,
PullRequestReviewThread,
PullRequestRevisionMarker,
ReadyForReviewEvent,
ReferencedEvent,
RemovedFromMergeQueueEvent,
RemovedFromProjectEvent,
RenamedTitleEvent,
ReopenedEvent,
ReviewDismissedEvent,
ReviewRequestRemovedEvent,
ReviewRequestedEvent,
SubscribedEvent,
TransferredEvent,
UnassignedEvent,
UnlabeledEvent,
UnlockedEvent,
UnmarkedAsDuplicateEvent,
UnpinnedEvent,
UnsubscribedEvent,
UserBlockedEvent,
)
| PullRequestTimelineItems |
python | pandas-dev__pandas | pandas/io/sas/sas7bdat.py | {
"start": 2384,
"end": 3002
} | class ____:
col_id: int
name: str | bytes
label: str | bytes
format: str | bytes
ctype: bytes
length: int
def __init__(
self,
col_id: int,
# These can be bytes when convert_header_text is False
name: str | bytes,
label: str | bytes,
format: str | bytes,
ctype: bytes,
length: int,
) -> None:
self.col_id = col_id
self.name = name
self.label = label
self.format = format
self.ctype = ctype
self.length = length
# SAS7BDAT represents a SAS data file in SAS7BDAT format.
| _Column |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 3849,
"end": 14231
} | class ____(__TestCase):
def test_contextmanager_plain(self):
state = []
@contextmanager
def woohoo():
state.append(1)
yield 42
state.append(999)
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_finally(self):
state = []
@contextmanager
def woohoo():
state.append(1)
try:
yield 42
finally:
state.append(999)
with self.assertRaises(ZeroDivisionError):
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
raise ZeroDivisionError()
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_traceback(self):
@contextmanager
def f():
yield
try:
with f():
1/0
except ZeroDivisionError as e:
frames = traceback.extract_tb(e.__traceback__)
self.assertEqual(len(frames), 1)
self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
self.assertEqual(frames[0].line, '1/0')
# Repeat with RuntimeError (which goes through a different code path)
with torch._dynamo.error_on_graph_break(False):
class RuntimeErrorSubclass(RuntimeError):
pass
try:
with f():
raise RuntimeErrorSubclass(42)
except RuntimeErrorSubclass as e:
frames = traceback.extract_tb(e.__traceback__)
self.assertEqual(len(frames), 1)
self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
self.assertEqual(frames[0].line, 'raise RuntimeErrorSubclass(42)')
with torch._dynamo.error_on_graph_break(False):
class StopIterationSubclass(StopIteration):
pass
for stop_exc in (
StopIteration('spam'),
StopIterationSubclass('spam'),
):
with self.subTest(type=type(stop_exc)):
try:
with f():
raise stop_exc
except type(stop_exc) as e:
self.assertIs(e, stop_exc)
frames = traceback.extract_tb(e.__traceback__)
else:
self.fail(f'{stop_exc} was suppressed')
self.assertEqual(len(frames), 1)
self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
self.assertEqual(frames[0].line, 'raise stop_exc')
def test_contextmanager_no_reraise(self):
@contextmanager
def whee():
yield
ctx = whee()
ctx.__enter__()
# Calling __exit__ should not result in an exception
self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None))
def test_contextmanager_trap_yield_after_throw(self):
@contextmanager
def whoo():
try:
yield
except:
yield
ctx = whoo()
ctx.__enter__()
with self.assertRaises(RuntimeError):
ctx.__exit__(TypeError, TypeError("foo"), None)
# if support.check_impl_detail(cpython=True):
# # The "gen" attribute is an implementation detail.
# self.assertFalse(ctx.gen.gi_suspended)
def test_contextmanager_trap_no_yield(self):
@contextmanager
def whoo():
if False:
yield
ctx = whoo()
with self.assertRaises(RuntimeError):
ctx.__enter__()
def test_contextmanager_trap_second_yield(self):
@contextmanager
def whoo():
yield
yield
ctx = whoo()
ctx.__enter__()
with self.assertRaises(RuntimeError):
ctx.__exit__(None, None, None)
# if support.check_impl_detail(cpython=True):
# # The "gen" attribute is an implementation detail.
# self.assertFalse(ctx.gen.gi_suspended)
def test_contextmanager_non_normalised(self):
@contextmanager
def whoo():
try:
yield
except RuntimeError:
raise SyntaxError
ctx = whoo()
ctx.__enter__()
with self.assertRaises(SyntaxError):
ctx.__exit__(RuntimeError, None, None)
def test_contextmanager_except(self):
state = []
@contextmanager
def woohoo():
state.append(1)
try:
yield 42
except ZeroDivisionError as e:
state.append(e.args[0])
self.assertEqual(state, [1, 42, 999])
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
state.append(x)
raise ZeroDivisionError(999)
self.assertEqual(state, [1, 42, 999])
def test_contextmanager_except_stopiter(self):
@contextmanager
def woohoo():
yield
with torch._dynamo.error_on_graph_break(False):
class StopIterationSubclass(StopIteration):
pass
for stop_exc in (StopIteration('spam'), StopIterationSubclass('spam')):
with self.subTest(type=type(stop_exc)):
try:
with woohoo():
raise stop_exc
except Exception as ex:
self.assertIs(ex, stop_exc)
else:
self.fail(f'{stop_exc} was suppressed')
def test_contextmanager_except_pep479(self):
code = """\
from __future__ import generator_stop
from contextlib import contextmanager
@contextmanager
def woohoo():
yield
"""
locals = {}
exec(code, locals, locals)
woohoo = locals['woohoo']
stop_exc = StopIteration('spam')
try:
with woohoo():
raise stop_exc
except Exception as ex:
self.assertIs(ex, stop_exc)
else:
self.fail('StopIteration was suppressed')
def test_contextmanager_do_not_unchain_non_stopiteration_exceptions(self):
@contextmanager
def test_issue29692():
try:
yield
except Exception as exc:
raise RuntimeError('issue29692:Chained') from exc
try:
with test_issue29692():
raise ZeroDivisionError
except Exception as ex:
self.assertIs(type(ex), RuntimeError)
self.assertEqual(ex.args[0], 'issue29692:Chained')
self.assertIsInstance(ex.__cause__, ZeroDivisionError)
try:
with test_issue29692():
raise StopIteration('issue29692:Unchained')
except Exception as ex:
self.assertIs(type(ex), StopIteration)
self.assertEqual(ex.args[0], 'issue29692:Unchained')
self.assertIsNone(ex.__cause__)
def test_contextmanager_wrap_runtimeerror(self):
@contextmanager
def woohoo():
try:
yield
except Exception as exc:
raise RuntimeError(f'caught {exc}') from exc
with self.assertRaises(RuntimeError):
with woohoo():
1 / 0
# If the context manager wrapped StopIteration in a RuntimeError,
# we also unwrap it, because we can't tell whether the wrapping was
# done by the generator machinery or by the generator itself.
with self.assertRaises(StopIteration):
with woohoo():
raise StopIteration
def _create_contextmanager_attribs(self):
def attribs(**kw):
def decorate(func):
for k,v in kw.items():
setattr(func,k,v)
return func
return decorate
@contextmanager
@attribs(foo='bar')
def baz(spam):
"""Whee!"""
yield
return baz
def test_contextmanager_attribs(self):
baz = self._create_contextmanager_attribs()
self.assertEqual(baz.__name__,'baz')
self.assertEqual(baz.foo, 'bar')
@support.requires_docstrings
def test_contextmanager_doc_attrib(self):
baz = self._create_contextmanager_attribs()
self.assertEqual(baz.__doc__, "Whee!")
@support.requires_docstrings
def test_instance_docstring_given_cm_docstring(self):
baz = self._create_contextmanager_attribs()(None)
self.assertEqual(baz.__doc__, "Whee!")
def test_keywords(self):
# Ensure no keyword arguments are inhibited
@contextmanager
def woohoo(self, func, args, kwds):
yield (self, func, args, kwds)
with woohoo(self=11, func=22, args=33, kwds=44) as target:
self.assertEqual(target, (11, 22, 33, 44))
def test_nokeepref(self):
with torch._dynamo.error_on_graph_break(False):
class A:
pass
@contextmanager
def woohoo(a, b):
a = weakref.ref(a)
b = weakref.ref(b)
# Allow test to work with a non-refcounted GC
support.gc_collect()
self.assertIsNone(a())
self.assertIsNone(b())
yield
with woohoo(A(), b=A()):
pass
def test_param_errors(self):
@contextmanager
def woohoo(a, *, b):
yield
with self.assertRaises(TypeError):
woohoo()
with self.assertRaises(TypeError):
woohoo(3, 5)
with self.assertRaises(TypeError):
woohoo(b=3)
def test_recursive(self):
depth = 0
ncols = 0
@contextmanager
def woohoo():
nonlocal ncols
ncols += 1
nonlocal depth
before = depth
depth += 1
yield
depth -= 1
self.assertEqual(depth, before)
@woohoo()
def recursive():
if depth < 10:
recursive()
recursive()
self.assertEqual(ncols, 10)
self.assertEqual(depth, 0)
| ContextManagerTestCase |
python | qdrant__qdrant-client | qdrant_client/auth/bearer_auth.py | {
"start": 87,
"end": 1567
} | class ____(httpx.Auth):
def __init__(
self,
auth_token_provider: Union[Callable[[], str], Callable[[], Awaitable[str]]],
):
self.async_token: Optional[Callable[[], Awaitable[str]]] = None
self.sync_token: Optional[Callable[[], str]] = None
if asyncio.iscoroutinefunction(auth_token_provider):
self.async_token = auth_token_provider
else:
if callable(auth_token_provider):
self.sync_token = auth_token_provider # type: ignore
else:
raise ValueError("auth_token_provider must be a callable or awaitable")
def _sync_get_token(self) -> str:
if self.sync_token is None:
raise ValueError("Synchronous token provider is not set.")
return self.sync_token()
def sync_auth_flow(self, request: httpx.Request) -> httpx.Request:
token = self._sync_get_token()
request.headers["Authorization"] = f"Bearer {token}"
yield request
async def _async_get_token(self) -> str:
if self.async_token is not None:
return await self.async_token() # type: ignore
# Fallback to synchronous token if asynchronous token is not available
return self._sync_get_token()
async def async_auth_flow(self, request: httpx.Request) -> httpx.Request:
token = await self._async_get_token()
request.headers["Authorization"] = f"Bearer {token}"
yield request
| BearerAuth |
python | realpython__materials | python-class/shapes.py | {
"start": 567,
"end": 714
} | class ____:
side = PositiveNumber()
def __init__(self, side):
self.side = side
def area(self):
return self.side**2
| Square |
python | facelessuser__soupsieve | tests/test_level4/test_out_of_range.py | {
"start": 57,
"end": 10928
} | class ____(util.TestCase):
"""Test out of range selectors."""
def test_out_of_range_number(self):
"""Test in range number."""
markup = """
<!-- These should not match -->
<input id="0" type="number" min="0" max="10" value="5">
<input id="1" type="number" min="-1" max="10" value="5">
<input id="2" type="number" min="2.2" max="8.8" value="5.2">
<input id="3" type="number" min="2.2" value="5.2">
<input id="4" type="number" max="8.8" value="5.2">
<input id="5" type="number" min="2.2" value="2.2">
<input id="6" type="number" max="8.8" value="8.8">
<input id="7" type="number" max="8.8">
<input id="8" type="number" max="8.8" value="invalid">
<!-- These should match -->
<input id="9" type="number" min="0" max="10" value="-1">
<input id="10" type="number" min="0" max="10" value="10.1">
<input id="11" type="number" max="0" min="10" value="11">
<!-- These cannot match -->
<input id="12" type="number" value="10">
<input id="13" type="number" min="invalid" value="10">
"""
self.assert_selector(
markup,
":out-of-range",
['9', '10', '11'],
flags=util.HTML
)
def test_out_of_range_range(self):
"""Test in range range."""
markup = """
<!-- These should not match -->
<input id="0" type="range" min="0" max="10" value="5">
<input id="1" type="range" min="-1" max="10" value="5">
<input id="2" type="range" min="2.2" max="8.8" value="5.2">
<input id="3" type="range" min="2.2" value="5.2">
<input id="4" type="range" max="8.8" value="5.2">
<input id="5" type="range" min="2.2" value="2.2">
<input id="6" type="range" max="8.8" value="8.8">
<input id="7" type="range" max="8.8">
<input id="8" type="range" max="8.8" value="invalid">
<!-- These should match -->
<input id="9" type="range" min="0" max="10" value="-1">
<input id="10" type="range" min="0" max="10" value="10.1">
<!-- These cannot match -->
<input id="11" type="range" value="10">
<input id="12" type="range" min="invalid" value="10">
"""
self.assert_selector(
markup,
":out-of-range",
['9', '10'],
flags=util.HTML
)
def test_out_of_range_month(self):
"""Test in range month."""
markup = """
<!-- These should not match -->
<input id="0" type="month" min="1980-02" max="2004-08" value="1999-05">
<input id="1" type="month" min="1980-02" max="2004-08" value="1980-02">
<input id="2" type="month" min="1980-02" max="2004-08" value="2004-08">
<input id="3" type="month" min="1980-02" value="1999-05">
<input id="4" type="month" max="2004-08" value="1999-05">
<input id="5" type="month" min="1980-02" max="2004-08" value="1999-13">
<input id="6" type="month" min="1980-02" max="2004-08">
<!-- These should match -->
<input id="7" type="month" min="1980-02" max="2004-08" value="1979-02">
<input id="8" type="month" min="1980-02" max="2004-08" value="1980-01">
<input id="9" type="month" min="1980-02" max="2004-08" value="2005-08">
<input id="10" type="month" min="1980-02" max="2004-08" value="2004-09">
<!-- These cannot match -->
<input id="11" type="month" value="1999-05">
<input id="12" type="month" min="invalid" value="1999-05">
"""
self.assert_selector(
markup,
":out-of-range",
['7', '8', '9', '10'],
flags=util.HTML
)
def test_out_of_range_week(self):
"""Test in range week."""
markup = """
<!-- These should not match -->
<input id="0" type="week" min="1980-W53" max="2004-W20" value="1999-W05">
<input id="1" type="week" min="1980-W53" max="2004-W20" value="1980-W53">
<input id="2" type="week" min="1980-W53" max="2004-W20" value="2004-W20">
<input id="3" type="week" min="1980-W53" value="1999-W05">
<input id="4" type="week" max="2004-W20" value="1999-W05">
<input id="5" type="week" min="1980-W53" max="2004-W20" value="2005-W53">
<input id="6" type="week" min="1980-W53" max="2004-W20" value="2005-w52">
<input id="7" type="week" min="1980-W53" max="2004-W20">
<!-- These should match -->
<input id="8" type="week" min="1980-W53" max="2004-W20" value="1979-W53">
<input id="9" type="week" min="1980-W53" max="2004-W20" value="1980-W52">
<input id="10" type="week" min="1980-W53" max="2004-W20" value="2005-W20">
<input id="11" type="week" min="1980-W53" max="2004-W20" value="2004-W21">
<!-- These cannot match -->
<input id="12" type="week" value="1999-W05">
<input id="13" type="week" min="invalid" value="1999-W05">
"""
self.assert_selector(
markup,
":out-of-range",
['8', '9', '10', '11'],
flags=util.HTML
)
def test_out_of_range_date(self):
"""Test in range date."""
markup = """
<!-- These should not match -->
<input id="0" type="date" min="1980-02-20" max="2004-08-14" value="1999-05-16">
<input id="1" type="date" min="1980-02-20" max="2004-08-14" value="1980-02-20">
<input id="2" type="date" min="1980-02-20" max="2004-08-14" value="2004-08-14">
<input id="3" type="date" min="1980-02-20" value="1999-05-16">
<input id="4" type="date" max="2004-08-14" value="1999-05-16">
<input id="5" type="date" min="1980-02-20" max="2004-08-14" value="1999-13-16">
<input id="6" type="date" min="1980-02-20" max="2004-08-14">
<!-- These should match -->
<input id="7" type="date" min="1980-02-20" max="2004-08-14" value="1979-02-20">
<input id="8" type="date" min="1980-02-20" max="2004-08-14" value="1980-01-20">
<input id="9" type="date" min="1980-02-20" max="2004-08-14" value="1980-02-19">
<input id="10" type="date" min="1980-02-20" max="2004-08-14" value="2005-08-14">
<input id="11" type="date" min="1980-02-20" max="2004-08-14" value="2004-09-14">
<input id="12" type="date" min="1980-02-20" max="2004-08-14" value="2004-09-15">
<!-- These cannot match -->
<input id="13" type="date" value="1999-05-16">
<input id="14" type="date" min="invalid" value="1999-05-16">
"""
self.assert_selector(
markup,
":out-of-range",
['7', '8', '9', '10', '11', '12'],
flags=util.HTML
)
def test_out_of_range_date_time(self):
"""Test in range date time."""
markup = """
<!-- These should not match -->
<input id="0" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1999-05-16T20:20">
<input id="1" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1980-02-20T01:30">
<input id="2" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="2004-08-14T18:45">
<input id="3" type="datetime-local" min="1980-02-20T01:30" value="1999-05-16T20:20">
<input id="4" type="datetime-local" max="2004-08-14T18:45" value="1999-05-16T20:20">
<input id="5" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1999-05-16T24:20">
<input id="6" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45">
<!-- These should match -->
<input id="7" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1979-02-20T01:30">
<input id="8" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1980-01-20T01:30">
<input id="9" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1980-02-19T01:30">
<input id="10" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1980-02-19T00:30">
<input id="11" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="1980-02-19T01:29">
<input id="12" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="2005-08-14T18:45">
<input id="13" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="2004-09-14T18:45">
<input id="14" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="2004-08-15T18:45">
<input id="15" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="2004-08-14T19:45">
<input id="16" type="datetime-local" min="1980-02-20T01:30" max="2004-08-14T18:45" value="2004-08-14T18:46">
<!-- These cannot match -->
<input id="17" type="datetime-local" value="1999-05-16T20:20">
<input id="18" type="datetime-local" min="invalid" value="1999-05-16T20:20">
"""
self.assert_selector(
markup,
":out-of-range",
['7', '8', '9', '10', '11', '12', '13', '14', '15', '16'],
flags=util.HTML
)
def test_out_of_range_time(self):
"""Test in range time."""
markup = """
<!-- These should not match -->
<input id="0" type="time" min="01:30" max="18:45" value="10:20">
<input id="1" type="time" max="01:30" min="18:45" value="20:20">
<input id="2" type="time" min="01:30" max="18:45" value="01:30">
<input id="3" type="time" min="01:30" max="18:45" value="18:45">
<input id="4" type="time" min="01:30" value="10:20">
<input id="5" type="time" max="18:45" value="10:20">
<input id="6" type="time" min="01:30" max="18:45" value="24:20">
<input id="7" type="time" min="01:30" max="18:45">
<!-- These should match -->
<input id="8" type="time" min="01:30" max="18:45" value="00:30">
<input id="9" type="time" min="01:30" max="18:45" value="01:29">
<input id="10" type="time" min="01:30" max="18:45" value="19:45">
<input id="11" type="time" min="01:30" max="18:45" value="18:46">
<input id="12" type="time" max="01:30" min="18:45" value="02:30">
<input id="13" type="time" max="01:30" min="18:45" value="17:45">
<input id="14" type="time" max="01:30" min="18:45" value="18:44">
<!-- These cannot match -->
<input id="15" type="time" value="10:20">
<input id="16" type="time" min="invalid" value="10:20">
"""
self.assert_selector(
markup,
":out-of-range",
['8', '9', '10', '11', '12', '13', '14'],
flags=util.HTML
)
| TestOutOfRange |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.