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 | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_reflection.py | {
"start": 92637,
"end": 108572
} | class ____(ComparesIndexes, fixtures.TestBase):
__sparse_driver_backend__ = True
@testing.fixture(params=[True, False])
def use_schema_fixture(self, request):
if request.param:
return config.test_schema
else:
return None
@testing.fixture()
def inspect_for_table(self, metadata, connection, use_schema_fixture):
@contextlib.contextmanager
def go(tablename):
yield use_schema_fixture, inspect(connection)
metadata.create_all(connection)
return go
def ck_eq(self, reflected, expected):
# trying to minimize effect of quoting, parenthesis, etc.
# may need to add more to this as new dialects get CHECK
# constraint reflection support
def normalize(sqltext):
return " ".join(
re.findall(r"and|\d|=|a|b|c|or|<|>", sqltext.lower(), re.I)
)
reflected = sorted(
[
{"name": item["name"], "sqltext": normalize(item["sqltext"])}
for item in reflected
],
key=lambda item: (item["sqltext"]),
)
expected = sorted(
expected,
key=lambda item: (item["sqltext"]),
)
eq_(reflected, expected)
@testing.requires.check_constraint_reflection
def test_check_constraint_no_constraint(self, metadata, inspect_for_table):
with inspect_for_table("no_constraints") as (schema, inspector):
Table(
"no_constraints",
metadata,
Column("data", sa.String(20)),
schema=schema,
)
self.ck_eq(
inspector.get_check_constraints("no_constraints", schema=schema),
[],
)
@testing.requires.inline_check_constraint_reflection
@testing.combinations(
"my_inline", "MyInline", None, argnames="constraint_name"
)
def test_check_constraint_inline(
self, metadata, inspect_for_table, constraint_name
):
with inspect_for_table("sa_cc") as (schema, inspector):
Table(
"sa_cc",
metadata,
Column("id", Integer(), primary_key=True),
Column(
"a",
Integer(),
sa.CheckConstraint(
"a > 1 AND a < 5", name=constraint_name
),
),
Column("data", String(50)),
schema=schema,
)
reflected = inspector.get_check_constraints("sa_cc", schema=schema)
self.ck_eq(
reflected,
[
{
"name": constraint_name or mock.ANY,
"sqltext": "a > 1 and a < 5",
},
],
)
@testing.requires.check_constraint_reflection
@testing.combinations(
"my_ck_const", "MyCkConst", None, argnames="constraint_name"
)
def test_check_constraint_standalone(
self, metadata, inspect_for_table, constraint_name
):
with inspect_for_table("sa_cc") as (schema, inspector):
Table(
"sa_cc",
metadata,
Column("a", Integer()),
sa.CheckConstraint(
"a = 1 OR (a > 2 AND a < 5)", name=constraint_name
),
schema=schema,
)
reflected = inspector.get_check_constraints("sa_cc", schema=schema)
self.ck_eq(
reflected,
[
{
"name": constraint_name or mock.ANY,
"sqltext": "a = 1 or a > 2 and a < 5",
},
],
)
@testing.requires.inline_check_constraint_reflection
def test_check_constraint_mixed(self, metadata, inspect_for_table):
with inspect_for_table("sa_cc") as (schema, inspector):
Table(
"sa_cc",
metadata,
Column("id", Integer(), primary_key=True),
Column("a", Integer(), sa.CheckConstraint("a > 1 AND a < 5")),
Column(
"b",
Integer(),
sa.CheckConstraint("b > 1 AND b < 5", name="my_inline"),
),
Column("c", Integer()),
Column("data", String(50)),
sa.UniqueConstraint("data", name="some_uq"),
sa.CheckConstraint("c > 1 AND c < 5", name="cc1"),
sa.UniqueConstraint("c", name="some_c_uq"),
schema=schema,
)
reflected = inspector.get_check_constraints("sa_cc", schema=schema)
self.ck_eq(
reflected,
[
{"name": "cc1", "sqltext": "c > 1 and c < 5"},
{"name": "my_inline", "sqltext": "b > 1 and b < 5"},
{"name": mock.ANY, "sqltext": "a > 1 and a < 5"},
],
)
@testing.requires.indexes_check_column_order
def test_index_column_order(self, metadata, inspect_for_table):
"""test for #12894"""
with inspect_for_table("sa_multi_index") as (schema, inspector):
test_table = Table(
"sa_multi_index",
metadata,
Column("Column1", Integer, primary_key=True),
Column("Column2", Integer),
Column("Column3", Integer),
)
Index(
"Index_Example",
test_table.c.Column3,
test_table.c.Column1,
test_table.c.Column2,
)
indexes = inspector.get_indexes("sa_multi_index")
eq_(indexes[0]["column_names"], ["Column3", "Column1", "Column2"])
@testing.requires.indexes_with_expressions
def test_reflect_expression_based_indexes(self, metadata, connection):
t = Table(
"t",
metadata,
Column("x", String(30)),
Column("y", String(30)),
Column("z", String(30)),
)
Index("t_idx", func.lower(t.c.x), t.c.z, func.lower(t.c.y))
long_str = "long string " * 100
Index("t_idx_long", func.coalesce(t.c.x, long_str))
Index("t_idx_2", t.c.x)
metadata.create_all(connection)
insp = inspect(connection)
expected = [
{
"name": "t_idx_2",
"column_names": ["x"],
"unique": False,
"dialect_options": {},
}
]
def completeIndex(entry):
if testing.requires.index_reflects_included_columns.enabled:
entry["include_columns"] = []
entry["dialect_options"] = {
f"{connection.engine.name}_include": []
}
else:
entry.setdefault("dialect_options", {})
completeIndex(expected[0])
class lower_index_str(str):
def __eq__(self, other):
ol = other.lower()
# test that lower and x or y are in the string
return "lower" in ol and ("x" in ol or "y" in ol)
class coalesce_index_str(str):
def __eq__(self, other):
# test that coalesce and the string is in other
return "coalesce" in other.lower() and long_str in other
if testing.requires.reflect_indexes_with_expressions.enabled:
expr_index = {
"name": "t_idx",
"column_names": [None, "z", None],
"expressions": [
lower_index_str("lower(x)"),
"z",
lower_index_str("lower(y)"),
],
"unique": False,
}
completeIndex(expr_index)
expected.insert(0, expr_index)
expr_index_long = {
"name": "t_idx_long",
"column_names": [None],
"expressions": [
coalesce_index_str(f"coalesce(x, '{long_str}')")
],
"unique": False,
}
completeIndex(expr_index_long)
expected.append(expr_index_long)
eq_(insp.get_indexes("t"), expected)
m2 = MetaData()
t2 = Table("t", m2, autoload_with=connection)
else:
with expect_warnings(
"Skipped unsupported reflection of expression-based "
"index t_idx"
):
eq_(insp.get_indexes("t"), expected)
m2 = MetaData()
t2 = Table("t", m2, autoload_with=connection)
self.compare_table_index_with_expected(
t2, expected, connection.engine.name
)
@testing.requires.index_reflects_included_columns
def test_reflect_covering_index(self, metadata, connection):
t = Table(
"t",
metadata,
Column("x", String(30)),
Column("y", String(30)),
)
idx = Index("t_idx", t.c.x)
idx.dialect_options[connection.engine.name]["include"] = ["y"]
metadata.create_all(connection)
insp = inspect(connection)
get_indexes = insp.get_indexes("t")
eq_(
get_indexes,
[
{
"name": "t_idx",
"column_names": ["x"],
"include_columns": ["y"],
"unique": False,
"dialect_options": mock.ANY,
}
],
)
eq_(
get_indexes[0]["dialect_options"][
"%s_include" % connection.engine.name
],
["y"],
)
t2 = Table("t", MetaData(), autoload_with=connection)
eq_(
list(t2.indexes)[0].dialect_options[connection.engine.name][
"include"
],
["y"],
)
def _type_round_trip(self, connection, metadata, *types):
t = Table(
"t",
metadata,
*[Column("t%d" % i, type_) for i, type_ in enumerate(types)],
)
t.create(connection)
return [c["type"] for c in inspect(connection).get_columns("t")]
@testing.requires.table_reflection
def test_numeric_reflection(self, connection, metadata):
for typ in self._type_round_trip(
connection, metadata, sql_types.Numeric(18, 5)
):
assert isinstance(typ, sql_types.Numeric)
eq_(typ.precision, 18)
eq_(typ.scale, 5)
@testing.requires.table_reflection
@testing.combinations(
sql_types.String,
sql_types.VARCHAR,
sql_types.CHAR,
(sql_types.NVARCHAR, testing.requires.nvarchar_types),
(sql_types.NCHAR, testing.requires.nvarchar_types),
argnames="type_",
)
def test_string_length_reflection(self, connection, metadata, type_):
typ = self._type_round_trip(connection, metadata, type_(52))[0]
if issubclass(type_, sql_types.VARCHAR):
assert isinstance(typ, sql_types.VARCHAR)
elif issubclass(type_, sql_types.CHAR):
assert isinstance(typ, sql_types.CHAR)
else:
assert isinstance(typ, sql_types.String)
eq_(typ.length, 52)
assert isinstance(typ.length, int)
@testing.requires.table_reflection
def test_nullable_reflection(self, connection, metadata):
t = Table(
"t",
metadata,
Column("a", Integer, nullable=True),
Column("b", Integer, nullable=False),
)
t.create(connection)
eq_(
{
col["name"]: col["nullable"]
for col in inspect(connection).get_columns("t")
},
{"a": True, "b": False},
)
@testing.combinations(
(
None,
"CASCADE",
None,
testing.requires.foreign_key_constraint_option_reflection_ondelete,
),
(
None,
None,
"SET NULL",
testing.requires.foreign_key_constraint_option_reflection_onupdate,
),
(
{},
None,
"NO ACTION",
testing.requires.foreign_key_constraint_option_reflection_onupdate,
),
(
{},
"NO ACTION",
None,
testing.requires.fk_constraint_option_reflection_ondelete_noaction,
),
(
None,
None,
"RESTRICT",
testing.requires.fk_constraint_option_reflection_onupdate_restrict,
),
(
None,
"RESTRICT",
None,
testing.requires.fk_constraint_option_reflection_ondelete_restrict,
),
argnames="expected,ondelete,onupdate",
)
def test_get_foreign_key_options(
self, connection, metadata, expected, ondelete, onupdate
):
options = {}
if ondelete:
options["ondelete"] = ondelete
if onupdate:
options["onupdate"] = onupdate
if expected is None:
expected = options
Table(
"x",
metadata,
Column("id", Integer, primary_key=True),
test_needs_fk=True,
)
Table(
"table",
metadata,
Column("id", Integer, primary_key=True),
Column("x_id", Integer, ForeignKey("x.id", name="xid")),
Column("test", String(10)),
test_needs_fk=True,
)
Table(
"user",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(50), nullable=False),
Column("tid", Integer),
sa.ForeignKeyConstraint(
["tid"], ["table.id"], name="myfk", **options
),
test_needs_fk=True,
)
metadata.create_all(connection)
insp = inspect(connection)
# test 'options' is always present for a backend
# that can reflect these, since alembic looks for this
opts = insp.get_foreign_keys("table")[0]["options"]
eq_({k: opts[k] for k in opts if opts[k]}, {})
opts = insp.get_foreign_keys("user")[0]["options"]
eq_(opts, expected)
# eq_(dict((k, opts[k]) for k in opts if opts[k]), expected)
@testing.combinations(
(Integer, sa.text("10"), r"'?10'?"),
(Integer, "10", r"'?10'?"),
(Boolean, sa.true(), r"1|true"),
(
Integer,
sa.text("3 + 5"),
r"3\+5",
testing.requires.expression_server_defaults,
),
(
Integer,
sa.text("(3 * 5)"),
r"3\*5",
testing.requires.expression_server_defaults,
),
(DateTime, func.now(), r"current_timestamp|now|getdate"),
(
Integer,
sa.literal_column("3") + sa.literal_column("5"),
r"3\+5",
testing.requires.expression_server_defaults,
),
argnames="datatype, default, expected_reg",
)
@testing.requires.server_defaults
def test_server_defaults(
self, metadata, connection, datatype, default, expected_reg
):
t = Table(
"t",
metadata,
Column("id", Integer, primary_key=True),
Column("thecol", datatype, server_default=default),
)
t.create(connection)
reflected = inspect(connection).get_columns("t")[1]["default"]
reflected_sanitized = re.sub(r"[\(\) \']", "", reflected)
eq_regex(reflected_sanitized, expected_reg, flags=re.IGNORECASE)
| ComponentReflectionTestExtra |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/sagemaker.py | {
"start": 1302,
"end": 4880
} | class ____(BaseTrigger):
"""
SageMakerTrigger is fired as deferred class with params to run the task in triggerer.
:param job_name: name of the job to check status
:param job_type: Type of the sagemaker job whether it is Transform or Training
:param poke_interval: polling period in seconds to check for the status
:param max_attempts: Number of times to poll for query state before returning the current state,
defaults to None.
:param aws_conn_id: AWS connection ID for sagemaker
"""
def __init__(
self,
job_name: str,
job_type: str,
poke_interval: int = 30,
max_attempts: int = 480,
aws_conn_id: str | None = "aws_default",
):
super().__init__()
self.job_name = job_name
self.job_type = job_type
self.poke_interval = poke_interval
self.max_attempts = max_attempts
self.aws_conn_id = aws_conn_id
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize SagemakerTrigger arguments and classpath."""
return (
"airflow.providers.amazon.aws.triggers.sagemaker.SageMakerTrigger",
{
"job_name": self.job_name,
"job_type": self.job_type,
"poke_interval": self.poke_interval,
"max_attempts": self.max_attempts,
"aws_conn_id": self.aws_conn_id,
},
)
@cached_property
def hook(self) -> SageMakerHook:
return SageMakerHook(aws_conn_id=self.aws_conn_id)
@staticmethod
def _get_job_type_waiter(job_type: str) -> str:
return {
"training": "TrainingJobComplete",
"transform": "TransformJobComplete",
"processing": "ProcessingJobComplete",
"tuning": "TuningJobComplete",
"endpoint": "endpoint_in_service", # this one is provided by boto
}[job_type.lower()]
@staticmethod
def _get_waiter_arg_name(job_type: str) -> str:
return {
"training": "TrainingJobName",
"transform": "TransformJobName",
"processing": "ProcessingJobName",
"tuning": "HyperParameterTuningJobName",
"endpoint": "EndpointName",
}[job_type.lower()]
@staticmethod
def _get_response_status_key(job_type: str) -> str:
return {
"training": "TrainingJobStatus",
"transform": "TransformJobStatus",
"processing": "ProcessingJobStatus",
"tuning": "HyperParameterTuningJobStatus",
"endpoint": "EndpointStatus",
}[job_type.lower()]
async def run(self):
self.log.info("job name is %s and job type is %s", self.job_name, self.job_type)
async with await self.hook.get_async_conn() as client:
waiter = self.hook.get_waiter(
self._get_job_type_waiter(self.job_type), deferrable=True, client=client
)
await async_wait(
waiter=waiter,
waiter_delay=self.poke_interval,
waiter_max_attempts=self.max_attempts,
args={self._get_waiter_arg_name(self.job_type): self.job_name},
failure_message=f"Error while waiting for {self.job_type} job",
status_message=f"{self.job_type} job not done yet",
status_args=[self._get_response_status_key(self.job_type)],
)
yield TriggerEvent({"status": "success", "message": "Job completed.", "job_name": self.job_name})
| SageMakerTrigger |
python | giampaolo__psutil | psutil/_common.py | {
"start": 3665,
"end": 3835
} | class ____(enum.IntEnum):
NIC_DUPLEX_FULL = 2
NIC_DUPLEX_HALF = 1
NIC_DUPLEX_UNKNOWN = 0
globals().update(NicDuplex.__members__)
# sensors_battery()
| NicDuplex |
python | scrapy__scrapy | tests/test_core_downloader.py | {
"start": 1372,
"end": 3199
} | class ____:
context_factory = None
@async_yield_fixture
async def server_url(self, tmp_path):
(tmp_path / "file").write_bytes(b"0123456789")
r = static.File(str(tmp_path))
r.putChild(b"payload", PayloadResource())
site = server.Site(r, timeout=None)
port = self._listen(site)
portno = port.getHost().port
yield f"https://127.0.0.1:{portno}/"
await port.stopListening()
def _listen(self, site):
from twisted.internet import reactor
return reactor.listenSSL(
0,
site,
contextFactory=self.context_factory or ssl_context_factory(),
interface="127.0.0.1",
)
@staticmethod
async def get_page(
url: str,
client_context_factory: BrowserLikePolicyForHTTPS,
body: str | None = None,
) -> bytes:
from twisted.internet import reactor
agent = Agent(reactor, contextFactory=client_context_factory)
body_producer = _RequestBodyProducer(body.encode()) if body else None
response: TxResponse = cast(
"TxResponse",
await maybe_deferred_to_future(
agent.request(
b"GET",
url.encode(),
bodyProducer=cast("IBodyProducer", body_producer),
)
),
)
with warnings.catch_warnings():
# https://github.com/twisted/twisted/issues/8227
warnings.filterwarnings(
"ignore",
category=DeprecationWarning,
message=r".*does not have an abortConnection method",
)
d: Deferred[bytes] = readBody(response) # type: ignore[arg-type]
return await maybe_deferred_to_future(d)
| TestContextFactoryBase |
python | readthedocs__readthedocs.org | readthedocs/notifications/querysets.py | {
"start": 372,
"end": 6029
} | class ____(NoReprQuerySet, models.QuerySet):
def add(self, *args, **kwargs):
"""
Create a notification without duplicating it.
If a notification with the same ``message_id`` is already attached to the object,
its ``modified_at`` timestamp and ``state`` is updated.
Otherwise, a new notification object is created for this object.
"""
message_id = kwargs.get("message_id")
attached_to = kwargs.pop("attached_to")
content_type = ContentType.objects.get_for_model(attached_to)
notification = self.filter(
attached_to_content_type=content_type,
attached_to_id=attached_to.id,
message_id=message_id,
# Update only ``READ`` and ``UNREAD`` notifications because we want
# to keep track of ``DISMISSED`` and ``CANCELLED`` ones.
state__in=(UNREAD, READ),
).first()
if notification:
# Remove the fields we are overriding.
# Avoids passing these fields twice to ``.update()`` which
# raises an exception in that case.
kwargs.pop("state", None)
kwargs.pop("modified", None)
self.filter(pk=notification.pk).update(
*args,
modified=timezone.now(),
state=UNREAD,
**kwargs,
)
notification.refresh_from_db()
return notification
return super().create(*args, attached_to=attached_to, **kwargs)
def cancel(self, message_id, attached_to):
"""
Cancel an on-going notification because the underlying state has changed.
When a notification is not valid anymore because the user has made the
required action (e.g. paid an unpaid subscription) we use this method
to mark those notifications as ``CANCELLED``.
It only cancels notifications that are ``UNREAD`` or ``READ``.
"""
content_type = ContentType.objects.get_for_model(attached_to)
self.filter(
attached_to_content_type=content_type,
attached_to_id=attached_to.id,
message_id=message_id,
state__in=(UNREAD, READ),
).update(
state=CANCELLED,
modified=timezone.now(),
)
def for_user(self, user, resource):
"""
Retrieve notifications related to resource for a particular user.
Given a user, returns all the notifications for the specified ``resource``
considering permissions (e.g. does not return any notification if the ``user``
doesn't have admin permissions on the ``resource``).
If ``resource="all"``, it returns the following notifications:
- are attached to an ``Organization`` where the user is owner
- are attached to a ``Project`` where the user is admin
- are attacehd to the ``User`` themselves
It only returns notifications that are ``READ`` or ``UNREAD``.
"""
# Need to be here due to circular imports
from readthedocs.organizations.models import Organization
from readthedocs.projects.models import Project
if resource == "all":
# http://chibisov.github.io/drf-extensions/docs/#usage-with-generic-relations
user_notifications = self.filter(
attached_to_content_type=ContentType.objects.get_for_model(User),
attached_to_id=user.pk,
)
project_notifications = self.filter(
attached_to_content_type=ContentType.objects.get_for_model(Project),
attached_to_id__in=AdminPermission.projects(
user,
admin=True,
member=False,
).values("id"),
)
organization_notifications = self.filter(
attached_to_content_type=ContentType.objects.get_for_model(Organization),
attached_to_id__in=AdminPermission.organizations(
user,
owner=True,
member=False,
).values("id"),
)
# Return all the notifications related to this user attached to:
# User, Project and Organization models where the user is admin.
return (user_notifications | project_notifications | organization_notifications).filter(
state__in=(UNREAD, READ)
)
if isinstance(resource, User):
if user == resource:
return self.filter(
attached_to_content_type=ContentType.objects.get_for_model(resource),
attached_to_id=resource.pk,
state__in=(UNREAD, READ),
)
if isinstance(resource, Project):
if resource in AdminPermission.projects(user, admin=True, member=False):
return self.filter(
attached_to_content_type=ContentType.objects.get_for_model(resource),
attached_to_id=resource.pk,
state__in=(UNREAD, READ),
)
if isinstance(resource, Organization):
if resource in AdminPermission.organizations(
user,
owner=True,
member=False,
):
return self.filter(
attached_to_content_type=ContentType.objects.get_for_model(resource),
attached_to_id=resource.pk,
state__in=(UNREAD, READ),
)
return self.none()
| NotificationQuerySet |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 54379,
"end": 60807
} | class ____(TestCase):
"""Tests for ``split_into()``"""
def test_iterable_just_right(self):
"""Size of ``iterable`` equals the sum of ``sizes``."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [2, 3, 4]
expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_iterable_too_small(self):
"""Size of ``iterable`` is smaller than sum of ``sizes``. Last return
list is shorter as a result."""
iterable = [1, 2, 3, 4, 5, 6, 7]
sizes = [2, 3, 4]
expected = [[1, 2], [3, 4, 5], [6, 7]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_iterable_too_small_extra(self):
"""Size of ``iterable`` is smaller than sum of ``sizes``. Second last
return list is shorter and last return list is empty as a result."""
iterable = [1, 2, 3, 4, 5, 6, 7]
sizes = [2, 3, 4, 5]
expected = [[1, 2], [3, 4, 5], [6, 7], []]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_iterable_too_large(self):
"""Size of ``iterable`` is larger than sum of ``sizes``. Not all
items of iterable are returned."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [2, 3, 2]
expected = [[1, 2], [3, 4, 5], [6, 7]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_using_none_with_leftover(self):
"""Last item of ``sizes`` is None when items still remain in
``iterable``. Last list returned stretches to fit all remaining items
of ``iterable``."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [2, 3, None]
expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_using_none_without_leftover(self):
"""Last item of ``sizes`` is None when no items remain in
``iterable``. Last list returned is empty."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [2, 3, 4, None]
expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9], []]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_using_none_mid_sizes(self):
"""None is present in ``sizes`` but is not the last item. Last list
returned stretches to fit all remaining items of ``iterable`` but
all items in ``sizes`` after None are ignored."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [2, 3, None, 4]
expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_iterable_empty(self):
"""``iterable`` argument is empty but ``sizes`` is not. An empty
list is returned for each item in ``sizes``."""
iterable = []
sizes = [2, 4, 2]
expected = [[], [], []]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_iterable_empty_using_none(self):
"""``iterable`` argument is empty but ``sizes`` is not. An empty
list is returned for each item in ``sizes`` that is not after a
None item."""
iterable = []
sizes = [2, 4, None, 2]
expected = [[], [], []]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_sizes_empty(self):
"""``sizes`` argument is empty but ``iterable`` is not. An empty
generator is returned."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = []
expected = []
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_both_empty(self):
"""Both ``sizes`` and ``iterable`` arguments are empty. An empty
generator is returned."""
iterable = []
sizes = []
expected = []
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_bool_in_sizes(self):
"""A bool object is present in ``sizes`` is treated as a 1 or 0 for
``True`` or ``False`` due to bool being an instance of int."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [3, True, 2, False]
expected = [[1, 2, 3], [4], [5, 6], []]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_invalid_in_sizes(self):
"""A ValueError is raised if an object in ``sizes`` is neither ``None``
or an integer."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [1, [], 3]
with self.assertRaises(ValueError):
list(mi.split_into(iterable, sizes))
def test_invalid_in_sizes_after_none(self):
"""A item in ``sizes`` that is invalid will not raise a TypeError if it
comes after a ``None`` item."""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = [3, 4, None, []]
expected = [[1, 2, 3], [4, 5, 6, 7], [8, 9]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
def test_generator_iterable_integrity(self):
"""Check that if ``iterable`` is an iterator, it is consumed only by as
many items as the sum of ``sizes``."""
iterable = (i for i in range(10))
sizes = [2, 3]
expected = [[0, 1], [2, 3, 4]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
iterable_expected = [5, 6, 7, 8, 9]
iterable_actual = list(iterable)
self.assertEqual(iterable_actual, iterable_expected)
def test_generator_sizes_integrity(self):
"""Check that if ``sizes`` is an iterator, it is consumed only until a
``None`` item is reached"""
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sizes = (i for i in [1, 2, None, 3, 4])
expected = [[1], [2, 3], [4, 5, 6, 7, 8, 9]]
actual = list(mi.split_into(iterable, sizes))
self.assertEqual(actual, expected)
sizes_expected = [3, 4]
sizes_actual = list(sizes)
self.assertEqual(sizes_actual, sizes_expected)
| SplitIntoTests |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 9339,
"end": 9919
} | class ____(Event):
name: str = "align_judge"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
result = {}
if (traces := arguments.get("traces")) is not None:
try:
result["trace_count"] = len(traces)
except TypeError:
result["trace_count"] = None
if optimizer := arguments.get("optimizer"):
result["optimizer_type"] = type(optimizer).__name__
else:
result["optimizer_type"] = "default"
return result
| AlignJudgeEvent |
python | modin-project__modin | modin/core/io/file_dispatcher.py | {
"start": 3632,
"end": 11316
} | class ____(ClassLogger, modin_layer="CORE-IO", log_level=LogLevel.DEBUG):
"""
Class handles util functions for reading data from different kinds of files.
Notes
-----
`_read`, `deploy`, `parse` and `materialize` are abstract methods and should be
implemented in the child classes (functions signatures can differ between child
classes).
"""
BUFFER_UNSUPPORTED_MSG = (
"Reading from buffers or other non-path-like objects is not supported"
)
frame_cls = None
frame_partition_cls = None
query_compiler_cls = None
@classmethod
def read(cls, *args, **kwargs):
"""
Read data according passed `args` and `kwargs`.
Parameters
----------
*args : iterable
Positional arguments to be passed into `_read` function.
**kwargs : dict
Keywords arguments to be passed into `_read` function.
Returns
-------
query_compiler : BaseQueryCompiler
Query compiler with imported data for further processing.
Notes
-----
`read` is high-level function that calls specific for defined storage format, engine and
dispatcher class `_read` function with passed parameters and performs some
postprocessing work on the resulting query_compiler object.
"""
try:
query_compiler = cls._read(*args, **kwargs)
except ModinAssumptionError as err:
param_name = "path_or_buf" if "path_or_buf" in kwargs else "fname"
fname = kwargs.pop(param_name)
return cls.single_worker_read(fname, *args, reason=str(err), **kwargs)
# TextFileReader can also be returned from `_read`.
if not AsyncReadMode.get() and hasattr(query_compiler, "dtypes"):
# at the moment it is not possible to use `wait_partitions` function;
# in a situation where the reading function is called in a row with the
# same parameters, `wait_partitions` considers that we have waited for
# the end of remote calculations, however, when trying to materialize the
# received data, it is clear that the calculations have not yet ended.
# for example, `test_io_exp.py::test_read_evaluated_dict` is failed because of that.
# see #5944 for details
_ = query_compiler.dtypes
return query_compiler
@classmethod
def _read(cls, *args, **kwargs):
"""
Perform reading of the data from file.
Should be implemented in the child class.
Parameters
----------
*args : iterable
Positional arguments of the function.
**kwargs : dict
Keywords arguments of the function.
"""
raise NotImplementedError(NOT_IMPLEMENTED_MESSAGE)
@classmethod
def get_path(cls, file_path):
"""
Process `file_path` in accordance to it's type.
Parameters
----------
file_path : str, os.PathLike[str] object or file-like object
The file, or a path to the file. Paths to S3 buckets are also
acceptable.
Returns
-------
str
Updated or verified `file_path` parameter.
Notes
-----
if `file_path` is a URL, parameter will be returned as is, otherwise
absolute path will be returned.
"""
if is_fsspec_url(file_path) or is_url(file_path):
return file_path
else:
return os.path.abspath(file_path)
@classmethod
def file_size(cls, f):
"""
Get the size of file associated with file handle `f`.
Parameters
----------
f : file-like object
File-like object, that should be used to get file size.
Returns
-------
int
File size in bytes.
"""
cur_pos = f.tell()
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(cur_pos, os.SEEK_SET)
return size
@classmethod
def file_exists(cls, file_path, storage_options=None):
"""
Check if `file_path` exists.
Parameters
----------
file_path : str
String that represents the path to the file (paths to S3 buckets
are also acceptable).
storage_options : dict, optional
Keyword from `read_*` functions.
Returns
-------
bool
Whether file exists or not.
"""
if not is_fsspec_url(file_path) and not is_url(file_path):
return os.path.exists(file_path)
try:
from botocore.exceptions import (
ConnectTimeoutError,
EndpointConnectionError,
NoCredentialsError,
)
credential_error_type = (
NoCredentialsError,
PermissionError,
EndpointConnectionError,
ConnectTimeoutError,
)
except ModuleNotFoundError:
credential_error_type = (PermissionError,)
if storage_options is not None:
new_storage_options = dict(storage_options)
new_storage_options.pop("anon", None)
else:
new_storage_options = {}
fs, _ = fsspec.core.url_to_fs(file_path, **new_storage_options)
exists = False
try:
exists = fs.exists(file_path)
except credential_error_type:
fs, _ = fsspec.core.url_to_fs(file_path, anon=True, **new_storage_options)
exists = fs.exists(file_path)
return exists
@classmethod
def deploy(cls, func, *args, num_returns=1, **kwargs): # noqa: PR01
"""
Deploy remote task.
Should be implemented in the task class (for example in the `RayWrapper`).
"""
raise NotImplementedError(NOT_IMPLEMENTED_MESSAGE)
def parse(self, func, args, num_returns): # noqa: PR01
"""
Parse file's data in the worker process.
Should be implemented in the parser class (for example in the `PandasCSVParser`).
"""
raise NotImplementedError(NOT_IMPLEMENTED_MESSAGE)
@classmethod
def materialize(cls, obj_id): # noqa: PR01
"""
Get results from worker.
Should be implemented in the task class (for example in the `RayWrapper`).
"""
raise NotImplementedError(NOT_IMPLEMENTED_MESSAGE)
@classmethod
def build_partition(cls, partition_ids, row_lengths, column_widths):
"""
Build array with partitions of `cls.frame_partition_cls` class.
Parameters
----------
partition_ids : list
Array with references to the partitions data.
row_lengths : list
Partitions rows lengths.
column_widths : list
Number of columns in each partition.
Returns
-------
np.ndarray
array with shape equals to the shape of `partition_ids` and
filed with partition objects.
"""
return np.array(
[
[
cls.frame_partition_cls(
partition_ids[i][j],
length=row_lengths[i],
width=column_widths[j],
)
for j in range(len(partition_ids[i]))
]
for i in range(len(partition_ids))
]
)
@classmethod
def _file_not_found_msg(cls, filename: str): # noqa: GL08
return f"No such file: '{filename}'"
| FileDispatcher |
python | huggingface__transformers | src/transformers/models/plbart/modular_plbart.py | {
"start": 1863,
"end": 1924
} | class ____(BartDecoder):
pass
@auto_docstring
| PLBartDecoder |
python | google__jax | jax/_src/pjit.py | {
"start": 3568,
"end": 19206
} | class ____(NamedTuple):
"""Things that we know about a jit instance before it is called.
In other words, this structure contains arguments to jit()/pjit(),
preprocessed and validated.
"""
fun_sourceinfo: str
fun_signature: inspect.Signature | None
# Shardings, as specified by the user. These can either be UNSPECIFIED or they
# can be a tree (prefix) of shardings or None.
user_specified_in_shardings: bool
in_shardings_treedef: PyTreeDef
in_shardings_leaves: tuple[Any, ...]
out_shardings_treedef: PyTreeDef
out_shardings_leaves: tuple[Any, ...]
in_layouts_treedef: PyTreeDef
in_layouts_leaves: tuple[Any, ...]
out_layouts_treedef: PyTreeDef
out_layouts_leaves: tuple[Any, ...]
static_argnums: tuple[int, ...]
static_argnames: tuple[str, ...]
donate_argnums: tuple[int, ...]
donate_argnames: tuple[str, ...]
device: xc.Device | None
backend: str | None
keep_unused: bool
inline: bool
abstracted_axes: Any | None
use_resource_env: bool # False for jit, True for pjit
compiler_options_kvs: tuple[tuple[str, Any], ...]
# Hash and compare PjitInfo by identity when used as a cache key.
def __hash__(self):
return id(self)
def __eq__(self, other):
return self is other
def _python_pjit_helper(fun: Callable, jit_info: PjitInfo, *args, **kwargs):
p, args_flat = _infer_params(fun, jit_info, args, kwargs)
for arg in args_flat:
dispatch.check_arg(arg)
try:
if (core.trace_state_clean() and not config.debug_key_reuse.value
and not p.params['jaxpr'].jaxpr.is_high):
args_flat = map(core.full_lower, args_flat)
core.check_eval_args(args_flat)
out_flat, compiled, profiler, const_args = _pjit_call_impl_python(
*args_flat, **p.params)
else:
out_flat = jit_p.bind(*args_flat, **p.params)
compiled = None
profiler = None
const_args = []
except stages.DeviceAssignmentMismatchError as e:
fails, = e.args
fun_name = getattr(fun, '__qualname__', getattr(fun, '__name__', str(fun)))
arg_types = map(convert_to_metaty, args_flat)
msg = stages._device_assignment_mismatch_error(
fun_name, fails, arg_types, 'jit', p.arg_names)
raise ValueError(msg) from None
except dtypes.InvalidInputException as e:
arg_names = [''] * len(args_flat) if p.arg_names is None else p.arg_names
# Run canonicalization again to figure out which arg failed.
if p.params['jaxpr'].consts:
raise TypeError(e.args[0]) from e
else:
for arg, name, aval in zip(args_flat, arg_names, p.in_avals):
try:
dtypes.canonicalize_value(arg)
except dtypes.InvalidInputException as _:
# Reraise as TypeError with the new message.
raise TypeError(
f"Argument '{name}' of shape {aval.str_short()} of type"
f' {type(arg)} is not a valid JAX type.') from e
raise AssertionError("Unreachable") from e
except api_util.InternalFloatingPointError as e:
if getattr(fun, '_apply_primitive', False):
raise FloatingPointError(f"invalid value ({e.ty}) encountered in {fun.__qualname__}") from None
api_util.maybe_recursive_nan_check(e, fun, args, kwargs)
outs = tree_unflatten(p.out_tree, out_flat)
return (outs, out_flat, p.out_tree, args_flat,
p.params['jaxpr'], compiled, profiler, const_args)
def _need_to_rebuild_with_fdo(pgle_profiler):
return (pgle_profiler is not None and pgle_profiler.is_enabled()
and not pgle_profiler.is_fdo_consumed())
def _get_fastpath_data(
executable, out_tree, args_flat, out_flat, effects, consts_for_constvars,
abstracted_axes, pgle_profiler, const_args: Sequence[ArrayLike]
) -> pxla.MeshExecutableFastpathData | None:
if (
executable is None
or not isinstance(executable, pxla.MeshExecutable)
or not isinstance(executable.unsafe_call, pxla.ExecuteReplicated)
# No effects in computation
or executable.unsafe_call.ordered_effects
or executable.unsafe_call.has_unordered_effects
or abstracted_axes is not None
# no ref state effects
or any(isinstance(e, RefEffect) for e in effects)
# no prng reuse checking
or (config.debug_key_reuse.value and any(
hasattr(arg, 'dtype') and dtypes.issubdtype(arg.dtype, dtypes.prng_key)
for arg in (*args_flat, *out_flat, *consts_for_constvars)))
or _need_to_rebuild_with_fdo(pgle_profiler)
or config.no_execution.value
):
return None
out_reflattened, out_tree = pxla.reflatten_outputs_for_dispatch(out_tree, out_flat)
if not all(isinstance(x, xc.ArrayImpl) for x in out_reflattened):
return None
out_avals = [o.aval for o in out_reflattened]
out_committed = [o._committed for o in out_reflattened]
kept_var_bitvec = [i in executable._kept_var_idx
for i in range(len(const_args) + len(args_flat))]
in_shardings = [
sharding_impls.physical_sharding(a, s)
if a is not core.abstract_token and dtypes.issubdtype(a.dtype, dtypes.extended)
else s
for s, a in zip(executable._in_shardings, executable.in_avals)
]
return pxla.MeshExecutableFastpathData(
executable.xla_executable, out_tree, in_shardings,
executable._out_shardings, out_avals, out_committed, kept_var_bitvec,
executable._dispatch_in_layouts, const_args)
# The entries are doubled here from the default 4096 because _pjit_call_impl
# also has a cpp dispatch path and that would double the number of entries in
# the global shared cache.
# This cache is only used for jit's with only fun. For example: jax.jit(f)
_cpp_pjit_cache_fun_only = xc._xla.PjitFunctionCache(capacity=8192)
# This cache is used for jit where extra arguments are defined other than the
# fun. For example: jax.jit(f, donate_argnums=...) OR
# jax.jit(f, out_shardings=...), etc. We don't use the same cache because the
# capacity might get full very fast because of all the jitted function in JAX
# which might evict train_step for example.
_cpp_pjit_cache_explicit_attributes = xc._xla.PjitFunctionCache(capacity=8192)
def _get_cpp_global_cache(contains_explicit_attributes: bool):
if contains_explicit_attributes:
return _cpp_pjit_cache_explicit_attributes
else:
return _cpp_pjit_cache_fun_only
def _cpp_pjit(fun: Callable, jit_info: PjitInfo):
@api_boundary
def cache_miss(*args, **kwargs):
# args do not include the const args
# See https://docs.jax.dev/en/latest/internals/constants.html.
if config.no_tracing.value:
raise RuntimeError(f"re-tracing function {jit_info.fun_sourceinfo} for "
"`jit`, but 'no_tracing' is set")
(outs, out_flat, out_tree, args_flat, jaxpr,
executable, pgle_profiler, const_args) = _python_pjit_helper(
fun, jit_info, *args, **kwargs)
maybe_fastpath_data = _get_fastpath_data(
executable, out_tree, args_flat, out_flat, jaxpr.effects, jaxpr.consts,
jit_info.abstracted_axes, pgle_profiler,
const_args)
return outs, maybe_fastpath_data, _need_to_rebuild_with_fdo(pgle_profiler)
cache_key = pxla.JitGlobalCppCacheKeys(
donate_argnums=jit_info.donate_argnums,
donate_argnames=jit_info.donate_argnames,
device=jit_info.device, backend=jit_info.backend,
in_shardings_treedef=jit_info.in_shardings_treedef,
in_shardings_leaves=jit_info.in_shardings_leaves,
out_shardings_treedef=jit_info.out_shardings_treedef,
out_shardings_leaves=jit_info.out_shardings_leaves,
in_layouts_treedef=jit_info.in_layouts_treedef,
in_layouts_leaves=jit_info.in_layouts_leaves,
out_layouts_treedef=jit_info.out_layouts_treedef,
out_layouts_leaves=jit_info.out_layouts_leaves,
compiler_options_kvs=jit_info.compiler_options_kvs)
cpp_pjit_f = xc._xla.pjit(
fun_name(fun), fun, cache_miss, jit_info.static_argnums,
jit_info.static_argnames, cache_key, tree_util.dispatch_registry,
pxla.cc_shard_arg,
_get_cpp_global_cache(cache_key.contains_explicit_attributes))
cpp_pjitted_f = wraps(fun)(cpp_pjit_f)
cpp_pjitted_f._fun = fun
cpp_pjitted_f._jit_info = jit_info
cpp_jitted_f_class = type(cpp_pjitted_f)
# TODO(necula): make clear_cache private, no need to have it part of the API
cpp_jitted_f_class.clear_cache = jit_evict_fn
cpp_jitted_f_class.lower = jit_lower
cpp_jitted_f_class.trace = jit_trace
cpp_jitted_f_class.eval_shape = jit_eval_shape
return cpp_pjitted_f
@api_boundary
def jit_trace(jit_func, *args, **kwargs) -> stages.Traced:
p, args_flat = _infer_params(jit_func._fun, jit_func._jit_info, args, kwargs)
arg_types = map(convert_to_metaty, args_flat)
return stages.Traced(arg_types, p.params, p.in_tree, p.out_tree, p.consts)
@api_boundary
def jit_lower(jit_func, *args, **kwargs):
return jit_trace(jit_func, *args, **kwargs).lower()
@api_boundary
def jit_eval_shape(jit_func, *args, **kwargs):
return jit_trace(jit_func, *args, **kwargs).out_info
def jit_evict_fn(self):
self._clear_cache()
_create_pjit_jaxpr.evict_function(self._fun) # pytype: disable=attribute-error
_infer_params_cached.cache_clear()
def _split_layout_and_sharding(entries):
entries_flat, treedef = tree_flatten(entries, is_leaf=lambda x: x is None)
layouts, shardings = [], []
for e in entries_flat:
if isinstance(e, Format):
layouts.append(e.layout)
shardings.append(e.sharding)
elif isinstance(e, (Layout, AutoLayout)):
raise ValueError(
'`jax.jit` does not accept device-local layouts directly. Create '
'a `Format` instance wrapping this device-local layout and pass '
f'that to `jit` instead. Got {e}')
else:
layouts.append(None)
shardings.append(e)
assert len(layouts) == len(shardings)
return tree_unflatten(treedef, layouts), tree_unflatten(treedef, shardings)
def _parse_jit_arguments(fun: Callable, *, in_shardings: Any,
out_shardings: Any,
static_argnums: int | Sequence[int] | None,
static_argnames: str | Iterable[str] | None,
donate_argnums: int | Sequence[int] | None,
donate_argnames: str | Iterable[str] | None,
keep_unused: bool, device: xc.Device | None,
backend: str | None, inline: bool,
abstracted_axes: Any | None,
compiler_options: dict[str, Any] | None,
use_resource_env: bool) -> PjitInfo:
"""Parses the arguments to jit/pjit.
Performs any preprocessing and validation of the arguments that we can do
ahead of time before the jit()-ed function is invoked.
"""
if abstracted_axes and not config.dynamic_shapes.value:
raise ValueError("abstracted_axes must be used with --jax_dynamic_shapes")
check_callable(fun)
if backend is not None or device is not None:
warnings.warn(
'backend and device argument on jit is deprecated. You can use'
' `jax.device_put(..., jax.local_devices(backend="cpu")[0])` on the'
' inputs to the jitted function to get the same behavior.',
DeprecationWarning,
)
if device is not None and backend is not None:
raise ValueError("can't specify both a device and a backend for jit, "
f"got {device=} and {backend=}")
if in_shardings is not None and not isinstance(in_shardings, UnspecifiedValue):
raise ValueError('If backend or device is specified on jit, then '
'in_shardings should not be specified.')
if out_shardings is not None and not isinstance(out_shardings, UnspecifiedValue):
raise ValueError('If backend or device is specified on jit, then '
'out_shardings should not be specified.')
if isinstance(in_shardings, list):
# To be a tree prefix of the positional args tuple, in_axes can never be a
# list: if in_axes is not a leaf, it must be a tuple of trees. However,
# in cases like these users expect tuples and lists to be treated
# essentially interchangeably, so we canonicalize lists to tuples here
# rather than raising an error. https://github.com/jax-ml/jax/issues/2367
in_shardings = tuple(in_shardings)
in_layouts, in_shardings = _split_layout_and_sharding(in_shardings)
out_layouts, out_shardings = _split_layout_and_sharding(out_shardings)
in_shardings = prepare_axis_resources(in_shardings, 'in_shardings')
out_shardings = prepare_axis_resources(out_shardings, 'out_shardings',
allow_unconstrained_dims=True)
user_specified_in_shardings = (in_shardings is not None and
not isinstance(in_shardings, UnspecifiedValue))
in_shardings_leaves, in_shardings_treedef = none_lr.flatten(in_shardings)
out_shardings_leaves, out_shardings_treedef = none_lr.flatten(out_shardings)
in_layouts_leaves, in_layouts_treedef = none_lr.flatten(in_layouts)
out_layouts_leaves, out_layouts_treedef = none_lr.flatten(out_layouts)
fun_sourceinfo = api_util.fun_sourceinfo(fun)
fun_signature = api_util.fun_signature(fun)
donate_argnums, donate_argnames, static_argnums, static_argnames = resolve_argnums(
fun, fun_signature, donate_argnums, donate_argnames, static_argnums,
static_argnames)
compiler_options_kvs = (() if compiler_options is None else
tuple(compiler_options.items()))
return PjitInfo(
fun_sourceinfo=fun_sourceinfo,
fun_signature=fun_signature,
user_specified_in_shardings=user_specified_in_shardings,
in_shardings_treedef=in_shardings_treedef,
in_shardings_leaves=tuple(in_shardings_leaves),
out_shardings_treedef=out_shardings_treedef,
out_shardings_leaves=tuple(out_shardings_leaves),
in_layouts_treedef=in_layouts_treedef,
in_layouts_leaves=tuple(in_layouts_leaves),
out_layouts_treedef=out_layouts_treedef,
out_layouts_leaves=tuple(out_layouts_leaves),
static_argnums=static_argnums,
static_argnames=static_argnames, donate_argnums=donate_argnums,
donate_argnames=donate_argnames, device=device, backend=backend,
keep_unused=keep_unused, inline=inline,
abstracted_axes=abstracted_axes,
use_resource_env=use_resource_env,
compiler_options_kvs=compiler_options_kvs)
def make_jit(fun: Callable,
*,
in_shardings: Any,
out_shardings: Any,
static_argnums: int | Sequence[int] | None,
static_argnames: str | Iterable[str] | None,
donate_argnums: int | Sequence[int] | None,
donate_argnames: str | Iterable[str] | None,
keep_unused: bool,
device: xc.Device | None,
backend: str | None,
inline: bool,
abstracted_axes: Any | None,
compiler_options: dict[str, Any] | None,
use_resource_env: bool) -> Any:
"""jit() and pjit() are thin wrappers around this function."""
jit_info = _parse_jit_arguments(
fun, in_shardings=in_shardings, out_shardings=out_shardings,
static_argnums=static_argnums, static_argnames=static_argnames,
donate_argnums=donate_argnums, donate_argnames=donate_argnames,
keep_unused=keep_unused, device=device, backend=backend, inline=inline,
abstracted_axes=abstracted_axes, compiler_options=compiler_options,
use_resource_env=use_resource_env)
return _cpp_pjit(fun, jit_info)
| PjitInfo |
python | ansible__ansible | lib/ansible/cli/console.py | {
"start": 1237,
"end": 22002
} | class ____(CLI, cmd.Cmd):
"""
A REPL that allows for running ad-hoc tasks against a chosen inventory
from a nice shell with built-in tab completion (based on dominis'
``ansible-shell``).
It supports several commands, and you can modify its configuration at
runtime:
- ``cd [pattern]``: change host/group
(you can use host patterns eg.: ``app*.dc*:!app01*``)
- ``list``: list available hosts in the current path
- ``list groups``: list groups included in the current path
- ``become``: toggle the become flag
- ``!``: forces shell module instead of the ansible module
(``!yum update -y``)
- ``verbosity [num]``: set the verbosity level
- ``forks [num]``: set the number of forks
- ``become_user [user]``: set the become_user
- ``remote_user [user]``: set the remote_user
- ``become_method [method]``: set the privilege escalation method
- ``check [bool]``: toggle check mode
- ``diff [bool]``: toggle diff mode
- ``timeout [integer]``: set the timeout of tasks in seconds
(0 to disable)
- ``help [command/module]``: display documentation for
the command or module
- ``exit``: exit ``ansible-console``
"""
name = 'ansible-console'
modules = [] # type: list[str] | None
ARGUMENTS = {'host-pattern': 'A name of a group in the inventory, a shell-like glob '
'selecting hosts in inventory or any combination of the two separated by commas.'}
# use specific to console, but fallback to highlight for backwards compatibility
NORMAL_PROMPT = C.COLOR_CONSOLE_PROMPT or C.COLOR_HIGHLIGHT
USES_CONNECTION = True
def __init__(self, args):
super(ConsoleCLI, self).__init__(args)
self.intro = 'Welcome to the ansible console. Type help or ? to list commands.\n'
self.groups = []
self.hosts = []
self.pattern = None
self.variable_manager = None
self.loader = None
self.passwords = dict()
self.cwd = '*'
# Defaults for these are set from the CLI in run()
self.remote_user = None
self.become = None
self.become_user = None
self.become_method = None
self.check_mode = None
self.diff = None
self.forks = None
self.task_timeout = None
self.collections = None
cmd.Cmd.__init__(self)
def init_parser(self):
super(ConsoleCLI, self).init_parser(
desc="REPL console for executing Ansible tasks.",
epilog="This is not a live session/connection: each task is executed in the background and returns its results."
)
opt_help.add_runas_options(self.parser)
opt_help.add_inventory_options(self.parser)
opt_help.add_connect_options(self.parser)
opt_help.add_check_options(self.parser)
opt_help.add_vault_options(self.parser)
opt_help.add_fork_options(self.parser)
opt_help.add_module_options(self.parser)
opt_help.add_basedir_options(self.parser)
opt_help.add_runtask_options(self.parser)
opt_help.add_tasknoplay_options(self.parser)
# options unique to shell
self.parser.add_argument('pattern', help='host pattern', metavar='pattern', default='all', nargs='?')
self.parser.add_argument('--step', dest='step', action='store_true',
help="one-step-at-a-time: confirm each task before running")
def post_process_args(self, options):
options = super(ConsoleCLI, self).post_process_args(options)
display.verbosity = options.verbosity
self.validate_conflicts(options, runas_opts=True, fork_opts=True)
return options
def get_names(self):
return dir(self)
def cmdloop(self):
try:
cmd.Cmd.cmdloop(self)
except KeyboardInterrupt:
self.cmdloop()
except EOFError:
self.display("[Ansible-console was exited]")
self.do_exit(self)
def set_prompt(self):
login_user = self.remote_user or getpass.getuser()
self.selected = self.inventory.list_hosts(self.cwd)
prompt = "%s@%s (%d)[f:%s]" % (login_user, self.cwd, len(self.selected), self.forks)
if self.become and self.become_user in [None, 'root']:
prompt += "# "
color = C.COLOR_ERROR
else:
prompt += "$ "
color = self.NORMAL_PROMPT
self.prompt = stringc(prompt, color, wrap_nonvisible_chars=True)
def list_modules(self):
return list_plugins('module', self.collections)
def default(self, line, forceshell=False):
""" actually runs modules """
if line.startswith("#"):
return False
if not self.cwd:
display.error("No host found")
return False
# defaults
module = 'shell'
module_args = line
if forceshell is not True:
possible_module, *possible_args = line.split()
if module_loader.find_plugin(possible_module):
# we found module!
module = possible_module
if possible_args:
module_args = ' '.join(possible_args)
else:
module_args = ''
module_args = TrustedAsTemplate().tag(module_args)
if self.callback:
cb = self.callback
elif C.DEFAULT_LOAD_CALLBACK_PLUGINS and C.DEFAULT_STDOUT_CALLBACK != 'default':
cb = C.DEFAULT_STDOUT_CALLBACK
else:
cb = 'minimal'
result = None
try:
check_raw = module in C._ACTION_ALLOWS_RAW_ARGS
task = dict(action=module, args=parse_kv(module_args, check_raw=check_raw), timeout=self.task_timeout)
play_ds = dict(
name="Ansible Shell",
hosts=self.cwd,
gather_facts='no',
tasks=[task],
remote_user=self.remote_user,
become=self.become,
become_user=self.become_user,
become_method=self.become_method,
check_mode=self.check_mode,
diff=self.diff,
collections=self.collections,
)
play = Play().load(play_ds, variable_manager=self.variable_manager, loader=self.loader)
except Exception as e:
display.error(u"Unable to build command: %s" % to_text(e))
return False
try:
# now create a task queue manager to execute the play
self._tqm = None
try:
self._tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
passwords=self.passwords,
stdout_callback_name=cb,
run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
run_tree=False,
forks=self.forks,
)
result = self._tqm.run(play)
display.debug(result)
finally:
if self._tqm:
self._tqm.cleanup()
if self.loader:
self.loader.cleanup_all_tmp_files()
if result is None:
display.error("No hosts found")
return False
except KeyboardInterrupt:
display.error('User interrupted execution')
return False
except Exception as ex:
display.error(ex)
return False
def emptyline(self):
return
def do_shell(self, arg):
"""
You can run shell commands through the shell module.
eg.:
shell ps uax | grep java | wc -l
shell killall python
shell halt -n
You can use the ! to force the shell module. eg.:
!ps aux | grep java | wc -l
"""
self.default(arg, True)
def help_shell(self):
display.display("You can run shell commands through the shell module.")
def do_forks(self, arg):
"""Set the number of forks"""
if arg:
try:
forks = int(arg)
except TypeError:
display.error('Invalid argument for "forks"')
self.usage_forks()
if forks > 0:
self.forks = forks
self.set_prompt()
else:
display.display('forks must be greater than or equal to 1')
else:
self.usage_forks()
def help_forks(self):
display.display("Set the number of forks to use per task")
self.usage_forks()
def usage_forks(self):
display.display('Usage: forks <number>')
do_serial = do_forks
help_serial = help_forks
def do_collections(self, arg):
"""Set list of collections for 'short name' usage"""
if arg in ('', 'none'):
self.collections = None
elif not arg:
self.usage_collections()
else:
collections = arg.split(',')
for collection in collections:
if self.collections is None:
self.collections = []
self.collections.append(collection.strip())
if self.collections:
display.v('Collections name search is set to: %s' % ', '.join(self.collections))
else:
display.v('Collections name search is using defaults')
def help_collections(self):
display.display("Set the collection name search path when using short names for plugins")
self.usage_collections()
def usage_collections(self):
display.display('Usage: collections <collection1>[, <collection2> ...]\n Use empty quotes or "none" to reset to default.\n')
def do_verbosity(self, arg):
"""Set verbosity level"""
if not arg:
display.display('Usage: verbosity <number>')
else:
try:
display.verbosity = int(arg)
display.v('verbosity level set to %s' % arg)
except (TypeError, ValueError) as e:
display.error('The verbosity must be a valid integer: %s' % to_text(e))
def help_verbosity(self):
display.display("Set the verbosity level, equivalent to -v for 1 and -vvvv for 4.")
def do_cd(self, arg):
"""
Change active host/group. You can use hosts patterns as well eg.:
cd webservers
cd webservers:dbservers
cd webservers:!phoenix
cd webservers:&staging
cd webservers:dbservers:&staging:!phoenix
"""
if not arg:
self.cwd = '*'
elif arg in '/*':
self.cwd = 'all'
elif self.inventory.get_hosts(arg):
self.cwd = arg
else:
display.display("no host matched")
self.set_prompt()
def help_cd(self):
display.display("Change active host/group. ")
self.usage_cd()
def usage_cd(self):
display.display("Usage: cd <group>|<host>|<host pattern>")
def do_list(self, arg):
"""List the hosts in the current group"""
if not arg:
for host in self.selected:
display.display(host.name)
elif arg == 'groups':
for group in self.groups:
display.display(group)
else:
display.error('Invalid option passed to "list"')
self.help_list()
def help_list(self):
display.display("List the hosts in the current group or a list of groups if you add 'groups'.")
def do_become(self, arg):
"""Toggle whether plays run with become"""
if arg:
self.become = boolean(arg, strict=False)
display.v("become changed to %s" % self.become)
self.set_prompt()
else:
display.display("Please specify become value, e.g. `become yes`")
def help_become(self):
display.display("Toggle whether the tasks are run with become")
def do_remote_user(self, arg):
"""Given a username, set the remote user plays are run by"""
if arg:
self.remote_user = arg
self.set_prompt()
else:
display.display("Please specify a remote user, e.g. `remote_user root`")
def help_remote_user(self):
display.display("Set the user for use as login to the remote target")
def do_become_user(self, arg):
"""Given a username, set the user that plays are run by when using become"""
if arg:
self.become_user = arg
else:
display.display("Please specify a user, e.g. `become_user jenkins`")
display.v("Current user is %s" % self.become_user)
self.set_prompt()
def help_become_user(self):
display.display("Set the user for use with privilege escalation (which remote user attempts to 'become' when become is enabled)")
def do_become_method(self, arg):
"""Given a become_method, set the privilege escalation method when using become"""
if arg:
self.become_method = arg
display.v("become_method changed to %s" % self.become_method)
else:
display.display("Please specify a become_method, e.g. `become_method su`")
display.v("Current become_method is %s" % self.become_method)
def help_become_method(self):
display.display("Set the privilege escalation plugin to use when become is enabled")
def do_check(self, arg):
"""Toggle whether plays run with check mode"""
if arg:
self.check_mode = boolean(arg, strict=False)
display.display("check mode changed to %s" % self.check_mode)
else:
display.display("Please specify check mode value, e.g. `check yes`")
display.v("check mode is currently %s." % self.check_mode)
def help_check(self):
display.display("Toggle check_mode for the tasks")
def do_diff(self, arg):
"""Toggle whether plays run with diff"""
if arg:
self.diff = boolean(arg, strict=False)
display.display("diff mode changed to %s" % self.diff)
else:
display.display("Please specify a diff value , e.g. `diff yes`")
display.v("diff mode is currently %s" % self.diff)
def help_diff(self):
display.display("Toggle diff output for the tasks")
def do_timeout(self, arg):
"""Set the timeout"""
if arg:
try:
timeout = int(arg)
if timeout < 0:
display.error('The timeout must be greater than or equal to 1, use 0 to disable')
else:
self.task_timeout = timeout
except (TypeError, ValueError) as e:
display.error('The timeout must be a valid positive integer, or 0 to disable: %s' % to_text(e))
else:
self.usage_timeout()
def help_timeout(self):
display.display("Set task timeout in seconds")
self.usage_timeout()
def usage_timeout(self):
display.display('Usage: timeout <seconds>')
def do_exit(self, args):
"""Exits from the console"""
sys.stdout.write('\nAnsible-console was exited.\n')
return -1
def help_exit(self):
display.display("LEAVE!")
do_EOF = do_exit
help_EOF = help_exit
def helpdefault(self, module_name):
if module_name:
in_path = module_loader.find_plugin(module_name)
if in_path:
oc, a, _dummy1, _dummy2 = plugin_docs.get_docstring(in_path, fragment_loader)
if oc:
display.display(oc['short_description'])
display.display('Parameters:')
for opt in oc['options'].keys():
display.display(' ' + stringc(opt, self.NORMAL_PROMPT) + ' ' + oc['options'][opt]['description'][0])
else:
display.error('No documentation found for %s.' % module_name)
else:
display.error('%s is not a valid command, use ? to list all valid commands.' % module_name)
def help_help(self):
display.warning("Don't be redundant!")
def complete_cd(self, text, line, begidx, endidx):
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
if self.cwd in ('all', '*', '\\'):
completions = self.hosts + self.groups
else:
completions = [x.name for x in self.inventory.list_hosts(self.cwd)]
return [to_native(s)[offs:] for s in completions if to_native(s).startswith(to_native(mline))]
def completedefault(self, text, line, begidx, endidx):
if line.split()[0] in self.list_modules():
mline = line.split(' ')[-1]
offs = len(mline) - len(text)
completions = self.module_args(line.split()[0])
return [s[offs:] + '=' for s in completions if s.startswith(mline)]
def module_args(self, module_name):
in_path = module_loader.find_plugin(module_name)
oc, a, _dummy1, _dummy2 = plugin_docs.get_docstring(in_path, fragment_loader, is_module=True)
return list(oc['options'].keys())
def run(self):
super(ConsoleCLI, self).run()
sshpass = None
becomepass = None
# hosts
self.pattern = context.CLIARGS['pattern']
self.cwd = self.pattern
# Defaults from the command line
self.remote_user = context.CLIARGS['remote_user']
self.become = context.CLIARGS['become']
self.become_user = context.CLIARGS['become_user']
self.become_method = context.CLIARGS['become_method']
self.check_mode = context.CLIARGS['check']
self.diff = context.CLIARGS['diff']
self.forks = context.CLIARGS['forks']
self.task_timeout = context.CLIARGS['task_timeout']
# set module path if needed
if context.CLIARGS['module_path']:
for path in context.CLIARGS['module_path']:
if path:
module_loader.add_directory(path)
# dynamically add 'canonical' modules as commands, aliases could be used and dynamically loaded
self.modules = self.list_modules()
for module in self.modules:
setattr(self, 'do_' + module, lambda arg, module=module: self.default(module + ' ' + arg))
setattr(self, 'help_' + module, lambda module=module: self.helpdefault(module))
(sshpass, becomepass) = self.ask_passwords()
self.passwords = {'conn_pass': sshpass, 'become_pass': becomepass}
self.loader, self.inventory, self.variable_manager = self._play_prereqs()
hosts = self.get_host_list(self.inventory, context.CLIARGS['subset'], self.pattern)
self.groups = self.inventory.list_groups()
self.hosts = [x.name for x in hosts]
# This hack is to work around readline issues on a mac:
# http://stackoverflow.com/a/7116997/541202
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
histfile = os.path.join(os.path.expanduser("~"), ".ansible-console_history")
try:
readline.read_history_file(histfile)
except OSError:
pass
atexit.register(readline.write_history_file, histfile)
self.set_prompt()
self.cmdloop()
def __getattr__(self, name):
""" handle not found to populate dynamically a module function if module matching name exists """
attr = None
if name.startswith('do_'):
module = name.replace('do_', '')
if module_loader.find_plugin(module):
setattr(self, name, lambda arg, module=module: self.default(module + ' ' + arg))
attr = object.__getattr__(self, name)
elif name.startswith('help_'):
module = name.replace('help_', '')
if module_loader.find_plugin(module):
setattr(self, name, lambda module=module: self.helpdefault(module))
attr = object.__getattr__(self, name)
if attr is None:
raise AttributeError(f"{self.__class__} does not have a {name} attribute")
return attr
def main(args=None):
ConsoleCLI.cli_executor(args)
if __name__ == '__main__':
main()
| ConsoleCLI |
python | Textualize__textual | src/textual/keys.py | {
"start": 232,
"end": 10246
} | class ____(str, Enum): # type: ignore[no-redef]
"""
List of keys for use in key bindings.
Note that this is an "StrEnum", all values can be compared against
strings.
"""
@property
def value(self) -> str:
return super().value
Escape = "escape" # Also Control-[
ShiftEscape = "shift+escape"
Return = "return"
ControlAt = "ctrl+@" # Also Control-Space.
ControlA = "ctrl+a"
ControlB = "ctrl+b"
ControlC = "ctrl+c"
ControlD = "ctrl+d"
ControlE = "ctrl+e"
ControlF = "ctrl+f"
ControlG = "ctrl+g"
ControlH = "ctrl+h"
ControlI = "ctrl+i" # Tab
ControlJ = "ctrl+j" # Newline
ControlK = "ctrl+k"
ControlL = "ctrl+l"
ControlM = "ctrl+m" # Carriage return
ControlN = "ctrl+n"
ControlO = "ctrl+o"
ControlP = "ctrl+p"
ControlQ = "ctrl+q"
ControlR = "ctrl+r"
ControlS = "ctrl+s"
ControlT = "ctrl+t"
ControlU = "ctrl+u"
ControlV = "ctrl+v"
ControlW = "ctrl+w"
ControlX = "ctrl+x"
ControlY = "ctrl+y"
ControlZ = "ctrl+z"
Control1 = "ctrl+1"
Control2 = "ctrl+2"
Control3 = "ctrl+3"
Control4 = "ctrl+4"
Control5 = "ctrl+5"
Control6 = "ctrl+6"
Control7 = "ctrl+7"
Control8 = "ctrl+8"
Control9 = "ctrl+9"
Control0 = "ctrl+0"
ControlShift1 = "ctrl+shift+1"
ControlShift2 = "ctrl+shift+2"
ControlShift3 = "ctrl+shift+3"
ControlShift4 = "ctrl+shift+4"
ControlShift5 = "ctrl+shift+5"
ControlShift6 = "ctrl+shift+6"
ControlShift7 = "ctrl+shift+7"
ControlShift8 = "ctrl+shift+8"
ControlShift9 = "ctrl+shift+9"
ControlShift0 = "ctrl+shift+0"
ControlBackslash = "ctrl+backslash"
ControlSquareClose = "ctrl+right_square_bracket"
ControlCircumflex = "ctrl+circumflex_accent"
ControlUnderscore = "ctrl+underscore"
Left = "left"
Right = "right"
Up = "up"
Down = "down"
Home = "home"
End = "end"
Insert = "insert"
Delete = "delete"
PageUp = "pageup"
PageDown = "pagedown"
ControlLeft = "ctrl+left"
ControlRight = "ctrl+right"
ControlUp = "ctrl+up"
ControlDown = "ctrl+down"
ControlHome = "ctrl+home"
ControlEnd = "ctrl+end"
ControlInsert = "ctrl+insert"
ControlDelete = "ctrl+delete"
ControlPageUp = "ctrl+pageup"
ControlPageDown = "ctrl+pagedown"
ShiftLeft = "shift+left"
ShiftRight = "shift+right"
ShiftUp = "shift+up"
ShiftDown = "shift+down"
ShiftHome = "shift+home"
ShiftEnd = "shift+end"
ShiftInsert = "shift+insert"
ShiftDelete = "shift+delete"
ShiftPageUp = "shift+pageup"
ShiftPageDown = "shift+pagedown"
ControlShiftLeft = "ctrl+shift+left"
ControlShiftRight = "ctrl+shift+right"
ControlShiftUp = "ctrl+shift+up"
ControlShiftDown = "ctrl+shift+down"
ControlShiftHome = "ctrl+shift+home"
ControlShiftEnd = "ctrl+shift+end"
ControlShiftInsert = "ctrl+shift+insert"
ControlShiftDelete = "ctrl+shift+delete"
ControlShiftPageUp = "ctrl+shift+pageup"
ControlShiftPageDown = "ctrl+shift+pagedown"
BackTab = "shift+tab" # shift + tab
F1 = "f1"
F2 = "f2"
F3 = "f3"
F4 = "f4"
F5 = "f5"
F6 = "f6"
F7 = "f7"
F8 = "f8"
F9 = "f9"
F10 = "f10"
F11 = "f11"
F12 = "f12"
F13 = "f13"
F14 = "f14"
F15 = "f15"
F16 = "f16"
F17 = "f17"
F18 = "f18"
F19 = "f19"
F20 = "f20"
F21 = "f21"
F22 = "f22"
F23 = "f23"
F24 = "f24"
ControlF1 = "ctrl+f1"
ControlF2 = "ctrl+f2"
ControlF3 = "ctrl+f3"
ControlF4 = "ctrl+f4"
ControlF5 = "ctrl+f5"
ControlF6 = "ctrl+f6"
ControlF7 = "ctrl+f7"
ControlF8 = "ctrl+f8"
ControlF9 = "ctrl+f9"
ControlF10 = "ctrl+f10"
ControlF11 = "ctrl+f11"
ControlF12 = "ctrl+f12"
ControlF13 = "ctrl+f13"
ControlF14 = "ctrl+f14"
ControlF15 = "ctrl+f15"
ControlF16 = "ctrl+f16"
ControlF17 = "ctrl+f17"
ControlF18 = "ctrl+f18"
ControlF19 = "ctrl+f19"
ControlF20 = "ctrl+f20"
ControlF21 = "ctrl+f21"
ControlF22 = "ctrl+f22"
ControlF23 = "ctrl+f23"
ControlF24 = "ctrl+f24"
# Matches any key.
Any = "<any>"
# Special.
ScrollUp = "<scroll-up>"
ScrollDown = "<scroll-down>"
# For internal use: key which is ignored.
# (The key binding for this key should not do anything.)
Ignore = "<ignore>"
# Some 'Key' aliases (for backwardshift+compatibility).
ControlSpace = "ctrl-at"
Tab = "tab"
Space = "space"
Enter = "enter"
Backspace = "backspace"
# ShiftControl was renamed to ControlShift in
# 888fcb6fa4efea0de8333177e1bbc792f3ff3c24 (20 Feb 2020).
ShiftControlLeft = ControlShiftLeft
ShiftControlRight = ControlShiftRight
ShiftControlHome = ControlShiftHome
ShiftControlEnd = ControlShiftEnd
# Unicode db contains some obscure names
# This mapping replaces them with more common terms
KEY_NAME_REPLACEMENTS = {
"solidus": "slash",
"reverse_solidus": "backslash",
"commercial_at": "at",
"hyphen_minus": "minus",
"plus_sign": "plus",
"low_line": "underscore",
}
REPLACED_KEYS = {value: key for key, value in KEY_NAME_REPLACEMENTS.items()}
# Convert the friendly versions of character key Unicode names
# back to their original names.
# This is because we go from Unicode to friendly by replacing spaces and dashes
# with underscores, which cannot be undone by replacing underscores with spaces/dashes.
KEY_TO_UNICODE_NAME = {
"exclamation_mark": "EXCLAMATION MARK",
"quotation_mark": "QUOTATION MARK",
"number_sign": "NUMBER SIGN",
"dollar_sign": "DOLLAR SIGN",
"percent_sign": "PERCENT SIGN",
"left_parenthesis": "LEFT PARENTHESIS",
"right_parenthesis": "RIGHT PARENTHESIS",
"plus_sign": "PLUS SIGN",
"hyphen_minus": "HYPHEN-MINUS",
"full_stop": "FULL STOP",
"less_than_sign": "LESS-THAN SIGN",
"equals_sign": "EQUALS SIGN",
"greater_than_sign": "GREATER-THAN SIGN",
"question_mark": "QUESTION MARK",
"commercial_at": "COMMERCIAL AT",
"left_square_bracket": "LEFT SQUARE BRACKET",
"reverse_solidus": "REVERSE SOLIDUS",
"right_square_bracket": "RIGHT SQUARE BRACKET",
"circumflex_accent": "CIRCUMFLEX ACCENT",
"low_line": "LOW LINE",
"grave_accent": "GRAVE ACCENT",
"left_curly_bracket": "LEFT CURLY BRACKET",
"vertical_line": "VERTICAL LINE",
"right_curly_bracket": "RIGHT CURLY BRACKET",
}
# Some keys have aliases. For example, if you press `ctrl+m` on your keyboard,
# it's treated the same way as if you press `enter`. Key handlers `key_ctrl_m` and
# `key_enter` are both valid in this case.
KEY_ALIASES = {
"tab": ["ctrl+i"],
"enter": ["ctrl+m"],
"escape": ["ctrl+left_square_brace"],
"ctrl+at": ["ctrl+space"],
"ctrl+j": ["newline"],
}
KEY_DISPLAY_ALIASES = {
"up": "↑",
"down": "↓",
"left": "←",
"right": "→",
"backspace": "⌫",
"escape": "esc",
"enter": "⏎",
"minus": "-",
"space": "space",
"pagedown": "pgdn",
"pageup": "pgup",
"delete": "del",
}
ASCII_KEY_NAMES = {"\t": "tab"}
def _get_unicode_name_from_key(key: str) -> str:
"""Get the best guess for the Unicode name of the char corresponding to the key.
This function can be seen as a pseudo-inverse of the function `_character_to_key`.
"""
return KEY_TO_UNICODE_NAME.get(key, key)
def _get_key_aliases(key: str) -> list[str]:
"""Return all aliases for the given key, including the key itself"""
return [key] + KEY_ALIASES.get(key, [])
@lru_cache(1024)
def format_key(key: str) -> str:
"""Given a key (i.e. the `key` string argument to Binding __init__),
return the value that should be displayed in the app when referring
to this key (e.g. in the Footer widget)."""
display_alias = KEY_DISPLAY_ALIASES.get(key)
if display_alias:
return display_alias
original_key = REPLACED_KEYS.get(key, key)
tentative_unicode_name = _get_unicode_name_from_key(original_key)
try:
unicode_name = unicodedata.lookup(tentative_unicode_name)
except KeyError:
pass
else:
if unicode_name.isprintable():
return unicode_name
return tentative_unicode_name
@lru_cache(1024)
def key_to_character(key: str) -> str | None:
"""Given a key identifier, return the character associated with it.
Args:
key: The key identifier.
Returns:
A key if one could be found, otherwise `None`.
"""
_, separator, key = key.rpartition("+")
if separator:
# If there is a separator, then it means a modifier (other than shift) is applied.
# Keys with modifiers, don't come from printable keys.
return None
if len(key) == 1:
# Key identifiers with a length of one, are also characters.
return key
try:
return unicodedata.lookup(KEY_TO_UNICODE_NAME[key])
except KeyError:
pass
try:
return unicodedata.lookup(key.replace("_", " ").upper())
except KeyError:
pass
# Return None if we couldn't identify the key.
return None
def _character_to_key(character: str) -> str:
"""Convert a single character to a key value.
This transformation can be undone by the function `_get_unicode_name_from_key`.
"""
if not character.isalnum():
try:
key = (
unicodedata.name(character).lower().replace("-", "_").replace(" ", "_")
)
except ValueError:
key = ASCII_KEY_NAMES.get(character, character)
else:
key = character
key = KEY_NAME_REPLACEMENTS.get(key, key)
return key
def _normalize_key_list(keys: str) -> str:
"""Normalizes a comma separated list of keys.
Replaces single letter keys with full name.
"""
keys_list = [key.strip() for key in keys.split(",")]
return ",".join(
_character_to_key(key) if len(key) == 1 else key for key in keys_list
)
| Keys |
python | sympy__sympy | sympy/polys/domains/old_polynomialring.py | {
"start": 10627,
"end": 15988
} | class ____(PolynomialRingBase):
"""A generalized polynomial ring, with objects DMF. """
dtype = DMF
def new(self, a):
"""Construct an element of ``self`` domain from ``a``. """
res = self.dtype(a, self.dom, len(self.gens) - 1)
# make sure res is actually in our ring
if res.denom().terms(order=self.order)[0][0] != (0,)*len(self.gens):
from sympy.printing.str import sstr
raise CoercionFailed("denominator %s not allowed in %s"
% (sstr(res), self))
return res
def __contains__(self, a):
try:
a = self.convert(a)
except CoercionFailed:
return False
return a.denom().terms(order=self.order)[0][0] == (0,)*len(self.gens)
def to_sympy(self, a):
"""Convert ``a`` to a SymPy object. """
return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) /
basic_from_dict(a.denom().to_sympy_dict(), *self.gens))
def from_sympy(self, a):
"""Convert SymPy's expression to ``dtype``. """
p, q = a.as_numer_denom()
num, _ = dict_from_basic(p, gens=self.gens)
den, _ = dict_from_basic(q, gens=self.gens)
for k, v in num.items():
num[k] = self.dom.from_sympy(v)
for k, v in den.items():
den[k] = self.dom.from_sympy(v)
return self((num, den)).cancel()
def exquo(self, a, b):
"""Exact quotient of ``a`` and ``b``. """
# Elements are DMF that will always divide (except 0). The result is
# not guaranteed to be in this ring, so we have to check that.
r = a / b
try:
r = self.new((r.num, r.den))
except CoercionFailed:
raise ExactQuotientFailed(a, b, self)
return r
def from_FractionField(K1, a, K0):
dmf = K1.get_field().from_FractionField(a, K0)
return K1((dmf.num, dmf.den))
def _vector_to_sdm(self, v, order):
"""
Turn an iterable into a sparse distributed module.
Note that the vector is multiplied by a unit first to make all entries
polynomials.
Examples
========
>>> from sympy import ilex, QQ
>>> from sympy.abc import x, y
>>> R = QQ.old_poly_ring(x, y, order=ilex)
>>> f = R.convert((x + 2*y) / (1 + x))
>>> g = R.convert(x * y)
>>> R._vector_to_sdm([f, g], ilex)
[((0, 0, 1), 2), ((0, 1, 0), 1), ((1, 1, 1), 1), ((1,
2, 1), 1)]
"""
# NOTE this is quite inefficient...
u = self.one.numer()
for x in v:
u *= x.denom()
return _vector_to_sdm_helper([x.numer()*u/x.denom() for x in v], order)
@public
def PolynomialRing(dom, *gens, **opts):
r"""
Create a generalized multivariate polynomial ring.
A generalized polynomial ring is defined by a ground field `K`, a set
of generators (typically `x_1, \ldots, x_n`) and a monomial order `<`.
The monomial order can be global, local or mixed. In any case it induces
a total ordering on the monomials, and there exists for every (non-zero)
polynomial `f \in K[x_1, \ldots, x_n]` a well-defined "leading monomial"
`LM(f) = LM(f, >)`. One can then define a multiplicative subset
`S = S_> = \{f \in K[x_1, \ldots, x_n] | LM(f) = 1\}`. The generalized
polynomial ring corresponding to the monomial order is
`R = S^{-1}K[x_1, \ldots, x_n]`.
If `>` is a so-called global order, that is `1` is the smallest monomial,
then we just have `S = K` and `R = K[x_1, \ldots, x_n]`.
Examples
========
A few examples may make this clearer.
>>> from sympy.abc import x, y
>>> from sympy import QQ
Our first ring uses global lexicographic order.
>>> R1 = QQ.old_poly_ring(x, y, order=(("lex", x, y),))
The second ring uses local lexicographic order. Note that when using a
single (non-product) order, you can just specify the name and omit the
variables:
>>> R2 = QQ.old_poly_ring(x, y, order="ilex")
The third and fourth rings use a mixed orders:
>>> o1 = (("ilex", x), ("lex", y))
>>> o2 = (("lex", x), ("ilex", y))
>>> R3 = QQ.old_poly_ring(x, y, order=o1)
>>> R4 = QQ.old_poly_ring(x, y, order=o2)
We will investigate what elements of `K(x, y)` are contained in the various
rings.
>>> L = [x, 1/x, y/(1 + x), 1/(1 + y), 1/(1 + x*y)]
>>> test = lambda R: [f in R for f in L]
The first ring is just `K[x, y]`:
>>> test(R1)
[True, False, False, False, False]
The second ring is R1 localised at the maximal ideal (x, y):
>>> test(R2)
[True, False, True, True, True]
The third ring is R1 localised at the prime ideal (x):
>>> test(R3)
[True, False, True, False, True]
Finally the fourth ring is R1 localised at `S = K[x, y] \setminus yK[y]`:
>>> test(R4)
[True, False, False, True, False]
"""
order = opts.get("order", GeneralizedPolynomialRing.default_order)
if iterable(order):
order = build_product_order(order, gens)
order = monomial_key(order)
opts['order'] = order
if order.is_global:
return GlobalPolynomialRing(dom, *gens, **opts)
else:
return GeneralizedPolynomialRing(dom, *gens, **opts)
| GeneralizedPolynomialRing |
python | mlflow__mlflow | mlflow/transformers/__init__.py | {
"start": 9348,
"end": 73266
} | class ____(NamedTuple):
task: str
model: _DummyModel
@docstring_version_compatibility_warning(integration_name=FLAVOR_NAME)
@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name=FLAVOR_NAME))
def save_model(
transformers_model,
path: str,
processor=None,
task: str | None = None,
torch_dtype: torch.dtype | None = None,
model_card=None,
code_paths: list[str] | None = None,
mlflow_model: Model | None = None,
signature: ModelSignature | None = None,
input_example: ModelInputExample | None = None,
pip_requirements: list[str] | str | None = None,
extra_pip_requirements: list[str] | str | None = None,
conda_env=None,
metadata: dict[str, Any] | None = None,
model_config: dict[str, Any] | None = None,
prompt_template: str | None = None,
save_pretrained: bool = True,
**kwargs, # pylint: disable=unused-argument
) -> None:
"""
Save a trained transformers model to a path on the local file system. Note that
saving transformers models with custom code (i.e. models that require
``trust_remote_code=True``) requires ``transformers >= 4.26.0``.
Args:
transformers_model:
The transformers model to save. This can be one of the following format:
1. A transformers `Pipeline` instance.
2. A dictionary that maps required components of a pipeline to the named keys
of ["model", "image_processor", "tokenizer", "feature_extractor"].
The `model` key in the dictionary must map to a value that inherits from
`PreTrainedModel`, `TFPreTrainedModel`, or `FlaxPreTrainedModel`.
All other component entries in the dictionary must support the defined task
type that is associated with the base model type configuration.
3. A string that represents a path to a local/DBFS directory containing a model
checkpoint. The directory must contain a `config.json` file that is required
for loading the transformers model. This is particularly useful when logging
a model that cannot be loaded into memory for serialization.
An example of specifying a `Pipeline` from a default pipeline instantiation:
.. code-block:: python
from transformers import pipeline
qa_pipe = pipeline("question-answering", "csarron/mobilebert-uncased-squad-v2")
with mlflow.start_run():
mlflow.transformers.save_model(
transformers_model=qa_pipe,
path="path/to/save/model",
)
An example of specifying component-level parts of a transformers model is shown below:
.. code-block:: python
from transformers import MobileBertForQuestionAnswering, AutoTokenizer
architecture = "csarron/mobilebert-uncased-squad-v2"
tokenizer = AutoTokenizer.from_pretrained(architecture)
model = MobileBertForQuestionAnswering.from_pretrained(architecture)
with mlflow.start_run():
components = {
"model": model,
"tokenizer": tokenizer,
}
mlflow.transformers.save_model(
transformers_model=components,
path="path/to/save/model",
)
An example of specifying a local checkpoint path is shown below:
.. code-block:: python
with mlflow.start_run():
mlflow.transformers.save_model(
transformers_model="path/to/local/checkpoint",
path="path/to/save/model",
)
path: Local path destination for the serialized model to be saved.
processor: An optional ``Processor`` subclass object. Some model architectures,
particularly multi-modal types, utilize Processors to combine text
encoding and image or audio encoding in a single entrypoint.
.. Note:: If a processor is supplied when saving a model, the
model will be unavailable for loading as a ``Pipeline`` or for
usage with pyfunc inference.
task: The transformers-specific task type of the model, or MLflow inference task type.
If provided a transformers-specific task type, these strings are utilized so
that a pipeline can be created with the appropriate internal call architecture
to meet the needs of a given model.
If this argument is provided as a inference task type or not specified, the
pipeline utilities within the transformers library will be used to infer the
correct task type. If the value specified is not a supported type,
an Exception will be thrown.
torch_dtype: The Pytorch dtype applied to the model when loading back. This is useful
when you want to save the model with a specific dtype that is different from the
dtype of the model when it was trained. If not specified, the current dtype of the
model instance will be used.
model_card: An Optional `ModelCard` instance from `huggingface-hub`. If provided, the
contents of the model card will be saved along with the provided
`transformers_model`. If not provided, an attempt will be made to fetch
the card from the base pretrained model that is provided (or the one that is
included within a provided `Pipeline`).
.. Note:: In order for a ModelCard to be fetched (if not provided),
the huggingface_hub package must be installed and the version
must be >=0.10.0
code_paths: {{ code_paths }}
mlflow_model: An MLflow model object that specifies the flavor that this model is being
added to.
signature: A Model Signature object that describes the input and output Schema of the
model. The model signature can be inferred using `infer_signature` function
of `mlflow.models.signature`.
.. code-block:: python
:caption: Example
from mlflow.models import infer_signature
from mlflow.transformers import generate_signature_output
from transformers import pipeline
en_to_de = pipeline("translation_en_to_de")
data = "MLflow is great!"
output = generate_signature_output(en_to_de, data)
signature = infer_signature(data, output)
mlflow.transformers.save_model(
transformers_model=en_to_de,
path="/path/to/save/model",
signature=signature,
input_example=data,
)
loaded = mlflow.pyfunc.load_model("/path/to/save/model")
print(loaded.predict(data))
# MLflow ist großartig!
If an input_example is provided and the signature is not, a signature will
be inferred automatically and applied to the MLmodel file iff the
pipeline type is a text-based model (NLP). If the pipeline type is not
a supported type, this inference functionality will not function correctly
and a warning will be issued. In order to ensure that a precise signature
is logged, it is recommended to explicitly provide one.
input_example: {{ input_example }}
pip_requirements: {{ pip_requirements }}
extra_pip_requirements: {{ extra_pip_requirements }}
conda_env: {{ conda_env }}
metadata: {{ metadata }}
model_config:
A dict of valid overrides that can be applied to a pipeline instance during inference.
These arguments are used exclusively for the case of loading the model as a ``pyfunc``
Model or for use in Spark.
These values are not applied to a returned Pipeline from a call to
``mlflow.transformers.load_model()``
.. Warning:: If the key provided is not compatible with either the
Pipeline instance for the task provided or is not a valid
override to any arguments available in the Model, an
Exception will be raised at runtime. It is very important
to validate the entries in this dictionary to ensure
that they are valid prior to saving or logging.
An example of providing overrides for a question generation model:
.. code-block:: python
from transformers import pipeline, AutoTokenizer
task = "text-generation"
architecture = "gpt2"
sentence_pipeline = pipeline(
task=task,
tokenizer=AutoTokenizer.from_pretrained(architecture),
model=architecture,
)
# Validate that the overrides function
prompts = ["Generative models are", "I'd like a coconut so that I can"]
# validation of config prior to save or log
model_config = {
"top_k": 2,
"num_beams": 5,
"max_length": 30,
"temperature": 0.62,
"top_p": 0.85,
"repetition_penalty": 1.15,
}
# Verify that no exceptions are thrown
sentence_pipeline(prompts, **model_config)
mlflow.transformers.save_model(
transformers_model=sentence_pipeline,
path="/path/for/model",
task=task,
model_config=model_config,
)
prompt_template: {{ prompt_template }}
save_pretrained: {{ save_pretrained }}
kwargs: Optional additional configurations for transformers serialization.
"""
import transformers
_validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements)
path = pathlib.Path(path).absolute()
_validate_and_prepare_target_save_path(str(path))
code_dir_subpath = _validate_and_copy_code_paths(code_paths, str(path))
if isinstance(transformers_model, transformers.Pipeline):
_validate_transformers_model_dict(transformers_model)
built_pipeline = transformers_model
elif isinstance(transformers_model, dict):
_validate_transformers_model_dict(transformers_model)
built_pipeline = _build_pipeline_from_model_input(transformers_model, task=task)
elif isinstance(transformers_model, str):
# When a string is passed, it should be a path to model checkpoint in local storage or DBFS
if transformers_model.startswith("dbfs:"):
# Replace the DBFS URI to the actual mount point
transformers_model = transformers_model.replace("dbfs:", "/dbfs", 1)
if task is None:
raise MlflowException(
"The `task` argument must be specified when logging a model from a local "
"checkpoint. Please provide the task type of the pipeline.",
error_code=INVALID_PARAMETER_VALUE,
)
if not save_pretrained:
raise MlflowException(
"The `save_pretrained` argument must be set to True when logging a model from a "
"local checkpoint. Please set `save_pretrained=True`.",
error_code=INVALID_PARAMETER_VALUE,
)
# Create a dummy pipeline object to be used for saving the model
built_pipeline = _DummyPipeline(
task=task, model=_DummyModel(name_or_path=transformers_model)
)
else:
raise MlflowException(
"The `transformers_model` must be one of the following types: \n"
" (1) a transformers Pipeline\n"
" (2) a dictionary of components for a transformers Pipeline\n"
" (3) a path to a local/DBFS directory containing a transformers model checkpoint.\n"
f"received: {type(transformers_model)}",
error_code=INVALID_PARAMETER_VALUE,
)
# Verify that the model has not been loaded to distributed memory
# NB: transformers does not correctly save a model whose weights have been loaded
# using accelerate iff the model weights have been loaded using a device_map that is
# heterogeneous. There is a distinct possibility for a partial write to occur, causing an
# invalid state of the model's weights in this scenario. Hence, we raise.
# We might be able to remove this check once this PR is merged to transformers:
# https://github.com/huggingface/transformers/issues/20072
if _is_model_distributed_in_memory(built_pipeline.model):
raise MlflowException(
"The model that is attempting to be saved has been loaded into memory "
"with an incompatible configuration. If you are using the accelerate "
"library to load your model, please ensure that it is saved only after "
"loading with the default device mapping. Do not specify `device_map` "
"and please try again."
)
if mlflow_model is None:
mlflow_model = Model()
if task and task.startswith(_LLM_INFERENCE_TASK_PREFIX):
llm_inference_task = task
# For local checkpoint saving, we set built_pipeline.task to the original `task`
# argument value earlier, which is LLM v1 task. Thereby here we update it to the
# corresponding Transformers task type.
if isinstance(transformers_model, str):
default_task = _get_default_task_for_llm_inference_task(llm_inference_task)
built_pipeline = built_pipeline._replace(task=default_task)
_validate_llm_inference_task_type(llm_inference_task, built_pipeline.task)
else:
llm_inference_task = None
if llm_inference_task:
mlflow_model.signature = infer_signature_from_llm_inference_task(
llm_inference_task, signature
)
elif signature is not None:
mlflow_model.signature = signature
if input_example is not None:
input_example = format_input_example_for_special_cases(input_example, built_pipeline)
_save_example(mlflow_model, input_example, str(path))
if metadata is not None:
mlflow_model.metadata = metadata
# Check task consistency between model metadata and task argument
# NB: Using mlflow_model.metadata instead of passed metadata argument directly, because
# metadata argument is not directly propagated from log_model() to save_model(), instead
# via the mlflow_model object attribute.
if (
mlflow_model.metadata is not None
and (metadata_task := mlflow_model.metadata.get(_METADATA_LLM_INFERENCE_TASK_KEY))
and metadata_task != task
):
raise MlflowException(
f"LLM v1 task type '{metadata_task}' is specified in "
"metadata, but it doesn't match the task type provided in the `task` argument: "
f"'{task}'. The mismatched task type may cause incorrect model inference behavior. "
"Please provide the correct LLM v1 task type in the `task` argument. E.g. "
f'`mlflow.transformers.save_model(task="{metadata_task}", ...)`',
error_code=INVALID_PARAMETER_VALUE,
)
if prompt_template is not None:
# prevent saving prompt templates for unsupported pipeline types
if built_pipeline.task not in _SUPPORTED_PROMPT_TEMPLATING_TASK_TYPES:
raise MlflowException(
f"Prompt templating is not supported for the `{built_pipeline.task}` task type. "
f"Supported task types are: {_SUPPORTED_PROMPT_TEMPLATING_TASK_TYPES}."
)
_validate_prompt_template(prompt_template)
if mlflow_model.metadata:
mlflow_model.metadata[FlavorKey.PROMPT_TEMPLATE] = prompt_template
else:
mlflow_model.metadata = {FlavorKey.PROMPT_TEMPLATE: prompt_template}
if is_peft_model(built_pipeline.model):
_logger.info(
"Overriding save_pretrained to False for PEFT models, following the Transformers "
"behavior. The PEFT adaptor and config will be saved, but the base model weights "
"will not and reference to the HuggingFace Hub repository will be logged instead."
)
# This will only save PEFT adaptor weights and config, not the base model weights
built_pipeline.model.save_pretrained(path.joinpath(_PEFT_ADAPTOR_DIR_NAME))
save_pretrained = False
if not save_pretrained and not is_valid_hf_repo_id(built_pipeline.model.name_or_path):
_logger.warning(
"The save_pretrained parameter is set to False, but the specified model does not "
"have a valid HuggingFace Hub repository identifier. Therefore, the weights will "
"be saved to disk anyway."
)
save_pretrained = True
# Create the flavor configuration
if isinstance(transformers_model, str):
flavor_conf = build_flavor_config_from_local_checkpoint(
transformers_model, built_pipeline.task, processor, torch_dtype
)
else:
flavor_conf = build_flavor_config(built_pipeline, processor, torch_dtype, save_pretrained)
if llm_inference_task:
flavor_conf.update({_LLM_INFERENCE_TASK_KEY: llm_inference_task})
if mlflow_model.metadata:
mlflow_model.metadata[_METADATA_LLM_INFERENCE_TASK_KEY] = llm_inference_task
else:
mlflow_model.metadata = {_METADATA_LLM_INFERENCE_TASK_KEY: llm_inference_task}
mlflow_model.add_flavor(
FLAVOR_NAME,
transformers_version=transformers.__version__,
code=code_dir_subpath,
**flavor_conf,
)
# Flavor config should not be mutated after being added to MLModel
flavor_conf = MappingProxyType(flavor_conf)
# Save pipeline model and components weights
if save_pretrained:
if isinstance(transformers_model, str):
save_local_checkpoint(path, transformers_model, flavor_conf, processor)
else:
save_pipeline_pretrained_weights(path, built_pipeline, flavor_conf, processor)
else:
repo = built_pipeline.model.name_or_path
_logger.info(
"Skipping saving pretrained model weights to disk as the save_pretrained argument"
f"is set to False. The reference to the HuggingFace Hub repository {repo} "
"will be logged instead."
)
model_name = built_pipeline.model.name_or_path
# Get the model card from either the argument or the HuggingFace marketplace
card_data = model_card or _fetch_model_card(model_name)
# If the card data can be acquired, save the text and the data separately
_write_card_data(card_data, path)
# Write the license information (or guidance) along with the model
_write_license_information(model_name, card_data, path)
# Only allow a subset of task types to have a pyfunc definition.
# Currently supported types are NLP-based language tasks which have a pipeline definition
# consisting exclusively of a Model and a Tokenizer.
if (
# TODO: when a local checkpoint path is provided as a model, we assume it is eligible
# for pyfunc prediction. This may not be true for all cases, so we should revisit this.
isinstance(transformers_model, str) or _should_add_pyfunc_to_model(built_pipeline)
):
if mlflow_model.signature is None:
mlflow_model.signature = infer_or_get_default_signature(
pipeline=built_pipeline,
example=input_example,
model_config=model_config,
flavor_config=flavor_conf,
)
# if pipeline is text-generation and a prompt template is specified,
# provide the return_full_text=False config by default to avoid confusing
# extra text for end-users
if prompt_template is not None and built_pipeline.task == "text-generation":
return_full_text_key = "return_full_text"
model_config = model_config or {}
if return_full_text_key not in model_config:
model_config[return_full_text_key] = False
_logger.info(_PROMPT_TEMPLATE_RETURN_FULL_TEXT_INFO)
pyfunc.add_to_model(
mlflow_model,
loader_module="mlflow.transformers",
conda_env=_CONDA_ENV_FILE_NAME,
python_env=_PYTHON_ENV_FILE_NAME,
code=code_dir_subpath,
model_config=model_config,
)
else:
if processor:
reason = "the model has been saved with a 'processor' argument supplied."
else:
reason = (
"the model is not a language-based model and requires a complex input type "
"that is currently not supported."
)
_logger.warning(
f"This model is unable to be used for pyfunc prediction because {reason} "
f"The pyfunc flavor will not be added to the Model."
)
if size := get_total_file_size(path):
mlflow_model.model_size_bytes = size
mlflow_model.save(str(path.joinpath(MLMODEL_FILE_NAME)))
if conda_env is None:
if pip_requirements is None:
default_reqs = get_default_pip_requirements(built_pipeline.model)
if isinstance(transformers_model, str) or is_peft_model(built_pipeline.model):
_logger.info(
"A local checkpoint path or PEFT model is given as the `transformers_model`. "
"To avoid loading the full model into memory, we don't infer the pip "
"requirement for the model. Instead, we will use the default requirements, "
"but it may not capture all required pip libraries for the model. Consider "
"providing the pip requirements explicitly."
)
else:
# Infer the pip requirements with a timeout to avoid hanging at prediction
inferred_reqs = infer_pip_requirements(
model_uri=str(path),
flavor=FLAVOR_NAME,
fallback=default_reqs,
timeout=MLFLOW_INPUT_EXAMPLE_INFERENCE_TIMEOUT.get(),
)
default_reqs = set(inferred_reqs).union(default_reqs)
default_reqs = sorted(default_reqs)
else:
default_reqs = None
conda_env, pip_requirements, pip_constraints = _process_pip_requirements(
default_reqs, pip_requirements, extra_pip_requirements
)
else:
conda_env, pip_requirements, pip_constraints = _process_conda_env(conda_env)
with path.joinpath(_CONDA_ENV_FILE_NAME).open("w") as f:
yaml.safe_dump(conda_env, stream=f, default_flow_style=False)
if pip_constraints:
write_to(str(path.joinpath(_CONSTRAINTS_FILE_NAME)), "\n".join(pip_constraints))
write_to(str(path.joinpath(_REQUIREMENTS_FILE_NAME)), "\n".join(pip_requirements))
_PythonEnv.current().to_yaml(str(path.joinpath(_PYTHON_ENV_FILE_NAME)))
@docstring_version_compatibility_warning(integration_name=FLAVOR_NAME)
@format_docstring(LOG_MODEL_PARAM_DOCS.format(package_name=FLAVOR_NAME))
def log_model(
transformers_model,
artifact_path: str | None = None,
processor=None,
task: str | None = None,
torch_dtype: torch.dtype | None = None,
model_card=None,
code_paths: list[str] | None = None,
registered_model_name: str | None = None,
signature: ModelSignature | None = None,
input_example: ModelInputExample | None = None,
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
pip_requirements: list[str] | str | None = None,
extra_pip_requirements: list[str] | str | None = None,
conda_env=None,
metadata: dict[str, Any] | None = None,
model_config: dict[str, Any] | None = None,
prompt_template: str | None = None,
save_pretrained: bool = True,
prompts: list[str | Prompt] | None = None,
name: str | None = None,
params: dict[str, Any] | None = None,
tags: dict[str, Any] | None = None,
model_type: str | None = None,
step: int = 0,
model_id: str | None = None,
**kwargs,
):
"""
Log a ``transformers`` object as an MLflow artifact for the current run. Note that
logging transformers models with custom code (i.e. models that require
``trust_remote_code=True``) requires ``transformers >= 4.26.0``.
Args:
transformers_model:
The transformers model to save. This can be one of the following format:
1. A transformers `Pipeline` instance.
2. A dictionary that maps required components of a pipeline to the named keys
of ["model", "image_processor", "tokenizer", "feature_extractor"].
The `model` key in the dictionary must map to a value that inherits from
`PreTrainedModel`, `TFPreTrainedModel`, or `FlaxPreTrainedModel`.
All other component entries in the dictionary must support the defined task
type that is associated with the base model type configuration.
3. A string that represents a path to a local/DBFS directory containing a model
checkpoint. The directory must contain a `config.json` file that is required
for loading the transformers model. This is particularly useful when logging
a model that cannot be loaded into memory for serialization.
An example of specifying a `Pipeline` from a default pipeline instantiation:
.. code-block:: python
from transformers import pipeline
qa_pipe = pipeline("question-answering", "csarron/mobilebert-uncased-squad-v2")
with mlflow.start_run():
mlflow.transformers.log_model(
transformers_model=qa_pipe,
name="model",
)
An example of specifying component-level parts of a transformers model is shown below:
.. code-block:: python
from transformers import MobileBertForQuestionAnswering, AutoTokenizer
architecture = "csarron/mobilebert-uncased-squad-v2"
tokenizer = AutoTokenizer.from_pretrained(architecture)
model = MobileBertForQuestionAnswering.from_pretrained(architecture)
with mlflow.start_run():
components = {
"model": model,
"tokenizer": tokenizer,
}
mlflow.transformers.log_model(
transformers_model=components,
name="model",
)
An example of specifying a local checkpoint path is shown below:
.. code-block:: python
with mlflow.start_run():
mlflow.transformers.log_model(
transformers_model="path/to/local/checkpoint",
name="model",
)
artifact_path: Deprecated. Use `name` instead.
processor: An optional ``Processor`` subclass object. Some model architectures,
particularly multi-modal types, utilize Processors to combine text
encoding and image or audio encoding in a single entrypoint.
.. Note:: If a processor is supplied when logging a model, the
model will be unavailable for loading as a ``Pipeline`` or for usage
with pyfunc inference.
task: The transformers-specific task type of the model. These strings are utilized so
that a pipeline can be created with the appropriate internal call architecture
to meet the needs of a given model. If this argument is not specified, the
pipeline utilities within the transformers library will be used to infer the
correct task type. If the value specified is not a supported type within the
version of transformers that is currently installed, an Exception will be thrown.
torch_dtype: The Pytorch dtype applied to the model when loading back. This is useful
when you want to save the model with a specific dtype that is different from the
dtype of the model when it was trained. If not specified, the current dtype of the
model instance will be used.
model_card: An Optional `ModelCard` instance from `huggingface-hub`. If provided, the
contents of the model card will be saved along with the provided
`transformers_model`. If not provided, an attempt will be made to fetch
the card from the base pretrained model that is provided (or the one that is
included within a provided `Pipeline`).
.. Note:: In order for a ModelCard to be fetched (if not provided),
the huggingface_hub package must be installed and the version
must be >=0.10.0
code_paths: {{ code_paths }}
registered_model_name: If given, create a model
version under ``registered_model_name``, also creating a
registered model if one with the given name does not exist.
signature: A Model Signature object that describes the input and output Schema of the
model. The model signature can be inferred using `infer_signature` function
of `mlflow.models.signature`.
.. code-block:: python
:caption: Example
from mlflow.models import infer_signature
from mlflow.transformers import generate_signature_output
from transformers import pipeline
en_to_de = pipeline("translation_en_to_de")
data = "MLflow is great!"
output = generate_signature_output(en_to_de, data)
signature = infer_signature(data, output)
with mlflow.start_run() as run:
mlflow.transformers.log_model(
transformers_model=en_to_de,
name="english_to_german_translator",
signature=signature,
input_example=data,
)
model_uri = f"runs:/{run.info.run_id}/english_to_german_translator"
loaded = mlflow.pyfunc.load_model(model_uri)
print(loaded.predict(data))
# MLflow ist großartig!
If an input_example is provided and the signature is not, a signature will
be inferred automatically and applied to the MLmodel file iff the
pipeline type is a text-based model (NLP). If the pipeline type is not
a supported type, this inference functionality will not function correctly
and a warning will be issued. In order to ensure that a precise signature
is logged, it is recommended to explicitly provide one.
input_example: {{ input_example }}
await_registration_for: Number of seconds to wait for the model version
to finish being created and is in ``READY`` status.
By default, the function waits for five minutes.
Specify 0 or None to skip waiting.
pip_requirements: {{ pip_requirements }}
extra_pip_requirements: {{ extra_pip_requirements }}
conda_env: {{ conda_env }}
metadata: {{ metadata }}
model_config:
A dict of valid overrides that can be applied to a pipeline instance during inference.
These arguments are used exclusively for the case of loading the model as a ``pyfunc``
Model or for use in Spark. These values are not applied to a returned Pipeline from a
call to ``mlflow.transformers.load_model()``
.. Warning:: If the key provided is not compatible with either the
Pipeline instance for the task provided or is not a valid
override to any arguments available in the Model, an
Exception will be raised at runtime. It is very important
to validate the entries in this dictionary to ensure
that they are valid prior to saving or logging.
An example of providing overrides for a question generation model:
.. code-block:: python
from transformers import pipeline, AutoTokenizer
task = "text-generation"
architecture = "gpt2"
sentence_pipeline = pipeline(
task=task,
tokenizer=AutoTokenizer.from_pretrained(architecture),
model=architecture,
)
# Validate that the overrides function
prompts = ["Generative models are", "I'd like a coconut so that I can"]
# validation of config prior to save or log
model_config = {
"top_k": 2,
"num_beams": 5,
"max_length": 30,
"temperature": 0.62,
"top_p": 0.85,
"repetition_penalty": 1.15,
}
# Verify that no exceptions are thrown
sentence_pipeline(prompts, **model_config)
with mlflow.start_run():
mlflow.transformers.log_model(
transformers_model=sentence_pipeline,
name="my_sentence_generator",
task=task,
model_config=model_config,
)
prompt_template: {{ prompt_template }}
save_pretrained: {{ save_pretrained }}
prompts: {{ prompts }}
name: {{ name }}
params: {{ params }}
tags: {{ tags }}
model_type: {{ model_type }}
step: {{ step }}
model_id: {{ model_id }}
kwargs: Additional arguments for :py:class:`mlflow.models.model.Model`
"""
return Model.log(
artifact_path=artifact_path,
name=name,
flavor=sys.modules[__name__], # Get the current module.
registered_model_name=registered_model_name,
await_registration_for=await_registration_for,
metadata=metadata,
transformers_model=transformers_model,
processor=processor,
task=task,
torch_dtype=torch_dtype,
model_card=model_card,
conda_env=conda_env,
code_paths=code_paths,
signature=signature,
input_example=input_example,
# NB: We don't validate the serving input if the provided model is a path
# to a local checkpoint. This is because the purpose of supporting that
# input format is to avoid loading large model into memory. Serving input
# validation loads the model into memory and make prediction, which is
# expensive and can cause OOM errors.
validate_serving_input=not isinstance(transformers_model, str),
pip_requirements=pip_requirements,
extra_pip_requirements=extra_pip_requirements,
model_config=model_config,
prompt_template=prompt_template,
save_pretrained=save_pretrained,
prompts=prompts,
params=params,
tags=tags,
model_type=model_type,
step=step,
model_id=model_id,
**kwargs,
)
@docstring_version_compatibility_warning(integration_name=FLAVOR_NAME)
def load_model(
model_uri: str, dst_path: str | None = None, return_type="pipeline", device=None, **kwargs
):
"""
Load a ``transformers`` object from a local file or a run.
Args:
model_uri: The location, in URI format, of the MLflow model. For example:
- ``/Users/me/path/to/local/model``
- ``relative/path/to/local/model``
- ``s3://my_bucket/path/to/model``
- ``runs:/<mlflow_run_id>/run-relative/path/to/model``
- ``mlflow-artifacts:/path/to/model``
For more information about supported URI schemes, see
`Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#
artifact-locations>`_.
dst_path: The local filesystem path to utilize for downloading the model artifact.
This directory must already exist if provided. If unspecified, a local output
path will be created.
return_type: A return type modifier for the stored ``transformers`` object.
If set as "components", the return type will be a dictionary of the saved
individual components of either the ``Pipeline`` or the pre-trained model.
The components for NLP-focused models will typically consist of a
return representation as shown below with a text-classification example:
.. code-block:: python
{"model": BertForSequenceClassification, "tokenizer": BertTokenizerFast}
Vision models will return an ``ImageProcessor`` instance of the appropriate
type, while multi-modal models will return both a ``FeatureExtractor`` and
a ``Tokenizer`` along with the model.
Returning "components" can be useful for certain model types that do not
have the desired pipeline return types for certain use cases.
If set as "pipeline", the model, along with any and all required
``Tokenizer``, ``FeatureExtractor``, ``Processor``, or ``ImageProcessor``
objects will be returned within a ``Pipeline`` object of the appropriate
type defined by the ``task`` set by the model instance type. To override
this behavior, supply a valid ``task`` argument during model logging or
saving. Default is "pipeline".
device: The device on which to load the model. Default is None. Use 0 to
load to the default GPU.
kwargs: Optional configuration options for loading of a ``transformers`` object.
For information on parameters and their usage, see
`transformers documentation <https://huggingface.co/docs/transformers/index>`_.
Returns:
A ``transformers`` model instance or a dictionary of components
"""
if return_type not in _SUPPORTED_RETURN_TYPES:
raise MlflowException(
f"The specified return_type mode '{return_type}' is unsupported. "
"Please select one of: 'pipeline' or 'components'.",
error_code=INVALID_PARAMETER_VALUE,
)
model_uri = str(model_uri)
local_model_path = _download_artifact_from_uri(artifact_uri=model_uri, output_path=dst_path)
flavor_config = _get_flavor_configuration_from_uri(model_uri, FLAVOR_NAME, _logger)
if return_type == "pipeline" and FlavorKey.PROCESSOR_TYPE in flavor_config:
raise MlflowException(
"This model has been saved with a processor. Processor objects are "
"not compatible with Pipelines. Please load this model by specifying "
"the 'return_type'='components'.",
error_code=BAD_REQUEST,
)
_add_code_from_conf_to_system_path(local_model_path, flavor_config)
return _load_model(local_model_path, flavor_config, return_type, device, **kwargs)
def persist_pretrained_model(model_uri: str) -> None:
"""
Persist Transformers pretrained model weights to the artifacts directory of the specified
model_uri. This API is primary used for updating an MLflow Model that was logged or saved
with setting save_pretrained=False. Such models cannot be registered to Databricks Workspace
Model Registry, due to the full pretrained model weights being absent in the artifacts.
Transformers models saved in this mode store only the reference to the HuggingFace Hub
repository. This API will download the model weights from the HuggingFace Hub repository
and save them in the artifacts of the given model_uri so that the model can be registered
to Databricks Workspace Model Registry.
Args:
model_uri: The URI of the existing MLflow Model of the Transformers flavor.
It must be logged/saved with save_pretrained=False.
Examples:
.. code-block:: python
import mlflow
# Saving a model with save_pretrained=False
with mlflow.start_run() as run:
model = pipeline("question-answering", "csarron/mobilebert-uncased-squad-v2")
mlflow.transformers.log_model(
transformers_model=model, name="pipeline", save_pretrained=False
)
# The model cannot be registered to the Model Registry as it is
try:
mlflow.register_model(f"runs:/{run.info.run_id}/pipeline", "qa_pipeline")
except MlflowException as e:
print(e.message)
# Use this API to persist the pretrained model weights
mlflow.transformers.persist_pretrained_model(f"runs:/{run.info.run_id}/pipeline")
# Now the model can be registered to the Model Registry
mlflow.register_model(f"runs:/{run.info.run_id}/pipeline", "qa_pipeline")
"""
# Check if the model weight already exists in the model artifact before downloading
root_uri, artifact_path = _get_root_uri_and_artifact_path(model_uri)
artifact_repo = get_artifact_repository(root_uri)
file_names = [os.path.basename(f.path) for f in artifact_repo.list_artifacts(artifact_path)]
if MLMODEL_FILE_NAME in file_names and _MODEL_BINARY_FILE_NAME in file_names:
_logger.info(
"The full pretrained model weight already exists in the artifact directory of the "
f"specified model_uri: {model_uri}. No action is needed."
)
return
with TempDir() as tmp_dir:
local_model_path = artifact_repo.download_artifacts(artifact_path, dst_path=tmp_dir.path())
pipeline = load_model(local_model_path, return_type="pipeline")
# Update MLModel flavor config
mlmodel_path = os.path.join(local_model_path, MLMODEL_FILE_NAME)
model_conf = Model.load(mlmodel_path)
updated_flavor_conf = update_flavor_conf_to_persist_pretrained_model(
model_conf.flavors[FLAVOR_NAME]
)
model_conf.add_flavor(FLAVOR_NAME, **updated_flavor_conf)
model_conf.save(mlmodel_path)
# Save pretrained weights
save_pipeline_pretrained_weights(
pathlib.Path(local_model_path), pipeline, updated_flavor_conf
)
# Upload updated local artifacts to MLflow
for dir_to_upload in (_MODEL_BINARY_FILE_NAME, _COMPONENTS_BINARY_DIR_NAME):
local_dir = os.path.join(local_model_path, dir_to_upload)
if not os.path.isdir(local_dir):
continue
try:
artifact_repo.log_artifacts(local_dir, os.path.join(artifact_path, dir_to_upload))
except Exception as e:
# NB: log_artifacts method doesn't support rollback for partial uploads,
raise MlflowException(
f"Failed to upload {local_dir} to the existing model_uri due to {e}."
"Some other files may have been uploaded."
) from e
# Upload MLModel file
artifact_repo.log_artifact(mlmodel_path, artifact_path)
_logger.info(f"The pretrained model has been successfully persisted in {model_uri}.")
def _is_model_distributed_in_memory(transformers_model):
"""Check if the model is distributed across multiple devices in memory."""
# Check if the model attribute exists. If not, accelerate was not used and the model can
# be safely saved
if not hasattr(transformers_model, "hf_device_map"):
return False
# If the device map has more than one unique value entry, then the weights are not within
# a contiguous memory system (VRAM, SYS, or DISK) and thus cannot be safely saved.
return len(set(transformers_model.hf_device_map.values())) > 1
# This function attempts to determine if a GPU is available for the PyTorch and TensorFlow libraries
def is_gpu_available():
# try pytorch and if it fails, try tf
is_gpu = None
try:
import torch
is_gpu = torch.cuda.is_available()
except ImportError:
pass
if is_gpu is None:
try:
import tensorflow as tf
is_gpu = tf.test.is_gpu_available()
except ImportError:
pass
if is_gpu is None:
is_gpu = False
return is_gpu
def _load_model(path: str, flavor_config, return_type: str, device=None, **kwargs):
"""
Loads components from a locally serialized ``Pipeline`` object.
"""
import transformers
conf = {
"task": flavor_config[FlavorKey.TASK],
}
if framework := flavor_config.get(FlavorKey.FRAMEWORK):
conf["framework"] = framework
# Note that we don't set the device in the conf yet because device is
# incompatible with device_map.
accelerate_model_conf = {}
if MLFLOW_HUGGINGFACE_USE_DEVICE_MAP.get():
device_map_strategy = MLFLOW_HUGGINGFACE_DEVICE_MAP_STRATEGY.get()
conf["device_map"] = device_map_strategy
accelerate_model_conf["device_map"] = device_map_strategy
# Cannot use device with device_map
if device is not None:
raise MlflowException.invalid_parameter_value(
"The environment variable MLFLOW_HUGGINGFACE_USE_DEVICE_MAP is set to True, but "
f"the `device` argument is provided with value {device}. The device_map and "
"`device` argument cannot be used together. Set MLFLOW_HUGGINGFACE_USE_DEVICE_MAP "
"to False to specify a particular device ID, or pass None for the `device` "
"argument to use device_map."
)
device = None
elif device is None:
if device_value := MLFLOW_DEFAULT_PREDICTION_DEVICE.get():
try:
device = int(device_value)
except ValueError:
_logger.warning(
f"Invalid value for {MLFLOW_DEFAULT_PREDICTION_DEVICE}: {device_value}. "
f"{MLFLOW_DEFAULT_PREDICTION_DEVICE} value must be an integer. "
f"Setting to: {_TRANSFORMERS_DEFAULT_CPU_DEVICE_ID}."
)
device = _TRANSFORMERS_DEFAULT_CPU_DEVICE_ID
elif is_gpu_available():
device = _TRANSFORMERS_DEFAULT_GPU_DEVICE_ID
if device is not None:
conf["device"] = device
accelerate_model_conf["device"] = device
if dtype_val := kwargs.get(_TORCH_DTYPE_KEY) or flavor_config.get(FlavorKey.TORCH_DTYPE):
if isinstance(dtype_val, str):
dtype_val = _deserialize_torch_dtype(dtype_val)
conf[_TORCH_DTYPE_KEY] = dtype_val
flavor_config[_TORCH_DTYPE_KEY] = dtype_val
accelerate_model_conf[_TORCH_DTYPE_KEY] = dtype_val
accelerate_model_conf["low_cpu_mem_usage"] = MLFLOW_HUGGINGFACE_USE_LOW_CPU_MEM_USAGE.get()
# Load model and components either from local or from HuggingFace Hub. We check for the
# presence of the model revision (a commit hash of the hub repository) that is only present
# in the model logged with `save_pretrained=False
if FlavorKey.MODEL_REVISION not in flavor_config:
model_and_components = load_model_and_components_from_local(
path=pathlib.Path(path),
flavor_conf=flavor_config,
accelerate_conf=accelerate_model_conf,
device=device,
)
else:
model_and_components = load_model_and_components_from_huggingface_hub(
flavor_conf=flavor_config, accelerate_conf=accelerate_model_conf, device=device
)
# Load and apply PEFT adaptor if saved
if peft_adapter_dir := flavor_config.get(FlavorKey.PEFT, None):
model_and_components[FlavorKey.MODEL] = get_model_with_peft_adapter(
base_model=model_and_components[FlavorKey.MODEL],
peft_adapter_path=os.path.join(path, peft_adapter_dir),
)
conf = {**conf, **model_and_components}
if return_type == "pipeline":
conf.update(**kwargs)
with suppress_logs("transformers.pipelines.base", filter_regex=_PEFT_PIPELINE_ERROR_MSG):
return transformers.pipeline(**conf)
elif return_type == "components":
return conf
def _fetch_model_card(model_name):
"""
Attempts to retrieve the model card for the specified model architecture iff the
`huggingface_hub` library is installed. If a card cannot be found in the registry or
the library is not installed, returns None.
"""
try:
import huggingface_hub as hub
except ImportError:
_logger.warning(
"Unable to store ModelCard data with the saved artifact. In order to "
"preserve this information, please install the huggingface_hub package "
"by running 'pip install huggingingface_hub>0.10.0'"
)
return
if hasattr(hub, "ModelCard"):
try:
return hub.ModelCard.load(model_name)
except Exception as e:
_logger.warning(f"The model card could not be retrieved from the hub due to {e}")
else:
_logger.warning(
"The version of huggingface_hub that is installed does not provide "
f"ModelCard functionality. You have version {hub.__version__} installed. "
"Update huggingface_hub to >= '0.10.0' to retrieve the ModelCard data."
)
def _write_card_data(card_data, path):
"""
Writes the card data, if specified or available, to the provided path in two separate files
"""
if card_data:
try:
path.joinpath(_CARD_TEXT_FILE_NAME).write_text(card_data.text, encoding="utf-8")
except UnicodeError as e:
_logger.warning(f"Unable to save the model card text due to: {e}")
with path.joinpath(_CARD_DATA_FILE_NAME).open("w") as file:
yaml.safe_dump(
card_data.data.to_dict(), stream=file, default_flow_style=False, encoding="utf-8"
)
def _extract_license_file_from_repository(model_name):
"""Returns the top-level file inventory of `RepoFile` objects from the huggingface hub"""
try:
import huggingface_hub as hub
except ImportError:
_logger.debug(
f"Unable to list repository contents for the model repo {model_name}. In order "
"to enable repository listing functionality, please install the huggingface_hub "
"package by running `pip install huggingface_hub>0.10.0"
)
return
try:
files = hub.list_repo_files(model_name)
return next(file for file in files if _LICENSE_FILE_PATTERN.search(file))
except Exception as e:
_logger.debug(
f"Failed to retrieve repository file listing data for {model_name} due to {e}"
)
def _write_license_information(model_name, card_data, path):
"""Writes the license file or instructions to retrieve license information."""
fallback = (
f"A license file could not be found for the '{model_name}' repository. \n"
"To ensure that you are in compliance with the license requirements for this "
f"model, please visit the model repository here: https://huggingface.co/{model_name}"
)
if license_file := _extract_license_file_from_repository(model_name):
try:
import huggingface_hub as hub
license_location = hub.hf_hub_download(repo_id=model_name, filename=license_file)
except Exception as e:
_logger.warning(f"Failed to download the license file due to: {e}")
else:
local_license_path = pathlib.Path(license_location)
target_path = path.joinpath(local_license_path.name)
try:
shutil.copy(local_license_path, target_path)
return
except Exception as e:
_logger.warning(f"The license file could not be copied due to: {e}")
# Fallback or card data license info
if card_data and card_data.data.license != "other":
fallback = f"{fallback}\nThe declared license type is: '{card_data.data.license}'"
else:
_logger.warning(
"Unable to find license information for this model. Please verify "
"permissible usage for the model you are storing prior to use."
)
path.joinpath(_LICENSE_FILE_NAME).write_text(fallback, encoding="utf-8")
def _get_supported_pretrained_model_types():
"""
Users might not have all the necessary libraries installed to determine the supported model
"""
supported_model_types = ()
try:
from transformers import FlaxPreTrainedModel
supported_model_types += (FlaxPreTrainedModel,)
except Exception:
pass
try:
from transformers import PreTrainedModel
supported_model_types += (PreTrainedModel,)
except Exception:
pass
try:
from transformers import TFPreTrainedModel
supported_model_types += (TFPreTrainedModel,)
except Exception:
pass
return supported_model_types
def _build_pipeline_from_model_input(model_dict: dict[str, Any], task: str | None) -> Pipeline:
"""
Utility for generating a pipeline from component parts. If required components are not
specified, use the transformers library pipeline component validation to force raising an
exception. The underlying Exception thrown in transformers is verbose enough for diagnosis.
"""
from transformers import pipeline
model = model_dict[FlavorKey.MODEL]
if not (isinstance(model, _get_supported_pretrained_model_types()) or is_peft_model(model)):
raise MlflowException(
"The supplied model type is unsupported. The model must be one of: "
"PreTrainedModel, TFPreTrainedModel, FlaxPreTrainedModel, or PeftModel",
error_code=INVALID_PARAMETER_VALUE,
)
if task is None or task.startswith(_LLM_INFERENCE_TASK_PREFIX):
default_task = _get_default_task_for_llm_inference_task(task)
task = _get_task_for_model(model.name_or_path, default_task=default_task)
try:
with suppress_logs("transformers.pipelines.base", filter_regex=_PEFT_PIPELINE_ERROR_MSG):
return pipeline(task=task, **model_dict)
except Exception as e:
raise MlflowException(
"The provided model configuration cannot be created as a Pipeline. "
"Please verify that all required and compatible components are "
"specified with the correct keys.",
error_code=INVALID_PARAMETER_VALUE,
) from e
def _get_task_for_model(model_name_or_path: str, default_task=None) -> str:
"""
Get the Transformers pipeline task type fro the model instance.
NB: The get_task() function only works for remote models available in the Hugging
Face hub, so the default task should be supplied when using a custom local model.
"""
from transformers.pipelines import get_supported_tasks, get_task
try:
model_task = get_task(model_name_or_path)
if model_task in get_supported_tasks():
return model_task
elif default_task is not None:
_logger.warning(
f"The task '{model_task}' inferred from the model is not"
"supported by the transformers pipeline. MLflow will "
f"construct the pipeline with the fallback task {default_task} "
"inferred from the specified 'llm/v1/xxx' task."
)
return default_task
else:
raise MlflowException(
f"Cannot construct transformers pipeline because the task '{model_task}' "
"inferred from the model is not supported by the transformers pipeline. "
"Please construct the pipeline instance manually and pass it to the "
"`log_model` or `save_model` function."
)
except RuntimeError as e:
if default_task:
return default_task
raise MlflowException(
"The task could not be inferred from the model. If you are saving a custom "
"local model that is not available in the Hugging Face hub, please provide "
"the `task` argument to the `log_model` or `save_model` function.",
error_code=INVALID_PARAMETER_VALUE,
) from e
def _validate_llm_inference_task_type(llm_inference_task: str, pipeline_task: str) -> None:
"""
Validates that an ``inference_task`` type is supported by ``transformers`` pipeline type.
"""
supported_llm_inference_tasks = _SUPPORTED_LLM_INFERENCE_TASK_TYPES_BY_PIPELINE_TASK.get(
pipeline_task, []
)
if llm_inference_task not in supported_llm_inference_tasks:
raise MlflowException(
f"The task provided is invalid. '{llm_inference_task}' is not a supported task for "
f"the {pipeline_task} pipeline. Must be one of {supported_llm_inference_tasks}",
error_code=INVALID_PARAMETER_VALUE,
)
def _get_engine_type(model):
"""
Determines the underlying execution engine for the model based on the 3 currently supported
deep learning framework backends: ``tensorflow``, ``torch``, or ``flax``.
"""
from transformers import FlaxPreTrainedModel, PreTrainedModel, TFPreTrainedModel
from transformers.utils import is_torch_available
if is_peft_model(model):
model = get_peft_base_model(model)
for cls in model.__class__.__mro__:
if issubclass(cls, TFPreTrainedModel):
return "tensorflow"
elif issubclass(cls, PreTrainedModel):
return "torch"
elif issubclass(cls, FlaxPreTrainedModel):
return "flax"
# As a fallback, we check current environment to determine the engine type
return "torch" if is_torch_available() else "tensorflow"
def _should_add_pyfunc_to_model(pipeline) -> bool:
"""
Discriminator for determining whether a particular task type and model instance from within
a ``Pipeline`` is currently supported for the pyfunc flavor.
Image and Video pipelines can still be logged and used, but are not available for
loading as pyfunc.
Similarly, esoteric model types (Graph Models, Timeseries Models, and Reinforcement Learning
Models) are not permitted for loading as pyfunc due to the complex input types that, in
order to support, will require significant modifications (breaking changes) to the pyfunc
contract.
"""
import transformers
exclusion_model_types = {
"GraphormerPreTrainedModel",
"InformerPreTrainedModel",
"TimeSeriesTransformerPreTrainedModel",
"DecisionTransformerPreTrainedModel",
}
# NB: When pyfunc functionality is added for these pipeline types over time, remove the
# entries from the following list.
exclusion_pipeline_types = [
"DocumentQuestionAnsweringPipeline",
"ImageToTextPipeline",
"VisualQuestionAnsweringPipeline",
"ImageSegmentationPipeline",
"DepthEstimationPipeline",
"ObjectDetectionPipeline",
"VideoClassificationPipeline",
"ZeroShotImageClassificationPipeline",
"ZeroShotObjectDetectionPipeline",
"ZeroShotAudioClassificationPipeline",
]
for model_type in exclusion_model_types:
if hasattr(transformers, model_type):
if isinstance(pipeline.model, getattr(transformers, model_type)):
return False
if type(pipeline).__name__ in exclusion_pipeline_types:
return False
return True
def _get_model_config(local_path, pyfunc_config):
"""
Load the model configuration if it was provided for use in the `_TransformersWrapper` pyfunc
Model wrapper.
"""
config_path = local_path.joinpath("inference_config.txt")
if config_path.exists():
_logger.warning(
"Inference config stored in file ``inference_config.txt`` is deprecated. New logged "
"models will store the model configuration in the ``pyfunc`` flavor configuration."
)
return json.loads(config_path.read_text())
else:
return pyfunc_config or {}
def _load_pyfunc(path, model_config: dict[str, Any] | None = None):
"""
Loads the model as pyfunc model
"""
local_path = pathlib.Path(path)
flavor_configuration = _get_flavor_configuration(local_path, FLAVOR_NAME)
model_config = _get_model_config(local_path.joinpath(_COMPONENTS_BINARY_DIR_NAME), model_config)
prompt_template = _get_prompt_template(local_path)
return _TransformersWrapper(
_load_model(str(local_path), flavor_configuration, "pipeline"),
flavor_configuration,
model_config,
prompt_template,
)
def _is_conversational_pipeline(pipeline):
"""
Checks if the pipeline is a ConversationalPipeline.
"""
if cp := _try_import_conversational_pipeline():
return isinstance(pipeline, cp)
return False
def _try_import_conversational_pipeline():
"""
Try importing ConversationalPipeline because for version > 4.41.2
it is removed from the transformers package.
"""
try:
from transformers import ConversationalPipeline
return ConversationalPipeline
except ImportError:
return
def generate_signature_output(pipeline, data, model_config=None, params=None, flavor_config=None):
"""
Utility for generating the response output for the purposes of extracting an output signature
for model saving and logging. This function simulates loading of a saved model or pipeline
as a ``pyfunc`` model without having to incur a write to disk.
Args:
pipeline: A ``transformers`` pipeline object. Note that component-level or model-level
inputs are not permitted for extracting an output example.
data: An example input that is compatible with the given pipeline
model_config: Any additional model configuration, provided as kwargs, to inform
the format of the output type from a pipeline inference call.
params: A dictionary of additional parameters to pass to the pipeline for inference.
flavor_config: The flavor configuration for the model.
Returns:
The output from the ``pyfunc`` pipeline wrapper's ``predict`` method
"""
import transformers
from mlflow.transformers import signature
if not isinstance(pipeline, transformers.Pipeline):
raise MlflowException(
f"The pipeline type submitted is not a valid transformers Pipeline. "
f"The type {type(pipeline).__name__} is not supported.",
error_code=INVALID_PARAMETER_VALUE,
)
return signature.generate_signature_output(pipeline, data, model_config, params)
| _DummyPipeline |
python | getsentry__sentry | tests/sentry/integrations/jira/test_sentry_installation.py | {
"start": 1876,
"end": 2647
} | class ____(JiraSentryInstallationViewTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
def assert_no_errors(self, response):
assert REFRESH_REQUIRED not in response.content
assert UNABLE_TO_VERIFY_INSTALLATION.encode() not in response.content
@patch("sentry.integrations.jira.views.sentry_installation.get_integration_from_request")
def test_simple_get(self, mock_get_integration_from_request: MagicMock) -> None:
mock_get_integration_from_request.return_value = self.integration
response = self.client.get(self.path)
assert response.status_code == 200
self.assert_no_errors(response)
assert CLICK_TO_FINISH in response.content
| JiraSentryInstallationViewTest |
python | protocolbuffers__protobuf | python/google/protobuf/internal/message_factory_test.py | {
"start": 866,
"end": 14236
} | class ____(unittest.TestCase):
def setUp(self):
self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb)
self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb)
def _ExerciseDynamicClass(self, cls):
msg = cls()
msg.mandatory = 42
msg.nested_factory_2_enum = 0
msg.nested_factory_2_message.value = 'nested message value'
msg.factory_1_message.factory_1_enum = 1
msg.factory_1_message.nested_factory_1_enum = 0
msg.factory_1_message.nested_factory_1_message.value = (
'nested message value')
msg.factory_1_message.scalar_value = 22
msg.factory_1_message.list_value.extend([u'one', u'two', u'three'])
msg.factory_1_message.list_value.append(u'four')
msg.factory_1_enum = 1
msg.nested_factory_1_enum = 0
msg.nested_factory_1_message.value = 'nested message value'
msg.circular_message.mandatory = 1
msg.circular_message.circular_message.mandatory = 2
msg.circular_message.scalar_value = 'one deep'
msg.scalar_value = 'zero deep'
msg.list_value.extend([u'four', u'three', u'two'])
msg.list_value.append(u'one')
msg.grouped.add()
msg.grouped[0].part_1 = 'hello'
msg.grouped[0].part_2 = 'world'
msg.grouped.add(part_1='testing', part_2='123')
msg.loop.loop.mandatory = 2
msg.loop.loop.loop.loop.mandatory = 4
serialized = msg.SerializeToString()
converted = factory_test2_pb2.Factory2Message.FromString(serialized)
reserialized = converted.SerializeToString()
self.assertEqual(serialized, reserialized)
result = cls.FromString(reserialized)
self.assertEqual(msg, result)
def testGetMessageClass(self):
db = descriptor_database.DescriptorDatabase()
pool = descriptor_pool.DescriptorPool(db)
db.Add(self.factory_test1_fd)
db.Add(self.factory_test2_fd)
cls = message_factory.GetMessageClass(pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory2Message'))
self.assertFalse(cls is factory_test2_pb2.Factory2Message)
self._ExerciseDynamicClass(cls)
cls2 = message_factory.GetMessageClass(pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory2Message'))
self.assertTrue(cls is cls2)
def testGetExistingPrototype(self):
# Get Existing Prototype should not create a new class.
cls = message_factory.GetMessageClass(
descriptor=factory_test2_pb2.Factory2Message.DESCRIPTOR)
msg = factory_test2_pb2.Factory2Message()
self.assertIsInstance(msg, cls)
self.assertIsInstance(msg.factory_1_message,
factory_test1_pb2.Factory1Message)
def testGetMessages(self):
# performed twice because multiple calls with the same input must be allowed
for _ in range(2):
# GetMessage should work regardless of the order the FileDescriptorProto
# are provided. In particular, the function should succeed when the files
# are not in the topological order of dependencies.
# Assuming factory_test2_fd depends on factory_test1_fd.
self.assertIn(self.factory_test1_fd.name,
self.factory_test2_fd.dependency)
# Get messages should work when a file comes before its dependencies:
# factory_test2_fd comes before factory_test1_fd.
messages = message_factory.GetMessages([self.factory_test2_fd,
self.factory_test1_fd],
descriptor_pool.Default())
self.assertTrue(
set(['google.protobuf.python.internal.Factory2Message',
'google.protobuf.python.internal.Factory1Message'],
).issubset(set(messages.keys())))
self._ExerciseDynamicClass(
messages['google.protobuf.python.internal.Factory2Message'])
factory_msg1 = messages['google.protobuf.python.internal.Factory1Message']
self.assertTrue(set(
['google.protobuf.python.internal.Factory2Message.one_more_field',
'google.protobuf.python.internal.another_field'],).issubset(set(
ext.full_name
for ext in factory_msg1.DESCRIPTOR.file.pool.FindAllExtensions(
factory_msg1.DESCRIPTOR))))
msg1 = messages['google.protobuf.python.internal.Factory1Message']()
ext1 = msg1.Extensions._FindExtensionByName(
'google.protobuf.python.internal.Factory2Message.one_more_field')
ext2 = msg1.Extensions._FindExtensionByName(
'google.protobuf.python.internal.another_field')
self.assertEqual(0, len(msg1.Extensions))
msg1.Extensions[ext1] = 'test1'
msg1.Extensions[ext2] = 'test2'
self.assertEqual('test1', msg1.Extensions[ext1])
self.assertEqual('test2', msg1.Extensions[ext2])
self.assertEqual(None,
msg1.Extensions._FindExtensionByNumber(12321))
self.assertEqual(2, len(msg1.Extensions))
if api_implementation.Type() == 'python':
self.assertEqual(None,
msg1.Extensions._FindExtensionByName(0))
self.assertEqual(None,
msg1.Extensions._FindExtensionByNumber(''))
else:
self.assertRaises(TypeError, msg1.Extensions._FindExtensionByName, 0)
self.assertRaises(TypeError, msg1.Extensions._FindExtensionByNumber, '')
def testDuplicateExtensionNumber(self):
pool = descriptor_pool.DescriptorPool()
# Add Container message.
f = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/container.proto',
package='google.protobuf.python.internal')
f.message_type.add(name='Container').extension_range.add(start=1, end=10)
pool.Add(f)
msgs = message_factory.GetMessageClassesForFiles([f.name], pool)
self.assertIn('google.protobuf.python.internal.Container', msgs)
# Extend container.
f = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/extension.proto',
package='google.protobuf.python.internal',
dependency=['google/protobuf/internal/container.proto'])
msg = f.message_type.add(name='Extension')
msg.extension.add(
name='extension_field',
number=2,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='Extension',
extendee='Container',
)
pool.Add(f)
msgs = message_factory.GetMessageClassesForFiles([f.name], pool)
self.assertIn('google.protobuf.python.internal.Extension', msgs)
# Add Duplicate extending the same field number.
f = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/duplicate.proto',
package='google.protobuf.python.internal',
dependency=['google/protobuf/internal/container.proto'])
msg = f.message_type.add(name='Duplicate')
msg.extension.add(
name='extension_field',
number=2,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='Duplicate',
extendee='Container',
)
if api_implementation.Type() == 'upb':
with self.assertRaisesRegex(
TypeError,
"Couldn't build proto file into descriptor pool: "
'duplicate extension entry',
):
pool.Add(f)
else:
# TODO: b/381131694 - Ensure conformance between upb/c++/python.
# C++ and pure Python implementations should raise an error when adding a
# duplicate extension number. There doesn't seem to be a benefit to failing
# only when GetMessageClassesForFiles is called.
pool.Add(f)
with self.assertRaises(Exception) as cm:
message_factory.GetMessageClassesForFiles([f.name], pool)
self.assertIn(
str(cm.exception),
[
(
'Extensions'
' "google.protobuf.python.internal.Duplicate.extension_field"'
' and'
' "google.protobuf.python.internal.Extension.extension_field"'
' both try to extend message type'
' "google.protobuf.python.internal.Container" with field'
' number 2.'
),
'Double registration of Extensions',
],
)
def testExtensionValueInDifferentFile(self):
# Add Container message.
f1 = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/container.proto',
package='google.protobuf.python.internal')
f1.message_type.add(name='Container').extension_range.add(start=1, end=10)
# Add ValueType message.
f2 = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/value_type.proto',
package='google.protobuf.python.internal')
f2.message_type.add(name='ValueType').field.add(
name='setting',
number=1,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type=descriptor_pb2.FieldDescriptorProto.TYPE_INT32,
default_value='123')
# Extend container with field of ValueType.
f3 = descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/extension.proto',
package='google.protobuf.python.internal',
dependency=[f1.name, f2.name])
f3.extension.add(
name='top_level_extension_field',
number=2,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='ValueType',
extendee='Container',
)
f3.message_type.add(name='Extension').extension.add(
name='nested_extension_field',
number=3,
label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
type_name='ValueType',
extendee='Container',
)
pool = descriptor_pool.Default()
try:
pool.Add(f1)
pool.Add(f2)
pool.Add(f3)
except:
pass
msgs = message_factory.GetMessageClassesForFiles(
[f1.name, f3.name], pool) # Deliberately not f2.
msg = msgs['google.protobuf.python.internal.Container']
desc = msgs['google.protobuf.python.internal.Extension'].DESCRIPTOR
ext1 = desc.file.extensions_by_name['top_level_extension_field']
ext2 = desc.extensions_by_name['nested_extension_field']
m = msg()
m.Extensions[ext1].setting = 234
m.Extensions[ext2].setting = 345
serialized = m.SerializeToString()
f1.name='google/protobuf/internal/another/container.proto'
f1.package='google.protobuf.python.internal.another'
f2.name='google/protobuf/internal/another/value_type.proto'
f2.package='google.protobuf.python.internal.another'
f3.name='google/protobuf/internal/another/extension.proto'
f3.package='google.protobuf.python.internal.another'
f3.ClearField('dependency')
f3.dependency.extend([f1.name, f2.name])
try:
pool.Add(f1)
pool.Add(f2)
pool.Add(f3)
except:
pass
msgs = message_factory.GetMessageClassesForFiles(
[f1.name, f3.name], pool) # Deliberately not f2.
msg = msgs['google.protobuf.python.internal.another.Container']
desc = msgs['google.protobuf.python.internal.another.Extension'].DESCRIPTOR
ext1 = desc.file.extensions_by_name['top_level_extension_field']
ext2 = desc.extensions_by_name['nested_extension_field']
m = msg.FromString(serialized)
self.assertEqual(2, len(m.ListFields()))
self.assertEqual(234, m.Extensions[ext1].setting)
self.assertEqual(345, m.Extensions[ext2].setting)
def testDescriptorKeepConcreteClass(self):
def loadFile():
f= descriptor_pb2.FileDescriptorProto(
name='google/protobuf/internal/meta_class.proto',
package='google.protobuf.python.internal')
msg_proto = f.message_type.add(name='Empty')
msg_proto.nested_type.add(name='Nested')
msg_proto.field.add(name='nested_field',
number=1,
label=descriptor.FieldDescriptor.LABEL_REPEATED,
type=descriptor.FieldDescriptor.TYPE_MESSAGE,
type_name='Nested')
return message_factory.GetMessages([f])
messages = loadFile()
for des, meta_class in messages.items():
message = meta_class()
nested_des = message.DESCRIPTOR.nested_types_by_name['Nested']
nested_msg = nested_des._concrete_class()
def testOndemandCreateMetaClass(self):
def loadFile():
f = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb)
return message_factory.GetMessages([f])
messages = loadFile()
data = factory_test1_pb2.Factory1Message()
data.map_field['hello'] = 'welcome'
# Force GC to collect. UPB python will clean up the map entry class.
# cpp extension and pure python will still keep the map entry class.
gc.collect()
message = messages['google.protobuf.python.internal.Factory1Message']()
message.ParseFromString(data.SerializeToString())
value = message.map_field
values = [
# The entry class will be created on demand in upb python.
value.GetEntryClass()(key=k, value=value[k]) for k in sorted(value)
]
gc.collect()
self.assertEqual(1, len(values))
self.assertEqual('hello', values[0].key)
self.assertEqual('welcome', values[0].value)
if __name__ == '__main__':
unittest.main()
| MessageFactoryTest |
python | pandas-dev__pandas | pandas/core/groupby/indexing.py | {
"start": 7494,
"end": 8899
} | class ____:
def __init__(self, groupby_object: groupby.GroupBy) -> None:
self.groupby_object = groupby_object
def __getitem__(self, arg: PositionalIndexer | tuple) -> DataFrame | Series:
"""
Select by positional index per group.
Implements GroupBy._positional_selector
Parameters
----------
arg : PositionalIndexer | tuple
Allowed values are:
- int
- int valued iterable such as list or range
- slice with step either None or positive
- tuple of integers and slices
Returns
-------
Series
The filtered subset of the original groupby Series.
DataFrame
The filtered subset of the original groupby DataFrame.
See Also
--------
DataFrame.iloc : Integer-location based indexing for selection by position.
GroupBy.head : Return first n rows of each group.
GroupBy.tail : Return last n rows of each group.
GroupBy._positional_selector : Return positional selection for each group.
GroupBy.nth : Take the nth row from each group if n is an int, or a
subset of rows, if n is a list of ints.
"""
mask = self.groupby_object._make_mask_from_positional_indexer(arg)
return self.groupby_object._mask_selected_obj(mask)
| GroupByPositionalSelector |
python | doocs__leetcode | solution/2900-2999/2932.Maximum Strong Pair XOR I/Solution2.py | {
"start": 0,
"end": 938
} | class ____:
__slots__ = ("children", "cnt")
def __init__(self):
self.children: List[Trie | None] = [None, None]
self.cnt = 0
def insert(self, x: int):
node = self
for i in range(7, -1, -1):
v = x >> i & 1
if node.children[v] is None:
node.children[v] = Trie()
node = node.children[v]
node.cnt += 1
def search(self, x: int) -> int:
node = self
ans = 0
for i in range(7, -1, -1):
v = x >> i & 1
if node.children[v ^ 1] and node.children[v ^ 1].cnt:
ans |= 1 << i
node = node.children[v ^ 1]
else:
node = node.children[v]
return ans
def remove(self, x: int):
node = self
for i in range(7, -1, -1):
v = x >> i & 1
node = node.children[v]
node.cnt -= 1
| Trie |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/utils/kernelspec.py | {
"start": 2377,
"end": 12479
} | class ____(KernelSpec, SpyderConfigurationAccessor):
"""Kernel spec for Spyder kernels"""
CONF_SECTION = 'ipython_console'
def __init__(self, path_to_custom_interpreter=None, **kwargs):
super().__init__(**kwargs)
self.path_to_custom_interpreter = path_to_custom_interpreter
self.display_name = 'Python 3 (Spyder)'
self.language = 'python3'
self.resource_dir = ''
self._env_vars = {}
@property
def argv(self):
"""Command to start kernels"""
# Python interpreter used to start kernels
if (
self.get_conf('default', section='main_interpreter')
and not self.path_to_custom_interpreter
):
pyexec = get_python_executable()
else:
pyexec = self.get_conf('executable', section='main_interpreter')
if self.path_to_custom_interpreter:
pyexec = self.path_to_custom_interpreter
if not has_spyder_kernels(pyexec):
raise SpyderKernelError(
ERROR_SPYDER_KERNEL_INSTALLED.format(
pyexec,
SPYDER_KERNELS_VERSION,
SPYDER_KERNELS_CONDA,
SPYDER_KERNELS_PIP
)
)
return
if not is_python_interpreter(pyexec):
pyexec = get_python_executable()
self.set_conf('executable', '', section='main_interpreter')
self.set_conf('default', True, section='main_interpreter')
self.set_conf('custom', False, section='main_interpreter')
# Command used to start kernels
kernel_cmd = []
if is_pixi_env(pyexec=pyexec):
pixi_exe = find_pixi()
if not pixi_exe:
raise SpyderKernelError(
_(
"Spyder couldn't find pixi in your system to activate "
"the kernel's environment. Please add the directory "
"where the pixi executable is located to your PATH "
"environment variable for it to be detected."
)
)
pixi_manifest, pixi_env = get_pixi_manifest_path_and_env_name(
pyexec,
)
kernel_cmd.extend([
pixi_exe,
'run',
'--environment',
pixi_env,
'--manifest-path',
pixi_manifest,
])
elif is_conda_env(pyexec=pyexec):
# If executable is a conda environment, use "run" subcommand to
# activate it and run spyder-kernels.
conda_exe = find_conda()
if not conda_exe:
conda_exe = (
self.get_conf("conda_path", section="main_interpreter")
if self.get_conf(
"custom_conda", section="main_interpreter"
)
else None
)
if not conda_exe:
# Raise error since we were unable to determine the path to
# the conda executable (e.g when Anaconda/Miniconda was
# installed in a non-standard location).
# See spyder-ide/spyder#23595
not_found_exe_message = _(
"Spyder couldn't find Conda, Mamba or Micromamba on your "
"system to activate the kernel's environment.<br><br>"
"Please set the path for one of their executables in "
"<tt>Preferences > Python interpreter > Conda "
"executable</tt>"
)
raise SpyderKernelError(not_found_exe_message)
# Get conda/mamba/micromamba version to perform some checks
conda_exe_version = conda_version(conda_executable=conda_exe)
# Base command
kernel_cmd.extend([
conda_exe,
'run',
'--prefix',
get_conda_env_path(pyexec)
])
# We need to use these flags to prevent conda_exe from capturing
# the kernel process stdout/stderr streams. That way we'll be able
# to show them in Spyder.
if "micromamba" in osp.basename(conda_exe) or (
# Fixes spyder-ide/spyder#24513
"mamba" in osp.basename(conda_exe)
and conda_exe_version >= parse("2.0")
):
kernel_cmd.extend(['--attach', '""'])
elif (
"mamba" in osp.basename(conda_exe)
and conda_exe_version < parse("2.0")
) or (
"conda" in osp.basename(conda_exe)
and conda_exe_version >= parse("4.9")
):
# Note: We use --no-capture-output instead of --live-stream
# here because it works for older Conda versions (conda>=4.9).
kernel_cmd.append('--no-capture-output')
else:
# Raise error since an unsupported conda version is being used
# (conda<4.9).
# See spyder-ide/spyder#22554
raise SpyderKernelError(
_(
"The detected version of Conda is too old and not "
"supported by Spyder. The minimum supported version is "
"4.9 and currently you have {conda_version}.<br><br>."
"<b>Note</b>: You need to restart Spyder after "
"updating Conda for the change to take effect."
).format(conda_version=conda_exe_version)
)
kernel_cmd.extend([
pyexec,
# This is necessary to avoid a spurious message on Windows.
# Fixes spyder-ide/spyder#20800.
'-Xfrozen_modules=off',
'-m', 'spyder_kernels.console',
'-f', '{connection_file}'
])
logger.info('Kernel command: {}'.format(kernel_cmd))
return kernel_cmd
@property
def env(self):
"""Environment variables for kernels"""
return self._env_vars
@env.setter
def env(self, env_vars):
"""Setter for environment variables for kernels"""
env_vars = dict(env_vars)
if os.name == "nt":
# Expand variables in case some are unexpanded.
# Fixes spyder-ide/spyder#25275
env_vars = {k: osp.expandvars(v) for k, v in env_vars.items()}
# Use case insensitive dictionary
env_vars = CaseInsensitiveDict(env_vars)
# HKCU path must be appended to HKLM path
path = os.getenv("path", "").split(";") # HKLM Path
path.extend(env_vars.get("path", "").split(";")) # HKCU Path
path = ";".join([p for p in path if p]) # Stringify
env_vars["PATH"] = path
# User variables supersede system variables
for k, v in os.environ.items():
env_vars.setdefault(k, v)
default_interpreter = self.get_conf(
'default', section='main_interpreter'
)
# List of modules to exclude from our UMR
umr_namelist = self.get_conf(
'umr/namelist', section='main_interpreter')
# Get TMPDIR value, if available
tmpdir_var = env_vars.get("TMPDIR", "")
# --- Adding to environment variables
# Environment variables that we need to pass to the kernel
env_vars.update({
'SPY_EXTERNAL_INTERPRETER': (not default_interpreter
or self.path_to_custom_interpreter),
'SPY_UMR_ENABLED': self.get_conf(
'umr/enabled', section='main_interpreter'),
'SPY_UMR_VERBOSE': self.get_conf(
'umr/verbose', section='main_interpreter'),
'SPY_UMR_NAMELIST': ','.join(umr_namelist),
'SPY_AUTOCALL_O': self.get_conf('autocall'),
'SPY_GREEDY_O': self.get_conf('greedy_completer'),
'SPY_JEDI_O': self.get_conf('jedi_completer'),
'SPY_TESTING': running_under_pytest() or get_safe_mode(),
'SPY_HIDE_CMD': self.get_conf('hide_cmd_windows'),
# This env var avoids polluting the OS default temp directory with
# files generated by `conda run`. It's restored/removed in the
# kernel after initialization.
"TMPDIR": get_temp_dir(),
# This is necessary to restore TMPDIR in the kernel, if it exists
"SPY_TMPDIR": tmpdir_var,
})
# This is necessary so that the kernel checks the Spyder pid for
# crashes and gets killed automatically when that happens.
# Fixes spyder-ide/spyder#22414
if not (running_in_ci() and os.name == "nt"):
env_vars["SPY_PARENT_PID"] = str(os.getpid())
# App considerations
# ??? Do we need this?
if is_conda_based_app() and default_interpreter:
# See spyder-ide/spyder#16927
# See spyder-ide/spyder#16828
# See spyder-ide/spyder#17552
env_vars['PYDEVD_DISABLE_FILE_VALIDATION'] = 1
# --- Removing from envrionment variables
env_vars.pop('PYTEST_CURRENT_TEST', None)
# Avoid IPython adding the virtualenv on which Spyder is running
# to the kernel sys.path
env_vars.pop('VIRTUAL_ENV', None)
# Do not pass PYTHONPATH to kernels directly, spyder-ide/spyder#13519
env_vars.pop('PYTHONPATH', None)
# Remove this variable because it prevents starting kernels for
# external interpreters when present.
# Fixes spyder-ide/spyder#13252
env_vars.pop('PYTHONEXECUTABLE', None)
# Making all env_vars strings, ensure cast as dict
self._env_vars = clean_env(dict(env_vars))
| SpyderKernelSpec |
python | sympy__sympy | sympy/stats/random_matrix_models.py | {
"start": 1361,
"end": 2140
} | class ____(Basic):
"""
Base class for random matrix ensembles.
It acts as an umbrella and contains
the methods common to all the ensembles
defined in sympy.stats.random_matrix_models.
"""
def __new__(cls, sym, dim=None):
sym, dim = _symbol_converter(sym), _sympify(dim)
if dim.is_integer == False:
raise ValueError("Dimension of the random matrices must be "
"integers, received %s instead."%(dim))
return Basic.__new__(cls, sym, dim)
symbol = property(lambda self: self.args[0])
dimension = property(lambda self: self.args[1])
def density(self, expr):
return Density(expr)
def __call__(self, expr):
return self.density(expr)
| RandomMatrixEnsembleModel |
python | sympy__sympy | sympy/physics/quantum/boson.py | {
"start": 3915,
"end": 4351
} | class ____(Bra):
"""Fock state bra for a bosonic mode.
Parameters
==========
n : Number
The Fock state number.
"""
def __new__(cls, n):
return Bra.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return BosonFockKet
@classmethod
def _eval_hilbert_space(cls, label):
return FockSpace()
| BosonFockBra |
python | gevent__gevent | src/gevent/tests/test__socket_send_memoryview.py | {
"start": 779,
"end": 960
} | class ____(unittest.TestCase):
def test_send(self):
import gevent.socket
_send(gevent.socket)
if __name__ == '__main__':
greentest.main()
| TestSendGeventSocket |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib_test.py | {
"start": 1761,
"end": 2183
} | class ____(distribute_lib.ReplicaContext):
def merge_call(self, fn, *args, **kwargs):
return kwargs["test_arg"]
def _get_test_variable(name, synchronization, aggregation):
return {
"name": name,
"synchronization": synchronization,
"aggregation": aggregation
}
def _test_input_fn(input_context):
del input_context
return dataset_ops.DatasetV2.from_tensors(1.).repeat()
| _TestReplicaContext |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 38511,
"end": 39043
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
pca_ = helper_functions.get_value("PCA")
if pca_ is None:
return np.NaN
sum_ = 0.0
idx = 0
while sum_ < 0.95 and idx < len(pca_.explained_variance_ratio_):
sum_ += pca_.explained_variance_ratio_[idx]
idx += 1
return float(idx) / float(X.shape[1])
# Kurtosis of first PC
@metafeatures.define("PCAKurtosisFirstPC", dependency="PCA")
| PCAFractionOfComponentsFor95PercentVariance |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 368154,
"end": 368845
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of UpdatePullRequestReview"""
__schema__ = github_schema
__field_names__ = ("pull_request_review_id", "body", "client_mutation_id")
pull_request_review_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="pullRequestReviewId")
"""The Node ID of the pull request review to modify."""
body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body")
"""The contents of the pull request review body."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| UpdatePullRequestReviewInput |
python | coleifer__peewee | tests/models.py | {
"start": 77338,
"end": 86076
} | class ____(ModelTestCase):
requires = [Sample]
def setUp(self):
super(TestWindowFunctionIntegration, self).setUp()
values = ((1, 10), (1, 20), (2, 1), (2, 3), (3, 100))
with self.database.atomic():
for counter, value in values:
Sample.create(counter=counter, value=value)
def test_simple_partition(self):
query = (Sample
.select(Sample.counter, Sample.value,
fn.AVG(Sample.value).over(
partition_by=[Sample.counter]))
.order_by(Sample.counter, Sample.value)
.tuples())
expected = [
(1, 10., 15.),
(1, 20., 15.),
(2, 1., 2.),
(2, 3., 2.),
(3, 100., 100.)]
self.assertEqual(list(query), expected)
window = Window(partition_by=[Sample.counter])
query = (Sample
.select(Sample.counter, Sample.value,
fn.AVG(Sample.value).over(window))
.window(window)
.order_by(Sample.counter, Sample.value)
.tuples())
self.assertEqual(list(query), expected)
def test_mixed_ordering(self):
s = fn.SUM(Sample.value).over(order_by=[Sample.value])
query = (Sample
.select(Sample.counter, Sample.value, s.alias('rtotal'))
.order_by(Sample.id))
# We end up with window going 1., 3., 10., 20., 100..
# So:
# 1 | 10 | (1 + 3 + 10)
# 1 | 20 | (1 + 3 + 10 + 20)
# 2 | 1 | (1)
# 2 | 3 | (1 + 3)
# 3 | 100 | (1 + 3 + 10 + 20 + 100)
self.assertEqual([(r.counter, r.value, r.rtotal) for r in query], [
(1, 10., 14.),
(1, 20., 34.),
(2, 1., 1.),
(2, 3., 4.),
(3, 100., 134.)])
def test_reuse_window(self):
w = Window(order_by=[Sample.value])
with self.database.atomic():
Sample.delete().execute()
for i in range(10):
Sample.create(counter=i, value=10 * i)
query = (Sample
.select(Sample.counter, Sample.value,
fn.NTILE(4).over(w).alias('quartile'),
fn.NTILE(5).over(w).alias('quintile'),
fn.NTILE(100).over(w).alias('percentile'))
.window(w)
.order_by(Sample.id))
results = [(r.counter, r.value, r.quartile, r.quintile, r.percentile)
for r in query]
self.assertEqual(results, [
# ct, v, 4tile, 5tile, 100tile
(0, 0., 1, 1, 1),
(1, 10., 1, 1, 2),
(2, 20., 1, 2, 3),
(3, 30., 2, 2, 4),
(4, 40., 2, 3, 5),
(5, 50., 2, 3, 6),
(6, 60., 3, 4, 7),
(7, 70., 3, 4, 8),
(8, 80., 4, 5, 9),
(9, 90., 4, 5, 10),
])
def test_ordered_window(self):
window = Window(partition_by=[Sample.counter],
order_by=[Sample.value.desc()])
query = (Sample
.select(Sample.counter, Sample.value,
fn.RANK().over(window=window).alias('rank'))
.window(window)
.order_by(Sample.counter, fn.RANK().over(window=window))
.tuples())
self.assertEqual(list(query), [
(1, 20., 1),
(1, 10., 2),
(2, 3., 1),
(2, 1., 2),
(3, 100., 1)])
def test_two_windows(self):
w1 = Window(partition_by=[Sample.counter]).alias('w1')
w2 = Window(order_by=[Sample.counter]).alias('w2')
query = (Sample
.select(Sample.counter, Sample.value,
fn.AVG(Sample.value).over(window=w1),
fn.RANK().over(window=w2))
.window(w1, w2)
.order_by(Sample.id)
.tuples())
self.assertEqual(list(query), [
(1, 10., 15., 1),
(1, 20., 15., 1),
(2, 1., 2., 3),
(2, 3., 2., 3),
(3, 100., 100., 5)])
def test_empty_over(self):
query = (Sample
.select(Sample.counter, Sample.value,
fn.LAG(Sample.counter, 1).over(order_by=[Sample.id]))
.order_by(Sample.id)
.tuples())
self.assertEqual(list(query), [
(1, 10., None),
(1, 20., 1),
(2, 1., 1),
(2, 3., 2),
(3, 100., 2)])
def test_bounds(self):
query = (Sample
.select(Sample.value,
fn.SUM(Sample.value).over(
partition_by=[Sample.counter],
start=Window.preceding(),
end=Window.following(1)))
.order_by(Sample.id)
.tuples())
self.assertEqual(list(query), [
(10., 30.),
(20., 30.),
(1., 4.),
(3., 4.),
(100., 100.)])
query = (Sample
.select(Sample.counter, Sample.value,
fn.SUM(Sample.value).over(
order_by=[Sample.id],
start=Window.preceding(2)))
.order_by(Sample.id)
.tuples())
self.assertEqual(list(query), [
(1, 10., 10.),
(1, 20., 30.),
(2, 1., 31.),
(2, 3., 24.),
(3, 100., 104.)])
def test_frame_types(self):
Sample.create(counter=1, value=20.)
Sample.create(counter=2, value=1.) # Observe logical peer handling.
# Defaults to RANGE.
query = (Sample
.select(Sample.counter, Sample.value,
fn.SUM(Sample.value).over(
order_by=[Sample.counter, Sample.value]))
.order_by(Sample.id))
self.assertEqual(list(query.tuples()), [
(1, 10., 10.),
(1, 20., 50.),
(2, 1., 52.),
(2, 3., 55.),
(3, 100., 155.),
(1, 20., 50.),
(2, 1., 52.)])
# Explicitly specify ROWS.
query = (Sample
.select(Sample.counter, Sample.value,
fn.SUM(Sample.value).over(
order_by=[Sample.counter, Sample.value],
frame_type=Window.ROWS))
.order_by(Sample.counter, Sample.value))
self.assertEqual(list(query.tuples()), [
(1, 10., 10.),
(1, 20., 30.),
(1, 20., 50.),
(2, 1., 51.),
(2, 1., 52.),
(2, 3., 55.),
(3, 100., 155.)])
# Including a boundary results in ROWS.
query = (Sample
.select(Sample.counter, Sample.value,
fn.SUM(Sample.value).over(
order_by=[Sample.counter, Sample.value],
start=Window.preceding(2)))
.order_by(Sample.counter, Sample.value))
self.assertEqual(list(query.tuples()), [
(1, 10., 10.),
(1, 20., 30.),
(1, 20., 50.),
(2, 1., 41.),
(2, 1., 22.),
(2, 3., 5.),
(3, 100., 104.)])
@skip_if(IS_MYSQL, 'requires OVER() with FILTER')
def test_filter_clause(self):
condsum = fn.SUM(Sample.value).filter(Sample.counter > 1).over(
order_by=[Sample.id], start=Window.preceding(1))
query = (Sample
.select(Sample.counter, Sample.value, condsum.alias('cs'))
.order_by(Sample.value))
self.assertEqual(list(query.tuples()), [
(2, 1., 1.),
(2, 3., 4.),
(1, 10., None),
(1, 20., None),
(3, 100., 103.),
])
@skip_if(IS_MYSQL or (IS_SQLITE and not IS_SQLITE_30),
'requires FILTER with aggregates')
def test_filter_with_aggregate(self):
condsum = fn.SUM(Sample.value).filter(Sample.counter > 1)
query = (Sample
.select(Sample.counter, condsum.alias('cs'))
.group_by(Sample.counter)
.order_by(Sample.counter))
self.assertEqual(list(query.tuples()), [
(1, None),
(2, 4.),
(3, 100.)])
@skip_if(IS_SQLITE or (IS_MYSQL and not IS_MYSQL_ADVANCED_FEATURES))
@skip_unless(db.for_update, 'requires for update')
| TestWindowFunctionIntegration |
python | walkccc__LeetCode | solutions/3345. Smallest Divisible Digit Product I/3345.py | {
"start": 0,
"end": 316
} | class ____:
def smallestNumber(self, n: int, t: int) -> int:
return next(num for num in range(n, n + 10)
if self._getDigitProd(num) % t == 0)
def _getDigitProd(self, num: int) -> int:
digitProd = 1
while num > 0:
digitProd *= num % 10
num //= 10
return digitProd
| Solution |
python | getsentry__sentry-python | sentry_sdk/utils.py | {
"start": 45405,
"end": 45547
} | class ____(Exception): # noqa: N818
"""Raised when a serverless method is about to reach its timeout."""
pass
| ServerlessTimeoutWarning |
python | PrefectHQ__prefect | src/prefect/_internal/schemas/fields.py | {
"start": 465,
"end": 837
} | class ____(BaseModel):
id: Optional[UUID] = Field(
default=None, description="The id of the updater of the object."
)
type: Optional[str] = Field(
default=None, description="The type of the updater of the object."
)
display_value: Optional[str] = Field(
default=None, description="The display value for the updater."
)
| UpdatedBy |
python | huggingface__transformers | src/transformers/models/zoedepth/configuration_zoedepth.py | {
"start": 992,
"end": 12819
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ZoeDepthForDepthEstimation`]. It is used to instantiate an ZoeDepth
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 ZoeDepth
[Intel/zoedepth-nyu](https://huggingface.co/Intel/zoedepth-nyu) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
backbone_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*, defaults to `BeitConfig()`):
The configuration of the backbone model.
backbone (`str`, *optional*):
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
Whether to use pretrained weights for the backbone.
backbone_kwargs (`dict`, *optional*):
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. 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.
batch_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the batch normalization layers.
readout_type (`str`, *optional*, defaults to `"project"`):
The readout type to use when processing the readout token (CLS token) of the intermediate hidden states of
the ViT backbone. Can be one of [`"ignore"`, `"add"`, `"project"`].
- "ignore" simply ignores the CLS token.
- "add" passes the information from the CLS token to all other tokens by adding the representations.
- "project" passes information to the other tokens by concatenating the readout to all other tokens before
projecting the
representation to the original feature dimension D using a linear layer followed by a GELU non-linearity.
reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
The up/downsampling factors of the reassemble layers.
neck_hidden_sizes (`list[str]`, *optional*, defaults to `[96, 192, 384, 768]`):
The hidden sizes to project to for the feature maps of the backbone.
fusion_hidden_size (`int`, *optional*, defaults to 256):
The number of channels before fusion.
head_in_index (`int`, *optional*, defaults to -1):
The index of the features to use in the heads.
use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
Whether to use bias in the pre-activate residual units of the fusion blocks.
num_relative_features (`int`, *optional*, defaults to 32):
The number of features to use in the relative depth estimation head.
add_projection (`bool`, *optional*, defaults to `False`):
Whether to add a projection layer before the depth estimation head.
bottleneck_features (`int`, *optional*, defaults to 256):
The number of features in the bottleneck layer.
num_attractors (`list[int], *optional*, defaults to `[16, 8, 4, 1]`):
The number of attractors to use in each stage.
bin_embedding_dim (`int`, *optional*, defaults to 128):
The dimension of the bin embeddings.
attractor_alpha (`int`, *optional*, defaults to 1000):
The alpha value to use in the attractor.
attractor_gamma (`int`, *optional*, defaults to 2):
The gamma value to use in the attractor.
attractor_kind (`str`, *optional*, defaults to `"mean"`):
The kind of attractor to use. Can be one of [`"mean"`, `"sum"`].
min_temp (`float`, *optional*, defaults to 0.0212):
The minimum temperature value to consider.
max_temp (`float`, *optional*, defaults to 50.0):
The maximum temperature value to consider.
bin_centers_type (`str`, *optional*, defaults to `"softplus"`):
Activation type used for bin centers. Can be "normed" or "softplus". For "normed" bin centers, linear normalization trick
is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded.
bin_configurations (`list[dict]`, *optional*, defaults to `[{'n_bins': 64, 'min_depth': 0.001, 'max_depth': 10.0}]`):
Configuration for each of the bin heads.
Each configuration should consist of the following keys:
- name (`str`): The name of the bin head - only required in case of multiple bin configurations.
- `n_bins` (`int`): The number of bins to use.
- `min_depth` (`float`): The minimum depth value to consider.
- `max_depth` (`float`): The maximum depth value to consider.
In case only a single configuration is passed, the model will use a single head with the specified configuration.
In case multiple configurations are passed, the model will use multiple heads with the specified configurations.
num_patch_transformer_layers (`int`, *optional*):
The number of transformer layers to use in the patch transformer. Only used in case of multiple bin configurations.
patch_transformer_hidden_size (`int`, *optional*):
The hidden size to use in the patch transformer. Only used in case of multiple bin configurations.
patch_transformer_intermediate_size (`int`, *optional*):
The intermediate size to use in the patch transformer. Only used in case of multiple bin configurations.
patch_transformer_num_attention_heads (`int`, *optional*):
The number of attention heads to use in the patch transformer. Only used in case of multiple bin configurations.
Example:
```python
>>> from transformers import ZoeDepthConfig, ZoeDepthForDepthEstimation
>>> # Initializing a ZoeDepth zoedepth-large style configuration
>>> configuration = ZoeDepthConfig()
>>> # Initializing a model from the zoedepth-large style configuration
>>> model = ZoeDepthForDepthEstimation(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "zoedepth"
sub_configs = {"backbone_config": AutoConfig}
def __init__(
self,
backbone_config=None,
backbone=None,
use_pretrained_backbone=False,
backbone_kwargs=None,
hidden_act="gelu",
initializer_range=0.02,
batch_norm_eps=1e-05,
readout_type="project",
reassemble_factors=[4, 2, 1, 0.5],
neck_hidden_sizes=[96, 192, 384, 768],
fusion_hidden_size=256,
head_in_index=-1,
use_batch_norm_in_fusion_residual=False,
use_bias_in_fusion_residual=None,
num_relative_features=32,
add_projection=False,
bottleneck_features=256,
num_attractors=[16, 8, 4, 1],
bin_embedding_dim=128,
attractor_alpha=1000,
attractor_gamma=2,
attractor_kind="mean",
min_temp=0.0212,
max_temp=50.0,
bin_centers_type="softplus",
bin_configurations=[{"n_bins": 64, "min_depth": 0.001, "max_depth": 10.0}],
num_patch_transformer_layers=None,
patch_transformer_hidden_size=None,
patch_transformer_intermediate_size=None,
patch_transformer_num_attention_heads=None,
**kwargs,
):
if readout_type not in ["ignore", "add", "project"]:
raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']")
if attractor_kind not in ["mean", "sum"]:
raise ValueError("Attractor_kind must be one of ['mean', 'sum']")
if use_pretrained_backbone:
raise ValueError("Pretrained backbones are not supported yet.")
if backbone_config is not None and backbone is not None:
raise ValueError("You can't specify both `backbone` and `backbone_config`.")
if backbone_config is None and backbone is None:
logger.info("`backbone_config` is `None`. Initializing the config with the default `BEiT` backbone.")
backbone_config = CONFIG_MAPPING["beit"](
image_size=384,
num_hidden_layers=24,
hidden_size=1024,
intermediate_size=4096,
num_attention_heads=16,
use_relative_position_bias=True,
reshape_hidden_states=False,
out_features=["stage6", "stage12", "stage18", "stage24"],
)
elif isinstance(backbone_config, dict):
backbone_model_type = backbone_config.get("model_type")
config_class = CONFIG_MAPPING[backbone_model_type]
backbone_config = config_class.from_dict(backbone_config)
if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
self.backbone_config = backbone_config
self.backbone = backbone
self.hidden_act = hidden_act
self.use_pretrained_backbone = use_pretrained_backbone
self.initializer_range = initializer_range
self.batch_norm_eps = batch_norm_eps
self.readout_type = readout_type
self.reassemble_factors = reassemble_factors
self.neck_hidden_sizes = neck_hidden_sizes
self.fusion_hidden_size = fusion_hidden_size
self.head_in_index = head_in_index
self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
self.num_relative_features = num_relative_features
self.add_projection = add_projection
self.bottleneck_features = bottleneck_features
self.num_attractors = num_attractors
self.bin_embedding_dim = bin_embedding_dim
self.attractor_alpha = attractor_alpha
self.attractor_gamma = attractor_gamma
self.attractor_kind = attractor_kind
self.min_temp = min_temp
self.max_temp = max_temp
self.bin_centers_type = bin_centers_type
self.bin_configurations = bin_configurations
self.num_patch_transformer_layers = num_patch_transformer_layers
self.patch_transformer_hidden_size = patch_transformer_hidden_size
self.patch_transformer_intermediate_size = patch_transformer_intermediate_size
self.patch_transformer_num_attention_heads = patch_transformer_num_attention_heads
super().__init__(**kwargs)
__all__ = ["ZOEDEPTH_PRETRAINED_CONFIG_ARCHIVE_MAP", "ZoeDepthConfig"]
| ZoeDepthConfig |
python | coleifer__peewee | tests/regressions.py | {
"start": 7335,
"end": 7490
} | class ____(TestModel):
name = TextField()
parent = ForeignKeyField('self', backref='children', null=True)
user = ForeignKeyField(User2)
| Category2 |
python | django__django | tests/model_options/models/default_related_name.py | {
"start": 860,
"end": 1056
} | class ____(Store):
editor = models.ForeignKey(Editor, models.CASCADE)
available_books = models.ManyToManyField(Book)
class Meta:
default_related_name = "editor_stores"
| EditorStore |
python | django__django | tests/lookup/tests.py | {
"start": 67259,
"end": 75504
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.s1 = Season.objects.create(year=1942, gt=1942)
cls.s2 = Season.objects.create(year=1842, gt=1942, nulled_text_field="text")
cls.s3 = Season.objects.create(year=2042, gt=1942)
Game.objects.create(season=cls.s1, home="NY", away="Boston")
Game.objects.create(season=cls.s1, home="NY", away="Tampa")
Game.objects.create(season=cls.s3, home="Boston", away="Tampa")
def test_annotate(self):
qs = Season.objects.annotate(equal=Exact(F("year"), 1942))
self.assertCountEqual(
qs.values_list("year", "equal"),
((1942, True), (1842, False), (2042, False)),
)
def test_alias(self):
qs = Season.objects.alias(greater=GreaterThan(F("year"), 1910))
self.assertCountEqual(qs.filter(greater=True), [self.s1, self.s3])
def test_annotate_value_greater_than_value(self):
qs = Season.objects.annotate(greater=GreaterThan(Value(40), Value(30)))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, True), (2042, True)),
)
def test_annotate_field_greater_than_field(self):
qs = Season.objects.annotate(greater=GreaterThan(F("year"), F("gt")))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, False), (1842, False), (2042, True)),
)
def test_annotate_field_greater_than_value(self):
qs = Season.objects.annotate(greater=GreaterThan(F("year"), Value(1930)))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, False), (2042, True)),
)
def test_annotate_field_greater_than_literal(self):
qs = Season.objects.annotate(greater=GreaterThan(F("year"), 1930))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, False), (2042, True)),
)
def test_annotate_literal_greater_than_field(self):
qs = Season.objects.annotate(greater=GreaterThan(1930, F("year")))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, False), (1842, True), (2042, False)),
)
def test_annotate_less_than_float(self):
qs = Season.objects.annotate(lesser=LessThan(F("year"), 1942.1))
self.assertCountEqual(
qs.values_list("year", "lesser"),
((1942, True), (1842, True), (2042, False)),
)
def test_annotate_greater_than_or_equal(self):
qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, True), (1842, False), (2042, True)),
)
def test_annotate_greater_than_or_equal_float(self):
qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942.1))
self.assertCountEqual(
qs.values_list("year", "greater"),
((1942, False), (1842, False), (2042, True)),
)
def test_combined_lookups(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.annotate(gte=expression)
self.assertCountEqual(
qs.values_list("year", "gte"),
((1942, True), (1842, False), (2042, True)),
)
def test_lookup_in_filter(self):
qs = Season.objects.filter(GreaterThan(F("year"), 1910))
self.assertCountEqual(qs, [self.s1, self.s3])
def test_isnull_lookup_in_filter(self):
self.assertSequenceEqual(
Season.objects.filter(IsNull(F("nulled_text_field"), False)),
[self.s2],
)
self.assertCountEqual(
Season.objects.filter(IsNull(F("nulled_text_field"), True)),
[self.s1, self.s3],
)
def test_in_lookup_in_filter(self):
test_cases = [
((), ()),
((1942,), (self.s1,)),
((1842,), (self.s2,)),
((2042,), (self.s3,)),
((1942, 1842), (self.s1, self.s2)),
((1942, 2042), (self.s1, self.s3)),
((1842, 2042), (self.s2, self.s3)),
((1942, 1942, 1942), (self.s1,)),
((1942, 2042, 1842), (self.s1, self.s2, self.s3)),
]
for years, seasons in test_cases:
with self.subTest(years=years, seasons=seasons):
self.assertSequenceEqual(
Season.objects.filter(In(F("year"), years)).order_by("pk"), seasons
)
def test_filter_lookup_lhs(self):
qs = Season.objects.annotate(before_20=LessThan(F("year"), 2000)).filter(
before_20=LessThan(F("year"), 1900),
)
self.assertCountEqual(qs, [self.s2, self.s3])
def test_filter_wrapped_lookup_lhs(self):
qs = (
Season.objects.annotate(
before_20=ExpressionWrapper(
Q(year__lt=2000),
output_field=BooleanField(),
)
)
.filter(before_20=LessThan(F("year"), 1900))
.values_list("year", flat=True)
)
self.assertCountEqual(qs, [1842, 2042])
def test_filter_exists_lhs(self):
qs = Season.objects.annotate(
before_20=Exists(
Season.objects.filter(pk=OuterRef("pk"), year__lt=2000),
)
).filter(before_20=LessThan(F("year"), 1900))
self.assertCountEqual(qs, [self.s2, self.s3])
def test_filter_subquery_lhs(self):
qs = Season.objects.annotate(
before_20=Subquery(
Season.objects.filter(pk=OuterRef("pk")).values(
lesser=LessThan(F("year"), 2000),
),
)
).filter(before_20=LessThan(F("year"), 1900))
self.assertCountEqual(qs, [self.s2, self.s3])
def test_combined_lookups_in_filter(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.filter(expression)
self.assertCountEqual(qs, [self.s1, self.s3])
def test_combined_annotated_lookups_in_filter(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.annotate(gte=expression).filter(gte=True)
self.assertCountEqual(qs, [self.s1, self.s3])
def test_combined_annotated_lookups_in_filter_false(self):
expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942)
qs = Season.objects.annotate(gte=expression).filter(gte=False)
self.assertSequenceEqual(qs, [self.s2])
def test_lookup_in_order_by(self):
qs = Season.objects.order_by(LessThan(F("year"), 1910), F("year"))
self.assertSequenceEqual(qs, [self.s1, self.s3, self.s2])
def test_aggregate_combined_lookup(self):
expression = Cast(GreaterThan(F("year"), 1900), models.IntegerField())
qs = Season.objects.aggregate(modern=models.Sum(expression))
self.assertEqual(qs["modern"], 2)
def test_conditional_expression(self):
qs = Season.objects.annotate(
century=Case(
When(
GreaterThan(F("year"), 1900) & LessThanOrEqual(F("year"), 2000),
then=Value("20th"),
),
default=Value("other"),
)
).values("year", "century")
self.assertCountEqual(
qs,
[
{"year": 1942, "century": "20th"},
{"year": 1842, "century": "other"},
{"year": 2042, "century": "other"},
],
)
def test_multivalued_join_reuse(self):
self.assertEqual(
Season.objects.get(Exact(F("games__home"), "NY"), games__away="Boston"),
self.s1,
)
self.assertEqual(
Season.objects.get(Exact(F("games__home"), "NY") & Q(games__away="Boston")),
self.s1,
)
self.assertEqual(
Season.objects.get(
Exact(F("games__home"), "NY") & Exact(F("games__away"), "Boston")
),
self.s1,
)
| LookupQueryingTests |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/fifo_queue_test.py | {
"start": 65178,
"end": 65471
} | class ____(test.TestCase):
def testContainer(self):
with ops.Graph().as_default():
with ops.container("test"):
q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32)
self.assertEqual(
compat.as_bytes("test"), q.queue_ref.op.get_attr("container"))
| QueueContainerTest |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/annotation/_hoverlabel.py | {
"start": 235,
"end": 5142
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.annotation"
_path_str = "layout.scene.annotation.hoverlabel"
_valid_props = {"bgcolor", "bordercolor", "font"}
@property
def bgcolor(self):
"""
Sets the background color of the hover label. By default uses
the annotation's `bgcolor` made opaque, or white if it was
transparent.
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bordercolor(self):
"""
Sets the border color of the hover label. By default uses
either dark grey or white, for maximum contrast with
`hoverlabel.bgcolor`.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def font(self):
"""
Sets the hover label text font. By default uses the global
hover font and size, with color from `hoverlabel.bordercolor`.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.annotation.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.layout.scene.annotation.hoverlabel.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def _prop_descriptions(self):
return """\
bgcolor
Sets the background color of the hover label. By
default uses the annotation's `bgcolor` made opaque, or
white if it was transparent.
bordercolor
Sets the border color of the hover label. By default
uses either dark grey or white, for maximum contrast
with `hoverlabel.bgcolor`.
font
Sets the hover label text font. By default uses the
global hover font and size, with color from
`hoverlabel.bordercolor`.
"""
def __init__(self, arg=None, bgcolor=None, bordercolor=None, font=None, **kwargs):
"""
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.scene.a
nnotation.Hoverlabel`
bgcolor
Sets the background color of the hover label. By
default uses the annotation's `bgcolor` made opaque, or
white if it was transparent.
bordercolor
Sets the border color of the hover label. By default
uses either dark grey or white, for maximum contrast
with `hoverlabel.bgcolor`.
font
Sets the hover label text font. By default uses the
global hover font and size, with color from
`hoverlabel.bordercolor`.
Returns
-------
Hoverlabel
"""
super().__init__("hoverlabel")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.scene.annotation.Hoverlabel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.scene.annotation.Hoverlabel`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("font", arg, font)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Hoverlabel |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 11218,
"end": 11932
} | class ____(UsernameMixin, PasswordMixin, wtforms.Form):
__params__ = ["confirm_password", "macaroon_id"]
macaroon_id = wtforms.StringField(
validators=[wtforms.validators.InputRequired(message="Identifier required")]
)
def __init__(self, *args, macaroon_service, user_service, **kwargs):
super().__init__(*args, **kwargs)
self.user_service = user_service
self.macaroon_service = macaroon_service
def validate_macaroon_id(self, field):
macaroon_id = field.data
if self.macaroon_service.find_macaroon(macaroon_id) is None:
raise wtforms.validators.ValidationError("No such macaroon")
# /manage/organizations/ forms
| DeleteMacaroonForm |
python | PrefectHQ__prefect | tests/server/schemas/test_core.py | {
"start": 8523,
"end": 9537
} | class ____:
def test_health_policy_enforces_max_late_runs(self):
policy = schemas.core.WorkQueueHealthPolicy(
maximum_late_runs=1, maximum_seconds_since_last_polled=None
)
assert policy.evaluate_health_status(late_runs_count=0) is True
assert policy.evaluate_health_status(late_runs_count=2) is False
def test_health_policy_enforces_seconds_since_last_polled(self):
policy = schemas.core.WorkQueueHealthPolicy(
maximum_late_runs=None, maximum_seconds_since_last_polled=30
)
assert (
policy.evaluate_health_status(late_runs_count=0, last_polled=now("UTC"))
is True
)
assert (
policy.evaluate_health_status(
late_runs_count=2, last_polled=now("UTC") - timedelta(seconds=60)
)
is False
)
assert (
policy.evaluate_health_status(late_runs_count=2, last_polled=None) is False
)
| TestWorkQueueHealthPolicy |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_retry_execution.py | {
"start": 17994,
"end": 28758
} | class ____(ExecutingGraphQLContextTestMatrix):
def test_retry_hard_failure(self, graphql_context: WorkspaceRequestContext):
selector = infer_job_selector(graphql_context, "hard_failer")
result = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"runConfigData": {"ops": {"hard_fail_or_0": {"config": {"fail": True}}}},
}
},
)
run_id = result.data["launchPipelineExecution"]["run"]["runId"]
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_started(logs, "hard_fail_or_0")
assert step_did_not_run(logs, "hard_fail_or_0")
assert step_did_not_run(logs, "increment")
retry = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"runConfigData": {"ops": {"hard_fail_or_0": {"config": {"fail": False}}}},
"executionMetadata": {
"rootRunId": run_id,
"parentRunId": run_id,
"tags": [{"key": RESUME_RETRY_TAG, "value": "true"}],
},
}
},
)
run_id = retry.data["launchPipelineReexecution"]["run"]["runId"]
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_did_succeed(logs, "hard_fail_or_0")
assert step_did_succeed(logs, "increment")
def test_retry_failure_all_steps_with_reexecution_params(
self, graphql_context: WorkspaceRequestContext
):
"""Test with providng reexecutionParams rather than executionParams."""
selector = infer_job_selector(graphql_context, "chained_failure_job")
# trigger failure in the conditionally_fail op
output_file = os.path.join(
get_system_temp_directory(), "chained_failure_job_conditionally_fail"
)
try:
with open(output_file, "w", encoding="utf8"):
result = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
}
},
)
finally:
os.remove(output_file)
run_id = result.data["launchPipelineExecution"]["run"]["runId"]
run = graphql_context.instance.get_run_by_id(run_id)
assert run and run.status == DagsterRunStatus.FAILURE
assert run.tags[RUN_FAILURE_REASON_TAG] == RunFailureReason.STEP_FAILURE.value
retry = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={"reexecutionParams": {"parentRunId": run_id, "strategy": "ALL_STEPS"}},
)
assert retry.data["launchPipelineReexecution"].get("run"), retry.data[
"launchPipelineReexecution"
]
run_id = retry.data["launchPipelineReexecution"]["run"]["runId"]
run = graphql_context.instance.get_run_by_id(run_id)
assert run and run.status == DagsterRunStatus.SUCCESS
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_did_succeed(logs, "always_succeed")
assert step_did_succeed(logs, "conditionally_fail")
assert step_did_succeed(logs, "after_failure")
def test_retry_asset_job_with_reexecution_params(
self, graphql_context: WorkspaceRequestContext
):
selector = infer_job_selector(
graphql_context, "two_assets_job", asset_selection=[{"path": ["asset_one"]}]
)
result = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
}
},
)
run_id = result.data["launchPipelineExecution"]["run"]["runId"]
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_did_succeed(logs, "asset_one")
assert step_did_not_run(logs, "asset_two")
retry_one = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={"reexecutionParams": {"parentRunId": run_id, "strategy": "ALL_STEPS"}},
)
run_id = retry_one.data["launchPipelineReexecution"]["run"]["runId"]
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_did_succeed(logs, "asset_one")
assert step_did_not_run(logs, "asset_two")
def test_retry_hard_failure_with_reexecution_params_run_config_changed(
self, graphql_context: WorkspaceRequestContext
):
"""Test that reexecution fails if the run config changes."""
selector = infer_job_selector(graphql_context, "chained_failure_job")
# trigger failure in the conditionally_fail op
output_file = os.path.join(
get_system_temp_directory(), "chained_failure_job_conditionally_fail"
)
try:
with open(output_file, "w", encoding="utf8"):
result = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
}
},
)
finally:
os.remove(output_file)
parent_run_id = result.data["launchPipelineExecution"]["run"]["runId"]
parent_run = graphql_context.instance.get_run_by_id(parent_run_id)
assert parent_run
assert parent_run.status == DagsterRunStatus.FAILURE
# override run config to make it fail
graphql_context.instance.delete_run(parent_run_id)
graphql_context.instance.add_run(parent_run._replace(run_config={"bad": "config"}))
retry = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={
"reexecutionParams": {"parentRunId": parent_run_id, "strategy": "FROM_FAILURE"}
},
)
assert "DagsterInvalidConfigError" in str(
retry.data["launchPipelineReexecution"]["message"]
)
def test_retry_failure_with_reexecution_params(self, graphql_context: WorkspaceRequestContext):
"""Test with providng reexecutionParams rather than executionParams."""
selector = infer_job_selector(graphql_context, "chained_failure_job")
# trigger failure in the conditionally_fail op
output_file = os.path.join(
get_system_temp_directory(), "chained_failure_job_conditionally_fail"
)
try:
with open(output_file, "w", encoding="utf8"):
result = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
}
},
)
finally:
os.remove(output_file)
run_id = result.data["launchPipelineExecution"]["run"]["runId"]
run = graphql_context.instance.get_run_by_id(run_id)
assert run and run.status == DagsterRunStatus.FAILURE
retry = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={"reexecutionParams": {"parentRunId": run_id, "strategy": "FROM_FAILURE"}},
)
run_id = retry.data["launchPipelineReexecution"]["run"]["runId"]
run = graphql_context.instance.get_run_by_id(run_id)
assert run and run.status == DagsterRunStatus.SUCCESS
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_did_not_run(logs, "always_succeed")
assert step_did_succeed(logs, "conditionally_fail")
assert step_did_succeed(logs, "after_failure")
def test_graphene_reexecution_strategy():
"""Check that graphene enum has corresponding values in the ReexecutionStrategy enum."""
for strategy in GrapheneReexecutionStrategy.__enum__:
assert ReexecutionStrategy[strategy.value]
def _do_retry_intermediates_test(graphql_context):
selector = infer_job_selector(graphql_context, "eventually_successful")
result = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_EXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
}
},
)
assert result.data["launchPipelineExecution"]["__typename"] == "LaunchRunSuccess"
run_id = result.data["launchPipelineExecution"]["run"]["runId"]
logs = get_all_logs_for_finished_run_via_subscription(graphql_context, run_id)[
"pipelineRunLogs"
]["messages"]
assert step_did_succeed(logs, "spawn")
assert step_did_fail(logs, "fail")
assert step_did_not_run(logs, "fail_2")
assert step_did_not_run(logs, "fail_3")
assert step_did_not_run(logs, "reset")
retry_one = execute_dagster_graphql_and_finish_runs(
graphql_context,
LAUNCH_PIPELINE_REEXECUTION_MUTATION,
variables={
"executionParams": {
"selector": selector,
"executionMetadata": {
"rootRunId": run_id,
"parentRunId": run_id,
"tags": [{"key": RESUME_RETRY_TAG, "value": "true"}],
},
}
},
)
retry_run_id = retry_one.data["launchPipelineReexecution"]["run"]["runId"]
return retry_run_id
| TestHardFailures |
python | pennersr__django-allauth | allauth/account/views.py | {
"start": 25349,
"end": 25719
} | class ____(TemplateView):
template_name = (
"account/password_reset_from_key_done." + app_settings.TEMPLATE_EXTENSION
)
password_reset_from_key_done = PasswordResetFromKeyDoneView.as_view()
@method_decorator(rate_limit(action="reset_password_from_key"), name="dispatch")
@method_decorator(login_not_required, name="dispatch")
| PasswordResetFromKeyDoneView |
python | pytorch__pytorch | torch/xpu/__init__.py | {
"start": 6546,
"end": 10440
} | class ____(device):
r"""Context-manager that changes the current device to that of given object.
You can use both tensors and storages as arguments. If a given object is
not allocated on a XPU, this is a no-op.
Args:
obj (Tensor or Storage): object allocated on the selected device.
"""
def __init__(self, obj) -> None:
idx = obj.get_device() if obj.is_xpu else -1
super().__init__(idx)
def set_device(device: _device_t) -> None:
r"""Set the current device.
Args:
device (torch.device or int or str): selected device. This function is a
no-op if this argument is negative.
"""
_lazy_init()
device = _get_device_index(device)
if device >= 0:
torch._C._xpu_setDevice(device)
def get_device_name(device: Optional[_device_t] = None) -> str:
r"""Get the name of a device.
Args:
device (torch.device or int or str, optional): device for which to
return the name. This function is a no-op if this argument is a
negative integer. It uses the current device, given by :func:`~torch.xpu.current_device`,
if :attr:`device` is ``None`` (default).
Returns:
str: the name of the device
"""
return get_device_properties(device).name
@lru_cache(None)
def get_device_capability(device: Optional[_device_t] = None) -> dict[str, Any]:
r"""Get the xpu capability of a device.
Args:
device (torch.device or int or str, optional): device for which to
return the device capability. This function is a no-op if this
argument is a negative integer. It uses the current device, given by
:func:`~torch.xpu.current_device`, if :attr:`device` is ``None``
(default).
Returns:
dict[str, Any]: the xpu capability dictionary of the device
"""
props = get_device_properties(device)
# Only keep attributes that are safe for dictionary serialization.
serializable_types = (int, float, bool, str, type(None), list, tuple, dict)
return {
key: value
for key in dir(props)
if not key.startswith("__")
and isinstance((value := getattr(props, key)), serializable_types)
}
def get_device_properties(
device: Optional[_device_t] = None,
) -> _XpuDeviceProperties: # pyrefly: ignore # not-a-type
r"""Get the properties of a device.
Args:
device (torch.device or int or str): device for which to return the
properties of the device.
Returns:
_XpuDeviceProperties: the properties of the device
"""
_lazy_init()
device = _get_device_index(device, optional=True)
return _get_device_properties(device) # type: ignore[name-defined] # noqa: F821
def current_device() -> int:
r"""Return the index of a currently selected device."""
_lazy_init()
return torch._C._xpu_getDevice()
def _get_device(device: Union[int, str, torch.device]) -> torch.device:
r"""Return the torch.device type object from the passed in device.
Args:
device (torch.device or int or str): selected device.
"""
if isinstance(device, str):
device = torch.device(device)
elif isinstance(device, int):
device = torch.device("xpu", device)
return device
def can_device_access_peer(device: _device_t, peer: _device_t) -> bool:
r"""Query whether a device can access a peer device's memory.
Args:
device (torch.device or int or str): selected device.
peer (torch.device or int or str): peer device to query access to.
Returns:
bool: ``True`` if ``device`` can access ``peer``, ``False`` otherwise.
"""
_lazy_init()
device = _get_device_index(device, optional=True)
peer = _get_device_index(peer, optional=True)
return torch._C._xpu_canDeviceAccessPeer(device, peer)
| device_of |
python | scipy__scipy | scipy/signal/tests/test_array_tools.py | {
"start": 225,
"end": 3589
} | class ____:
def test_axis_slice(self):
a = np.arange(12).reshape(3, 4)
s = axis_slice(a, start=0, stop=1, axis=0)
xp_assert_equal(s, a[0:1, :])
s = axis_slice(a, start=-1, axis=0)
xp_assert_equal(s, a[-1:, :])
s = axis_slice(a, start=0, stop=1, axis=1)
xp_assert_equal(s, a[:, 0:1])
s = axis_slice(a, start=-1, axis=1)
xp_assert_equal(s, a[:, -1:])
s = axis_slice(a, start=0, step=2, axis=0)
xp_assert_equal(s, a[::2, :])
s = axis_slice(a, start=0, step=2, axis=1)
xp_assert_equal(s, a[:, ::2])
def test_axis_reverse(self):
a = np.arange(12).reshape(3, 4)
r = axis_reverse(a, axis=0)
xp_assert_equal(r, a[::-1, :])
r = axis_reverse(a, axis=1)
xp_assert_equal(r, a[:, ::-1])
def test_odd_ext(self):
a = np.array([[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5]])
odd = odd_ext(a, 2, axis=1)
expected = np.array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
[11, 10, 9, 8, 7, 6, 5, 4, 3]])
xp_assert_equal(odd, expected)
odd = odd_ext(a, 1, axis=0)
expected = np.array([[-7, -4, -1, 2, 5],
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[17, 14, 11, 8, 5]])
xp_assert_equal(odd, expected)
assert_raises(ValueError, odd_ext, a, 2, axis=0)
assert_raises(ValueError, odd_ext, a, 5, axis=1)
def test_even_ext(self):
a = np.array([[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5]])
even = even_ext(a, 2, axis=1)
expected = np.array([[3, 2, 1, 2, 3, 4, 5, 4, 3],
[7, 8, 9, 8, 7, 6, 5, 6, 7]])
xp_assert_equal(even, expected)
even = even_ext(a, 1, axis=0)
expected = np.array([[9, 8, 7, 6, 5],
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[1, 2, 3, 4, 5]])
xp_assert_equal(even, expected)
assert_raises(ValueError, even_ext, a, 2, axis=0)
assert_raises(ValueError, even_ext, a, 5, axis=1)
def test_const_ext(self):
a = np.array([[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5]])
const = const_ext(a, 2, axis=1)
expected = np.array([[1, 1, 1, 2, 3, 4, 5, 5, 5],
[9, 9, 9, 8, 7, 6, 5, 5, 5]])
xp_assert_equal(const, expected)
const = const_ext(a, 1, axis=0)
expected = np.array([[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[9, 8, 7, 6, 5]])
xp_assert_equal(const, expected)
def test_zero_ext(self):
a = np.array([[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5]])
zero = zero_ext(a, 2, axis=1)
expected = np.array([[0, 0, 1, 2, 3, 4, 5, 0, 0],
[0, 0, 9, 8, 7, 6, 5, 0, 0]])
xp_assert_equal(zero, expected)
zero = zero_ext(a, 1, axis=0)
expected = np.array([[0, 0, 0, 0, 0],
[1, 2, 3, 4, 5],
[9, 8, 7, 6, 5],
[0, 0, 0, 0, 0]])
xp_assert_equal(zero, expected)
| TestArrayTools |
python | django__django | tests/model_meta/models.py | {
"start": 3926,
"end": 3992
} | class ____(Person):
class Meta:
proxy = True
| ProxyPerson |
python | getsentry__sentry | src/sentry/analytics/events/eventuser_snuba_for_projects.py | {
"start": 85,
"end": 283
} | class ____(analytics.Event):
project_ids: list[int]
total_tries: int
total_rows_returned: int
total_time_ms: int
analytics.register(EventUserSnubaForProjects)
| EventUserSnubaForProjects |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 277286,
"end": 277986
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of RemoveLabelsFromLabelable"""
__schema__ = github_schema
__field_names__ = ("labelable_id", "label_ids", "client_mutation_id")
labelable_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="labelableId")
"""The id of the Labelable to remove labels from."""
label_ids = sgqlc.types.Field(sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(ID))), graphql_name="labelIds")
"""The ids of labels to remove."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| RemoveLabelsFromLabelableInput |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 343,
"end": 394
} | class ____:
x = attr.ib(type=List[int])
@attr.s
| D |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/instance_variable.py | {
"start": 0,
"end": 125
} | class ____:
def __init__(self):
self.attr1 = None #: docstring foo
self.attr2 = None #: docstring foo
| Foo |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 1697,
"end": 3103
} | class ____(type):
def __instancecheck__(cls, instance):
"""Override for isinstance(instance, cls)."""
# TODO: add support for user-generated subclasses with custom instance
# checks
# e.g., could check for a fetch response with x.constructor.name == "Response"
# or Object.prototype.toString.call(x) == "[object Response]".
return cls.__subclasscheck__(type(instance))
def __subclasscheck__(cls, subclass):
# TODO: This works for now but maybe there is a better or cleaner way to
# do this.
if type.__subclasscheck__(cls, subclass):
return True
if not hasattr(subclass, "_js_type_flags"):
return False
# For the "synthetic" subtypes defined in this file, we define
# _js_type_flags as a string. We look these up in the _js_flags dict to
# convert to a number.
cls_flags = cls._js_type_flags # type:ignore[attr-defined]
if isinstance(cls_flags, int):
cls_flags = [cls_flags]
else:
cls_flags = [_process_flag_expression(f) for f in cls_flags]
subclass_flags = subclass._js_type_flags
if not isinstance(subclass_flags, int):
subclass_flags = _binor_reduce(_js_flags[f] for f in subclass_flags)
return any(cls_flag & subclass_flags == cls_flag for cls_flag in cls_flags)
| _JsProxyMetaClass |
python | scrapy__scrapy | tests/test_pipeline_images.py | {
"start": 12432,
"end": 21310
} | class ____:
img_cls_attribute_names = [
# Pipeline attribute names with corresponding setting names.
("EXPIRES", "IMAGES_EXPIRES"),
("MIN_WIDTH", "IMAGES_MIN_WIDTH"),
("MIN_HEIGHT", "IMAGES_MIN_HEIGHT"),
("IMAGES_URLS_FIELD", "IMAGES_URLS_FIELD"),
("IMAGES_RESULT_FIELD", "IMAGES_RESULT_FIELD"),
("THUMBS", "IMAGES_THUMBS"),
]
# This should match what is defined in ImagesPipeline.
default_pipeline_settings = {
"MIN_WIDTH": 0,
"MIN_HEIGHT": 0,
"EXPIRES": 90,
"THUMBS": {},
"IMAGES_URLS_FIELD": "image_urls",
"IMAGES_RESULT_FIELD": "images",
}
def _generate_fake_settings(self, tmp_path, prefix=None):
"""
:param prefix: string for setting keys
:return: dictionary of image pipeline settings
"""
def random_string():
return "".join([chr(random.randint(97, 123)) for _ in range(10)])
settings = {
"IMAGES_EXPIRES": random.randint(100, 1000),
"IMAGES_STORE": tmp_path,
"IMAGES_RESULT_FIELD": random_string(),
"IMAGES_URLS_FIELD": random_string(),
"IMAGES_MIN_WIDTH": random.randint(1, 1000),
"IMAGES_MIN_HEIGHT": random.randint(1, 1000),
"IMAGES_THUMBS": {
"small": (random.randint(1, 1000), random.randint(1, 1000)),
"big": (random.randint(1, 1000), random.randint(1, 1000)),
},
}
if not prefix:
return settings
return {
prefix.upper() + "_" + k if k != "IMAGES_STORE" else k: v
for k, v in settings.items()
}
def _generate_fake_pipeline_subclass(self):
"""
:return: ImagePipeline class will all uppercase attributes set.
"""
class UserDefinedImagePipeline(ImagesPipeline):
# Values should be in different range than fake_settings.
MIN_WIDTH = random.randint(1000, 2000)
MIN_HEIGHT = random.randint(1000, 2000)
THUMBS = {
"small": (random.randint(1000, 2000), random.randint(1000, 2000)),
"big": (random.randint(1000, 2000), random.randint(1000, 2000)),
}
EXPIRES = random.randint(1000, 2000)
IMAGES_URLS_FIELD = "field_one"
IMAGES_RESULT_FIELD = "field_two"
return UserDefinedImagePipeline
def test_different_settings_for_different_instances(self, tmp_path):
"""
If there are two instances of ImagesPipeline class with different settings, they should
have different settings.
"""
custom_settings = self._generate_fake_settings(tmp_path)
default_sts_pipe = ImagesPipeline(tmp_path, crawler=get_crawler(None))
user_sts_pipe = ImagesPipeline.from_crawler(get_crawler(None, custom_settings))
for pipe_attr, settings_attr in self.img_cls_attribute_names:
expected_default_value = self.default_pipeline_settings.get(pipe_attr)
custom_value = custom_settings.get(settings_attr)
assert expected_default_value != custom_value
assert (
getattr(default_sts_pipe, pipe_attr.lower()) == expected_default_value
)
assert getattr(user_sts_pipe, pipe_attr.lower()) == custom_value
def test_subclass_attrs_preserved_default_settings(self, tmp_path):
"""
If image settings are not defined at all subclass of ImagePipeline takes values
from class attributes.
"""
pipeline_cls = self._generate_fake_pipeline_subclass()
pipeline = pipeline_cls.from_crawler(
get_crawler(None, {"IMAGES_STORE": tmp_path})
)
for pipe_attr, settings_attr in self.img_cls_attribute_names:
# Instance attribute (lowercase) must be equal to class attribute (uppercase).
attr_value = getattr(pipeline, pipe_attr.lower())
assert attr_value != self.default_pipeline_settings[pipe_attr]
assert attr_value == getattr(pipeline, pipe_attr)
def test_subclass_attrs_preserved_custom_settings(self, tmp_path):
"""
If image settings are defined but they are not defined for subclass default
values taken from settings should be preserved.
"""
pipeline_cls = self._generate_fake_pipeline_subclass()
settings = self._generate_fake_settings(tmp_path)
pipeline = pipeline_cls.from_crawler(get_crawler(None, settings))
for pipe_attr, settings_attr in self.img_cls_attribute_names:
# Instance attribute (lowercase) must be equal to
# value defined in settings.
value = getattr(pipeline, pipe_attr.lower())
assert value != self.default_pipeline_settings[pipe_attr]
setings_value = settings.get(settings_attr)
assert value == setings_value
def test_no_custom_settings_for_subclasses(self, tmp_path):
"""
If there are no settings for subclass and no subclass attributes, pipeline should use
attributes of base class.
"""
class UserDefinedImagePipeline(ImagesPipeline):
pass
user_pipeline = UserDefinedImagePipeline.from_crawler(
get_crawler(None, {"IMAGES_STORE": tmp_path})
)
for pipe_attr, settings_attr in self.img_cls_attribute_names:
# Values from settings for custom pipeline should be set on pipeline instance.
custom_value = self.default_pipeline_settings.get(pipe_attr.upper())
assert getattr(user_pipeline, pipe_attr.lower()) == custom_value
def test_custom_settings_for_subclasses(self, tmp_path):
"""
If there are custom settings for subclass and NO class attributes, pipeline should use custom
settings.
"""
class UserDefinedImagePipeline(ImagesPipeline):
pass
prefix = UserDefinedImagePipeline.__name__.upper()
settings = self._generate_fake_settings(tmp_path, prefix=prefix)
user_pipeline = UserDefinedImagePipeline.from_crawler(
get_crawler(None, settings)
)
for pipe_attr, settings_attr in self.img_cls_attribute_names:
# Values from settings for custom pipeline should be set on pipeline instance.
custom_value = settings.get(prefix + "_" + settings_attr)
assert custom_value != self.default_pipeline_settings[pipe_attr]
assert getattr(user_pipeline, pipe_attr.lower()) == custom_value
def test_custom_settings_and_class_attrs_for_subclasses(self, tmp_path):
"""
If there are custom settings for subclass AND class attributes
setting keys are preferred and override attributes.
"""
pipeline_cls = self._generate_fake_pipeline_subclass()
prefix = pipeline_cls.__name__.upper()
settings = self._generate_fake_settings(tmp_path, prefix=prefix)
user_pipeline = pipeline_cls.from_crawler(get_crawler(None, settings))
for pipe_attr, settings_attr in self.img_cls_attribute_names:
custom_value = settings.get(prefix + "_" + settings_attr)
assert custom_value != self.default_pipeline_settings[pipe_attr]
assert getattr(user_pipeline, pipe_attr.lower()) == custom_value
def test_cls_attrs_with_DEFAULT_prefix(self, tmp_path):
class UserDefinedImagePipeline(ImagesPipeline):
DEFAULT_IMAGES_URLS_FIELD = "something"
DEFAULT_IMAGES_RESULT_FIELD = "something_else"
pipeline = UserDefinedImagePipeline.from_crawler(
get_crawler(None, {"IMAGES_STORE": tmp_path})
)
assert (
pipeline.images_result_field
== UserDefinedImagePipeline.DEFAULT_IMAGES_RESULT_FIELD
)
assert (
pipeline.images_urls_field
== UserDefinedImagePipeline.DEFAULT_IMAGES_URLS_FIELD
)
def test_user_defined_subclass_default_key_names(self, tmp_path):
"""Test situation when user defines subclass of ImagePipeline,
but uses attribute names for default pipeline (without prefixing
them with pipeline class name).
"""
settings = self._generate_fake_settings(tmp_path)
class UserPipe(ImagesPipeline):
pass
pipeline_cls = UserPipe.from_crawler(get_crawler(None, settings))
for pipe_attr, settings_attr in self.img_cls_attribute_names:
expected_value = settings.get(settings_attr)
assert getattr(pipeline_cls, pipe_attr.lower()) == expected_value
def _create_image(format_, *a, **kw):
buf = io.BytesIO()
Image.new(*a, **kw).save(buf, format_)
buf.seek(0)
return Image.open(buf), buf
| TestImagesPipelineCustomSettings |
python | getsentry__sentry | src/sentry/consumers/synchronized.py | {
"start": 1500,
"end": 11894
} | class ____(Consumer[TStrategyPayload]):
"""
This class implements a consumer that is can only consume messages that
have already been consumed and committed b y one or more other consumer
groups.
The consumer groups that are being "followed" are required to publish
their offsets to a shared commit log topic. The advancement of the
offsets for these consumer groups in the commit log topic controls
whether or not the local consumer is allowed to consume messages from its
assigned partitions. (This commit log topic works similarly to/was
inspired by/essentially duplicates the contents of the Kafka built-in
``__consumer_offsets`` topic, which seems to be intended to be a private
API of the Kafka system based on the lack of external documentation.)
It is important to note that the since the local consumer is only allowed
to consume messages that have been consumed and committed by all of the
members of the referenced consumer groups, this consumer can only consume
messages as fast as the slowest consumer (or in other words, the most
latent or lagging consumer) for each partition. If one of these consumers
stops consuming messages entirely, this consumer will also stop making
progress in those partitions.
"""
def __init__(
self,
consumer: Consumer[TStrategyPayload],
commit_log_consumer: Consumer[KafkaPayload],
commit_log_topic: Topic,
commit_log_groups: set[str],
) -> None:
self.__consumer = consumer
self.__commit_log_consumer = commit_log_consumer
self.__commit_log_topic = commit_log_topic
self.__commit_log_groups = commit_log_groups
self.__remote_offsets: Synchronized[Mapping[str, MutableMapping[Partition, int]]] = (
Synchronized({group: {} for group in commit_log_groups})
)
self.__commit_log_worker_stop_requested = Event()
self.__commit_log_worker_subscription_received = Event()
self.__commit_log_worker = execute(self.__run_commit_log_worker)
logger.debug("Waiting for commit log consumer to receieve assignment...")
while not self.__commit_log_worker_subscription_received.wait(0.1):
# Check to make sure we're not waiting for an event that will never
# happen if the commit log consumer has crashed.
if not self.__commit_log_worker.running():
self.__commit_log_worker.result()
else:
logger.debug("Commit log consumer has started.")
# The set of partitions that have been paused by the caller/user. This
# takes precedence over whether or not the partition should be paused
# due to offset synchronization.
self.__paused: set[Partition] = set()
def __run_commit_log_worker(self) -> None:
# TODO: This needs to roll back to the initial offset.
# TODO: This needs to ensure that it is subscribed to all partitions.
def assignment_callback(offsets: Mapping[Partition, int]) -> None:
logger.debug("Commit log consumer received assignment: %r", offsets)
self.__commit_log_worker_subscription_received.set()
self.__commit_log_consumer.subscribe(
[self.__commit_log_topic], on_assign=assignment_callback
)
while not self.__commit_log_worker_stop_requested.is_set():
try:
message = self.__commit_log_consumer.poll(0.1)
except EndOfPartition:
continue
if message is None:
continue
commit = commit_codec.decode(message.payload)
if commit.group not in self.__commit_log_groups:
continue
now = time()
with self.__remote_offsets.get() as remote_offsets:
# NOTE: This will store data about partitions that are not
# actually part of the subscription or assignment. This
# approach (potentially) requires more memory and locking
# overhead (due to writing state for partitions that are not
# subscribed or assigned), but amortizes the cost of the
# initial load of the topic and makes the implementation
# quite a bit simpler.
remote_offsets[commit.group][commit.partition] = commit.offset
if commit.orig_message_ts is not None:
metrics.distribution(
"commit_log_msg_latency",
(now - commit.orig_message_ts) * 1000,
tags={
"partition": str(commit.partition.index),
"group": commit.group,
},
unit="millisecond",
)
metrics.distribution(
"commit_log_latency",
(now - datetime.timestamp(message.timestamp)) * 1000,
tags={
"partition": str(commit.partition.index),
"group": commit.group,
},
unit="millisecond",
)
self.__commit_log_consumer.close()
def __check_commit_log_worker_running(self) -> None:
if not self.closed and not self.__commit_log_worker.running():
try:
self.__commit_log_worker.result()
except Exception as e:
raise RuntimeError("commit log consumer thread crashed") from e
else:
raise RuntimeError("commit log consumer thread unexpectedly exited")
def subscribe(
self,
topics: Sequence[Topic],
on_assign: Callable[[Mapping[Partition, int]], None] | None = None,
on_revoke: Callable[[Sequence[Partition]], None] | None = None,
) -> None:
def assignment_callback(offsets: Mapping[Partition, int]) -> None:
for partition in offsets:
self.__paused.discard(partition)
if on_assign is not None:
on_assign(offsets)
def revocation_callback(partitions: Sequence[Partition]) -> None:
for partition in partitions:
self.__paused.discard(partition)
if on_revoke is not None:
on_revoke(partitions)
return self.__consumer.subscribe(
topics, on_assign=assignment_callback, on_revoke=revocation_callback
)
def unsubscribe(self) -> None:
return self.__consumer.unsubscribe()
def poll(self, timeout: float | None = None) -> BrokerValue[TStrategyPayload] | None:
self.__check_commit_log_worker_running()
# Resume any partitions that can be resumed (where the local
# offset is less than the remote offset.)
resume_candidates = set(self.__consumer.paused()) - self.__paused
if resume_candidates:
local_offsets = self.tell()
resume_partitions = []
with self.__remote_offsets.get() as remote_offsets:
for partition in resume_candidates:
remote_offset = min(
(offsets.get(partition, 0) for offsets in remote_offsets.values()),
default=0,
)
if remote_offset > local_offsets[partition]:
resume_partitions.append(partition)
if resume_partitions:
self.__consumer.resume(resume_partitions)
# We don't need to explicitly handle ``EndOfPartition`` here -- even if
# we receive the next message before the leader, we will roll back our
# offsets and wait for the leader to advance.
message = self.__consumer.poll(timeout)
if message is None:
return None
with self.__remote_offsets.get() as remote_offsets:
remote_offset = min(
(offsets.get(message.partition, 0) for offsets in remote_offsets.values()),
default=0,
)
# Check to make sure the message does not exceed the remote offset. If
# it does, pause the partition and seek back to the message offset.
if message.offset >= remote_offset:
self.__consumer.pause([message.partition])
self.__consumer.seek({message.partition: message.offset})
return None
return message
def pause(self, partitions: Sequence[Partition]) -> None:
if self.closed:
raise RuntimeError("consumer is closed")
if set(partitions) - self.tell().keys():
raise ConsumerError("cannot pause unassigned partitions")
for partition in partitions:
self.__paused.add(partition)
self.__consumer.pause(partitions)
def resume(self, partitions: Sequence[Partition]) -> None:
if self.closed:
raise RuntimeError("consumer is closed")
if set(partitions) - self.tell().keys():
raise ConsumerError("cannot resume unassigned partitions")
# Partitions are not actually resumed by the inner consumer immediately
# upon calling this method. Instead, any partitions that are able to be
# resumed will be resumed at the start of the next ``poll`` call.
for partition in partitions:
self.__paused.discard(partition)
def paused(self) -> Sequence[Partition]:
return [*self.__paused]
def tell(self) -> Mapping[Partition, int]:
return self.__consumer.tell()
def seek(self, offsets: Mapping[Partition, int]) -> None:
return self.__consumer.seek(offsets)
def stage_offsets(self, offsets: Mapping[Partition, int]) -> None:
return self.__consumer.stage_offsets(offsets)
def commit_offsets(self) -> Mapping[Partition, int] | None:
return self.__consumer.commit_offsets()
def close(self, timeout: float | None = None) -> None:
# TODO: Be careful to ensure there are not any deadlock conditions
# here. Should this actually wait for the commit log worker?
self.__commit_log_worker_stop_requested.set()
return self.__consumer.close(timeout)
@property
def closed(self) -> bool:
return self.__consumer.closed
@property
def member_id(self) -> str:
return self.__consumer.member_id
| SynchronizedConsumer |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/mwaa.py | {
"start": 1480,
"end": 8694
} | class ____(AwsBaseOperator[MwaaHook]):
"""
Trigger a Dag Run for a Dag in an Amazon MWAA environment.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:MwaaTriggerDagRunOperator`
:param env_name: The MWAA environment name (templated)
:param trigger_dag_id: The ID of the DAG to be triggered (templated)
:param trigger_run_id: The Run ID. This together with trigger_dag_id are a unique key. (templated)
:param logical_date: The logical date (previously called execution date). This is the time or interval
covered by this DAG run, according to the DAG definition. This together with trigger_dag_id are a
unique key. This field is required if your environment is running with Airflow 3. (templated)
:param data_interval_start: The beginning of the interval the DAG run covers
:param data_interval_end: The end of the interval the DAG run covers
:param conf: Additional configuration parameters. The value of this field can be set only when creating
the object. (templated)
:param note: Contains manually entered notes by the user about the DagRun. (templated)
:param airflow_version: The Airflow major version the MWAA environment runs.
This parameter is only used if the local web token method is used to call Airflow API. (templated)
:param wait_for_completion: Whether to wait for DAG run to stop. (default: False)
:param waiter_delay: Time in seconds to wait between status checks. (default: 120)
:param waiter_max_attempts: Maximum number of attempts to check for DAG run completion. (default: 720)
:param deferrable: If True, the operator will wait asynchronously for the DAG run to stop.
This implies waiting for completion. This mode requires aiobotocore module to be installed.
(default: False)
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:param botocore_config: Configuration dictionary (key-values) for botocore client. See:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
"""
aws_hook_class = MwaaHook
template_fields: Sequence[str] = aws_template_fields(
"env_name",
"trigger_dag_id",
"trigger_run_id",
"logical_date",
"data_interval_start",
"data_interval_end",
"conf",
"note",
"airflow_version",
)
template_fields_renderers = {"conf": "json"}
def __init__(
self,
*,
env_name: str,
trigger_dag_id: str,
trigger_run_id: str | None = None,
logical_date: str | None = None,
data_interval_start: str | None = None,
data_interval_end: str | None = None,
conf: dict | None = None,
note: str | None = None,
airflow_version: Literal[2, 3] | None = None,
wait_for_completion: bool = False,
waiter_delay: int = 60,
waiter_max_attempts: int = 20,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(**kwargs)
self.env_name = env_name
self.trigger_dag_id = trigger_dag_id
self.trigger_run_id = trigger_run_id
self.logical_date = logical_date
self.data_interval_start = data_interval_start
self.data_interval_end = data_interval_end
self.conf = conf if conf else {}
self.note = note
self.airflow_version = airflow_version
self.wait_for_completion = wait_for_completion
self.waiter_delay = waiter_delay
self.waiter_max_attempts = waiter_max_attempts
self.deferrable = deferrable
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> dict:
validated_event = validate_execute_complete_event(event)
if validated_event["status"] != "success":
raise AirflowException(f"DAG run failed: {validated_event}")
dag_run_id = validated_event["dag_run_id"]
self.log.info("DAG run %s of DAG %s completed", dag_run_id, self.trigger_dag_id)
return self.hook.invoke_rest_api(
env_name=self.env_name,
path=f"/dags/{self.trigger_dag_id}/dagRuns/{dag_run_id}",
method="GET",
airflow_version=self.airflow_version,
)
def execute(self, context: Context) -> dict:
"""
Trigger a Dag Run for the Dag in the Amazon MWAA environment.
:param context: the Context object
:return: dict with information about the Dag run
For details of the returned dict, see :py:meth:`botocore.client.MWAA.invoke_rest_api`
"""
response = self.hook.invoke_rest_api(
env_name=self.env_name,
path=f"/dags/{self.trigger_dag_id}/dagRuns",
method="POST",
body={
"dag_run_id": self.trigger_run_id,
"logical_date": self.logical_date,
"data_interval_start": self.data_interval_start,
"data_interval_end": self.data_interval_end,
"conf": self.conf,
"note": self.note,
},
airflow_version=self.airflow_version,
)
dag_run_id = response["RestApiResponse"]["dag_run_id"]
self.log.info("DAG run %s of DAG %s created", dag_run_id, self.trigger_dag_id)
task_description = f"DAG run {dag_run_id} of DAG {self.trigger_dag_id} to complete"
if self.deferrable:
self.log.info("Deferring for %s", task_description)
self.defer(
trigger=MwaaDagRunCompletedTrigger(
external_env_name=self.env_name,
external_dag_id=self.trigger_dag_id,
external_dag_run_id=dag_run_id,
waiter_delay=self.waiter_delay,
waiter_max_attempts=self.waiter_max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
elif self.wait_for_completion:
self.log.info("Waiting for %s", task_description)
api_kwargs = {
"Name": self.env_name,
"Path": f"/dags/{self.trigger_dag_id}/dagRuns/{dag_run_id}",
"Method": "GET",
}
self.hook.get_waiter("mwaa_dag_run_complete").wait(
**api_kwargs,
WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts},
)
return response
| MwaaTriggerDagRunOperator |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 92730,
"end": 93647
} | class ____:
@pytest.mark.parametrize(
"one, two",
list(
itertools.combinations(
(
SUBCLASS_SAFE_FUNCTIONS,
UNSUPPORTED_FUNCTIONS,
set(FUNCTION_HELPERS.keys()),
set(DISPATCHED_FUNCTIONS.keys()),
),
2,
),
),
)
def test_no_duplicates(self, one, two):
assert not one.intersection(two)
def test_all_included(self):
included_in_helpers = (
SUBCLASS_SAFE_FUNCTIONS
| UNSUPPORTED_FUNCTIONS
| set(FUNCTION_HELPERS.keys())
| set(DISPATCHED_FUNCTIONS.keys())
)
assert all_wrapped_functions == included_in_helpers
def test_ignored_are_untested(self):
assert IGNORED_FUNCTIONS | TBD_FUNCTIONS == untested_functions
| TestFunctionHelpersCompleteness |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-clarifai/llama_index/embeddings/clarifai/base.py | {
"start": 469,
"end": 5063
} | class ____(BaseEmbedding):
"""
Clarifai embeddings class.
Clarifai uses Personal Access Tokens(PAT) to validate requests.
You can create and manage PATs under your Clarifai account security settings.
Export your PAT as an environment variable by running `export CLARIFAI_PAT={PAT}`
"""
model_url: Optional[str] = Field(
description=f"Full URL of the model. e.g. `{EXAMPLE_URL}`"
)
model_id: Optional[str] = Field(description="Model ID.")
model_version_id: Optional[str] = Field(description="Model Version ID.")
app_id: Optional[str] = Field(description="Clarifai application ID of the model.")
user_id: Optional[str] = Field(description="Clarifai user ID of the model.")
pat: Optional[str] = Field(
description="Personal Access Tokens(PAT) to validate requests."
)
_model: Any = PrivateAttr()
def __init__(
self,
model_name: Optional[str] = None,
model_url: Optional[str] = None,
model_version_id: Optional[str] = "",
app_id: Optional[str] = None,
user_id: Optional[str] = None,
pat: Optional[str] = None,
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
callback_manager: Optional[CallbackManager] = None,
):
embed_batch_size = min(128, embed_batch_size)
if pat is None and os.environ.get("CLARIFAI_PAT") is not None:
pat = os.environ.get("CLARIFAI_PAT")
if not pat and os.environ.get("CLARIFAI_PAT") is None:
raise ValueError(
"Set `CLARIFAI_PAT` as env variable or pass `pat` as constructor argument"
)
if model_url is not None and model_name is not None:
raise ValueError("You can only specify one of model_url or model_name.")
if model_url is None and model_name is None:
raise ValueError("You must specify one of model_url or model_name.")
if model_name is not None:
if app_id is None or user_id is None:
raise ValueError(
f"Missing one app ID or user ID of the model: {app_id=}, {user_id=}"
)
else:
model = Model(
user_id=user_id,
app_id=app_id,
model_id=model_name,
model_version={"id": model_version_id},
pat=pat,
)
if model_url is not None:
model = Model(model_url, pat=pat)
model_name = model.id
super().__init__(
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
model_name=model_name,
)
self._model = model
@classmethod
def class_name(cls) -> str:
return "ClarifaiEmbedding"
def _embed(self, sentences: List[str]) -> List[List[float]]:
"""Embed sentences."""
try:
from clarifai.client.input import Inputs
except ImportError:
raise ImportError("ClarifaiEmbedding requires `pip install clarifai`.")
embeddings = []
try:
for i in range(0, len(sentences), self.embed_batch_size):
batch = sentences[i : i + self.embed_batch_size]
input_batch = [
Inputs.get_text_input(input_id=str(id), raw_text=inp)
for id, inp in enumerate(batch)
]
predict_response = self._model.predict(input_batch)
embeddings.extend(
[
list(output.data.embeddings[0].vector)
for output in predict_response.outputs
]
)
except Exception as e:
logger.error(f"Predict failed, exception: {e}")
return embeddings
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
return self._embed([query])[0]
async def _aget_query_embedding(self, query: str) -> List[float]:
"""Get query embedding async."""
return self._get_query_embedding(query)
async def _aget_text_embedding(self, text: str) -> List[float]:
"""Get text embedding async."""
return self._get_text_embedding(text)
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
return self._embed([text])[0]
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings."""
return self._embed(texts)
| ClarifaiEmbedding |
python | streamlit__streamlit | e2e_playwright/st_write_objects.py | {
"start": 1356,
"end": 1470
} | class ____:
name: str
age: int
st.write(ExampleClass)
st.subheader("st.write(reprhtmlable)")
| ExampleClass |
python | astropy__astropy | astropy/table/jsviewer.py | {
"start": 247,
"end": 3208
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.table.jsviewer`.
"""
jquery_url = _config.ConfigItem(
"https://code.jquery.com/jquery-3.6.0.min.js", "The URL to the jquery library."
)
datatables_url = _config.ConfigItem(
"https://cdn.datatables.net/2.1.8/js/dataTables.min.js",
"The URL to the jquery datatables library.",
)
css_urls = _config.ConfigItem(
["https://cdn.datatables.net/2.1.8/css/dataTables.dataTables.min.css"],
"The URLs to the css file(s) to include.",
cfgtype="string_list",
)
conf = Conf()
_TABLE_DIR = Path(extern.__file__).parent
EXTERN_JS_DIR = _TABLE_DIR.joinpath("jquery", "data", "js").resolve()
EXTERN_CSS_DIR = _TABLE_DIR.joinpath("jquery", "data", "css").resolve()
_SORTING_SCRIPT_PART_1 = """
var astropy_sort_num = function(a, b) {{
var a_num = parseFloat(a);
var b_num = parseFloat(b);
if (isNaN(a_num) && isNaN(b_num))
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
else if (!isNaN(a_num) && !isNaN(b_num))
return ((a_num < b_num) ? -1 : ((a_num > b_num) ? 1 : 0));
else
return isNaN(a_num) ? -1 : 1;
}}
"""
_SORTING_SCRIPT_PART_2 = """
jQuery.extend( jQuery.fn.dataTableExt.oSort, {{
"optionalnum-asc": astropy_sort_num,
"optionalnum-desc": function (a,b) {{ return -astropy_sort_num(a, b); }}
}});
"""
IPYNB_JS_SCRIPT = """
<script>
%(sorting_script1)s
require.config({{paths: {{
datatables: '{datatables_url}'
}}}});
require(["datatables"], function(){{
console.log("$('#{tid}').dataTable()");
%(sorting_script2)s
$('#{tid}').dataTable({{
order: [],
pageLength: {display_length},
lengthMenu: {display_length_menu},
pagingType: "full_numbers",
columnDefs: [{{targets: {sort_columns}, type: "optionalnum"}}]
}});
}});
</script>
""" % dict( # noqa: UP031
sorting_script1=_SORTING_SCRIPT_PART_1, sorting_script2=_SORTING_SCRIPT_PART_2
)
HTML_JS_SCRIPT = (
_SORTING_SCRIPT_PART_1
+ _SORTING_SCRIPT_PART_2
+ """
$(document).ready(function() {{
$('#{tid}').dataTable({{
order: [],
pageLength: {display_length},
lengthMenu: {display_length_menu},
pagingType: "full_numbers",
columnDefs: [{{targets: {sort_columns}, type: "optionalnum"}}]
}});
}} );
"""
)
# Default CSS for the JSViewer writer
DEFAULT_CSS = """\
body {font-family: sans-serif;}
table.dataTable {width: auto !important; margin: 0 !important;}
.dataTables_filter, .dataTables_paginate {float: left !important; margin-left:1em}
"""
# Default CSS used when rendering a table in the IPython notebook
DEFAULT_CSS_NB = """\
table.dataTable {clear: both; width: auto !important; margin: 0 !important;}
.dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate{
display: inline-block; margin-right: 1em; }
.paginate_button { margin-right: 5px; }
"""
| Conf |
python | mkdocstrings__mkdocstrings | scripts/make.py | {
"start": 2081,
"end": 7711
} | class ____(subprocess.CalledProcessError):
def __init__(self, *args: Any, python_version: str, **kwargs: Any):
super().__init__(*args, **kwargs)
self.python_version = python_version
def run(version: str, cmd: str, *args: str, **kwargs: Any) -> None:
"""Run a command in a virtual environment."""
kwargs = {"check": True, **kwargs}
uv_run = ["uv", "run", "--no-sync"]
try:
if version == "default":
with environ(UV_PROJECT_ENVIRONMENT=".venv"):
subprocess.run([*uv_run, cmd, *args], **kwargs) # noqa: S603, PLW1510
else:
with environ(UV_PROJECT_ENVIRONMENT=f".venvs/{version}", MULTIRUN="1"):
subprocess.run([*uv_run, cmd, *args], **kwargs) # noqa: S603, PLW1510
except subprocess.CalledProcessError as process:
raise _RunError(
returncode=process.returncode,
python_version=version,
cmd=process.cmd,
output=process.output,
stderr=process.stderr,
) from process
def multirun(cmd: str, *args: str, **kwargs: Any) -> None:
"""Run a command for all configured Python versions."""
if PYTHON_VERSIONS:
for version in PYTHON_VERSIONS:
run(version, cmd, *args, **kwargs)
else:
run("default", cmd, *args, **kwargs)
def allrun(cmd: str, *args: str, **kwargs: Any) -> None:
"""Run a command in all virtual environments."""
run("default", cmd, *args, **kwargs)
if PYTHON_VERSIONS:
multirun(cmd, *args, **kwargs)
def clean() -> None:
"""Delete build artifacts and cache files."""
paths_to_clean = ["build", "dist", "htmlcov", "site", ".coverage*", ".pdm-build"]
for path in paths_to_clean:
shutil.rmtree(path, ignore_errors=True)
cache_dirs = {".cache", ".pytest_cache", ".mypy_cache", ".ruff_cache", "__pycache__"}
for dirpath in Path(".").rglob("*/"):
if dirpath.parts[0] not in (".venv", ".venvs") and dirpath.name in cache_dirs:
shutil.rmtree(dirpath, ignore_errors=True)
def vscode() -> None:
"""Configure VSCode to work on this project."""
shutil.copytree("config/vscode", ".vscode", dirs_exist_ok=True)
def main() -> int:
"""Main entry point."""
args = list(sys.argv[1:])
if not args or args[0] == "help":
if len(args) > 1:
run("default", "duty", "--help", args[1])
else:
print(
dedent(
"""
Available commands
help Print this help. Add task name to print help.
setup Setup all virtual environments (install dependencies).
run Run a command in the default virtual environment.
multirun Run a command for all configured Python versions.
allrun Run a command in all virtual environments.
3.x Run a command in the virtual environment for Python 3.x.
clean Delete build artifacts and cache files.
vscode Configure VSCode to work on this project.
""",
),
flush=True,
)
if os.path.exists(".venv"):
print("\nAvailable tasks", flush=True)
run("default", "duty", "--list")
return 0
while args:
cmd = args.pop(0)
if cmd == "run":
if not args:
print("make: run: missing command", file=sys.stderr)
return 1
run("default", *args) # ty: ignore[missing-argument]
return 0
if cmd == "multirun":
if not args:
print("make: run: missing command", file=sys.stderr)
return 1
multirun(*args) # ty: ignore[missing-argument]
return 0
if cmd == "allrun":
if not args:
print("make: run: missing command", file=sys.stderr)
return 1
allrun(*args) # ty: ignore[missing-argument]
return 0
if cmd.startswith("3."):
if not args:
print("make: run: missing command", file=sys.stderr)
return 1
run(cmd, *args) # ty: ignore[missing-argument]
return 0
opts = []
while args and (args[0].startswith("-") or "=" in args[0]):
opts.append(args.pop(0))
if cmd == "clean":
clean()
elif cmd == "setup":
setup()
elif cmd == "vscode":
vscode()
elif cmd == "check":
multirun("duty", "check-quality", "check-types", "check-docs")
run("default", "duty", "check-api")
elif cmd in {"check-quality", "check-docs", "check-types", "test"}:
multirun("duty", cmd, *opts)
else:
run("default", "duty", cmd, *opts)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except _RunError as process:
if process.output:
print(process.output, file=sys.stderr)
if (code := process.returncode) == 139: # noqa: PLR2004
print(
f"✗ (python{process.python_version}) '{' '.join(process.cmd)}' failed with return code {code} (segfault)",
file=sys.stderr,
)
if process.python_version == PYTHON_DEV:
code = 0
sys.exit(code)
| _RunError |
python | boto__boto3 | tests/unit/resources/test_action.py | {
"start": 826,
"end": 4538
} | class ____(BaseTestCase):
def setUp(self):
super().setUp()
self.action_def = {'request': {'operation': 'GetFrobs', 'params': []}}
@property
def action(self):
return Action('test', self.action_def, {})
@mock.patch(
'boto3.resources.action.create_request_parameters', return_value={}
)
def test_service_action_creates_params(self, params_mock):
resource = mock.Mock()
resource.meta = ResourceMeta('test', client=mock.Mock())
action = ServiceAction(self.action)
action(resource, foo=1)
assert params_mock.called
@mock.patch(
'boto3.resources.action.create_request_parameters',
return_value={'bar': 'baz'},
)
def test_service_action_calls_operation(self, params_mock):
resource = mock.Mock()
resource.meta = ResourceMeta('test', client=mock.Mock())
operation = resource.meta.client.get_frobs
operation.return_value = 'response'
action = ServiceAction(self.action)
response = action(resource, foo=1)
operation.assert_called_with(foo=1, bar='baz')
assert response == 'response'
@mock.patch(
'boto3.resources.action.create_request_parameters', return_value={}
)
@mock.patch('boto3.resources.action.RawHandler')
def test_service_action_calls_raw_handler(self, handler_mock, params_mock):
resource = mock.Mock()
resource.meta = ResourceMeta('test', client=mock.Mock())
operation = resource.meta.client.get_frobs
operation.return_value = 'response'
action = ServiceAction(self.action)
handler_mock.return_value.return_value = 'response'
action(resource)
handler_mock.assert_called_with(None)
handler_mock.return_value.assert_called_with(resource, {}, 'response')
@mock.patch(
'boto3.resources.action.create_request_parameters', return_value={}
)
@mock.patch('boto3.resources.action.ResourceHandler')
def test_service_action_calls_resource_handler(
self, handler_mock, params_mock
):
self.action_def['resource'] = {'type': 'Frob', 'path': 'Container'}
resource = mock.Mock()
resource.meta = ResourceMeta('test', client=mock.Mock())
operation = resource.meta.client.get_frobs
operation.return_value = 'response'
factory = mock.Mock()
resource_defs = {}
service_model = mock.Mock()
action_model = self.action
service_context = ServiceContext(
service_name='test',
service_model=service_model,
resource_json_definitions=resource_defs,
service_waiter_model=None,
)
action = ServiceAction(
action_model=action_model,
factory=factory,
service_context=service_context,
)
handler_mock.return_value.return_value = 'response'
action(resource)
handler_mock.assert_called_with(
search_path='Container',
factory=factory,
resource_model=action_model.resource,
service_context=service_context,
operation_name='GetFrobs',
)
def test_service_action_call_positional_argument(self):
def _api_call(*args, **kwargs):
if args:
raise TypeError("get_frobs() only accepts keyword arguments.")
resource = mock.Mock()
resource.meta = ResourceMeta('test', client=mock.Mock())
resource.meta.client.get_frobs = _api_call
action = ServiceAction(self.action)
with pytest.raises(TypeError):
action(resource, 'item1')
| TestServiceActionCall |
python | mahmoud__boltons | boltons/socketutils.py | {
"start": 28808,
"end": 29900
} | class ____(NetstringProtocolError):
"""NetstringMessageTooLong is raised when the size prefix contains a
valid integer, but that integer is larger than the
:class:`NetstringSocket`'s configured *maxsize*.
When this exception is raised, it's recommended to simply close
the connection instead of trying to recover.
"""
def __init__(self, size, maxsize):
msg = ('netstring message length exceeds configured maxsize: %s > %s'
% (size, maxsize))
super().__init__(msg)
"""
attrs worth adding/passing through:
properties: type, proto
For its main functionality, BufferedSocket can wrap any object that
has the following methods:
- gettimeout()
- settimeout()
- recv(size)
- send(data)
The following methods are passed through:
...
"""
# TODO: buffered socket check socket.type == SOCK_STREAM?
# TODO: make recv_until support taking a regex
# TODO: including the delimiter in the recv_until return is not
# necessary, as ConnectionClosed differentiates empty messages
# from socket closes.
| NetstringMessageTooLong |
python | conda__conda | conda/gateways/repodata/__init__.py | {
"start": 22802,
"end": 32723
} | class ____:
"""
Combine RepodataCache and RepoInterface to provide subdir_data.SubdirData()
with what it needs.
Provide a variety of formats since some ``RepoInterface`` have to
``json.loads(...)`` anyway, and some clients don't need the Python data
structure at all.
"""
cache_path_base: Path
channel: Channel
repodata_fn: str
url_w_subdir: str
url_w_credentials: str
repo_interface_cls: Any
def __init__(
self,
cache_path_base: Path,
channel: Channel,
repodata_fn: str,
*,
repo_interface_cls,
):
self.cache_path_base = cache_path_base
self.channel = channel
self.repodata_fn = repodata_fn
self.url_w_subdir = self.channel.url(with_credentials=False) or ""
self.url_w_credentials = self.channel.url(with_credentials=True) or ""
self.repo_interface_cls = repo_interface_cls
def fetch_latest_parsed(self) -> tuple[dict, RepodataState]:
"""
Retrieve parsed latest or latest-cached repodata as a dict; update
cache.
:return: (repodata contents, state including cache headers)
"""
parsed, state = self.fetch_latest()
if isinstance(parsed, str):
try:
return json.loads(parsed), state
except json.JSONDecodeError as e:
e.args = (
f'{e.args[0]}; got "{parsed[:ERROR_SNIPPET_LENGTH]}"',
*e.args[1:],
)
raise
else:
return parsed, state
def fetch_latest_path(self) -> tuple[Path, RepodataState]:
"""
Retrieve latest or latest-cached repodata; update cache.
:return: (pathlib.Path to uncompressed repodata contents, RepodataState)
"""
_, state = self.fetch_latest()
return self.cache_path_json, state
@property
def url_w_repodata_fn(self):
return self.url_w_subdir + "/" + self.repodata_fn
@property
def cache_path_json(self):
return self.repo_cache.cache_path_json
@property
def cache_path_state(self):
"""
Out-of-band etag and other state needed by the RepoInterface.
"""
return self.repo_cache.cache_path_state
@property
def repo_cache(self) -> RepodataCache:
return RepodataCache(self.cache_path_base, self.repodata_fn)
@property
def _repo(self) -> RepoInterface:
"""
Changes as we mutate self.repodata_fn.
"""
return self.repo_interface_cls(
self.url_w_credentials,
repodata_fn=self.repodata_fn,
cache=self.repo_cache,
)
def fetch_latest(self) -> tuple[dict | str, RepodataState]:
"""
Return up-to-date repodata and cache information. Fetch repodata from
remote if cache has expired; return cached data if cache has not
expired; return stale cached data or dummy data if in offline mode.
"""
cache = self.repo_cache
cache.load_state()
# XXX cache_path_json and cache_path_state must exist; just try loading
# it and fall back to this on error?
if not cache.cache_path_json.exists():
log.debug(
"No local cache found for %s at %s",
self.url_w_repodata_fn,
self.cache_path_json,
)
if context.use_index_cache or (
context.offline and not self.url_w_subdir.startswith("file://")
):
log.debug(
"Using cached data for %s at %s forced. Returning empty repodata.",
self.url_w_repodata_fn,
self.cache_path_json,
)
return (
{},
cache.state,
) # XXX basic properties like info, packages, packages.conda? instead of {}?
else:
if context.use_index_cache:
log.debug(
"Using cached repodata for %s at %s because use_cache=True",
self.url_w_repodata_fn,
self.cache_path_json,
)
_internal_state = self.read_cache()
return _internal_state
stale = cache.stale()
if (not stale or context.offline) and not self.url_w_subdir.startswith(
"file://"
):
timeout = cache.timeout()
log.debug(
"Using cached repodata for %s at %s. Timeout in %d sec",
self.url_w_repodata_fn,
self.cache_path_json,
timeout,
)
_internal_state = self.read_cache()
return _internal_state
log.debug(
"Local cache timed out for %s at %s",
self.url_w_repodata_fn,
self.cache_path_json,
)
try:
try:
repo = self._repo
if hasattr(repo, "repodata_parsed"):
raw_repodata = repo.repodata_parsed(cache.state) # type: ignore
else:
raw_repodata = repo.repodata(cache.state) # type: ignore
except RepodataIsEmpty:
if self.repodata_fn != REPODATA_FN:
raise # is UnavailableInvalidChannel subclass
# the surrounding try/except/else will cache "{}"
raw_repodata = None
except RepodataOnDisk:
# used as a sentinel, not the raised exception object
raw_repodata = RepodataOnDisk
except Response304ContentUnchanged:
log.debug(
"304 NOT MODIFIED for '%s'. Updating mtime and loading from disk",
self.url_w_repodata_fn,
)
cache.refresh()
_internal_state = self.read_cache()
return _internal_state
else:
try:
if raw_repodata is RepodataOnDisk:
# this is handled very similar to a 304. Can the cases be merged?
# we may need to read_bytes() and compare a hash to the state, instead.
# XXX use self._repo_cache.load() or replace after passing temp path to jlap
raw_repodata = self.cache_path_json.read_text()
stat = self.cache_path_json.stat()
cache.state["size"] = stat.st_size # type: ignore
mtime_ns = stat.st_mtime_ns
cache.state["mtime_ns"] = mtime_ns # type: ignore
cache.refresh()
elif isinstance(raw_repodata, dict):
# repo implementation cached it, and parsed it
# XXX check size upstream for locking reasons
stat = self.cache_path_json.stat()
cache.state["size"] = stat.st_size
mtime_ns = stat.st_mtime_ns
cache.state["mtime_ns"] = mtime_ns # type: ignore
cache.refresh()
elif isinstance(raw_repodata, (str, type(None))):
# Can we pass this information in state or with a sentinel/special exception?
if raw_repodata is None:
raw_repodata = "{}"
cache.save(raw_repodata)
else: # pragma: no cover
raise RuntimeError(f"Unreachable {raw_repodata}")
except OSError as e:
if e.errno in (errno.EACCES, errno.EPERM, errno.EROFS):
raise NotWritableError(self.cache_path_json, e.errno, caused_by=e)
else:
raise
return raw_repodata, cache.state
def read_cache(self) -> tuple[str, RepodataState]:
"""
Read repodata from disk, without trying to fetch a fresh version.
"""
# pickled data is bad or doesn't exist; load cached json
log.debug(
"Loading raw json for %s at %s",
self.url_w_repodata_fn,
self.cache_path_json,
)
cache = self.repo_cache
try:
raw_repodata_str = cache.load()
return raw_repodata_str, cache.state
except ValueError as e:
# OSError (locked) may happen here
# ValueError: Expecting object: line 11750 column 6 (char 303397)
log.debug("Error for cache path: '%s'\n%r", self.cache_path_json, e)
message = """An error occurred when loading cached repodata. Executing
`conda clean --index-cache` will remove cached repodata files
so they can be downloaded again."""
raise CondaError(message)
def _md5_not_for_security(data):
return hashlib.md5(data, usedforsecurity=False)
def cache_fn_url(url, repodata_fn=REPODATA_FN):
# url must be right-padded with '/' to not invalidate any existing caches
if not url.endswith("/"):
url += "/"
# add the repodata_fn in for uniqueness, but keep it off for standard stuff.
# It would be more sane to add it for everything, but old programs (Navigator)
# are looking for the cache under keys without this.
if repodata_fn != REPODATA_FN:
url += repodata_fn
md5 = _md5_not_for_security(url.encode("utf-8"))
return f"{md5.hexdigest()[:8]}.json"
def get_cache_control_max_age(cache_control_value: str | None):
cache_control_value = cache_control_value or ""
max_age = re.search(r"max-age=(\d+)", cache_control_value)
return int(max_age.groups()[0]) if max_age else 0
def create_cache_dir():
cache_dir = os.path.join(PackageCacheData.first_writable().pkgs_dir, "cache")
mkdir_p_sudo_safe(cache_dir)
return cache_dir
| RepodataFetch |
python | catalyst-team__catalyst | catalyst/contrib/data/dataset.py | {
"start": 218,
"end": 1692
} | class ____(Dataset):
"""General purpose dataset class with several data sources `list_data`."""
def __init__(
self,
list_data: List[Dict],
open_fn: Callable,
dict_transform: Optional[Callable] = None,
):
"""
Args:
list_data: list of dicts, that stores
you data annotations,
(for example path to images, labels, bboxes, etc.)
open_fn: function, that can open your
annotations dict and
transfer it to data, needed by your network
(for example open image by path, or tokenize read string.)
dict_transform: transforms to use on dict.
(for example normalize image, add blur, crop/resize/etc)
"""
self.data = list_data
self.open_fn = open_fn
self.dict_transform = (
dict_transform if dict_transform is not None else lambda x: x
)
def __getitem__(self, index: int) -> Any:
"""Gets element of the dataset.
Args:
index: index of the element in the dataset
Returns:
Single element by index
"""
item = self.data[index]
dict_ = self.open_fn(item)
dict_ = self.dict_transform(dict_)
return dict_
def __len__(self) -> int:
"""
Returns:
int: length of the dataset
"""
return len(self.data)
| ListDataset |
python | lepture__authlib | authlib/oauth2/rfc6749/requests.py | {
"start": 1241,
"end": 1576
} | class ____(OAuth2Payload):
def __init__(self, payload):
self._data = payload
self._datalist = {key: [value] for key, value in payload.items()}
@property
def data(self):
return self._data
@property
def datalist(self) -> defaultdict[str, list]:
return self._datalist
| BasicOAuth2Payload |
python | realpython__materials | name-main-idiom/adder.py | {
"start": 69,
"end": 234
} | class ____(unittest.TestCase):
def test_add_adds_two_numbers(self):
self.assertEqual(add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
| TestAdder |
python | realpython__materials | python-guitar-synthesizer/source_code_step_2/src/digitar/synthesis.py | {
"start": 314,
"end": 1282
} | class ____:
burst_generator: BurstGenerator = WhiteNoise()
sampling_rate: int = AUDIO_CD_SAMPLING_RATE
def vibrate(
self, frequency: Hertz, duration: Time, damping: float = 0.5
) -> np.ndarray:
assert 0 < damping <= 0.5
def feedback_loop() -> Iterator[float]:
buffer = self.burst_generator(
num_samples=round(self.sampling_rate / frequency),
sampling_rate=self.sampling_rate,
)
for i in cycle(range(buffer.size)):
yield (current_sample := buffer[i])
next_sample = buffer[(i + 1) % buffer.size]
buffer[i] = (current_sample + next_sample) * damping
return normalize(
remove_dc(
np.fromiter(
feedback_loop(),
np.float64,
duration.get_num_samples(self.sampling_rate),
)
)
)
| Synthesizer |
python | bokeh__bokeh | src/bokeh/application/application.py | {
"start": 8840,
"end": 9376
} | class ____(metaclass=ABCMeta):
''' A harness for server-specific information and tasks related to
collections of Bokeh sessions.
*This base class is probably not of interest to general users.*
'''
# Properties --------------------------------------------------------------
@property
@abstractmethod
def sessions(self) -> list[ServerSession]:
''' ``SessionContext`` instances belonging to this application.
*Subclasses must implement this method.*
'''
pass
| ServerContext |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 13221,
"end": 13646
} | class ____:
"""Test sk_SK currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.sk_SK import Provider as SkSkCurrencyProvider
cls.provider = SkSkCurrencyProvider
def test_pricetag(self, faker, num_samples):
for _ in range(num_samples):
pricetag = faker.pricetag()
assert isinstance(pricetag, str)
| TestSkSk |
python | openai__openai-python | src/openai/types/beta/realtime/response_create_event.py | {
"start": 885,
"end": 4427
} | class ____(BaseModel):
conversation: Union[str, Literal["auto", "none"], None] = None
"""Controls which conversation the response is added to.
Currently supports `auto` and `none`, with `auto` as the default value. The
`auto` value means that the contents of the response will be added to the
default conversation. Set this to `none` to create an out-of-band response which
will not add items to default conversation.
"""
input: Optional[List[ConversationItemWithReference]] = None
"""Input items to include in the prompt for the model.
Using this field creates a new context for this Response instead of using the
default conversation. An empty array `[]` will clear the context for this
Response. Note that this can include references to items from the default
conversation.
"""
instructions: Optional[str] = None
"""The default system instructions (i.e.
system message) prepended to model calls. This field allows the client to guide
the model on desired responses. The model can be instructed on response content
and format, (e.g. "be extremely succinct", "act friendly", "here are examples of
good responses") and on audio behavior (e.g. "talk quickly", "inject emotion
into your voice", "laugh frequently"). The instructions are not guaranteed to be
followed by the model, but they provide guidance to the model on the desired
behavior.
Note that the server sets default instructions which will be used if this field
is not set and are visible in the `session.created` event at the start of the
session.
"""
max_response_output_tokens: Union[int, Literal["inf"], None] = None
"""
Maximum number of output tokens for a single assistant response, inclusive of
tool calls. Provide an integer between 1 and 4096 to limit output tokens, or
`inf` for the maximum available tokens for a given model. Defaults to `inf`.
"""
metadata: Optional[Metadata] = None
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
"""
modalities: Optional[List[Literal["text", "audio"]]] = None
"""The set of modalities the model can respond with.
To disable audio, set this to ["text"].
"""
output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None
"""The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`."""
temperature: Optional[float] = None
"""Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8."""
tool_choice: Optional[str] = None
"""How the model chooses tools.
Options are `auto`, `none`, `required`, or specify a function, like
`{"type": "function", "function": {"name": "my_function"}}`.
"""
tools: Optional[List[ResponseTool]] = None
"""Tools (functions) available to the model."""
voice: Union[str, Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"], None] = None
"""The voice the model uses to respond.
Voice cannot be changed during the session once the model has responded with
audio at least once. Current voice options are `alloy`, `ash`, `ballad`,
`coral`, `echo`, `sage`, `shimmer`, and `verse`.
"""
| Response |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/forms.py | {
"start": 169,
"end": 1553
} | class ____(forms.Form):
"""Helper form that wraps a form to validate its contents on post.
class PanelForm(forms.Form):
# fields
On render:
form = SignedDataForm(initial=PanelForm(initial=data).initial)
On POST:
signed_form = SignedDataForm(request.POST)
if signed_form.is_valid():
panel_form = PanelForm(signed_form.verified_data)
if panel_form.is_valid():
# Success
"""
salt = "django_debug_toolbar"
signed = forms.CharField(required=True, widget=forms.HiddenInput)
def __init__(self, *args, **kwargs):
initial = kwargs.pop("initial", None)
if initial:
initial = {"signed": self.sign(initial)}
super().__init__(*args, initial=initial, **kwargs)
def clean_signed(self):
try:
verified = json.loads(
signing.Signer(salt=self.salt).unsign(self.cleaned_data["signed"])
)
return verified
except signing.BadSignature as exc:
raise ValidationError("Bad signature") from exc
def verified_data(self):
return self.is_valid() and self.cleaned_data["signed"]
@classmethod
def sign(cls, data):
return signing.Signer(salt=cls.salt).sign(
json.dumps({key: force_str(value) for key, value in data.items()})
)
| SignedDataForm |
python | django-compressor__django-compressor | compressor/filters/base.py | {
"start": 744,
"end": 1816
} | class ____:
"""
A base class for filters that does nothing.
Subclasses should implement `input` and/or `output` methods which must
return a string or raise a NotImplementedError.
"""
# Since precompiling moves files around, it breaks url()
# statements in css files. therefore we run the absolute and relative filter
# on precompiled css files even if compression is disabled.
# This flag allows those filters to do so.
run_with_compression_disabled = False
def __init__(
self,
content,
attrs=None,
filter_type=None,
filename=None,
verbose=0,
charset=None,
**kwargs
):
self.type = filter_type or getattr(self, "type", None)
self.content = content
self.verbose = verbose or settings.COMPRESS_VERBOSE
self.logger = logger
self.filename = filename
self.charset = charset
def input(self, **kwargs):
raise NotImplementedError
def output(self, **kwargs):
raise NotImplementedError
| FilterBase |
python | joke2k__faker | faker/providers/address/en_US/__init__.py | {
"start": 119,
"end": 13688
} | class ____(AddressProvider):
city_prefixes = ("North", "East", "West", "South", "New", "Lake", "Port")
city_suffixes = (
"town",
"ton",
"land",
"ville",
"berg",
"burgh",
"borough",
"bury",
"view",
"port",
"mouth",
"stad",
"furt",
"chester",
"mouth",
"fort",
"haven",
"side",
"shire",
)
building_number_formats = ("#####", "####", "###")
street_suffixes = (
"Alley",
"Avenue",
"Branch",
"Bridge",
"Brook",
"Brooks",
"Burg",
"Burgs",
"Bypass",
"Camp",
"Canyon",
"Cape",
"Causeway",
"Center",
"Centers",
"Circle",
"Circles",
"Cliff",
"Cliffs",
"Club",
"Common",
"Corner",
"Corners",
"Course",
"Court",
"Courts",
"Cove",
"Coves",
"Creek",
"Crescent",
"Crest",
"Crossing",
"Crossroad",
"Curve",
"Dale",
"Dam",
"Divide",
"Drive",
"Drive",
"Drives",
"Estate",
"Estates",
"Expressway",
"Extension",
"Extensions",
"Fall",
"Falls",
"Ferry",
"Field",
"Fields",
"Flat",
"Flats",
"Ford",
"Fords",
"Forest",
"Forge",
"Forges",
"Fork",
"Forks",
"Fort",
"Freeway",
"Garden",
"Gardens",
"Gateway",
"Glen",
"Glens",
"Green",
"Greens",
"Grove",
"Groves",
"Harbor",
"Harbors",
"Haven",
"Heights",
"Highway",
"Hill",
"Hills",
"Hollow",
"Inlet",
"Inlet",
"Island",
"Island",
"Islands",
"Islands",
"Isle",
"Isle",
"Junction",
"Junctions",
"Key",
"Keys",
"Knoll",
"Knolls",
"Lake",
"Lakes",
"Land",
"Landing",
"Lane",
"Light",
"Lights",
"Loaf",
"Lock",
"Locks",
"Locks",
"Lodge",
"Lodge",
"Loop",
"Mall",
"Manor",
"Manors",
"Meadow",
"Meadows",
"Mews",
"Mill",
"Mills",
"Mission",
"Mission",
"Motorway",
"Mount",
"Mountain",
"Mountain",
"Mountains",
"Mountains",
"Neck",
"Orchard",
"Oval",
"Overpass",
"Park",
"Parks",
"Parkway",
"Parkways",
"Pass",
"Passage",
"Path",
"Pike",
"Pine",
"Pines",
"Place",
"Plain",
"Plains",
"Plains",
"Plaza",
"Plaza",
"Point",
"Points",
"Port",
"Port",
"Ports",
"Ports",
"Prairie",
"Prairie",
"Radial",
"Ramp",
"Ranch",
"Rapid",
"Rapids",
"Rest",
"Ridge",
"Ridges",
"River",
"Road",
"Road",
"Roads",
"Roads",
"Route",
"Row",
"Rue",
"Run",
"Shoal",
"Shoals",
"Shore",
"Shores",
"Skyway",
"Spring",
"Springs",
"Springs",
"Spur",
"Spurs",
"Square",
"Square",
"Squares",
"Squares",
"Station",
"Station",
"Stravenue",
"Stravenue",
"Stream",
"Stream",
"Street",
"Street",
"Streets",
"Summit",
"Summit",
"Terrace",
"Throughway",
"Trace",
"Track",
"Trafficway",
"Trail",
"Trail",
"Tunnel",
"Tunnel",
"Turnpike",
"Turnpike",
"Underpass",
"Union",
"Unions",
"Valley",
"Valleys",
"Via",
"Viaduct",
"View",
"Views",
"Village",
"Village",
"Villages",
"Ville",
"Vista",
"Vista",
"Walk",
"Walks",
"Wall",
"Way",
"Ways",
"Well",
"Wells",
)
postcode_formats = ("#####", "#####-####")
states = (
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming",
)
states_abbr = (
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"DC",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY",
)
states_postcode = {
"AL": (35004, 36925),
"AK": (99501, 99950),
"AZ": (85001, 86556),
"AR": (71601, 72959),
"CA": (90001, 96162),
"CO": (80001, 81658),
"CT": (6001, 6389),
"DE": (19701, 19980),
"DC": (20001, 20039),
"FL": (32004, 34997),
"GA": (30001, 31999),
"HI": (96701, 96898),
"ID": (83201, 83876),
"IL": (60001, 62999),
"IN": (46001, 47997),
"IA": (50001, 52809),
"KS": (66002, 67954),
"KY": (40003, 42788),
"LA": (70001, 71232),
"ME": (3901, 4992),
"MD": (20812, 21930),
"MA": (1001, 2791),
"MI": (48001, 49971),
"MN": (55001, 56763),
"MS": (38601, 39776),
"MO": (63001, 65899),
"MT": (59001, 59937),
"NE": (68001, 68118),
"NV": (88901, 89883),
"NH": (3031, 3897),
"NJ": (7001, 8989),
"NM": (87001, 88441),
"NY": (10001, 14905),
"NC": (27006, 28909),
"ND": (58001, 58856),
"OH": (43001, 45999),
"OK": (73001, 73199),
"OR": (97001, 97920),
"PA": (15001, 19640),
"RI": (2801, 2940),
"SC": (29001, 29948),
"SD": (57001, 57799),
"TN": (37010, 38589),
"TX": (75503, 79999),
"UT": (84001, 84784),
"VT": (5001, 5495),
"VA": (22001, 24658),
"WA": (98001, 99403),
"WV": (24701, 26886),
"WI": (53001, 54990),
"WY": (82001, 83128),
# Territories & freely-associated states
# incomplete ranges with accurate subsets - https://www.geonames.org/postalcode-search.html
"AS": (96799, 96799),
"FM": (96941, 96944),
"GU": (96910, 96932),
"MH": (96960, 96970),
"MP": (96950, 96952),
"PW": (96940, 96940),
"PR": (600, 799),
"VI": (801, 805),
}
territories_abbr = (
"AS",
"GU",
"MP",
"PR",
"VI",
)
# Freely-associated states (sovereign states; members of COFA)
# https://en.wikipedia.org/wiki/Compact_of_Free_Association
freely_associated_states_abbr = (
"FM",
"MH",
"PW",
)
known_usps_abbr = states_abbr + territories_abbr + freely_associated_states_abbr
military_state_abbr = ("AE", "AA", "AP")
military_ship_prefix = ("USS", "USNS", "USNV", "USCGC")
military_apo_format = "PSC ####, Box ####"
military_dpo_format = "Unit #### Box ####"
city_formats = (
"{{city_prefix}} {{first_name}}{{city_suffix}}",
"{{city_prefix}} {{first_name}}",
"{{first_name}}{{city_suffix}}",
"{{last_name}}{{city_suffix}}",
)
street_name_formats = (
"{{first_name}} {{street_suffix}}",
"{{last_name}} {{street_suffix}}",
)
street_address_formats = (
"{{building_number}} {{street_name}}",
"{{building_number}} {{street_name}} {{secondary_address}}",
)
address_formats = OrderedDict(
(
("{{street_address}}\n{{city}}, {{state_abbr}} {{postcode}}", 25.0),
# military address formatting.
("{{military_apo}}\nAPO {{military_state}} {{postcode}}", 1.0),
(
"{{military_ship}} {{last_name}}\nFPO {{military_state}} {{postcode}}",
1.0,
),
("{{military_dpo}}\nDPO {{military_state}} {{postcode}}", 1.0),
)
)
secondary_address_formats = ("Apt. ###", "Suite ###")
def city_prefix(self) -> str:
return self.random_element(self.city_prefixes)
def secondary_address(self) -> str:
return self.numerify(self.random_element(self.secondary_address_formats))
def administrative_unit(self) -> str:
return self.random_element(self.states)
state = administrative_unit
def state_abbr(
self,
include_territories: bool = True,
include_freely_associated_states: bool = True,
) -> str:
"""
:returns: A random two-letter USPS postal code
By default, the resulting code may abbreviate any of the fifty states,
five US territories, or three freely-associating sovereign states.
:param include_territories: If True, territories will be included.
If False, US territories will be excluded.
:param include_freely_associated_states: If True, freely-associated states will be included.
If False, sovereign states in free association with the US will be excluded.
"""
abbreviations: Tuple[str, ...] = self.states_abbr
if include_territories:
abbreviations += self.territories_abbr
if include_freely_associated_states:
abbreviations += self.freely_associated_states_abbr
return self.random_element(abbreviations)
def postcode(self) -> str:
return "%05d" % self.generator.random.randint(501, 99950)
def zipcode_plus4(self) -> str:
return "%s-%04d" % (self.zipcode(), self.generator.random.randint(1, 9999))
def postcode_in_state(self, state_abbr: Optional[str] = None) -> str:
"""
:returns: A random postcode within the provided state abbreviation
:param state_abbr: A state abbreviation
"""
if state_abbr is None:
state_abbr = self.random_element(self.states_abbr)
if state_abbr in self.known_usps_abbr:
postcode = "%d" % (
self.generator.random.randint(
self.states_postcode[state_abbr][0],
self.states_postcode[state_abbr][1],
)
)
# zero left pad up until desired length (some have length 3 or 4)
target_postcode_len = 5
current_postcode_len = len(postcode)
if current_postcode_len < target_postcode_len:
pad = target_postcode_len - current_postcode_len
postcode = f"{'0'*pad}{postcode}"
return postcode
else:
raise Exception("State Abbreviation not found in list")
def military_ship(self) -> str:
"""
:example: 'USS'
"""
return self.random_element(self.military_ship_prefix)
def military_state(self) -> str:
"""
:example: 'APO'
"""
return self.random_element(self.military_state_abbr)
def military_apo(self) -> str:
"""
:example: 'PSC 5394 Box 3492
"""
return self.numerify(self.military_apo_format)
def military_dpo(self) -> str:
"""
:example: 'Unit 3333 Box 9342'
"""
return self.numerify(self.military_dpo_format)
# Aliases
def zipcode(self) -> str:
return self.postcode()
def zipcode_in_state(self, state_abbr: Optional[str] = None) -> str:
return self.postcode_in_state(state_abbr)
def postalcode(self) -> str:
return self.postcode()
def postalcode_in_state(self, state_abbr: Optional[str] = None) -> str:
return self.postcode_in_state(state_abbr)
def postalcode_plus4(self) -> str:
return self.zipcode_plus4()
| Provider |
python | davidhalter__jedi | test/test_api/test_call_signatures.py | {
"start": 747,
"end": 16500
} | class ____(TestCase):
@pytest.fixture(autouse=True)
def init(self, Script):
self.Script = Script
def _run_simple(self, source, name, index=0, column=None, line=1):
assert_signature(self.Script, source, name, index, line, column)
def test_simple(self):
run = self._run_simple
# simple
s1 = "tuple(a, bool("
run(s1, 'tuple', 0, 6)
run(s1, 'tuple', None, 8)
run(s1, 'tuple', None, 9)
run(s1, 'bool', 0, 14)
s2 = "abs(), "
run(s2, 'abs', 0, 4)
run(s2, None, column=5)
run(s2, None)
s3 = "abs()."
run(s3, None, column=5)
run(s3, None)
def test_more_complicated(self):
run = self._run_simple
s4 = 'abs(bool(), , set,'
run(s4, None, column=3)
run(s4, 'abs', 0, 4)
run(s4, 'bool', 0, 9)
run(s4, 'abs', 0, 10)
run(s4, 'abs', None, 11)
s5 = "tuple(1,\nif 2:\n def a():"
run(s5, 'tuple', 0, 6)
run(s5, 'tuple', None, 8)
s6 = "bool().__eq__("
run(s6, '__eq__', 0)
run(s6, 'bool', 0, 5)
s7 = "str().upper().center("
s8 = "bool(int[abs("
run(s7, 'center', 0)
run(s8, 'abs', 0)
run(s8, 'bool', 0, 10)
run("import time; abc = time; abc.sleep(", 'sleep', 0)
def test_issue_57(self):
# jedi #57
s = "def func(alpha, beta): pass\n" \
"func(alpha='101',"
self._run_simple(s, 'func', 0, column=13, line=2)
def test_for(self):
# jedi-vim #11
self._run_simple("for tuple(", 'tuple', 0)
self._run_simple("for s in tuple(", 'tuple', 0)
def test_with(Script):
# jedi-vim #9
sigs = Script("with open(").get_signatures()
assert sigs
assert all(sig.name == 'open' for sig in sigs)
def test_get_signatures_empty_parentheses_pre_space(Script):
s = dedent("""\
def f(a, b):
pass
f( )""")
assert_signature(Script, s, 'f', 0, line=3, column=3)
def test_multiple_signatures(Script):
s = dedent("""\
if x:
def f(a, b):
pass
else:
def f(a, b):
pass
f(""")
assert len(Script(s).get_signatures()) == 2
def test_get_signatures_whitespace(Script):
# note: trailing space after 'abs'
s = 'abs( \ndef x():\n pass\n'
assert_signature(Script, s, 'abs', 0, line=1, column=5)
def test_decorator_in_class(Script):
"""
There's still an implicit param, with a decorator.
Github issue #319.
"""
s = dedent("""\
def static(func):
def wrapped(obj, *args):
return f(type(obj), *args)
return wrapped
class C(object):
@static
def test(cls):
return 10
C().test(""")
signatures = Script(s).get_signatures()
assert len(signatures) == 1
x = [p.description for p in signatures[0].params]
assert x == ['param *args']
def test_additional_brackets(Script):
assert_signature(Script, 'abs((', 'abs', 0)
def test_unterminated_strings(Script):
assert_signature(Script, 'abs(";', 'abs', 0)
def test_whitespace_before_bracket(Script):
assert_signature(Script, 'abs (', 'abs', 0)
assert_signature(Script, 'abs (";', 'abs', 0)
assert_signature(Script, 'abs\n(', None)
def test_brackets_in_string_literals(Script):
assert_signature(Script, 'abs (" (', 'abs', 0)
assert_signature(Script, 'abs (" )', 'abs', 0)
def test_function_definitions_should_break(Script):
"""
Function definitions (and other tokens that cannot exist within call
signatures) should break and not be able to return a signature.
"""
assert_signature(Script, 'abs(\ndef x', 'abs', 0)
assert not Script('abs(\ndef x(): pass').get_signatures()
def test_flow_call(Script):
assert not Script('if (1').get_signatures()
def test_chained_calls(Script):
source = dedent('''
class B():
def test2(self, arg):
pass
class A():
def test1(self):
return B()
A().test1().test2(''')
assert_signature(Script, source, 'test2', 0)
def test_return(Script):
source = dedent('''
def foo():
return '.'.join()''')
assert_signature(Script, source, 'join', 0, column=len(" return '.'.join("))
def test_find_signature_on_module(Script):
"""github issue #240"""
s = 'import datetime; datetime('
# just don't throw an exception (if numpy doesn't exist, just ignore it)
assert Script(s).get_signatures() == []
def test_complex(Script, environment):
s = """
def abc(a,b):
pass
def a(self):
abc(
if 1:
pass
"""
assert_signature(Script, s, 'abc', 0, line=6, column=20)
s = """
import re
def huhu(it):
re.compile(
return it * 2
"""
sig1, sig2 = sorted(Script(s).get_signatures(line=4, column=27), key=lambda s: s.line)
assert sig1.name == sig2.name == 'compile'
assert sig1.index == sig2.index == 0
func1, = sig1._name.infer()
func2, = sig2._name.infer()
# Do these checks just for Python 3, I'm too lazy to deal with this
# legacy stuff. ~ dave.
assert get_signature(func1.tree_node) \
== 'compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]'
assert get_signature(func2.tree_node) \
== 'compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) ->\nPattern[AnyStr]'
# jedi-vim #70
s = """def foo("""
assert Script(s).get_signatures() == []
# jedi-vim #116
s = """import itertools; test = getattr(itertools, 'chain'); test("""
assert_signature(Script, s, 'chain', 0)
def _params(Script, source, line=None, column=None):
signatures = Script(source).get_signatures(line, column)
assert len(signatures) == 1
return signatures[0].params
def test_int_params(Script):
sig1, sig2 = Script('int(').get_signatures()
# int is defined as: `int(x[, base])`
assert len(sig1.params) == 1
assert sig1.params[0].name == 'x'
assert len(sig2.params) == 2
assert sig2.params[0].name == 'x'
assert sig2.params[1].name == 'base'
def test_pow_params(Script):
# See Github #1357.
for sig in Script('pow(').get_signatures():
param_names = [p.name for p in sig.params]
assert param_names in (['base', 'exp'], ['base', 'exp', 'mod'])
def test_param_name(Script):
sigs = Script('open(something,').get_signatures()
for sig in sigs:
# All of the signatures (in Python the function is overloaded),
# contain the same param names.
assert sig.params[0].name in ['file', 'name']
assert sig.params[1].name == 'mode'
assert sig.params[2].name == 'buffering'
def test_builtins(Script):
"""
The self keyword should be visible even for builtins, if not
instantiated.
"""
p = _params(Script, 'str.endswith(')
assert p[0].name == 'self'
assert p[1].name == 'suffix'
p = _params(Script, 'str().endswith(')
assert p[0].name == 'suffix'
def test_signature_is_definition(Script):
"""
Through inheritance, a signature is a sub class of Name.
Check if the attributes match.
"""
s = """class Spam(): pass\nSpam"""
signature = Script(s + '(').get_signatures()[0]
definition = Script(s + '(').infer(column=0)[0]
signature.line == 1
signature.column == 6
# Now compare all the attributes that a Signature must also have.
for attr_name in dir(definition):
dont_scan = ['defined_names', 'parent', 'goto_assignments', 'infer',
'params', 'get_signatures', 'execute', 'goto',
'desc_with_module']
if attr_name.startswith('_') or attr_name in dont_scan:
continue
attribute = getattr(definition, attr_name)
signature_attribute = getattr(signature, attr_name)
if inspect.ismethod(attribute):
assert attribute() == signature_attribute()
else:
assert attribute == signature_attribute
def test_no_signature(Script):
# str doesn't have a __call__ method
assert Script('str()(').get_signatures() == []
s = dedent("""\
class X():
pass
X()(""")
assert Script(s).get_signatures() == []
assert len(Script(s).get_signatures(column=2)) == 1
assert Script('').get_signatures() == []
def test_dict_literal_in_incomplete_call(Script):
source = """\
import json
def foo():
json.loads(
json.load.return_value = {'foo': [],
'bar': True}
c = Foo()
"""
script = Script(dedent(source))
assert script.get_signatures(line=4, column=15)
def test_completion_interference(Script):
"""Seems to cause problems, see also #396."""
cache.parser_cache.pop(None, None)
assert Script('open(').get_signatures()
# complete something usual, before doing the same get_signatures again.
assert Script('from datetime import ').complete()
assert Script('open(').get_signatures()
def test_keyword_argument_index(Script, environment):
def get(source, column=None):
return Script(source).get_signatures(column=column)[0]
assert get('sorted([], key=a').index == 1
assert get('sorted([], key=').index == 1
assert get('sorted([], no_key=a').index is None
kw_func = 'def foo(a, b): pass\nfoo(b=3, a=4)'
assert get(kw_func, column=len('foo(b')).index == 0
assert get(kw_func, column=len('foo(b=')).index == 1
assert get(kw_func, column=len('foo(b=3, a=')).index == 0
kw_func_simple = 'def foo(a, b): pass\nfoo(b=4)'
assert get(kw_func_simple, column=len('foo(b')).index == 0
assert get(kw_func_simple, column=len('foo(b=')).index == 1
args_func = 'def foo(*kwargs): pass\n'
assert get(args_func + 'foo(a').index == 0
assert get(args_func + 'foo(a, b').index == 0
kwargs_func = 'def foo(**kwargs): pass\n'
assert get(kwargs_func + 'foo(a=2').index == 0
assert get(kwargs_func + 'foo(a=2, b=2').index == 0
both = 'def foo(*args, **kwargs): pass\n'
assert get(both + 'foo(a=2').index == 1
assert get(both + 'foo(a=2, b=2').index == 1
assert get(both + 'foo(a=2, b=2)', column=len('foo(b=2, a=2')).index == 1
assert get(both + 'foo(a, b, c').index == 0
code1 = 'def f(u, /, v=3, *, abc, abd, xyz): pass'
code2 = 'def g(u, /, v=3, *, abc, abd, xyz, **kwargs): pass'
code3 = 'def h(u, /, v, *args, x=1, y): pass'
code4 = 'def i(u, /, v, *args, x=1, y, **kwargs): pass'
_calls = [
# No *args, **kwargs
(code1, 'f(', 0),
(code1, 'f(a', 0),
(code1, 'f(a,', 1),
(code1, 'f(a,b', 1),
(code1, 'f(a,b,', 2),
(code1, 'f(a,b,c', None),
(code1, 'f(a,b,a', 2),
(code1, 'f(a,b,a=', None),
(code1, 'f(a,b,abc', 2),
(code1, 'f(a,b,abc=(', 2),
(code1, 'f(a,b,abc=(f,1,2,3', 2),
(code1, 'f(a,b,abd', 3),
(code1, 'f(a,b,x', 4),
(code1, 'f(a,b,xy', 4),
(code1, 'f(a,b,xyz=', 4),
(code1, 'f(a,b,xy=', None),
(code1, 'f(u=', (0, None)),
(code1, 'f(v=', 1),
# **kwargs
(code2, 'g(a,b,a', 2),
(code2, 'g(a,b,abc', 2),
(code2, 'g(a,b,abd', 3),
(code2, 'g(a,b,arr', 5),
(code2, 'g(a,b,xy', 4),
(code2, 'g(a,b,xyz=', 4),
(code2, 'g(a,b,xy=', 5),
(code2, 'g(a,b,abc=1,abd=4,', 4),
(code2, 'g(a,b,abc=1,xyz=3,abd=4,', 5),
(code2, 'g(a,b,abc=1,abd=4,lala', 5),
(code2, 'g(a,b,abc=1,abd=4,lala=', 5),
(code2, 'g(a,b,abc=1,abd=4,abd=', 5),
(code2, 'g(a,b,kw', 5),
(code2, 'g(a,b,kwargs=', 5),
(code2, 'g(u=', (0, 5)),
(code2, 'g(v=', 1),
# *args
(code3, 'h(a,b,c', 2),
(code3, 'h(a,b,c,', 2),
(code3, 'h(a,b,c,d', 2),
(code3, 'h(a,b,c,d[', 2),
(code3, 'h(a,b,c,(3,', 2),
(code3, 'h(a,b,c,(3,)', 2),
(code3, 'h(a,b,args=', None),
(code3, 'h(u,v=', 1),
(code3, 'h(u=', (0, None)),
(code3, 'h(u,*xxx', 1),
(code3, 'h(u,*xxx,*yyy', 1),
(code3, 'h(u,*[]', 1),
(code3, 'h(u,*', 1),
(code3, 'h(u,*, *', 1),
(code3, 'h(u,1,**', 3),
(code3, 'h(u,**y', 1),
(code3, 'h(u,x=2,**', 1),
(code3, 'h(u,x=2,**y', 1),
(code3, 'h(u,v=2,**y', 3),
(code3, 'h(u,x=2,**vv', 1),
# *args, **kwargs
(code4, 'i(a,b,c,d', 2),
(code4, 'i(a,b,c,d,e', 2),
(code4, 'i(a,b,c,d,e=', 5),
(code4, 'i(a,b,c,d,e=3', 5),
(code4, 'i(a,b,c,d=,x=', 3),
(code4, 'i(a,b,c,d=5,x=4', 3),
(code4, 'i(a,b,c,d=5,x=4,y', 4),
(code4, 'i(a,b,c,d=5,x=4,y=3,', 5),
(code4, 'i(a,b,c,d=5,y=4,x=3,', 5),
(code4, 'i(a,b,c,d=4,', 3),
(code4, 'i(a,b,c,x=1,d=,', 4),
# Error nodes
(code4, 'i(1, [a,b', 1),
(code4, 'i(1, [a,b=,', 2),
(code4, 'i(1, [a?b,', 2),
(code4, 'i(1, [a?b,*', 2),
(code4, 'i(?b,*r,c', 1),
(code4, 'i(?*', 0),
(code4, 'i(?**', (0, 1)),
# Random
(code4, 'i(()', 0),
(code4, 'i((),', 1),
(code4, 'i([(),', 0),
(code4, 'i([(,', 1),
(code4, 'i(x,()', 1),
]
@pytest.mark.parametrize('ending', ['', ')'])
@pytest.mark.parametrize('code, call, expected_index', _calls)
def test_signature_index(Script, environment, code, call, expected_index, ending):
if isinstance(expected_index, tuple):
expected_index = expected_index[environment.version_info > (3, 8)]
if environment.version_info < (3, 8):
code = code.replace('/,', '')
sig, = Script(code + '\n' + call + ending).get_signatures(column=len(call))
index = sig.index
assert expected_index == index
@pytest.mark.parametrize('code', ['foo', 'instance.foo'])
def test_arg_defaults(Script, environment, code):
def foo(arg="bla", arg1=1):
pass
class Klass:
def foo(self, arg="bla", arg1=1):
pass
instance = Klass()
src = dedent("""
def foo2(arg="bla", arg1=1):
pass
class Klass2:
def foo2(self, arg="bla", arg1=1):
pass
instance = Klass2()
""")
executed_locals = dict()
exec(src, None, executed_locals)
locals_ = locals()
def iter_scripts():
yield Interpreter(code + '(', namespaces=[locals_])
yield Script(src + code + "2(")
yield Interpreter(code + '2(', namespaces=[executed_locals])
for script in iter_scripts():
signatures = script.get_signatures()
assert signatures[0].params[0].description in ('param arg="bla"', "param arg='bla'")
assert signatures[0].params[1].description == 'param arg1=1'
def test_bracket_start(Script):
def bracket_start(src):
signatures = Script(src).get_signatures()
assert len(signatures) == 1
return signatures[0].bracket_start
assert bracket_start('abs(') == (1, 3)
def test_different_caller(Script):
"""
It's possible to not use names, but another function result or an array
index and then get the signature of it.
"""
assert_signature(Script, '[abs][0](', 'abs', 0)
assert_signature(Script, '[abs][0]()', 'abs', 0, column=len('[abs][0]('))
assert_signature(Script, '(abs)(', 'abs', 0)
assert_signature(Script, '(abs)()', 'abs', 0, column=len('(abs)('))
def test_in_function(Script):
code = dedent('''\
class X():
@property
def func(''')
assert not Script(code).get_signatures()
def test_lambda_params(Script):
code = dedent('''\
my_lambda = lambda x: x+1
my_lambda(1)''')
sig, = Script(code).get_signatures(column=11)
assert sig.index == 0
assert sig.name == '<lambda>'
assert [p.name for p in sig.params] == ['x']
CLASS_CODE = dedent('''\
| TestSignatures |
python | kamyu104__LeetCode-Solutions | Python/find-number-of-coins-to-place-in-tree-nodes.py | {
"start": 1638,
"end": 2442
} | class ____(object):
def placedCoins(self, edges, cost):
"""
:type edges: List[List[int]]
:type cost: List[int]
:rtype: List[int]
"""
def dfs(u, p):
arr = [cost[u]]
for v in adj[u]:
if v == p:
continue
arr.extend(dfs(v, u))
arr.sort()
if len(arr) > 5:
arr = arr[:2]+arr[-3:]
result[u] = 1 if len(arr) < 3 else max(arr[0]*arr[1]*arr[-1], arr[-3]*arr[-2]*arr[-1], 0)
return arr
adj = [[] for _ in xrange(len(cost))]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
result = [0]*len(cost)
dfs(0, -1)
return result
| Solution2 |
python | django-haystack__django-haystack | test_haystack/test_indexes.py | {
"start": 23249,
"end": 23906
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True)
author = indexes.CharField(model_attr="author")
pub_date = indexes.DateTimeField(model_attr="pub_date")
average_delay = indexes.FloatField(null=True)
def get_model(self):
return AnotherMockModel
def prepare(self, obj):
self.prepared_data = super().prepare(obj)
if isinstance(obj, AThirdMockModel):
self.prepared_data["average_delay"] = obj.average_delay
return self.prepared_data
def index_queryset(self, using=None):
return self.get_model().objects.all()
| PolymorphicModelSearchIndex |
python | sympy__sympy | sympy/stats/drv_types.py | {
"start": 10466,
"end": 12393
} | class ____(SingleDiscreteDistribution):
_argnames = ('r', 'p')
set = S.Naturals0
@staticmethod
def check(r, p):
_value_check(r > 0, 'r should be positive')
_value_check((p > 0, p < 1), 'p should be between 0 and 1')
def pdf(self, k):
r = self.r
p = self.p
return binomial(k + r - 1, k) * (1 - p)**k * p**r
def _characteristic_function(self, t):
r = self.r
p = self.p
return (p / (1 - (1 - p) * exp(I*t)))**r
def _moment_generating_function(self, t):
r = self.r
p = self.p
return (p / (1 - (1 - p) * exp(t)))**r
def NegativeBinomial(name, r, p):
r"""
Create a discrete random variable with a Negative Binomial distribution.
Explanation
===========
The density of the Negative Binomial distribution is given by
.. math::
f(k) := \binom{k + r - 1}{k} (1 - p)^k p^r
Parameters
==========
r : A positive value
Number of successes until the experiment is stopped.
p : A value between 0 and 1
Probability of success.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import NegativeBinomial, density, E, variance
>>> from sympy import Symbol, S
>>> r = 5
>>> p = S.One / 3
>>> z = Symbol("z")
>>> X = NegativeBinomial("x", r, p)
>>> density(X)(z)
(2/3)**z*binomial(z + 4, z)/243
>>> E(X)
10
>>> variance(X)
30
References
==========
.. [1] https://en.wikipedia.org/wiki/Negative_binomial_distribution
.. [2] https://mathworld.wolfram.com/NegativeBinomialDistribution.html
"""
return rv(name, NegativeBinomialDistribution, r, p)
#-------------------------------------------------------------------------------
# Poisson distribution ------------------------------------------------------------
| NegativeBinomialDistribution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 137798,
"end": 138042
} | class ____(Response):
"""
Response of dataviews.move endpoint.
"""
_service = "dataviews"
_action = "move"
_version = "2.23"
_schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
| MoveResponse |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_hashtag.py | {
"start": 482,
"end": 1589
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_hashtag"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
def matches_hashtag_regex(x):
return bool(re.match(HASHTAG_REGEX, str(x)))
return column.apply(lambda x: matches_hashtag_regex(x) if x else False)
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidHashtag |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 36999,
"end": 37184
} | class ____(BaseReshape):
params = [get_benchmark_shapes("TimeUnstack")]
param_names = ["shape"]
def time_unstack(self, shape):
execute(self.df.unstack(1))
| TimeUnstack |
python | getsentry__sentry | src/sentry/notifications/notifications/organization_request/integration_request.py | {
"start": 1142,
"end": 3521
} | class ____(OrganizationRequestNotification):
# TODO: switch to a strategy based on the integration write scope
RoleBasedRecipientStrategyClass = OwnerRecipientStrategy
metrics_key = "integration_request"
template_path = "sentry/emails/requests/organization-integration"
def __init__(
self,
organization: Organization,
requester: User,
provider_type: str,
provider_slug: str,
provider_name: str,
message: str | None = None,
) -> None:
super().__init__(organization, requester)
self.provider_type = provider_type
self.provider_slug = provider_slug
self.provider_name = provider_name
self.message = message
self.integration_link = get_url(
self.organization,
self.provider_type,
self.provider_slug,
)
def get_context(self) -> MutableMapping[str, Any]:
return {
**self.get_base_context(),
"requester_name": self.requester.get_display_name(),
"organization_name": self.organization.name,
"integration_link": self.integration_link,
"integration_name": self.provider_name,
"message": self.message,
}
def get_subject(self, context: Mapping[str, Any] | None = None) -> str:
return f"Your team member requested the {self.provider_name} integration on Sentry"
def get_notification_title(
self, provider: ExternalProviders, context: Mapping[str, Any] | None = None
) -> str:
return self.get_subject()
def build_attachment_title(self, recipient: Actor) -> str:
return "Request to Install"
def get_message_description(self, recipient: Actor, provider: ExternalProviders) -> str:
requester_name = self.requester.get_display_name()
optional_message = (
f" They've included this message `{self.message}`" if self.message else ""
)
return f"{requester_name} is requesting to install the {self.provider_name} integration into {self.organization.name}.{optional_message}"
def get_message_actions(
self, recipient: Actor, provider: ExternalProviders
) -> Sequence[MessageAction]:
# TODO: update referrer
return [MessageAction(name="Check it out", url=self.integration_link)]
| IntegrationRequestNotification |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/schedules/schedules.py | {
"start": 10234,
"end": 10422
} | class ____(graphene.Union):
class Meta:
types = (GrapheneSchedules, GrapheneRepositoryNotFoundError, GraphenePythonError)
name = "SchedulesOrError"
| GrapheneSchedulesOrError |
python | great-expectations__great_expectations | great_expectations/core/result_format.py | {
"start": 91,
"end": 395
} | class ____(str, enum.Enum):
BOOLEAN_ONLY = "BOOLEAN_ONLY"
BASIC = "BASIC"
COMPLETE = "COMPLETE"
SUMMARY = "SUMMARY"
ResultFormatUnion = Union[
ResultFormat, dict, Literal["BOOLEAN_ONLY", "BASIC", "SUMMARY", "COMPLETE"]
]
DEFAULT_RESULT_FORMAT: Final = ResultFormat.SUMMARY
| ResultFormat |
python | django__django | tests/apps/query_performing_app/apps.py | {
"start": 1295,
"end": 1383
} | class ____(CursorQueryAppConfig):
database = "other"
| QueryOtherDatabaseCursorAppConfig |
python | celery__celery | t/unit/app/test_builtins.py | {
"start": 4000,
"end": 5528
} | class ____(BuiltinsCase):
def setup_method(self):
self.task = builtins.add_chord_task(self.app)
super().setup_method()
def test_apply_async(self):
x = chord([self.add.s(i, i) for i in range(10)], body=self.xsum.s())
r = x.apply_async()
assert r
assert r.parent
def test_run_header_not_group(self):
self.task([self.add.s(i, i) for i in range(10)], self.xsum.s())
def test_forward_options(self):
body = self.xsum.s()
x = chord([self.add.s(i, i) for i in range(10)], body=body)
x.run = Mock(name='chord.run(x)')
x.apply_async(group_id='some_group_id')
x.run.assert_called()
resbody = x.run.call_args[0][1]
assert resbody.options['group_id'] == 'some_group_id'
x2 = chord([self.add.s(i, i) for i in range(10)], body=body)
x2.run = Mock(name='chord.run(x2)')
x2.apply_async(chord='some_chord_id')
x2.run.assert_called()
resbody = x2.run.call_args[0][1]
assert resbody.options['chord'] == 'some_chord_id'
def test_apply_eager(self):
self.app.conf.task_always_eager = True
x = chord([self.add.s(i, i) for i in range(10)], body=self.xsum.s())
r = x.apply_async()
assert r.get() == 90
def test_apply_eager_with_arguments(self):
self.app.conf.task_always_eager = True
x = chord([self.add.s(i) for i in range(10)], body=self.xsum.s())
r = x.apply_async([1])
assert r.get() == 55
| test_chord |
python | conda__conda | conda/core/path_actions.py | {
"start": 40592,
"end": 41147
} | class ____(UnlinkPathAction):
def __init__(
self, transaction_context, linked_package_data, target_prefix, target_short_path
):
super().__init__(
transaction_context, linked_package_data, target_prefix, target_short_path
)
def execute(self):
super().execute()
PrefixData(self.target_prefix).remove(self.linked_package_data.name)
def reverse(self):
super().reverse()
PrefixData(self.target_prefix)._load_single_record(self.target_full_path)
| RemoveLinkedPackageRecordAction |
python | scrapy__scrapy | tests/test_commands.py | {
"start": 14029,
"end": 14540
} | class ____(TestProjectBase):
COMMANDS = [
"parse",
"startproject",
"view",
"crawl",
"edit",
"list",
"fetch",
"settings",
"shell",
"runspider",
"version",
"genspider",
"check",
"bench",
]
def test_help_messages(self, proj_path: Path) -> None:
for command in self.COMMANDS:
_, out, _ = proc(command, "-h", cwd=proj_path)
assert "Usage" in out
| TestHelpMessage |
python | tensorflow__tensorflow | tensorflow/lite/python/lite_test.py | {
"start": 78863,
"end": 85421
} | class ____(LiteTest):
def _initObjectDetectionArgs(self):
# Initializes the arguments required for the object detection model.
# Looks for the model file which is saved in a different location internally
# and externally.
filename = resource_loader.get_path_to_datafile('testdata/tflite_graph.pb')
if not os.path.exists(filename):
filename = os.path.join(
resource_loader.get_root_dir_with_all_resources(),
'../tflite_mobilenet_ssd_quant_protobuf/tflite_graph.pb')
if not os.path.exists(filename):
raise IOError("File '{0}' does not exist.".format(filename))
self._graph_def_file = filename
self._input_arrays = ['normalized_input_image_tensor']
self._output_arrays = [
'TFLite_Detection_PostProcess', 'TFLite_Detection_PostProcess:1',
'TFLite_Detection_PostProcess:2', 'TFLite_Detection_PostProcess:3'
]
self._input_shapes = {'normalized_input_image_tensor': [1, 300, 300, 3]}
def testTFLiteGraphDef(self):
# Tests the object detection model that cannot be loaded in TensorFlow.
self._initObjectDetectionArgs()
converter = lite.TFLiteConverter.from_frozen_graph(self._graph_def_file,
self._input_arrays,
self._output_arrays,
self._input_shapes)
converter.allow_custom_ops = True
tflite_model = converter.convert()
self.assertIsNotNone(tflite_model)
# Check values from converted model.
interpreter = Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
self.assertLen(input_details, 1)
self.assertEqual('normalized_input_image_tensor', input_details[0]['name'])
self.assertEqual(np.float32, input_details[0]['dtype'])
self.assertAllEqual([1, 300, 300, 3], input_details[0]['shape'])
self.assertEqual((0., 0.), input_details[0]['quantization'])
output_details = interpreter.get_output_details()
self.assertLen(output_details, 4)
self.assertEqual('TFLite_Detection_PostProcess', output_details[0]['name'])
self.assertEqual(np.float32, output_details[0]['dtype'])
self.assertAllEqual([1, 10, 4], output_details[0]['shape'])
self.assertEqual((0., 0.), output_details[0]['quantization'])
self.assertEqual('TFLite_Detection_PostProcess:1',
output_details[1]['name'])
self.assertAllEqual([1, 10], output_details[1]['shape'])
self.assertEqual('TFLite_Detection_PostProcess:2',
output_details[2]['name'])
self.assertAllEqual([1, 10], output_details[2]['shape'])
self.assertEqual('TFLite_Detection_PostProcess:3',
output_details[3]['name'])
self.assertAllEqual([1], output_details[3]['shape'])
def testTFLiteGraphDefWithControlOutput(self):
with ops.Graph().as_default():
in_tensor = array_ops.placeholder(
shape=[5, 5], dtype=dtypes.float32, name='input')
out_tensor = in_tensor + in_tensor
logging_ops.print_v2(out_tensor)
sess = session.Session()
converter = lite.TFLiteConverter(
sess.graph_def,
input_tensors=None,
output_tensors=None,
input_arrays_with_shape=[('input', [5, 5])],
output_arrays=None,
experimental_debug_info_func=None)
converter._control_output_arrays = ['PrintV2']
converter.target_spec.supported_ops = [
lite.OpsSet.TFLITE_BUILTINS,
lite.OpsSet.SELECT_TF_OPS,
]
tflite_model = converter.convert()
self.assertIsNotNone(tflite_model)
model = util._convert_model_from_bytearray_to_object(tflite_model)
self.assertEqual(model.operatorCodes[0].builtinCode,
schema_fb.BuiltinOperator.ADD)
self.assertEqual(model.operatorCodes[1].builtinCode,
schema_fb.BuiltinOperator.CUSTOM)
self.assertEqual(model.operatorCodes[1].customCode, b'FlexStringFormat')
self.assertEqual(model.operatorCodes[2].builtinCode,
schema_fb.BuiltinOperator.CUSTOM)
self.assertEqual(model.operatorCodes[2].customCode, b'FlexPrintV2')
# Check values from converted model.
interpreter = Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
self.assertLen(input_details, 1)
self.assertEqual('input', input_details[0]['name'])
self.assertEqual(np.float32, input_details[0]['dtype'])
self.assertAllEqual([5, 5], input_details[0]['shape'])
self.assertEqual((0., 0.), input_details[0]['quantization'])
output_details = interpreter.get_output_details()
self.assertLen(output_details, 0)
def testModifyIOToUint8(self):
# Tests the object detection model that cannot be loaded in TensorFlow.
self._initObjectDetectionArgs()
def representative_dataset_gen():
for _ in range(2):
yield [
np.random.uniform(low=0, high=1,
size=(1, 300, 300, 3)).astype(np.float32)
]
converter = lite.TFLiteConverter.from_frozen_graph(self._graph_def_file,
self._input_arrays,
self._output_arrays,
self._input_shapes)
converter.representative_dataset = representative_dataset_gen
converter.target_spec.supported_ops = {lite.OpsSet.TFLITE_BUILTINS_INT8}
converter.inference_type = dtypes.int8
converter.inference_input_type = dtypes.uint8
converter.inference_output_type = dtypes.uint8
converter.experimental_new_quantizer = True
converter.quantized_input_stats = {
'normalized_input_image_tensor': (0., 1.)
} # mean, std_dev
converter.allow_custom_ops = True
tflite_model = converter.convert()
self.assertIsNotNone(tflite_model)
model = util._convert_model_from_bytearray_to_object(tflite_model)
quant_opcode_idxs = util.get_quantize_opcode_idx(model)
subgraph = model.subgraphs[0]
tensors = subgraph.tensors
operators = subgraph.operators
for op in operators:
if op.opcodeIndex in quant_opcode_idxs:
input_type = util._convert_tflite_enum_type_to_tf_type(
tensors[op.inputs[0]].type)
if op.outputs[0] in subgraph.outputs:
self.assertEqual(input_type, dtypes.float32)
| FromFrozenGraphObjectDetection |
python | RaRe-Technologies__gensim | gensim/models/callbacks.py | {
"start": 10832,
"end": 13938
} | class ____(Metric):
"""Metric class for topic difference evaluation."""
def __init__(self, distance="jaccard", num_words=100, n_ann_terms=10, diagonal=True,
annotation=False, normed=True, logger=None, viz_env=None, title=None):
"""
Parameters
----------
distance : {'kullback_leibler', 'hellinger', 'jaccard'}, optional
Measure used to calculate difference between any topic pair.
num_words : int, optional
The number of most relevant words used if `distance == 'jaccard'`. Also used for annotating topics.
n_ann_terms : int, optional
Max number of words in intersection/symmetric difference between topics. Used for annotation.
diagonal : bool, optional
Whether we need the difference between identical topics (the diagonal of the difference matrix).
annotation : bool, optional
Whether the intersection or difference of words between two topics should be returned.
normed : bool, optional
Whether the matrix should be normalized or not.
logger : {'shell', 'visdom'}, optional
Monitor training process using one of the available methods. 'shell' will print the coherence value in
the active shell, while 'visdom' will visualize the coherence value with increasing epochs using the Visdom
visualization framework.
viz_env : object, optional
Visdom environment to use for plotting the graph. Unused.
title : str, optional
Title of the graph plot in case `logger == 'visdom'`. Unused.
"""
self.distance = distance
self.num_words = num_words
self.n_ann_terms = n_ann_terms
self.diagonal = diagonal
self.annotation = annotation
self.normed = normed
self.logger = logger
self.viz_env = viz_env
self.title = title
def get_value(self, **kwargs):
"""Get the difference between each pair of topics in two topic models.
Parameters
----------
**kwargs
Key word arguments to override the object's internal attributes.
Two models of type :class:`~gensim.models.ldamodelLdaModel`
are expected using the keys `model` and `other_model`.
Returns
-------
np.ndarray of shape (`model.num_topics`, `other_model.num_topics`)
Matrix of differences between each pair of topics.
np.ndarray of shape (`model.num_topics`, `other_model.num_topics`, 2), optional
Annotation matrix where for each pair we include the word from the intersection of the two topics,
and the word from the symmetric difference of the two topics. Only included if `annotation == True`.
"""
super(DiffMetric, self).set_parameters(**kwargs)
diff_diagonal, _ = self.model.diff(
self.other_model, self.distance, self.num_words, self.n_ann_terms,
self.diagonal, self.annotation, self.normed
)
return diff_diagonal
| DiffMetric |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table37.py | {
"start": 315,
"end": 1584
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table37.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
worksheet.write(1, 0, 1)
worksheet.write(2, 0, 2)
worksheet.write(3, 0, 3)
worksheet.write(4, 0, 4)
worksheet.write(5, 0, 5)
worksheet.write(1, 1, 10)
worksheet.write(2, 1, 15)
worksheet.write(3, 1, 20)
worksheet.write(4, 1, 10)
worksheet.write(5, 1, 15)
worksheet.set_column("A:B", 10.288)
worksheet.add_table("A1:B6")
chart.axis_ids = [88157568, 89138304]
chart.add_series(
{
"name": "=Sheet1!$B$1",
"categories": "=Sheet1!$A$2:$A$6",
"values": "=Sheet1!$B$2:$B$6",
}
)
chart.set_title({"none": True})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_scalarmath.py | {
"start": 8998,
"end": 13753
} | class ____(TestCase):
def test_modulus_basic(self):
# dt = np.typecodes["AllInteger"] + np.typecodes["Float"]
dt = "Bbhil" + "efd"
for op in [floordiv_and_mod, divmod]:
for dt1, dt2 in itertools.product(dt, dt):
for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)):
fmt = "op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s"
msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
a = np.array(sg1 * 71, dtype=dt1)[()]
b = np.array(sg2 * 19, dtype=dt2)[()]
div, rem = op(a, b)
assert_equal(div * b + rem, a, err_msg=msg)
if sg2 == -1:
assert_(b < rem <= 0, msg)
else:
assert_(b > rem >= 0, msg)
@slow
def test_float_modulus_exact(self):
# test that float results are exact for small integers. This also
# holds for the same integers scaled by powers of two.
nlst = list(range(-127, 0))
plst = list(range(1, 128))
dividend = nlst + [0] + plst
divisor = nlst + plst
arg = list(itertools.product(dividend, divisor))
tgt = [divmod(*t) for t in arg]
a, b = np.array(arg, dtype=int).T
# convert exact integer results from Python to float so that
# signed zero can be used, it is checked.
tgtdiv, tgtrem = np.array(tgt, dtype=float).T
tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv)
tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem)
for op in [floordiv_and_mod, divmod]:
for dt in np.typecodes["Float"]:
msg = f"op: {op.__name__}, dtype: {dt}"
fa = a.astype(dt)
fb = b.astype(dt)
# use list comprehension so a_ and b_ are scalars
div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)])
assert_equal(div, tgtdiv, err_msg=msg)
assert_equal(rem, tgtrem, err_msg=msg)
def test_float_modulus_roundoff(self):
# gh-6127
# dt = np.typecodes["Float"]
dt = "efd"
for op in [floordiv_and_mod, divmod]:
for dt1, dt2 in itertools.product(dt, dt):
for sg1, sg2 in itertools.product((+1, -1), (+1, -1)):
fmt = "op: %s, dt1: %s, dt2: %s, sg1: %s, sg2: %s"
msg = fmt % (op.__name__, dt1, dt2, sg1, sg2)
a = np.array(sg1 * 78 * 6e-8, dtype=dt1)[()]
b = np.array(sg2 * 6e-8, dtype=dt2)[()]
div, rem = op(a, b)
# Equal assertion should hold when fmod is used
assert_equal(div * b + rem, a, err_msg=msg)
if sg2 == -1:
assert_(b < rem <= 0, msg)
else:
assert_(b > rem >= 0, msg)
@parametrize("dt", "efd")
def test_float_modulus_corner_cases(self, dt):
if dt == "e":
# FIXME: make xfail
raise SkipTest("RuntimeError: 'nextafter_cpu' not implemented for 'Half'")
b = np.array(1.0, dtype=dt)
a = np.nextafter(np.array(0.0, dtype=dt), -b)
rem = operator.mod(a, b)
assert_(rem <= b, f"dt: {dt}")
rem = operator.mod(-a, -b)
assert_(rem >= -b, f"dt: {dt}")
# Check nans, inf
# with suppress_warnings() as sup:
# sup.filter(RuntimeWarning, "invalid value encountered in remainder")
# sup.filter(RuntimeWarning, "divide by zero encountered in remainder")
# sup.filter(RuntimeWarning, "divide by zero encountered in floor_divide")
# sup.filter(RuntimeWarning, "divide by zero encountered in divmod")
# sup.filter(RuntimeWarning, "invalid value encountered in divmod")
for dt in "efd":
fone = np.array(1.0, dtype=dt)
fzer = np.array(0.0, dtype=dt)
finf = np.array(np.inf, dtype=dt)
fnan = np.array(np.nan, dtype=dt)
rem = operator.mod(fone, fzer)
assert_(np.isnan(rem), f"dt: {dt}")
# MSVC 2008 returns NaN here, so disable the check.
# rem = operator.mod(fone, finf)
# assert_(rem == fone, 'dt: %s' % dt)
rem = operator.mod(fone, fnan)
assert_(np.isnan(rem), f"dt: {dt}")
rem = operator.mod(finf, fone)
assert_(np.isnan(rem), f"dt: {dt}")
for op in [floordiv_and_mod, divmod]:
div, mod = op(fone, fzer)
assert_(np.isinf(div)) and assert_(np.isnan(mod))
| TestModulus |
python | python-excel__xlrd | tests/test_missing_records.py | {
"start": 134,
"end": 658
} | class ____(TestCase):
def setUp(self):
path = from_sample('biff4_no_format_no_window2.xls')
self.book = open_workbook(path)
self.sheet = self.book.sheet_by_index(0)
def test_default_format(self):
cell = self.sheet.cell(0, 0)
self.assertEqual(cell.ctype, XL_CELL_TEXT)
def test_default_window2_options(self):
self.assertEqual(self.sheet.cached_page_break_preview_mag_factor, 0)
self.assertEqual(self.sheet.cached_normal_view_mag_factor, 0)
| TestMissingRecords |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial005_py310.py | {
"start": 71,
"end": 1548
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.age < 35)
results = session.exec(statement)
for hero in results:
print(hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | joke2k__faker | faker/providers/ssn/lv_LV/__init__.py | {
"start": 58,
"end": 2251
} | class ____(SsnProvider):
def ssn(self, min_age: int = 0, max_age: int = 105) -> str:
"""
Returns 11 character Latvian personal identity code (Personas kods).
This function assigns random age to person.
Personal code consists of eleven characters of the form DDMMYYCZZZQ, where
DDMMYY is the date of birth, C the century sign, ZZZ the individual
number and Q the control character (checksum). The number for the
century is either 0 (1800–1899), 1 (1900–1999), or 2 (2000–2099).
"""
def _checksum(ssn_without_checksum):
weights = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
weighted_sum = sum(int(digit) * weight for digit, weight in zip(ssn_without_checksum, weights))
reminder = (1 - weighted_sum) % 11
if reminder == 10:
return 0
elif reminder < -1:
return reminder + 11
return reminder
age = datetime.timedelta(days=self.generator.random.randrange(min_age * 365, max_age * 365))
birthday = datetime.date.today() - age
ssn_date = f"{birthday:%d%m%y}"
century = self._get_century_code(birthday.year) # Century
suffix = self.generator.random.randrange(111, 999)
checksum = _checksum(f"{ssn_date}{century:01d}{suffix:03d}")
ssn = f"{ssn_date}-{century:01d}{suffix:03d}{checksum:01d}"
return ssn
@staticmethod
def _get_century_code(year: int) -> int:
"""Returns the century code for a given year"""
if 2000 <= year < 3000:
code = 2
elif 1900 <= year < 2000:
code = 1
elif 1800 <= year < 1900:
code = 0
else:
raise ValueError("SSN do not support people born before the year 1800 or after the year 2999")
return code
"""
A Faker provider for the Latvian VAT IDs
"""
vat_id_formats = ("LV###########",)
def vat_id(self) -> str:
"""
http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
:return: a random Latvian VAT ID
"""
return self.bothify(self.random_element(self.vat_id_formats))
| Provider |
python | PyCQA__pylint | doc/data/messages/a/arguments-renamed/bad.py | {
"start": 0,
"end": 121
} | class ____:
def brew(self, ingredient_name: str):
print(f"Brewing a {type(self)} with {ingredient_name}")
| Fruit |
python | getsentry__sentry | src/sentry/seer/services/test_generation/model.py | {
"start": 320,
"end": 483
} | class ____(RpcModel):
error_detail: str | None = None
@property
def success(self) -> bool:
return self.error_detail is None
| CreateUnitTestResponse |
python | numpy__numpy | numpy/lib/tests/test_twodim_base.py | {
"start": 10617,
"end": 15251
} | class ____:
def test_dtype(self):
out = array([[1, 0, 0],
[1, 1, 0],
[1, 1, 1]])
assert_array_equal(tri(3), out)
assert_array_equal(tri(3, dtype=bool), out.astype(bool))
def test_tril_triu_ndim2():
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
a = np.ones((2, 2), dtype=dtype)
b = np.tril(a)
c = np.triu(a)
assert_array_equal(b, [[1, 0], [1, 1]])
assert_array_equal(c, b.T)
# should return the same dtype as the original array
assert_equal(b.dtype, a.dtype)
assert_equal(c.dtype, a.dtype)
def test_tril_triu_ndim3():
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
a = np.array([
[[1, 1], [1, 1]],
[[1, 1], [1, 0]],
[[1, 1], [0, 0]],
], dtype=dtype)
a_tril_desired = np.array([
[[1, 0], [1, 1]],
[[1, 0], [1, 0]],
[[1, 0], [0, 0]],
], dtype=dtype)
a_triu_desired = np.array([
[[1, 1], [0, 1]],
[[1, 1], [0, 0]],
[[1, 1], [0, 0]],
], dtype=dtype)
a_triu_observed = np.triu(a)
a_tril_observed = np.tril(a)
assert_array_equal(a_triu_observed, a_triu_desired)
assert_array_equal(a_tril_observed, a_tril_desired)
assert_equal(a_triu_observed.dtype, a.dtype)
assert_equal(a_tril_observed.dtype, a.dtype)
def test_tril_triu_with_inf():
# Issue 4859
arr = np.array([[1, 1, np.inf],
[1, 1, 1],
[np.inf, 1, 1]])
out_tril = np.array([[1, 0, 0],
[1, 1, 0],
[np.inf, 1, 1]])
out_triu = out_tril.T
assert_array_equal(np.triu(arr), out_triu)
assert_array_equal(np.tril(arr), out_tril)
def test_tril_triu_dtype():
# Issue 4916
# tril and triu should return the same dtype as input
for c in np.typecodes['All']:
if c == 'V':
continue
arr = np.zeros((3, 3), dtype=c)
assert_equal(np.triu(arr).dtype, arr.dtype)
assert_equal(np.tril(arr).dtype, arr.dtype)
# check special cases
arr = np.array([['2001-01-01T12:00', '2002-02-03T13:56'],
['2004-01-01T12:00', '2003-01-03T13:45']],
dtype='datetime64')
assert_equal(np.triu(arr).dtype, arr.dtype)
assert_equal(np.tril(arr).dtype, arr.dtype)
arr = np.zeros((3, 3), dtype='f4,f4')
assert_equal(np.triu(arr).dtype, arr.dtype)
assert_equal(np.tril(arr).dtype, arr.dtype)
def test_mask_indices():
# simple test without offset
iu = mask_indices(3, np.triu)
a = np.arange(9).reshape(3, 3)
assert_array_equal(a[iu], array([0, 1, 2, 4, 5, 8]))
# Now with an offset
iu1 = mask_indices(3, np.triu, 1)
assert_array_equal(a[iu1], array([1, 2, 5]))
def test_tril_indices():
# indices without and with offset
il1 = tril_indices(4)
il2 = tril_indices(4, k=2)
il3 = tril_indices(4, m=5)
il4 = tril_indices(4, k=2, m=5)
a = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
b = np.arange(1, 21).reshape(4, 5)
# indexing:
assert_array_equal(a[il1],
array([1, 5, 6, 9, 10, 11, 13, 14, 15, 16]))
assert_array_equal(b[il3],
array([1, 6, 7, 11, 12, 13, 16, 17, 18, 19]))
# And for assigning values:
a[il1] = -1
assert_array_equal(a,
array([[-1, 2, 3, 4],
[-1, -1, 7, 8],
[-1, -1, -1, 12],
[-1, -1, -1, -1]]))
b[il3] = -1
assert_array_equal(b,
array([[-1, 2, 3, 4, 5],
[-1, -1, 8, 9, 10],
[-1, -1, -1, 14, 15],
[-1, -1, -1, -1, 20]]))
# These cover almost the whole array (two diagonals right of the main one):
a[il2] = -10
assert_array_equal(a,
array([[-10, -10, -10, 4],
[-10, -10, -10, -10],
[-10, -10, -10, -10],
[-10, -10, -10, -10]]))
b[il4] = -10
assert_array_equal(b,
array([[-10, -10, -10, 4, 5],
[-10, -10, -10, -10, 10],
[-10, -10, -10, -10, -10],
[-10, -10, -10, -10, -10]]))
| TestTri |
python | fsspec__filesystem_spec | fsspec/caching.py | {
"start": 23818,
"end": 25592
} | class ____(Generic[P, T]):
"""
Custom implementation of LRU cache that allows updating keys
Used by BackgroudBlockCache
"""
class CacheInfo(NamedTuple):
hits: int
misses: int
maxsize: int
currsize: int
def __init__(self, func: Callable[P, T], max_size: int = 128) -> None:
self._cache: OrderedDict[Any, T] = collections.OrderedDict()
self._func = func
self._max_size = max_size
self._hits = 0
self._misses = 0
self._lock = threading.Lock()
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
if kwargs:
raise TypeError(f"Got unexpected keyword argument {kwargs.keys()}")
with self._lock:
if args in self._cache:
self._cache.move_to_end(args)
self._hits += 1
return self._cache[args]
result = self._func(*args, **kwargs)
with self._lock:
self._cache[args] = result
self._misses += 1
if len(self._cache) > self._max_size:
self._cache.popitem(last=False)
return result
def is_key_cached(self, *args: Any) -> bool:
with self._lock:
return args in self._cache
def add_key(self, result: T, *args: Any) -> None:
with self._lock:
self._cache[args] = result
if len(self._cache) > self._max_size:
self._cache.popitem(last=False)
def cache_info(self) -> UpdatableLRU.CacheInfo:
with self._lock:
return self.CacheInfo(
maxsize=self._max_size,
currsize=len(self._cache),
hits=self._hits,
misses=self._misses,
)
| UpdatableLRU |
python | ansible__ansible | lib/ansible/parsing/yaml/objects.py | {
"start": 1152,
"end": 2150
} | class ____:
"""Backwards compatibility type."""
def __new__(cls, ciphertext: str | bytes):
encrypted_string = _vault.EncryptedString(ciphertext=_converters.to_text(_datatag.AnsibleTagHelper.untag(ciphertext)))
return _datatag.AnsibleTagHelper.tag_copy(ciphertext, encrypted_string)
def __getattr__(name: str) -> _t.Any:
"""Inject import-time deprecation warnings."""
if (value := globals().get(f'_{name}', None)) and name.startswith('Ansible'):
# deprecated: description='enable deprecation of everything in this module', core_version='2.23'
# from ansible.utils.display import Display
#
# Display().deprecated(
# msg=f"Importing {name!r} is deprecated.",
# help_text="Instances of this type cannot be created and will not be encountered.",
# version="2.27",
# )
return value
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
| _AnsibleVaultEncryptedUnicode |
python | django__django | tests/check_framework/test_caches.py | {
"start": 1181,
"end": 5144
} | class ____(SimpleTestCase):
warning_message = (
"Your 'default' cache configuration might expose your cache or lead "
"to corruption of your data because its LOCATION %s %s."
)
@staticmethod
def get_settings(setting, cache_path, setting_path):
return {
"CACHES": {
"default": {
"BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
"LOCATION": cache_path,
},
},
setting: [setting_path] if setting == "STATICFILES_DIRS" else setting_path,
}
def test_cache_path_matches_media_static_setting(self):
root = pathlib.Path.cwd()
for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"):
settings = self.get_settings(setting, root, root)
with self.subTest(setting=setting), self.settings(**settings):
msg = self.warning_message % ("matches", setting)
self.assertEqual(
check_cache_location_not_exposed(None),
[
Warning(msg, id="caches.W002"),
],
)
def test_cache_path_inside_media_static_setting(self):
root = pathlib.Path.cwd()
for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"):
settings = self.get_settings(setting, root / "cache", root)
with self.subTest(setting=setting), self.settings(**settings):
msg = self.warning_message % ("is inside", setting)
self.assertEqual(
check_cache_location_not_exposed(None),
[
Warning(msg, id="caches.W002"),
],
)
def test_cache_path_contains_media_static_setting(self):
root = pathlib.Path.cwd()
for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"):
settings = self.get_settings(setting, root, root / "other")
with self.subTest(setting=setting), self.settings(**settings):
msg = self.warning_message % ("contains", setting)
self.assertEqual(
check_cache_location_not_exposed(None),
[
Warning(msg, id="caches.W002"),
],
)
def test_cache_path_not_conflict(self):
root = pathlib.Path.cwd()
for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"):
settings = self.get_settings(setting, root / "cache", root / "other")
with self.subTest(setting=setting), self.settings(**settings):
self.assertEqual(check_cache_location_not_exposed(None), [])
def test_staticfiles_dirs_prefix(self):
root = pathlib.Path.cwd()
tests = [
(root, root, "matches"),
(root / "cache", root, "is inside"),
(root, root / "other", "contains"),
]
for cache_path, setting_path, msg in tests:
settings = self.get_settings(
"STATICFILES_DIRS",
cache_path,
("prefix", setting_path),
)
with self.subTest(path=setting_path), self.settings(**settings):
msg = self.warning_message % (msg, "STATICFILES_DIRS")
self.assertEqual(
check_cache_location_not_exposed(None),
[
Warning(msg, id="caches.W002"),
],
)
def test_staticfiles_dirs_prefix_not_conflict(self):
root = pathlib.Path.cwd()
settings = self.get_settings(
"STATICFILES_DIRS",
root / "cache",
("prefix", root / "other"),
)
with self.settings(**settings):
self.assertEqual(check_cache_location_not_exposed(None), [])
| CheckCacheLocationTest |
python | scrapy__scrapy | tests/test_squeues.py | {
"start": 4114,
"end": 4434
} | class ____:
def test_serialize(self):
q = self.queue()
q.push("a")
q.push(123)
q.push({"a": "dict"})
assert q.pop() == {"a": "dict"}
assert q.pop() == 123
assert q.pop() == "a"
test_nonserializable_object = nonserializable_object_test
| LifoDiskQueueTestMixin |
python | huggingface__transformers | src/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py | {
"start": 18414,
"end": 20994
} | class ____(GradientCheckpointingLayer):
"""Conformer block based on https://huggingface.co/papers/2005.08100."""
def __init__(self, config):
super().__init__()
embed_dim = config.hidden_size
dropout = config.attention_dropout
# Feed-forward 1
self.ffn1_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.ffn1 = Wav2Vec2BertFeedForward(config)
# Self-Attention
self.self_attn_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.self_attn_dropout = nn.Dropout(dropout)
self.self_attn = Wav2Vec2BertSelfAttention(config)
# Conformer Convolution
self.conv_module = Wav2Vec2BertConvolutionModule(config)
# Feed-forward 2
self.ffn2_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.ffn2 = Wav2Vec2BertFeedForward(config)
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
def forward(
self,
hidden_states,
attention_mask: Optional[torch.Tensor] = None,
relative_position_embeddings: Optional[torch.Tensor] = None,
output_attentions: bool = False,
conv_attention_mask: Optional[torch.Tensor] = None,
):
# 1. Feed-Forward 1 layer
residual = hidden_states
hidden_states = self.ffn1_layer_norm(hidden_states)
hidden_states = self.ffn1(hidden_states)
hidden_states = hidden_states * 0.5 + residual
residual = hidden_states
# 2. Self-Attention layer
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states, attn_weigts = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
relative_position_embeddings=relative_position_embeddings,
output_attentions=output_attentions,
)
hidden_states = self.self_attn_dropout(hidden_states)
hidden_states = hidden_states + residual
# 3. Convolutional Layer
residual = hidden_states
hidden_states = self.conv_module(hidden_states, attention_mask=conv_attention_mask)
hidden_states = residual + hidden_states
# 4. Feed-Forward 2 Layer
residual = hidden_states
hidden_states = self.ffn2_layer_norm(hidden_states)
hidden_states = self.ffn2(hidden_states)
hidden_states = hidden_states * 0.5 + residual
hidden_states = self.final_layer_norm(hidden_states)
return hidden_states, attn_weigts
| Wav2Vec2BertEncoderLayer |
python | pytorch__pytorch | test/package/package_a/test_module.py | {
"start": 309,
"end": 495
} | class ____(torch.nn.Module):
def __init__(self, tensor):
super().__init__()
self.tensor = tensor
def forward(self, x):
return self.tensor * x
| ModWithTensor |
python | pytorch__pytorch | torch/_inductor/runtime/triton_heuristics.py | {
"start": 135595,
"end": 138925
} | class ____:
"""Generate code for grid size expressions in launcher"""
inductor_meta: dict[str, Any]
mode: Literal["python", "cpp"] = "python"
prefix: list[str] = dataclasses.field(default_factory=list)
x_grid: str | int = 1
y_grid: str | int = 1
z_grid: str | int = 1
def __post_init__(self) -> None:
assert self.mode in ("python", "cpp")
def generate(self, meta: dict[str, int]) -> None:
raise NotImplementedError
def ceildiv(self, numel: str | int, block: None | int | str) -> str | int:
if block is None or block == 1:
return numel
if isinstance(numel, int) and isinstance(block, int):
return ceildiv(numel, block) # constant fold
# This trick only works in python, where
# negative integer division is floored
if self.mode == "python":
return f"-(({numel}) // -({block}))"
# For cpp code gen
return f"(({numel} + ({block} - 1)) / ({block}))"
def maximum(self, seq: list[int | str]) -> int | str:
"""Codegen for max function with constant folding, constants are represented as int"""
items = self._constant_fold(max, seq)
if len(items) <= 1:
return items[0]
if self.mode == "python":
return f"max({', '.join(map(str, items))})"
return functools.reduce(lambda x, y: f"std::max({x}, {y})", items)
def summation(self, seq: list[int | str]) -> int | str:
"""Codegen for sum function with constant folding, constants are represented as int"""
items = self._constant_fold(sum, seq)
if len(items) <= 1:
return items[0]
return " + ".join(map(str, items))
def _constant_fold(
self, fn: Callable[[list[int]], int], seq: list[int | str]
) -> list[int | str]:
"""Constant fold through a commutative fn where ints are constants"""
items: list[int | str] = [x for x in seq if not isinstance(x, int)]
const_items = [x for x in seq if isinstance(x, int)]
if const_items:
items.append(fn(const_items))
return items
def assign_tmp(self, name: str, expr: str | int) -> str:
# Grid functions are one per kernel, so name collisions are fine
if self.mode == "python":
return f"{name} = {expr}"
if self.mode == "cpp":
return f"uint32_t {name} = {expr};"
raise AssertionError(f"invalid mode {self.mode}")
@staticmethod
def from_meta(
inductor_meta: dict[str, Any],
cfg: Config | dict[str, int],
mode: Literal["python", "cpp"] = "python",
) -> GridExpr:
grid_cls = globals()[inductor_meta["grid_type"]]
assert issubclass(grid_cls, GridExpr)
grid = grid_cls(inductor_meta=inductor_meta, mode=mode)
if isinstance(cfg, Config):
cfg = config_to_dict(cfg)
grid.generate(cfg)
return grid
def eval_slow(self, meta: dict[str, int]) -> tuple[int, int, int]:
scope = {**meta}
for line in self.prefix:
exec(line, scope)
exec(f"grid_0 = {self.x_grid}", scope)
exec(f"grid_1 = {self.y_grid}", scope)
exec(f"grid_2 = {self.z_grid}", scope)
return scope["grid_0"], scope["grid_1"], scope["grid_2"]
| GridExpr |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call.py | {
"start": 550,
"end": 1028
} | class ____(BaseModel):
button: Literal["left", "right", "wheel", "back", "forward"]
"""Indicates which mouse button was pressed during the click.
One of `left`, `right`, `wheel`, `back`, or `forward`.
"""
type: Literal["click"]
"""Specifies the event type. For a click action, this property is always `click`."""
x: int
"""The x-coordinate where the click occurred."""
y: int
"""The y-coordinate where the click occurred."""
| ActionClick |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.